Tuesday, August 31, 2010

How to copy a file from one server to another server.

Using FTP:
If you have valid FTP username and password to the target server we can use web client and UploadFile(...) method.
Example:
NetworkCredential networkCredentials = new NetworkCredential("UserName""Password");
WebClient client = new WebClient();
client.Credentials = networkCredentials;
Byte[] resposne = client.UploadFile("ftp://www.my-website.com/Image.jpg""C:\\Data\\Image.jpg");

Using HTTP:
If you dont have a valid FTP account, you can hand over the file to target server but from the target server should accept the file save it by itself (security consideration, make sence). Possibly using a generic http handler.
Example:
From the Source Server:
Byte[] response = 
    new WebClient().UploadFile("http://www.my-website.com/FileHandler.ashx""C:\\StockMarketUpdate.xls");

From the Target Server:
FileHanlder.ashx
public class FileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        foreach (string f in context.Request.Files.AllKeys)
        {
            HttpPostedFile file = context.Request.Files[f];
            string fileName = Path.Combine(context.Server.MapPath("~/Data"), file.FileName);
            if (File.Exists(fileName)) File.Delete(fileName);
            file.SaveAs(fileName);
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

How to bind DataTable to a asp.net menu using ParentID and ID relationship

Here are some useful tips for you:
  1. Menu control expects a heirarchical data structure, so we cant bind the DataTable to menu directly.
  2. Use data table Select where ParentID = ID
  3. Please use a recursive method to create child items relevent to current menu item ID
Here is an example that you may use to transfer your ralational data structure (TABLE) to hierarchical data structure (TREE) using the relationship between ParentID and ID
<%@ 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)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
                this.AddItems(this.menuNavigation.Items, 0, this.LoadData());
        }
        private void AddItems(MenuItemCollection items, int level, System.Data.DataTable dt)
        {
            string filterExp = string.Format("ParentID='{0}'", level);
            foreach (System.Data.DataRow r in dt.Select(filterExp))
            {
                MenuItem item = new MenuItem()
                {
                    Text = r[1].ToString(),
                    NavigateUrl = r[2].ToString()
                };
                this.AddItems(item.ChildItems, int.Parse(r[0].ToString()), dt);
                items.Add(item);
            }
        }
        private System.Data.DataTable LoadData()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID"String.Empty.GetType());
            dt.Columns.Add("[Name]"String.Empty.GetType());
            dt.Columns.Add("[Link]"String.Empty.GetType());
            dt.Columns.Add("ParentID"String.Empty.GetType());
            dt.Columns.Add("[Order]"String.Empty.GetType());
            int index = 9;
            for (int i = 0; i < 1100; i++)
            {
                string item = "{0},Item{1},Page{1}.aspx,{2},{1}";
                if (i < 110)
                {
                    index = i < 10 ? 0 : int.Parse(Math.Ceiling((decimal)i / 10).ToString());
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
                else
                {
                    if (i % 10 == 0) index++;
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
            }
            return dt;
 
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu runat="server" ID="menuNavigation" />
    </form>
</body>
</html>

Monday, August 30, 2010

How to register asynchronous task in asp.net page execution

Why we need asynchronous tasks?

Execute a time consuming operations in parallel to the CLR thread which execute the request

If you have long running operations to execute in the page execution, you can execute them in parallel rather than serial execution. The difference between page asynchronous task and firing up a separate thread is, page will NOT get rendered until all the page asynchronous tasks get completed but if you handle part of your execution to a separate thread, page get rendered regardless of external thread completed or not.
There are two major points that we may need to understand when registering asynchronous with page execution.
Asynchronous Result – A class which implements IAsyncResult interface, which can be found at the end of this post.
  1. Asynchronous Result – A class which implements IAsyncResult interface, which can be found at the end of this post.
  2. Separate work item queued in the ThreadPool which execute the time consuming operation

Page:
Demonstrate how to register page asynchronous task using custom PageAsyncResult class which implements the IAsyncResult interface.
public partial class Test : Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.Response.Write("Executing Init...<br />");
        PageAsyncTask task1 = new PageAsyncTask(OnBegin, OnEnd, OnTimeOut, null);
        this.RegisterAsyncTask(task1);
    }
    private void PerformAsyncWork(Object state)
    {
        PageAsyncResult result = state as PageAsyncResult;
        try
        {
            ///
            /// Do your time consuming operation here
            /// Folloing is a fake time consuming operation
            /// Only for the demonstration
            ///
            result.Context.Response.Write("Executing time consuming operation...<br />");
            for (int i = 0; i < 5; i++)
                Thread.Sleep(1000);
            result.Context.Response.Write("Finised executing time consuming operation...<br />");
        }
        catch (Exception e)
        {
            result.Context.AddError(e);
        }
        finally
        {
            result.Complete(false);                
        }
    }
    private IAsyncResult OnBegin(Object sender, EventArgs e, AsyncCallback callback, Object state)
    {
        IAsyncResult result = new PageAsyncResult(callback, HttpContext.Current);
        ThreadPool.QueueUserWorkItem(PerformAsyncWork, result);
        return result;
    }
    private void OnEnd(IAsyncResult result)
    {
    }
    private void OnTimeOut(IAsyncResult result)
    {
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.Response.Write("Executing Load...<br/>");
    }
}


PageAsyncResult class:
PageAsyncResult class which implements IAsyncResult interface.  This class contains HttpContext what we can use in the asynchronous to manipulate response, request, session etc.
public class PageAsyncResult : IAsyncResult
{
    #region Attributes
        
    private AsyncCallback callback;
    private HttpContext context;
    private bool completed;
    private bool completedSynchronously;
 
    #endregion
 
    #region IAsyncResult Members
 
    bool IAsyncResult.IsCompleted { get { return completed; } }
    Object IAsyncResult.AsyncState { get { return null; } }
    WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
    bool IAsyncResult.CompletedSynchronously
    {
        get { return completedSynchronously; }
    }
 
    #endregion
 
    #region Properties
        
    public HttpContext Context
    {
        get
        {
            if (completed || context == nullthrow new InvalidOperationException();
            return context;
        }
    }
    #endregion
 
    #region Methods
        
    public PageAsyncResult(AsyncCallback cb, HttpContext context)
    {
        callback = cb;
        this.context = context;
    }
    public void Complete(bool synchronous)
    {
        completed = true;
        completedSynchronously = synchronous;
        context = null;
        if (callback != null)
            callback(this);
    }
 
    #endregion
}

AddOnPreRenderCompleteAsync vs RegisterAsyncTask 

The System.Web.UI.Page class introduces another method to facilitate asynchronous operations: AddOnPreRenderCompleteAsync. RegisterAsyncTask has four advantages over AddOnPreRenderCompleteAsync. First, in addition to Begin and End methods, RegisterAsyncTask lets you register a timeout method that's called if an asynchronous operation takes too long to complete. You can set the timeout declaratively by including an AsyncTimeout attribute in the page's @ Page directive. AsyncTimeout="5" sets the timeout to 5 seconds. The second advantage is that you can call RegisterAsyncTask several times in one request to register several async operations. As with MethodAsync, ASP.NET delays rendering the page until all the operations have completed. Third, you can use RegisterAsyncTask's fourth parameter to pass state to your Begin methods. Finally, RegisterAsyncTask flows impersonation, culture, and HttpContext.Current to the End and Timeout methods. As mentioned earlier in this discussion, the same is not true of an End method registered with AddOnPreRenderCompleteAsync.

Reference 1 - MSDN:
Reference 2 - MSDN:

Sunday, August 29, 2010

How to remove asp.net menu item using java script and jQuery

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(document).ready(function () {
            $(".Hide").parent().remove();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="Container">
        <asp:SiteMapDataSource runat="server" ID="smdDataSource" ShowStartingNode="false" />
        <asp:Menu runat="server" ID="menuItems" DataSourceID="smdDataSource">
            <DynamicItemTemplate>
                <asp:HyperLink runat="server" ID="menuLink" 
                    Text='<%# Eval("Text") %>' 
                    NavigateUrl='<%# Eval("NavigateUrl") %>'                          
                    CssClass='<%# (Eval("NavigateUrl").ToString()).Contains("HiddenPage.aspx")? "Hide" : "Normal" %>'
                 />
            </DynamicItemTemplate>
        </asp:Menu>
    </div>
    </form>
</body>
</html>

Asp.net expressions overview and comparison

 <%# ... %> Executes at the call to DataBind() method.
<%= ... %> Not valid for server controls, will not get executed for server controls. But when place in the mark-up, value get rendered to the output html stream.
<%$ Prefix:Value %> Before page init/At the point of execution.

Example:

Web.condig:
  <appSettings>
    <add key="Label" value="Expressions"/>
  </appSettings>

Page:
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        public string Label = "Expressions";
        string a, b, c;
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            a = this.txtNameA.Text; /// Expressions
            b = this.txtNameB.Text; /// ""
            c = this.txtNameC.Text; /// <%= this.Label %>
        }
        protected override void OnLoad(EventArgs e)
        {
            a = this.txtNameA.Text; /// Expressions
            b = this.txtNameB.Text; /// ""
            c = this.txtNameC.Text; /// <%= this.Label %>
            base.OnLoad(e);
            this.DataBind();
            a = this.txtNameA.Text; /// Expressions
            b = this.txtNameB.Text; /// Expressions
            c = this.txtNameC.Text; /// <%= this.Label %>
        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            a = this.txtNameA.Text; /// Expressions
            b = this.txtNameB.Text; /// Expressions
            c = this.txtNameC.Text; /// <%= this.Label %>
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox runat="server" ID="txtNameA" Text="<%$ AppSettings:Label  %>" />
        <asp:TextBox runat="server" ID="txtNameB" Text="<%# this.Label %>" />
        <asp:TextBox runat="server" ID="txtNameC" Text="<%= this.Label %>" />
        <p><%= this.Label %></p>
    </form>
</body>
</html>

Output:

Thursday, August 26, 2010

How to postback a button to a diffrent page and invoke a relevent event

To postback a page to diffrent page and invoke a relevent event, we can use PostBackUrl property of the button contorl
Page1.aspx
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button 
            runat="server" 
            ID="btnSave" Text="Save" 
            PostBackUrl="~/Page2.aspx" 
            UseSubmitBehavior="false" />
    </div>
    </form>
</body>
</html>
Page2.aspx
<head id="Head1" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string s = this.Request.Form["__EVENTTARGET"];
            if (s.Contains("btnSave")) this.Save();
        }
        protected void Save()
        {
 
        }
      </script>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

How to save a file with number prefix while uploading if file being saved previously

This will save, say you upload Image.gif.
  1. First save of Image.gif will be Image001.gif
  2. Then again if you try to save Image.gif, Then it will be Image002.gif
  3. And so on...
FileInfo file = new FileInfo(this.fileImage.PostedFile.FileName);
string filePreFix = file.Name.Replace(file.Extension, string.Empty).ToLower();
string fileExtension = file.Extension;
int maxFile = 0;
foreach (FileInfo f in new DirectoryInfo(Server.MapPath("~/Images")).GetFiles())
{
    string name = f.Name.ToLower();
    if (name.Contains(filePreFix) && f.Extension.ToLower().Equals(fileExtension))
    {
        int number = int.Parse(name.Replace(filePreFix, string.Empty).Replace(fileExtension, string.Empty));
        if (number > maxFile) maxFile = number;
    }
}
string newFileName = string.Format("{0}{1:000}{2}", filePreFix, maxFile + 1, fileExtension);

How to validate IP address using Regular expression

string exp = @"
    ^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
     (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
string ipAddress = "127.0.0.1";
bool isMatch = Regex.IsMatch(ipAddress,exp);

How to avoid rendering VIEWSTATE, EVENTVALIDATION and other hidden fileds

public class PageBase : Page
{
    string[] tags = { "__VIEWSTATE""__EVENTTARGET""__EVENTARGUMENT""__EVENTVALIDATION" };
    protected override void Render(HtmlTextWriter writer)
    {
        StringBuilder sb = new StringBuilder();
        HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
        base.Render(htw);
        string html = sb.ToString();
        foreach (string tag in tags)
            html = this.RemoveTag(tag, html);
        writer.Write(html);
    }
    public string RemoveTag(string tag, string html)
    {
        int lowerBound = html.IndexOf(tag);
        if (lowerBound < 0) return html;
        while (html[lowerBound--] != '<') ;
        int upperBound = html.IndexOf("/>", lowerBound) + 2;
        html = html.Remove(lowerBound, upperBound - lowerBound);
        if (html.Contains(tag)) html = this.RemoveTag(tag, html);
        return html;
    }
}
public partial class Test : PageBase
{
}

How to list all the directories and files in to a asp.net menu

<%@ 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)
        {
            base.OnLoad(e);
            DirectoryInfo d = new DirectoryInfo(Server.MapPath("~/"));
            MenuItem root = new MenuItem("\\", d.FullName);
            this.AddChildren(root, d);
            this.menuNavigation.Items.Add(root);
        }
        private void AddChildren(MenuItem item, DirectoryInfo direcotry)
        {
            foreach (DirectoryInfo child in direcotry.GetDirectories())
            {
                MenuItem childItem = new MenuItem(child.Name, child.FullName);
                item.ChildItems.Add(childItem);
                if (child.GetDirectories().Count() > 0)
                    this.AddChildren(childItem, child);
            }
            foreach (FileInfo child in direcotry.GetFiles())
            {
                MenuItem childNode = new MenuItem(child.Name, child.FullName);
                item.ChildItems.Add(childNode);
            }
        }       
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu runat="server" ID="menuNavigation" />
    </form>
</body>
</html>

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;
        }
    }
}

How to access values of server controls in client side

‘How to access values of server controls in client side’ is a frequently asked question in asp.net developer community.  Technically solution to the question can be sub divided in to two simple answers.
1. How to access server control value in Page
We can use
var input = document.getElementById('<%=txtValue1.ClientID %>');
Syntax to access server side controls in the client side. However
Please refer this article for more information

2. How to access server control values in UserControl or WebControl
In this case we have to hold the script in a string variable and inject necessary ClientIDs in the run time. Then use this.Page.RegisterClientScriptBlock(...) method to register the script by the render time.
this.Page.ClientScript.RegisterClientScriptBlock(
        this.GetType(),
        this.GetType().Name,
        string.Format(this.script, this.txtValue1.ClientID, 
        this.txtValue2.ClientID, this.txtValue3.ClientID),
        true);
Please refer this article for more information

How to access server side control values using java script and change in the client side - Part 2 [ UserControl or WebControl]

To inject control ClientID values to the script for in WebControl or UserControl we can register script dynamically using this.Page.ClientScript.RegisterClientScriptBlock(...) method.
Example:
<%@ Control Language="C#" 
            AutoEventWireup="true" 
            CodeBehind="WebUserControl.ascx.cs" 
            Inherits="ActiveTest.WebUserControl" %>
<script runat="server">
    string script = @"
            function GetValue() {{
                var input = document.getElementById('{0}');
                alert(input.value);
                return false;
            }}
            function SetValue() {{
                var value = prompt(""Input Value"", ""BMW"");
                var input = document.getElementById('{1}');
                input.value = value;
                return false;
            }}
            function TransferValue() {{
                var input1 = document.getElementById('{0}');
                var input3 = document.getElementById('{2}');
                input3.value = input1.value;
                return false;
            }}
        ";
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(),
                this.GetType().Name,
                string.Format(this.script, this.txtValue1.ClientID, this.txtValue2.ClientID, this.txtValue3.ClientID),
                true);
    }    
</script>
<div id="Control">
    <h4>Get Value</h4>
    <asp:TextBox runat="server" ID="txtValue1" Text="Toyota" />
    <asp:Button runat="server" ID="btnGetValue" Text="Get Value" OnClientClick="javascript:return GetValue()" />
    <hr />
    <h4>Set Value</h4>
    <asp:TextBox runat="server" ID="txtValue2" />
    <asp:Button runat="server" ID="btnSetvalue" Text="Set Value" OnClientClick="javascript:return SetValue()" />
    <hr />
    <h4>Transfer Value</h4>
    <asp:TextBox runat="server" ID="txtValue3" />
    <asp:Button runat="server" ID="btnTransferValue" Text="Transfer Value" OnClientClick="javascript:return TransferValue()" />
</div>

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