Wednesday, August 25, 2010

How to add google custom search to your asp.net page with Master Page

Master page
<%@ Master Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head2" runat="server">
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
    <script runat="server">
        public string RootUrl
        {
            get
            {
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.Scheme,
                    Uri.SchemeDelimiter,
                    requestUri.Host,
                    requestUri.IsDefaultPort ?
                        string.Empty : string.Format(":{0}", requestUri.Port),
                    request.ApplicationPath);
                return rootUrl.EndsWith("/") ? rootUrl :
                        string.Format("{0}/", rootUrl);
            }
        }
    </script>
</head>
<body>
    <form id="Form2" runat="server">
        <div id="search">
            <iframe 
                src="<%=this.RootUrl %>Search.html" 
                class="SearchContainer" 
                frameborder="0" 
                scrolling="no">
                <b>Your browser does not support frames</b>
            </iframe>
        </div>
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />  
    </form>
</body>
</html>
Search html
<!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>
    <title></title>
    <style type="text/css">
    </style>
</head>
<body>
    <form target="_blank" id="searchForm" method="get" action="http://www.google.com/custom">
        <span id="searchText"><em>Search</em></span>
        <input id="searchInput" type="text" name="q" title="Search www.charith.gunasekara.web-sphere.co.uk" />
        <input id="searchButton" type="submit" value="Search" title="Search" />
  <input type="hidden" name="domains" value="http://www.charith.gunasekara.web-sphere.co.uk" />
  <input type="hidden" name="sitesearch" value="http://www.charith.gunasekara.web-sphere.co.uk" />        
    </form>
</body>
</html>
 

How to access server side control values using java script and change in the client side - Part 1 [in a Page]

We can use ClientID propery of any control to access values of controls in the client side java scripts.
var input = document.getElementById('<%=txtName.ClientID %>');

Example
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script language="javascript">
        function GetValue() {
            var input = document.getElementById('<%=txtValue1.ClientID %>');
            alert(input.value);
            return false;
        }
        function SetValue() {
            var value = prompt("Input Value""BMW");
            var input = document.getElementById('<%=txtValue2.ClientID %>');
            input.value = value;
            return false;
        }
        function TransferValue() {
            var input1 = document.getElementById('<%=txtValue1.ClientID %>');
            var input3 = document.getElementById('<%=txtValue3.ClientID %>');
            input3.value = input1.value;
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <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()" />
    </form>
</body>
</html>

Tuesday, August 24, 2010

Binary serialization - c#, asp.net example

Markup:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView runat="server" ID="grvItems" />
        <asp:Panel runat="server" ID="pnlAddCar">
            Modal: <asp:TextBox runat="server" ID="txtModal" />
            Color: <asp:TextBox runat="server" ID="txtColor" />
            <asp:Button runat="server" ID="btnSave" Text="Save Car" OnClick="SaveCar" />
        </asp:Panel>
    </form>
</body>
</html>
Code:
public partial class Test : Page
{
    private string fileName;
    public List<Car> Cars
    {
        get { return ViewState["Items"as List<Car>; }
        set { ViewState["Items"] = value; }
    }
    public Test()
    {
        fileName = Server.MapPath("~/Data.bin");
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!this.IsPostBack)
            this.LoadCars();
    }
    protected void SaveCar(object sender, EventArgs e)
    {
        if (this.Cars == nullthis.Cars = new List<Car>();
        Car car = new Car() { Color = this.txtColor.Text, Modal = this.txtModal.Text };
        this.Cars.Add(car);
        Stream stream = File.Open(fileName, FileMode.Create);
        BinaryFormatter bFormatter = new BinaryFormatter();
        bFormatter.Serialize(stream, this.Cars);
        stream.Close();
        this.grvItems.DataSource = this.Cars;
        this.grvItems.DataBind();
    }
    protected void LoadCars()
    {
        List<Car> cars;
        if (File.Exists(this.fileName))
        {
            Stream stream = File.Open(fileName, FileMode.Open);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            cars = (List<Car>)binaryFormatter.Deserialize(stream);
            stream.Close();
            this.Cars = cars;
        }
        if (this.Cars != null)
        {
            this.grvItems.DataSource = this.Cars;
            this.grvItems.DataBind();
        }
    }
}
[Serializable]
public class Car
{
    #region Properties
        
    public string Modal { getset; }
    public string Color { getset; }
 
    #endregion
 
    #region Methods
 
    #endregion
}

How to bind XML file in to asp.net Menu control

Example page:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string xmlPath = Server.MapPath("~/Navigation.xml");
            XmlDataSource xmlDS = new XmlDataSource();
            xmlDS.DataFile = xmlPath;
            string iRole = "1";
            xmlDS.XPath = "Home/Role[@id='" + iRole + "']";
            this.menuNavigation.DataSource = xmlDS;
            this.menuNavigation.DataBind();
            this.menuNavigation.Items[0].Text = "";
            this.menuNavigation.Items[0].Value = "";
            this.menuNavigation.Items[0].Selectable = false;            
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Menu 
        ID="menuNavigation" 
        runat="server" 
        StaticDisplayLevels="2"
        DynamicHorizontalOffset="1" 
        DynamicVerticalOffset="1"
        Orientation="Horizontal">
        <DataBindings>
            <asp:MenuItemBinding 
                DataMember="Menu" 
                TextField="text" 
                ValueField="text" 
                NavigateUrlField="url" />
            <asp:MenuItemBinding 
                DataMember="SubMenu" 
                NavigateUrlField="url" 
                TextField="text"
                ValueField="text" />
        </DataBindings>
    </asp:Menu>
    </form>
</body>
</html>

XML file:
<?xml version="1.0" encoding="utf-8" ?>
<Home>
  <Role id="1">
    <Menu text="Item1" url="Item1.aspx">
      <SubMenu text="Page-1-1" url="Page-1-1.aspx" />
      <SubMenu text="Page-1-2" url="Page-1-2.aspx" />
      <SubMenu text="page-1-3" url="Page-1-3.aspx" />
    </Menu>
    <Menu text="Item2"  url="Item2.aspx">
      <SubMenu text="Page-2-1" url="Page-2-1.aspx">
        <SubMenu text="Page-2-1-1" url="Page-2-1-1.aspx">
          <SubMenu text="Page-2-1-1-1" url="Page-2-1-1-1.aspx" />
          <SubMenu text="Page-2-1-1-2" url="Page-2-1-1-2.aspx" />
          <SubMenu text="Page-2-1-1-3" url="Page-2-1-1-3.aspx" />
        </SubMenu>
        <SubMenu text="Page-2-1-2" url="Page-2-1-2.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Page-2-2" url="Page-2-2.aspx">
        <SubMenu text="Page-2-2-1" url="ComedyPage-2-2-1.aspx">
          <SubMenu text="Page-2-2-1-1" url="Page-2-2-1-1.aspx" />
          <SubMenu text="Page-2-2-1-2" url="Page-2-2-1-2.aspx" />
          <SubMenu text="Page-2-2-1-3" url="Page-2-2-1-3.aspx" />
          <SubMenu text="Page-2-2-1-4" url="Page-2-2-1-4.aspx" />
        </SubMenu>
        <SubMenu text="Page-2-2-2" url="Page-2-2-2.aspx" />
        <SubMenu text="Page-2-2-3" url="Page-2-2-3.aspx" />
      </SubMenu>
    </Menu>
    <Menu text="Item3" url="Item3.aspx" />
  </Role>
  <Role id="2">
    <Menu text="Item4" url="Item4.aspx">
      <SubMenu text="Page-4-1" url="Page-4-1.aspx" />
      <SubMenu text="Page-4-2" url="Page-4-2.aspx" />
    </Menu>
    <Menu text="Item5" url="Item5.aspx" />
  </Role>
</Home>

How to append RootUrl to ReturnUrl parameter in login page

We can append Root Url to return url parameter in the login page and do a response redirect to same page so that return url value will get updated to routed value.
Example:
public partial class Login : Page
{
    public string RootUrl
    {
        get
        {
            Uri requestUri = Context.Request.Url;
            HttpRequest request = Context.Request;
            string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                requestUri.Scheme,
                Uri.SchemeDelimiter,
                requestUri.Host,
                requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                request.ApplicationPath);
            return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
        }
    }
 
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        string returnUrl = this.Request.QueryString.Get("ReturnUrl");
        if (!string.IsNullOrEmpty(returnUrl))
        {
            if (!returnUrl.ToLower().Contains("http://"))
            {
                returnUrl = Path.Combine(this.RootUrl, returnUrl);
                string url = string.Format("{0}?ReturnUrl={1}", this.Request.Path, Server.UrlEncode(returnUrl));
                this.Response.Redirect(url);
            }
        }
    }
}
Referene

Sunday, August 22, 2010

How to update a asp.net page at the same time we download a file in asp.net

When we use Response.WriteFile(Results.xls), asp.net serve you the desired file, but in such cases the underline page does not get refreshed due to no html reponse generated by the server. To get the page updated with the same time when we download a file we may consider handling the file download to separate request. This request can be handled by a generic handler in asp.net.
Example
Page 
<%@ Page Language="C#"  %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        public string RootUrl
        {
            get
            {
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.Scheme,
                    Uri.SchemeDelimiter,
                    requestUri.Host,
                    requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                    request.ApplicationPath);
                return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.lblFile.Text = DateTime.Now.ToString("hh:mm:ss");
        }
        protected void GetFile(object sender, EventArgs e)
        {
            string fileName = "StudentResults.xls";
            this.ClientScript.RegisterStartupScript(
                this.GetType(), this.GetType().Name,
                string.Format("window.location.href='{0}DownloadHandler.ashx?fileName={1}'", 
                    this.RootUrl, fileName), true);
        }        
    </script>
</head>
<body>
    <form id="form2" runat="server">
        <asp:Label runat="server" ID="lblFile" />
        <asp:Button runat="server" ID="btnGetFile" Text="GetFile" OnClick="GetFile" />
    </form>
</body>
</html>

lblFile: is there only to demonstrate that page is updating. When you click on GetFile button, it always update the lblFile.Text with the crrent time so the page update is visible to the user. Please note, this lblFile is not essntial, but it is there only for the purpose of demonstration.

Generic Hanlder - DownloadHanlder.ashx
public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string fileName = context.Request.QueryString.Get("fileName");
        HttpResponse response = context.Response;
        response.Clear();
        response.ContentType = "application/vnd.ms-excel";
        response.AppendHeader("Content-Disposition"string.Format("attachment;filename={0}", fileName));
        response.WriteFile(context.Server.MapPath(fileName));
        response.Flush();
        response.End();
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

How to pass values from parent page to child page [embedded in iframe] in asp.net

Parent Page: - Buy.aspx
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
    <title></title>
    <script runat="server">        
        protected void Buy(object sender, EventArgs e)
        {
            this.ifmContainer.Attributes.Add("src"this.ResolveUrl(
                string.Format("~/Checkout.aspx?p={0}&q={1}"this.txtProduct.Text, this.txtQuantity.Text)));
        }
    </script>
</head>
<body>
    <form id="form2" runat="server">
        Product : <asp:TextBox runat="server" ID="txtProduct" />
        Quentity : <asp:TextBox runat="server" ID="txtQuantity" />
        <asp:Button runat="server" ID="btnBuy" Text="Buy" OnClick="Buy" />
        <iframe runat="server" id="ifmContainer" src="Checkout.aspx">
            <b>Your browser does not support iframes</b>
        </iframe> 
    </form>
</body>
</html>

Child Page: - Checkout.aspx
<%@ Page Language="C#" %>
<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);
            this.lblProduct.Text = this.Request.QueryString.Get("p");
            this.lblQuentity.Text = this.Request.QueryString.Get("q");            
        }    
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Product: <asp:Label runat="server" ID="lblProduct" />
        Quantity: <asp:Label runat="server" ID="lblQuentity" />
    </form>
</body>
</html>
 

How to stop a asp.net button being postback to server

Attach an OnClientClick java script function with return inline. From the function return false based on your logic
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script type="text/javascript">
        function Validate() {
            alert("Validate Controls");
            var isValid = false;
            if (isValid)
                document.forms[0].submit();
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button runat="server" ID="btnLogin" 
            OnClientClick="javascript:return Validate()" 
            Text="Login" />
    </form>
</body>
</html>

Saturday, August 21, 2010

How to print ASCII charactors in asp.net

<%@ 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);
            TableRow tr = new TableRow();
            int index = 0;
            for (int i = 31; i < 256; i++)
            {
                string text = string.Format("{0:000} - (&#{0})", i);
                if (index % 10 == 0)
                {
                    tr = new TableRow();
                    this.tblCharSet.Rows.Add(tr);
                }
                tr.Cells.Add(new TableCell() { Text = text });
                this.ddlCharactors.Items.Add(new ListItem(string.Format("{0:000}", i), i.ToString()));
                index++;
            }
        }     
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DropDownList ID="ddlCharactors" runat="server" />
        <asp:Table runat="server" ID="tblCharSet" />
    </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...