Tuesday, July 20, 2010

How to perform a postback using JavaScript - Asp.net

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <title></title>
    <style>
        .Hide { display:none; }
    </style>
    <script runat="server">
        protected void DoSomething(object sedner, EventArgs e)
        {
            Response.Write(DateTime.Now.ToString("hh:mm:ss"));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button runat="server" ID="btnHidden" CssClass="Hide" 
            UseSubmitBehavior="false" OnClick="DoSomething" />      
 
        <a href="javascript:__doPostBack('<%=btnHidden.UniqueID %>', '')">Invoke Button</a>
    </form>
</body>
</html>

How to implement a session varable which is available since the first execution cycle - Asp.net

public partial class Test : Page
{
    private string item;
    public string Item
    {
        get
        {
            if (!string.IsNullOrEmpty(item)) return item;
            return (item = (string)(Session["item"] ?? string.Empty));
        }
        set
        {
            Session["Item"] = this.item = value;
        }
    }
 
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.Item = DateTime.Now.ToString("hh:mm:ss");
    }
    protected override void OnLoad(EventArgs e)
    {
        this.Response.Write(this.Item);
    }
}

Other Types:
int? time;
public int Time
{
    get
    {
        if (this.time.HasValue) return time.Value;
        return (time = (int)(Session["time"] ?? 0)).Value;
    }
    set
    {
        Session["time"] = this.time = value;
    }
}
bool? isLive;
public bool IsLive
{
    get
    {
        if (this.isLive.HasValue) return isLive.Value;
        return (isLive = (bool)(Session["isLive"] ?? false)).Value;
    }
    set
    {
        Session["isLive"] = this.isLive = value;
    }
}

Sunday, July 18, 2010

How to build a templated control - Asp.net

[ParseChildren(true)]
public class CustomControl : WebControl
{
    public ContentItem Item { getset; }
 
    [PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateContainer(typeof(ContentItem))]
    public ITemplate ContentTemplate { getset; }
 
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.CreateControlHeirarchy();
 
    }
    public void CreateControlHeirarchy()
    {
        this.Item = new ContentItem();
        this.Controls.Add(Item);
        this.ContentTemplate.InstantiateIn(this.Item);
    }
 
}
 
public class ContentItem : WebControlINamingContainer
{
}

Saturday, July 17, 2010

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster - Asp.net, IIS

Machine Authentication Check, or MAC
Machine authenication check (MAC) is there to ensure that the request received from the computer is same as the computer which response transmitted out.

1. ViewState Timeout:

Cause:
This situation is due to shutting down the application pool work process after some ideal timeout.
Solution:
IIS6:
  1. Open IIS - run inetmgr
  2. View application pools
  3. Locate your web application's application pool
  4. Right click and Select properties
  5. Select performanace tab
  6. Uncheck the ideal timeout [shutdown worker process after being idle for...] option
IIS7
  1. Open IIS - run inetmgr
  2. Click on application pools node
  3. Locate your web application's application pool
  4. Rightclick and select Advanace Settings
  5. Set the Idle Time-out(minutes) property to 0 or I would increate the value to 30 minutes or an hour (60 mins)
For more information please refer this article

2. ViewState Validation Fails

Please refer this article for more information

How to validate set of asp.net controls based on a condition - Asp.net

Cause: While having validators disabled in the clientside still get Page.IsValid property is false.

Explanation:
Asp.net validation controls have dual validation mecanisum. One is client side, which is optional and the second one is server side validation, which is mandatory. First in the client side if the clientside validation fails framework block the postback. However clientside validation result will not carried over to the codebehind to populate page.IsValied property but asp.net page life-cycle validate all the validation controls in the serverside and populate the Page.IsValid property. In this senario it does not care that you have set the enable/disable in the client side. Page execution talke all the validators in to account and validate. So it is needed to implement the same logic which you have in client side in the serverside as well and enable disable + set validator.IsValid property to true/false accordingly

However there is a easy way to achive your objective. More framework friendly
  1. Disable client side validation for all your validators.
  2. On page load event enable disable validators accorting to radio button selection
 Here is an example
<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title></title>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.rblOption.SelectedValue.Equals("No"))
            {
                this.rvalName.IsValid = true;
                this.rvalName.Visible = false;
            }
            else
                this.rvalName.Visible = true;
        }
        protected void Save(object sender, EventArgs e)
        {
            this.Page.Validate();
            bool valid = this.Page.IsValid;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList runat="server" ID="rblOption" AutoPostBack="true">
            <asp:ListItem Value="Yes" Selected="True">Yes</asp:ListItem>
            <asp:ListItem Value="No">No</asp:ListItem>
        </asp:RadioButtonList>
        <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
        <asp:RequiredFieldValidator runat="server" ID="rvalName" ControlToValidate="txtName" ErrorMessage="*Required" EnableClientScript="false" />
        <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" />
    </form>
</body>
</html> 

How to add an existing silverlight application to Asp.net Web Application - Asp.net, Silverlight

1. Select web project right click and select properties.

2. Select Silverlgiht Application tab

3. Select your Silverlight Application from the list (in this case only one available)

4. Select Add

5. From the next dialogue select check add a test page option (recommended not mandatory) and then click on Add

Tuesday, July 13, 2010

How to change the Assembly Name and Default Namespace of an asp.net Web-Application - Asp.net, Visual Studio

1.Rightclick on the Web-Applicaiton

2.Select Application Tab and Specify Default Namespace and Assembly Name at the very top of the page

Monday, July 12, 2010

How to change the status code of the Page Not Found page to 404 - Asp.net

public partial class PageNotFound : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Response.Buffer = true;
        Response.StatusCode = 404;
        Response.Status = "404 Not Found";
    }
}

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>

How to auto update a segment a page - Asp.net

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .Hide {display:none; }
    </style>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ScriptManager.RegisterStartupScript(
                thisthis.GetType(), 
                this.GetType().Name, 
                string.Format("setTimeout(\"__doPostBack('{0}','')\", 5000)", 
                this.btnPostback.UniqueID), 
                true);
            this.lblUpdatedOn.Text = DateTime.Now.ToString("hh:mm:ss");            
        }
        protected void AutoPostback(object sender, EventArgs e)
        {
        }
    </script>
</head>
<body>
    
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server" ID="upnlCascadeDropdown">
             <ContentTemplate>
                Last Updated on: <asp:Label runat="server" ID="lblUpdatedOn" />
                <asp:Button CssClass="Hide" 
                    runat="server" 
                    ID="btnPostback" 
                    OnClick="AutoPostback" 
                    UseSubmitBehavior="false" />
             </ContentTemplate>
        </asp:UpdatePanel>
    </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...