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.

Monday 18 June 2012

Robots.txt and Sitemap.xml


Since working with Google and Microsoft to support a single format for submission with Sitemaps, we have continued to discuss further enhancements to make it easy for webmasters to get their content to all search engines quickly. All search crawlers recognize robots.txt, so it seemed like a good idea to use that mechanism to allow webmasters to share their Sitemaps.

robots.txt 

 

A robots.txt file is a text file in a simple format which gives information to web robots (such as search engine spiders) about which parts of your website they are and aren't allowed to visit.

User-agent: *
Disallow: /
 
The "User-agent: *" means this section applies to all robots.
The "Disallow: /" tells the robot that it should not visit any pages on the site. 

For Example: if your site is at http://www.testsite.com/ then the robot.txt must go at
http://www.testsite.com/robot.txt
 

Sitemap linking in robot.txt

This can be used to tell search engines or other robots where your sitemap is located.
For example the complete robots.txt could look like this: 

User-agent: *
Disallow:
SITEMAP: http://www.testsite.com/sitemap.xml

 

SiteMaps
 
Whereas robots.txt files are usually used to ask robots to avoid a particular part of your site, a sitemap is used to give the robot a list of pages that it is welcome to visit.

By giving the search engine a sitemap you can (hopefully) increase the number of pages that it indexes. As well as telling the search engine the URLs of your pages, the sitemap can also tell the robots when the page was last modified, the pages priority, and how often the page is likely to be updated.

We can simple use Sitemap Generator to generate the sitemap of our website.


Sitemaps for multiple domains

If you have multiple websites, you can simplify the process of creating and submitting Sitemaps by creating one or more Sitemaps that includes URLs for all your verified sites, and saving the Sitemap(s) to a single location. All sites must be verified in Webmaster Tools. You can choose to use:
  • A single Sitemap that includes URLs for multiple websites, including sites from different domains. For example, the Sitemap located at http://host1.example.com/sitemap.xml can include URLs for the following sites:
    • http://host1.example.com
    • http://host2.example.com
    • http://host3.example.com
    • http://host1.example1.com
  • Individual Sitemaps (one for each site) that all reside in a single location. For example:
    • http://host1.example.com/host1-example-sitemap.xml
    • http://host1.example.com/host2-example-sitemap.xml
    • http://host1.example.com/host3-example-sitemap.xml
    • http://host1.example.com/host1-example1-sitemap.xml
 




  

Friday 15 June 2012

Url Rewriting in IIS7

The Microsoft URL Rewrite Module 2.0 for IIS 7 enables IIS administrators to create powerful customized rules to map request URLs to friendly URLs that are easier for users to remember and easier for search engines to find. You can use the URL Rewrite module to perform URL manipulation tasks.

Creating Rewrite Rules


To test how the URL Rewrite Module works, we will use ASP.NET page called "article.aspx". This page reads the Web server variables and outputs their values in the browser.

write a label in article.aspx page:


 <asp:Label ID="lblName" runat="server"></asp:Label>

and code also in "article.aspx.cs"


string strURL = "http://" + Settings.hostUrl;

string strValue = ; // user name value

this.lblName.Text  = "<a href='" + strURL + "/article/" + 
strValue + "'>" + strName.Replace(" ", "").Replace("_", "-") 
+ "</a>" + ", ";

We will create a rewrite rule by using URL Rewrite UI in IIS Manager. To do this follow these steps:

1. Go to IIS Manager.
2. Select Default Web Site.
3. In the feature --> click Url Rewrite

4. In the Actions on the right hand side --> click Add Rule

5. In the Add rule Dialogue --> select Blank Rule


Now you must define the actual rewrite rule. In the URL Rewrite Module, a rewrite rule is defined by four required types of information:
  • Name of the rule - Enter a name that will uniquely identify the rule, for ex. "Article Url".
  • Pattern to use for matching the URL string - Enter the following string  ^article/([0-9]+)/([_0-9a-z-]+) This string is a regular expression that specifies that the pattern will match any URL string that meets the following conditions:
    1. Starts with the sequence of characters 'article/".
    2. Contains one or more numeric characters after the first "/".
    3. Contains one or more alphanumeric or "_" or "-" characters after the second "/".
  • Optional set of conditions.
  • Action to perform if a pattern is matched and whether all conditions checks succeed - Choose the Rewrite action type that is listed in the Action group box. Enter the following string article.aspx?id={R:1}&title={R:2}
The Edit Rule property page should look like:



Save the rule by click apply.

Now, View the Rewrite Url in Web.Config file



<rewrite>

  <rules>

    <rule name="Article Url">

      <match url="^article/([0-9]+)/([_0-9a-z-]+)" />

      <action type="Rewrite" url="article.aspx?id={R:1}&amp;
title={R:2}" appendQueryString="false" logRewrittenUrl="true"/>

    </rule>

  </rules>

</rewrite> 

Testing the Url

 

http://localhost/article/123/title-name

You should see that the rewrite rule on your Web server has changed the original URL to Article.aspx and it has passed "123" and "title-name" as values for query string parameters.

Done.You have learned how to configure URL Rewrite Rules by using IIS Manager or by manually editing Web.config files. 

Create,Populate & Remove dynamic textbox at runtime using javascript

In this article I will explain how to create, save and remove dynamic textbox at run time in asp.net using JavaScript. JavaScript is a very useful language for client side scripting. Often you need to add control dynamically in your page. Sometimes you need customization according to client selection criteria. JavaScript is very handy to fulfill these. There are many ways to add a control dynamically using JavaScript.

To start with i added code in default.aspx

 <head runat="server">  
   <title></title>  
   <script src="scripts/dynamictextbox.js" type="text/javascript">
</script>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <asp:HiddenField ID="hdnValues" runat="server" />  
    <asp:HiddenField ID="addMore" runat="server" />  
   <img alt="" src="../images_common/blank.jpg" 

onload="javascript:showaddElement('<%=strID%>','<%=objvalue%>');" />  
   <div>  
     <table>  
       <tr>  
         <td style="width: 100%">  
           <table width="100%">  
             <tr>  
               <td style="width: 20%" align="left">  
                 TextBox1  
               </td>  
               <td style="width: 20%" align="left">  
                 TextBox2  
               </td>  
               <td style="width: 20%" align="left">  
                 TextBox3  
               </td>  
             </tr>  
       </table> </td> </tr>  
       <tr>  
         <td style="width: 100%">  
              <%-- For Only Example--%>  
           <div id="showexDiv" runat="server">  
             <table style="width: 100%">  
               <tr>  
                 <td style="width: 25%">  
                   <asp:TextBox ID="txt1" runat="server" 
Text="example1" Enabled="false"></asp:TextBox>  
                 </td>  
                 <td style="width: 25%">  
                   <asp:TextBox ID="txt2" runat="server" 
Text="example2" Enabled="false"></asp:TextBox>  
                 </td>  
                 <td style="width: 25%">  
                   <asp:TextBox ID="txt3" runat="server" 
Text="example3" Enabled="false"></asp:TextBox>  
                 </td>  
                 <td style="width: 25%">  
                   <a href="javascript:;" onclick="addElement();">
AddMore</a>  
                 </td>  
               </tr>  
             </table>  
           </div>  
           <div id="showmyDiv" runat="server">  
             <table style="width: 100%">  
               <tr>  
                 <td style="width: 25%">  
                 </td>  
                 <td style="width: 25%">  
                 </td>  
                 <td style="width: 25%">  
                 </td>  
                 <td style="width: 28%">  
                   <a href="javascript:;" onclick="addElement();">
AddMore</a>  
                 </td>  
               </tr>  
             </table>  
           </div>  
         </td>  
       </tr>  
       <tr>  
         <td colspan="4">  
           <table style="width: 100%">  
             <tr>  
               <td>  
                 <div id="myDiv">  
                 </div>  
               </td>  
             </tr>  
           </table>  
         </td>  
       </tr>  
     </table>  
   </div>  
   </form>  
 </body>  

then write code in default.aspx.cs file

  public static string strID = "";  
     public static string objvalue = "";  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       this.showexDiv.Attributes.Add("style", "display:inline");  
       this.showmyDiv.Attributes.Add("style", "display:none");  
     }  
     private void SaveData()  
     {  
       // write code for save textbox values in DB  
       hdnValues.Value = ""; // give value from DB  
       if (hdnValues.Value != "")  
       {  
         this.showmyDiv.Attributes.Add("style", "display:inline");  
         this.showexDiv.Attributes.Add("style", "display:none");  
       }  
       else  
       {  
         this.showexDiv.Attributes.Add("style", "display:inline");  
         this.showmyDiv.Attributes.Add("style", "display:none");  
       }  
     }  

Add code in dynamictextbox.js file

 var numi;  
 var num;  
 var count;  
 function showaddElement(id, txtvalue) {  
   var data = txtvalue.split('>>')  
   var txtid = data[0];  
   var txtvalues = data[1];  
   if (id == txtid) {  
     var countvalue = txtvalues.split(';');  
     count = countvalue.length;  
   }  
   numi = document.getElementById("addMore");  
   if (count > 0) {  
     numi.value = count;  
     num = (count - 1) + 2;  
     numi.value = num;  
     var newdiv = document.createElement("div");  
     var showDiv = document.getElementById("myDiv");  
     for (var i = 0; i < count; i++) {  
       var newdiv = document.createElement("div");  
       var divIdName = "my" + (i + 1) + "Div";  
       newdiv.setAttribute("id", divIdName);  
       var cvalue = countvalue[i].split(',');  
       newdiv.innerHTML = newdiv.innerHTML + '<input type="text" 
value="' + cvalue[0] + '" id="txt1' + (i + 1) + '" 
disabled="true"/>&nbsp;';  
       newdiv.innerHTML = newdiv.innerHTML + '<input type="text" 
value="' + cvalue[1] + '" id="txt2' + (i + 1) + '" 
disabled="true"/>&nbsp;';  
       newdiv.innerHTML = newdiv.innerHTML + '<input type="text" 
value="' + cvalue[2] + '" id="txt3' + (i + 1) + '"
disabled="true"/>&nbsp;';  
       newdiv.innerHTML = newdiv.innerHTML + '<input type="button" 
value="Populate" id="btnRemove' + (i + 1) + '" 
onclick="removeElement(\'' + divIdName + '\',this)"/>';  
       newdiv.innerHTML = newdiv.innerHTML + '<br>';  
       showDiv.appendChild(newdiv);  
     }  
   }  
   else {  
     num = (document.getElementById("addMore").value - 1) + 2;  
     numi.value = num;  
   }  
 }  
 function addElement() {  
   var orgDV = document.getElementById("myDiv");  
   GetchildControls(orgDV);  
   var newdiv = document.createElement("div");  
   var divIdName = "my" + num + "Div";  
   newdiv.setAttribute("id", divIdName);  
   newdiv.innerHTML = newdiv.innerHTML + '<input type="text" value="" 
id="txt1' + num + '" />&nbsp;';  
   newdiv.innerHTML = newdiv.innerHTML + '<input type="text" value="" 
id="txt2' + num + '" />&nbsp;';  
   newdiv.innerHTML = newdiv.innerHTML + '<input type="text" value="" 
id="txt3' + num + '" />&nbsp;';  
   newdiv.innerHTML = newdiv.innerHTML + '<input type="button" 
value="Populate" id="btnRemove' + num + '" onclick="removeElement(
\'' + divIdName + '\',this)"/>';  
   num = (num - 1) + 2;  
   numi = num;  
   orgDV.appendChild(newdiv);  
 }  
 function GetchildControls(orgDV) {  
   var divs = orgDV.getElementsByTagName("div");  
   for (var i = 0; i < divs.length; i++) {  
     dv = document.getElementById(divs[i].id);  
     var collection = dv.getElementsByTagName('input');  
     for (var x = 0; x < collection.length; x++) {  
       if (collection[x].type.toUpperCase() == 'TEXT')  
         document.getElementById(collection[x].id).disabled = true;  
     }  
   }  
 }  
 function GetchildControlValues() {  
   var orgDV = document.getElementById('myDiv');  
   var divs = orgDV.getElementsByTagName("div");  
   var hdnValues = document.getElementById("hdnValues");  
   hdnValues.value = "";  
   for (var i = 0; i < divs.length; i++) {  
     dv = document.getElementById(divs[i].id);  
     var collection = dv.getElementsByTagName('input');  
     for (var x = 0; x < collection.length; x++) {  
       if (collection[x].type.toUpperCase() == 'TEXT') {  
         if (hdnValues.value == "") {  
           if (document.getElementById(collection[x].id).value != "")  
             hdnValues.value = document.getElementById(
collection[x].id).value;  
         }  
         else  
           if (document.getElementById(collection[x].id).value != "")  
             hdnValues.value = hdnValues.value + "," + 
document.getElementById(collection[x].id).value;  
       }  
       if (collection[x].type.toUpperCase() == 'BUTTON') {  
         if (hdnValues.value != "")  
           hdnValues.value = hdnValues.value + "BUTTON";  
       }  
     }  
   }  
   hdnValues.value = hdnValues.value.substring(0, 
hdnValues.value.lastIndexOf("BUTTON"));  
 }  
 function removeElement(divNum, btn) {  
   var orgDV = document.getElementById('myDiv');  
   var olddiv = document.getElementById(divNum);  
   if (btn.value.toLowerCase() == 'populate') {  
     if (olddiv != null) {  
       var collection = olddiv.getElementsByTagName('input');  
       for (var x = 0; x < collection.length; x++) {  
         if (collection[x].type.toUpperCase() == 'TEXT')  
           document.getElementById(collection[x].id).disabled = false;  
         if (collection[x].type.toUpperCase() == 'BUTTON')  
           document.getElementById(collection[x].id).value = "Remove";  
       }  
     }  
   }  
   else if (btn.value.toLowerCase() == 'remove') {  
     orgDV.removeChild(olddiv);  
   }  
 }  

Just drop me a comment if you have any suggestion, comments or query.

Wednesday 13 June 2012

Sending Automated Emails using C# Windows Service

This article explains the creation of a C# Windows Service to send Automated Emails depends on frequency daily, weekly or monthly.Concepts are involved for sending mail automatically are SMTP Server for sending mails, Window service used to mail automatically, Event log is used to see whether the window service is working.

1. Window Service 

 

Windows Service is used to create a application to run in a windows sessions. windows service can automatically run,  restart or paused when the system boots , we do not show any user interface for doing the window service. 

2. Event Log 

 

Eventlog class used to create or accessing the windows event logs. Administration privileges need to write to an event log for every logs.EventLog,class method are used to read from existing logs, write entries to logs and create a logs  or delete event sources. 

3. SMTP Server


The SMTP Server Class is used to Send Mail from a SMTP Server. .Net Framework 2.0 later supports the SMTP Server class from  System.Net.Mail namespace. 
System.Net.Mail namespace supports three class
a) MailMessage - used to describe the messages.
b) MailAddress -  used to define the sender and recipients.
c) Attachments - used to attach the file along with the mail.

4. Timer

 

.Net providers timer component is a server-based timer allows you to specify interval and the elapsed event is raised in your application. This event to provide regular processing. while create a service that uses a timer to periodically , it will check the server is running or not. 

Let’s get started with the creation of Windows Service.

  1. Open VS 2010
  2. File -- New -- Project
  3. Select ‘Visual C#’ -- Windows -- Windows Service --"SchedulerService"
  4. Delete default program file and change/move the main method in Service1.cs
  5. Add log.txt in bin folder
To access Database, add app.config file. To add app.config file -
  1. Right click 'SchedulerService’ in the solution explorer –- Select ‘Add New Item’.
  2. Select ‘Visual C#’ -- Select Application Configuration File -- Click ADD.
Put the following code in the created app.config file –

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="testconnection" value="Data Source=...;Initial Catalog=...;User ID=...;pwd=..;"></add>
<add key="StartTime" value="05:12 PM "/>
<add key="callDuration" value="2"/>
<add key="CallType" value="1"/> 
<add key="fromAdd" value=".................." />
<add key="BccAdd" value="................" />
</appSettings
<system.net>
      <mailSettings>
        <smtp from="..............">

          <network host="localhost" password="........." userName="......"/>
        </smtp>
      </mailSettings>
  </system.net>
</configuration>


Now, Writing code to Service1.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using Microsoft.Win32;
using System.Timers;
using System.Threading;
using System.IO;
using System.Security;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Xml;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Web;


namespace SchedulerService
{
    public class ScheduleService : System.ServiceProcess.ServiceBase
    {
        private string timeString;
        private System.ComponentModel.IContainer components;
        private System.Timers.Timer timer;
        public int getCallType;

        public ScheduleService()
        {
            InitializeComponent();
            int strTime = Convert.ToInt32(ConfigurationSettings.AppSettings["callDuration"]);
            getCallType = Convert.ToInt32(ConfigurationSettings.AppSettings["CallType"]);
            if (getCallType == 1)
            {
                timer = new System.Timers.Timer();
                double inter = (double)GetNextInterval();
                timer.Interval = inter;
                timer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
            }
            else
            {
                timer = new System.Timers.Timer();
                timer.Interval = strTime * 1000;
                timer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
            }
        }

        private double GetNextInterval()
        {
            timeString = ConfigurationSettings.AppSettings["StartTime"];
            DateTime t = DateTime.Parse(timeString);
            TimeSpan ts = new TimeSpan();
            int x;
            ts = t - System.DateTime.Now;
            if (ts.TotalMilliseconds < 0)
            {
                ts = t.AddDays(1) - System.DateTime.Now;
            }
            return ts.TotalMilliseconds;
        }

        private void timerElapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();
            System.Threading.Thread.Sleep(1000000);
            SetTimer();
        }

        private void SetTimer()
        {
            try
            {
                double inter = (double)GetNextInterval();
                timer.Interval = inter;
                timer.Start();
            }
            catch (Exception ex)
            {
            }
        }

        [STAThread]
        static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ScheduleService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }

        private void InitializeComponent()
        {
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.ServiceName = "EmailFrequencyScheduler";
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        protected override void OnStart(string[] args)
        {
            timer.AutoReset = true;
            timer.Enabled = true;
            string urlLogPath = System.Windows.Forms.Application.StartupPath + "\\Schedulerlog\\log.txt";
            string file = urlLogPath;
            if (File.Exists(file))
            {
                File.AppendAllText(file, "\n=================\n");
                File.AppendAllText(file, "Onstart" + System.DateTime.Now + " \r\n " );
            }
            else
            {
                File.Create(urlLogPath);
                File.AppendAllText(file, "File created on --" + System.DateTime.Now + " ");
                File.AppendAllText(file, "Onstart" + System.DateTime.Now + " \r\n ");
            }
        }

        protected override void OnStop()
        {
            timer.AutoReset = false;
            timer.Enabled = false;
        }

        private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            string timeInterval = ConfigurationSettings.AppSettings["callDuration"];
            string strondemand = ConfigurationSettings.AppSettings["testconnection"];
            string urlLogPath = System.Windows.Forms.Application.StartupPath + "\\Schedulerlog\\log.txt";
            string file = urlLogPath;

            try
            {
                DataTable dtemail = new DataTable();
                string strSql = "Select * from Email ";
                SqlConnection con = new SqlConnection(strondemand);
                con.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(strSql, con);
                adapter.Fill(dtemail);
                string strSub = string.Empty;
                string strquery = string.Empty;
                string strAttachFile = string.Empty;
                if (dtemail.Rows.Count > 0)
                {
                    foreach (DataRow dremail in dtemail.Rows)
                    {
                        string strEmailTo = Convert.ToString(dremail["Email"]);
                        string frequency = Convert.ToString(dremail["Frequency"]);
                        string strEmailID = Convert.ToString(dremail["id"]);
                        strAttachFile = "C:\\Inetpub\\wwwroot\\EmailSchedule" + strEmailID + ".xls";

                        if (Convert.ToString(dremail["ScheduleDate"]) == "" || Convert.ToString(dremail["ScheduleDate"]) == null)
                        {
                            DateTime strUpDate;
                            DateTime currentDate = DateTime.Now; ;
                            DateTime UpdatedDate = currentDate;

                            if (Convert.ToString(dremail["Frequency"]) == "Daily")
                            {
                                strSub = "Report - Daily email";
                                strUpDate = currentDate;
                                strquery = "update Email set ScheduleDate = '" + strUpDate  + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                SqlCommand cmd = new SqlCommand(strquery, con);
                                cmd.ExecuteNonQuery();
                                sendEmailReport(strEmailTo, strSub, strAttachFile);
                            }
                            if (Convert.ToString(dremail["Frequency"]) == "Weekly")
                            {
                                strSub = "Report - Weekly email";
                                strUpDate = currentDate.AddDays(7);
                                strquery = "update Email set ScheduleDate = '" + strUpDate  + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                SqlCommand cmd = new SqlCommand(strquery, con);
                                cmd.ExecuteNonQuery();
                                sendEmailReport(strEmailTo, strSub, strAttachFile);
                            }
                            if (Convert.ToString(dremail["Frequency"]) == "Monthly")
                            {
                                strSub = "Report - Monthly email";
                                strUpDate = currentDate.AddMonths(1);
                                strquery = "update Email set ScheduleDate = '" + strUpDate + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                SqlCommand cmd = new SqlCommand(strquery, con);
                                cmd.ExecuteNonQuery();
                                sendEmailReport(strEmailTo, strSub, strAttachFile);
                            }
                        }
                        else
                        {
                            DateTime strtime = DateTime.Now;
                            TimeSpan span = new TimeSpan();
                            if (Convert.ToString(dremail["Frequency"]) == "Daily")
                            {
                                strSub = "Report - Daily email";
                                DateTime strlastdate = Convert.ToDateTime(dremail["ScheduleDate"]);
                                span = strtime.Subtract(strlastdate);
                                if (span.Minutes >= 59)
                                {
                                    strquery = "update Email set ScheduleDate = '" + strtime + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                    SqlCommand cmd = new SqlCommand(strquery, con);
                                    cmd.ExecuteNonQuery();
                                    sendEmailReport(strEmailTo, strSub, strAttachFile);
                                }
                            }
                            if (Convert.ToString(dremail["Frequency"]) == "Weekly")
                            {
                                strSub = "Report - Weekly email";
                                DateTime strlastdate = Convert.ToDateTime(dremail["ScheduleDate"]);
                                span = strtime.Subtract(strlastdate);
                                if (span.Days == 7)
                                {
                                    strquery = "update Email set ScheduleDate = '" + strtime + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                    SqlCommand cmd = new SqlCommand(strquery, con);
                                    cmd.ExecuteNonQuery();
                                    sendEmailReport(strEmailTo, strSub, strAttachFile);
                                }
                            }
                            if (Convert.ToString(dremail["Frequency"]) == "Monthly")
                            {
                                strSub = "Report - Monthly email";
                                DateTime strlastdate = Convert.ToDateTime(dremail["ScheduleDate"]);
                                span = strtime.Subtract(strlastdate);
                                if (span.Days == 30)
                                {
                                    strquery = "update Email set ScheduleDate = '" + strtime + "' where id ='" + Convert.ToString(dremail["id"]) + "'";
                                    SqlCommand cmd = new SqlCommand(strquery, con);
                                    cmd.ExecuteNonQuery();
                                    sendEmailReport(strEmailTo, strSub, strAttachFile);
                                }
                            }
                            if (File.Exists(file))
                            {
                                File.AppendAllText(file, "\n=================\n");
                                File.AppendAllText(file, "Span :" + span.Days);
                            }
                            else
                            {
                                File.Create(urlLogPath);
                                File.AppendAllText(file, "File created on --" + System.DateTime.Now + " ");
                                File.AppendAllText(file, "Span :" + span.Days);
                            }
                        }
                    }
                }

                string strResponse = "Mail is send successfully";

            }
            catch (Exception ex)
            {
                if (File.Exists(file))
                {
                    File.AppendAllText(file, "\n=================\n");
                    File.AppendAllText(file, ex.Message.ToString());
                }
                else
                {
                    File.Create(urlLogPath);
                    File.AppendAllText(file, "File created on --" + System.DateTime.Now + " ");
                    File.AppendAllText(file, ex.Message.ToString());
                }
            }
            if (getCallType == 1)
            {
                timer.Stop();
                System.Threading.Thread.Sleep(1000000);
                SetTimer();
            }
        }

        private void sendEmailReport(string strEmailTo, string strSubject, string strEmailAttachFile)
        {
            string urlLogPath = System.Windows.Forms.Application.StartupPath + "\\Schedulerlog\\log.txt";
            string file = urlLogPath;
            MailMessage MailMsg = new MailMessage();
            try
            {
               

                // Add your code to send Email

                smtpClient.Send(MailMsg);
                if (File.Exists(file))
                {
                    File.AppendAllText(file, "\n=================\n");
                    File.AppendAllText(file,  "Email sent to "+strEmailTo+" " + System.DateTime.Now + " \r\n ");
                }
                else
                {
                    File.Create(urlLogPath);
                    File.AppendAllText(file, "File created on --" + System.DateTime.Now + " \r\n ");
                    File.AppendAllText(file, "Email sent to " + strEmailTo + " " + System.DateTime.Now + " \r\n ");
                }
            }
            catch (Exception ex)
            {
                if (File.Exists(file))
                {
                    File.AppendAllText(file, "\n=================\n");
                    File.AppendAllText(file, ex.Message.ToString());
                }
                else
                {
                    File.Create(urlLogPath);
                    File.AppendAllText(file, "File created on --" + System.DateTime.Now + " ");
                    File.AppendAllText(file, ex.Message.ToString());
                }
            }
            finally
            {
                MailMsg.Attachments.Dispose();
                MailMsg.Dispose();
            }
        }   
    }
}


 

Once written coding,compile if no error occurs. Then  Rightclick in design mode -- Select Add installer -- it will create two components
a) ServiceProcessInstaller -- used to define the windows service work in which account.Here we can set the account type as LocalSystem,User,Network service. In my project i have used LocalSystem
b) ServiceInstaller -- Set ServiceName for ex. (EmailFrequencyScheduler) and Starttype as Automatic.

Once Set the property and Build. Now created web service.

Now, Create Windows Service Setup project

 

1. In solution explorer, Add new project -- select setup and deployment under other project types and add setup named "EmailSchedulerService". Add Project Output -- Primary Output in Application folder and log.txt (which is previously added in bin folder) file also. It looks like.....

2. In Solution Explorer, right-click the EmailSchedulerService setup project -- point to View -- then choose Custom Actions. And add Primary Output to  four nodes of custom actions i.e. Install, Commit, Rollback and Uninstall. Looks like...


3. In Solution Explorer, right-click the EmailSchedulerService setup project and choose Build.


The complete Folder structure would be -


Install the Windows Service

 

To install, right-click the setup project in the Solution Explorer and select Install
To uninstall, right-click the setup project in the solution explorer and select uninstall options. 

Stop and Start Window Service 

 

Click Start --> Programs --> Control Panel –> Administrative Tools –> Services --> click Start.


View event log files 

 

Click Start --> Programs --> Control Panel –> Administrative Tools –> Event Viewer –> Applications and Services Logs.  

Debug Window Service

 

1. Build the Solution.
2. Start your Service.
3. While your Service is starting, Goto --> Debug --> Attach Process
4. Make sure "Show Process from all users" and "Show Process in all sessions" are checked.
5. Find your "" in the list and click "Attach".
6. You should now be at the breakpoint you inserted.
     
Download Files: EmailScheduler.rar
 
Its Done. Please feel free to send your feedback. Thank you.