Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Sunday, October 17, 2010

How to show budy cursor while processing a request


Please note this example deos not work in Mozilla Firefox.

Demo:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        public void Save(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
            this.lblLastUpdate.Text = DateTime.Now.ToString("hh:mm:ss");
        }
    </script> 
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="pageScriptManager">
        </asp:ScriptManager>
        <script language="javascript" type="text/jscript">
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
                document.body.style.cursor = "auto";
            });
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function () {
                document.body.style.cursor = "wait";
            });
        </script>
        <asp:UpdatePanel runat="server" ID="upnlInsertContent">
            <ContentTemplate>                
                <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
                <asp:Label runat="server" ID="lblLastUpdate" />
            </ContentTemplate>
        </asp:UpdatePanel>    
    </form>
</body>
</html>

Friday, October 01, 2010

How to handle asynchronous request errors and reqeust end event in JavaScript

<script language="javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        if (args.get_error() != undefined) {
            if ((args.get_response().get_statusCode() == '12007')
                 || (args.get_response().get_statusCode() == '12029')) {
                alert('Time-out Error');
                args.set_errorHandled(true);
            }
        }
    }
</script>

Saturday, September 18, 2010

How to dynamically load a DropDownList using jQuery and JSON


Demo:

If you want to load dropdownlist on the spot, you can use onmouseover and onfocus events to respond both mouse and keyboard. I would use jQuery + JSON to load dropdownlists dynamically which will be the ideal case. I have used GenericHander.ashx to servie all the dropdownlist data.

But the problem is when you add/change dropdown list items in the client side using JavaScripts, in the very next postback, it fails the EventValidation I am not going to discuss about this issue here. But I have a seperate article with detailed information how to overcome this issue. So I have used used AddableDropDownList for this example.

Other key point is, you have to remember load items to the list only the first page load inside the JavaScript. Because once you added items to the list they will get listed in AddableDropDownList.Items collection and they will be in ViewState for subsequent postbacks. So no need to load on each postback.

Markup - Test Page
<%@ Register Assembly="ActiveTest" Namespace="ActiveTest" TagPrefix="asp" %>
<%@ Page Language="C#" %>
<html>
<head runat="server">
    <style type="text/css">
        .countries { width:150px; }
    </style>        
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var countriesLoaded = false;
        function load(key) {
            if ('<%=this.IsPostBack %>' != 'True') {
                if (key == 'countries' && countriesLoaded) return;
                var target = $("." + key);
                target.attr("disabled""disabled");
                $.getJSON('GenericHandler.ashx?q=' + key, function (data) {
                    for (i = 0; i < data.length; i++)
                        AddListItem(data[i].value, data[i].text, '<%=AddableDropDownList1.ClientID %>');
                    countriesLoaded = true;
                    target.removeAttr("disabled");
                });
            }
        }
    </script>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.IsPostBack)
                this.lblLstPostBackTime.Text = 
                    string.Format("Last posted pack at: {0}"DateTime.Now.ToString("hh:mm:ss"));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:AddableDropDownList
            ID="AddableDropDownList1" 
            runat="server" 
            CssClass="countries" 
            onmouseover="javascript:load('countries')" 
            onfocus="javascript:load('countries')">
            <asp:ListItem>Please Select</asp:ListItem>
        </asp:AddableDropDownList>
        <hr />
        <p>Event validation enabled </p>   
        <asp:Button runat="server" ID="btnSave" Text="Save" /> 
        | <asp:Label runat="server" ID="lblLstPostBackTime" />
    </form>
</body>
</html>

Generic Handler:
public class GenericHandler : IHttpHandlerIRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        StringBuilder data = new StringBuilder();
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.Clear();
        data.Append("[");
        string q = context.Request.QueryString.Get("q");
        switch(q)
        {
            case "countries":
                for (int i = 0; i < 1000; i++)
                    data.AppendFormat("{{\"value\":\"Value{0}\", \"text\":\"Text{0}\"}},", i);
                break;
        }
        data.Append("]");            
        string json = data.ToString();
        if (json.EndsWith(",]")) json = json.Remove(json.Length - 2, 1);
        context.Response.ContentType = "application/json";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.Write(json);
        context.Response.Flush();
        context.ApplicationInstance.CompleteRequest();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Wednesday, August 25, 2010

How to defer long running data binding from initial page load - Late Binding

We can use wrap data bound conrols with an update panel and ignore the databound controls for initial page load
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
    {
        ///
        /// Long running data binding operations
        ///
    }
}
Then once page loaded with a message 'Loading page ... please wait...' then fire up a asyc requst the server representing the update panel to bind data bound controls inside the update panel.
Demo:
Example:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ///
            /// if page does only a asyc postback 
            /// execute my long running operation.
            ///
            if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
            {
                ///
                /// Just a fake dealy
                ///
                for (int i = 0; i < 5; i++)
                    System.Threading.Thread.Sleep(1000);
                ///
                /// Bind the item list
                /// 
                List<object> items = new List<object>();
                for (int i = 0; i < 10; i++)
                    items.Add(new { Item = "Item " + i });
                this.grvItems.DataSource = items;
                this.grvItems.DataBind();
                ScriptManager.RegisterStartupScript(
                    this.grvItems,
                    this.grvItems.GetType(),
                    this.grvItems.ID,
                    string.Format("document.getElementById('{0}').style.display = 'none';", 
                        this.pnlUpdateProgess.ClientID),
                    true);
            }
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="PageScriptManager">            
        </asp:ScriptManager>
        <h1>Late binding example</h1>
        <hr />
        <asp:Panel runat="server" ID="pnlUpdateProgess">
            <span>Loading page... please wait...</span>
        </asp:Panel>
        <asp:UpdatePanel runat="server" ID="upnlContents">
            <ContentTemplate>
               <asp:GridView runat="server" ID="grvItems" /> 
            </ContentTemplate>            
        </asp:UpdatePanel>
        <script language="javascript" type="text/javascript">
            __doPostBack('<%= this.upnlContents.UniqueID %>''');
        </script>
    </form>
</body>
</html>

How to update small portion of a website using jQuery and ajax

We can use Generic Hanlder to render the response for the ajax request.
Example

Page
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
            function UpdateTime() {                
                $.ajax({
                    url: "GenericHandler.ashx",
                    success: function (data) {
                        $(".LabelTime").text(data);
                    }
                });
            }
 
            $(document).ready(function () {
                setInterval('UpdateTime()', 3000);
            });
    </script>
    <script runat="server">        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.lblTime.Text = DateTime.Now.ToString("hh:mm:ss");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label runat="server" ID="lblTime" CssClass="LabelTime" />
    </form>
</body>
</html>
GenericHandler.ashx
public class GenericHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {            
        context.Response.Write(DateTime.Now.ToString("hh:mm:ss"));
        context.Response.Flush();
        context.Response.End();
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Saturday, July 10, 2010

How to implement date range validator - Asp.net

<%@ Page Language="C#" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <asp:TextBox ID="Txtfrom" runat="server" CssClass="dataField" Width="120px"></asp:TextBox>
        <asp:calendarextender id="Txtfrom_CalendarExtender" runat="server" enabled="True"
             targetcontrolid="Txtfrom"
             cleartime="True" 
             todaysdateformat="dd/MM/yyyy" 
             format="dd/MM/yyyy" />
        <asp:TextBox 
             ID="Txtto" 
             runat="server" 
             CssClass="dataField" />
        <asp:calendarextender
            id="Txtto_CalendarExtender" 
            runat="server" 
            enabled="True" 
            targetcontrolid="Txtto"
            format="dd/MM/yyyy" 
            todaysdateformat="dd/MM/yyyy" />
        <asp:CompareValidator 
            ID="CompareValidator2" 
            runat="server" 
            ControlToCompare="Txtfrom"
            ControlToValidate="Txtto" 
            ErrorMessage="from date should not greater then to date"
            Operator="GreaterThan" 
            Type="Date" />
         <asp:Button runat="server" ID="btnPostback" Text="Postback" />
    </div>
    </form>
</body>
</html>

How to bulid a simple cascade dropdownlist - Asp.net

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        protected void SelectSubCategoies(object sender, EventArgs e)
        {
            string s = this.ddlCategories.SelectedValue;
            this.ddlSubcategories.Items.Clear();
            if (s.Equals("-1"))
                this.ddlSubcategories.Enabled = false;
            else
            {
                this.ddlSubcategories.Enabled = true;
                for (int i = 0; i < 10; i++)
                    this.ddlSubcategories.Items.Add(new ListItem(s + " Sub Cateogry"));
            }
        }
    </script>
</head>
<body>
    
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server" ID="upnlCascadeDropdown">
             <ContentTemplate>
                  <asp:DropDownList runat="server" ID="ddlCategories" 
                            AutoPostBack="true" OnSelectedIndexChanged="SelectSubCategoies">
                       <asp:ListItem Value="-1">Select</asp:ListItem>
                       <asp:ListItem Value="A">Category A</asp:ListItem>
                       <asp:ListItem Value="B">Category B</asp:ListItem>
                       <asp:ListItem Value="C">Category C</asp:ListItem>
                       <asp:ListItem Value="D">Category D</asp:ListItem>
                  </asp:DropDownList>
                  <asp:DropDownList runat="server" ID="ddlSubcategories" 
                                                Enabled="false"></asp:DropDownList>
             </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Monday, June 28, 2010

How to show the progress of long running operation - Simple Example

Demo:
This article demonstrates how to show the progress of a long running operation using simple label text. But you can add a spning progress indicator and make it much fancy.

Screenshots:


Markup:
<%@ Page Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="Test.aspx.cs" 
    Inherits="ActiveTest.Test"  %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .Hide { display:none; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Button runat="server" ID="btnDoTask" Text="Do Task" OnClick="Button1_Click" />
                <asp:Label runat="server" ID="lblMessage" />
                <asp:Button runat="server" ID="btnHidden" UseSubmitBehavior="false" CssClass="Hide" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>
 Code behind:
public partial class TestPage
{
    private string script = @"setTimeout(""__doPostBack('{0}','')"", 5000);";
    public bool Processing
    {
        get { return (bool)(Session["Processing"] ?? false); }
        set { Session["Processing"] = value; }
    }
    public bool Completed
    {
        get
        {
            return (bool)(Session["Completed"] ??
                (Session["Completed"] = true));
        }
        set { Session["Completed"] = value; }
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (this.Processing)
        {
            this.lblMessage.Text = "Processing... Please wait...";
            ScriptManager.RegisterStartupScript(thisthis.GetType(),
                this.GetType().Name, string.Format(script, this.btnHidden.ClientID),
                true);
        }
        else
        {
            if (!this.Completed)
            {
                lblMessage.Text = "Processing is complete";
                this.Completed = true;
            }
            else
                lblMessage.Text = string.Empty;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(new ThreadStart(SomeLongOperation));
        thread.Start();
        this.lblMessage.Text = "Processing... Please wait...";
        this.Processing = true;
        ScriptManager.RegisterStartupScript(thisthis.GetType(),
            this.GetType().Name, string.Format(script, this.btnHidden.ClientID), true);
    }
    void SomeLongOperation()
    {
        this.Completed = false;
        for (int i = 0; i < 20; i++)
            Thread.Sleep(1000);
        this.Processing = false;
    }
} 

Thursday, June 17, 2010

How to access Page Method using Script Manager - Asp.net

Demo:
Using asp.net ScriptManger setting EnablePageMethods=true we can access WebMethods
  1. Method should be static
  2. Set ScriptManager EnablePageMethods=true
  3. Use java script PageMethods.CheckUserName(value, OnSucceeded, OnFailed);
  4. OnSucceeded - function to executed on success
  5. OnFailed - function to executed on fail
Please see the example below
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        [System.Web.Services.WebMethod]
        public static string CheckUserName(string struname)
        {
            string uerror = string.Empty;
            try
            {
                bool userExists = false;
                ///
                /// Check if user exists
                ///
                if (struname.ToLower().Equals("bob")) userExists = true;
                if (userExists) uerror = "UserName already exists!";
                else uerror = "UserName available!";
            }
            catch
            {
                uerror = "Error";
            }
            return uerror;
        }        
    </script>
    <script type="text/javascript">
        function checkUsername(soruce) {
            var valueuseremail = soruce.value;
            if (valueuseremail != "") {
                PageMethods.CheckUserName(valueuseremail, OnSucceeded, OnFailed);
            }
        }
        function OnSucceeded(result, usercontext, methodName) {
            document.getElementById('<%= lblValidationResult.ClientID %>').innerHTML = result;
        }
        function OnFailed(error, userContext, methodName) {
            alert("Error");
        }
     
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager 
            ID="ScriptManager" 
            runat="server" 
            EnablePageMethods="true" />
        <asp:TextBox 
            ID="txtEmail" 
            runat="server" 
            onkeyup="checkUsername(this);">
        </asp:TextBox>
        <asp:Label 
            ID="lblValidationResult" 
            runat="server">
        </asp:Label>
    </form>
</body>
</html>

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...