Tag Archives: C#

Cookies in ASP.NET

Cookies is a small piece of information stored on the client machine. This file is located on client machines “C:\Document and Settings\Currently_Login user\Cookie” path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called  Systen.Web.HttpCookie before we use cookie.
Type of Cookies?

  1. Persist Cookie – A cookie has not have expired time Which is called as Persist Cookie

  2. Non-Persist Cookie – A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?
Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
Example 1:
        HttpCookie userInfo = new HttpCookie(“userInfo”);
        userInfo[“UserName”] = “Annathurai”;
        userInfo[“UserColor”] = “Black”;
        userInfo.Expires.Add(new TimeSpan(0, 1, 0));

Example 2:
        Response.Cookies[“userName”].Value = “Annathurai”;
        Response.Cookies[“userColor”].Value = “Black”;
How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.
Example 1:
        string User_Name = string.Empty;
        string User_Color = string.Empty;
        User_Name = Request.Cookies[“userName”].Value;
        User_Color = Request.Cookies[“userColor”].Value;

Example 2:
        string User_name = string.Empty;
        string User_color = string.Empty;
        HttpCookie reqCookies = Request.Cookies[“userInfo”];
        if (reqCookies != null)
            User_name = reqCookies[“UserName”].ToString();
            User_color = reqCookies[“UserColor”].ToString();
When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie’s common property:

  1. Domain => Which is used to associate cookies to domain.

  2. Secure  => We can enable secure cookie to set true(HTTPs).

  3. Value    => We can manipulate individual cookie.

  4. Values  => We can manipulate cookies with key/value pair.

  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

  1. Its clear text so user can able to read it.

  2. We can store user preference information on the client machine.

  3. Its easy way to maintain.

  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can’t get it back.

  2. No security.

  3. Each request will have cookie information with page.

How to clear the cookie information?


  • we can clear cookie information from client machine on cookie folder


  1. To set expires to cookie object
    userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.


This article  is copy from http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ some article is very useful, I past it here, so I could use it  when I need it.

How to use the procedure I write it in last post in your asp.net web application

In my last post I just create a store procedure to insert data into 2 tables, here is the c# code how do you use it in your project.

I write a event so for anyone need it just change you connection string then will be reuse.

protected void ButtonClick_StoreRecords(string parameterRef, string parameterLM_Booking_Ref,  string parameterLMStatus, DateTime parameterEntry_datetime)
        string CS = ConfigurationManager.ConnectionStrings["youconnectionstringhere"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
            SqlCommand cmd = new SqlCommand("spStoreLMStatusRecording", con);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramRef = new SqlParameter();
            paramRef.ParameterName = "@parameterRef";
            paramRef.Value = parameterRef;

            SqlParameter paramLM_Booking_Ref = new SqlParameter();
            paramLM_Booking_Ref.ParameterName = "@parameterLM_Booking_Ref";
            paramLM_Booking_Ref.Value = parameterLM_Booking_Ref;

            SqlParameter paramLMStatus = new SqlParameter();
            paramLMStatus.ParameterName = "@parameterLMStatus";
            paramLMStatus.Value = parameterLMStatus;

            SqlParameter paramEntry_datetime = new SqlParameter();
            paramEntry_datetime.ParameterName = "@parameterEntry_datetime";
            paramEntry_datetime.Value = parameterEntry_datetime;



How to send Asynchronously Email

Recently need create a email system to arrow driver confirm a job from online. Every time the driver login to the web system, so they could accept a job, after the driver click accept button will send the email to be read by a software then update the database.

In that case, what will happen if multiple driver click the button at same time, then will cause my email problems.

Here is the simply solve by using Thread. you only need this code to solve you problems.

Thread email = new Thread(delegate()
                var mysmtpClient = new SmtpClient();
            email.IsBackground = true;

//email sending process will be executed in background Thread and thus removes the latency involved in the email sending process.

Build a Shopping Cart by use C# work in asp.net—end in this post

Now to create Products page, add a new webform and name it Products.aspx, add sqldataSource and configure it for select statement,
Add a DataList Control on the page and make SqlDataSource1 it’s source.
Configure Datalist according to below mentioned source

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />


<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”

ConnectionString=”<%$ ConnectionStrings:ConnectionString %>”

SelectCommand=”SELECT [ProductID], [Name], [Description],

[Price], [ImageUrl] FROM [Products]”>




<asp:DataList ID=”DataList1″ runat=”server”





<asp:ImageButton ID=”ImageButton1″ runat=”server”

ImageUrl='<%# Eval(“ImageUrl”, “Images\\thumb_{0}”) %>’

PostBackUrl='<%# Eval(“ProductID”,

“ProductDetails.aspx?ProductID={0}”) %>’ />

<br />

<asp:Label ID=”NameLabel” runat=”server”

Text='<%# Eval(“Name”) %>’>


<asp:Label ID=”PriceLabel” runat=”server”

Text='<%# Eval(“Price”, “{0:C}”) %>’>

</asp:Label><br />

<br />

<br />


</asp:DataList><br />

<asp:HyperLink ID=”CartLink” runat=”server”


View Shopping Cart

</asp:HyperLink><br />

Now add a new webform and name it ProductDetails.aspx , this page is used for showing details for selected product from product catalog page, again add a SqlDataSource and DataList Control on this page and configure them according to source shown below, this time datalist is populated using QueryString Parameters.

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”

ConnectionString=”<%$ ConnectionStrings:ConnectionString %>”

SelectCommand=”SELECT [ProductID], [Name], [Description],

[Price], [ImageUrl] FROM [Products]

WHERE ([ProductID] = @ProductID)”>


<asp:QueryStringParameter Name=”ProductID”


Type=”Decimal” />





<asp:DataList ID=”DataList1″ runat=”server”



<asp:Image ID=”Image1″ runat=”server”

ImageUrl='<%# Eval(“ImageUrl”,”~/Images\\{0}”) %>’/>

<asp:Label ID=”ImageUrlLabel” runat=”server”

Text='<%# Eval(“ImageUrl”) %>’


</asp:Label><br />

<asp:Label ID=”NameLabel” runat=”server”

Text='<%# Eval(“Name”) %>’>

</asp:Label><br />

<asp:Label ID=”DescriptionLabel” runat=”server”

Text='<%# Eval(“Description”) %>’>

</asp:Label><br />

<asp:Label ID=”PriceLabel” runat=”server”

Text='<%# Eval(“Price”, “{0:##0.00}” ) %>’>

</asp:Label><br />


</asp:DataList><br />

<asp:Button ID=”btnAdd” runat=”server” OnClick=”Button1_Click”

Text=”Add to Cart” /><br /><br />

<asp:HyperLink ID=”HyperLink1″ runat=”server”


Return to Products Page


Write this code in C# code behind of ProductDetails.aspx page

protected void Button1_Click(object sender, EventArgs e)


double Price = double.Parse(((Label)


string ProductName = ((Label)


string ProductImageUrl = ((Label)


int ProductID = int.Parse(Request.QueryString[“ProductID”]);

if (Profile.SCart == null)


Profile.SCart = new ShoppingCartExample.Cart();



(ProductID, Price, 1, ProductName, ProductImageUrl);


Now right click on solution explorer and add new web user control, name it CartControl.ascx
In design view of this control add a new GridView control and a label below gridview, html shource of this control should look like this

<%@ Control Language=”C#” AutoEventWireup=”true”


Inherits=”CartControl” %>

<asp:GridView ID=”grdCart” runat=”server”










<asp:Image ID=”Image1″ runat=”server”




<asp:BoundField DataField=”ProductName”

HeaderText=”Product” ReadOnly=”True”/>

<asp:BoundField DataField=”Quantity” HeaderText=”Quantity”/>

<asp:BoundField DataField=”Price” DataFormatString=”{0:c}”

HeaderText=”Price” ReadOnly=”True” />

<asp:BoundField DataField=”SubTotal” DataFormatString=”{0:c}”

HeaderText=”Total” ReadOnly=”True” />

<asp:CommandField ShowDeleteButton=”True”




Your Shopping Cart is empty, add items

<a href=”Products.aspx”>Add Products</a>



<asp:Label ID=”TotalLabel” runat=”server”></asp:Label>
Open web.config file and add this section for enabling anonymous users to add items to cart



<allow users=”?” />

<allow roles=”admin” />


<roleManager enabled=”true” />

<authentication mode=”Forms” />

<compilation debug=”true”>




<anonymousIdentification enabled=”true”/>

<profile enabled=”true”>


<add name=”SCart” serializeAs=”Binary”





Now go to code behnd of CartControl.ascx and write this code

protected void Page_Load(object sender, EventArgs e)


if (Profile.SCart == null)


Profile.SCart = new ShoppingCartExample.Cart();


if (!Page.IsPostBack)




if(Profile.SCart.Items == null)


TotalLabel.Visible = false;



protected void grdCart_RowEditing

(object sender, GridViewEditEventArgs e)


grdCart.EditIndex = e.NewEditIndex;



protected void grdCart_RowUpdating

(object sender, GridViewUpdateEventArgs e)


TextBox txtQuantity = (TextBox)


int Quantity = Convert.ToInt32(txtQuantity.Text);

if (Quantity == 0)







= Quantity;


grdCart.EditIndex = -1;



protected void grdCart_RowCancelingEdit

(object sender, GridViewCancelEditEventArgs e)


grdCart.EditIndex = -1;



protected void grdCart_RowDeleting

(object sender, GridViewDeleteEventArgs e)





private void ReBindGrid()


grdCart.DataSource = Profile.SCart.Items;


TotalLabel.Text = string.Format(“Total:{0,19:C}”,


Now add Global Application Class (Global.asax) by right clicking on solution explorer > add new Item. and write code mentioned below in it.

01void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)

02    {

03        ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);

04        if (anonymousProfile.SCart != null)

05        {

06            if (Profile.SCart == null)

07                Profile.SCart = new ShoppingCartExample.Cart();


09            Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);


11            anonymousProfile.SCart = null;

12        }


14        ProfileManager.DeleteProfile(e.AnonymousID);

15        AnonymousIdentificationModule.ClearAnonymousIdentifier();

16    }


Add another webform and name it UserCart.aspx, in design view of this page drag the CartControl we’ve just created and put a hyperlink for going back to products cataloge page

Tha’s it , build and run the application
Have fun


How to access a use control from another user control in asp.net,C#

I recently need work with sitefinity CMS system website. I need create a page have left sidebar images url equal to my left side dropdown list value.So I create two user controls and left sidebar user control and right content user control. Then I have problems to solve just let my left sidebar user control to access my right sidebar user control. Here is my solution, see the link below for how it work.


First, I create a user control is PackageBookingForm.ascx, and on the back code I create this
//make get this dropdown list value

public DropDownList Experience_DDL
return this.DropDownList_experience;

Second, I create another user control, called Image_package_sidebar.ascx, because I need access PackageBookingForm.ascx control’s dropdown list value, here is the very important to put reference on the top of this control,here is <%@ Reference VirtualPath=”youpath/PackageBookingForm.ascx” %>, then write the code on the back end.

PackageBookingForm ctrlP = (PackageBookingForm)Page.FindControl("yourcontrolID");
DropDownList ddl = ctrlP.Experience_DDL;
Image_package_sidebar.ImageUrl = "~/yourpath/" + ddl.SelectedValue + ".jpg";

then put those control in the same page, the left sidebar control will access your right user control dropdown list value

How to let your visual studio 2010 support HTML5?

Mircosoft won’t let code people use notepadd++ to write codes.Html5 is very popular,how can vs2010 won’t support html5? here I will teacher you how to let you vs2010 support html5.

all you need is vs2010 and a browser.

what do we need a browser? hehe,if you want you vs2010 support html5. first thing first is that you need update vs2010 to sp1.

How do we up microsoft Visual Studio 2010 to microsoft Visual Studio 2010 sp1?
There are two ways:
1.Go straight to microsoft website, download center download Microsoft Visual Studio 2010 Service Pack 1

2.open windows update, the system will automatically find vs2010 update file, size around 600MB

Once you finished update, then open you vs2010 goto tool->option->HTML->Validation


ASP.NET Page Life Cycle

  • Page request A request to an ASPX page starts the life cycle of that page. When the web server is able and allowed to return a cached copy of the page, the entire life cycle is not executed. In all other situations, the page enters the start phase.
  • Start In this phase, the page gets access to properties like Request and Response that are used to interact with the page’s environment. In addition,during this phase the PreInit event is raised to signal that the page is about to go into the initialization phase.
  • Page initialization During this phase, the controls you have set up in your page or added programmatically become available. Additionally, the Page class fires three events: Init, InitComplete, and PreLoad. Also during this phase, the control properties are loaded from View State and Control State again during a postback. So, for example, when you change the selected item in a DropDownList and then cause a postback, this is the moment where the correct item gets preselected in the drop-down list again, which you can then work with in your server-side code.
  • Load During this phase the page raises the Load event.
  • Validation In the validation phase, the Validation controls used to validate user input are processed.
  • Postback event handling During this phase, the controls in your page may raise their own events. For example, the DropDownList may raise a SelectedIndexChanged event when the user has chosen a different option in the list. Similarly, a TextBox may raise the TextChanged event when the user has changed the text before she posted back to the server. When all event processing is done, the page raises the LoadComplete event. During this phase the PreRender event is raised to signal that the page is about to render to the browser. Shortly after that, SaveStateComplete is raised to indicate that the page is done storing all the relevant data for the controls in View State.
  • Rendering Rendering is the phase where the controls (and the page itself) output their HTML to the browser.
  • Unload The unload phase is really a clean-up phase. This is the moment where the page and controls can release resources like database connections.During this phase, the Unload event is raised so you can handle any cleanup you may need to do.

Code Files and Data Files

Code Files

  • Web Service .asmx Can be called by other systems, including browsers, and can contain code that can be executed on your server.
  • Class .cs Can contain code to program your web site.
  • Global Application Class .asax Can contain code that is fired in response to interesting things that happen in your site, such as the start of the application or when an error occurs somewhere in the site.

Data Files

  • XML File .xml Used to store data in XML format. In addition to plain XML files, ASP.NET supports a few more XML-based files, two of which you briefly saw before: web.config and the Site Map.
  • SQL Server Database .mdf Files with an .mdf extension are databases that are used by Microsoft SQL Server.
  • ADO.NET Entity Data Model .dbml Used to access databases declaratively, without the need to write code. Technically, this is not a data file, because it does not contain the actual data. However, because it is tied to the database so closely, it makes sense to group it under this header.

Web Files

Web Files are specific to web applications and can either be requested by a browser directly, or are used to build up part of the web page that is requested in the browser. The following table lists the various web files and their extensions, and describes how each file is used.

  • Web Form .aspx The workhorses of any ASP.NET web site, Web Forms represent the pages that your users view in their browser.
  • Master Page .master Enable you to define the global structure and the look and feel of a web site.
  • Web User Control .ascx Contains page fragments that can be reused in multiple pages in your site.
  • HTML Page .htm / .html Can be used to display static HTML in your web site.
  • Style Sheet .css Contains CSS code that enables you to style and format your web site. 
  • Web Configuration File .config Contains global configuration information that is used throughout the site.
  • Site Map .sitemap Contains a hierarchical representation of files in your site in an XML format.
  • JScript File .js Contains JavaScript (which Microsoft calls JScript) that can be executed in the client’s browser.
  • Skin File .skin Contains design information for controls in your web site.