Pages

Ruchi Tech

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 22 July 2012

How to create RDLC Report in C#

RDLC - Report Definition Language Client-Side

Step 1: In Solution Explorer - right click on add select new item. Select Report wizard with name like "report1.rdlc".




Step 2: In Solution Explorer - right click on add select new item. Select DataSet.



DataSet designer window is display. Right click on it and add Table Adapter.



Now Table Adapter Configuration window is display. Click on New Connection



Add Connection window is display. Now
  • Server Name- Fill your server name
  • Log on to the Server - Click on "Use SQL Server Authentication" and fill your username and password.
  • Connect to a database - select your database name.
  • Test Connection - click on it. If test connection is succeeded, then click on OK.
Click Next then select use SQL statements radio button and click next.

 
Click on Query Builder and add Table and close. There is an option of Execute Query. So use that to execute your query.

Finally, connection string is added on app.config file.

Step 3: Now, on your report1.rdlc, add datasource then Arrange Fields window is display then Drag and drop fields accordingly


Click Next and see the preview . Choose layout and style accordingly. And then click on finish.

Step 4: Add a Window Form, Form the toolbox select reporting and add Report Viewer on it.



Choose Report - Add your report "report1.rlc"
Choose Data Source - Add data source

then click on next and finish.

Now Run your application.

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() %>

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

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.

Friday, 15 June 2012

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.