DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Capture SOAP Request using Fiddler

Sometimes you are not able to Capture Soap request using fiddler. In that case you have to make some changes in config file.

Add these lines to web.config files:

  1. <system.net>  
  2.    <defaultProxy>  
  3.       <proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />  
  4.    </defaultProxy>  
  5. </system.net>  

Variable.ToString() vs. Convert.ToString(variable)

variable.ToString() and Convert.ToString(variable) both are used for converting data into string. But the main difference is that Convert.ToString() handles null, while ToString() doesn't handle null value.

Apart from that both works almost same. Let’s take an example to explain it:
  1. double amount = 10000.0;  
  2. Console.WriteLine(amount.ToString());  
  3. Console.WriteLine(Convert.ToString(amount));   
In this case both method will convert “amount” to string and will return the same value but in case of null value variable.ToString() method will throw exception.

Now take another example:

  1. object myObject = null;  
  2. string myString;  
  3.   
  4. //myString = myObject.ToString();  
  5. // System.NullReferenceException : { "Object reference not set to an instance of an object."}  
  6.   
  7. myString = Convert.ToString(myObject);  
  8. //return empty string

Getting More than 2 Values for an Enum Item

As we know that we can get Enum and it value from an Enum type e.g. I want to create an enum for sorting of article like below:

  1. enum ArticleSortingOptions  
  2. {  
  3.    MostPopularArticle =1,  
  4.    LatestArticles =2,  
  5.    FeaturedArtilces =3,  
  6.    MostLikedArtilces =4,  
  7.    MostCommentedArtilces=5  
  8. }  

And accessing it like

  1. WriteLine(MostPopularArticle.ToString());  
  2. WriteLine((int)MostPopularArticle);  

Output

MostPopularArticle

1

you may be thinking that I am aceesing enum item without enum name. Yes, it is possible in C# 6 & C# 7 that we can acess enum items without enum name for that we have to write enum name in using statement i.e.

  1. using static MultiValuedEnum.ArticleSortingOptions;  

You will never prefer to display the value like “MostPopularArticle” but to be displayed like “Most Popular Article”. As we know that enum will not allow you to write an item with spaces. So we will require 3 types of values

1. Integer value of enum item.

2.   2. Name of enum Item (string Value of enum).

3.   3. Description of Enum (or some other value as per requirement).

We can achieve this by writing and extension method for enum.

  1. public static class ExtendEnum  
  2. {  
  3.    public static string DisplayString<T>(this T enumVal)  
  4.    {  
  5.       FieldInfo fi = enumVal.GetType().GetField(enumVal.ToString());  
  6.       var attrs = fi?.GetCustomAttributes(typeof(DescriptionAttribute), true);  
  7.       if (attrs != null && attrs.Length > 0)  
  8.       {  
  9.          return ((DescriptionAttribute)attrs[0]).Description;  
  10.       }  
  11.       return "No Description found";  
  12.    }  
  13. }  

And access like:

  1. WriteLine(MostPopularArticle.ToString());  
  2. WriteLine((int)MostPopularArticle);  
  3. WriteLine(MostPopularArticle.DisplayString());  

Complete Code:

  1. using System.ComponentModel;  
  2. using System.Reflection;  
  3. using static MultiValuedEnum.ArticleSortingOptions;  
  4. using static System.Console;  
  5.   
  6. namespace MultiValuedEnum  
  7. {  
  8.     enum ArticleSortingOptions  
  9.     {  
  10.         [Description("Most Popular Article")]  
  11.         MostPopularArticle = 1,          
  12.         LatestArticles = 2,  
  13.         FeaturedArtilces = 3,  
  14.         MostLikedArtilces = 4,  
  15.         MostCommentedArtilces = 5  
  16.     }  
  17.     class Program  
  18.     {  
  19.         static void Main(string[] args)  
  20.         {  
  21.             WriteLine(MostPopularArticle.ToString());  
  22.             WriteLine((int)MostPopularArticle);  
  23.             WriteLine(MostPopularArticle.DisplayString());  
  24.         }  
  25.     }  
  26.   
  27.     public static class ExtendEnum  
  28.     {  
  29.         public static string DisplayString<T>(this T enumVal)  
  30.         {  
  31.             FieldInfo fi = enumVal.GetType().GetField(enumVal.ToString());  
  32.             var attrs = fi?.GetCustomAttributes(typeof(DescriptionAttribute), true);  
  33.             if (attrs != null && attrs.Length > 0)  
  34.             {  
  35.                 return ((DescriptionAttribute)attrs[0]).Description;  
  36.             }  
  37.             return "No Description found";  
  38.         }  
  39.     }  
  40. }  

Output

MostPopularArticle

1

Most Popular Article

Read and Write XML File using XMLDocument

Read & Write XML File using XMLDocument

Write XML File Using Xml Writer,
  1. public void WriteXMLFileUsingXmlWriter()  
  2. {  
  3.     List < LumiaMobile > LumiaMobiles = new List < LumiaMobile > ();  
  4.     LumiaMobiles.Add(new LumiaMobile  
  5.     {  
  6.         ModelId = "lumia550",  
  7.             Height = "136.1 mm",  
  8.             Width = "67.8 mm",  
  9.             Thickness = "9.9 mm",  
  10.             Weight = "141.9 g"  
  11.     });  
  12.     LumiaMobiles.Add(new LumiaMobile  
  13.     {  
  14.         ModelId = "lumia950",  
  15.             Height = "145 mm",  
  16.             Width = "73.2 mm",  
  17.             Thickness = "8.2 mm",  
  18.             Weight = "150 g"  
  19.     });  
  20.     LumiaMobiles.Add(new LumiaMobile  
  21.     {  
  22.         ModelId = "Text",  
  23.             Height = "",  
  24.             Width = "",  
  25.             Thickness = "8.2 mm",  
  26.             Weight = "150 g"  
  27.     });  
  28.     using(XmlWriter writer = XmlWriter.Create("LumiaMobiles.xml"))  
  29.     {  
  30.         writer.WriteStartDocument();  
  31.         writer.WriteStartElement("LumiaMobiles");  
  32.         foreach(LumiaMobile lumiaMobile in LumiaMobiles)  
  33.         {  
  34.             writer.WriteStartElement(lumiaMobile.ModelId);  
  35.             writer.WriteElementString("Height", lumiaMobile.Height);  
  36.             writer.WriteElementString("Width", lumiaMobile.Width);  
  37.             writer.WriteElementString("Thickness", lumiaMobile.Thickness);  
  38.             writer.WriteElementString("Weight", lumiaMobile.Weight);  
  39.             writer.WriteEndElement();  
  40.         }  
  41.         writer.WriteEndElement();  
  42.         writer.WriteEndDocument();  
  43.     }  
  44. }  
The above code snippet will write XML file in single line i.e. not formatted, all content in same line. 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LumiaMobiles>  
  3.         <lumia550>  
  4.             <Height>136.1 mm</Height>  
  5.             <Width>67.8 mm</Width>  
  6.             <Thickness>9.9 mm</Thickness>  
  7.             <Weight>141.9 g</Weight>  
  8.         </lumia550>  
  9.         <lumia950>  
  10.             <Height>145 mm</Height>  
  11.             <Width>73.2 mm</Width>  
  12.             <Thickness>8.2 mm</Thickness>  
  13.             <Weight>150 g</Weight>  
  14.         </lumia950>  
  15.         <Text>  
  16.             <Height />  
  17.             <Width />  
  18.             <Thickness>8.2 mm</Thickness>  
  19.             <Weight>150 g</Weight>  
  20.         </Text>  
  21.     </LumiaMobiles>  
So to write formatted XML data we can use XmlTextWriter,
 
Write XML File Using Xml TextWriter,
  1. public void WriteXMLFileUsingXmlTextWriter()  
  2. {  
  3.     List < LumiaMobile > LumiaMobiles = new List < LumiaMobile > ();  
  4.     LumiaMobiles.Add(new LumiaMobile  
  5.     {  
  6.         ModelId = "lumia550",  
  7.             Height = "136.1 mm",  
  8.             Width = "67.8 mm",  
  9.             Thickness = "9.9 mm",  
  10.             Weight = "141.9 g"  
  11.     });  
  12.     LumiaMobiles.Add(new LumiaMobile  
  13.     {  
  14.         ModelId = "lumia950",  
  15.             Height = "145 mm",  
  16.             Width = "73.2 mm",  
  17.             Thickness = "8.2 mm",  
  18.             Weight = "150 g"  
  19.     });  
  20.     LumiaMobiles.Add(new LumiaMobile  
  21.     {  
  22.         ModelId = "Text",  
  23.             Height = "",  
  24.             Width = "",  
  25.             Thickness = "8.2 mm",  
  26.             Weight = "150 g"  
  27.     });  
  28.     string filename = "LumiaMobiles.xml";  
  29.     using(XmlTextWriter writer = new XmlTextWriter(new StreamWriter(new FileStream(filename, FileMode.Create))))  
  30.     {  
  31.         writer.Formatting = Formatting.Indented;  
  32.         writer.Indentation = 4;  
  33.         writer.WriteStartDocument();  
  34.         writer.WriteStartElement("LumiaMobiles");  
  35.         foreach(LumiaMobile lumiaMobile in LumiaMobiles)  
  36.         {  
  37.             writer.WriteStartElement(lumiaMobile.ModelId);  
  38.             writer.WriteElementString("Height", lumiaMobile.Height);  
  39.             writer.WriteElementString("Width", lumiaMobile.Width);  
  40.             writer.WriteElementString("Thickness", lumiaMobile.Thickness);  
  41.             writer.WriteElementString("Weight", lumiaMobile.Weight);  
  42.             writer.WriteEndElement();  
  43.         }  
  44.         writer.WriteEndElement();  
  45.         writer.WriteEndDocument();  
  46.     }  
  47. }  
It will write XML file as: 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LumiaMobiles>  
  3.     <lumia550>  
  4.         <Height>136.1 mm</Height>  
  5.         <Width>67.8 mm</Width>  
  6.         <Thickness>9.9 mm</Thickness>  
  7.         <Weight>141.9 g</Weight>  
  8.     </lumia550>  
  9.     <lumia950>  
  10.         <Height>145 mm</Height>  
  11.         <Width>73.2 mm</Width>  
  12.         <Thickness>8.2 mm</Thickness>  
  13.         <Weight>150 g</Weight>  
  14.     </lumia950>  
  15.     <Text>  
  16.         <Height />  
  17.         <Width />  
  18.         <Thickness>8.2 mm</Thickness>  
  19.         <Weight>150 g</Weight>  
  20.     </Text>  
  21. </LumiaMobiles>   
Now use the below code to Read the above XML File,
  1. public void ReadXMLFile(string xmlFileName)  
  2. {  
  3.     XmlDocument xmlDocument = new XmlDocument();  
  4.     xmlDocument.Load(xmlFileName);  
  5.     XmlNodeList nodeList = xmlDocument.SelectNodes("LumiaMobiles");  
  6.     foreach(XmlNode node in nodeList)  
  7.     {  
  8.         XmlNodeList lumianodes = node.ChildNodes;  
  9.         foreach(XmlNode item in lumianodes)  
  10.         {  
  11.             Console.WriteLine("ModelID : {0}", item.Name);  
  12.             Console.WriteLine("Height: {0}", item.SelectSingleNode("Height").InnerText);  
  13.             Console.WriteLine("Width: {0}", item.SelectSingleNode("Width").InnerText);  
  14.             Console.WriteLine("Thickness: {0}", item.SelectSingleNode("Thickness").InnerText);  
  15.             Console.WriteLine("Weight: {0}", item.SelectSingleNode("Weight").InnerText);  
  16.             Console.WriteLine();  
  17.         }  
  18.     }  
  19.     Console.ReadKey();  
  20. }  

    Using Static Classes as Directive in C# 6

    As we know that in C# 6 we can use static classes in using directive. To use static classes in using directive we use the following syntax:

    Using static <StaticClassNameWithCompleteNameSpace>;

    1. using System;  
    2. using static System.Console;  
    3. using static System.Convert;  
    4.   
    5. namespace UsingStaticToPrintDay  
    6. {  
    7.     class Program  
    8.     {  
    9.         static void Main(string[] args)  
    10.         {  
    11.             try  
    12.             {  
    13.                 WriteLine("Enter you choice from 1-7 and it will print corresponding day of a week");  
    14.                 int choiceofday  = ToInt32(ReadLine());    
    15.                 //Cast int to Enum                
    16.                 string dayOfweek = Enum.GetName(typeof(DayOfWeek), choiceofday);  
    17.                 WriteLine(dayOfweek);                
    18.             }  
    19.             catch (Exception ex)  
    20.             {  
    21.                 WriteLine(ex.Message);  
    22.             }  
    23.              
    24.               
    25.         }  
    26.     }  
    27. }  

    Converting DateTime to Unix TimeStamp in Local Time

    The unix time stamp is the number of seconds between a particular date and the Unix Epoch. The counts of Unix Epoch start on 01-Jan-1970 at UTC.

    But sometimes we need to calculate the time stamp as per local time. Suppose an event has been occurred on 01-Jan-1990 00:00 IST (GMT + 5:30) and I convert it to time stamp as per UTC then here will be difference of 5:30 hrs. To get exact time stamp with 00:00 hrs difference I am converting it as per local time.

    Way1 :

    /// <summary> /// Convers to unix date time stamp way1. /// </summary> /// <param name="dateToConvert">The date to convert.</param> /// <returns></returns> public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert) { TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)); return Convert.ToInt64(timeSpan.TotalSeconds); }









    /// <summary>   
    /// Convers to unix date time stamp way1.
    /// </summary>
    /// <param name="dateToConvert">The date to convert.</param>
    /// <returns></returns>
    public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert) {
    TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local));
    return Convert.ToInt64(timeSpan.TotalSeconds); }







    1.   

    Way2 :

    1. /// <summary>   
    2. /// Convers to unix date time stamp way2.   
    3. /// </summary>   
    4. /// <param name="dateToConvert">The date to convert.</param>   
    5. /// <param name="dateFormat">The date format.</param>   
    6. /// <returns></returns>   
    7. public static string ConverToUnixDateTimeStampWay2(string dateToConvert, string dateFormat)  
    8. {  
    9.     DateTime dtToConvert = new DateTime();  
    10.     DateTime.TryParseExact(dateToConvert, dateFormat, null, DateTimeStyles.AssumeLocal, out dtToConvert);  
    11.   
    12.     //in the below statement DateTime.Parse("01 /01/1970 00:00:00") is not safe and will throw exception while changing DateTimeFormat   
    13.     long ticks = dtToConvert.Subtract(new TimeSpan(1, 0, 0)).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;  
    14.     ticks /= 10000000; //Convert windows ticks to seconds   
    15.     return ticks.ToString();  
    16. }  

    In both of the above methods you can see that I am storing all data in long (System.Int64) instead of int (System.Int32).

    If I store time stamp in int (System.Int32) then it will throw exception for any date after 19-January-2038.