How can authenticate user by their Google, Yahoo or OpenID accounts in MVC?

One of the major problem for websites users is that they have to create account for too many websites which they want to use, and it is hard to remember all accounts information. One the best solution is that users login to your website with another account that already have , same as Google , Microsoft , Facebook, Twitter and etc…

Today I am going to teach you how let users to connect to your website by these three accounts

  1. Google ( Gmail)
  2. Yahoo
  3. OpenId

Let start with making some changes in the AuthConfig.cs file, you can access to this file from the App_Start folder in application root, as you see here the code in the file is commented, we need to change it to this:

Before you change the code, should add these reference to the class,

using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.Web.WebPages.OAuth;
using MvcAuction.Models;

And your code should be like this :

public static class AuthConfig
        public static void RegisterAuth()


            var MyOpenIdClient =
new OpenIdClient("myopenid", WellKnownProviders.MyOpenId);
            OAuthWebSecurity.RegisterClient(MyOpenIdClient, "myOpenID", null);

You need these three critical functions to authenticate the users:
1. Offers the list of available providers.

public ActionResult Login()

            ViewBag.List = OAuthWebSecurity.RegisteredClientData;

           return View();


Here there is a sample code for View file, that shows you how retrieve data from above function and show them as list of button to users

 <form method="post" action="/AdminUsers/ExternalLogins" > 
    @foreach (AuthenticationClientData p in ViewBag.List)
            <button type="submit" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button>

2. When the user click on one of the buttons that you created for each provider, this function will be run and sends request to the provider :

 public void ExternalLogins(string Provider)


3. This function gets the result from provider and you can make appropriate decision Based on result:

  public ActionResult GetResult()
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication();
            return View();

As I said before , may the posts on MVC will not be clear or easy for those programmer that are new in MVC, therefore please feel free to contact me if you have any questions or leave comment here, good luck


How can bind a Dropdownlist in MVC and use selected value?

If you have been a ASP.Net programmer and now you decided to move to MVC this post can help you to find out how populate a Dropdownlist and how use selected value when the form is posted to the controller.

What is scenario?

I have this table in the database, as you see here, this table contains student’s information, I need a Dropdownlist in the form for list of available programs that user can select for each students.

Id int
Name nvarchar(50)
Family nvarchar(50)
Tel nvarchar(50)
Address nvarchar(50)
ProgramId int

In this function I created a list that contains program information (value, text), then I wanted to assign it to the DropDownlist:

public ActionResult Create()

            IEnumerable<SelectListItem> ProgramList= new[]

        new SelectListItem { Value = "1", Text = "bachelor" },
        new SelectListItem { Value = "2", Text = "Master" },
        new SelectListItem { Value = "3", Text = "PHD" },


           ViewBag.List = ProgramList;
            return View();

After that you need to make a view base on Student class, because we need to use ProgramId to post back a selected program’s Id and other student information to the controller that want to save data.
Here I just show you how to create a DropDownlist and I ignore other student’s fields:

<form method="post" action="students/create">
 @Html.DropDownListFor(model => model.ProgramId, new SelectList(ViewBag.List, "Value", "Text"))
  <input type="submit" />

I am sure that this post it is not clear for those programmer that are new in MVC , therefore if you need more help , just leave comment here then I will help you to improve your knowledge in MVC and also I can help you to find good reference to learn MVC 🙂

How can work with Dictionaries through VB.Net & C#?


What is Dictionaries ?

Dictionaries are collections that are meant to store lists of key/value pairs to allow lookup of values based on a key.

For example, assume that you needed to map student code to the full name of some students. For this purpose you can use the Hashtable.


 Private Sub CreateHashTable()
        Dim StudentCodes As New Hashtable()
        'The first method. 
        StudentCodes.Add("MN145098", "Mehran,Jn")
        'The second method.
        StudentCodes("MN18454") = "Arman,Nas"
    End Sub


private void CreateHashTable()
    Hashtable StudentCodes = new Hashtable();
    //The first method. 
    StudentCodes.Add("MN145098", "Mehran,Jn");
    //The second method.
    StudentCodes["MN18454"] = "Arman,Nas";

In this way you can read HashTable


  For Each Item As DictionaryEntry In StudentCodes


foreach (DictionaryEntry Item in StudentCodes) {

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][][];