-->

Monday, March 24, 2014

How to make Register control in asp.net

Introduction

Design Register control for change unauthenticated user to authenticated user. It store user information in Database table permanently. Registration is the first stage of authentication. If you want to give membership to your website then you first design register control, Visual studio IDE  provide a in-built register control named as "CreateUserWizard".

How to Design Register Control

Need some controls, such as TextBox, Button, Label and validation etc. for design it. Let's go for design it in some steps. These are:

Step-1

First of all, Add Html table control on design window,Type 'username' Text in first cell of table. In second cell of table(first row and second column), Add TextBox control in it. Make some changes in TextBox property such as

Id of TextBox : usrname
ValidationGroup : rv

Now, Add RequiredField Validator control in third cell of table (first row and third column). Now, Set some properties of Requiredfield validator.

ErrorMessage : "UserName Must"
ControlToValidate : "usrname"
ForeColor: "Red"
Text : *

Step-2  

Similarly again, Add some other control on design window and also set properties using property window.
Now the complete code of source page is
   <div>
 
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
 
        UserName:
        <asp:TextBox ID="usrname" runat="server" Width="175px" ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="usrname" ErrorMessage="UserName Must" ForeColor="Red">*</asp:RequiredFieldValidator>

        <br />

        Password:&nbsp;
        <asp:TextBox ID="pwdtxt" runat="server" Width="175px" TextMode="Password" 
            ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="pwdtxt" Display="Dynamic" ErrorMessage="Password Must" 
            ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>
        <br />

        Re-Type:&nbsp;&nbsp;
        <asp:TextBox ID="repwdtxt" runat="server" Width="175px" TextMode="Password" 
            ValidationGroup="rv"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToCompare="pwdtxt" ControlToValidate="repwdtxt" Display="Dynamic" 
            ErrorMessage="Password doesn't match" ForeColor="Red" ValidationGroup="rv">*</asp:CompareValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
            ControlToValidate="repwdtxt" Display="Dynamic" 
            ErrorMessage="Retype Password Required" ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>

        <br />

        Email :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="emailtxt" runat="server" Width="175px" ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" 
            ControlToValidate="emailtxt" Display="Dynamic" ErrorMessage="Email Must" 
            ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
            ControlToValidate="emailtxt" Display="Dynamic" ErrorMessage="Email Required" 
            ForeColor="Red" 
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
            ValidationGroup="rv">*</asp:RegularExpressionValidator>
        <br />
        <br />

        <asp:Button ID="Button1" runat="server" Text="Register it" Width="114px" 
            ValidationGroup ="rv" onclick="Button1_Click" />
 
        <asp:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server" 
            ConfirmText="Are You sure You want to create an account" Enabled="True" TargetControlID="Button1">
        </asp:ConfirmButtonExtender>
 
        <br />
 
    </div>
    <asp:Label ID="Label1" runat="server"></asp:Label> 

Design view of your source code is:

Design view of register control


Design Business logic code on Button_click event

DOTNET provides a Namespace, such as System.Data.SqlClient, which connects front-end to back-end. This Namespace contains multiple classes such as SqlConnection, SqlCommand and etc.
Front-end can connect with back-end using SqlConnection class. First of all, we create an object for it.
We can access the Data member and member function of class with the help of that object. such as

Step-1

using System. Data. SqlClient;

// Create an instance of SqlConnection class
SqlConnection con = new SqlConnection( );

// Access connection string using con instance.

con. ConnectionString = " Connection String Parameter ";

// Initialize connection string with database parameter

Some ConnectionString parameters which passes inside the ConnectionString. like
Data Source : Server Name;
Database Name : Name of your Database;
User-name : Database user name;
Password :  Password of your Database

For example
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"

Step-2

Now, open the state of connection. Because state of connection close by default. So call open method from instance of SqlConnection class, such as

con.open( );

After making connection, you can access or delete data from Database table. CommandText property of SqlCommand class provide interface with Database table. You can access this property by instance of SqlCommand class, such as

Step-3

SqlCommand cmd = new SqlCommand( );
  cmd.CommandText = "select * from Register";
With the help of  this query,  we can access whole data of register table. If you want to access particular column from table, must include column name inside the query. Like

cmd. CommandText = "Select column-name from [Table-name]";

Step-4

Now, Connect SqlCommand class with Connection object using connection property of SqlCommand class.
cmd. Connection = con;

Step-5

After fetching the data from database table, Read must from SqlDataReader class, which is inside in System.Data.SqlClient Namespace. Like

SqlDataReader rd= cmd. ExecuteReader( ); 

Read all rows of Database table using Read ( ) method of SqlDataReader class. Also check data, which is inputted by unauthenticated user whether is already exist or not in Database table. If Exist then set dirty flag is false and break while loop.If inputted data does not exist in Database table, you can insert inoutted data into database table.

while (rd.Read ())
  {
    if (rd["UserName"].ToString () == usrname .Text || rd["Email"].ToString ()==emailtxt .Text)
  {
flag=false;
   rd.Close ();
     break;
     
  }
           
  }
    if (flag ==false)
  {
                    Label1 .Text ="User Name and Email already registred";
                    Label1 .ForeColor =System.Drawing.Color.Red;
       
     
  }
                else
                {
                    insertdata();

                }

Code Generate the following output

User Name and Email already registred

Step-6

Design Data insertion algorithm 

Step-1 : Repeat step I and II
Step-2 : Now, Create insertion query for Data insertion into database table. Your query look like this

cmd.CommandText = "insert into Register(UserName,Password,Email)values(@uname,@pass,@em)";

Step-3 : Add some Parameters using AddWithValue ( ) method of SqlParameter class.

cmd.Parameters .AddWithValue ("@uname",usrname.Text);
                cmd.Parameters .AddWithValue ("@pass",pwdtxt .Text);
                cmd.Parameters .AddWithValue ("@em",emailtxt .Text);

Step-4 : Now, call ExecuteNonQuery (); method of SqlCommand class for update rows of database table.
Step-5 :  If Rows is affected by ExecuteNonQuery (); method then it returns 1 bydefault.
How to make Register control in asp.net

The complete code Data Insertion

using System;
using System.Data.SqlClient;
using System.Configuration;

public partial class registerrcontrol : System.Web.UI.Page
{
    bool flag = true;
    public registerrcontrol()
    {

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString =ConfigurationManager.ConnectionStrings ["ConnectionString"].ToString ();
            con.Open ();
            using(SqlCommand cmd = new SqlCommand ())
{
                cmd.CommandText = "select * from Register";
                cmd.Connection =con;
                SqlDataReader rd=cmd.ExecuteReader ();
                while (rd.Read ())
{
                    if (rd["UserName"].ToString () == usrname .Text || rd["Email"].ToString ()==emailtxt .Text)
{
flag=false;
                        rd.Close ();
                        break;

 
}
        
}
                if (flag ==false)
{
                    Label1 .Text ="User Name and Email already registred";
                    Label1 .ForeColor =System.Drawing.Color.Red;
             


 
}
                else
                {
                    insertdata();

                }

 
}
        }

       
    }

    private void insertdata()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString =ConfigurationManager.ConnectionStrings ["ConnectionString"].ToString ();
            con.Open ();
            using(SqlCommand cmd = new SqlCommand ())
{
                cmd.CommandText = "insert into Register(UserName,Password,Email)values(@uname,@pass,@em)";
                cmd.Connection =con;
                cmd.Parameters .AddWithValue ("@uname",usrname.Text);
                cmd.Parameters .AddWithValue ("@pass",pwdtxt .Text);
                cmd.Parameters .AddWithValue ("@em",emailtxt .Text);
                
               cmd.Connection =con;
                int a= cmd.ExecuteNonQuery ();
                if (a>0)
{
                    Label1 .Text ="Data Inserted";
                    Label1 .ForeColor =System.Drawing.Color .Green ;
 
}
            }
        }
       
    }
}

Sunday, March 23, 2014

Reverse array item example in c#

Sorting means ," arranging items of array either in ascending or descending order, known as sorting. Here this example display reverse order of any array items. If you take string type then use Reverse method of Array.

Source code in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
        Width="100px" />
    <div style="width: 180px">
   
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   
    </div>
    </form>
</body>
</html>

Code behind code

    protected void Button1_Click(object sender, EventArgs e)  
    {
        string[] fruits = new string[]
        {
            "Red Apple",
            "Yellow Papaya",
            "Orang Orange"
        };

        int[] numbers = new int[] { 65,105,640,800};

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

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

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

        Array.Reverse(numbers);
        Label1.Text += "<br />numbers array elements [after reverse array elements].........<br />";
        for (int j = 0; j < numbers.Length; j++)
        {
            Label1.Text += numbers[j].ToString() + "<br />";
        }
    }  
 

Reverse array item example in c#

Example of Selection sort for Data Structure in 'C'

Selection sort:

            In this technique of sorting, the fact of selecting the minimum element from n (size of the array) number of elements is used. The selected minimum element is interchanged with the first element of the array. Then leaving the first element, the minimum element is again picked from the remaining n-1 elements and interchanged with the second element. The same process of selecting minimum element and interchanging it from the respective element is repeated to obtain the sorted array. In total n-1 passes are applied to obtain the sorted array. As we select the minimum element in every pass this technique of sorting the elements is called as Selection sort. Let us understand this technique with the help of an analytical example before going into the algorithm and C function. 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 order. So to arrange the elements in ascending order we can apply the selection sort. 

In the first pass, we select the minimum element from the 10 elements as 10 with index 6. Interchange the element 10 with the element 91 (first element of the array). After this pass the array looks as follows:
                 10 18 22 43 34 91 88 11 33 77
In the second pass, we select the minimum element from 9 elements leaving the first element (as it is already sorted) as 11 with index 8. Interchange the element 11 with 18 (second element of the array). After this pass the array looks as follows:
                  10 11 22 43 34 91 88 18 33 77
In the third pass, we select the minimum element from 8 elements leaving the first two elements (as they are already sorted) as 18 with index 8. Interchange the element 18 with 22 (third element of the array). After this pass the array looks as follows:
                   10 11 18 43 34 91 88 22 33 77
In the fourth pass, we select the minimum element from 7 elements leaving the first three elements (as they are already sorted) as 22 with index 8. Interchange the element 22 with 43 (fourth element of the array). After this pass the array looks as follows:
                     10 11 18 22 34 91 88 43 33 77
 In the fifth pass, we select the minimum element from 6 elements leaving the first four elements (as they are already sorted) as 33 with index 9. Interchange the element 33 with 34 (fifth element of the array). After this pass the array looks as follows:
                      10 11 18 22 33 91 88 43 34 77
In the six pass, we select the minimum element from 5 elements leaving the first five elements (as they are already sorted) as 34 with index 9. Interchange the element 34 with 91 (sixth element of the array). After this pass the array looks as follows:
                       10 11 18 22 33 34 88 43 91 77
In the seventh pass, we select the minimum element from 4 elements leaving the first six elements (as they are already sorted) as 43 with index 8. Interchange the element 43 with 88 (seventh element of the array). After this pass the array looks as follows:
                       10 11 18 22 33 34 43 88 91 77
In the eighth pass, we select the minimum element from 3 elements leaving the first seven elements (as they are already sorted) as 77 with index 10. Interchange the element 77 with 88 (eighth element of the array). After this pass the array looks as follows:
                        10 11 18 22 33 34 43 77 91 88
In the ninth pass, we select the minimum element from 2 elements leaving the first three elements (as they are already sorted) as 88 with index 10. Interchange the element 77 with 91 (ninth element of the array). After this pass the array looks as follows:
                         10 11 18 22 33 34 43 77 88 91
The ninth pass is the last pass. We can observe from the last pass that after that pass we remain with the largest element of the array and is placed at its proper place. That is why we require only n-1 in this case 9 passes to sort the array.

Elementary sorting and Selection sort for data structure in 'C'

Elementary sorting:

            As we have seen in the case of binary search that it is necessary to arrange the elements of the array in a particular order either in ascending or in descending order. So if the elements of the array are arranged in either ascending or descending order then such array is called as sorted array. The operation necessary to apply on the array to arrange the elements of the same in order is called as sorting. If the array elements are not stored order then we apply sorting operation to sort the array elements. the elementary sorting techniques that are used are Selection sort, Insertion sort, and bubble sort. Basically the sorting operation is applied to sort the elements in ascending order. Let us study the techniques to sort the elements of one-dimensional array in ascending order.

  Selection sort:

           In this technique of sorting, the fact of selecting the minimum element from n (size of the array) number of elements is used. The selected minimum element is interchanged with the first element of the array. Then leaving the first element, the minimum element is again picked from the remaining n-1 elements and interchanged with the second element. The same process of selecting minimum element and interchanging it from the respective element is repeated to obtain the sorted array. In total n-1 passes are applied to obtain the sorted array. As we select the minimum element in every pass this technique of sorting the elements is called as Selection sort. 

Saturday, March 22, 2014

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

In earlier article we have added an empty controller with an action named GetValues in Visual Studio 2013. That action is of type HttpGet and return a simple view having a textbox control only. In this article we will access that value in the same controller with of course an HttpPost type of action.

The first thing is to create an HttpPost type of action having the same name to access the value from the view. Write the following code in the Empty controller just below the previously written GetValues action that is of type HttpGet.

[HttpPost]
public ActionResult GetValues(string username)
{
ViewBag.insertedValue = username;
return View();
}
Check out the parameter name of this action, it have the same spelling our textbox have. I have just save that value in the ViewBag and return the same view. Now in the view page I have added a simple submit button the section to display the value of this ViewBag. Here is the code of view page:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
        </div>
        <input type="submit" value="Send" />
        <div>
            Accessed value: @ViewBag.insertedValue
        </div>
    </div>
}
Remaining code is as same as in earlier article, the change is only the submit button and a section to display the value. Now run this MVC application and write http://localhost:portNo/Empty/GetValues in the address bar of the browser and press enter.

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

At the last of image Accessed value:  is blank initially. Write anything in the textbox (here DotProgramming) and click on the Send button. It will go to the HttpPost action of this view i.e. written above with the value inserted and then save that value in ViewBag. Remember, we have return the view in post action so it will come back with the value inserted and write on the view page as shown.

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

The algorithms using recursion Ascending and Descending order array

We can rewrite both the algorithms using recursion:

Ascending order array:

BINSEARCH(arr, FIRST, LAST, key)
[‘arr’ is one-dimensional array of size ‘n’, key is element to search ]
[‘arr’ elements are stored in ascending order]
[FIRST is lower bound and LAST is upper bound of the array]
MID <--INTEGER((FIRST+LAST)/2)
If (arr[MID] = key) Then:
 Return 1[1for TRUE, successful search]
Else:
   If FIRST > LAST Then:
     BINSEARCH(arr, FIRST, MID-1, key)
    Else:
      BINSEARCH(arr, FIRST, MID+1, LAST,  key)
     [End of If]
  [End of If]
[End of if]
Exit.

Descending order array:

BINSEARCH(arr, FIRST, LAST, key)
[‘arr’ elements are stored in descending order]
[FIRST is lower bound and LAST is upper bound of the array]
MID <-- INTEGER((FIRST+LAST)/2)
If(arr[MID]= key) Then:
  Return 1[1 for TRUE, successful search]
Else:
  If FIRST>LAST Then:
    Return 0[0 for FALSE, unsuccessful search]
  Else:
     If arr[mid] > key Then:
        BINSEARCH(arr, MID+1,LAST,key)
      Else:
        BINSEARCH(arr, FIRST, MID+1, key)
       [End of If]
   [End of If]
[End of If]
Exit.
 

Create Custom View using an Empty Controller in VS 2013: MVC 4

In MVC4 application with Visual Studio 2013, we have added a student controller with its default CRUD actions/views including list, create, edit and details. In this article we will add an empty controller and create a new action with its associated view (having a form in it).

On the controller folder right click and add a new controller. After clicking on Add an Add Controller window will open opting some options shown in the following image:

Create Custom View using an Empty Controller in VS 2013: MVC 4

The first input is the name of controller, write Empty and in the Template option select Empty MVC
Controller and click on “Add”. It will add a new empty controller with a single action i.e. Index having a single line of code, delete this code and create a new action with that single line of code as shown:

public class EmptyController : Controller
{
public ActionResult GetValues()
{
return View();
}
}
Right click on GetValues text and select Add View option, it will show an Add View window with some of the options to be selected by the programmer. Just select only master file if not selected and leave all remaining options as they are. Those options are not usable now, we will discuss them later.

Create Custom View using an Empty Controller in VS 2013: MVC 4

Click on Add and a view having a piece of code containing title message, layout and a header text also. Leave that code and write the following code in that view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
        </div>
    </div>
}
This code will create a single textbox having the id "username" that will be used to access the value entered in this textbox. There is no button on this form to submit the value of this textbox that will be created in next article. As I have discussed earlier that an action have two types HttpGet and HttpPost. So the above action GetValues is an HttpGet type of method because of single returning view code.

The post method is used to get the inputted values of this view and use them for further process. Through this get method programmer can also send some value to the view just like the title of the view. The title of the view is GetValues as written on the first line of the .cshtml code. Programmer can easily change this title by either sending the title by the Get view or by simple edit this line of code. Now run this MVC application and write http://localhost:portNo/Empty/GetValues in the address bar of the browser and press enter.

Create Custom View using an Empty Controller in VS 2013: MVC 4

Now we will create a submit button on this view and access the value of this textbox in the HttpPost method of the same action in further article.
© Copyright 2013 Computer Programming | All Right Reserved