How can use XML Serialization in VB.Net and C#?

Xml-tool-iconAs you know there are different types of machines and OS in the world that they have to connect to each other and transfer data but each system has own structure and may cannot understand the data that are coming from other system(s), but technology has solved it for them! One of the solutions is XML

What is XML?

XML  (Extensible Markup Language) is a format that was designed to transport and store data.Both machine and human can understand XML.

If you want to learn more about the XML I suggest you to go this link.

Before start you must import these classes:


Imports System.IO
Imports System.Xml.Serialization


using System.IO;
using System.Xml.Serialization;


 Private Sub CreateXML()
        Dim OFileStream As FileStream = _
New FileStream("C:/CodingTips.XML", _
        Dim Oxmlsr As XmlSerializer = _ 
New XmlSerializer(GetType(DateTime))
        Oxmlsr.Serialize(OFileStream, System.DateTime.Now.ToString)
    End Sub


private void CreateXML()
    FileStream OFileStream = new FileStream("C:/CodingTips.XML",_
    XmlSerializer Oxmlsr = new XmlSerializer(typeof(DateTime));
    Oxmlsr.Serialize(OFileStream, System.DateTime.Now.ToString());

How can make SAH1 through VB.Net & C#


What is SHA1?

This part has been copied directly form Wikipedia

SHA-1 is a cryptographic hash function designed by the United States National Security Agency and published by the United States NIST as a U.S. Federal Information Processing Standard. SHA stands for “secure hash algorithm”. For further information click here

Why you need SHA1?

If you want to make your sensitive information secure, one of the best way, is that make them encrypt. There are different ways which  you can use them to make your information encrypt but  in most of cases the encrypted information can be decrypted easily , So these methods  cannot be  good choice  for encrypting  data same as Base64, But SHA1 is a one way street , it means after encrypt  nobody can decrypt  it . Awesome!

If there is no way to decrypt SHA1, how we can use it?

It is common question about SHA1! Somebody still looking for a way to decrypt the SHA1 but I suggest them to stop searching because they cannot find anything.

Now I will explain you how SHA1 can work for you. For example you make a SAH1 from the password that you want to save on the database, when user wants to login to the system you have to make another SHA1 form the string that user has entered, then compare it with SHA1 that you have been saved before on the database if they are same user is eligible to login to the system.

To make a SAH1 you need to pass 3 steps:

  1. Make byte stream from the string that you want to encrypt.
  2. Make SHA1 form the byte.
  3. Make string from the SHA1 that you have produced.

I have mention these three steps in the code below:


 Private Sub EncryptData()
    Dim strToHash As String = "Please Encrypt me !"
    Dim Result As String = ""
    Dim OSha1 As New _

    'Step 1
    Dim bytesToHash() As Byte _
     = System.Text.Encoding.ASCII.GetBytes(strToHash)

    'Step 2
    bytesToHash = OSha1.ComputeHash(bytesToHash)

    'Step 3
     For Each item As Byte In bytesToHash
          Result += item.ToString("x2")
    End Sub


private void EncryptData()
    string strToHash = "Please Encrypt me !";
    string Result = "";
    System.Security.Cryptography.SHA1CryptoServiceProvider OSha1 = _
    new System.Security.Cryptography.SHA1CryptoServiceProvider();

    //Step 1
    byte[] bytesToHash = _

    //Step 2
    bytesToHash =_

    //Step 3
    foreach (byte item in bytesToHash) {
        Result += item.ToString("x2");

How To Write File Through VB.Net & C#


As I have promised ,today I am going to show you how to create a file, you can write (create) file in different ways same as reading file.

Before you start, have to import System.IO.


Imports System.IO


using System.IO;

Writing File

Let met to start with the easiest way,


With this function you can create and write file at the same time!


File.WriteAllText("c:\CodingTips.txt", "coding is easy !")


File.WriteAllText("c:\\CodingTips.txt", "coding is easy !")


This Pattern is much like reading file.


Dim writer As StreamWriter =File.CreateText("c:\CodingTips.txt") 
writer.WriteLine("coding is easy") 


StreamWriter writer = File.CreateText("c:\\CodingTips.txt");
writer.WriteLine("coding is easy");


Sometimes you will need to create a stream (the string that you want to write to the file) before you really need to store it somewhere (like in a file). for example you have 5 functions in your code, and each function has a specific result and you want to store the results of these functions in one file, you cannot use the methods that I explained above, in this case, first you need to prepare the stream and then write it to the file, for this purpose MemoryStream would be a good choice,


Dim memoryStrm As New MemoryStream()
Dim writer As New StreamWriter(memoryStrm) 

'This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.


MemoryStream memoryStrm= new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStrm);

//This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.

After you prepared your MemoryStream you can write it to the file:


' Here you must ask the writer to push the data into the 
' underlying stream 
' the create a file stream 
Dim MyFile As FileStream = File.Create("c:\CodingTips.txt") 
' now Write the MemoryStream to the file
memoryStrm .WriteTo(theFile) 
' the you have to Clean up the objects 
memoryStrm .Close()


// Here you must ask the writer to push the data into the 
// underlying stream 

    // the create a file stream 
    FileStream MyFile = File.Create("c:\\CodingTips.txt");
    // now Write the MemoryStream to the file
    // the you have to Clean up the objects 

How Read a Files Through VB.Net & C#

Reading and writing files are two of the most common tasks in the world of development. As a .NET developer, .NET Framework makes it easy to perform these tasks.

Before you start, have to import System.IO.


Imports System.IO


using System.IO;

1.Reading File

There are different ways that you can use them for reading file,

if you want to read a whole file as string, this ways could be fine for you:


 Dim Result As String = File.ReadAllText("C:\CodingTips.txt")


string Result = File.ReadAllText("C:\\CodingTips.txt");

if you need more properties and futures ,

same as searching specific text in the file, I suppose  this ways is more  efficient:

 Private Sub Readfile()
        Dim strReader As StreamReader = File.OpenText("C:\CodingTips.txt")
        ' We will Search the stream until we reach the end or find the specific string.
        While Not strReader.EndOfStream
            Dim line As String = strReader.ReadLine()
            If line.Contains("Code") Then
                'If we find the specific string, we will inform the user and finish the while loop.
                Console.WriteLine("Found Code:")
                Exit While
            End If
        End While
        ' Here we have to clean the memory.
    End Sub


private void Readfile()
    StreamReader strReader = File.OpenText("C:\\CodingTips.txt");
    // We will Search the stream until we reach the end or find the specific string.
    while (!strReader.EndOfStream) {
        string line = strReader.ReadLine();
        if (line.Contains("Code")) {
            //If we find the specific string, we will inform the user and finish the while loop.
            Console.WriteLine("Found Code:");
            break; // TODO: might not be correct. Was : Exit While
    // Here we have to clean the memory.

In the next post I will teach you , How to write a file 🙂

How can send mail through VB.Net or C# ?

For a developer, e-mail is an effective way to allow an application to send files or reports to users and to notify users of problems or events.Here i am going to explain how can send mail through or C#.

To send an email you need two objects:

1.MailMessage object: with this object you can create your message that you want to send.

2.SmtpClient object: with this object you can  send your MailMessage to the recipients.

Before you create a function that send mail ,you need to import System.Net.Mail :


Imports System.Net.Mail


using System.Net.Mail;

Now your code is ready for creating SendMail function


 Private Sub SendMail()
        Dim Message As MailMessage = New MailMessage()
        Message.From = New MailAddress("", "Arman")
        Message.To.Add(New MailAddress("", "Mehran"))
        Message.To.Add(New MailAddress("", "Mike"))
        Message.To.Add(New MailAddress("", "JM"))
        Message.Subject = "Quarterlydata report."
        Message.Body = "See the attached spreadsheet."
        Message.Attachments.Add(New Attachment("C:\Test.txt"))

        Dim sc As SmtpClient = New SmtpClient("")
        sc.Port = 587
        sc.EnableSsl = True
        sc.Credentials = New NetworkCredential("Username", "Password")

    End Sub


private void SendMail()
    MailMessage Message = new MailMessage();
    Message.From = new MailAddress("", "Arman");
    Message.To.Add(new MailAddress("", "Mehran"));
    Message.To.Add(new MailAddress("", "Mike"));
    Message.To.Add(new MailAddress("", "JM"));
    Message.Subject = "Quarterlydata report.";
    Message.Body = "See the attached spreadsheet.";
    Message.Attachments.Add(new Attachment("C:\\Test.txt"));

    SmtpClient sc = new SmtpClient("");
    sc.Port = 587;
    sc.EnableSsl = true;
    sc.Credentials = new NetworkCredential("Username", "Password");



SmtpClient.port: it depends on the server that you want to use it to send mail.

SmtpClient .Host: it depends on the server that you want to use it to send mail. (here I used “”)

SmtpClient.EnableSsl: If your server is using the SSL you can user this option.

How can create Array in VB.Net & C# ?

ms_visual_studio    There are different ways that you can create array , here I am going to explain them for you
1.You can supply the array size when you are declaring it , as the following example shows.


        Dim cargoWeights(10) As Double 

        Dim atmospherePressures(2, 2, 4, 10) As Short 

        Dim inquiriesByYearMonthDay(20)()() As Byte


        double[] cargoWeights = new double[11];

        short[,,,] atmospherePressures = new short[3, 3, 5, 11];

        byte[][][] inquiriesByYearMonthDay = new byte[21][][];

2.You can also use a New clause to supply the size of an array
 when it’s created, as the following example shows.


          cargoWeights = New Double(10) {}

          atmospherePressures = New Short(2, 2, 4, 10) {}

          inquiriesByYearMonthDay = New Byte(20)()() {}


          cargoWeights = new double[11];

          atmospherePressures = new short[3, 3, 5, 11];

          inquiriesByYearMonthDay = new byte[21][][];

How to create cookie in VB.Net & C#

Cookie is  one of the useful object that can be used in the web application, and you can use it to save user setting on the local computer or device.

 Before create any Cookie please read these hints:
1. This part was copied directly from Cookie Law :
  Cookie laws have changed with effect from 26th May 2011.
On 26th May 2011, new laws came into force in the UK that affect most web sites. If cookies are used in a site, the Privacy and Electronic Communications (EC Directive) (Amendment) Regulations 2011 (UK Regulations) provide that certain information must be given to that site’s visitors and the user must give his or her consent to the placing of the cookies…..
For further information please go to  the Cookie Law
2. Programmers have not to save sensitive(confidential) information same as Username, Password, Credit card number or something like that in the Cookies.
Seat your belt we want to finish this part rapidly 🙂
Different parts of Cookies:
 1. Name: each Cookie must has the specific name.
2. Value: Each Cookie has specific value, without value Cookie does not have meaning.
3 Expire Date: .Each Cookie must have Expire date, we do not want to save a Cookie for ever!
Before you create a Cookie must check the Cookie existent, if the Cookie already is exits no need to create it again, you just have to update the value or Expire date.

 Private Sub CreateCookies()

        If Request.Cookies("UserName") Is Nothing Then

            Dim aCookie As New HttpCookie("UserName")

            aCookie.Value = "MyUsername"

            aCookie.Expires = DateTime.Now.AddDays(30)



            Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies("UserName")

            cookie.Value = "UserName"

            cookie.Expires = DateTime.Now.AddDays(30)


        End If



private void CreateCookies()


    if (Request.Cookies("UserName") == null) {

        HttpCookie aCookie = new HttpCookie("UserName");

        aCookie.Value = "MyUsername";

        aCookie.Expires = DateTime.Now.AddDays(30);


    } else {

        HttpCookie cookie = HttpContext.Current.Request.Cookies("UserName");

        cookie.Value = "UserName";

        cookie.Expires = DateTime.Now.AddDays(30);





How can Connect to the SQL Server and Run Commands in VB.Net & C# ?

If you have difficulty to connect to the SQL Server, read this post, it can help you to understand the fundamental:
First let me to explain the basic objects:
This objects contains SQL Connection String, other objects use this object to connect to the SQL Server
This object contains SQL Commands that will be run, it can carry SQL commands or Stored procedure name.
3. SqlDataAdapter
If you want to run Commands that return data (records), you should use this object, it can bring data from SQL Server to your application

now we are familiar with the basic objects that we need to connect to the SQL Server, let start to write the function that run the SQL command for us.


Private Sub ConnectToSQLServer()
            Dim SqlConnection As New Data.SqlClient.SqlConnection(
"Integrated Security=SSPI;Persist Security Info=False;Initial 
Catalog=Diet;Data Source=.\server2008")
            Dim SQLcommand As New Data.SqlClient.SqlCommand("SELECT * FROM Foods", SqlConnection)
            Dim SqlDataAdapter As New Data.SqlClient.SqlDataAdapter(SQLcommand)
            Dim DtResult As New DataTable
        Catch ex As Exception
            Throw ex.InnerException
        End Try
    End Sub

private void ConnectToSQLServer()
    try {
        System.Data.SqlClient.SqlConnection SqlConnection = new System.Data.SqlClient.SqlConnection
("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Diet;Data Source=.\\server2008");
        System.Data.SqlClient.SqlCommand SQLcommand = 
           new System.Data.SqlClient.SqlCommand("SELECT * FROM Foods", SqlConnection);
        System.Data.SqlClient.SqlDataAdapter SqlDataAdapter =
          new System.Data.SqlClient.SqlDataAdapter(SQLcommand);
        DataTable DtResult = new DataTable();
    } catch (Exception ex) {
        throw ex.InnerException;