Monday 8 August 2011

Ajax Rating Control with Database

Introduction:

Here I will explain how to use Ajax rating control with database to display average rating for particular article using asp.net

Description:

Previously I explained
how to use Ajax Collapsible panel . Now I will explain how to use Ajax rating control with Database in asp.net. In many sites we will see rating options for books, articles and movies etc by giving rating option to user we have chance to know about particular thing how much users are feeling comfort with particular thing. In Ajax we have a rating control by using that we can display the rating option easily. Here I am storing each user rating details into database and displaying the average rating based on number of users rating. To achieve this first design one table in your database and give name like RatingDetails if you want to give another name you can but you need to change table name in code also.

Column Name
Data Type
Allow Nulls
Id
Int(Set Identity=true)
No
Rate
int
Yes
After completion of design table in database add AjaxControlToolkit reference to your application after that add
<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>

To your aspx page and design your page likes this

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!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 runat="server">
<title>Ajax Rating Sample</title>
<style type="text/css">
.ratingEmpty
{
background-image: url(ratingStarEmpty.gif);
width:18px;
height:18px;
}
.ratingFilled
{
background-image: url(ratingStarFilled.gif);
width:18px;
height:18px;
}
.ratingSaved
{
 background-image: url(ratingStarSaved.gif);
width:18px;
height:18px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<div>
<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>
<table width="35%">
<tr>
<td width="27%">
<b>Average Rating:</b>
</td>
<td>
<ajax:Rating ID="ratingControl" AutoPostBack="true" OnChanged="RatingControlChanged" runat="server" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
</ajax:Rating>
<b> <asp:label ID="lbltxt" runat="server"/> </b>
</td>
</tr>
<tr>
<td colspan="2">
aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
If you observe above code I define lot of properties to ajax:Rating now I will explain all the properties of Ajax rating control

AutoPostBack – This property should be true because we are storing rating details during rating item click.

OnChanged – This event is used to get how many stars user has selected.

StarCssClass – This cssclass is used for to display starts.

WaitingStarCssClass – This cssclass is used to show the starts color during saving the rating value.

EmptyStarCssClass – This cssclass is used to display empty starts color.

 FilledStarCssClass – This cssclass is used to display filled stars color.
 CurrentRating – This property is used to display Initial rating value (Number of starts to be filled initially).

MaxRating – This property is used to display maximum rating value (No. of starts here I am displaying only 5 if you want to increase starts value give property like this MaxRating=10).

ReadOnly – This property is used to make rating control read only.

RatingAlign – This property is used to set starts vertical or horizontal.

RatingDirection – This property is used to set the direction of stars(LeftToRight or TopToBottom or RightToLeft or BottomToTop).

Now in code behind add following namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After completion of adding namespaces in code behind add following code


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindRatingControl();
}
}
protected void RatingControlChanged(object sender, AjaxControlToolkit.RatingEventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RatingDetails(Rate)values(@Rating)",con);
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating);
cmd.ExecuteNonQuery();
con.Close();
BindRatingControl();
}
protected void BindRatingControl()
{
int total = 0;

DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from RatingDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
for(int i=0;i<dt.Rows.Count;i++)
{
total += Convert.ToInt32(dt.Rows[i][0].ToString());
}
int average = total/(dt.Rows.Count);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count+"user(s) have rated this article";
}
}
Now in web.config file set your database connection because in above code I am getting connection from web.config
<connectionStrings>
<add name="dbConnection" connectionString="Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"/>
</connectionStrings>

Demo


Saturday 6 August 2011

URL Re-Writing in ASP.Net

Introduction

One of the most popular extensions to the Apache webserver has been mod_rewrite - a filter which rewrites URLs. For example, instead of a URL such as
http://www.apache.org/BookDetails.pl?id=5

you could provide a filter which accepts URLs such as
http://www.apache.org/Book/5.html
and it will silently perform a server-side redirect to the first URL. In this way, the real URL could be hidden, providing an obfuscated facade to the web page. The benefits are easier to remember URLs and increasing the difficulty of hacking a website.
Mod_rewrite became very popular and grew to encompass a couple of other features not related to URL Rewriting, such as caching. This article demonstrates URL Rewriting with ASP.NET, whereby the requested URL is matched based on a regular expression and the URL mappings are stored in the standard ASP.NET web.config configuration file. ASP.NET includes great caching facilities, so there's no need to duplicate mod_rewrite's caching functionality.
As more and more websites are being rewritten with ASP.NET, the old sites which had been indexed by google and linked from other sites are lost, inevitably culminating in the dreaded 404 error. I will show how legacy ASP sites can be upgraded to ASP.NET, while maintaining links from search engines.

ASP.NET support for URL Rewriting

ASP.NET provides very limited support out of the box. In fact, it's support is down to a single method:
void HttpContext.RewritePath(string path)
which should be called during the Application_BeginRequest() event in the Global.asax file. This is fine as long as the number of URLs to rewrite is a small, finite, managable number. However most ASP sites are in some way dynamic, passing parameters in the Query String, so we require a much more configurable approach.
The storage location for all ASP.NET Configuration information is the web.config file, so we'd really like to specify the rewrites in there. Additionally, .Net has a fast regular expression processor, giving free and fast search and replace of URLs. Let's define a section in the web.config file which specifies those rewrites:
<configuration>
  <system.web>
        <urlrewrites>
            <rule>
                <url>/urlrewriter/show\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/wohs\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/show(.*)\.asp</url>
                <rewrite>show.aspx?$1</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/(.*)show\.html</url>
                <rewrite>show.aspx?id=$1&amp;cat=2</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/s/h/o/w/(.*)\.html</url>
                <rewrite>/urlrewriter/show.aspx?id=$1</rewrite>
            </rule>
        </urlrewrites>
    </system.web>
</configuration>
Notice how we have to escape the period in the url element such as 'show\.asp'. This is a Regular Expression escape and it's a small price to pay for the flexibility of regular expressions. These also show how we set-up a capturing expression using (.*) in the <url> element and refer to that capture in the <rewrite> element with $1

Configuration Section Handlers

.Net's configuration mechanism requires us to write code as a "handler" for this section. Here's the code for that:
<configuration>
    <configSections>
        <sectionGroup name="system.web">
          <section name="urlrewrites" type="ThunderMain.URLRewriter.Rewriter,
              ThunderMain.URLRewriter, Version=1.0.783.30976,
              Culture=neutral, PublicKeyToken=7a95f6f4820c8dc3"/>
        </sectionGroup>
    </configSections>
</configuration>
This section handler specifies that for every section called "urlrewrites", there is a class called ThunderMain.URLRewriter.Rewriter which can be found in the ThunderMain.URLRewriter.dll assembly with the given public key token. The public key token is required because this assembly has to be placed into the GAC and therefore given a strong name.
A section handler is defined as a class which implements the IConfigurationSectionHandler interface. This has one method, Create(), which should be implemented, and in our code that is very simple. It merely stores the urlrewrites element for later use:

public object Create(object parent, object configContext, XmlNode section) 
{
    _oRules=section;

    return this;
}

Initiating the rewrite process

Coming back to actually rewriting the URL, as I said earlier, we need to do something in the Application_BeginRequest() event in Global.asax - we just delegate this to another class:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
    ThunderMain.URLRewriter.Rewriter.Process();
}
which calls the static method Process() on the Rewriter class. Process() first obtains a reference to the configuration section handler (which happens to be an instance of the current class) and then delegates most of the work to GetSubstitution() - an instance method of this class.
public static void Process() 
{
    Rewriter oRewriter=
       (Rewriter)ConfigurationSettings.GetConfig("system.web/urlrewrites");

    string zSubst=oRewriter.GetSubstitution(HttpContext.Current.Request.Path);

    if(zSubst.Length>0) {
        HttpContext.Current.RewritePath(zSubst);
    }
}
GetSubstitution() is just as simple - iterating through all possible URL Rewrites to see if one matches. If it does, it returns the new URL, otherwise it just returns the original URL:
public string GetSubstitution(string zPath) 
{
    Regex oReg;

    foreach(XmlNode oNode in _oRules.SelectNodes("rule")) {
        oReg=new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch=oReg.Match(zPath);

        if(oMatch.Success) {
            return oReg.Replace(zPath,
                             oNode.SelectSingleNode("rewrite/text()").Value);
        }
    }

    return zPath;
}

Installing the sample code

Extract the code into a URLRewriter folder, then turn this into a virtual directory using the Internet Information Services MMC control panel applet. Compile the code use the 'Make Rewriter.bat' batch script into the bin sub-folder. Then add bin/ThunderMain.URLRewriter.dll to the Global Assembly Cache by copying and pasting the dll into %WINDIR%\assembly using Windows Explorer. Finally, navigate to http://localhost/URLRewriter/default.aspx and try the demo URLs listed.
None will actually work because there's one last thing we have to be aware of...

Finally

There's one major caveat with all this. If you want to process a request with a file extension other than .aspx such as .asp or .html, then you need to change IIS to pass all requests through to the ASP.NET ISAPI extension. Unfortunately, you will need physical access to the server to perform this, which prevents you from simply XCOPY deploying your code to an ISP.

We've added the HEAD, GET and POST verbs to all files with .* file extension (ie all files) and mapped those to the ASP.NET ISAPI extension - aspnet_isapi.dll.

The complete range of mappings, including the new .* mapping.

Friday 5 August 2011

How to Attach Holidays Detail with Calendar Control?

HTML Code :

<body>
<form id="form1" runat="server">
<div>
<div>
<p style="text-align: center"><b><asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Arial Black" Font-Size="Medium"ForeColor="#0066FF">Indian List of Holidays 2011</asp:Label><br /></b></p>
<asp:Calendar ID="Calendar1" runat="server" BackColor="#FFFFCC" BorderColor="#FFCC66"BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"ForeColor="#663399" ShowGridLines="True" OnDayRender="Calendar1_DayRender" OnSelectionChanged="Calendar1_SelectionChanged"OnVisibleMonthChanged="Calendar1_VisibleMonthChanged"><SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
<SelectorStyle BackColor="#FFCC66" />
<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#CC9966" /><NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" ForeColor="#FFFFCC" />
</asp:Calendar><br /><b></b>
<asp:Label ID="LabelAction" runat="server"></asp:Label><br />
</b>
</div>
</div>
</form>
</body>


C# Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;

public partial class calender : System.Web.UI.Page
{
    Hashtable HolidayList;

protected void Page_Load(object sender, EventArgs e)
    {
        HolidayList = Getholiday();
        Calendar1.Caption = "Calender - Author: Espranza";
        Calendar1.FirstDayOfWeek = FirstDayOfWeek.Sunday;
        Calendar1.NextPrevFormat = NextPrevFormat.FullMonth;
        Calendar1.TitleFormat = TitleFormat.MonthYear;
        Calendar1.ShowGridLines = true;
        Calendar1.DayStyle.Height = new Unit(50);
        Calendar1.DayStyle.Width = new Unit(50);
        Calendar1.DayStyle.HorizontalAlign = HorizontalAlign.Center;
        Calendar1.DayStyle.VerticalAlign = VerticalAlign.Middle;
        Calendar1.OtherMonthDayStyle.BackColor = System.Drawing.Color.AliceBlue;
    }

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {if (HolidayList[e.Day.Date.ToShortDateString()] != null)
        {
            Literal  literal1 = new Literal();
            literal1.Text = "<br/>";
            e.Cell.Controls.Add(literal1);
            Label label1 = new Label();
            label1.Text = (string)HolidayList[e.Day.Date.ToShortDateString()];
            label1.Font.Size = new FontUnit(FontSize.Small);
            label1.Font.Bold = true;
            e.Cell.Controls.Add(label1);
        }
    }

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        LabelAction.Text = "Date changed to :" + Calendar1.SelectedDate.ToShortDateString();
    }

protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {
        LabelAction.Text = "Month changed to :" + e.NewDate.ToShortDateString();
    }

private Hashtable Getholiday()
    {
        Hashtable holiday = new Hashtable();
        holiday["1/1/2011"] = "New Year";
        holiday["1/5/2011"] = "Guru Govind Singh Jayanti";
        holiday["1/8/2011"] = "Muharam (Al Hijra)";
        holiday["1/14/2011"] = "Pongal";
        holiday["1/26/2011"] = "Republic Day";
        holiday["2/23/2011"] = "Maha Shivaratri";
        holiday["3/10/2011"] = "Milad un Nabi (Birthday of the Prophet";
        holiday["3/21/2011"] = "Holi";
        holiday["3/21/2011"] = "Telugu New Year";
        holiday["4/3/2011"] = "Ram Navmi";
        holiday["4/7/2011"] = "Mahavir Jayanti";
        holiday["4/10/2011"] = "Good Friday";
        holiday["4/12/2011"] = "Easter";
        holiday["4/14/2011"] = "Tamil New Year and Dr Ambedkar Birth Day";
        holiday["5/1/2011,5/1/2011"] = "May Day";
        holiday["5/9/2011"] = "Buddha Jayanti and Buddha Purnima";
        holiday["6/24/2011"] = "Rath yatra";
        holiday["8/13/2011"] = "Krishna Jayanthi";
        holiday["8/14/2011"] = "Janmashtami";
        holiday["8/15/2011"] = "Independence Day";
        holiday["8/19/2011"] = "Parsi New Year";
        holiday["8/23/2011"] = "Vinayaka Chaturthi";
        holiday["9/2/2011"] = "Onam";
        holiday["9/5/2011"] = "Teachers Day";
        holiday["9/21/2011"] = "Ramzan";
        holiday["9/27/2011"] = "Ayutha Pooja";
        holiday["9/28/2011"] = "Vijaya Dasami (Dusherra)";
        holiday["10/2/2011"] = "Gandhi Jayanti";
        holiday["10/17/2011"] = "Diwali & Govardhan Puja";
        holiday["10/19/2011"] = "Bhaidooj";
        holiday["11/2/2011"] = "Guru Nanak Jayanti";
        holiday["11/14/2011"] = "Children's Day";
        holiday["11/28/2011"] = "Bakrid";
        holiday["12/25/2011"] = "Christmas Day";
        holiday["12/28/2011"] = "Muharram";return holiday;
    }
}