Advertisements

Archive

Archive for June, 2011

How to use Listview control in ASP.Net

June 14, 2011 9 comments

Simple steps to create a ListView Control in ASP.Net,C#

In ASP.Net 3.5 Microsoft introduced a new control Listview, can be used to repeated controls as per the data like repeater, gridview etc.. Listview is a very simple control to use for a developer for displaying multiple items like products, employee details etc.. There is very useful events are available from the ListView control like item databound and item command.

ListView contros to display product/item boxes for shopping cart

Here we are going to demonstrate how we can create a simple listview control for shopping cart. Commonly a shopping cart site must have a page which display searched item details with n number of product boxes, each of them having product details like image, code, name, and also some butoon like details, add to cart etc.. This requirement can be easily achieved by using ListView control.

Listview Control Features/Options :

Layout Template : Allows to define a custom user interface (UI) for the root container of the ListView control.

GroupTemplate: Use the GroupTemplate property to create a tiled layout in the ListView control. In a tiled table layout, the items are repeated horizontally in a row. The numbers of times that an item is repeated is specified by the property.

ItemTemplate : Use the ItemTemplate property to define a custom user interface (UI) to display the data items. Here we can design a template that will be a single part of the listview, that means this part is repeated according to the number of data.

EmptyDataTemplate : The empty template is displayed in a ListView <http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.aspx>  control when the data source that is bound to the control does not contain any records.

Create a simple listview control to display products

We are going to display product details, like a shopping site. For doing this first of all create a listview control, which shows the product image, item code, item name and more.. Here also create a Empty Template and included a message like ‘No items Found’ so that this messgae will display once the datasource does not contain any data.

<asp:ListView runat="server" ID="lstViewItems" GroupItemCount="100" 
OnItemCommand="lstViewItems_ItemCommand"
OnItemDataBound="lstViewItems_ItemDataBound">
<LayoutTemplate>
    <div>
        <asp:PlaceHolder runat="server" ID="groupPlaceHolder" />
    </div>
</LayoutTemplate>
<GroupTemplate>
    <div style="width: 100%;">
        <asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
    </div>
</GroupTemplate>
<ItemTemplate>
    <div>
        <asp:HiddenField ID="hdItemID" runat="server" Value='<%# Eval("ID") %>' />
        <asp:HiddenField ID="hdItemName" runat="server" Value='<%# Eval("Name") %>' />
        <asp:HiddenField ID="hdItemImage" runat="server" Value='<%# Eval("Image") %>' />
        <asp:HiddenField ID="hdPriceValue" runat="server" />
        <table width="100%" border="0" cellpadding="1" cellspacing="3">
        <tr>
            <td align="center" valign="middle">
                <asp:ImageButton ID="imgItem" runat="server" CommandName="ViewDetails" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblItemDescription" runat="server" Text='<%# Eval("Name") %>' />
            </td>
        </tr>
        <tr>
            <td style="padding-left: 15px;">
                Code:<asp:Label ID="lblItemCode" runat="server" Text='<%# Eval("ItemCode") %>' />
            </td>
        </tr>
        <tr>
            <td id="tdPrice" runat="server" style="padding-left: 15px;">
                <%--Price: Rs:<asp:Label ID="lblPrice" runat="server" 
Text='<%# Eval("Price") %>' />--%>
            </td>
        </tr>
        <tr>
            <td id="tdOffer" runat="server" style="padding-left: 15px;">
                <%--<asp:Label ID="lblOfferPrice" runat="server" 
Text='<%# Eval("OfferPrice") %>' />--%>
            </td>
        </tr>
    </table>
    <table width="100%">
        <tr>
            <td>
                Qty :
                <asp:TextBox ID="txtQnty" runat="server" Text="1" CssClass="QtyTextBox" />
            </td>
            <td style="text-align: left;">
                <asp:ImageButton ID="btnAddToCart" runat="server"
                    ToolTip="Add To Cart" CommandName="AddToCart" />
            </td>
            <td style="text-align: right;">
                <asp:Button ID="Button1" ToolTip="View Details" runat="server" Text="Details" 
                    CommandName="ViewDetails" />
            </td>
        </tr>
        </table>
    </div>
</ItemTemplate>
<EmptyDataTemplate>
    <div style="text-align: left; padding: 6px 0px 0px 6px;
        font-family: Verdana;">
        No items found</div>
</EmptyDataTemplate>
</asp:ListView>

Main events provided by ListView Control are OnItemDataBound and OnItemCommand events. We implemented events OnItemCommand and OnItemDataBound for doing something with the data which are bounded to listview control. OnitemDatabound event fired once the data are binding to each control in the listview. OnItemDataCommand event fired once the button or other server control clicked by user, we have to mention the command name for the control like button we mentioned above. So we can identify that which control in the listview clicked by user by by checking this command name.

OnItem DataBound Event in ListviewControl

Here we are assigning image url to img control in the listview control and all particular data manipulation can be done in the event

protected void lstViewItems_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    try
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            if (dataItem.DataItem != null)
            {
                DataRowView view = (DataRowView)dataItem.DataItem;
                Image imgItem = (Image)e.Item.FindControl("imgItem");
                    imgItem.ImageUrl = view["Image"];
            }
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}

OnItemCommand Event in the ListView Control

We got controls here once the user press details button or image in the listview control. We can identify the control that a user clicked by checking the command name as follows. Then we can easily doing the coding for particular event.

protected void lstViewItems_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "ViewDetails":
    HiddenField hdItemID = (HiddenField)e.Item.FindControl("hdItemID");
    SelectedItemID = hdItemID.Value;
    break;
case "AvailableAt":
    Server.Transfer("AvailableAt.aspx");
    break;
case "AddToCart":
    List<eMallEntity.OrderDetails> shoppinCart = 
    new List<eMallEntity.OrderDetails>();
    shoppinCart = (List<eMallEntity.OrderDetails>)Session["Cart"];
    eMallEntity.OrderDetails newItem = new eMallEntity.OrderDetails();
    newItem.ItemCode = ((Label)e.Item.FindControl("lblItemCode")).Text;
    newItem.ItemID =
    int.Parse(((HiddenField)e.Item.FindControl("hdItemID")).Value);
    newItem.ItemName =
    ((HiddenField)e.Item.FindControl("hdItemName")).Value;
    newItem.Price =
    Double.Parse(((HiddenField)e.Item.FindControl("hdPriceValue")).Value);
    int qnty = 1;
    int.TryParse(((TextBox)e.Item.FindControl("txtQnty")).Text, out qnty);
    newItem.Image = ((HiddenField)e.Item.FindControl("hdItemImage")).Value;
    if (shoppinCart == null)
        shoppinCart = (List<eMallEntity.OrderDetails>)eMallBL.createDefaultCart();
    shoppinCart.Add(newItem);
    break;
}
}
Advertisements

How to implement caching in ASP.Net for optimisation

June 13, 2011 Leave a comment

Simple way to use cache in ASP.Net/C# 

Caching in ASP.Net is a very useful mechanism for developers in the optimisation part. Once we developed a website with ASP.Net, next importatnt thing that we need to consider is performance of the site. So its better to write optimised codes and techniques from the beginning of code writing. But the caching mechanism we can implemented easily even after completed the development. 

How we can optimise a website using cache in ASP.Net 

In some cases, we are displaying same results by fetching data from databases or other servers or static data to the user. As a optimisation part, we can avoid this same data visualisation which will take very long time. For achieving this, we can store this static data or dynamic data by same request Into webserver cache memory so that webserver can easily retrieve this data for the next time.

 Types of data that we can use cache mechanisam 

Cache in Static Pages : All static pages in the aspx application like ContactUs, AboutUs can be stored in cache and can be reuse once the user request again this pages. In order to cache this pages, we just include following code to the top of the static aspx pages that we are planning to apply cache.

 <%@OutputCache Duration="60" VaryByParam="none" %>

 The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET Web page’s HTML dynamically generated, and the cache repopulated with this HTML. The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method=”POST”) parameters should be used in varying what gets cached. In other words, multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or POST.

Cache in partial pages/usercontrol: Suppose we are including some usercontrols and a usercontrol’s data is static then we can apply cache mechanism for this portion. In order to achieve this , we can just include the following code in to the top of the usercontrol that we are planning to cache.

%@OutputCache Duration="60" VaryByParam="none" %

 

The problem in the usercontrol cache, we are not able to get events dispatched from user controls. If we are not dispatch any events from usercontrol to aspx page, we can use cache for the usercontrol.

Cache in dynamic pages : We can use same technique also for dynamic pages that having dynamic data according to the qery string. Eg: If a itemDetails page in a shopping site display the selected item details by getting item id from query string (mydomain.com/item.aspx?itemid=2). Here also we can cache this dynamic data using following code.

<%@OutputCache Duration="60" VaryByParam="itemid" %>

Once the query string itemid changing cache autamatically expired, otherwise page will display from cache. Cache for dynamic data : If we are listing all items in a database to a page, we can store this results of data into the cache and can be reuse for the second time. Same as we can store a variable, dataset, object, datatable etc.. into cache and reuse for the second time for the same request.

Cache[“myString”] = “String to Cache”; (Assign a string to cache)
String cacheString = Cache[“myString”]; (Retrieve string from cache)
DataTable itemsDatatable = getItems();
Cache[“dtItems”] = itemsDatatable;  (Store datatable to cache)
itemsDatatable = (DataTable)Cache[“dtItems”];  (Retrieve datatable from cache)

How to call serverside function from client side javascript in ASP.Net?

June 10, 2011 26 comments

Call ASP.Net/C# function using Javscript

Usually in ASP.net platform, server side functions (all codes written in asp.net,C#) are executing from the server side and all client side funtions (javascript,jquery,ajax) are executing from the client side. Obviously client side functions are too faster than the server side because there is no need to go upto server, will running from the browser itself.

But we are unable to written all functions in client side to get good performance. But for this technique, there is some tips can be used. What we are going to do is, we are writing a server side code in ASP.Net,C# and call these functions from client side using javascript and ajax.

Steps to Calling ServerSide method from javscript

  1. Create a aspx page with three textboxes and a button control.
  2. User enter two numbers in first two textboxes and press calculate button.
  3. We are fetching entered values and calling a serverside funtion by passing this values.
  4. In the server side function find the sum and return the result.
  5. In client side’s succes event, getting result from the server and displayed to third textbox.

Step 1 :

 Create a aspx page with controls, two textboxes for entering the numbers, one button for find the sum of number and a one more text box to display the result.

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="testWebApp.Result" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!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:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    Number1:
                </td>
                <td>
                    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Number2:
                </td>
                <td>
                    <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Sum:
                </td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSum" runat="server" Text="Sum" OnClientClick="CallSum();return false;" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Step 2  

In code behind, write a web method to access two parameters and return the result. In the function we added parameters and return the result.

protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Server side function Sum
        /// </summary>
        /// <param name="arg1">arg1</param>
        /// <param name="arg2">arg2</param>
        /// <returns>result(sum)</returns>
        [System.Web.Services.WebMethod]
        public static int Sum(int arg1, int arg2)
        {

            /* On server side we can do any thing. Like we can access the Session.
             * We can do database access operation. Without postback.
             */
            try
            {
                return arg1 + arg2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Step 3

 Create a javscript method in aspx page to get input textboxes values and call serverside function. Here itself we decalre a success and failure event, for getting the event from the server after the current function executed.

 <script language="javascript" type="text/javascript">
    <!--

        // Javascript function
        function CallSum() {
            //Get the controls
            var txt1 = $get("txt1");
            var txt2 = $get("txt2");
            var txtresult = $get("txtSum");

            //Call server side function
            PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);

            /*Server side function get the 2 arguments arg1 and arg2. We are passing txt1.value and txt2.value
            for that. OnCallSumComplete is callback function for complete successfully. OnCallSumError is callback
            function on error. txtresult is usercontext parameter.

            OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

            If server side code executed successfully then OnCallSumComplete will call.
            If server side code do not executed successfully then OnCallSumError will call.

            */
        }

        // Callback function on complete
        // First argument is always "result" if server side code returns void then this value will be null
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumComplete(result, txtresult, methodName) {
            //Show the result in txtresult
            txtresult.value = result;
        }

        // Callback function on error
        // Callback function on complete
        // First argument is always "error" if server side code throws any exception
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumError(error, userContext, methodName) {
            if (error !== null) {
                alert(error.get_message());
            }
        }

    // -->
    </script>

Project is ready for call server sided functions from client side using javascript. Run the application and enter two numbers in first and second textboxes then press calculate button, the we can show that result is displayed in third box without any page postback. If we enterd alphabets instead of numbers, from the server it will happening error and ‘failure’ event occurred in the javascript will alert the details of the error.

How to handle usercontrol events in aspx page?

June 10, 2011 4 comments

Raise a event from usercontrol to aspx page 

ASP.Net  applications with user controls need to commucinate with usercontrols and aspx page. We can sent parameter as properties to usercontrol from aspx page and also we can access the usercontrol controls from aspx page. This post describing how we can communicate between aspx page and usercontrols. 

Multiple usercontrols in a single aspx page communication

 Here we consider the scenario, we have two usercontrols in a single page and need to communicate between usercontrols through aspx page. 

Usercontrol1

Create a usercontrol with name usercontrol1 and having login screen with login button. The usercontrol having two textboxes one for username, and other for pasword and a textbox for login. 

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs"
    Inherits="testWebApp.UserControl1" %>
<div>
    username
    <asp:TextBox ID="txtUserName" runat="server" />
    Password
    <asp:TextBox ID="txtPassword" runat="server" />
    <asp:Button ID="btnLogin" runat="server" onclick="btnLogin_Click" Text="Login" />
</div>
 

 UserControl 2

Create a usercontrol with name usercontrol2 and having single label control to display login name. 

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl2.ascx.cs" Inherits="testWebApp.UserControl2" %> 
<asp:Label ID="lblUserName" runat="server" Text="This is from UserControl2" />

 ASPX page

Create a aspx page with name main.aspx page and included above user controls and also created a label control for displaying current username

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="main.aspx.cs" Inherits="testWebApp.main" %>
 <%@ Register Src="~/UserControl1.ascx" TagName="uc1" TagPrefix="uc" %>
<%@ Register Src="~/UserControl2.ascx" TagName="uc2" TagPrefix="uc" %>
<!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>
        <asp:Label runat="server" ID="lblUserName" Text="This is from Aspx Page" />
        <uc:uc1 runat="server" ID="uc1" />
        <uc:uc2 runat="server" ID="uc2" />
    </div>
    </form>
</body>
</html>

 When we enter username and press enter, will raise a event from usercontrol to aspx page, means from usercontrol1 to main aspx. At the same time we need to display username in the aspx page. For achieving that first we store the username in the usercontrol itself as properties and raise a event from usercontrol to aspx page. To raise a event to parent page, declared a Event Handler and will call the event handler once the user press the button.

 Code behind of UserControl1 

public partial class UserControl1 : System.Web.UI.UserControl
    {
        public EventHandler loginClickArgs;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserName = txtUserName.Text;
            loginClickArgs(sender,e);
        }

        private string _username;
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }
    }
 

Codebehind main ASPX page 

To get event from usercontrol in aspx page, we need to initialise the event in the page load and create a funtion for curresponding event. The username entered in the usercontrol1 will get from the usercontrol1 properties. From here we assigned the label text by taking the value from usercontrol1.

     public partial class main : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            uc1.loginClickArgs += new EventHandler(login_Click);
        }

        private void login_Click(object sender, EventArgs e)
        {
            lblUserName.Text = "Hi " + uc1.UserName + ", Welcome to ASPX Page";
            uc2.UserName = uc1.UserName;
            uc2.displayMessage();
        }
    }
 

 Code behind userControl2

To call a function in usercontrol from aspx page, we need to declare a function as public in the usercontrol. If we need any dynamic parameter to the function, we need to create a properties in the usercontrol and set this from the aspx page. Here we are setting the username from the usercontrol1 to usercontrol2 from main aspx page. Then calling a public function displaymessage() in the usercontrol2 from the aspx page.

 public partial class UserControl2 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void displayMessage()
        {
            lblUserName.Text = "Hi " + UserName + ", This message from usercontrol";
        }

        private string _username;
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }
    } 

As a conclution, we have done following thing : we raise a event from a usercontrol to parent aspx page

(Event delegation from user control to aspx page in ASP.NET,C#), access the usercontrol event from aspx page, access the usercontrol variable from aspx page, call usercontrol’s public function from aspx page, setting a usercontrol’s variable from aspx page. That means we discussed all about usercontrol and aspx page communication.

How to change master page navigation style from aspx page?

June 8, 2011 2 comments

How to include site navigation in master page?

A Master page in most of the ASP.Net applications conatin common contents in the site like header,footer,left menus etc.. But some of the time we need to communicate with master page content from aspx page for changing style, displaying current user details etc. 

Here we are explaining how to change navigation div style in masterpage from the aspx page as per the page visits. Here we are having navigation divs Home,AboutUS,ContatcUS etc.. All this divs are in the master page. All the div background color is white and once we visited the particular page we need to set curresponding navigation div background color to blue. The steps explaining also how to access master page control from aspx page.

 Steps to change style of master page from aspx page 

Step 1 : For first step creating a master page with common header contents with navigations divs. Like below mentioned image, we have created 4 divs and back ground color is gray, and active page has background color is blue. CSS for menu and active menu is also given below. 

ASPX page 

<div class='<%= HomeMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="Home.aspx”">Home</a></div>
                </div>
                <div class='<%= ShopeMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="Products.aspx">Shope</a></div>
                </div>
                <div class='<%= ContactUsMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="ContactUs.aspx">Contact Us</a></div>
                </div>
                <div class='<%= AboutUsMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="AboutUs.aspx">About Us</a></div>
                </div> 

CSS Style 

.menubutton
{
background-color:#f2f2f2;
}
.menubuttonselect
{
background-color:#507cd1;
}
 

Step2 : Creating properties for each div navigation menu for style. 

private string _homeMenu = "menubutton";
        public string HomeMenu
        {
            get { return _homeMenu; }
            set { _homeMenu = value; }
        }

        private string _shopeMenu = "menubutton";
        public string ShopeMenu
        {
            get { return _shopeMenu; }
            set { _shopeMenu = value; }
        }

        private string _contactUsMenu = "menubutton";
        public string ContactUsMenu
        {
            get { return _contactUsMenu; }
            set { _contactUsMenu = value; }
        }

        private string _aboutUsMenu = "menubutton";
        public string AboutUsMenu
        {
            get { return _aboutUsMenu; }
            set { _aboutUsMenu = value; }
        }
 

Step 3 :

 In load event of every aspx page, we need to set active menu property of the master page as per the browsing page. Suppose when a user browses contact us page we need to set ‘ContactUsMenu’ to active class from the aspx page. 

protected void Page_Load(object sender, EventArgs e)
{ 
 Master.ContactUsMenu = "menubuttonselect";
}

How to set favicon for website page?


What is a favicon ? 

It’s a good practice to add a favicon to the website. Favicon is nothing but it is a small icon associated with a particular website, and typically displayed in the address bar of a browser viewing the site. A favicon (short for favorites icon), also known as a website icon, shortcut icon, url icon, or bookmark icon is a 16×16, 32×32 or 64×64 pixel square icon associated with a particular website or webpage. 

How to set favicon for websites? 

Setting favicon to the website is very simple, can be acieved by simple steps. First of all we need to create fav icon which should be associated with our website, size 16×16, 32×32 or 64×64 and uploaded to our website (commonly inside images folder). 

In the second step we have to put below codes inside the header tag of all webapages in our site. After that if you browse your web page you can see that your favicon is showing in address bar. Eg : www.supershope.com

 <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />

How to show error page in ASP.Net


Handle custom errors in ASP.Net

Once the ASP.Net application is ready to launh to customers, there is no need to show the error details in to the web page when any errors occurred. In this scenario we can show our customised page with details like “Server is busy now please after some time” to the customer. At the same time we can store error details to database or txt file for future reference for developers. For customise errors in the ASP.Net we need to do some settings in the web.config file.

 Settings on web.config to show error page 

<customErrors mode="On" defaultRedirect="error.aspx">
<error statusCode="404" redirect="404Error.aspx"/>
</customErrors> 

The above code should be placed in the web.config file for handling custom errors (mode=”On”). Also we can handling particular erros with error code with appropriate error page. In above mentioned code, if a user request a page that is not in the server, 404 error is occurred then page is automatically direct to 404Error.aspx. If any other errors occurred, it will show web page error.aspx. In the same way we can handle any type of error with the status code, with the appropriate web page.

%d bloggers like this: