Saturday, July 24, 2010

How to use object oriented concepts (classes and objects) in a asp.net web page - C# , Asp.net

    public partial class Test : Page
    {
        private Car car1, car2;
 
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            /// 
            /// new car object
            /// 
            car1 = new Car();
            /// 
            /// new car object with inline constructor
            /// 
            car2 = new Car()
            {
                Color = "Blue",
                Price = 45000,
                MaxSpeed = 200,
                Bhp = 300
            };
            /// 
            /// set properties
            /// 
            car1.Color = "Black";
            car1.Price = 25000;
 
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            /// 
            /// Call methods
            /// 
            car1.Drive();
            car1.Reverse();
        }
        protected void Button_Clicked(object sender, EventHandler e)
        {
            /// 
            /// Call methods
            /// 
            car1.Drive();
            car1.Turn();
            car1.Drive();
            /// 
            /// Call methods
            /// 
            car2.Reverse();
            car2.Turn();
            car2.Drive();
            car2.Turn();
            car2.Drive();
        }
    }
    public class Car
    {
        /// <summary>
        /// Automatic Properties
        /// </summary>
        public string Color { get; set; }
        public double Price { get; set; }
        public int MaxSpeed { get; set; }
        public int Bhp { get; set; }
 
        /// <summary>
        /// Construcotrs
        /// </summary>
        public Car()
        {
            this.Color = "Red";
            this.Price = 30000;
            this.MaxSpeed = 140;
            this.Bhp = 335;
        }
 
        public void Drive()
        {
            ///
            /// Implement how to drive
            /// 
        }
        public void Reverse()
        {
            ///
            /// Implement how to reverse
            ///
        }
        public void Turn()
        {
            ///
            /// Implement how to turn
            ///
        }
    }

How to add/get a list from Cache/ Clear Cache - Asp.net

public class CacheWrapper
{
    public static void AddAll<T>(List<T> cacheObjectList, string keyPrefix) where T : class
    {
        foreach (T item in cacheObjectList)
            HttpContext.Current.Cache.Insert(
                string.Concat(keyPrefix, 
                cacheObjectList.IndexOf(item).ToString()), 
                item);
    }
    public static List<T> GetAll<T>(string keyPrefix) where T : class
    {
        List<T> items = new List<T>();
        IDictionaryEnumerator cacheContents = HttpContext.Current.Cache.GetEnumerator();
        while (cacheContents.MoveNext())
        {
            string key = cacheContents.Key.ToString();
            if (key.Contains(keyPrefix) && HttpContext.Current.Cache[key] is T)
                items.Add(HttpContext.Current.Cache[key] as T);
        }
        return items;
    }
    public static void Clear()
    {
        IDictionaryEnumerator cacheContents = HttpContext.Current.Cache.GetEnumerator();
        while (cacheContents.MoveNext())
            HttpContext.Current.Cache.Remove(cacheContents.Key.ToString());
    }
}

Usage
List<string> items = new List<string>();
///
/// Add to cache
///
items.Add("Category 1");
items.Add("Category 2");
items.Add("Category 3");
items.Add("Category 4");
items.Add("Category 5");
 
CacheWrapper.AddAll<string>(items, "Category");
///
/// Get from the cache
///
items = new List<string>();
items = CacheWrapper.GetAll<string>("Category");

Friday, July 23, 2010

How to upload a file – Asp.net

When uploading a file there are two main concerns.
  1. Do we have correct permissions to the directory? Asp.net work process should have write permissions to the upload directory in-order to save the uploaded file.
  2. The file size that we try to upload, does it exceed the allowed request limit of by the .net runtime? This example allows requests smaller than 2 MB (2024 KB)
<system.web>
  <httpRuntime maxRequestLength="2024" />
In this case provide a suitable error message for error 404.13
Here is a complete example to demonstrate how to upload a file using asp.net
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head2" runat="server">
        <script runat="server">
            string uploadPath = "Uploads";
            public void Save(object sender, EventArgs e)
            {
                if (this.fuFile.HasFile)
                {
                    string filepath = Server.MapPath(Path.Combine(this.uploadPath, this.fuFile.FileName));
                    if (!File.Exists(filepath))
                    {
                        this.fuFile.SaveAs(filepath);
                        this.lblResults.Text = "File uploaded successfully";
                    }
                    else
                        this.lblResults.Text = "File already exists";
                }
                else
                    this.lblResults.Text = "Please slect a file";
            }        
        </script>
    </head>
    <body>
        <form id="form2" runat="server">
        <div>
            <asp:FileUpload runat="server" ID="fuFile" />
            <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
            <asp:Label runat="server" ID="lblResults" />
        </div>
        </form>
    </body>
</html> 

Thursday, July 22, 2010

How to create controls in a button event - Asp.net

If you add dropdownlist and texbox in button click, then when you fire up another event, inside the second event first button event (control creation logic) wont get fired. So there will not be textbox and dropdownlist in the next postback. In-order to use viewstate you need to create your dynamic controls at least in the page init method.
For this kind of senario you can use hidden field to determine the control creation button clicked and you need to find wihich button clicked in the page init method

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        protected bool ControlsCreated { get; set; }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            string controlsCreated = this.Request.Form[this.hdnControlsCreated.UniqueID];
            if (!string.IsNullOrEmpty(controlsCreated))
                this.ControlsCreated = bool.Parse(controlsCreated);
            if (this.IsPostBack)
            {
                string uniqueId = this.Request.Form["__EVENTTARGET"];
                 
                if (!string.IsNullOrEmpty(uniqueId))
                {
                    string[] parts = uniqueId.Split("$".ToCharArray());
                    string id = parts[parts.Length - 1];
                    if (this.btnCreateControls.ID.Equals(id))
                        this.ControlsCreated = true;                       
                }
            }
            if (this.ControlsCreated)
            {
                List<string> items = new List<string>();
                items.Add("Item 1");
                items.Add("Item 2");               
                DropDownList ddlItems = new DropDownList();
                ddlItems.ID = "ddlItems";
                ddlItems.AutoPostBack = true;
                ddlItems.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
                ddlItems.DataSource = items;
                this.phControls.Controls.Add(ddlItems);
                TextBox txtName = new TextBox() { ID = "txtName" };
                this.phControls.Controls.Add(txtName);
            }
        }
 
        private void SelectedIndexChanged(object sender, EventArgs e)
        {
             
        }
        private void GetValues(object sender, EventArgs e)
        {
            string result = string.Empty;
            TextBox txtNames = this.FindControl("txtName") as TextBox;
            DropDownList ddlItems = this.FindControl("ddlItems") as DropDownList;
            if (txtNames != null)
                result += string.Format(" Textbox Value: {0}", txtNames.Text);
            if (ddlItems != null)
                result += string.Format(" Dropdownlist Value: {0}", ddlItems.SelectedItem.Value);
            this.lblResults.Text = result;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.DataBind();
            this.hdnControlsCreated.Value = this.ControlsCreated.ToString();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel runat="server" ID="pnlContainer">
            <asp:Button
                runat="server"
                ID="btnCreateControls"
                Text="Create Controls"
                UseSubmitBehavior="false" />
            <asp:Button
                runat="server"
                ID="Button1"
                Text="Get Values"
                OnClick="GetValues" />
            <hr />
            <asp:PlaceHolder runat="server" ID="phControls"></asp:PlaceHolder>
            <asp:Label runat="server" ID="lblResults" />
            <asp:HiddenField runat="server" ID="hdnControlsCreated" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>
 
 

How to register a startup (document).ready(..) script only for the first page load - Asp.net, JQuery, JavaScripts

public partial class Test : Page
{
    private string script = @"
        $(document).ready(function () {
            
        });
    ";
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (!this.Page.IsPostBack)
            this.Page.ClientScript.RegisterStartupScript(
                this.GetType(), 
                this.GetType().Name, 
                this.script, 
                true);
    }
}

Wednesday, July 21, 2010

How to run a exe file using JavaScripts - JavaScripts

<script language="javascript">
    function runApp() {
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var shell = new ActiveXObject("WScript.shell");
        shell.run("d:\\tempfile\\test.exe", 1, true)
    }
</script>

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 { get; set; }
 
    [PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateContainer(typeof(ContentItem))]
    public ITemplate ContentTemplate { get; set; }
 
    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 : WebControl, INamingContainer
{
}

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> 

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