Saturday, March 24, 2012

Gridview rows blink using JQuery in asp.net

When I'm developing an application with .NET platform, I have a case that is a Gridview row blinking depend on the some column data every one second. I solved it out using JQuery and it is also a simple way by applying "setTimeout" javascript function as below.

Gridview Row Blinking
Gridview Row Blinking
Put the following style sheet to <head> tag.
<style type="text/css">     .bgRow     {         background-color: Green;     }     .norRow     {         background-color: Silver;     } </style>
 Add the following scripts to <head> tag.
<script src="yourUrl/jquery-1.4.1.min.js" type="text/javascript"></script> //it need for JQuery <script type="text/javascript">     function setBG(gridId) {         var id = "#" + gridId;         $(id).find("tr").each(function () {             var css = $(this).attr("class");             if (css != null && css == "bgRow")                 $(this).addClass("norRow").removeClass("bgRow");             else if (css != null && css == "norRow")                 $(this).addClass("bgRow").removeClass("norRow");         });         setTimeout("setBG('" + gridId + "')", 1000); //1000 is equal to one second and call function every one second.     } </script>
Create a Gridview as below. I used "Northwind" db and "Suppliers" table. 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
    AllowPaging="True" AlternatingRowStyle-Wrap="True" EmptyDataText="There is no data."
    OnRowDataBound="GridView1_RowDataBound" 
    onpageindexchanging="GridView1_PageIndexChanging">
    <Columns>
        <asp:BoundField HeaderText="Supplier ID" DataField="SupplierID" />
        <asp:BoundField HeaderText="Company Name" DataField="CompanyName" />
        <asp:BoundField HeaderText="Address" DataField="Address" />
        <asp:BoundField HeaderText="Country" DataField="Country" />
    </Columns>
</asp:GridView>
Add the below code snippet to code-behind.
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (!Page.IsPostBack)
        {
            using (var context = new NorthwindEntities())
            {
                //Data binding here. I used EF.                 var suppliers = context.Suppliers.ToList();                 GridView1.DataSource = suppliers;                 GridView1.DataBind();             }            }
        //Register javascript and call "setBG" function.         ClientScript.RegisterStartupScript(GetType(), "BG", "setBG('" + GridView1.ClientID + "')", true);     }     catch (Exception ex)     {             } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {     if (e.Row.RowType == DataControlRowType.DataRow)     {         string country = DataBinder.Eval(e.Row.DataItem, "Country").ToString();         if(country == "USA")  //set the row background color on condition here.             e.Row.CssClass = "bgRow";     } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {
    //handle for page index here     GridView1.PageIndex = e.NewPageIndex;     using (var context = new NorthwindEntities())     {         var suppliers = context.Suppliers.ToList();         GridView1.DataSource = suppliers;         GridView1.DataBind();     } }
That's all what you have to do. You'll be glad you did.
Every row has blinking, when they have "Country" column is "USA".

Sunday, March 18, 2012

How to populate RSS Feed in .aspx

RSS is an XML format used for syndicating news and similar content from online news sources. It stands for "Really Simple Syndication" and consists of a channel that represents the news source, which has a title, link, and description that describe the news source minimally . Additionally, an RSS feed typically contains one or more item elements that represent individual news items, each of which should have a title, link, or description. Having an RSS feed for your site has become a necessity in recent years. With blogs or news sites being updated frequently, RSS has allowed readers to keep up with new content without being forced to visit them. This tutorial show you how to create an RSS feed with ASP.NET, and how to render XML documents on ASP.NET Web pages.

RSS Feed in .aspx

Create "RSSFeed.aspx" and remove default html markup and then put Repeater control and embed the RSS syntax as below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RSSFeed.aspx.cs" Inherits="WebAppBlog.RSSFeed" %>

<asp:repeater id="Repeater1" runat="server">
    <HeaderTemplate>
    <rss version="2.0">
      <channel>
        <title>Name of the Website</title>
        <link>http://www.yourdomain.com</link>
        <description>This is the syndication feed for yourdomain.com</description>
         <image>
          <title>Name of the Website</title>
          <url>your image url</url>
          <link>http://www.yourdomain.com</link>
        </image>
    </HeaderTemplate>
    <ItemTemplate>
        <item>
          <title><%# (Eval("CompanyName"))%></title>
          <description><![CDATA[<%# FormatForXML(Eval("ContactName") + " (" + Eval("ContactTitle") + ")" + Eval("Address"))  %>]]></description>
          <pubDate><%= DateTime.Now.ToString("R")%></pubDate>
          <link><%# "http://www.yourdomain.com/CompanyDetail.aspx?id=" + Eval("SupplierID")%></link>
        </item>
    </ItemTemplate>
    <FooterTemplate>
    </channel>
 </rss>
  </FooterTemplate>
</asp:repeater>

 I used the "Northwind" database (download here) and "Suppliers" table, and created ADO.NET Entity Data Model "NorthwindEntities" for data access (see here how to create Entity Data Model from Database).
After creating Entity Data Model, you will see "NorthwindEntities" connection look like below.
<connectionStrings>
     <add name="NorthwindEntities" connectionString="metadata=res://*/NorthwindModel.csdl|res:    //*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True&quot;"
         providerName="System.Data.EntityClient" />
</connectionStrings>

Add the following code to code-behind.

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (!Page.IsPostBack)
        {
            using (var context = new NorthwindEntities())
            {
                var topProduct = context.Suppliers.OrderByDescending(p => p.SupplierID).Take(10).ToList();
                Repeater1.DataSource = topProduct;
                Repeater1.DataBind();
            }
        }
    }
    catch (Exception ex)
    {
    }
}
protected string FormatForXML(object input)
{
    string data = input.ToString();
    // replace those characters disallowed in XML documents
    data = data.Replace("&", "&amp;");
    data = data.Replace("\"", "&quot;");
    data = data.Replace("'", "&apos;");
    data = data.Replace("<", "&lt;");
    data = data.Replace(">", "&gt;");
    return data;
}

That's it. Now, your RSS Feed is available to your reader.

RSS 2.0 Specification

Similar Post

Saturday, March 17, 2012

How to show RSS Feed from web site.

If your site has RSS Feed available and you want to support this (the orange icon show up in the status bar) as below image, you can make it easy.


Add the following line to <head> tag :

<link href="RSSFeedUrlHere" title="TitleHere" type="application/rss+xml" rel="alternate"/>

For example, I used  the following lines for my site.
<link href="http://www.iblogseeker.com/rss/RecentBlogs.aspx" title="iBlogSeeker » Most Recent Blogs" type="application/rss+xml" rel="alternate"/>

This feature support in IE and Firefox but don't support in Google Chrome (you need Extensions).

Sunday, March 4, 2012

How to create image verification for user registration in asp.net

Often, we have to use image verification for sign up in our application to prevent the automated registrations. This is essential because someone may send a lot of request programmatically to your server so that to slow down the speed of your server and making the size of your database large and large by entering much nuisance information. By creating the image verification on sign up page, it can reduces system loads and make better performance and security of your web site.
This sample is about how you can verify user sign up while registering a user to your web site look like Yahoo and Google.
Imag verification on sign up page
First we create ImageVerifyTest.aspx (such as Sign Up page) and put the following code to <form> tag. It use "UpdatePanel" for image so that don't refresh the whole page while clicking "Try a different image" button.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
    <table cellpadding="2" cellspacing="0">
        <tr>
            <td align="right">
                <asp:Label ID="Label5" runat="server" Text="Type the code shown"></asp:Label>
            </td>
            <td></td>
            <td>
                <asp:TextBox ID="txtImgVerify" runat="server" Text=""></asp:TextBox>
                <asp:Label ID="lblVerifyMsg" runat="server" Font-Bold="True" ForeColor="Red" Text="*"
                    Visible="False"></asp:Label>
            </td>
        </tr>
        <tr>
            <td align="right">
                <asp:LinkButton ID="lnkBtnImgVerify" runat="server" ForeColor="Blue" OnClick="lnkBtnImgVerify_Click"
                    Text="Try a different image" ValidationGroup="try"></asp:LinkButton>
            </td>
            <td></td>
            <td style="height: 50px;">
                <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:Image ID="imgVerify" runat="server" ImageUrl="imageVerify.aspx" />
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="lnkBtnImgVerify" EventName="Click"></asp:AsyncPostBackTrigger>
                    </Triggers>
                </asp:UpdatePanel>
            </td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td>
                <asp:Button ID="btnGo" runat="server" onclick="btnGo_Click" Text="Go"
                    Width="56px" />
            </td>
        </tr>
    </table>
</div>
</form>

And add the snippet code as below in code-behind.
protected void lnkBtnImgVerify_Click(object sender, EventArgs e)
{
    try
    {
        lblVerifyMsg.Visible = false;
        imgVerify.ImageUrl = "imageVerify.aspx";
    }
    catch (Exception ex) { }
}
protected void btnGo_Click(object sender, EventArgs e)
{
    //check image verification here
    if (!Session["CheckCode"].ToString().Equals(txtImgVerify.Text.Trim()))
    {
        lblVerifyMsg.Visible = true;
        return;
    }
    else
    {
        //here go on process after successful verification
    }
}

Second, create ImageVerify.aspx (for image) and put the code to code-behind as below.
using System.Drawing;
public partial class ImageVerify : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string checkCode = string.Empty;
            checkCode = CreateRandomCode(6);
            Session["CheckCode"] = checkCode;
            CreateImage(checkCode);
        }
        catch (Exception ex)
        {}
    }
    private void CreateImage(string checkCode)
    {
        Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 19))), 50);
        Graphics g = Graphics.FromImage(image);
        try
        {
            Random random = new Random();
            g.Clear(Color.AliceBlue);
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            Font font = new System.Drawing.Font("Comic Sans MS", 15, System.Drawing.FontStyle.Regular);
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, new SolidBrush(Color.Green), 10, 10);
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    public string CreateRandomCode(int codeCount)
    {
        string randomCode = "";
        try
        {
            string allChar = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(26);
                if (temp != -1 && temp == t)
                {
                    return createRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }
        catch (Exception ex)
        {
            return randomCode;
        }
    }
}

Run your application and enter the characters shown in the image and click the Go button to verify the characters. Safety Frist! :)

Saturday, March 3, 2012

How to check url is still alive in asp.net

When I develop the web directory "iblogseeker.com", I need to check blog url user input. I found out the best way to detect whether a blog is alive or not, since blog url is very important and sensitive in this case. This example show detecting url on web using System.Net.HttpWebRequest and HttpWebRequest, and ValidatorCallout and RegularExpressionValidator for validating client side user input.

ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an TextBox "txtUrl" and a validator control "RegularExpressionValidator1" as you normally do. Then add the ValidatorCallout "ValidatorCalloutExtender1" and set its TargetControlID property to reference the validator control.

Validating Url with ASP.Net

Add the following code to <form> tag.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Label ID="Label2" runat="server" Text="URL :"></asp:Label><br/>
        <asp:TextBox ID="txtUrl" runat="server" Width="250px" MaxLength="200">http://www.iblogseeker.com</asp:TextBox>
        <asp:Button ID="button1" runat="server" Text="Go" onclick="button1_Click" />
        <br />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txtUrl"
            ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"
            Display="None"
            ErrorMessage="<b>Url is not well-formatted.</b><br />
            <div style='margin-top:5px;padding:5px;border:1px solid #e9e9e9;background-color:white;'>
            <b>e.g.&nbsp;</b>
            <a href='javascript:window.open(&quot;http://www.aspmemo.net&quot;);'>http://www.aspmemo.net</a></div>">
            </asp:RegularExpressionValidator>
        <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender1"
            runat="server" Enabled="True" TargetControlID="RegularExpressionValidator1"></asp:ValidatorCalloutExtender>
        <br />
        <asp:Label ID="lblUrlMsg" runat="server"></asp:Label>
    </div>
</form>


In code-behind, button click event look like as below.

protected void button1_Click(object sender, EventArgs e)
{
    try
    {
        string url = txtUrl.Text;
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            string msg = string.Empty;
            switch (response.StatusCode)
            {
                case HttpStatusCode.OK: //HTTP status 200
                    msg = HttpStatusCode.OK.ToString();
                    break;
                case HttpStatusCode.NoContent: //HTTP status 204
                    msg = HttpStatusCode.NoContent.ToString();
                    break;
                case HttpStatusCode.NotFound: //HTTP status 404
                    msg = HttpStatusCode.NotFound.ToString();
                    break;
                case HttpStatusCode.RequestTimeout: //HTTP status 408
                    msg = HttpStatusCode.RequestTimeout.ToString();
                    break;
                case HttpStatusCode.ServiceUnavailable: //HTTP status 503
                    msg = HttpStatusCode.ServiceUnavailable.ToString();
                    break;
                case HttpStatusCode.Unauthorized: //HTTP status 401
                    msg = HttpStatusCode.Unauthorized.ToString();
                    break;
                case HttpStatusCode.MovedPermanently: //HTTP status 301
                    msg = HttpStatusCode.MovedPermanently.ToString();
                    break;
                case HttpStatusCode.BadRequest: //HTTP status 400
                    msg = HttpStatusCode.BadRequest.ToString();
                    break;
                default:
                    msg = "Invalid URL!";
                    break;
            }
            lblUrlMsg.Text = msg;
        }
    }
    catch (Exception ex)
    {
        lblUrlMsg.Text = "Invalid URL!";
    }
}

Whenever you type not-well-formatted url (including special character), it show message. if you put well-formatted url, it show HttpStatus of url.

HttpStatusCode : http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

ValidatorCallout Demonstration : http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ValidatorCallout/ValidatorCallout.aspx