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.

0 comments:

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

March 30, 2014 0 Comments

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

0 comments:

Difference between LINQ to XML and DOM Method

March 29, 2014 0 Comments

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.

0 comments:

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

March 28, 2014 0 Comments

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

0 comments:

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

March 27, 2014 , , , 0 Comments

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.

0 comments:

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

March 26, 2014 0 Comments

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

0 comments:

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

March 26, 2014 0 Comments

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#

0 comments:

Remove last element of array in C#

March 25, 2014 0 Comments

Using the Resize method you can decrement size of an array. Resize method creates a new array with new specified size Also copy old array items into newly created. Let's take an simple example to remove last element. Take less than one size of original array size. Newly created array skip last element of original array size.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Height="37px" onclick="Button1_Click"
        Text="Vegetable" Width="100px" />
    <div>
 
        <asp:Label ID="Label1" runat="server" Text="Label" Width="100px" ForeColor="Black" BackColor="Yellow"></asp:Label>
 
    </div>
    </form>

Business Logic code

 protected void Button1_Click(object sender, EventArgs e)
    {
        string[] Vegtables = new string[]
        {
            "1.Tomato",
            "2.Sweet-potato",
            "3.Onion",
            "4.Potato",
            "5.Carrot",
            "6.Locky",
            "7.Brinjal"
        };

        Label1.Text = "Vegtables array...<br />";
        foreach (string Vegtable in Vegtables)
        {
            Label1.Text += Vegtable + "<br />";
        }

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

        Label1.Text += "<br />Vegtables array [last element remove...<br />";
        foreach (string Vegtable in Vegtables)
        {
            Label1.Text += Vegtable + "<br />";
        }
    }

Code Generate the following Output


Resize array method

0 comments:

Print element of array at specific position in c#, LINQ subset array

March 25, 2014 0 Comments

Using the LINQ subset array you can print element of array at specific position through Skip( ) method. If you want to print array element at position number 3 then you should skip three starting index of array. Like
ArrayName .Skip(3).Take(2).ToArray( ) .

Source

<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1" runat="server" Height="33px" onclick="Button1_Click"
            Text="Button" Width="96px" />  
    </div>
    <p style="width: 118px">
        <asp:Label ID="Label1" runat="server" Height="40px" Text="Label" Width="100px"></asp:Label>
    </p>
    </form>

Business Logic Code

 protected void Button1_Click(object sender, EventArgs e)
    {
        string[] Vegetables = new string[]
        {
            "Tomato",
            "Potato",
            "Onion",
            "Carrot",
            "Sweet-Potato",
            "Locky"

        };

        Label1.Text = "Vegetables array...<br />";
        foreach (string Vegetable in Vegetables)
        {
            Label1.Text += Vegetable + "<br />";
        }
        string[] arraySubset = Vegetables.Skip(3).Take(2).ToArray();

        Label1.Text += "<br />Vegetables sub array [element after 3 and count 2]...<br />";
        foreach (string Vegetable in arraySubset)
        {
            Label1.Text += Vegetable + "<br />";
        }

Print element of array at specific position in c#, LINQ subset array

0 comments:

Insertion sort and let us consider an array of size 10 for Data Structure in 'C'

March 25, 2014 0 Comments

Insertion sort: 

                 In this technique of sorting, the fact of inserting the pivotal element  at its proper position from n (size of the array) number of elements is used. The pivotal element to be inserted is picked from the array itself. The selected pivotal element is inserted at the position from the left part of the array that is treated as sorted.
                   Initially the first element of the array is treated as left part of the array and being one element that is treated as sorted part of the array. The first pivotal element that is selected for insertion is the second element of the array. the pivotal element is compared with the first element and if the first element is greater than the pivotal element, then it is moved to the second position. Now we remain with no elements compared to be compared in the left part, the position where the pivotal element is found as the first position. The pivotal element is inserted at the first position to over the pass. If the first element is not greater than the pivotal element then the position of the pivotal element is right and remains at the same place. After the first pass the left part of the array containing two elements is in sorted order.
                 In the further passes the element of the unsorted part of the array is selected as pivotal element and a position to insert it in the sorted part (left array) of the array is found by shifting the sorted elements to the right if required. So after every pass the pivotal element is inserted at its proper position in the array. As the insertion operation is being performed to insert the pivotal element, this technique of sorting the array is called as ‘’insertion sort’’.

 Let us consider an array of size 10 with the following elements:

                              91 18 22 43 34 10 88 11 33 77

We can observe the elements and see that the elements are not in any order. So to arrange the elements in ascending order we can apply the insertion sort.
In the first pass, we select the element 18 is pivotal element. The left part of the of the array before the pivotal element contains only one element and it is the sorted part of the array. 18 is compared with 91,91 is greater than 18. So, 91 is shifted to the right by one position. Now there are no elements to be compared in the sorted part of the array with the pivotal element. Now the pivotal element is inserted at first position of the array. After this pass the array looks as follows: [sorted elements-BOLD, pivotal element – underlined].
                                    18 91 22 43 34 10 88 11 33 77
In the second pass, 22 is selected as pivotal element. 22 is compared with 91, as 91 is greater then 22, 91 is shifted towards its right by one position. Again 22 is compared with 18,18 is not greater then the pivotal element 22. So, the comparison is stopped because the position where the pivotal element 22 is to be inserted is found. The pivotal element 22 is inserted at second position. After this pass the array looks as follows:
                                     18 22 91 43 34 10 88 11 33 77
In the third pass, 43 is selected as pivotal element from the unsorted part of the array. 43 is compared with 91 and  91 is shifted towards its right by one position. 43 is again compared with 22. 22 is not greater then 43 and comparison is stops. 43 is inserted at third element of array.  After this pass the array looks as follows:
                                     18 22 43 91 34 10 88 11 33 77
In the fourth pass, 34 is selected as pivotal element from the unsorted part of the array. 34 is compared with 91 and 91 is shifted towards its right by one position. 34 is again compared with 43. 43 is also right shifted by one position. 34 is now comparison with 22. 22 is not greater then 34 and comparison stops. 34 is inserted at third element of array.  After this pass the array looks as follows:
                                     18 22 34 43 91 10 88 11 33 77
In the fifth pass, 10 is selected as pivotal element from the unsorted part of the array. As 10 smaller then all the sorted elements of the left part of the array, each element is shifted to right by one position respectively. 10 is inserted as the first element of array.  After this pass the array looks as follows:
                                     10 18 22 34 43 91 88 11 33 77
In the sixth pass, 88 is selected as pivotal element from the unsorted part of the array. 88 is compared with 91 and  91 is shifted towards its right by one position because it is greater then 88. 88 is now compared with 43. and comparison is stops. 88 is inserted at sixth element of array.  After this pass the array looks as follows:
                                     10 18 22 34 43 88 91 11 33 77
In the seventh pass, 11 is selected as pivotal element from the unsorted part of the array. 11 is compared with all the element up to 18 and they are  shifted to right by one position respectively. The comparison is stops when 11 is compared with 10. So, 11 is inserted at second element of the array.  After this pass the array looks as follows:
                                     10 11 18 22 34 43 88 91 33 77
In the eighth pass, 33 is selected as pivotal element from the unsorted part of the array. 33 is compared with all the element up to 34 and they are  shifted to right by one position respectively. The comparison is stops when 33 is compared with 22. So, 33 is inserted at fifth element of the array.  After this pass the array looks as follows:
                                     10 11 18 22 33 34 43 88 91 77
In the ninth and final pass, 77 is selected as pivotal element from the unsorted part of the array. 77 is compared with 91 and 88 and they are shifted to right by one position respectively. The comparison is stops when 77 is compared with 43. So, 77 is inserted at eighth element of the array.  After this pass the array looks as follows:
                                     10 11 18 22 33 34 43 77 88 91 

0 comments:

Change Header border style as dotted of Gridview in ASP.NET

March 25, 2014 0 Comments

Make border dotted of GridView header row using BorderStyle property using property window. This style enumeration is applies on compile time. First bind Gridview with SqlDataSource control , after that make some changes in style properties. This example cover dotted border style. Some steps are:

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Add Gridview control on design window.
Step-4 : Bind Gridview with SqlDataSource control, make changes in border style

Example of Headerstyle BorderStyle of Gridview in asp.net


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno" 
                SortExpression="contactno" />
        </Columns>

 <HeaderStyle BorderStyle="Dotted" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)" 
        SelectCommand="SELECT * FROM [userdataTable]" 
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
    
    </div>
    </form>
</body>
</html>

Code Generate the following output


Example of Headerstyle BorderStyle of Gridview in asp.net

0 comments:

How to use LINQ to SQL in ASP.NET

March 25, 2014 0 Comments

INTRODUCTION

LINQ to SQL is a component of .NET Framework, and is specifically designed for working with SQL server database. It provides a run-time infrastructure for managing relational data as objects. It allows you to write queries to retrieve and manipulate data from the SQL server. LINQ to SQL supports all the key functions that you would expect while developing SQL applications. You can retrieve the data from the database, insert, update, and also delete the information from the table. Your query expression is translated into parameterized SQL code, parameters are created, and the query is executed on the server. LINQ to SQL also supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model.

LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. With the help of LINQ to SQL ORM mapping, the classes that match the database table are created automatically from the database itself and you can start using the classes immediately.

Let's take an simple Example

Step-1 : Add a LINQ to SQL class to the application 
Step-2 : Right-click the Solution name in the solution explorer and select Add New Item from The context menu. This will open the Add New Item dialog box.
Step-3 : In the dialog box, select LINQ to SQL Classes and rename the file as my.dbml. Default name for LINQ to SQL class is DataClasses.dbml

LINQ to SQL Class in asp.net

Step-4 : Click Add

The object Relational Designer window opens. In this window, you can drag and drop the table from the server Explorer. The action will add the table to your application, and you can retrieve any data from the table. In this case, the products table from the database is added to the object Relational Designer window, 
After you have added the table to the my.dbml file, you can find the code for the .aspx in the listing

Add database table into dbml file

Source code
<form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" Height="97px" Width="98px"></asp:ListBox> 
    </div>
    </form>
Code Behind Code
protected void Page_Load(object sender, EventArgs e)
    {
        myDataContext dc = new myDataContext();
        var query = dc.usertables;
        foreach (usertable  item in query)
        {
            ListBox1.Items.Add(item.id.ToString() + " " + item.name);
        }
    }

Code generate the following output

How to use LINQ to SQL in ASP.NET
If your .dbml name is my then your DataContext name is myDataContext. After adding the table into dbml file , your table name look in the dbml file. 

0 comments:

C program to sort 10 elements of an array and a list of 11 names in ascending order using selection sort technique

March 25, 2014 0 Comments

C program to sort 10 elements of an array in ascending order using selection sort technique.

#include<stdio.h>
#include<conio.h>
void se1_sort_ao(int arr[],int n)
{
  int i, j, min, mops;
  for(i=0;i<n-1;i++)
   {
    min = arr[i]; mpos = 1;
    for(j=i+1; j<n; j++)
    if(arr[j] < min)
      {
      min = arr[j]; mops = j;

      }
    arr[mpos] = arr[i];   arr[i] = min;
   }
}
main()
{
    int a[10], i;
    printf("Enter 10 element of the array:\n \n");
    for(i=0;i<10;i++)
      scanf("%d",&a[i]);
    printf("The array before sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
    sel_sort_ao(a,10);
    printf("\n \n The array after sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
}

C program to sort a list of 11 names in ascending order using selection sort technique.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void se1sortstrao(char a[][20],int n)
{
  int i, j, mops, k; char min[20];
  for(i=0;i<n-1;i++)
   {
    strcpy( min,a[i]); mpos=i;
    for(j=i+1; j<n; j++)
    if(strcmp(a[j],min)<0)
      {
       strcpy(min,a[j]);   mpos=j;

      }
    strcpy(a[mpos],a[i]);  strcpy(a[i],min);
   }
}
main()
{
    char a[11][20];
    int i;
    clrscr();
    printf("Enter List of 11 names:\n \n");
    for(i=0;i<11;i++)
    gets(a[i]);
    selsortstrao(a,11);
    clrscr();
    printf("The List after sorting:\n \n");
    for(i=0;i<11;i++)
    puts(a[i]);
}

0 comments:

'C' Function to implement 'selection sort' in ascending and descending order

March 24, 2014 0 Comments

‘C’ function to implement ‘selection sort’ in ascending order.


void se1_sort_ao(int arr[],int n)
{
    int i, j, min, mpos;
    for(i=0;i<n-1;i++)
    {
    min = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of min element */
     if(arr[j] < min)
     {
      min = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing min element */
    arr[i] = min;
    }    
}

‘C’ function to implement ‘selection sort’ in descending order.

void se1_sort_ao(int arr[],int n)
{
    int i, j, max, mpos;
    for(i=0;i<n-1;i++)
    {
    max = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of max element */
     if(arr[j] > max)
     {
      max = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing max element */
    arr[i] = max;
    }    
}

0 comments:

Algorithm to implement selection sort ascending and descending order

March 24, 2014 0 Comments

Algorithm to implement selection sort (ascending order):


SELECTIONSORTAO(arr,n)
Repeat For I =1 to n-1                [n-1 passes]
MIN <-- arr[I]
POS <-- I
Repeat for J=I+1 to n  [to select minimum element]
  If arr[J]< MIN Then:
     MIN <-- arr[J]
     POS <-- J
  [ End of if ]
 [ End of for J ]
 arr[pos] <-- arr[I]
 arr[I] <-- MIN
[End of For I ]
Exit.  

Algorithm to implement selection sort (descending order):

 SELECTIONSORTDO(arr,n)
[‘arr’ is an array of n elements]
Repeat For I =1 to n-1            
  MAX <-- arr[I]; POS <-- I
 Repeat for J=I+1 to n
   If arr[J]>MAX Then:
       MAX <-- arr[J];  POS <-- J
    [ End of if ]
   [ End of for J ]
   arr[pos] <-- arr[I];  arr[I] <-- MAX
[End of For I ]
Exit.  


0 comments:

How to use LINQ projection Operators in ASP.NET

March 24, 2014 0 Comments

Introduction

Projection operators are used to transform an object into a new object of a different type. By using the Projection operators, you can construct a new object of a different type that is built from each object. The Select and SelectMany clauses are the Projection operators used in LINQ.
The Select operator performs a projection over a sequence and projects the value that is based on a transform function. The Select operator in LINQ performs function just as the Select statement in SQL. The Select operator specifies which elements are to be retrieved. For example, you can use the Select clause to project the first letter from each string in a list of strings. The syntax of using the Select clause is:

C#
public static lEnumerable<S> Select<T, S>( this IEnumerable<T> source, Function<T, S> selector);

The second type of Projection operator used in LINQ is the SelectMany operator. The SelectMany operator projects a sequence of values that are based on a transform function and then organize them into one sequence. The syntax of using the SelectMany clause is:
C#
public static IEnumerable<S> SeIectMany<T, S>( this IEnumerable<T> source, Function<T, IEnumerable<S»selector);

You must be wondering about the difference between the Select and SelectMany operators. The Select and
SelectMany operators are both used to produce a result value from a source of values. The difference lies in
the result value. The Select operator is used to produce one result value for every source value. The result
value is a collection that has the same number of elements from the query.
In contrast, the SelectMany operator produces a single result that contains a concatenated collection from the query.

Let's take an simple example of SelectMany Clause

Source view
  <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Select Many Clause" 
            onclick="Button1_Click" />
        <br />
    </div>
    <asp:ListBox ID="ListBox1" runat="server" Height="169px" Width="108px">
    </asp:ListBox>
    </form>
Code Behind View
 protected void Button1_Click(object sender, EventArgs e)
    {
        string[] mytext = new string[] { "Hello world", " this is simple", "example of projection operator" };
        IEnumerable<string[]> myword = mytext.Select(x => x.Split(' '));
        foreach (string[] item in myword)
            foreach (string wr in item)
                ListBox1.Items.Add(wr);
            
        
    }
Code Generate the Following Output
How to use LINQ projection Operators in ASP.NET

0 comments:

How to make custom password change control in asp.net

March 24, 2014 0 Comments

Introduction

This control is designed for authenticated user, he/she can change own profile password. Basically, it have three fields, such as old password field, New password field, and retype password field. Looking like

If your old password doesn't match with stored data then new password will not update. Id password match with stored data then your new password will be updated.

Algorithm behind the program 

Step-1 : First of all match your old password with table data using user_id, which is unique. For that, we will create a SELECT query.
Step-2 : Result of Select Query match with Text Box, which is defined for old password.
Step-3 : If Your inputted password is matched with fetched data, which is fetched from select query.
Step-4 : Design update query and will change your old password with new one.

Programming code

Step-1 : Create connection from SqlEngine using SqlConnection class, which is inside in System. Data. SqlClient namespace.

SqlConnection con;
 con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();


Step-2 : After establishing connection, check data which is inside in database table. Check data using SqlDataReader , if data is already exist in table, will not  update new password with old. If doesn't exist data in table , update database table

private void checkold()
    {
        con.Open();
        cmd.CommandText = "select * from Register";
        cmd.Connection = con;
        rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            if (rd["Password"].ToString() == oldpwd.Text && rd["Email"].ToString() == Session["email"].ToString ())
            {
                flag = false;
                break;
            }

        }
        if (flag == false)
        {
            con.Close();
            updatepassword();
        }
        else
        {
            Label1.Text = "Password doesn't match";
            Label1.ForeColor = System.Drawing.Color.Red;            
        }
    } 


Step-3 : Update database table with new one password

private void updatepassword()
    {
        con.Open();
        cmd.CommandText = "update register set Password=@pass where email=@em";
        cmd.Parameters.AddWithValue("@pass", pass.Text);
        cmd.Parameters.AddWithValue("@em", Session["email"].ToString());
        cmd.Connection = con;
        int update = cmd.ExecuteNonQuery();
        if (update >0)
        {
            Label1.Text = "Password Update";
            Label1.ForeColor = System.Drawing.Color.Green; 
        }
        else
        {

            Label1.Text = "Error";
            Label1.ForeColor = System.Drawing.Color.Yellow; 
          
        }
    }

Code Generate the following output

How to make custom password change control in asp.net

How to make custom password change control in asp.net

0 comments: