DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Using Non-Static classes in using block as directive in C# 6

It is a misconception that “using static” keyword is used to including only static classes as a directive in C# 6. But I have checked it in Visual Studio 2015 and it can also include Non-static classes.

E.g.

Class1.cs
  1. namespace UsingStatic1  
  2. {  
  3.     public class Class1  
  4.     {  
  5.         public static int Add(int x, int y)  
  6.         {  
  7.             return x + y;  
  8.         }  
  9.     }  
  10. }  

Program.cs
  
  1. using static UsingStatic1.Class1;  
  2. namespace UsingStatic  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int i = Add(20, 30);  
  9.         }  
  10.     }  
  11. }  
  UsingStatic1.Class1  is a non-static class and value of i will be 20+30=50;

Read Write and Update XML using LINQ Queries

I am going to take a Simple XML data and will show how to read write and Update it using LINQ.

Sample XML File:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LumiaMobiles>  
  3.   <LumiaMobile>  
  4.     <ModelId>lumia550</ModelId>  
  5.     <Height>136.1 mm</Height>  
  6.     <Width>67.8 mm</Width>  
  7.     <Thickness>9.9 mm</Thickness>  
  8.     <Weight>141.9 g</Weight>  
  9.   </LumiaMobile>  
  10.   <LumiaMobile>  
  11.     <ModelId>lumia950</ModelId>  
  12.     <Height>145 mm</Height>  
  13.     <Width>73.2 mm</Width>  
  14.     <Thickness>8.2 mm</Thickness>  
  15.     <Weight>150 g</Weight>  
  16.   </LumiaMobile>  
  17. </LumiaMobiles>  

Corresponding class for XML Data:

  1. public class LumiaMobile  
  2. {  
  3.    public string ModelId { getset; }  
  4.    public string Height { getset; }  
  5.    public string Width { getset; }  
  6.    public string Thickness { getset; }  
  7.    public string Weight { getset; }  
  8. }  

Code to Write XML File 

  1. private void WriteLumiaMobilesDetails(List<LumiaMobile> lstLumiaMobiles)  
  2. {  
  3.     using (XmlWriter writer = XmlWriter.Create("LumiaMobiles2.xml"))  
  4.     {  
  5.         writer.WriteStartDocument();  
  6.         writer.WriteStartElement("LumiaMobiles");  
  7.         foreach (var mobile in lstLumiaMobiles)  
  8.         {  
  9.             writer.WriteStartElement("LumiaMobile");  
  10.             writer.WriteElementString("ModelId", mobile.ModelId);  
  11.             writer.WriteElementString("Height", mobile.Height);  
  12.             writer.WriteElementString("Width", mobile.Width);  
  13.             writer.WriteElementString("Thickness", mobile.Thickness);  
  14.             writer.WriteElementString("Weight", mobile.Weight);  
  15.             writer.WriteEndElement();  
  16.         }  
  17.   
  18.         writer.WriteEndElement();  
  19.         writer.WriteEndDocument();  
  20.     }  
  21. }  

Calling Write XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.     Program p = new Program();              
  4.     List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  5.     lstLumiaMobiles.Add(new LumiaMobile  
  6.     {  
  7.         ModelId = "lumia550",  
  8.         Height = "136.1 mm",  
  9.         Width = "67.8 mm",  
  10.         Thickness = "9.9 mm",  
  11.         Weight = "141.9 g"  
  12.     });  
  13.   
  14.     lstLumiaMobiles.Add(new LumiaMobile  
  15.     {  
  16.         ModelId = "lumia950",  
  17.         Height = "145 mm",  
  18.         Width = "73.2 mm",  
  19.         Thickness = "8.2 mm",  
  20.         Weight = "150 g"  
  21.     });  
  22.     p.WriteLumiaMobilesDetails(lstLumiaMobiles);              
  23. }  

Code to Read XML Data:

  1. public List<LumiaMobile> ReadLumiaMobilesDetails()  
  2. {  
  3.     List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  4.     try  
  5.     {  
  6.         using (XmlReader xr = XmlReader.Create(@"LumiaMobiles.xml"))  
  7.         {  
  8.             XDocument xdoc = XDocument.Load(xr);  
  9.             var LumiaMobiles = xdoc.Descendants("LumiaMobiles").Descendants("LumiaMobile");  
  10.             foreach (var mobile in LumiaMobiles)  
  11.             {  
  12.                 lstLumiaMobiles.Add(new LumiaMobile  
  13.                 {  
  14.                     ModelId = Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value),  
  15.                     Height = Convert.ToString(mobile.Descendants("Height").FirstOrDefault().Value),  
  16.                     Width = Convert.ToString(mobile.Descendants("Width").FirstOrDefault().Value),  
  17.                     Thickness = Convert.ToString(mobile.Descendants("Thickness").FirstOrDefault().Value),  
  18.                     Weight = Convert.ToString(mobile.Descendants("Weight").FirstOrDefault().Value)  
  19.                 });  
  20.             }  
  21.         }  
  22.     }  
  23.     catch (Exception)  
  24.     {  
  25.   
  26.     }  
  27.     return lstLumiaMobiles;  
  28. }  

Calling Read XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.    Program p = new Program();  
  4.    p.ReadLumiaMobilesDetails();   
  5. }  

Code to Update XML Data:

  1. private void UpdateXmlElementforMobile(string ModelId, string element, string elementValue)  
  2. {  
  3.   
  4.     XDocument xdoc = XDocument.Load("LumiaMobiles.xml");  
  5.     var LumiaMobiles = xdoc.Descendants("LumiaMobile");  
  6.     foreach (var mobile in LumiaMobiles)  
  7.     {  
  8.         if (mobile.Descendants("ModelId").Any())  
  9.         {  
  10.             if (Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value) == ModelId)  
  11.             {  
  12.                 mobile.Descendants(element).FirstOrDefault().Value = elementValue;  
  13.                 xdoc.Save("LumiaMobiles.xml");  
  14.             }  
  15.         }  
  16.     }  
  17. }  

Calling Update XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.    Program p = new Program();  
  4.    p.UpdateXmlElementforMobile("lumia950""Height""145.0 mm");  
  5. }  

Complete Code is:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Xml;  
  5. using System.Xml.Linq;  
  6.   
  7. namespace XMLtoLINQ  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             Program p = new Program();  
  14.             p.ReadLumiaMobilesDetails();  
  15.             List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  16.             lstLumiaMobiles.Add(new LumiaMobile  
  17.             {  
  18.                 ModelId = "lumia550",  
  19.                 Height = "136.1 mm",  
  20.                 Width = "67.8 mm",  
  21.                 Thickness = "9.9 mm",  
  22.                 Weight = "141.9 g"  
  23.             });  
  24.   
  25.             lstLumiaMobiles.Add(new LumiaMobile  
  26.             {  
  27.                 ModelId = "lumia950",  
  28.                 Height = "145 mm",  
  29.                 Width = "73.2 mm",  
  30.                 Thickness = "8.2 mm",  
  31.                 Weight = "150 g"  
  32.             });  
  33.   
  34.             p.WriteLumiaMobilesDetails(lstLumiaMobiles);  
  35.   
  36.             p.UpdateXmlElementforMobile("lumia950""Height""145.0 mm");  
  37.         }  
  38.   
  39.         private void UpdateXmlElementforMobile(string ModelId, string element, string elementValue)  
  40.         {  
  41.   
  42.             XDocument xdoc = XDocument.Load("LumiaMobiles.xml");  
  43.             var LumiaMobiles = xdoc.Descendants("LumiaMobile");  
  44.             foreach (var mobile in LumiaMobiles)  
  45.             {  
  46.                 if (mobile.Descendants("ModelId").Any())  
  47.                 {  
  48.                     if (Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value) == ModelId)  
  49.                     {  
  50.                         mobile.Descendants(element).FirstOrDefault().Value = elementValue;  
  51.                         xdoc.Save("LumiaMobiles.xml");  
  52.                     }  
  53.                 }  
  54.             }  
  55.         }  
  56.   
  57.         private void WriteLumiaMobilesDetails(List<LumiaMobile> lstLumiaMobiles)  
  58.         {  
  59.             using (XmlWriter writer = XmlWriter.Create("LumiaMobiles2.xml"))  
  60.             {  
  61.                 writer.WriteStartDocument();  
  62.                 writer.WriteStartElement("LumiaMobiles");  
  63.                 foreach (var mobile in lstLumiaMobiles)  
  64.                 {  
  65.                     writer.WriteStartElement("LumiaMobile");  
  66.                     writer.WriteElementString("ModelId", mobile.ModelId);  
  67.                     writer.WriteElementString("Height", mobile.Height);  
  68.                     writer.WriteElementString("Width", mobile.Width);  
  69.                     writer.WriteElementString("Thickness", mobile.Thickness);  
  70.                     writer.WriteElementString("Weight", mobile.Weight);  
  71.                     writer.WriteEndElement();  
  72.                 }  
  73.   
  74.                 writer.WriteEndElement();  
  75.                 writer.WriteEndDocument();  
  76.             }  
  77.         }  
  78.   
  79.         public List<LumiaMobile> ReadLumiaMobilesDetails()  
  80.         {  
  81.             List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  82.             try  
  83.             {  
  84.                 using (XmlReader xr = XmlReader.Create(@"LumiaMobiles.xml"))  
  85.                 {  
  86.                     XDocument xdoc = XDocument.Load(xr);  
  87.                     var LumiaMobiles = xdoc.Descendants("LumiaMobiles").Descendants("LumiaMobile");  
  88.                     foreach (var mobile in LumiaMobiles)  
  89.                     {  
  90.                         lstLumiaMobiles.Add(new LumiaMobile  
  91.                         {  
  92.                             ModelId = Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value),  
  93.                             Height = Convert.ToString(mobile.Descendants("Height").FirstOrDefault().Value),  
  94.                             Width = Convert.ToString(mobile.Descendants("Width").FirstOrDefault().Value),  
  95.                             Thickness = Convert.ToString(mobile.Descendants("Thickness").FirstOrDefault().Value),  
  96.                             Weight = Convert.ToString(mobile.Descendants("Weight").FirstOrDefault().Value)  
  97.                         });  
  98.                     }  
  99.                 }  
  100.             }  
  101.             catch (Exception)  
  102.             {  
  103.   
  104.             }  
  105.             return lstLumiaMobiles;  
  106.         }  
  107.     }  
  108.   
  109.     public class LumiaMobile  
  110.     {  
  111.         public string ModelId { getset; }  
  112.         public string Height { getset; }  
  113.         public string Width { getset; }  
  114.         public string Thickness { getset; }  
  115.         public string Weight { getset; }  
  116.     }  
  117. }  

Read and Write a Text File With UTF8 Encoding

Write a Text File with UTF8 Encoding,
  1. public void WriteATxtFileWithUTF8Encoding()  
  2. {  
  3.     string txtFilePath = @"D:\bnarayan.txt";  
  4.     using (StreamWriter writer =  
  5.     new StreamWriter(txtFilePath, true, Encoding.UTF8))  
  6.     {  
  7.         writer.WriteLine("Name: Banketeshvar Narayan");  
  8.         writer.WriteLine("Email Id: bnarayan123@gmail.com");  
  9.     }  
  10. }  
Read Data from Text File With UTF8 Encoding,
  1. public void ReadDataFromTxtFileWithUTF8Encoding(string txtFilePath)  
  2. {  
  3.     if (File.Exists(txtFilePath))  
  4.     {  
  5.         using(var reader = new StreamReader(File.OpenRead(txtFilePath), Encoding.UTF8))  
  6.         {  
  7.             while (!reader.EndOfStream)  
  8.             {  
  9.                 var line = reader.ReadLine();  
  10.                 if (!String.IsNullOrEmpty(line))  
  11.                 {  
  12.                     Console.WriteLine(line);  
  13.                 }  
  14.             }  
  15.         }  
  16.     }  
  17. }  
Calling Read and Write methods for Text Files
  1. static void Main(string[] args)  
  2. {  
  3.     Program p = new Program();  
  4.     p.WriteATxtFileWithUTF8Encoding();  
  5.     p.ReadDataFromTxtFileWithUTF8Encoding(@"D:\bnarayan.txt");  
  6. }  

MD5 Hashing and Verification

  1. using System;  
  2. using System.Security.Cryptography;  
  3. using System.Text;..................................................................  
  4. static string GetMd5Hash(string textToHash)  
  5. {  
  6.     MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();  
  7.     byte[] data = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(textToHash));  
  8.     StringBuilder sbHashedCode = new StringBuilder();  
  9.     for (int i = 0; i < data.Length; i++)  
  10.     {  
  11.         sbHashedCode.Append(data[i].ToString("x2"));  
  12.     }  
  13.     return sbHashedCode.ToString();  
  14. }  
  15. static bool verifyMd5Hash(string plainText, string hashedValue)  
  16. {  
  17.     return StringComparer.OrdinalIgnoreCase.Compare(GetMd5Hash(plainText), hashedValue) == 0 ? true : false;  

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.