CountDown -Timer ajax control c#.net Asp.net

Task: CountDown Timer in ASP.NET using AjaxControl Toolkit

Description: Sometime we need to countdown timer on website as for bidding website or any else. Then we can use Ajax control to achieve this task. Here I created code for countdown timer (server time).
I used server countdown timer because for bidding we need server time not client machine time which used in javascript code.

note : need ajax control toolkit to add first.
It is freely available at http://www.asp.net/ajaxlibrary/AjaxControlToolkitSamlpleSite/
Here, you can find many sample code for how use ajax controls in your website.

In addition I make CSS for round corner of DIV tag. my div is as a circle.

////////////////
//Design Page ... Save it as timer.aspx
//////////////////


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="timer.aspx.cs" Inherits="timer" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .circle
        {
         text-align:center;
        float:left;
        width:60px;
        height:60px;
        background-color:#ffffff;
        border: 1px solid #000000;
        padding:20px 20px 20px 20px;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
     
         font-family:Cambria;
         font-size:35px;
        }
        .styletable
        {
          font-family:Cambria;
            font-size:15px;
         font-weight:bold;
        }
     </style>
</head>
<body>
    <form id="countdowntimerform" runat="server">
    <div><br />
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
         <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
        </asp:Timer>
        <br />
        <br />
        <table width="260">
        <tr>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label3" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label4" runat="server"></asp:Label></div></td>
        </tr>
        <tr align="center"><td><b>DAYS</b></td><td><b>HOURS</b></td><td><b>MIN</b></td><td><b>SEC</b></td></tr></table
        </ContentTemplate>
        </asp:UpdatePanel>
         </div>
    </form>
</body>
</html>



/////////////////////////////////////////////////////////////////////////////////////
Code Behind File    Save it as timer.aspx.cs
///////////////////////////////////////////////////////////////////////////////


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

public partial class timer : System.Web.UI.Page
{
    static DateTime setdt;
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
         DateTime dt = DateTime.Now;
         TimeSpan differ;
         System.DateTime date1 = new System.DateTime(2013, 4, 1, 20, 10, 0);
         differ = date1.Subtract(dt);
         double  t = differ.TotalSeconds;
       
           if (t>0)
           {
               double yr, mnth, dy, h, m, s;
               dy = differ.Days;
               h = differ.Hours;
               m = differ.Minutes;
               s = differ.Seconds;
               Label1.Text = dy.ToString();// +" Days " + h + " Hours " + m + " Minutes " + s + " Seconds left for celebration";
               Label2.Text = h.ToString();
               Label3.Text = m.ToString();
               Label4.Text = s.ToString();
           }
           else
           {
               Timer1.Enabled = false;
           }
    }
}
///////////////////////////////////////END OF C#.NET/ASP.NET CODE////////////////////////////////

Remove Html Tags from a String, C#.NET, ASP.NET


Task: Remove HTML tags from a string.

Description: When we update content using WYSIWYG HTML editor (ck-editor) then it used HTML tag for formatting the content. But some time we need the same content without any formatting so then we require the removing HTML tag from that content.

Here I use two variation for this first one is using a simple loop And Second one is using Regex.

// How convert a html tag to blank space in a string using c#.net/asp.net code
// Replacing the html tag <> to blank space, you can copy data with html tag and then convert to normal text
// eg. INPUT   -->  <div width="5">Hemant Singh <i>Rautela</i></div>
        OUTPUT--> Hemant Singh Rautela

//
//C#.NET , ASP.NET
// Method 1 : (Using Character Array)

 public string replace(string s)
 {
    int l = s.Length;
    int j = 0;
    char[] ch = s.ToCharArray();
    s = "";
    for (int i = 0; i < l; i++)
    {
        if (ch[i] == '<')
            j = 1;
        if (j == 1)
        {
            if (ch[i] == '>')
                j = 0;
            ch[i] = ' ';
        }
        s = s + ch[i].ToString();
    }
    return (s);
 }


// Method 2 (Using Regular Expressions- Regex)

 using System.Text.RegularExpressions;
 public string replace(string s)
 {
   String result = Regex.Replace(s, @"<[^>]*>", String.Empty);
 }

Trimming String C#.NET, ASP.NET Remove all extra space

Task:  Remove Extra spacing from a string(paragraph). Trimming the space from String.

Description:  Here I create a code for removing extra space from a string as Trimming externally and as well as internally also. So that two and more consecutive space will remove.

C#.NET,SQL SERVER, ASP.NET HELP

      public string replacespace(string s)
    {
        int l = s.Length;
        char[] ch = s.ToCharArray();
        s = "";
        for (int i = 0; i < l - 1; i++)
        {
            if (ch[i] == ' ')
            {
                if (ch[i + 1] == ' ')
                { }
                else
                    s = s + ch[i];
            }
            else
                s = s + ch[i];
        }
        if (ch[l - 1] != ' ')
            s = s + ch[l - 1];
        return (s);
    }


How to set Database Connection in C#.NET - ASP.NET for Excel, Access and Sql Server

// How to set connection string in c#.net /asp.net for 1)Excel , 2)MS-Acess and  3)Sql Server
// You can set connection string in your web.config file as describe below...

//Below Code describe the first step of ADO.Net , Set Connection string to connect .Net to database for communication between them.

<connectionStrings>
<add name="hhcsnot"  connectionString="Server=database_server_ip;Initial Catalog=databasename;User ID=username;Password=yourpassword"/>
</connectionStrings>



//1. EXCEL TO .NET-[Top]
// How Retrieve Data From Excel to Gridview in C#.NET , ASP.NET
//Database Connection String for Excel 2003 for C#.NET, ASP.NET HELP 
//
using System.Data.OleDb;
 protected void btn_showst_Click()
    {
        OleDbConnection con;
        try
        {
            string file = "book";
            string fn = "Sheet1";
            string fname2 = "[" + fn + "$]";
            con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\" + file + ".xls;Extended Properties=Excel 8.0;");
            con.Open();
            OleDbCommand cmd = new OleDbCommand("select * from " + fname2 + "", con);
            OleDbDataReader dr;
            dr = cmd.ExecuteReader();
            GridView1.DataSource = dr;
            GridView1.DataBind();
            con.Close();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }


/// 2. MS-ACCESS  TO .NET-[Top]
//Connection String for ms-access to C#.NET, ASP.NET 
// How Retrieve Data From Access to Gridview 


using System.Data.OleDb;
protected void btn_showst_Click()
    {
    OleDbConnection con;

    con = new OleDbConnection("Microsoft.Jet.OLEDB.4.0"      connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\databasename.mdb");

   // Here Access database should be in App_Data Folder..


  con.Open();
  OleDbCommand cmd = new OleDbCommand("select * from  tablename", con);
  OleDbDataReader dr;
  dr = cmd.ExecuteReader();
  GridView1.DataSource = dr;
  GridView1.DataBind();
  con.Close();
}

// 3. Sql Server To .NET -[Top]
// Connection String For Sql Server to C#.NET, ASP.NET
// How retrieve Data From Sql Server to Gridview


using System.Data.SqlClient;


protected void btn_showst_Click()
    {

SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\Database.mdf; Integrated Security=True;User Instance=True");
 // Here Sql Database file should be in App_Data Folder..

// or
con.Open();
SqlCommand com = new SqlCommand("select * from " + tablename + " ", con);
SqlDataReader dr = com.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
 con.Close();
}

NOTE : //////   Two Type of SqlConnection String First for sql file and Second for sql server you have to almost use 2nd type. Passing IP address of Database server , database name , User id & password.

SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\Database.mdf; Integrated Security=True;User Instance=True");

// In below Server name or ip address is come there , Initial Catalog for Database name; user id -password // is sql user id and password by defaul sql user is 'sa' and password you should be set it 
//
SqlConnection con = new SqlConnection( "Server=127.0.0.1;Initial Catalog=Database;User ID=sa;Password=123456" );



-[Top]

Manage CSS & Message Box(javascript) using C#.NET , ASP.NET Code at run time...

Task:  How can open a pop-up message box using asp.net or add css/javascript using c# code. (JavaScript alert box).

Description:  After the completing some task we have to show a message for user so that we need a message box. Here the first code is for creating a CSS dynamically using code and second one for generating a message box using c# asp.net code.

C# Code : For Dynamic Css C# Code

  protected void Page_Load(object sender, EventArgs e)
    {
  string c = "#f0ff0f";
        string d = "#0f0f00";
        LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        color:" + c + @";
                    }
                    .d:hover
                    {
                        color:" + d + @";
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
    }

.

////////////////// Message Box in asp.net/c#.net website

C# Code : For Message Box in Asp.Net C#

    public void msgbox(string message)
    {
        string msg = @"alert('" + message + "');";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "s1", msg, true);
    }




File/Image Updation or delete it using C#.Net , Asp.Net

 // FILE OR IMAGE DELETION AND CREATION ( Use for delete the Image) (UPDATING
// THE PREVIOUS FILE using c#.net , asp.net


using System.Drawing;
using System.IO;

public void filedel()        
    {
        string path = Server.MapPath(@"images\");
        string imgurl = path + "a.jpg";
        try
        {
            FileInfo TheFile = new FileInfo(imgurl);
            if (TheFile.Exists)
            {
                File.Delete(imgurl);   // It not works if file is used in another process
            }
            else
            {
               // File.Create(imgurl);
            //or
            // Code To Create image
            Bitmap bmp = new Bitmap(2, 2);
            bmp.Save(imgurl, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
            }
            Label1.Text = "Sucess";
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }

Advance Email Sending(With Attachment) Code(C#.NET with ASP.NET) using gmail


 Advance Email Sending Option , with attachement.
Task: Sending Email with attachment using c# code in asp.net website/ web application.
Description: Some time we need to a website viewer can send a enquiry with some attachment as  some kind of career option where a candidate can submit his/her resume and the website administrator receive the same within email.

As in my previous post I discuss about a email notification http://hemantrautela.blogspot.com/2012/08/how-to-send-email-from-website-aspnet.html without attachment option , Now we require a email with attachment, I use below code for sending email with attachment . Here I use two fileupload control for uploading attachment file (here I am not checking the extension of file / as you can check it first before sending email ).

// Below Function can be used for sending a email with attachment option using c# code
//  using gmail crdential
using System.Net.Mail;
public bool mailattachement2(string to, string replyto, string body, string subject, FileUpload f1, FileUpload f2)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress("xyz@gmail.com","Client Enquiry");
        mail.Subject = subject;
        mail.Body = body;
        MailAddress rt = new MailAddress(replyto);
        mail.ReplyTo = rt;
        //mail.Sender = rt;
        mail.IsBodyHtml = true;
        if (f1.HasFile)
        {
            mail.Attachments.Add(new Attachment(f1.PostedFile.InputStream, f1.FileName)); //add the attachment
        }
        if (f2.HasFile)
        {
            mail.Attachments.Add(new Attachment(f2.PostedFile.InputStream, f2.FileName)); //add the attachment
        }

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "password");
// Set the one email id and its password for authentication )
// email goes via using above email id...

        smtp.Port = 587;
        smtp.EnableSsl = true;
        try
        {
            smtp.Send(mail);
            return (true);
        }
        catch (Exception ex)
        {
            return (false);
        }
    }