Thursday, June 17, 2010

How to create a popup dialogue without using AJAX or java scripts - Asp.net

Screenshots:

There are some occations that we need to create popup messages and dialogues without using JavaScripts. (AJAX or JQuery). This article demonstrates how to show a dialogue or a popup using CSS and Asp.net
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <style type="text/css">
        div.DialogueBackground 
        { 
            position:absolute; 
            width:100%; 
            height:100%; 
            top:0; 
            left:0; 
            background-color:#777; 
            opacity:0.5;
            filter: alpha(opacity=50); 
            text-align:center; 
        }
        div.DialogueBackground div.Dialogue 
        {
            width:300px; 
            height:100px; 
            position:absolute; 
            left:50%; 
            top:50%; 
            margin-left:-150px; 
            margin-top:-50px; 
            border:solid 10px #aaa; 
            background-color:#fff; 
        }
    </style>
    <script runat="server">
        public void DialogueAccept(object sender, EventArgs e)
        {
            this.ShowHideDialogueInternal(false);
        }
        public void ShowHideDialogue(object sender, EventArgs e)
        {
            Button button = sender as Button;
            this.ShowHideDialogueInternal(button.CommandArgument.Equals("show"));
        }
        private void ShowHideDialogueInternal(bool state)
        {
            this.pnlDialogue.Visible = state;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel runat="server" ID="pnlDialogue" CssClass="DialogueBackground" Visible="false">
            <div class="Dialogue">
                <p>This is a dialogue</p>
                <div class="ButtonPanel">
                    <asp:Button 
                        runat="server" 
                        ID="btnOK" 
                        Text="OK" 
                        OnClick="DialogueAccept" />
                    <asp:Button 
                        runat="server" 
                        ID="btnCancel" 
                        Text="Cancel" 
                        OnClick="ShowHideDialogue" 
                        CommandArgument="hide" />
                </div>
            </div>
        </asp:Panel>
        <h1>Sample Dialogue using C# (without JavaScripts)</h1>
        <hr />
        <asp:Button 
            runat="server" 
            ID="btnShowDialogue" 
            Text="Show Dialogue" 
            OnClick="ShowHideDialogue" 
            CommandArgument="show" />
    </form>
</body>
</html>

This is a optional Section. 
If you need, you can implement this as a Web Control:
Dialogue Control:
public class Dialogue : Panel
{
    string style = @"
        <style type=""text/css"">
            div.DialogueBackground 
            { 
                position:absolute; 
                width:100%; 
                height:100%; 
                top:0; 
                left:0; 
                background-color:#777; 
                opacity:0.5;
                filter: alpha(opacity=50); 
                text-align:center; 
            }
            div.DialogueBackground div.Dialogue 
            {
                width:300px; 
                height:100px; 
                position:absolute; 
                left:50%; 
                top:50%; 
                margin-left:-150px; 
                margin-top:-50px; 
                border:solid 10px #aaa; 
                background-color:#fff; 
            }
        </style>
    ";
 
    public string Message { get; set; }
    public event EventHandler Accept;
    public event EventHandler Cancel;
    public Dialogue()
    {
        this.Visible = false;
        this.Message = "Are you sure?";
        this.CssClass = "DialogueBackground";
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.CreateControlHeirarchy();
    }
    public void CreateControlHeirarchy()
    {
        Button btnOk = new Button() { ID = "btnOK", Text = "OK", ValidationGroup = this.ID };
        btnOk.Click += new EventHandler(DialogueAccept);
        this.Controls.Add(btnOk);
        Button btnCancel = new Button() { ID = "btnCancel", Text = "Cancel", ValidationGroup = this.ID };
        btnCancel.Click += new EventHandler(HideDialogue);
        this.Controls.Add(btnCancel);
    }
    private void DialogueAccept(object sender, EventArgs e)
    {
        this.Hide();
        if (this.Accept != null) this.Accept(sender, e);
    }
    private void HideDialogue(object sender, EventArgs e)
    {
        this.Hide();
        if (this.Cancel != null) this.Cancel(sender, e);
    }
    public void Show()
    {
        this.Visible = true;
    }
    public void Hide()
    {
        this.Visible = false;
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (this.Page != null && this.Page.Header!=null)
            this.Page.Header.Controls.Add(new Literal() { Text = this.style });
    }
    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.Write("<div class=\"Dialogue\">");
        writer.Write(string.Format("<p>{0}</p>", this.Message));
        writer.Write("<div class=\"ButtonPanel\">");
        base.RenderContents(writer);
        writer.Write("</div>");
        writer.Write("</div>");
    }
}

Page (how you can use the Dialogue control): 
<%@ Page Language="C#" CodeBehind="~/Test.aspx.cs" Inherits="ActiveTest.Test" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">   
 <script runat="server">      
     public void Save(object sender, EventArgs e)
        {
            this.dlgConfirm.Show();
        }
        public void Accept(object sender, EventArgs e)
        {
            ///
            /// Confirmed... we can save data here...
            /// 
        }
        public void Cancel(object sender, EventArgs e)
        {
            
        }   
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
        <asp:Dialogue 
            runat="server" 
            ID="dlgConfirm" 
            Message="Are you want to save this details" 
            OnAccept="Accept" 
            OnCancel="Cancel" />
        <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
 </div>
 </form>
</body>
</html>

Wednesday, June 16, 2010

How to create a asp.net control using string text - Asp.net

This article demonstrate how to create a asp.net control and add it to the controls collection based on string text value.
Please note the original reference form asp.net forums


<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        protected void Button1_Click(object sender, EventArgs e)
        {
            string controlName = TextBox1.Text;
            string systemweblib = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Web.dll";
            System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFile(systemweblib);
            Type type = ass.GetType("System.Web.UI.WebControls." + controlName);
            Control c = (Control)Activator.CreateInstance(type);
            Panel1.Controls.Add(c);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Create Control" 
            onclick="Button1_Click" />
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Monday, June 14, 2010

How to load UserControl with parameters. LoadControl("VirtualPath", p1, p2) - Asp.net

This article demonstrate how to load a user control with constructor parameters in the LoadControl method. However we have implemented a method which accepts VirtualPath and n number of parameters.

Please review example below:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        public UserControl LoadControl(string UserControlPath, 
                params object[] constructorParameters)
        {
            List<Type> constParamTypes = new List<Type>();
            foreach (object constParam in constructorParameters)
                constParamTypes.Add(constParam.GetType());
            UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
            ConstructorInfo constructor = ctl.GetType()
                .BaseType.GetConstructor(constParamTypes.ToArray());
            if (constructor == null)
                throw new MemberAccessException("The requested constructor was not found on : " 
                    + ctl.GetType().BaseType.ToString());
            else
                constructor.Invoke(ctl, constructorParameters);
            return ctl;
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            List<Employee> employees = new List<Employee>();
            if (!this.IsPostBack)
                for (int i = 0; i < 10; i++)
                    employees.Add(new Employee() { Id = "Emp" + i, Name = "Employee" + i });
            List<object> parameters = new List<object>();
            this.phUserControl.Controls.Add(this.LoadControl("~/UserControls/ActiveUserControl.ascx", 
                employees, "Existing Employees"));
        }
        protected override void OnLoad(EventArgs e)
        {
            this.EnsureChildControls();
            base.OnLoad(e);
            if (!this.IsPostBack)
                this.phUserControl.DataBind();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="phUserControl"></asp:PlaceHolder>
    </form>
</body>
</html>

User Control

Markup:

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="ActiveUserControl.ascx.cs" 
    Inherits="ActiveTest.UserControls.ActiveUserControl" %>
<div>
    <h1><asp:Label runat="server" ID="lblTitle" /></h1>
    <hr />
    <asp:GridView runat="server" ID="grvEmployees" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblId" Text='<%# Eval("Id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txtName" Text='<%# Eval("Name") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code:

namespace ActiveTest.UserControls
{
    [ParseChildren(true)]
    public partial class ActiveUserControl : UserControl
    {
        public List<Employee> Employees
        {
            get { return (List<Employee>)(ViewState["Employees"] ?? (ViewState["Employees"] = new List<Employee>())); }
            set { ViewState["Employees"] = value; }
        }
        public string Title { get; set; }
        public ActiveUserControl() { }
        public ActiveUserControl(List<Employee> employees, string title)
        {
            this.Employees = employees;
            this.Title = title;
        }
        public override void DataBind()
        {
            this.lblTitle.Text = this.Title;
            this.grvEmployees.DataSource = this.Employees;
            this.grvEmployees.DataBind();
        }
    }
 
    [Serializable]
    public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

Sunday, June 13, 2010

How to find the control which caused a postback (Part 1 : Outside the event handler) - Asp.net

This article demonstrate how to find the control which cause a postback of a page outside the event handler. This code snippest cover
  1. Button
  2. Link Button
  3. TextBox
  4. Dropdown List
  5. Check Box
  6. Radio Button
Please note: When you try to find the clicked asp.net button, you have to turn off submit bebaviour to cuase a __doPostBack call
    Example

    <%@ Page Language="C#" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <script runat="server"> 
            protected override void OnLoad(EventArgs e)
            {
                if (this.IsPostBack)
                {
                    string uniqueId = this.Request.Form["__EVENTTARGET"];
                    if (!string.IsNullOrEmpty(uniqueId))
                    {
                        string[] parts = uniqueId.Split("$".ToCharArray());
                        string id = parts[parts.Length - 1];
                        Control ctrl = this.FindControl(id);
                        if (this.pnlPostbackDetails.Visible = ctrl != null)
                            this.lblControl.Text = string.Format(
                                "Type: {0} , Id: {1}", ctrl.GetType().Name, id);
                    }
                }
                base.OnLoad(e);
            }        
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Panel runat="server" ID="pnlContainer">
                <asp:Button 
                    runat="server" 
                    ID="btnPostabck" 
                    Text="Postback" 
                    UseSubmitBehavior="false" />
                <asp:LinkButton runat="server" ID="lnkPostback" Text="Postback" />
                <asp:TextBox runat="server" ID="txtName" AutoPostBack="true" />
                <asp:DropDownList runat="server" ID="ddlCountries" AutoPostBack="true">
                    <asp:ListItem>Select</asp:ListItem>
                    <asp:ListItem>SL (Sri Lanka)</asp:ListItem>
                    <asp:ListItem>UK (United Kingdom)</asp:ListItem>
                    <asp:ListItem>US (United States)</asp:ListItem>
                </asp:DropDownList>
                <asp:RadioButton 
                    runat="server" 
                    ID="rbPostback" 
                    Text="Postback" 
                    AutoPostBack="true" />
                <asp:CheckBox 
                    runat="server" 
                    ID="chkPostback" 
                    Text="Postback" 
                    AutoPostBack="true" />
            </asp:Panel>
            <hr />
            <asp:Panel runat="server" ID="pnlPostbackDetails" Visible="false">
                Postback Control Details: <asp:Label runat="server" ID="lblControl" />
            </asp:Panel>
        </div>
        </form>
    </body>
    </html>
     
     
     
     
     
     

    Tuesday, June 08, 2010

    How to access controls with in different Content Place Holders

    Sometimes it may necessary to access controls with in differnt Content Place Holders in the page. Solution is prefix Content Place Holder id with '$' control name.
    Control control = this.FindControl("FooterPlaceHolder$txtSearch");

    Example:

    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
                <asp:SqlDataSource
                    id="SqlDataSource1"
                    runat="server"
                    ConnectionString="<%$ ConnectionStrings:ActiveConnectionString%>"
                    SelectCommand="SELECT * FROM dbo.Country"
                    FilterExpression="Name='{0}'">
                    <FilterParameters>
                        <asp:ControlParameter 
                          Name="Name"
                          ControlID="FooterContent$txtSearch" 
                          PropertyName="Text"/>
                    </FilterParameters>
                </asp:SqlDataSource>
        
    </asp:Content>
    <asp:Content ID="FooterContent" runat="server" ContentPlaceHolderID="FooterContent">
        <asp:TextBox runat="server" ID="txtSearch" />
    </asp:Content>

    Monday, June 07, 2010

    How to read value with in a external web page

    Although it is not adviable, sometimes it might need to read some specific text with in external webpages as information extration. This post domonstrate how to read views within given video URL either YouTube or MetaCafe

    string youTubeMarker = "<strong class=\"watch-view-count\">";
    string metaCafeMarker = "<li>Views: <strong>";
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        ///
        /// I explan this using hard corded value
        /// But in real world please get this form your relevent textbox
        /// url = this.txtUrl.Text;
        /// You may not call this in page load
        /// But you may call this code in PostVideoLink event handler
        ///
        string url = "http://www.youtube.com/watch?v=3Kk-yZ7VpeA";
        string views = this.GetViews(url);
        Response.Write(string.Format("YouTube video views: {0}", views));
        url = "http://www.metacafe.com/watch/yt-ByGgMeQSK8Y
        /asp_net_tutorial_master_pages_site_navigation_part1/";
        views = this.GetViews(url);
        Response.Write(string.Format("MetaCafe video views: {0}", views));
    }
    protected void PostVideoLink(object sender, EventArgs e)
    {
    }
    private string GetViews(string url)
    {
        string marker = string.Empty;
        if (url.Contains("www.youtube.com"))
            marker = this.youTubeMarker;
        else if (url.Contains("www.metacafe.com"))
            marker = this.metaCafeMarker;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());
        if(string.IsNullOrEmpty(marker)) return string.Empty;
        string html = sr.ReadToEnd();
        int lb = html.IndexOf(marker) + marker.Length;
        int ub = html.IndexOf("<", lb);
        string views = html.Substring(lb, ub - lb);
        return views;
    }

    Saturday, June 05, 2010

    How does .Net Framework track Postback values : Asp.Net

    When page life cycle executes, for all controls in a page, if a control implements IPostBackDataHandler interface .net framwork invokes, IPostBackDataHandler's LoadPostData(string postKey, NameValueCollection postCollection)

    public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection)
    {
        ///
        /// Process your data here
        ///
        return false;
    }

    postCollection:
    Is a NameValueCollection which consist of all input filelds present in the page along with their values agaisnt corrosponding names.
    • ctrl00$txtFirstName - FirstName
    • ctrl00$txtSurname - Surname
    • ctrl00$txtAddress - Address
    Remember .net framwork use a format of ctl00_txtName as the id of the dom element. (.net control.ClientID) and exactly the same but separater is $ for name, ctrl00$txtName. (.net control UniqueID)
    postKey
    Is the name of the corresponding control. So easyly we can retrive the value of the input field like String postedValue = postCollection[postDataKey];
    In terms of writting HTML, when you write a html, you cant just use Response.Write("<input..... ) but you can write a simple web-control (in your case checkbox) and add instance of your custom check box to the page. Unless the control get added to the page, page life cycle wont be able to do anyting with your control. For build a simple web-control you can just extend WebControl class in System.Web.UI and to handle postbacks you may implement IPostBackDataHandler interface as well.
    Example:

    CustomCheckBox cchkBox = new CustomCheckBox();
    this.Page.Controls.Add(cchkBox);

    This is a complete example of Custom Checkbox which has a hidden field to hold it's value.

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class CustomCheckBox : WebControl,
                                    IPostBackDataHandler,
                                    INamingContainer
    {
        public bool Checked
        {
            get
            {
                return (bool)(ViewState["Checked"] ?? (ViewState["Checked"] = false));
            }
     
            set
            {
                ViewState["Checked"] = value;
            }
        }
        public bool AutoPostBack { get; set; }
        public event EventHandler CheckChanged;
        public string Label { get; set; }
        public virtual bool LoadPostData(string postDataKey,
                                        NameValueCollection postCollection)
        {
            bool presentValue = this.Checked;
            String postedValue = postCollection[postDataKey];
            if (!presentValue.Equals(postedValue))
            {
                this.Checked = postedValue.Equals("on") ? true : false;
                return true;
            }
            return false;
        }
        public virtual void RaisePostDataChangedEvent()
        {
            OnCheckChanged(EventArgs.Empty);
        }
        protected virtual void OnCheckChanged(EventArgs e)
        {
            if (CheckChanged != null)
                CheckChanged(this, e);
        }
        protected override void Render(HtmlTextWriter output)
        {
            output.Write(string.Format("<input type='checkbox' {0}{1} />",
                this.Checked ? " checked='checked'" : string.Empty,
                this.AutoPostBack ? string.Format(
                    " onclick=\"javascript:__doPostBack('{0}','');\"",
                    this.UniqueID) :
                string.Empty));
            output.Write(string.Format("<span>{0}</span>", this.Label));
            output.Write(string.Format("<input type='hidden' value='{0}' id='{1}' name='{2}' />",
                this.Checked ? "off" : "on", this.ClientID, this.UniqueID));
        }
    }

    Friday, June 04, 2010

    How to post values to diffent page using HttpWebRequest : Asp.net

    Using Asp.net HttpWebRequest object we can post data to external page and get a HttpWebResponse

    string strId = "regid789654";
    string strName = "Charith";
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "userid=" + strId;
    postData += ("&username=" + strName);
    byte[] data = encoding.GetBytes(postData);
    HttpWebRequest request =
        (HttpWebRequest)WebRequest.Create("http://www.domain.com/cart.asp");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    Stream newStream = request.GetRequestStream();
    newStream.Write(data, 0, data.Length);
    newStream.Close();
     
    StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());
    string result = sr.ReadToEnd();
    sr.Close();

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