Tag Archives: asp.net

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

What is Skin in asp.net?

Skins are simple text files that contain markup that enables you to define the look and feel of one or more server controls from a central location. Placed in a theme’s folder, they are an integral part of the ASP.NET themes feature. A skin file (with a .skin extension) contains the server-side presentational elements of a control. These settings are then applied to all the controls to which the skin  applies.

Skin markup is similar to the markup of a button. There are a few differences though. First of all, the control in the skin file cannot have an ID attribute. The ID is used to uniquely identify a control in a page, and because the skin is applied to all controls, there’s no point in giving it an ID. Another difference is the number of attributes you can set in the markup. Not all properties of a control are skinnable.

Generally speaking, properties that influence the appearance (BackColor, ForeColor, BorderColor, and so on) can be skinned and properties that influence behavior (Enabled, EnableViewState, and
more) cannot be set.

Use Cookie to Dynamically Switching Themes

Cookies are little pieces of text that you can store on the user’s computer. The data you store in a cookie is sent only to the server that set it in the first place, so other sites can’t read the cookie from
yours. However, because cookies are stored on the user’s computer as plain text, you should never use them to store any sensitive data, such as a password. Storing harmless data like the preferred
theme is an excellent use of cookies, though.

There has been a lot of debate about cookies and whether or not they can harm your privacy. Generally, cookies are safe, because they only store data that the server that sets it already has. They can’t be used to steal sensitive data from your computer if you haven’t given this data to the server yourself. In most scenarios, cookies improve the user’s browsing experience by remembering little pieces of data instead of asking you every single time you visit a page. Unfortunately, some large corporations like advertising agencies use a unique cookie to track your trails on the web, giving them some global idea of the sites you visit. To ensure that visitors to your site understand what information you have and keep about them, it’s usually a good idea to add a privacy statement to your site describing the intent and usage of cookies and any personal data you may keep.

To apply a theme to your web site, you have three different options: at the page level in the Page directive, at the site level by modifying the web.config file, and programmatically

To apply a theme to your web site, you have three different options: at the page level in the Page directive, at the site level by modifying the web.config file, and programmatically.

  • Setting the theme at the page level: Setting the Theme or StyleSheetTheme property at the page level is easy: just set the relevant attribute in the Page directive of the page:
    <%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” Theme=”DarkGrey” %>
  • Setting the theme at the site level: To enforce a theme throughout the entire web site, you can set the theme in the web.config file by adding a theme attribute to the <pages> element
    inside the <system.web> element:
    <pages theme=”DarkGrey”>

    Make sure you type theme with all lowercase letters because the XML in the web.config file is case sensitive.
  • Setting themes programmatically: The third and final way to set a theme is programmatically through code.

Choosing Between Theme and StyleSheetTheme

Because properties of the StyleSheetTheme can be overridden by the page, and the Theme in turn can override these properties again, both serve a distinct purpose. You should set
the StyleSheetTheme if you want to supply default settings for your controls. That is, the StyleSheetTheme can supply defaults for your controls, which can then be overridden at the page
level. You should use the Theme property instead if you want to enforce the look and feel of your controls. Because the settings from the Theme cannot be overridden anymore and effectively overwrite any customizations, you can be assured that your controls look the way you defined them in the theme. There is one exception: by setting EnableTheming on the control to False you can disable theming for that control.

Different Types of Themes

An ASP.NET page has two different properties that enable you to set a theme: the Theme property and the StyleSheetTheme property. Both of these properties use the themes that you define in the App_Themes folder. Although at first they seem very similar, it’s their runtime behavior that makes the difference. The StyleSheetTheme is applied very early in the page’s life cycle, shortly after the page instance has been created. This means that an individual page can override the settings from the theme by applying inline attributes on the controls. So, for example, a theme with a skin file that sets the BackColor of a button to purple can be overridden by the following control declaration in the markup of the page:
<asp:Button ID=”Button1” runat=”server” Text=”Button” BackColor=”Red” />
The theme in the Theme property, on the other hand, is applied late in the page’s life cycle, effectively overriding any customization you may have for individual controls.

Assign a page as the start page in asp.net

You can assign a page as the start page by right-clicking it in the Solution Explorer and choosing Set As Start Page. If you want to control this behavior at a later stage, right-click the web site in the Solution Explorer and choose Property Pages. In the Start Options category, you can indicate that you want the currently active page to open, or you can assign a specific page, as show


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.