Search This Blog

Wednesday 30 May 2012

How to implement caching in ASP.Net for optimisation


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

Wednesday 23 May 2012

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


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.

Wednesday 16 May 2012

How to handle usercontrol events in aspx page?


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 usercontrol and aspx page communication.