What is NuGet and How does it work?

NuGet is a package-management system for .NET and Visual Studio. Take a look at this scenario:

You want to add JQuery library to your project, so you will follow these steps:

1. Go to www. JQuery.com and download the latest Version of JQuery.

2. Unzip the packages

3. Add it to your project

You should follow these 3 steps to add any free package to your project meanwhile, the most time it is not as easy as JQuery package. I am sure that you have faced with so many errors during adding packages and references to your project. The other important issue is that, how you can trust the packages, especially ZIP packages because they may contain viruses and marvels.

The other problem that will be happened after adding references is, how update these packages? How can find the latest version? How can replace it with old version?

These are the problems that you may be faced during manual adding references. NuGet has solved the problems. NuGet is a places that you could find the latest free packages and add them to your project or get the latest update for current references.

For those who use Visual Studio 2010:

By default the 2010 version of visual studio does not support the NuGet, so first you should  install the NuGet extension, please follow these steps:

  1. Select tools menu
  2. Select Extension manager
  3. In the Extension manager page , search NuGet and the download it ( take a look at following screen shut)


Let start Using NuGet to add JQuery to your project:

  1. In the solution Explorer panel right click on your References and select Manage NuGet Packages.
  2. In the Mange NuGet Packages first click on the online (left panel) then type the JQuery on the search box (right panel) after some seconds you will see the list of items that is related to your search (middle panel). Select JQuery and press Install button.

The latest JQuery is downloaded and added to your project.in the next post I will teach you how to update your current references via NuGet.


What is Routing In MVC and how does it work ?

Hello everybody , Today I am going to talk about MVC-routing , if you are a ASP.net developer , you know that how it is easy in ASP.net to make a page as a startup page, just you need to right click on a page and choose “Set as start page”. But the story in MVC is totally different because, you cannot access pages directly, you can just access and call methods, YES IT IS!!! It means the first page of your project that will be displayed after running the project is a view page that is made for a function. But you cannot start view directly, you should call the function.


Take a look at the above URL, it has three parts

  1. www.mysample-mvc.com(domain)
  2. Home ( name of controller)
  3. Index ( name of function)

As you see I do not mention any page in URL address, just I mention controller and function name, but in ASP.net you should mention the name of page same as this example:


Now the question is that how we can change the startup page. For this purpose please expand App-Start folder (kindly find it in main root of your project) and the open RouteConfig.vb, You will see this code there:

 public static void RegisterRoutes(RouteCollection routes)

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new
 { controller = "Home", 
action = "Index", id = UrlParameter.Optional }

Please take a look at URL section it is look like this:

 url: "{controller}/{action}/{id}",

This part tell the system that all URLs should have three parts

  1. Controller ( name of controller )
  2. Action( name of function that you want to be run )
  3. Id ( parameters that will be passed to the function)

You may ask if your function does not have any parameter, why you have to pass ID. You are right if the function does not have any parameter you do not need to pass any Id or parameter because we will consider it in the next line of code:

defaults: new { controller = "Home", action = "Index", 
id = UrlParameter.Optional }

As you see URL is an optional parameter not mandatory.

Now everything is ready for you to change the startup page of your project, you just need to change the name of controller and action (function) in this line of code as you want:

  defaults: new { controller = "Home", 
action = "Index", 
id = UrlParameter.Optional }

How can make custome validation in MVC?

As you know there are lots of default validators in MVC same as Range, Requires and etc… But you may need to create your own validators for special purpose. Today I will show you how to create your own validator.

Let start, I want to make a validator that checks the string input and if the string contains these two characters “(“, “)”, shows an appropriate message to the user.

First you need to make a class that inherits from the ValidationAttribute and then overwrite the functions :

namespace System.ComponentModel.DataAnnotations

   public class CheckContentAttribute : ValidationAttribute
public CheckContentAttribute()
:base("{0} Check you input sting , it should not contain these
 two charachters : '(' and ')'")

protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
    if (value != null)
        var valueAsString = value.ToString();
       if (valueAsString.Contains("(")  ||valueAsString.Contains(")"))
            var errorMessage = FormatErrorMessage(
            return new ValidationResult(errorMessage);
    return ValidationResult.Success;

And now you can use this validator :

 public class Info_AdminUsers
        public int Id { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }


See it is much more easier than you thought , Am I right?

How can prevent Open Redirection attack in MVC ?

What is Open Redirection attack?

When redirection URL passed to the function as parameter in the URL, the Open Redirection attack could be happened. For example the user attempts to open a page in your website but he is redirected to the Login page because this page is just available for the website users. You may ask where the problem is? Please take a look at this two example:(These links are just sample, they do not work !)

1. http://www.codingtips.net/Account/login?ReturnUrl=/Home/Index

2. http://www.codingtips.net/Account/login?ReturnUrl=www.UnknownSite.com

The first address, redirects users to the Home/Index after successful Login but the second address redirects users to the Unknown website, it means the second address is manipulated by the hackers. Let me show you how can prevent this Open Redirection Attack.

private ActionResult Redirect(string returnUrl)
            if (Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
                return RedirectToAction("Index", "Home");

This function checks the Return URL if finds that the Return URL wants to redirect users to the outside of the site, it changes Return URL to the Home/Index. It is strongly recommended to use this function if you want pass Return URL as parameter in URL.

How can prevent Cross-Site Request Forgery in MVC? Part 1

What is Cross-site request?

wikipedia: is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. more info click here

You have a Logout function in AccountController that users use it to exit from the site. Now assume you have a forum in your site and user should login to your forum to post comments or read them, one of the ability in your forum is that users can upload an image now a devil user upload an image in this way with malicious content:

<img src="/account/logout" />

From now on, each user that visit this page, automatically sign-out from the site, because the Logout function is run automatically by the page.

Token Verification:

You can use token verification to prevent this attach, first you should use @Html.AntiForgeryToken() inside the Form Tag that you want to submit or you want to post to the controller :

<form action="/account/logout" method="post">

Then you should put [ValidateAntiforgeryToken] above the function that is called by the submit button from the view file.

public ActionResult logout
//put your code here

How it works?
@Html.AntiForgeryToken() generates a code like this:

<input type="hidden" value="012837udny31w90hjhf7u">

The value of the Token will be compared before running the function that uses [ValidateAntiforgeryToken], if both values will be same the function will be fire, by this method if the function is called from other places or by malicious code it won’t be run.

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 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 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 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.


  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)
            End Using
        End Using
    End Sub


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);

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





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


Dim strxml as string = ds.GetXml()


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.


Dim strm As New MemoryStream()


MemoryStream strm = new MemoryStream();