Archive for the 'C#' Category

08
Sep
10

Changing log4net log file path via code

Sometimes we might have to place the log files away from the location where the application is installed. And lo there is an option to do that! In the config file create a variable like below

<file type="log4net.Util.PatternString" value="%property{SomeVariable}log.txt" />

And in the code, before calling log4net configure, set the new path to the Variable

log4net.GlobalContext.Properties["SomeVariable"] = YourNewPath;
log4net.Config.XmlConfigurator.Configure();

Simple isn’t it Smile

24
Mar
10

remove objects from an Enumerable collection in a loop

If you are trying to remove an object from a list that you are currently iterating through like below,

foreach (MyObject myObject in MyListOfMyObjects)
{
     if (condition) MyListOfMyObjects.Remove(myObject);
}

you will get an error message that you cannot do it.

Best alternative is to create a copy of the object and loop through it and remove from main object

foreach (MyObject myObject in new List<MyObject>(MyListOfMyObjects))
{
     if (condition) MyListOfMyObjects.Remove(myObject);
}

Simple isn’t it :)

Source : StackOverflow

12
Mar
10

xml schema generation, serialization & deserialization explained

Lets consider a simple xml named as sample.xml. This can be an xml that you are getting as a output of webservice, a function or just a plain file that you might read in your application.

<users>
    <user>
        <id>1</id>
        <name>asdf</name>
        <fullname>asdf,asdf</fullname>
    </user>
    <user>
        <id>2</id>
        <name>qwer</name>
        <fullname>qwer,qwer</fullname>
    </user>
</users>

Lets create a XML Schema aka XSD file

Open ‘Visual Studio 2008 Command Prompt’ and type in

xsd sample.xml

This will generate sample.xsd file in the folder where you are currently running this command from. Below is how it looks.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="users" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="users" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="user">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="id" type="xs:string" minOccurs="0" />
              <xs:element name="name" type="xs:string" minOccurs="0" />
              <xs:element name="fullname" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Lets create a class for serialization of xml file

xsd sample.xsd /classes /language:cs

This will generate sample.cs file. By default in the generated file, the collection used is Array.

private usersUser[] itemsField;

Lets use ObservableCollection as it is a generic dynamic data collection that provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed.

Below is how the modified class file looks like.

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3607
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————

using System.Xml.Serialization;
using System.Collections.ObjectModel;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class users {

    private ObservableCollection<usersUser> itemsField;
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("user", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public ObservableCollection<usersUser> Items
    {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class usersUser {
    private string idField;
    private string nameField;
    private string fullnameField;
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string id {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string fullname {
        get {
            return this.fullnameField;
        }
        set {
            this.fullnameField = value;
        }
    }
}

Lets read a file from file system [ Serialization ]. Below is the sample code for doing so

System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "XML File|*.xml";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    try
    {
        if (File.Exists(ofd.FileName))
        {
        XmlSerializer deserializer = new XmlSerializer(typeof(users));
        TextReader textReader = new StreamReader(ofd.FileName);
        objUsers = new users();
        objUsers = (users)deserializer.Deserialize(textReader);
        textReader.Close();  
        }
    }
    catch
    {
        MessageBox.Show("Not a valid file");
    }
}

To add a new user, below is the sample code

usersUser newuser = new usersUser();
newuser.id = "3";
newuser.name = "zxcv";
newuser.fullname = "zxcv,zxcv";
if (objUsers == null)
    objUsers= new users();
objUsers.Items.Add(newuser);

Lets write a xml file from the objects that we have created [ Deserialization ]. Below is the sample code for doing so

if (objUsers == null)
    objUsers = new users();
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "New";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML file|*.xml";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
    string filepath = dlg.FileName;
    XmlSerializer serializer = new XmlSerializer(typeof(users));
    TextWriter textWriter = new StreamWriter(filepath);
    serializer.Serialize(textWriter, objUsers);
    textWriter.Close();
}          

Simple isn’t it :)

Sample code explained in this post is available here

11
Mar
10

capturing Barcode scan using C#

Technorati Tags: ,,,

It is know that barcode when scanned, it prints one letter at a time when it is scanning and once scan is complete, it inserts an carriage return at the end.

So barcode scan can be handled via 2 events

1. As it is scanning

Define public variables

public System.Windows.Forms.Timer tmrDelay;

On window Loaded function initialize variables

tmrDelay = new System.Windows.Forms.Timer();
tmrDelay.Interval = 1000;
tmrDelay.Enabled = false;

As we know that barcode when scanned, it prints one letter at a time when it is scanning. So when first letter is entered, start a timer during which the complete barcode will be scanned to the textbox. Once timer is off, you can process it or queue it for processing later.

So, On TextChanged event of the textbox where barcode will be entered, add the following code

private void txtBarcode_TextChanged(object sender, TextChangedEventArgs e)
{
    try
    {
    if (txtBarcode.Text.Trim().Length == 1)
    {
        tmrDelay.Enabled = true;
        tmrDelay.Start();
        tmrDelay.Tick += new EventHandler(tmrDelay_Tick);
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
}

void tmrDelay_Tick(object sender, EventArgs e)
{
    try
    {
    tmrDelay.Stop();
    string strCurrentString = txtBarcode.Text.Trim().ToString();
    if (strCurrentString != "")
    {
        //Do something with the barcode entered
        txtBarcode.Text = "";
    }
    txtBarcode.Focus();
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
}

2. After scan is complete

As we also know that once barcode once scan is complete, it inserts an carriage return at the end.

So, you can look for enter key on KeyUp event of the textbox where barcode will be entered, add the following code

private void txtBarcode_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
    string strCurrentString = txtBarcode.Text.Trim().ToString();
    if (strCurrentString != "")
    {
        //Do something with the barcode entered
        txtBarcode.Text = "";
    }
    txtBarcode.Focus();
    }
}

Choose the one that suits you :)

Simple isn’t it :)

Sample code is available here

15
Feb
10

Switching between Https and http while accessing wcf/asmx service

There may be an instance where we might have to test the clickonce application on production on SSL and stage on port 80, change the url of the wcf/asmx service dynamically etc.

Here is how I fixed the issue

public static MyService.MyServiceSoapClient GetSoapClient()
       {
           MyService.MyServiceSoapClient objClient = new MyService.MyServiceSoapClient();
          //sets the endpoint address dynamically
           objClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(strURLRoot + "services/myservice.asmx");

           //sets the security mode dynamically
           System.ServiceModel.BasicHttpBinding bhbBinding = (System.ServiceModel.BasicHttpBinding)objClient.Endpoint.Binding;
           if (SharedData.strURLRoot.Contains("https:"))
               bhbBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
           else
               bhbBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
           objClient.Endpoint.Binding = bhbBinding;
           return objClient;
       }

Simple isn’t it?

02
Dec
09

URL encode decode reference

I was looking for url encoding and decoding reference and found this cool resource.. http://www.w3schools.com/TAGS/ref_urlencode.asp

In C# to encode or decode string Uri.EscapeDataString and Uri.UnescapeDataString :)

24
Nov
09

if you need to send more data to wcf service

For example, you need to upload log file in case of error from desktop application to remote site using WCF service and if the log file is too big, you might have to tweak your WCF service’s Web.config.

By default the configuration for the service will be

      <services>
            <service behaviorConfiguration="ServiceBehavior" name="Service">
                <endpoint address="" binding="basicHttpBinding" contract="IService">
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>

You need to specify the binding manually and add binding reference as highlighted below.   

 

    <services>
            <service behaviorConfiguration="ServiceBehavior" name="Service">
                <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="IService">
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
        <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
                        maxReceivedMessageSize="2147483647" messageEncoding="Text"
                        textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
                            maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>

That’s it :) Simple isn’t it?

24
Nov
09

clone your custom objects with 2 lines of code in C#

There may be many instances where we have to clone a object. For example, we open the object for edit in a form and after few modifications, if the user decides to abandon changes/cancel modifications and if we are using the main object to do all the changes, it would be a disaster.

Cloning is a way out of it. I remember a time when we had to write another clone method to achieve the cloning of object. With C#, its 2 lines of code!

Your class can be like this..

public class myclass
       {
           public int id { get; set; }
           public string name { get; set; }
           public string value { get; set; }
       }

Now to make it clone-able change it this way…

public class myclass :ICloneable
        {
            public int id { get; set; }
            public string name { get; set; }
            public string value { get; set; }

            public object Clone() { return this.MemberwiseClone(); }

        }

Try this..

            myclass a = new myclass();
            a.id = 1;
            a.name = "asdf";
            a.value = "qwer";
            myclass b = a.Clone() as myclass;
            b.value = "zxcv";
            myclass c = a;
            Console.Write(a.value + " "  + b.value + " " + c.value) ;

output will be

              qwer zxcv qwer

Simple isn’t it?

More ways of cloning objects are shown here

Technorati Tags: ,,,
29
Oct
09

download clickonce update manually after app has started

Was trying all the while using ApplicationDeployment class. Ran into lot of errors. Found this awesome code from MSDN and it works like charm.. you might say obvious isn’t it :)

long sizeOfUpdate = 0;

private void UpdateApplication()
{
    if (ApplicationDeployment.IsNetworkDeployed)
    {
        ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
        ad.CheckForUpdateCompleted += new CheckForUpdateCompletedEventHandler(ad_CheckForUpdateCompleted);
        ad.CheckForUpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_CheckForUpdateProgressChanged);

        ad.CheckForUpdateAsync();
    }
}

void  ad_CheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    downloadStatus.Text = String.Format("Downloading: {0}. {1:D}K of {2:D}K downloaded.", GetProgressString(e.State), e.BytesCompleted/1024, e.BytesTotal/1024);  
}

string GetProgressString(DeploymentProgressState state)
{
    if (state == DeploymentProgressState.DownloadingApplicationFiles)
    {
        return "application files";
    }
    else if (state == DeploymentProgressState.DownloadingApplicationInformation)
    {
        return "application manifest";
    }
    else
    {
        return "deployment manifest";
    }
}

void ad_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not retrieve new version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }
    else if (e.Cancelled == true)
    {
        MessageBox.Show("The update was cancelled.");
    }

    // Ask the user if they would like to update the application now.
    if (e.UpdateAvailable)
    {
        sizeOfUpdate = e.UpdateSizeBytes;

        if (!e.IsUpdateRequired)
        {
            DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?\n\nEstimated Download Time: ", "Update Available", MessageBoxButtons.OKCancel);
            if (DialogResult.OK == dr)
            {
                BeginUpdate();
            }
        }
        else
        {
            MessageBox.Show("A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.");
            BeginUpdate();
        }
    }
}

private void BeginUpdate()
{
    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
    ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);

    // Indicate progress in the application’s status bar.
    ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
    ad.UpdateAsync();
}

void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    String progressText = String.Format("{0:D}K out of {1:D}K downloaded – {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage);
    downloadStatus.Text = progressText;
}

void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("The update of the application’s latest version was cancelled.");
        return;
    }
    else if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }

    DialogResult dr = MessageBox.Show("The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel);
    if (DialogResult.OK == dr)
    {
        Application.Restart();
    }
}

20
Oct
09

reading string into stream and vice versa

string to stream

byte[] byteArray = Encoding.ASCII.GetBytes( test );
MemoryStream stream = new MemoryStream( byteArray );

string to stream

StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();

via C#411




@pooran

 

May 2012
M T W T F S S
« Nov    
 123456
78910111213
14151617181920
21222324252627
28293031  

Visits so far..

  • 10,471

Follow

Get every new post delivered to your Inbox.