create update delete xml in csharp asp.net


//How to create xml file using c#.net asp.net code
//Append Node/ Modify Node in XML using c#.net asp.net
//
using System.Xml;
using System.IO;
 protected void Button1_Click(object sender, EventArgs e)

{
  string filepath = MapPath("xml/XMLFile3.xml"); // path of xml where we want to save it
   create(filepath);
}

private void create(string filepath)    // filepath is path where we want to save xml file
{
   string xml = @"<?xml version='1.0' encoding='utf-8'?>
                    <ParentXMLNode>
                    <Header>
                           <xmlnode1>value1</xmlnode1>
                           <xmlnode2>value2</xmlnode2>
                    </Header>
                    <xmlnode3>value3</xmlnode3>
                    <xmlnode4>value4</xmlnode4>  
                    <Message>
                        <xmlnode5></xmlnode5>
                        <xmlnode5></xmlnode5>
                        <xmlnode6>
                               <Node1></Node1>
                        </xmlnode6>
                     </Message>
                    </ParentXMLNode>";

        XmlDocument docConfig = new XmlDocument();
        docConfig.LoadXml(xml);
        Literal1.Text = "<XMP>" + xml + "</XMP>";
        docConfig.Save(filepath);
    }

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);
        }
    }

Dynamic SEO for c# website,How To Set Html Title, Meta Keywords & Meta Description From Asp.Net(C#.Net)

Task: Put SEO stuff (Title of page, Meta keyword, Meta description) in website using c# code in asp.net website/ web application. Onsite SEO –in Dynamic Website or E-Commerce Website.

Description: Now these day SEO is a very important thing in a Website (Dynamic Website or E-Commerce Website). When we work on SEO for website then we require the setup page title, Meta keyword, Meta description. So we require option for this in admin panel for Content Management System Website.

Here I use a small function for this, you can connect it to database and call on pageload.

C# Code for Dynamic SEO

  public void settitle(string pagetitle, string metakeyword, string metadescription)
    {
        HtmlTitle obj = new HtmlTitle();
        obj.Text = pagetitle;
        Header.Controls.Add(obj);

        //  or title can be set as
        Page.Title = pagetitle;

        HtmlMeta mt = new HtmlMeta();
        mt.Name = "keywords";
        mt.Content = metakeyword;
        Header.Controls.Add(mt);

        //  or can be set as, for position of meta tag
        Header.Controls.AddAt(2,mt);

        HtmlMeta mtd = new HtmlMeta();
        mtd.Name = "description";
        mtd.Content = metadescription;
        Header.Controls.Add(mtd);

       //  or can be set as, for position of meta tag
        Header.Controls.AddAt(2,mtd);
    }

How to Send Email From Website Asp.Net C#.Net


 How to Send Email from website
Task: Send Email Notification using c# code in asp.net website/web application.
Description: Many times we want to send auto email to our website viewer or website owner. As we require after the viewer of website submits any enquiry then it should be come immediate in email Inbox Or In E-Commerce website after successfully purchasing any item a auto email notification will be send to customer (billing detail) and as well as website administrator also.
So that I use two variation of code for sending email as shown below. For this we require a email account and password for authentication.

First one is require your any one email account, password and mail server detail. The second one is for using gmail account.


using System.Web.Mail;
 public bool mailsend(string sSubject, string sBody, string sMailFrom, string sToMail)
    {
        try
        {
            MailMessage sMail = new System.Web.Mail.MailMessage();
            sMail.To = sToMail.ToString();
            sMail.From = sMailFrom.ToString();
            sMail.Subject = sSubject.ToString();
            sMail.Body = sBody.ToString();
            sMail.Priority = MailPriority.High;
            sMail.BodyFormat = MailFormat.Html;
            SmtpMail.SmtpServer = "mail.website.com"; // your mail server name

          sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");  //basic authentication
          sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "emailid");  //set your username here
          sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");  //set your password here
            SmtpMail.Send(sMail);
            return true;
        }
        catch (Exception ex)
        {
           return false;
        }
    }

// using by gmail id for authentication
 public bool mailsend(string to, string sub, string msg, string replyto)
    {
        string from = "yourmailid@gmail.com"; //Replace this with your own correct Gmail Address
        string pwd = "password"; // Replace this with your above email id password.
        bool status = false;
        System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
        email.To.Add(to);
        email.From = new System.Net.Mail.MailAddress(to, "Client", System.Text.Encoding.UTF8);
        string mailbody = msg;
        email.Subject = sub;

        email.ReplyTo = new System.Net.Mail.MailAddress(replyto,"", System.Text.Encoding.UTF8);

        email.SubjectEncoding = System.Text.Encoding.UTF8;
        email.Body = mailbody;
        email.BodyEncoding = System.Text.Encoding.UTF8;
        email.IsBodyHtml = true;
        System.Net.Mail.SmtpClient emailclient = new System.Net.Mail.SmtpClient();
        client.Credentials = new System.Net.NetworkCredential(from, pwd);
        client.Port = 587; // Gmail works on this port
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true; //Gmail works on Server Secured Layer
        try
        {
            emailclient.Send(email);
            status = true;
            return (status);
        }
        catch (Exception ex)
        {
            status = false;
            return (status);
        }
    }

On Button Click How Open A page in new window in asp.net - c# code


Task: Open a new window using c# code in asp.net website/web application. 
Description: The problem is this we can use Response.Redirect() method for redirect/open  new webpage in same window, But how we can open a new page in new window.

So that I use javascript code(alert box) for popup new window in c# code behind file as describe below. I write below code on Button Click Event.

// Dynamic Alert box javascript using c# code in asp.net

 protected void btngeneraterecipt_Click(object sender, EventArgs e)
    {
        try
        {
            string queryString = "billformat.aspx";
            string jquery = "window.open('" + queryString + "');";
            ScriptManager.RegisterStartupScript(this,this.GetType(), "pop", jquery, true);
        }
        catch (Exception ee)
        {
            Label1.Text = ee.Message;
        }
    }

Image Upload & Resize in asp.net with c#.net

         Image Upload & Resize in asp.net
Task: Upload Image & Resize it proportionally.
Description: Now days we require upload product images in a E-Commerce Website & we want to resize it also. So we can resize image when uploaded by using admin panel.

Here I use below code to resize image with its proportionally. So it will not stretch. This code is useful for jpg and png images.

using System.Drawing;
 protected void button_upload_image(object sender, EventArgs e)
    {
       if (FileUpload1.PostedFile.ContentLength != 0)
       {
           string temp = Server.MapPath(@"images\");
           string path = temp + "hemant.jpg";
           temp = temp + "temp.jpg";
           FileUpload1.SaveAs(temp);
           setimagesize(temp, path, 800, 600,400,300);
        } 
    }



// Call this function for resizing ( compress height and width proportionally )
// destination and imagepath must be differ
 protected void setimagesize(string imagepath, string destination, int maxwidth, int maxheight,int minwid,int minhight)
    {
        string path = imagepath.ToString();
        string dest = destination.ToString();

        System.Drawing.Image img1 = System.Drawing.Image.FromFile(path); // source of large image
        int owd = Convert.ToInt32(img1.Width);
        int oht = Convert.ToInt32(img1.Height);
        //       Compress Large Image Height/Width to according our canvas max(800*600)
        int nwd, nht;
        nwd = owd;
        nht = oht;
        if (owd > oht)
        {
            if (owd > maxwidth)                                // For Maximum width
            {
                nwd = maxwidth;
                nht = oht * maxwidth / owd;
            }
            else if (owd < minwid)                      // For minimum width
            {
                nwd = minwid;
                nht = oht * minwid / owd;
            }
        }
        else
        {
            if (oht > maxheight)                                // For Maximum height
            {
                nht = maxheight;
                nwd = owd * maxheight / oht;
            }
            else if (oht < minhight)                    //  For Minimum width
            {
                nht = minhight;
                nwd = owd * minhight / oht;
            }
        }

        ///////////////////////////
        //     Saving Compress Image
        ///////////////////////////////////////
        Bitmap bmp = new Bitmap(nwd, nht);
        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, nwd, nht);
        gr.DrawImage(img1, rectDestination, 0, 0, owd, oht, GraphicsUnit.Pixel);
        bmp.Save(dest, img1.RawFormat); //image size reduce by using this code changing by    
        bmp.Save(dest);
        bmp.Dispose();
       gr.Dispose();
        img1.Dispose();
    }