-->

Monday, March 31, 2014

How to Implement Server Side Validation in Asp.Net MVC

Server side validation can be performed by submitting the model and then check the values in related action of the controller. Asp.Net MVC framework populates a ModelState object with any validation failure and passes that object to controller. If any error found just add the error in the state of model by using ModelState object of type ModelStateDictionary.

According to our previous article about client side validation, programmer have to change some minor changes in the view as well as controller’s action. Just write the following code in our GetValues view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
            @Html.ValidationMessage("nameError")
        </div>
        <input type="submit" value="Send" />
    </div>
}

Here I have added a validation message having the key "nameError" to show the validation message for username. The message passed with this key will be shown through this line of code. Programmer have to change the action code according to this view code and it should be look like:

[HttpPost]
public ActionResult GetValues(string username)
{
if (username == string.Empty)
{
ModelState.AddModelError("nameError", "Name must not be empty");
}
return View();
}

As you can see the condition I have placed that it will only check whether the textbox is empty. If username will be passed empty then it will just add an error message having the same key written in the view code, by using the code written in if block.

Run the MVC application the leave black the textbox, click on send button. It will go to the action, check the condition and then return the view after adding the error. The page will be look like:

How to Implement Server Side Validation in Asp.Net MVC

So this is how to perform server side validation and client side validation in MVC. In further articles we will understand more about these.

Sunday, March 30, 2014

Save Password using Encoding, decoding and Hashing Techniques in ASP.NET

Introduction

Plain text change in unreadable format known as encoding. And reverse of it known as decoding. Change a plain text into cipher text using any key known as hashing. There are lots of techniques available in hashing.
Here we take a simple example of among. First we start from Encoding.


How to change plain text into cipher text (Unreadable format)

first of all, take a string variable, after that take a byte array, which size is equal to string Length. Look like

String str = "Hello World";
Byte [] encode = new Byte[str.Length];

Get Bytes of string value using getBytes( ) method of UTF8 encoding. Now, your code look like

encode = Encoding.UTF8.GetBytes(str);
Now, change encoded byte array into Base64String.

encodepwd = Convert.ToBase64String(encode); // here encodepwd is the string variable.
Store encoded password is stored in encodepwd variable.

How to Change cipher Text into Plain Text

First of all, encoded string convert into specified string format, which is equivalent 8-bit unsigned integer array using FromBase64String ( ) method. count number of characters using GetCharCount( ) of byte array like.
 byte[] todecode = Convert.FromBase64String(decryptpwd);
 int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
Decode sequence of byte into set of characters using GetChars( ) method.

 char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

Complete source code

 <form id="form1" runat="server">
    <div>
    
        <table style="width:100%;">
            <tr>
                <td class="style1">
                    UserName</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" Caption="Encrypted Data">
    </asp:GridView>
    <br />
    <asp:GridView ID="GridView2" runat="server" Caption="Decrypted Data" 
        onrowdatabound="GridView2_RowDataBound">
    </asp:GridView>
    <br />
    </form>

Business Logic Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
            bindgridview2();
            
        }

    }

    private void bindgridview2()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView2.DataSource = ds;
        GridView2.DataBind();
      
    }

    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = encodepassword(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
        bindgridview2();


    }

    private string encodepassword(string p)
    {
        string encodepwd = string.Empty;
        byte[] encode = new byte[p.Length];
        encode = Encoding.UTF8.GetBytes(p);
        encodepwd = Convert.ToBase64String(encode);
        return encodepwd;

    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row .RowType ==DataControlRowType .DataRow)
        {
            string decryptpwd = e.Row.Cells[2].Text;
            e.Row.Cells[2].Text = decryptpassword(decryptpwd);
        }
        
    }

    private string decryptpassword(string decryptpwd)
    {
        string decryptpass = string.Empty;
        UTF8Encoding encode = new UTF8Encoding();
        Decoder decode = encode.GetDecoder();
        byte[] todecode = Convert.FromBase64String(decryptpwd);
        int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
        char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

        decryptpass = new String(decode_array);
        return decryptpass;
       
    }
    
}

Code Generate the following output

Save Password using Encoding, decoding

MD5 Hashing Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
           
            
        }

    }
    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = getMd5Hash(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
     


    }

    private static string getMd5Hash(string p)
    {
        MD5 md5Hasher = MD5.Create();

       
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(p));

       
        StringBuilder sBuilder = new StringBuilder();

       
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

      
        return sBuilder.ToString();

    }
  
}

Code Generate the following output

hashed password

Saturday, March 29, 2014

Difference between LINQ to XML and DOM Method

XML Document Object Model (DOM) is the current predominant XML programming API. In XML DOM, you build an XML tree in the bottom up direction. The typical way to create an XML tree using DOM is to use Xml Document. LINQ to XML also supports the Xml Document approach for constructing an XML tree, but also supports an alternative approach, called the functional construction. The functional construction uses the XElement and XAttribute constructors to build an XML tree.

In LINQ to XML, you can directly work with XML elements and attributes. You can create XML elements without using a document object. It also loads the T: System.Xml .Linq.XElement object directly from an XML file. It also serializes the T: System". Xml. Linq. XElement object to a file or a stream. When you compare this with XML DOM, the XML document is used as a logical container for the XML tree. In XML DOM, the nodes, which also include the elements and attributes, are created in the context of an XML document. The use of XML DOM is also complex. For example, if you want to use an element across multiple documents, you must import the nodes across the documents. This kind of complexity is not included in LINQ to XML.

The use of LINQ to XML also simplifies the names and namespaces by eliminating the prerequisite to deal with namespace prefix completely. The use of XML DOM does not let you change the name of node. As a substitute, you have to create a new node and copy all the child nodes to it, which leads to losing the original child identity.
LINQ to XML supports whitespace more simply than XML DOM.

Friday, March 28, 2014

Remove first element from array , Example of List and Resize method

Introduction

If you want to remove first element from an array. First of all, fill array with some values.Create a list collection and fill it with array list. Remove first element using RemoveAt(0) method , here 0 is the first index of array. After remove, must resize array using Resize( )  method. Again pass resized list into array.

Source Code

    <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Animal" Width="100px"
        onclick="Button1_Click" ForeColor="Red" />
    <div>
   
        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="Yellow"
            BorderStyle="Solid" Font-Underline="True" ForeColor="Blue"></asp:Label>
   
    </div>
    </form>

CodeBehind Code

#region remove_first_index
    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] animal = new string[]
        {
            "Cow",
            "Monkey",
            "Black buffalo",
            "Donkey",
            "Yak"
        };

        Label1.Text = "animal array.........<br />";
        foreach (string s in animal)
        {
            Label1.Text += s + "<br />";
        }
        List<string> animallist = animal.ToList();
        animallist.RemoveAt(0);

        Array.Resize(ref animal, animal.Length - 1);

        for (int i = 0; i < animal.Length; i++)
        {
            animal[i] = animallist[i];
        }


        foreach (string s in animal)
        {
            Label1.Text += s + "<br />";
        }
    }
    #endregion

Code Generate the following output

Remove first element from array , Example of List and Resize method

Thursday, March 27, 2014

How to Implement Client-Side Validation in ASP.NET MVC

Implementing Client-Side Validation in an Asp.Net MVC application requires some app settings in the web.config file that must be true. These settings are used to enable two jquery i.e. jquery.validate.min.js and jquery.validate.unobtrusive.min.js in our project.

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

These setting are by default enabled in an MVC project so programmer just remember to check these lines if validation are not working at all. In Visual studio there is an in-built validation attribute mostly used in all the required fields.

[Required]
(Field to be required…..)

This attribute is defined in System.ComponentModel.DataAnnotations namespace and it is used to not complete the page submission if user don’t enter any value in the respective field. The error message shown is the standard message ("Required") by default, it can be changed by the programmer by using:

[Required (ErrorMessage = "This field is Required ")]
(Field to be required…..)

After doing the changes in model, in view page programmer have to write the element which shows the error for that specified field.

(Field to be entered)
@Html.ValidationMessageFor("the labda expression for the property")

Some more lines are used by Visual Studio to adds these references automatically on view. It adds following code snippet to the bottom of the view:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Run the respected view, don’t insert any value, click on submit then it will show the specified error without submitting the page. This is client validation, when this page submitted and then show errors, it will called server side validation discussed in the next article.

Wednesday, March 26, 2014

Example of array in c# , print array element at specified position

Introduction

It is a simple example of array in c#, You can print element of array using for loop. Also print array element at specific position or index number. Simple, lower bound initialized from some value, where you want to print array element. Let's take an simple example

Source code

    <form id="form1" runat="server">
    <div>
 
        <asp:Button ID="Button1" runat="server" Text="Button" Width="81px"
            onclick="Button1_Click" />
 
    </div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>

Business Logic Code

    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] fruits = new string[]
        {
            "papaya",
            "Apple",
            "Banana",
            "Grapes",
            "Orange",
            "Pine-apple",  
            "Mango"
        };

        Label1.Text = "fruits array elements.........<br />";
        for (int i = 0; i < fruits.Length; i++)
        {
            Label1.Text += fruits[i] + "<br />";
        }

        Label1.Text += "<br />fruits array elements [index size 1 to 5].........<br />";
        for (int i = 1; i <= 5; i++)
        {
            Label1.Text += fruits[i] + "<br />";
        }

        Label1.Text += "<br />fruits array elements [index size 3 to 5].........<br />";
        for (int i = 3; i <= 5; i++)
        {
            Label1.Text += fruits[i] + "<br />";
        }
 }

Code Generate the following output

Example of array in c# , print array element at specified position

Append, modify or Edit string in ASP.NET C#

Introduction

"A group of characters known as string", Like "Hello World!". If you want to change in it, use StringBuilder class, which is a mutable string class. Mutable means, if you want create an object with some character value, also want to change in it further , that is possible with same object. So here we take StringBuilder class for appending string.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
        Width="68px" BackColor="#FFFF66" />
    <div style="width: 88px">
 
        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="#FFCC66"
            BorderColor="#CC0000"></asp:Label> 
    </div>
    </form>

Business Logic Code

protected void Button1_Click(object sender, EventArgs e)
 
        {
            StringBuilder stringd = new System.Text.StringBuilder();
            stringd.AppendLine("those are string.");
            stringd.AppendLine(" [ ");
            stringd.Append('H');
            stringd.AppendLine(" ] ");
            stringd.AppendLine("those are another string");

            Label1.Text = stringd.ToString();
        }  

Code Generate the following Output

output show Append, modify or Edit string in ASP.NET C#
© Copyright 2013 Computer Programming | All Right Reserved