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()
        {

            OAuthWebSecurity.RegisterGoogleClient();
            OAuthWebSecurity.RegisterYahooClient();

            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" > 
        <p> 
    @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>
        }
        </p>
</form>

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)
         {
             OAuthWebSecurity.RequestAuthentication(Provider,"/home/GetResult");

         }

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" />
  </form>

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 we learn MVC easily?

How can we learn MVC easily?

“How can we learn MVC? “ Is the major problem for those Web Developers who want to move from ASP.Net to the MVC, Today I want to introduce one of the good sources for learning MVC,http://mvcmusicstore.codeplex.com/

Music-store is an open source project with a learning PDF which you can download it here. I hope it can help you if you want learn MVC.

 

How to use OFFSET and FETCH NEXT ROWS in SQL Server 2012?

sql2008

--SQL Server 2012
WITH CTE_SoldProduct
AS
(
SELECT SUM(Quantity) QNT,ProductID FROM dbo.TBL_Sales
GROUP BY ProductID
)

SELECT 
      P.NAME 
      ,P.Price
      ,SP.QNT
    FROM CTE_SoldProduct SP
    INNER JOIN dbo.TBL_Product p ON SP.ProductID = p.ID
ORDER BY SP.QNT DESC
offset 1 rows FETCH NEXT 2 ROWS ONLY;

--SQL Server 2008
 WITH CTE_SoldProduct
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY SUM(Quantity) DESC) AS num, SUM(Quantity) QNT,ProductID FROM dbo.TBL_Sales
GROUP BY ProductID
)

SELECT 
      P.NAME 
      ,P.Price
      ,SP.QNT
    FROM CTE_SoldProduct SP
    INNER JOIN dbo.TBL_Product p ON SP.ProductID = p.ID
WHERE num >=2

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

ms_visual_studio

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.

[VB.Net]

 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

[C#]

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

[VB.Net]

  For Each Item As DictionaryEntry In StudentCodes
            Console.WriteLine(Item.Value)
        Next

[C#]

foreach (DictionaryEntry Item in StudentCodes) {
    Console.WriteLine(Item.Value);
}

How Can write a DataSet as XML through VB.Net & C#?

XMLToday I am going to talk about XML again, today we learn how to make XML from a Dataset.

There are 3 different methods that you can chose, but before producing a XML file or XML Content we need to produce a Dataset.

[VB.Net]

  Private Sub MakeDataSet()
        Dim ds As New DataSet()
        Dim OConnString As String = "Server=CodingTips;Database=_
                                   Library;" + _
                                   "Integrated Security=true;"

        Using conn As New SqlConnection(OConnString)
            Using cmd As SqlCommand = conn.CreateCommand()

                cmd.CommandText = "SELECT * FROM Books;"
                Dim Oda As New SqlDataAdapter(cmd)
                Oda.Fill(ds)
            End Using
        End Using
    End Sub

[C#]

private void MakeDataSet()
{
    DataSet ds = new DataSet();
    string OConnString = "Server=CodingTips;Database=Library;" + _
"Integrated Security=true;";

    using (SqlConnection conn = new SqlConnection(OConnString)) {
        using (SqlCommand cmd = conn.CreateCommand()) {

            cmd.CommandText = "SELECT * FROM Books;";
            SqlDataAdapter Oda = new SqlDataAdapter(cmd);
            Oda.Fill(ds);
        }
    }
}

Now you are ready to produce XML File,follow these three different methods.
1. Write XML directly in the film

[VB.Net]

ds.WriteXml("c:/CodingTips.xml")

[C#]

ds.WriteXml("c:/CodingTips.xml")

2.The second method is GetXml , the result of this method is String but it does not support any of the advanced features of the XML serialization

[VB.Net]

Dim strxml as string = ds.GetXml()

[C#]

string strxml = ds.GetXml();

3.Sometimes you want to use all advanced features of the XML serialization but you don’t want to save the file, in this case you can use this solution.

[VB.Net]

Dim strm As New MemoryStream()
ds.WriteXml(strm)

[C#]

MemoryStream strm = new MemoryStream();
ds.WriteXml(strm);

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:

[VB.Net]

Imports System.IO
Imports System.Xml.Serialization

[C#]

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

[VB.Net]

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

[C#]

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

How can make SAH1 through VB.Net & C#

Security

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:

[VB.Net]

 Private Sub EncryptData()
    Dim strToHash As String = "Please Encrypt me !"
    Dim Result As String = ""
    Dim OSha1 As New _
    System.Security.Cryptography.SHA1CryptoServiceProvider

    '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")
     Next
    End Sub

[C#]

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

    //Step 1
    byte[] bytesToHash = _
    System.Text.Encoding.ASCII.GetBytes(strToHash);

    //Step 2
    bytesToHash =_
    OSha1.ComputeHash(bytesToHash);

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

Cursor in SQL Server

sql2008

SQL Server Cursor is a row base operator but it does not have good performance

because it create different execution plan per each rows, personality

I do not like use this operator so always I look for standards operators same as JOIN,SELECT,GROUP,…

and Loop operators instead of cursor.

By the way few times the cursor is useful;

please pay attention to below example:

Simple Sample:

USE Arm_DB 
GO

DECLARE @ProductID INT
DECLARE @ProductName NVARCHAR(50)
DECLARE @ProductPrice DECIMAL(10,2)

DECLARE Product_Cursor CURSOR FOR 
                                SELECT ID,NAME,Price 
                                    FROM dbo.TBL_Product

OPEN Product_Cursor FETCH FROM Product_Cursor INTO  @ProductID
                                                   ,@ProductName
                                                   ,@ProductPrice
    WHILE @@FETCH_STATUS = 0
    BEGIN

        SELECT @ProductName ProductName
             ,SUM(Quantity)*@ProductPrice AS TotalSales 
            FROM dbo.TBL_Sales
            WHERE ProductID = @ProductID

        FETCH FROM Product_Cursor INTO @ProductID
                                      ,@ProductName
                                      ,@ProductPrice  
    END      
CLOSE Product_Cursor
DEALLOCATE Product_Cursor

Optimal Option: Use JOIN and GROUP BY instead of CURSOR

SELECT 
      P.NAME AS ProductName 
     ,SUM(S.Quantity) * P.Price AS TotalSales
 FROM dbo.TBL_Sales S
  INNER JOIN dbo.TBL_Product P ON S.ProductID = P.ID
GROUP BY P.NAME,P.Price

Useful sample: Get Backup from all user’s databases in SQL Server instance

USE Master 
Go

DECLARE @Path NVARCHAR(600) = 'C:\Arman\Mine\MyBlog\CodingTips\DBbackup\'
DECLARE @FileDate NVARCHAR(50) = CONVERT(NVARCHAR,GETDATE(),112)
DECLARE @DBname NVARCHAR(50) = ''
DECLARE @FileName NVARCHAR(1000) = ''

DECLARE DB_Cursor CURSOR For 
                            SELECT name 
                            FROM sys.databases  
                            WHERE database_id > 4 --Start From User Database

OPEN  DB_Cursor FETCH NEXT FROM DB_Cursor INTO @DBname
     WHILE @@FETCH_STATUS = 0
      BEGIN

        SET @FileName = @Path + @DBname + '_' + @FileDate + '.Bak'    
        BACKUP DATABASE @DBName TO DISK = @FileName    
        FETCH NEXT FROM DB_Cursor INTO @DBname         
      END 
CLOSE DB_Cursor
DEALLOCATE DB_Cursor

How to create table in SQL Server

sql2008

USE Arm_DB
Go

 IF (OBJECT_ID('TBL_Product','U') IS NOT NULL)
   DROP TABLE TBL_Product

Go

CREATE TABLE TBL_Product
(
ID INT IDENTITY(1,1)
,NAME NVARCHAR(50)
,Price DECIMAL(10,2)
,[Desc] NVARCHAR(MAX)
,InsertedDate DATETIME DEFAULT SYSDATETIME()
,MOdifiedDate DATETIME DEFAULT SYSDATETIME()
CONSTRAINT PK_TBL_Product PRIMARY KEY (ID)
)

GO 

 IF (OBJECT_ID('TBL_Sales','U')IS NOT NULL )
    DROP TABLE TBL_Sales

CREATE TABLE TBL_Sales
(
ID INT IDENTITY(1,1)
,ProductID INT 
,Quantity INT
,SalesDate DATETIME
,InsertedDate DATETIME DEFAULT SYSDATETIME()
,ModifiedDate DATETIME DEFAULT SYSDATETIME()
CONSTRAINT PK_TB_Sales PRIMARY KEY (ID)
CONSTRAINT FK_TBL_Sales_TBL_Product 
     FOREIGN KEY (ProductID) REFERENCES dbo.TBL_Product(ID)
)

GO

INSERT dbo.TBL_Product   ( NAME ,Price )
SELECT 'Book',32.4
UNION ALL
SELECT 'Pen',5.2
UNION ALL
SELECT 'Notebook',8.7

Go

INSERT INTO dbo.TBL_Sales( ProductID , Quantity ,SalesDate)
SELECT 1,4,'2013-Apr-10'
UNION ALL
SELECT 1,3,'2013-Apr-11'
UNION ALL
SELECT 1,8,'2013-Apr-13'
UNION ALL
SELECT 1,1,'2013-Apr-18'
UNION ALL
SELECT 2,4,'2013-Apr-10'
UNION ALL
SELECT 2,3,'2013-Apr-11'
UNION ALL
SELECT 2,8,'2013-Apr-13'
UNION ALL
SELECT 2,1,'2013-Apr-18'
UNION ALL
SELECT 3,4,'2013-Apr-10'
UNION ALL
SELECT 3,5,'2013-Apr-11'
UNION ALL
SELECT 3,3,'2013-Apr-13'
UNION ALL
SELECT 3,9,'2013-Apr-18'

SELECT * FROM dbo.TBL_Product

SELECT * FROM dbo.TBL_Sales