MY PRINCIPAL :- "THE GLORY OF LIFE ID TO LOVE NOT TO BELOVED...TO GIVE NOT TO GET..TO SERVE NOT TO BE SERVED."

Friday, December 10, 2010

ASP.Net State management Techniques.(Coockies)



Coockies:-


    -coockies are the concept of browser/http not any technologies like .Net,Java,php etc.
    -coockies are domain specific i.e. travelled between every request/response when requested from          particular domain.
    -Coockie is the name-value pair travel between every request/response and optionally stored also.
    -As coockies are browser/client based, only browser has rights to enable or disable the coockies.
    -we can store only simple/text data in coockie not any objects.
    -For every site there is only 20 coockies are allowed(standerd i.e. we can go beyond that depending on browser)
    -data in the coockies size upto 1mb(std).
    -For every domain 200 coockies are allowed.
    -For the developer to use coockie is the better option when there is no security issue because it has the ability to travel between every request/response.
    -We must not store critical information in the coockies (ex-credentials,passward).it may be tampered by hackers.
    -The default time for coockie is 30 days.
   
Types of Coockies:-

    There are two types of coockies.
     a. In-memory Cockie.
        b. Persistance Coockie.

a. In-Memory coockie:- These coockies are available whenever the user online or working with application      and stored in RAM of users computer.Once user log out or close the browser these coockies automatically get vanished.

b. Persistance Coockies:- These coockies are availble wheather user online or offline. It get stored in hard disk. suppose when we visit the same site again then browser itself search for that coockie in stored location specified and reads the coockie information. EX. Remember me checkbox.
-To make our coockie as Persistance store, we have to specify the time for that coockie.


Declaration and Syntax:-

single valued coockie:

        HttpCoockie ckobj=new HttpCoockie("Coockie name");
        ckobj.value="preference";
        Response.coockies.add(ckobj);

multivalued coockie:

It is single coockie for the browser but for us it is multivalue coockie.

        HttpCoockie ckobj=new HttpCoockie("Coockie name");
        ckobj.values="preference1";
        ckobj.values="preference2";
        ckobj.values="preference3";
        Response.coockies.add(ckobj);

Now, How to Read Coockies:

        if(Request.Coockies("Coockie name")!=Null)
        {
            string str=Request.Coockies["coockie name"].value;
        }

How to specify the  for coockies: ckobj.Expires(DateTime.Now.AddDays(10));

       
Now we will see the real time example of Coockies i.e. changing the Country preferences. You might have seen on the website that they are having
country preferences usually on top right of page.We are going to see that example here only.

ex: Create an application with one dropdown list and bound it to class containing the country list from database or static and one button on it.Onclick of button redirect the user to another page saying "your preference has been save".

Design;

Coding:


 1. DBHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for DBHelper
/// </summary>
public class DBHelper
{
    public DBHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static List<string> GetCountries()
    {
        List<string> country = new List<string>();
        country.Add("India");
        country.Add("Pakistan");
        country.Add("Australiya");
        country.Add("Newzeland");
        country.Add("Srilanka");
        country.Add("Bangladesh");

        return country;
    }
}
------------------------

2. Default.aspx

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

<!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">
    <div style="text-align: center; font-weight: 700; color: #FF3300">
   
        Select Your Preference:
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Set Preference" />
   
    </div>
    </form>
</body>
</html>
---------------------
3. Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = DBHelper.GetCountries();
            DropDownList1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string strpreference = DropDownList1.SelectedValue;
        HttpCookie ckobj = new HttpCookie("Country");
        ckobj.Value = strpreference;
        ckobj.Expires = DateTime.Now.AddDays(10);
        Response.Cookies.Add(ckobj);
        Response.Redirect("~/Default2.aspx");
    }
}
-----------------------

4. default2.aspx

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

<!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">
    <div>
   
        &nbsp;&nbsp;&nbsp;&nbsp; Your preference has been saved as:
        <asp:Label ID="Label1" runat="server"></asp:Label>
   
    </div>
    </form>
</body>
</html>
-------------------
5. Defalut2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["country"] != null)
        {
            Label1.Text = Request.Cookies["country"].Value;
        }

    }
}
---------------------------


Now two Practice example for you guys:

ex:2- Create an application Which will contains one shopping cart and save all the data in coockies for ex. product information and when
      user login next time show its purchased products. (use your own logic to developed shopping cart).

ex:3- create an application which will take input from user i.e. username and passward and do login. when the user log in and checks checkbox
      remember me then create coockie containing username only and show that username in username textbox when the user log in next time(make persistance coockie)

Saturday, November 20, 2010

Data Navigation through dataset in web application...

In last post we have seen the data navigation through dataset in windows application. Now in this post i am going to show u the same navigation but in web application.

Before that we should know that -In web world , we have to deal with the http protocol and that is stateless protocol so we need to maintain the state in our application. Each time whenever we request something from server it gives us that data but what abt next request..? Server does not recognize the request from where it is coming.I mean the next request is treated as the new request. So it is very important to us that to maintain the state during postbacks.unlike the windows applications are state full.

We have the following are some state management techniques to maintain the state. In this post i m not going to explain the full concepts of state management. u will find that in next post with detail description.

1.ViewState
2.Coockies
3.Session
4.Application

    In this post i am going to use the ViewState to maintain the state in application

Design:

Coding:
 
 1. default.aspx(presentation layer)

<%@ 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>
    <style type="text/css">
        .style1
        {
            width: 40%;
             background: #3399FF;
             font-family:Calibri;
             font-weight:bold;
             color:White;
        }
        .style2
        {
         font-family:Calibri;
             font-weight:bold;
             color:White;  
             background: #3499FF;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table class="style2" align="center">
            <tr>
                <td colspan="2" align="center">
                    Navigation Demo Using ViewState<hr /></td>
            </tr>
            <tr>
                <td>
                    Id:</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" Width="157px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Name:</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="157px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Surname:</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server" Width="157px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    City:</td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server" Width="157px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="Button1" runat="server" Text="First" onclick="Button1_Click" />
&nbsp;
                    <asp:Button ID="Button2" runat="server" Text="Prev" onclick="Button2_Click" />
&nbsp;
                    <asp:Button ID="Button3" runat="server" Text="Next" onclick="Button3_Click" />
&nbsp;
                    <asp:Button ID="Button4" runat="server" Text="Last" onclick="Button4_Click" />
                </td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</html>
 


 2. default.aspx.cs(code behind or business logic layer)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    helper help;
    int max;
    protected void Page_Load(object sender, EventArgs e)
    {
       
        help = new helper();
        DataSet ds1;
        ds1 = help.getdata();

        max = ds1.Tables["sample"].Rows.Count;
        if (!IsPostBack)
        {
          
            if (ViewState["inc"] == null)
                ViewState["inc"] = 0;

       DataRow drw= help.showrecord(Convert.ToInt32(ViewState["inc"]));

       showdata(drw);
        }
       

       
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        //next button_click
        if (Convert.ToInt32(ViewState["inc"]) < max - 1)
        {
            ViewState["inc"] =Convert.ToInt32( ViewState["inc"]) + 1;
           DataRow drw= help.showrecord(Convert.ToInt32(ViewState["inc"]));
           showdata(drw);
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        //prev button click
        if (Convert.ToInt32(ViewState["inc"]) > 0)
        {
           
            ViewState["inc"] = Convert.ToInt32(ViewState["inc"]) - 1;
            DataRow drw = help.showrecord(Convert.ToInt32(ViewState["inc"]));
            showdata(drw);
        }

    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        //last button click
        if (Convert.ToInt32(ViewState["inc"]) < max - 1)
        {
            ViewState["inc"] = max- 1;
           
            DataRow drw = help.showrecord(Convert.ToInt32(ViewState["inc"]));
            showdata(drw);
           
        }
    }

    private void showdata(DataRow drw)
    {
        TextBox1.Text = drw.ItemArray.GetValue(0).ToString();
        TextBox2.Text = drw.ItemArray.GetValue(1).ToString();
        TextBox3.Text = drw.ItemArray.GetValue(2).ToString();
        TextBox4.Text = drw.ItemArray.GetValue(3).ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //first button click
        if (Convert.ToInt32(ViewState["inc"])!=0)
        {
            ViewState["inc"] = 0;
            DataRow drw = help.showrecord(Convert.ToInt32(ViewState["inc"]));
            showdata(drw);
        }
    }
}


 3. dbhelper.cs(data access layer)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for helper
/// </summary>
public class helper
{
    private SqlConnection con;
    private SqlDataAdapter da;
    private DataSet ds;
    int maxrows;
    public helper()
    {
       

    }
    public DataSet getdata()
    {
        string strcon = @"Data Source=.;Initial Catalog=PracticeDB;Persist Security Info=True;User ID=sa;Password=123";
        con = new SqlConnection(strcon);
        da = new SqlDataAdapter("select * from sample",con);
        ds = new DataSet();
        da.Fill(ds, "sample");
        return ds;
    }

    public DataRow showrecord(int inc)
    {
        DataRow drow = ds.Tables["sample"].Rows[inc];

        return drow;
    }

   
}

Happy coding....

Data Navigation through dataset and CRUD operations In Windows Application

welcome again guys...
In last post we have seen data navigation through datareader. Now in this post i am going to show u a navigation of data through dataset as wel as the CRUD operations.

Here we are....

Design:






Coding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Datareader_navigation
{
    public partial class Form1 : Form
    {
        int inc,count;
        private SqlDataReader dr;
        private SqlConnection con;
        private DataTable dt;
        private DataSet ds;
        private SqlDataAdapter da;
        DataRow drow;
           
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = @"Data Source=NARESH-PC;Initial Catalog=PracticeDB;Persist Security Info=True;User ID=sa;Password=123";
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand();
            ds = new DataSet();
            da = new SqlDataAdapter("select * from sample",con);
            SqlCommandBuilder cmb = new SqlCommandBuilder(da);

            da.Fill(ds,"sample");
            count = ds.Tables["sample"].Rows.Count;
            if (ds == null)
            {
                MessageBox.Show("dataset is empty..");
            }
            showNextRecord( inc);
            panel1.Visible = false;
       
    }

      

        private void showNextRecord(int inc)
        {
           
            if (ds != null)
            {
                DataRow drow = ds.Tables["sample"].Rows[inc];
                textBox4.Text = drow.ItemArray.GetValue(0).ToString();
                textBox1.Text = drow.ItemArray.GetValue(1).ToString();
                textBox2.Text = drow.ItemArray.GetValue(2).ToString();
                textBox3.Text = drow.ItemArray.GetValue(3).ToString();
            }
            else
            {
                MessageBox.Show("dataset is empty..");
            }

          
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //next button click
            panel1.Visible = false;
            if (inc != count - 1)
            {
                inc++;
                showNextRecord(inc);
            }
            else
            {
                MessageBox.Show("no further record....");
            }
          
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            //previous button click
            panel1.Visible = false;
            if (inc > 0)
            {
                inc--;
                showNextRecord( inc);
            }
            else
            {
                MessageBox.Show("first record");
            }

        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            //first button click
            panel1.Visible = false;
            if (inc != 0)
            {
                inc = 0;
                showNextRecord(inc);
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            //last button click
            panel1.Visible = false;
            if (inc != count - 1)
            {
                inc = count - 1;
                showNextRecord(inc);
            }
          
        }

        private void addnew_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            textBox4.Visible = false;
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
           
            panel1.Visible = false;
            DataRow row = ds.Tables["sample"].NewRow();
           
            row["name"] = textBox1.Text;
            row["surname"] = textBox2.Text;
            row["city"] = textBox3.Text;
            ds.Tables["sample"].Rows.Add(row);
            count = count + 1;
            inc = count - 1;
            da.Update(ds,"sample");
            MessageBox.Show("entry added successfully...");
           
        }

        private void delete_Click(object sender, EventArgs e)
        {
            ds.Tables["sample"].Rows[inc].Delete();
            count--;
            inc = 0;
            da.Update(ds, "sample");
            MessageBox.Show("deleted successfully..");
            showNextRecord(inc);
            panel1.Visible = false;
        }

        private void update_Click(object sender, EventArgs e)
        {
            DataRow row1 = ds.Tables["sample"].Rows[inc];

            row1["name"] = textBox1.Text;
            row1["surname"] = textBox2.Text;
            row1["city"] = textBox3.Text;
            da.Update(ds,"sample");
            MessageBox.Show("updated successfully..");
            panel1.Visible = false;
        }

        private void viewall_Click(object sender, EventArgs e)
        {
           
          
            panel1.Visible = true;
            dataGridView1.DataSource = ds;
          


        }

      

          


}
}

Working With DataReader In Ado.Net

As we know the datareader is a forward only and read only..so we can navigate through records in an forward manner not in backward. Here is the code to perform navigation in datareader. After this post we are going to see how to navigate the records in dataset and CRUD operations..

Design:








Coding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;
namespace datareadernext
{
    public partial class Form1 : Form
    {
        private SqlConnection con;
        private SqlDataReader dr;
        private SqlCommand cmd;
        public Form1()

        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = @"Data Source=.;Initial Catalog=PracticeDB;Persist Security Info=True;User ID=sa;Password=123";
            con = new SqlConnection(strcon);
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from sample";
            if (con.State == ConnectionState.Closed)
                con.Open();
            dr = cmd.ExecuteReader();
          //  con.Close();
            showrecord();
           
        }

        private void showrecord()
        {
            if (dr.Read())
            {
                textBox1.Text = dr.GetValue(0).ToString();
                textBox2.Text = dr.GetValue(1).ToString();
                textBox3.Text = dr.GetValue(2).ToString();
                textBox4.Text = dr.GetValue(3).ToString();

            }
            else
            {
                MessageBox.Show("no further record...");
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            showrecord();
        }
    }
}

Thursday, November 18, 2010

ADO.Net(Continue from ado.net overview)

ADO.NET

    As we discussed in last post that ADO has some limitation. so to overcome that limitation we are switching to ADO.NET.

It is technology providing interface between database and the applications. It is the collection of       classes that enables us to connect to the database. It is the framework used for interacting with any database of xml document.







   -It supports two object models for connecting with database

    1. ADO.Net Disconnected model
    2. ADO.Net Connected model

   Now we will discuss both the models one by one...here we are..

  1. ADO.Net Disconnected Model
    It is used for interacting with the databases then connectivity between the application and the database is not needed whenever any data navigations or data manupulation has to be performed.

NOTE: It opens and close connection automatically when needed.

Architecture:

  It has the following objects:
 1. connection
 2. dataadaptor
 3. dataset

1. Connection Object:

        To get the data from database we need some kind of thing i.e. connection to the database. This connection object allow us to make the connection with the database to get the data or to make the application connection to the database .

2. DataAdaptor:

       Once the connection has been established with the database we need some intermediate kind of thing to get and set the data to and forth. DataAdaptor is the object which is the intermediate between database and dataset. When we get the data/ to update the data to/ from database we use dataadapter to achieve this kind of thing. we can say it is the bridge between the database and database. DataAdaptor internally uses command object to achieve this.

3. DataSet:

      Dataset is the in-memory representation of the data in xml format. It can have the data from multiple databases. ex-sqlserver,oracle,xml files.
     We are going to see the detail scenario of dataset that hoe it manages the different databases in next post...



we will discuss DataView later...because of time being am updating the post in chunks..

Wednesday, November 17, 2010

AutoComplete TextBox In C#(Windows Application)

Hello Guys...
 As we know we are basically dealing with web applications and desktop application in our day to day life...
 So my todays topic is to provide the autocomplete facility to the textbox in windows application. We always deal this type of thing in web application...but we can also implement this kind of thing in our windows application

Here we are.....

Design:





Coding:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace AutocompleteTextbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = @"Data Source=datasourcename;Initial Catalog=Northwind;Persist Security       Info=True;User ID=sa;Password=123";
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select ContactName from Customers";
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            con.Close();
            AutoCompleteStringCollection local = new AutoCompleteStringCollection();
            if(dt.Rows.Count>=0)
            {
                for (int count = 0; count < dt.Rows.Count; count++)
                {
                    local.Add(dt.Rows[count]["ContactName"].ToString());

                }
            }
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox1.AutoCompleteCustomSource = local;


        }
}

Explanation:

    
1.    AutoCompleteStringCollection: This allows us to make the collection for our textbox to bind. After getting the data from database we have add that data to this collection.

2.    AutoCompleteMode : Gets or sets an option that controls how automatic completion works for the textbox.

3.   .AutoCompleteSource:Gets or sets a value specifying the source of complete strings used for automatic completion.

4.    AutoCompleteCustomSource:Gets or sets a custom System.collections.specialized.stringcollection to use when the AutoCompleteSource property is set to CustomSource.


Happy coding.....

Tuesday, November 16, 2010

ADO.Net Overview

First of all i would like to tell u the database basic so that you can start using ado.net in your applications...

What is Database?
            "The database is the collection records or the data for permenant  storage so that only useful/meaningful  information can be stored".
             Before going further you should know the difference between the data and the information. so what is the actual difference between them..?

 Data:
It is the collection of useful  information as well as the information that is not useful but need to store.  I mean  it is the raw data without  any  reference .

Information:
  It is all the uefull information which has meaning. means it is the filtered from the data and now has a value.

for eg: suppose 10 mobile number is given to you but you dont know the corresponding names that it refers then it has no value. so that becomes your data and suppose i tell the name regarding the mobile numbers with reference then it becomes useful information so that you can contact them by their respective name. Now i think you people got the difference between data and information. Now its time to move further with our topic

Types Of Databases:
        There are two types of databases :-
1. ISAM (Index Sequential Access Database)
   example: ms-access,exel,flat files
2. VSAM(Virtual Sequential Access Database)
  example:sql server,my-sql,oracal etc.

Scenario Before Ado.Net:- 







Observation:

 DAO: It is  an object model specially designed for interacting with databases(ISAM).

Limitation: It doesnt understand the networks and hence it cant be used for VSAM and limited only to standalone applications.

RDO: It is an object model designed specially for VSAM using dsn(data source name) for interacting with odbc drivers for connecting to any database.

Limitation: It ises network concept so if we use it for interacting with ISAM them performance will slow and hence it uses odbc driver and it is tightly coupled with operating systems will create issues.

ADO: It is a special object model which uses COM for interacting with databases.

Limitation: All limitation of com object model will be applicable to ado

Now in next post i will be explaining you about the ADO.Net....Wait for post