Pages

Ruchi Tech

Tuesday, 26 June 2012

Show Online Users/Visitors in ASP.Net website

There are many ways to show online users/visitors in asp.net website.

Step:1 First, we need to add these lines in global.asax file



void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["OnlineUsers"] = 0;
    }
 
    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
        Application.UnLock();
    }
 
    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
        Application.UnLock();
    }

This will show that whenever distinct visitors opens our website in different browsers, and new session is created for him, our Online Users variable is increased in the global HttpApplicationState.

And when user closed browsers and does not click on any links then session will expires and Online Users variable is decreased.

Step:2 We need to enable SessionState and configure its mode also. To do that need to add these lines in web.config


  <system.web>
    <sessionState mode="InProc" cookieless="false" timeout="20" />
  </system.web>
 
  • In Proc mode stores session state value and variable in memory on the local web server. This mode is the only that supports Session_End event.
  • Timeout value (i.e in minutes) configure how long our sessions are kept alive. In this example, Timeout is set to 20 minutes that means, when the user click on some link on our website at least one time in 20 minutes, then users is considered as online but if they do not open any page or click on any link in 20 minutes then they are considered as offline.

So now we are done with the configuration steps. To show the number of online users/visitors, add these line in your aspx page

  Users/Visitors online: <%= Application["OnlineUsers"].ToString() %>

Monday, 25 June 2012

Paging in SQL Server 2011 (Denali)

SQL Server 2011 has been launched with exciting features and lots enhancement for SQL developers.
You can see syntax in MSDN.

Lets start, how paging works in SQL Server 2011:

Create Table with data like so:


Now lets use Order By with Offset Clause. When you specify Order By Clause with Offset then number of rows specified with Offset are ignored and remaining records are returned.


Select * from PagingData Order By Id Offset 3 rows

Output like so:


So you can see number of rows specified with Offset has been skipped.

Note: SQL will throw error if Order By is not used in query.

Now Limit the numbers of rows after Offset like


Select * from PagingData Order By Id Offset 3 Rows Fetch next 3 rows only

Now Let’s see, How We can use Stored Procedure to return Page Wise Data.


  Create Procedure Usp_GetPageWisePagingData  
    (  
    @PageNumber Int,  
    @RecordPerPage Int  
    )  
    AS  
    Begin  
    Select * From PagingData  
    Order By Id  
    Offset ((@PageNumber-1)*@RecordPerPage) Rows  
    Fetch Next @RecordPerPage Rows Only  
    End  
    Go   
Accordingly Passed two parameters named PageNumber (which is record page number), and RecordPerPage (which is number of record) in stored procdure, we will get the result paging wise.

Sunday, 24 June 2012

Create a Captcha Image in C# .NET

Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart.)

The Captcha technology help you to make sure your site is reasonably secure against automated attacks.

Step:1 Write the following code in a class named CaptchaText.cs or you can download it here


public class CaptchaText
{
   public string Text
   {
     get { return this.text; }
   }
   public Bitmap Image
   {
     get { return this.image; }
   }
   public int Width
   {
     get { return this.width; }
   }
   public int Height
   {
     get { return this.height; }
   }

   private string text;
   private int width;
   private int height;
   private string familyName;
   private Bitmap image;
   private Random random = new Random();
   public CaptchaText(string s, int width, int height)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.GenerateImage();
   }
   public CaptchaText(string s,int width,int height,string familyName)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.SetFamilyName(familyName);
     this.GenerateImage();
   }
   ~CaptchaText()
   {
     Dispose(false);
   }
   public void Dispose()
   {
     GC.SuppressFinalize(this);
     this.Dispose(true);
   }
   protected virtual void Dispose(bool disposing)
   {
     if (disposing)
     this.image.Dispose();
   }
   private void SetDimensions(int width, int height)
   {
    if (width <= 0)
    throw new ArgumentOutOfRangeException("width",width,"Argument out of range,
                                                                                must be greater than zero.");
    if (height <= 0)
    throw new ArgumentOutOfRangeException("height",height,"Argument out of range,
                                                                                must be greater than zero.");
    this.width = width;
    this.height = height;
   }
   private void SetFamilyName(string familyName)
   {
      try
      {
        Font font = new Font(this.familyName, 12F);
        this.familyName = familyName;
        font.Dispose();
      }
      catch (Exception ex)
      {
        this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
      }
   }
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width,this.height,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
HatchBrush hatchBrush=new HatchBrush(HatchStyle.SmallConfetti,Color.LightGray,Color.White);
g.FillRectangle(hatchBrush, rect);
   SizeF size;
   float fontSize = rect.Height + 1;
   Font font;
   do
   {
     fontSize--;
     font = new Font(this.familyName, fontSize, FontStyle.Bold);
     size = g.MeasureString(this.text, font);
   } while (size.Width > rect.Width);

  StringFormat format = new StringFormat();
  format.Alignment = StringAlignment.Center;
  format.LineAlignment = StringAlignment.Center;
 GraphicsPath path = new GraphicsPath();
 path.AddString(this.text,font.FontFamily,(int)font.Style,font.Size,rect,format);
 float v = 4F;
 PointF[] points =
 {
  new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
  new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
  new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
  new PointF(rect.Width - this.random.Next(rect.Width) / v,rect.Height - 
                                                                                      this.random.Next(rect.Height) / v)
  };
    Matrix matrix = new Matrix();
    matrix.Translate(0F, 0F);
    path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
    hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
    g.FillPath(hatchBrush, path);
    int m = Math.Max(rect.Width, rect.Height);
    for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
      {
            int x = this.random.Next(rect.Width);
            int y = this.random.Next(rect.Height);
            int w = this.random.Next(m / 50);
            int h = this.random.Next(m / 50);
            g.FillEllipse(hatchBrush, x, y, w, h);
      }
         font.Dispose();
         hatchBrush.Dispose();
         g.Dispose();
         this.image = bitmap;
    }
 } 

Step:2 Create a page named "Captcha.aspx" and add code in Captcha.aspx.cs


protected void Page_Load(object sender, EventArgs e) {   if (Session["CaptchaImageText"] != null)    {       CaptchaText ci = new CaptchaText(this.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook");        this.Response.Clear();        this.Response.ContentType = "image/jpeg";        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);        ci.Dispose();    }  }


Step:3 Now Call Captcha.aspx in that page you want to appear it for ex: "Default.aspx"

Add code in Default.aspx


<table width="100%">     <tr>       <td align="left">         <img id="imgcaptcha" runat="server" src="~/Captcha.aspx" alt="Enter the code shown" />        </td>     </tr>     <tr>       <td align="left">           <asp:Label runat="server" ID="lblBox" Text="Enter the code shown"></asp:Label>            <br />           <asp:TextBox ID="CodeNumberTextBox" runat="server"></asp:TextBox>           <asp:Label ID="lblerrCaptcha" runat="server" Visible="false"></asp:Label>         </td>      </tr>     <tr>      <td align="left">         <asp:LinkButton ID="lnkGetQuotes" Text="GetQuotes"  runat="server" OnClick="btnGetQuotes_Click">      </td>    </tr> </table>

Now,Compare that to value to what the users had keyed in to your text box, To do that add code in Default.aspx.cs


private Random random = new Random();
 protected void Page_Load(object sender, EventArgs e)
 {
   if (!IsPostBack)
    {
       Session["CaptchaImageText"] = "";
       Session["CaptchaImageText"] = GenerateRandomCode();
    }
 }
private string GenerateRandomCode()
{
            string s = "";
            for (int i = 0; i < 6; i++)
                s = String.Concat(s, this.random.Next(10).ToString());
            return s;
}
protected void btnGetQuotes_Click(object sender, EventArgs e)
{
   if (Convert.ToString(Session["CaptchaImageText"]) != "" &&
             Convert.ToString(CodeNumberTextBox.Text) != "")
   {
     if (CodeNumberTextBox.Text == Session["CaptchaImageText"].ToString())
     { 
        // add your code for the button
     }
    else
     {
         lblerrCaptcha.Visible = true;
         lblerrCaptcha.Text = "Please enter the correct code";
     }
}
else
   {
          lblerrCaptcha.Visible = true;
          lblerrCaptcha.Text = "Please enter the code"; 
   }
} 

The output is like as:


Thats it, Congratulations you have created your Captcha Image in your website.

Thursday, 21 June 2012

Draw a graph in c# .net

I’m going to give you a tutorial about how to draw graphs using a component called Chart



I first created a new application, added the Chart component in "Default.aspx"



It looked like this. Lets start coding

In Default.aspx


<asp:Chart ID="Chart2" runat="server" ViewStateContent="All" 
Width="670px" Palette="Bright" BackColor="LightGray"
BackGradientStyle="LeftRight" BorderlineColor="Transparent"
PaletteCustomColors="128, 128, 255">
<Series>             <asp:Series Name="Series1" BackGradientStyle="TopBottom"
BorderColor="Red" ChartType="Spline" IsValueShownAsLabel="True"

LabelBackColor="White" Legend="Legend1" MarkerStyle="Circle"
YValuesPerPoint="2"> </asp:Series>         </Series>         <ChartAreas>             <asp:ChartArea BackColor="#00CCCC" BorderDashStyle="Solid" IsSameFontSizeForAllAxes="True" Name="ChartArea1">                 <AxisY ArrowStyle="Triangle" InterlacedColor="Black" Title="Number of visitor" TitleForeColor="DarkCyan"></AxisY>                 <AxisX ArrowStyle="Triangle" InterlacedColor="Black"
Interval="1" Title="Month" TitleForeColor="DarkCyan"></AxisX>             </asp:ChartArea>         </ChartAreas>         <Legends>             <asp:Legend BackColor="#D2D2D2" LegendStyle="Row" Name="Legend1" TableStyle="Wide" Title="System"></asp:Legend>         </Legends>         <Titles>         </Titles>     </asp:Chart>

In Default.aspx.cs


string path = ConfigurationManager.ConnectionStrings["ConnectionPath"]
              .ConnectionString;

        SqlConnection con = new SqlConnection(path);

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = con;

        con.Open();

        cmd.CommandText = "SELECT TOP 5 premium, StateID, State 

         FROM PremiumCollection GROUP BY StateID, State";

        cmd.CommandType = CommandType.Text;

        SqlDataAdapter adp = new SqlDataAdapter(cmd);

        DataSet dt = new DataSet();

        adp.Fill(dt);

        con.Close();

        Chart2.DataSource = dt;

        Chart2.Legends.Add("leads");

        Chart2.Series["Series1"].XValueMember = "StateID";

        Chart2.Series["Series1"].YValueMembers = "premium";

        Chart2.Series["Series1"].MarkerBorderColor = 
                                           System.Drawing.Color.Red;

        Chart2.DataBind();

and add the following lines in Web.config file


 <handlers>

      <remove name="ChartImageHandler" />

      <add name="ChartImageHandler" preCondition="integratedMode" 
      verb="GET,HEAD,POST"

        path="ChartImg.axd" type="System.Web.UI.DataVisualization.
    Charting.ChartHttpHandler, System.Web.DataVisualization, 
    Version=4.0.0.0, Culture=neutral, 
    PublicKeyToken=31bf3856ad364e35" />

    </handlers>

The result is looked like shown the above graph image.Anything you would like to add, please use the comment area below.

Wednesday, 20 June 2012

Data binding using LINQ in c#

This article shows how you can connect to a database, get data from a database table, and display it in a DataGrid control. 

Step 1: Creating a C# LINQ ASP.NET Web Site

Step 2: Adding LINQ to SQL class in App_Code in your ASP.NET Web Site

Add your database and required table in this class. After adding, the model looks like


Step 3: Creating your first ASP.NET page using LINQ

Create a new page called "linq.aspx".  Within the .aspx page add a DataGrid control like so:

<asp:DataGrid ID="datagrd1" runat="server" CellPadding="4" CellSpacing="4" Width="100%" EnableViewState="False" AutoGenerateColumns="false">        <HeaderStyle BackColor="ActiveBorder" />             <Columns>                 <asp:TemplateColumn>                     <HeaderTemplate>                          <asp:Label runat="server" Text="User"></asp:Label>                     </HeaderTemplate>                  <ItemTemplate>                         <asp:Label ID="lbluser" runat="server" Text='<%# Eval("user") %>'></asp:Label>                   </ItemTemplate>                 </asp:TemplateColumn>              </Columns>              <Columns>                  <asp:TemplateColumn>                      <HeaderTemplate>                         <asp:Label runat="server" Text="City"></asp:Label>                      </HeaderTemplate>                      <ItemTemplate>                         <asp:Label ID="lblcity" runat="server" Text='<%# Eval("city") %>'></asp:Label>                      </ItemTemplate>                 </asp:TemplateColumn>              </Columns>              <Columns>                 <asp:TemplateColumn>                     <HeaderTemplate>                         <asp:Label runat="server" Text="Age"></asp:Label>                     </HeaderTemplate>                     <ItemTemplate>                        <asp:Label ID="lblage" runat="server" Text='<%# Eval("age") %>'></asp:Label>                     </ItemTemplate>                 </asp:TemplateColumn>             </Columns>
</asp:DataGrid>

Within the code-behind file we’ll then write the code for binding the datagrid like:

DataClassesDataContext dc = new DataClassesDataContext("ur_connection_string");
protected void Page_Load(object sender, EventArgs e)     {         if (!IsPostBack)         {                        dc.Connection.Open();             var q = from a in dc.aaas                     select new                     {                         user = a.user.ToString().Trim(),                         city = a.city.ToString().Trim(),                         age = a.age.ToString().Trim(),                     };             datagrd1.DataSource = q;             datagrd1.DataBind();         }     }
compile and run the program. The result like so:

This post gives you a little idea of how you can bind LINQ to DataSet query results, please let me know what kind of questions you’d like to see answered, and I will do my best to answer them.

Tuesday, 19 June 2012

Bind dropdown list using JSON,JQuery in asp.net

In this article i will show you how to bind a DropDownList using JSON, JQuery to avoid page refresh via a Web Method .It is very useful and many time we require to use Jquery Ajax.

Code to Bind dropdownlist in asp.net 

Add code in "Default.aspx" page

download jquery.js
 
<head runat="server">
<title></title>
    
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" language="javascript">
        $().ready(function () {
            $.ajax({
                type: "POST",
                url: "Default2.aspx/GetGenders",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                
                    $("#ddlGender").get(0).options.length = 0;
                    $("#ddlGender").get(0).options[0] = new Option
("Select Gender", "-1");

                    $.each(msg.d, function (index, item) {
                        $("#ddlGender")
.get(0).options[$("#ddlGender").get(0).options.length] = 
new Option(item.Display, item.Value);
                    });

                    $("#ddlGender").bind("change", function () {
                        GetNames($(this).val());
                    });
                },
                error: function () {
                    alert("Failed to load Genders");
                }
            });
        });

        function GetNames(genderID) {
            if (genderID > 0) {
                $("#ddlName").get(0).options.length = 0;
                $("#ddlName").get(0).options[0] = 
new Option("Loading names", "-1");

                $.ajax({
                    type: "POST",
                    url: "Default2.aspx/GetNames",
                    data: "{genderID:" + genderID + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#ddlName").get(0).options.length = 0;
                        $("#ddlName").get(0).options[0] = 
new Option("Select name", "-1");

                        $.each(msg.d, function (index, item) {
                            $("#ddlName")
.get(0).options[$("#ddlName").get(0).options.length] = 
new Option(item.Display, item.Value);
                        });
                    },
                    error: function () {
                        $("#ddlName").get(0).options.length = 0;
                        alert("Failed to load names");
                    }
                });
            }
            else {
                $("#ddlName").get(0).options.length = 0;
            }
        }
    </script>
    <style type="text/css">
        #ddlGender
        {
            width: 149px;
        }
        #ddlName
        {
            width: 146px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="border:1px solid gray; width:400px;">
    <table border="0" cellpadding="0" cellspacing="0" 
        style="width: 353px; height: 149px">
                <tr align="center">
                    <th>
                        Gender
                    </th>
                    <td>
                        <select id="ddlGender">
                        </select>
                    </td>
                </tr>
                <tr align="center">
                    <th>
                        Name
                    </th>
                    <td>
                        <select id="ddlName">
                        </select>
                    </td>
                </tr>
            </table>
            </div>
    </form>
</body> 

 

and in "Default.aspx.cs"


[WebMethod]
    public static ArrayList GetGenders()
    {
        return new ArrayList()
            {
                new { Value = 1, Display = "Male" },
                new { Value = 2, Display = "Female" }
            };
    }

    [WebMethod]
    public static ArrayList GetNames(int genderID)
    {
        if (genderID.Equals(1))
        {
            return new ArrayList()
                {
                    new { Value = 1, Display = "John" },
                    new { Value = 1, Display = "Tom" },
                    new { Value = 1, Display = "Harry" },
                    new { Value = 1, Display = "Bob" }
                };
        }
        else if (genderID.Equals(2))
        {
            return new ArrayList()
                {
                    new { Value = 1, Display = "Gauri" },
                    new { Value = 1, Display = "Rihana" },
                    new { Value = 1, Display = "Kate" },
                };
        }
        else
        {
            throw new ApplicationException("Invalid Gender ID");
        }
    }
The result is shown as 

Redirect 404 error to custom page

A 404 error message is the standard HTTP standard response code which is returned when the visitor cannot communicate with the server. This is a very common error on the web and it occurs when you are trying to visit a page which has either been deleted or has been moved somewhere else.

"A 404 error message usually looks something like this :

    Not Found

    The requested URL /index.php was not found on this server.


If a visitor comes to your site and sees a standard 404 error message it’s unlikely they will make the effort to see any part of your site. Therefore it is very important to create a 404 page on your site and redirect traffic from incorrect urls.

To do this just add the following line to "web.config" file


<system.web>

  <customErrors defaultRedirect="FileNotFound.aspx">

    <error statusCode="404" redirect="filenotfound.htm"/>

  </customErrors>

</system.web>

and create custom error page "filenotfound.htm" and "FileNotFound.aspx".

That’s all there is to it. Now when a visitor views an incorrect url on your site they will see your custom error page.