Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

June 19, 2015

Practically there are no differences between int and System.Int32 (except while using enums). C# allows for certain aliases and it is one of those. Both int and System.Int32 are compiled to System.Int32 in the Intermediate Language (IL). C# contains a number of aliases that allows for quick typing of the variable types. Here is a full list of the aliases.

May 18, 2015

C# Different ways to create a string

Strings, in C#, represents text as a series of Unicode characters. A string can be referenced as both "string" and "String" - string is basically an alias of System.String.  It can be created in a number of ways. In the simplest form, it can just be assigned or alternatively it can be created using the String's constructors. String, like other objects in .NET, can be assigned to null. Strings might look like and can be used like other variables like int or double but one important characteristics is that it is immutable - that is, once a String is created, it cannot be changed (so, when a string variable is re-assigned, behind the scenes, a new string is created and assigned to the variable).

May 15, 2015

All these methods Int32.Parse(), Convert.ToInt32(), and Int32.TryParse() ultimately does the same thing - convert a string to an integer. The main difference lies in what happens if the conversion does not succeed. With Int32.Parse(), exceptions are thrown if conversion does not work. With Convert.ToInt32() methods 0 is returned while parsing null, otherwise exceptions are thrown. With Int32.TryParse() method, no exception is thrown - it sets the correct value to an integer variable if conversion succeeds and at the same time returns a boolean value suggesting if conversion has succeeded.

 

July 18, 2014

Serialize Object to Xml

In this example, I will show how to serialize an object in xml. In this post, I will use an Employee object, create a List of Employees and then serialize the object to xml. Serialization can data from objects needs to be saved in the filesystem or other storage and then used later for retrieval. Here is the code on how this can be achieved.

Serialize
  1. public class Employee
  2. {
  3.     public string FirstName { get; set; }
  4.     public string LastName { get; set; }
  5.     public DateTime DateOfBirth { get; set; }
  6.     public DateTime DateJoined { get; set; }
  7.     public bool IsRetired { get; set; }
  8.  
  9.     public override string ToString()
  10.     {
  11.         return "First Name: " + FirstName + "\nLastName: " + LastName + "\nDate of Birth: " + DateOfBirth
  12.             + "\nDate Joined: " + DateJoined + "\nIs Retired? " + IsRetired;
  13.     }
  14.  
  15.     public override bool Equals(object obj)
  16.     {
  17.         Employee em = (Employee)obj;
  18.         return this.FirstName == em.FirstName
  19.             && this.LastName == em.LastName
  20.             && this.DateOfBirth == em.DateOfBirth
  21.             && this.DateJoined == em.DateJoined
  22.             && this.IsRetired == em.IsRetired;
  23.     }
  24.  
  25.     public override int GetHashCode()
  26.     {
  27.         unchecked
  28.         {
  29.             int hash = 23;
  30.  
  31.             hash = FirstName == null ? hash * 11 : hash * 17 + FirstName.GetHashCode();
  32.             hash = LastName == null ? hash * 19 : hash * 17 + LastName.GetHashCode();
  33.             hash = DateOfBirth == null ? hash * 13 : hash * 17 + DateOfBirth.GetHashCode();
  34.             hash = DateJoined == null ? hash * 7 : hash * 17 + DateJoined.GetHashCode();
  35.             hash = IsRetired == null ? hash * 7 : hash * 17 + IsRetired.GetHashCode();
  36.             return hash;
  37.         }
  38.     }  
  39. }
  40.  
  41. public class Company
  42. {
  43.     public List<Employee> ListOfEmployees { get; set; }
  44.  
  45.     public Company()
  46.     {
  47.         List<Employee> list = new List<Employee>();
  48.         list.Add(new Employee() { FirstName = "John", LastName = "Smith", DateJoined = new DateTime(2007, 10, 12), DateOfBirth = new DateTime(1960, 2, 8), IsRetired = false });
  49.         list.Add(new Employee() { FirstName = "Jake", LastName = "Troy", DateJoined = new DateTime(2010, 1, 13), DateOfBirth = new DateTime(1980, 2, 18), IsRetired = true });
  50.         list.Add(new Employee() { FirstName = "Shawn", LastName = "Clark", DateJoined = new DateTime(2008, 12, 15), DateOfBirth = new DateTime(1990, 12, 8), IsRetired = false });
  51.         ListOfEmployees = list;
  52.     }
  53. }
  54.  
  55. public class TestSerialize
  56. {
  57.     public string Serialize()
  58.     {
  59.         XmlSerializer xSer = new XmlSerializer(typeof(Company));
  60.         var req = new Company();
  61.         StringWriter sw = new StringWriter();
  62.         XmlWriter writer = XmlWriter.Create(sw);
  63.         xSer.Serialize(writer, req);
  64.         return sw.ToString();
  65.     }
  66. }

 

Once the code is run, the xml produced looks like below.

Resultant xml
  1. <?xml version="1.0" encoding="utf-16"?>
  2. <Company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3.   <ListOfEmployees>
  4.     <Employee>
  5.       <FirstName>John</FirstName>
  6.       <LastName>Smith</LastName>
  7.       <DateOfBirth>1960-02-08T00:00:00</DateOfBirth>
  8.       <DateJoined>2007-10-12T00:00:00</DateJoined>
  9.       <IsRetired>false</IsRetired>
  10.     </Employee>
  11.     <Employee>
  12.       <FirstName>Jake</FirstName>
  13.       <LastName>Troy</LastName>
  14.       <DateOfBirth>1980-02-18T00:00:00</DateOfBirth>
  15.       <DateJoined>2010-01-13T00:00:00</DateJoined>
  16.       <IsRetired>true</IsRetired>
  17.     </Employee>
  18.     <Employee>
  19.       <FirstName>Shawn</FirstName>
  20.       <LastName>Clark</LastName>
  21.       <DateOfBirth>1990-12-08T00:00:00</DateOfBirth>
  22.       <DateJoined>2008-12-15T00:00:00</DateJoined>
  23.       <IsRetired>false</IsRetired>
  24.     </Employee>
  25.   </ListOfEmployees>
  26. </Company>

May 30, 2014

Get System Information using C#

In this post, I will quickly show how to get system related information like machine name, user name, domain name, or how long ago the system started, etc. Most of these information can be retrieved from System.Environment class and I will take advantage of this class to display this data.

Below is an example of how most of these information can be obtained from the System.Environment class.

System Information using asp.n
  1. using System;
  2.  
  3. namespace WebApplication3
  4. {
  5.     public partial class Info : System.Web.UI.Page
  6.     {
  7.         protected void Page_Load(object sender, EventArgs e)
  8.         {
  9.             GetSystemInfo();
  10.         }
  11.  
  12.         private void GetSystemInfo()
  13.         {
  14.             string br = "<br/>";
  15.             Response.Write("Machine Name: " + Environment.MachineName + br);
  16.             Response.Write("OS Version: " + Environment.OSVersion + br);
  17.             Response.Write("System Directory: " + Environment.SystemDirectory + br);
  18.             Response.Write("Domain Name: " + Environment.UserDomainName + br);
  19.             Response.Write("User name: " + Environment.UserName + br);
  20.             Response.Write("CLR version: " + Environment.Version + br);
  21.               Response.Write("System Started: " + Environment.TickCount / (1000 * 60 * 60) + "hours ago"+ br);
  22.             Response.Write("No of processors: " + Environment.ProcessorCount + br);
  23.             Response.Write("Current Directory: " + Environment.CurrentDirectory + br);
  24.  
  25.         }
  26.     }
  27. }

May 29, 2014

Remove Duplicates from a List in C#

A List can contain simple types like int, string or other objects. Other day I was working and had to remove duplicates from a List collection. In this post, I will talk about how I remove the duplicates using minimum code. To start with a clue, I used a HashSet to remove the duplicates.

HashSet has the feature to only contain distinct items within it. Therefore, I could convert the List to HashSet and back to a list and this would remove all the duplicates for me. For HashSets to only contain unique items, the object needs to override the Equals and GetHashCode methods. Below is an example of how this can be done. I have created an Employee class with few members and overridden Equals and GetHashCode methods. Then I have another class EmployeeCollection where I have removed the duplicates.

Remove Duplicates
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace WebApplication3.Helper
  5. {
  6.     public class EmployeeCollection
  7.     {
  8.         private List<Employee> RemoveDuplicates()
  9.         {
  10.             List<Employee> list = new List<Employee>();
  11.             //load employees to list
  12.             //list.Add(new Employee() { FirstName = "John" });
  13.  
  14.             //HashSet removes duplicates
  15.             HashSet<Employee> emSet = new HashSet<Employee>(list);
  16.             return new List<Employee>(emSet);
  17.         }
  18.     }
  19.  
  20.     public class Employee
  21.     {
  22.         public string FirstName { get; set; }
  23.         public string LastName { get; set; }
  24.         public DateTime DateOfBirth { get; set; }
  25.         public DateTime DateJoined { get; set; }
  26.         public bool IsRetired { get; set; }
  27.  
  28.         public override string ToString()
  29.         {
  30.             return "First Name: " + FirstName + "\nLastName: " + LastName + "\nDate of Birth: " + DateOfBirth
  31.                 + "\nDate Joined: " + DateJoined + "\nIs Retired? " + IsRetired;
  32.         }
  33.  
  34.         public override bool Equals(object obj)
  35.         {
  36.             Employee em = (Employee)obj;
  37.             return this.FirstName == em.FirstName
  38.                 && this.LastName == em.LastName
  39.                 && this.DateOfBirth == em.DateOfBirth
  40.                 && this.DateJoined == em.DateJoined
  41.                 && this.IsRetired == em.IsRetired;
  42.         }
  43.  
  44.         public override int GetHashCode()
  45.         {
  46.             unchecked
  47.             {
  48.                 int hash = 23;
  49.  
  50.                 hash = FirstName == null ? hash * 11 : hash * 17 + FirstName.GetHashCode();
  51.                 hash = LastName == null ? hash * 19 : hash * 17 + LastName.GetHashCode();
  52.                 hash = DateOfBirth == null ? hash * 13 : hash * 17 + DateOfBirth.GetHashCode();
  53.                 hash = DateJoined == null ? hash * 7 : hash * 17 + DateJoined.GetHashCode();
  54.                 hash = IsRetired == null ? hash * 7 : hash * 17 + IsRetired.GetHashCode();
  55.                 return hash;
  56.             }
  57.         }  
  58.     }
  59. }

April 29, 2014

Send Email using Gmail and C#

Many of us use gmail for emails and it is possible to send emails using code and gmail as host. In this post, I will show how to send emails using gmail and C#. It is actually really easy to send emails via gmail. We just need to

Convert between XDocument and XmlDocument

In one of the applications I was working, I noticed that as we have developed the application we have used both System.Xml and System.Xml.Linq namespaces. Now this can happen for a number of reasons including that as the application got developed, the new namespaces were used but the old code has not been refactored and it's not a priority as well as the latest .NET framework supports it. However, sometimes we might need to convert files from old to new version and vice versa. In my situation, I had to convert XDocument to XmlDocument and vice versa. To cater for this requirement I wrote a class with static methods that perform the conversion taking advantage of the XmlNodeReader and XmlReader classes.

Here's the sample code of the class.

XDoc to XmlDoc
  1. public class XmlConversion
  2. {
  3.     public static XmlDocument ToXmlDocument(XDocument xdoc)
  4.     {
  5.         var xmlDocument = new XmlDocument();
  6.         using (var reader = xdoc.CreateReader())
  7.         {
  8.             xmlDocument.Load(reader);
  9.         }
  10.         return xmlDocument;
  11.     }
  12.  
  13.     public static XDocument ToXDocument(XmlDocument xmlDoc)
  14.     {
  15.         using (var reader = new XmlNodeReader(xmlDoc))
  16.         {
  17.             reader.MoveToContent();
  18.             return XDocument.Load(reader);
  19.         }
  20.     }
  21. }

April 16, 2014

Bind Enum to DropDownList in Asp.Net

Enum in C# is a quick way to store constants. We can also assign value like int or chars to the constants. In other words, we can have a basic key - value sort of scenario with enums. Okay, so, how can I use a enum and bind it to a dropdownlist in asp.net.

To analyse what we need to do, we basically need to pull the names and the values from the enum and say a particular key has a particular value. Enums do not have a way to export the data to a list but it can export the list of names and list of values separately. The lists produced are in the same order and so we can say list[value] belongs to list[key].

March 25, 2014

Copy Object using MemberwiseClone

MemberwiseClone method from the Object class can be used to perform a shallow copy of an object. The method creates a new Object, copies all the instance fields. For value type fields, it copies bit by bit. For reference types fields, the reference is copied. That is, if the reference field / object is changed by the initial object, then the cloned object will also get updated. I have written sample code to illustrate. I have used a web project - but you can use a console application if you like it.

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace WebApplication1
  5. {
  6.     public class TestClone
  7.     {
  8.         public string Field1;
  9.         public DateTime Date1;
  10.         public double Double1;
  11.         public List<TestList> List1;
  12.  
  13.  
  14.         public object Clone()
  15.         {
  16.             return this.MemberwiseClone();
  17.         }
  18.     }
  19.  
  20.     public class TestList
  21.     {
  22.         public string Name;
  23.         public int Age;
  24.     }
  25. }

 

  1. private void Copy()
  2. {
  3.     TestClone t = new TestClone() { Date1 = new DateTime(2014, 3, 2), Double1 = 2.0, Field1 = "hhh" };
  4.     
  5.     //create a new list
  6.     t.List1 = new List<TestList>();
  7.     t.List1.Add(new TestList() { Age = 20, Name = "Smith" });
  8.     t.List1.Add(new TestList() { Age = 30, Name = "John" });
  9.  
  10.     TestClone t2 = (TestClone)t.Clone();
  11.     
  12.  
  13.     //modify t
  14.     t.Double1 = 3.0;
  15.     t.Field1 = "ABC";
  16.     t.List1.Add(new TestList() { Age = 40, Name = "Jim" });
  17.  
  18.  
  19.     //t3 will have old Double1 and Field1 values but new List1
  20.     TestClone t3 = (TestClone)t2.Clone();
  21.  
  22.     //t4 will have new Double1, Field1 values and new List1
  23.     TestClone t4 = (TestClone)t.Clone();
  24.  
  25. }

March 6, 2014

Get Height & Width of Uploaded Image

I have an asp.net FileUpload control that is used to upload images and now I need to check the dimensions (height, width) of the image from code behind. So, how can I go about that.

To solve this problem, I can use the System.Drawing.Image class and System.IO.Stream class to get height and width of the image. To do so, let’s add the FileUpload control on designer.

<asp:FileUpload ID="fu1" runat="server" />

 

Next, on the code-behind, I have a method that retrieves the uploaded file stream, loads an image from the stream and then obtains the dimension of the image. Note that I have skipped validation for the image on the FileUpload control and have assumed that a valid image is uploaded.

Code Snippet
  1. private string GetImageDimension()
  2. {
  3.     System.IO.Stream stream = fu1.PostedFile.InputStream;
  4.     System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
  5.  
  6.     int height = image.Height;
  7.     int width = image.Width;
  8.  
  9.     return "Height: " + height + "; Width: " + width;
  10. }

September 18, 2013

Common String operations

We deal with strings to do just about anything. In this post, I am listing some of the common string operations that one would face every now and then.

August 22, 2013

How to get Client IP Address using Asp.Net

Client IP address might be sometimes useful depending on the use case. In different projects, the company might decide to release products based on IP address range, etc and it will be useful in those scenarios to get the ip address. However, if the product is a web application and it needs to get location of the user - then, HTML5's geolocation might be a better solution provided. I will discuss about HTML5 geolocation in a different post.

In asp.net, the Request object has access to various server variables including HTTP_X_FORWARDED_FOR and REMOTE_ADDR which are two important ones for retrieving client IP address. There is a method in the Request object as well - Request.UserHostAddress() - that can return the client IP. 

The problem with Request.UserHostAddress() is that this method only works if the user is not behind a proxy server. If the user is behind a proxy server, this method returns the IP address of the proxy server. In this situation, the IP address is stored in the server variable - HTTP_X_FORWARDED_FOR. This variable contains a list of comma separated IP addresses in the format client IP, proxy1 IP, proxy2 IP, ... It is important to note that if the original client IP is needed, then we need to get first IP address returned.

If the above variable - HTTP_X_FORWARDED_FOR - returns null, then a different server variable - REMOTE_ADDR - needs to be used to get the IP address. There is no difference between using the method - Request.UserHostAddress() - and the variable - REMOTE_ADDR. Here is a code snippet on how to get the IP address of the client.

Code Snippet
  1. public string GetUserIPAddress()
  2. {
  3.     string ip = null;
  4.  
  5.     //returns a comma separated IP addresses in the format client, proxy1, proxy2...
  6.     //the IP seen by system is the last proxy IP
  7.     ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  8.  
  9.     if (ip == null)
  10.     {
  11.         ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  12.         //or use the code below
  13.         //ip = System.Web.HttpContext.Current.Request.UserHostAddress;
  14.     }
  15.     else
  16.     {
  17.         ip = ip.Split(',')[0];
  18.     }
  19.     return ip;
  20. }

July 28, 2011

Transform object to xml using linq

Using Linq, it’s easily possible to query various types of data like sql database, xml, objects like DataTable, ArrayList. It’s also possible to transform data into other formats like xml using linq. In this article, I will demonstrate how to query an System.Collections.ArrayList collection and then to save the data in xml format.

At first, I will create an ArrayList object and add Person objects to it. The code to do is below.

Adding objects to ArrayList
  1. ArrayList list = new ArrayList();
  2. list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  3. list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  4. list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });

The Person class has 4 public properties of different data types – string, DateTime and int as shown below.

Person class
  1. using System;
  2. namespace WebApplication1.CSClass
  3. {
  4.     public class Person
  5.     {
  6.         public string FirstName { get; set; }
  7.         public string LastName { get; set; }
  8.         public DateTime DateOfBirth { get; set; }
  9.         public int Height { get; set; }
  10.  
  11.         public override string ToString()
  12.         {
  13.             return FirstName + " " + LastName;
  14.         }
  15.     }
  16. }

Person objects are added to the ArrayList list which can be queried using linq as shown in my previous post on query ArrayList using Linq. While querying the list, System.Xml.Linq.XElement objects can be created which can be saved as xml using System.Xml.Linq.XDocument’s Save() method. The code to show this is below.

Transform ArrayList to xml
  1. private void TransformToXml()
  2. {
  3.     ArrayList list = new ArrayList();
  4.     list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  5.     list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  6.     list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });
  7.  
  8.     var q = from Person p in list
  9.             orderby p.FirstName
  10.             orderby p.LastName
  11.             select p;
  12.  
  13.     var query = new XElement("Persons", from Person p in list
  14.                                 select new
  15.                                 XElement("Person",
  16.                                 new XElement("FirstName", p.FirstName),
  17.                                 new XElement("LastName", p.LastName),
  18.                                 new XElement("DateOfBirth", p.DateOfBirth),
  19.                                 new XElement("Height", p.Height)
  20.                                 )
  21.                                 );
  22.  
  23.     XDocument doc = new XDocument(query);
  24.     doc.Save(Server.MapPath("transform.xml"));
  25.  
  26.     var query2 = new XElement("Persons", from Person p in list
  27.                                 select new
  28.                                 XElement("Person",
  29.                                 new XAttribute("FirstName", p.FirstName),
  30.                                 new XAttribute("LastName", p.LastName),
  31.                                 new XAttribute("DateOfBirth", p.DateOfBirth),
  32.                                 new XAttribute("Height", p.Height)
  33.                                 )
  34.                                 );
  35.  
  36.     XDocument doc2 = new XDocument(query2);
  37.     doc2.Save(Server.MapPath("transform2.xml"));
  38. }

As can be seen, the ArrayList object is queried for Person objects. This is not really needed for the code to work but is an example on how objects can be queried from ArrayList.

Using another query, “query”, XElement objects are created. The names of the XElement – that is, the names of the xml elements are arbitrary and the value of the elements are obtained from the Person object. The XElement objects are then added to XDocument object and saved as xml using XDocument.Save() method. The resultant xml looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person>
  4.     <FirstName>Scooby</FirstName>
  5.     <LastName>Doo</LastName>
  6.     <DateOfBirth>2000-12-31T00:00:00</DateOfBirth>
  7.     <Height>160</Height>
  8.   </Person>
  9.   <Person>
  10.     <FirstName>Bugs</FirstName>
  11.     <LastName>Bunny</LastName>
  12.     <DateOfBirth>1999-02-07T00:00:00</DateOfBirth>
  13.     <Height>170</Height>
  14.   </Person>
  15.   <Person>
  16.     <FirstName>Peter</FirstName>
  17.     <LastName>Pan</LastName>
  18.     <DateOfBirth>2001-10-31T00:00:00</DateOfBirth>
  19.     <Height>150</Height>
  20.   </Person>
  21. </Persons>

One thing to note is that the xml declaration is automatically added. DateTime field – DateOfBirth is automatically converted to its string representation.

The xml produced previously contains elements only. The Linq query could be easily updated to change the data to be the attributes of xml elements. This is shown in another query – “query2”. System.Xml.Linq.XAttribute objects are created similarly instead of XElement objects and added to XElement object which is then added to XDocument object and saved as xml. The resultant xml file looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person FirstName="Scooby" LastName="Doo" DateOfBirth="2000-12-31T00:00:00" Height="160" />
  4.   <Person FirstName="Bugs" LastName="Bunny" DateOfBirth="1999-02-07T00:00:00" Height="170" />
  5.   <Person FirstName="Peter" LastName="Pan" DateOfBirth="2001-10-31T00:00:00" Height="150" />
  6. </Persons>

The data looks similar to the previous xml except that they are now attributes of “Person” element instead of child elements.

Reference: Shahed Kazi at AspNetify.com