Category Archives: asp.net in c#

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();
                mysmtpClient.Send(acceptMessage);
            });
            email.IsBackground = true;
            email.Start();

//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” />

<div>

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

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

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

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

</asp:SqlDataSource>

</div>

 

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

DataSourceID=”SqlDataSource1″

RepeatColumns=”4″

RepeatDirection=”Horizontal”>

<ItemTemplate>

<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>

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

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

</asp:Label><br />

<br />

<br />

</ItemTemplate>

</asp:DataList><br />

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

NavigateUrl=”~/UserCart.aspx”>

View Shopping Cart

</asp:HyperLink><br />

</form>
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)”>

<SelectParameters>

<asp:QueryStringParameter Name=”ProductID”

QueryStringField=”ProductID”

Type=”Decimal” />

</SelectParameters>

</asp:SqlDataSource>

</div>

 

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

DataSourceID=”SqlDataSource1″>

<ItemTemplate>

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

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

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

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

Visible=”False”>

</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 />

</ItemTemplate>

</asp:DataList><br />

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

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

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

NavigateUrl=”~/Products.aspx”>

Return to Products Page

</asp:HyperLink>

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

protected void Button1_Click(object sender, EventArgs e)

{

double Price = double.Parse(((Label)

DataList1.Controls[0].FindControl(“PriceLabel”)).Text);

string ProductName = ((Label)

DataList1.Controls[0].FindControl(“NameLabel”)).Text;

string ProductImageUrl = ((Label)

DataList1.Controls[0].FindControl(“ImageUrlLabel”)).Text;

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

if (Profile.SCart == null)

{

Profile.SCart = new ShoppingCartExample.Cart();

}

Profile.SCart.Insert

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

Server.Transfer(“Products.aspx”);

}
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”

CodeFile=”CartControl.ascx.cs”

Inherits=”CartControl” %>

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

AutoGenerateColumns=”False”

DataKeyNames=”ProductID”

OnRowCancelingEdit=”grdCart_RowCancelingEdit”

OnRowDeleting=”grdCart_RowDeleting”

OnRowEditing=”grdCart_RowEditing”

OnRowUpdating=”grdCart_RowUpdating”>

<Columns>

<asp:TemplateField>

<ItemTemplate>

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

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

</ItemTemplate>

</asp:TemplateField>

<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”

ShowEditButton=”True”/>

</Columns>

<EmptyDataTemplate>

Your Shopping Cart is empty, add items

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

</EmptyDataTemplate>

</asp:GridView>

<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

<system.web>

<authorization>

<allow users=”?” />

<allow roles=”admin” />

</authorization>

<roleManager enabled=”true” />

<authentication mode=”Forms” />

<compilation debug=”true”>

</compilation>

</system.web>

<system.web>

<anonymousIdentification enabled=”true”/>

<profile enabled=”true”>

<properties>

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

type=”ShoppingCartExample.Cart”

allowAnonymous=”true”/>

</properties>

</profile>

</system.web>
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)

{

ReBindGrid();

}

if(Profile.SCart.Items == null)

{

TotalLabel.Visible = false;

}

}

protected void grdCart_RowEditing

(object sender, GridViewEditEventArgs e)

{

grdCart.EditIndex = e.NewEditIndex;

ReBindGrid();

}

protected void grdCart_RowUpdating

(object sender, GridViewUpdateEventArgs e)

{

TextBox txtQuantity = (TextBox)

grdCart.Rows[e.RowIndex].Cells[2].Controls[0];

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

if (Quantity == 0)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

}

else

{

Profile.SCart.Items[e.RowIndex].Quantity

= Quantity;

}

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowCancelingEdit

(object sender, GridViewCancelEditEventArgs e)

{

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowDeleting

(object sender, GridViewDeleteEventArgs e)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

ReBindGrid();

}

private void ReBindGrid()

{

grdCart.DataSource = Profile.SCart.Items;

DataBind();

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

Profile.SCart.Total);

}
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();

08

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

10

11            anonymousProfile.SCart = null;

12        }

13

14        ProfileManager.DeleteProfile(e.AnonymousID);

15        AnonymousIdentificationModule.ClearAnonymousIdentifier();

16    }

17

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

 

Build a Shopping Cart by use C# work in asp.net—continue

Recently studying Java in UTS , It remind me that really like c# I just learned in TAFE.

Previous I create a shopping cart table in my database then use c# to add,update,delete the products in my shopping cart table into my database.

But know I have better solution,just by create a Shopping Cart Class,

here is it the Shopping Cart Class:(ShoppingCart.cs)

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace ShoppingCartExample
{
    [Serializable] 
    public class CartItem
    {
        private int _productID;
        private string _productName;
        private string _imageUrl;
        private int _quantity;
        private double _price;
        private double _subTotal;

        public CartItem()
        { 
        }
        public CartItem(int ProductID, string ProductName, string ImageUrl, int Quantity, double Price)
        {
            _productID = ProductID;
            _productName = ProductName;
            _imageUrl = ImageUrl;
            _quantity = Quantity;
            _price = Price;
            _subTotal = Quantity * Price;

        }
        public int ProductID
        {
            get
            {
                return _productID;
            }
            set
            {
                _productID = value;
            }
        }

         public string ProductName
         {
            get { return _productName; }
            set { _productName = value; }
         }

         public string ImageUrl
         {
             get { return _imageUrl; }
             set { _imageUrl = value; }
         }

         public int Quantity
         {
             get { return _quantity; }
             set { _quantity = value; }
         }

         public double Price
         {
             get { return _price; }
             set { _price = value; }
         }

         public double SubTotal
         {
             get { return _quantity * _price; }
            
         }
     
    }
    [Serializable]
    public class Cart
    {
        private DateTime _dateCreated;
        private DateTime _lastUpdate;
        private List _items;

        public Cart()
        {
            if (this._items == null)
            {
                this._items = new List();
                this._dateCreated = DateTime.Now;
            }
        }

        public List Items
        {
 		get { return _items;}
		set { _items = value;}
	    }

        public void Insert(int ProductID, double Price, int Quantity, string ProductName, string ImageUrl)
        {
            int ItemIndex = ItemIndexOfID(ProductID);
            if (ItemIndex == -1)
            {
                CartItem NewItem = new CartItem();
                NewItem.ProductID = ProductID;
                NewItem.Quantity = Quantity;
                NewItem.Price = Price;
                NewItem.ProductName = ProductName;
                NewItem.ImageUrl = ImageUrl;
                _items.Add(NewItem);
            }
            else
            {
                _items[ItemIndex].Quantity += 1;
            }
            _lastUpdate = DateTime.Now;
        }

        public void Update(int RowID, int ProductID, int Quantity, double Price)
        {
            CartItem Item = _items[RowID];
            Item.ProductID = ProductID;
            Item.Quantity = Quantity;
            Item.Price = Price;
            _lastUpdate = DateTime.Now;
        }

        public void DeleteItem(int rowID)
        {
            _items.RemoveAt(rowID);
            _lastUpdate = DateTime.Now;
        }

        private int ItemIndexOfID(int ProductID)
        {
            int index = 0;
            foreach (CartItem item in _items)
            {
                if (item.ProductID == ProductID)
                {
                    return index;
                }
                index += 1;
            }
            return -1;
        }

        public double Total
        {
            get
            {
                double t = 0;
                if (_items == null)
                {
                    return 0;
                }
                foreach (CartItem Item in _items)
                {
                    t += Item.SubTotal;
                }
                return t;
            }
        }
 
    }
}


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.

http://www.royaletravel.com.au/package-book?p=Romantic-Getaway-Premium

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
{
get
{
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

Image

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”>

    </pages>
    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.