Pages

Subscribe:

Ads 468x60px

Monday, October 15, 2012

How to Go back from current webpage in asp.net suing c#

In this web Programming tutorial we will learn that how we can go back from Current web page to previous one by clicking on the HTML button.
 

How to print a web page using javascript.

In this web Programming tutorial we will learn that how we can add Printing functionality on our web page using javascript in a asp.net or simple html page. see the below code and just copy and paste it.
 
Code to use in HTML part you want to print.
  
// Content Will goes here you want to print.

how to reboot or Restart your computer from web page in asp.net using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can Restart our computer by clicking on a button from our website. So below is the dream code just copy and paste it. and use it in your button's onClick event.
 System.Diagnostics.Process.Start("shutdown.exe", "-r -t 0");

how to shutdown you computer from website in asp.net using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can shutdown our computer by clicking on a button from our website. So below is the dream code just copy and paste it. and use it in your button's onClick event.
System.Diagnostics.Process.Start("shutdown.exe", "-s -t 0")

how to sow date and time on a asp.net page using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can show simple date and time on our web page in asp.net using c#. just copy and paste the below code.
 if (!Page.IsPostBack)
        {
            lbl_date.Text = DateTime.Now.ToLongDateString();
            TxtDateTo.Text = DateTime.Today.ToString("MM/dd/yyyy");
        }  

how to call a javascript function from server side page load event in asp.net using c#

In this web programming tutorial we will learn that how we can call a javascript function from server side in asp.net using c#. see the below simple code in which we are trying to call a radiobutton click event that is defined in Client side, but we will call it on page load event in asp.net using c#. Javascript Function in head section
 
Code for Function call in .CS file on Server side in page load event.
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {    
         RBAllHis.Attributes.Add("onclick", "others()");
        }
    }       
 

Saturday, October 13, 2012

import to excel in asp.net using c#

In this web programming tutorial we will learn that how we can import our Gridview data into excel file by click on a link button from our webpage in asp.net using c#.
  protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");        
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);     
        this.ClearControls(GridView1);
        GridView1.RenderControl(htw);       
        Response.Write(sw.ToString());
        Response.End();
    }
  private void ClearControls(Control ctrl)
    {
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(ctrl.Controls[i]);
        }

        if (!(ctrl is TableCell))
        {
            if (ctrl.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                ctrl.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
                }
                catch
                {

                }

                ctrl.Parent.Controls.Remove(ctrl);
            }

            else

                if (ctrl.GetType().GetProperty("Text") != null)
                {
                    if (ctrl.Visible == true)
                    {
                        LiteralControl literal = new LiteralControl();
                        ctrl.Parent.Controls.Add(literal);
                        literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
                        ctrl.Parent.Controls.Remove(ctrl);
                    }
                }
        }
        return;

    }

how to clear all gridview elements in aps.net using c#

In this simple web Programming tutorial we will learn that how we can clear all Controls available in a gridview by just one click instead clearing one by one. like as we clear a form's text fields or other form elements. just copy the below code in your .CS file. Function call.
        this.ClearControls(GridView1);
        GridView1.RenderControl(htw);
Method to clear Gridview fields.
 private void ClearControls(Control ctrl)
    {
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(ctrl.Controls[i]);
        }

        if (!(ctrl is TableCell))
        {
            if (ctrl.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                ctrl.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
                }
                catch
                {
                }
                ctrl.Parent.Controls.Remove(ctrl);
            }
            else
                if (ctrl.GetType().GetProperty("Text") != null)
                {
                    if (ctrl.Visible == true)
                    {
                        LiteralControl literal = new LiteralControl();
                        ctrl.Parent.Controls.Add(literal);
                        literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
                        ctrl.Parent.Controls.Remove(ctrl);
                    }
                }
            }
        return;
    }


how to define session as string in asp.net using c#

In this simple web programming tutorial we will learn that how we can define a Session as string in asp.net using C# to assign it to a string veriable. see the written below code and just copy and paste it.

  string data = Session["Data_var"] as string;

How to find the Previous Page Control's value on a current page in asp.net using c#

In this web Programming tutorial we will learn that how we can find or access a control like label, Dropdown, radiobutton, textbox etc from a previous page and its value to use in current page from gridview in asp.net using c#.
See the below code and just copy and paste the code and have fun.
  
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!empty)
            {                
                Label lblcharges = e.Row.FindControl("lbl_charges") as Label;  
             }
         }  
   }

Control Function method .CS file of Current page to access the control's Value.

   private Control FindControl(string controlID, ControlCollection controls)
    {
        foreach (Control c in controls)
        {

            if (c.ID == controlID)

                return c;
            if (c.HasControls())
            {
                Control cTmp = this.FindControl(controlID, c.Controls);

                if (cTmp != null)

                    return cTmp;
            }

        }
        return null;
    }

  

Format String into Money Format in asp.net using c#

In this programming Tutorial we will learn that how we can format amount string into money. below is the code just copy and paste and use it.

string charges = "125.35";
lbl_charges_total.Text  = string.Format("{0:###,###,##0.00}", charges);

Friday, October 12, 2012

how to add new row in gridview in asp.net using c#

In this web programming tutorial we will learn how we can add new column in a Gridview when there is no record and we want to show a proper message that there is no data against particular search in asp.net using c#. see the below code and copy and past.
          
              int columncount = GridView1.Rows[0].Cells.Count;
              GridView1.Rows[0].Cells.Clear();
              GridView1.Rows[0].Cells.Add(new TableCell());
              GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
              GridView1.Rows[0].Cells[0].Text = "No Record Found ";
              GridView1.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
              GridView1.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Maroon;
          

Saturday, September 1, 2012

How to format string money or currency format in asp.net using c#

In this web programming tutorial we will learn that how we can convert a string into money format in asp.net using c#. see the below code
Total_amount.Text = string.Format("{0:###,###,##0.00}", Total_Amountdue);

Thursday, August 30, 2012

how to upload file or image on FTP using asp.net uploader in asp.net using c#

In this web programming tutorial we will learn that how we can upload an image or file directly on FTP by using asp.net file uploader control in asp.net using c# see the below code it will help us by doing so.. just copy and paste.
public void ftpfile(string ftpfilepath)
 {
     string ftphost = "Domain";
     //here correct hostname or IP of the ftp server to be given  
 
     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
     ftp.Credentials = new NetworkCredential("Domain", "Password");
     //userid and password for the ftp server to given  
 
     ftp.KeepAlive = true;
     ftp.UseBinary = true;
     ftp.Method = WebRequestMethods.Ftp.UploadFile;
      
     // Resize Image is function to resize the image 
     System.Drawing.Image img1 = 
         ResizeImage(FileUpload1.PostedFile.InputStream, 84, 118);
 
     // Convert the image into bytes Array;
     byte[] buffer = ImageToByte(img1);
  
     // Send the image file in form of bytes
     Stream ftpstream = ftp.GetRequestStream();
     ftpstream.Write(buffer, 0, buffer.Length);
     ftpstream.Close();
}

how to concatenate Strings in asp.net using C#

In this web programming tutorial we will learn that how we can concatenate strings in asp.net using c#. just copy and paste the below code.
 string practice = "Adress1" + "," Karachi ", "state" + "4600";

Saturday, June 2, 2012

how to show prompt box using javascript

In this web programming tutorial we will learn that how we can use Javascript Prompt function on our web pages. see the below code and just copy and paste it as it is.

 
    Javascript Prompt Box
 

 
      




Thursday, May 31, 2012

how to upload photo or picture in asp.net using c#

In this web programming tutorial we will learn that how we can upload a picture or photo in asp.net using c#. just copy and paste below code in you .cs file.
protected void btn_upload_Click(object sender, EventArgs e)
    {
        imageflag = 1;
 
        if (!FileUpload_image.HasFile)
        {
            Alert.Show("No file for uploading");
            return;
        }
        if (FileUpload_image.HasFile)
        {
            //string imagetype = FileUpload_image.PostedFile.ContentType;
            string[] acceptedTypes = new string[] 
            { 
                "image/bmp", 
                "image/jpeg", 
                "image/tiff", 
                "image/gif", 
                "image/png"
                     };
 
            if (!acceptedTypes.Contains(FileUpload_image.PostedFile.ContentType))
            {
                Alert.Show("This is not image file");
                return;
            }
            Bitmap image = ResizeImage(FileUpload_image.PostedFile.InputStream, 84, 118);
            string imagename = Guid.NewGuid().ToString();
            image.Save(Server.MapPath("~/Pictures/") + imagename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            Img_Employee.ImageUrl = "~/Pictures/" + imagename + ".jpg";
            image_path = "~/Pictures/" + imagename + ".jpg";
        }
 
 
    }
    private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
 
        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = (int)Math.Round(newHeight * aspectRatio);
        }
 
        return new Bitmap(originalImage, newWidth, newHeight);
    }

how to Upload Image or file on FTP in Asp.net using c#

In this web programming tutorial we will learn that how we can Upload Image or file on FTP in Asp.net File Uploader using c#.

copy the below code in your .cs file.

public void ftpfile(string ftpfilepath)
 {
     string ftphost = "your domain name ";
     //here correct hostname or IP of the ftp server to be given  
 
     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
     ftp.Credentials = new NetworkCredential("your Domain", "Password");
     //userid and password for the ftp server to given  
 
     ftp.KeepAlive = true;
     ftp.UseBinary = true;
     ftp.Method = WebRequestMethods.Ftp.UploadFile;
      
     // Resize Image is function to resize the image 
     System.Drawing.Image img1 = 
         ResizeImage(FileUpload1.PostedFile.InputStream, 84, 118);
 
     // Convert the image into bytes Array;
     byte[] buffer = ImageToByte(img1);
  
     // Send the image file in form of bytes
     Stream ftpstream = ftp.GetRequestStream();
     ftpstream.Write(buffer, 0, buffer.Length);
     ftpstream.Close();
}

Saturday, May 26, 2012

how to disable right click using jquery

In this web programming tutorial we will learn that how we can prevent right click functionality in browser (this code snipit will work in all browsers).


    
    
    





how to create Tab menu widget using jquery

In this web programming tutorial we will learn that how can use jquery tabs widget using jquery UI.


    
    
    
    

    


    

This is tab one data.

This is tab two data.

This is tab three data.


how to generate image button dynamically in asp.net using c#

In this web programming tutorial we will learn that how we can create an image button dynamically in asp.net using c#. see the below code and put it in your .cs file in page load event.
protected void Page_Load(object sender, EventArgs e)
    {
        ImageButton imgBtn;
        imgBtn = new ImageButton();
        imgBtn.Attributes.Add("onclick", "javascript:return false;");
        imgBtn.ImageUrl = "~/sample.jpg";
        imgBtn.ID = "img_Tooltip";
        imgBtn.ToolTip = "www.web-healer.blogspot.com";
        imgBtn.CssClass = "img_tooltip_Style";
        imgBtn.Height = 50;
        imgBtn.Width = 100;
        form1.Controls.Add(imgBtn);
    }

Thursday, May 24, 2012

how to add text to image in asp.net using c#

In this web programming tutorial we will learn that how we can add some text on an image in asp.net using c#.just copy and page the code and add it in your .cs file.
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System;

public partial class About : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string inputImage = @"E:\color.jpg";
        string outputImageFilePath = @"E:\Resultimage.jpg";
        string textToDisplayOnImage = "www.webhealer.blogspot.com/";

        Bitmap imageInBitMap = new Bitmap(inputImage);
        Graphics imageGraphics = Graphics.FromImage(imageInBitMap);

        //Set the alignment based on the coordinates 
        StringFormat formatAssignment= new StringFormat();
        formatAssignment.Alignment = StringAlignment.Near;
        
        //Here we are going to assign the font color
        Color assignColorToString = System.Drawing.ColorTranslator.FromHtml("#000000");

        //Assigning font size, font family, position of the text to display and others.
        imageGraphics.DrawString(textToDisplayOnImage, new Font("Times new Roman", 8, FontStyle.Bold), new SolidBrush(assignColorToString), new Point(100, 150), formatAssignment);

        //saving in the computer
        imageInBitMap.Save(outputImageFilePath);
    }
}

Monday, May 21, 2012

how to use span tag on a web page using html

In this web programming tutorial we will learn about span tag by using it on a web page using html.

span tag is used to provide an additional structure to an html document. It is used to group and apply style sheet to inline elements of a web page. it can be used to gave characteristics to specific part of other elements.

below is the code example how to use spam tag.

This is a paragraph this is a paragraph this is a paragraph

this is a paragraph

output

This is a paragraph this is a paragraph this is a paragraph

this is a paragraph


how to use div tag on a web page using html

In this web programming tutorial we will learn that how we can use div tag in an html document or in a web page.

div tag is normally used to define a section in an html document or in a web page div tag is a pair tag and must be used a closing tag in order to complete the tag

this is div tag
output
this is div tag

how to use font tag in html

In this web programming tutorial we will learn that how we can use font tag in an html document or in a web page.
 this text is with Verdana font 
 this text is with arial font 
 this text is with helvitica font 
 this text is with impact font 
this text is with Verdana font
this text is with arial font
this text is with helvitica font
this text is with impact font

how to use different format text in html

In this web programming tutorial we will learn that how we can use different type of text format in an web page or in an html document. see the below code.

here is the code to make text bold

in order to make text bold
output:
in order to make text bold

here is the code to make text italic

in order to make text bold
output:
in order to make text Italic

here is the code to make text underline

in order to make text underline
output:
in order to make text underline

here is the code to make text super script

in order to make text Super Script
output:
in order to make text Super Script

here is the code to make text Sub script

in order to make text Sub Script
output:
in order to make text Super Script


how to use horizontal line tag in html

in this web programming tutorial we will learn that how we can use HR tag in an html document or in a web page using html.
 






how to use line break tag using html

In this web programming tutorial we will learn that how we can use Line Break tag in an html document tag.
Line breaks are used to decide where the text will break on a line or continue to the end of the window. it can be used to move the control to the next new line.
see the below code and example syntax of code of line break tag
this is line one<br>

this is line tow<br> 

this is line three<br> 


how to use paragraph tag in html

in this web programming tutorial we will learn that how we can use paragraph tag in an html document or in a web page.

paragraph tag are used in a document to add text in such a way that it will automatically adjust the end of line to suit the window size of the browser.

see the below example of paragraph tag

  

this is paragraph tag


how to use heading tag in html

in this web programming tutorial we will learn that how we can use heading tag heading in a html page.
headings are very important part of any web page. it is used to display different type of heading in HTML document
heading tag is a pair tag, pair tag means every opening tag must have a closing tag.
see the below code of heading tags. it has 6 types as follows

this is heading type 1

this is heading type 2

this is heading type 3

this is heading type 4

this is heading type 5
this is heading type 6
Output

this is heading type 1

this is heading type 2

this is heading type 3

this is heading type 4

this is heading type 5
this is heading type 6

Thursday, May 17, 2012

how to create basic html page

in this web programming tutorial we will learn that how we can create a basic html page. just copy and paste the below code in any editor such as note pad and save the file as test.html. just double click to run the page.

 
   my first page
 
 
     this is body of the page. web-healer.blogspot.com


Sunday, May 13, 2012

How to generate random numbers in asp.net using c#

in this we programming tutorial we will learn that how we can create random number in asp.net using c#. see the below code and just copy and paste.
Random rand = new Random((int)DateTime.Now.Ticks);
        int numIterations = 0;
        numIterations=  rand.Next(1, 100);
        Response.Write(numIterations.ToString());

Wednesday, April 18, 2012

How to sum the value of gridview column in asp.net using jquery and c#

In this web programming tutorial we will learn that how we can SUM the grid view columns values in asp.net using c#.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>




    
    
    


    
Code for .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        grdItems.DataSource = new Item().Items;
        grdItems.DataBind();

    }

}
public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }

    public List Items
    {
        get
        {
            return new List()
                       {
                           new Item(){Name = "Item01",Quantity = 10,Price = 180M},
                           new Item(){Name = "Item01",Quantity = 11,Price = 184M},
                           new Item(){Name = "Item01",Quantity = 12,Price = 190M},
                           new Item(){Name = "Item01",Quantity = 13,Price = 110M},
                       };
        }
    }
}

how to re-write url in asp.net using c#

In this web programming tutorial we will learn that how we can re-write url in asp.net, as it is very important and common and most difficult task for an asp.net developer to re-write url. For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net
Step 1: Download Binary Files for URLRewriter.Net
Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.
Step 3: Update Web.Config File to make URLRewriter.Net works.


Step 4: Adding Function to Generate SEO Friendly URL from given Title
public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
   strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}

Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.



   
       
                      
       
   
   
       
           
       
   









how to Send Email from Gmail in asp.net using c#

In this web programming tutorial we will learn that how we can send email from Gmail in asp.net using c#, see the below code and just copy and paste.

protected void btnSendEmail_Click(object sender, EventArgs e)
{
//Create Mail Message Object with content that you want to send with mail.
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("faisalpitafi@gmail.com","israrpatafi@yahoo.com",
"This is the mail subject", "Just wanted to say Hello");

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
System.Net.NetworkCredential mailAuthentication = new
System.Net.NetworkCredential("irfanpitafi@gmail.com", "myPassword");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);

//Enable SSL
mailClient.EnableSsl = true;

mailClient.UseDefaultCredentials = false;

mailClient.Credentials = mailAuthentication;

mailClient.Send(MyMailMessage);
}

how to Disable Multiple Button Click in Asp.net using jquery, javascript and c#

In this web programming tutorial we will learn that How to make a button disable immediately when user clicks it in asp.net so that user cannot click multiple time.




Code for body section


Note: onclick event is calling javascript client-side function and onserverclick event is calling server-side function which performs actual task.
This task can be any as per your logic, for an example I am performing some heavy time consuming task, you can even make use of Threading concept to minimize code.
Server-Side Event to perform actual task
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 1000; j++)
{
a.Add(i.ToString() + j.ToString());
}
}
Response.Write("I am done: " +
DateTime.Now.ToLongTimeString());
}

How to enable/disable dropdownlist combobox through a checkbox selection in asp.net using jquery

In this web programming tutorial we will learn that how we can enable/disable dropdownlist control through checkbox selection in asp.net.



    
    
    


    


How to Add copy to clipboard button on page

In this web programming tutorial we will learn how to add or PUT add copy to clip board button functionality on your html or asp.net page copy the below code in your html page.




    

Thursday, April 12, 2012

how to get IP address of visitor using php

In this web programming tutorial we will learn that how we can get or track real (orignal) IP address of visitor of our page.
return !empty($_SERVER['HTTP_CLIENT_IP']) ?
$_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ?
$_SERVER['HTTP_X_FORWARDED_FOR'] : (!empty($_SERVER['REMOTE_ADDR']) ?
$_SERVER['REMOTE_ADDR'] : null));

Wednesday, April 11, 2012

how to access web method or server side data at client side in asp.net using c#

In this web programming tutorial we will learn that how we can access server side data using Json ajax call at client side using asp.net or php. see the below code and just copy and past in your .aspx or .php file.
function BindPaymentRecord(txnId) { var request = "{'TXN_ID':'" + txnId + "'}"; $.ajax({ type: "POST", url: "Invoice.aspx/BindPaymentDetail", data: request, contentType: "application/json; charset=utf-8", dataType: "json", success: SuccessPaymentRecord }); } function BindChargesRecord(txnId) { var request = "{'TXN_ID':'" + txnId + "'}"; $.ajax({ type: "POST", url: "Invoice.aspx/BindChargesDetail", data: request, contentType: "application/json; charset=utf-8", dataType: "json", success: ChargesSuccessData }); } function SuccessPaymentRecord(data) { document.getElementById('<%=A_Paid.ClientID %>').innerHTML = data.d[0]; document.getElementById('<%=C_ref.ClientID %>').innerHTML = data.d[1]; document.getElementById('<%=C_Bal.ClientID %>').innerHTML = data.d[2]; document.getElementById('<%=Error.ClientID %>').innerHTML = data.d[3]; document.getElementById('<%=P_Method.ClientID %>').innerHTML = data.d[4]; document.getElementById('<%=P_date.ClientID %>').innerHTML = data.d[5]; }

how to generate barcode in asp.net using c#

In this web programming tutorial we will learn that how we can generate barcode in asp.net using c#, as it is often used in different projects and web developers have to face problem, see the below code and just copy and past in your page.
Code for .CS file

using System;
using System.Data;
using System.Drawing.Imaging;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Bytescout.BarCode;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Create new barcode
Barcode barcode = new Barcode();

// Set symbology
barcode.Symbology = SymbologyType.Code39;
// Set value
barcode.Value = "Sample";

// Clear http output
Response.Clear();
// Set the content type to PNG
Response.ContentType = "image/png";
// Add content type header
Response.AddHeader("Content-Type", "image/png");
// Set the content disposition
Response.AddHeader("Content-Disposition", "inline;filename=result.png");

// Save image to output stream
barcode.SaveImage(Response.OutputStream, ImageFormat.Png);

// End response
Response.End();

}
}

how to Writing a Text Files Line Counter in asp.net using c#

In this web programming tutorial we will learn that how we can Writing a Text Files Line Counter in asp.net using c#, Bellow is the code, it's so simple that I'm lazy to explain, enjoy:
DirectoryInfo dInfo = new DirectoryInfo(args[0]);
FileInfo[] Files = dInfo.GetFiles("*.php");
int i = 0;
foreach (FileInfo fInfo in Files)
{
  string[] temp = File.ReadAllLines(fInfo.FullName);
  i += temp.Length;
}
Console.WriteLine("Total Lines: " + i);
Console.ReadLine();

Sunday, March 25, 2012

what is a static member of the Class in asp.net using c#


Static Members
One of the tricks about .NET classes is that you really use them in two ways. You can use some
class members without creating an object first. These are called static members, and they’re
accessed by class name.

Foreach loop in asp.net using C#


In this web programming we will learn the use of foreach loop in C#. a foreach loop allows you to loop through the items in a set of data.
With a foreach loop, you don’t need to create an explicit counter variable. Instead, you create
a variable that represents the type of data for which you’re looking. Your code will then loop
until you’ve had a chance to process each piece of data in the set.
Code for .cs file
 string[] strarry = {"One","Two","Three","Four"};
        foreach (string element in strarry)
        {
            System.Diagnostics.Debug.Write(element + " ");
        }


Inner Join in sql quey

In this web programming tutorial we will learn that how we can write sql query for Inner join see the below inner join query,



SELECT *
FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID

How to use IF Else Condition to show hide div using Jquery

In this Web Programming tutorial we will learn that how we can use IF and ELSE Condition in Jquery to show or Hide an element on a web form. below is the code:
HTML Button Code:

Below code will check if Div element is hidden than it will make it show else it will nake it hidden.
Code for JQuery:
$('#toggleButton').click(function() {
if ($('#disclaimer').is(':visible')) {
$('#disclaimer').hide();
} else {
$('#disclaimer').show();
}
});

how to hide div on button click using jquery

In this JQuery web programming tutorial we will learn that how we can hide an element on a page using jquery. in this example we will learn that by clicking on a button how we can hide div or any element using jquery.
HTML button

JQuery Code
$('#hideButton').click(function () {
        $('#disclaimer').hide();
    });

how to remove css class from elements using jquery

In this web programming tutorial we will learn that how we can remove css class on some elements here is the way using jquery
$('#celebs tr.test').removeClass('test');

how to add or replace css class on using jquery

In this web Programming tutorial we will learn that how we can replace or Add a css Class to take effect on a specific table's row using jquery, Css Class we want to replace

.test {
background-color: #dddddd;
color: #666666;
}
Jquery Code to replace the class


above code will find the table with ID "celebs" and replace the above css class named "test" to all even Table rows using jquery.

how to change Row back ground color and text color using jquery

In this web programming tutorial we will learn that how we can change the background color and text color of Table's alternate rows ie we want that Every "Even" Row's text color and background color of a table should changed using Jquery, see the below code,

test
test
test
test
test
Jquery Code to affect all rows in a table


Thursday, March 22, 2012

how to reverse a string in asp.net using c#

In this web Programming tutorial we will learn that how we can print a string in reverse mode in asp.net using c#,
for example you have a string as below
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
and you want to print or show it in Reverse mode as below, Output: ZYXWVUTSRQPONMLKJIHGFEDCBA here is the code you can use in ur .cs file and can use as per your requirement. function call.
 string teest = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        test.Text = Reverse(teest);
actual function defination
     public string Reverse(string str)
         {
              int len = str.Length;
              char[] arr = new char[len];

                for (int i = 0; i < len; i++)
                {
                    arr[i] = str[len - 1 - i];
                }

                    return new string(arr);
         }

Wednesday, March 21, 2012

how to create image button dynamically in asp.net using c#

In this web programming tutorial we will learn that how we can creat a image button dynamically in asp.net using c#.
See the below code for your .cs file
in my case i have created a print button you may create a button as per your requirements.
ImageButton imgButton = new ImageButton();
                        imgButton.ID = "img1";
                        imgButton.CausesValidation = false;
                        imgButton.ImageUrl = "../img/printer_icon.gif";
                        string targeturl = "http://localhost:8000" + Request.RawUrl.ToString();
                        //imgButton.OnClientClick = "javascript:return OpenNewWindow('" + targeturl + "')";
                        imgButton.Click += new ImageClickEventHandler(ImageButton1_Click);
                        imgButton.ToolTip = "Print";
                        cc.Controls.Add(imgButton);

how to format amount (Moany) in asp.net using c#

In this web Programming tutorial we will learn that how we can format a string to Monay type. see the below code in asp.net using c#.
Code for .cs file
Total_amount.Text = string.Format("{0:###,###,##0.00}", Total_Amountdue);

Saturday, March 17, 2012

what is LINQ

LINQ (Language Integrated Query) is a set of extensions for the C# and Visual Basic languages. It allows
you to write C# or Visual Basic code that manipulates in-memory data in much the same way you query
a database.
Technically, LINQ defines about 40 query operators, such as select, from, in, where, and orderby (in
C#). These operators allow you to code your query. However, there are various types of data on which
this query can be performed, and each type of data requires a separate flavor of LINQ.
The most fundamental LINQ flavor is LINQ to Objects, which allows you to take a collection of
objects and perform a query that extracts some of the details from some of the objects. LINQ to Objects isn’t ASP.NET-specific. In other words, you can use it in a web page in exactly the same way that you use it in any other type of .NET application.
Along with LINQ to Objects is LINQ to DataSet, which provides similar behavior for querying an inmemory DataSet object, and LINQ to XML, which works on XML data. But one of the most interesting flavors of LINQ is LINQ to Entities, which allows you to use the LINQ syntax to execute a query against a relational database. Essentially, LINQ to Entities creates a properly parameterized SQL query based on your code, and executes the query when you attempt to access the query results. You don’t need to write any data access code or use the traditional ADO.NET objects. LINQ to Objects, LINQ to DataSet, and LINQ to XML are features that complement ASP.NET, and aren’t bound to it in any specific way. However, ASP.NET includes enhanced support for LINQ to Entities, including a data source control that lets you perform a query through LINQ to Entities and bind the results to a web control, with no extra code required.

Friday, March 16, 2012

how to save and fetch images from sql server in asp.net using c#

in previous article we explained that how to save files in sql server database using asp.net now we will learn that how to fetch images from sql server database in asp.net using c#

below function in page load event will just fetch the image data from sql server.
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value
        = Convert.ToInt32 (Request.QueryString["ImageID"]);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}
and we wll pass the parameters to our image tag as mention below in asp.net



how to save and fetch Files from SQL Server Database in ASP.Net using c#

In this web programming tutorial we will learn that how we can save files in sql server database and how we can fetch or retrieve saved files from sql server database in asp.net using c#.

Below is the table structure in order to save files

here is the connection string that will be used to connect to database



now here we need to read the file using file Stream and then File Stream will be converted into byte array using BinaryReader in order to save into the database.
// Read the file and convert it to Byte Array
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);
 
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();

after reading the file we need to save it into database by using following command
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
Below function InsertUpdateData accepts the SqlCommand object, executes the query and inserts the data into the database and thats it our file will be saved into database.
private Boolean InsertUpdateData(SqlCommand cmd)
{
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        return true;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return false;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}
Now we need to fetch the data and need to display. In order to do so web need to write a select command to fetch the data from sql server database table.
string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
    download(dt);
}
below function will simply execute select statement in sqlserver query window.
private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}
Here is the function which initiates the download of file. It basically reads the file contents into a Byte array and also gets the file name and the Content Type. Then it writes the bytes to the response using Response.BinaryWrite
private void download (DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = dt.Rows[0]["ContentType"].ToString();
    Response.AddHeader("content-disposition", "attachment;filename="
    + dt.Rows[0]["Name"].ToString());
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

how to calculate total rows and subtotal in asp.net gridview using jquery

In this web programming tutorial we will learn that how we can calculate the row total and subtotal of gridview using jquery.


    
        
        
        
            
                
            
        
        
            
                
            
        
    

Grand Total:

below jquery script will help us to perform all calculations in grid view rows.



how to maintain scroll position of the page after postback in asp.net using javascript

In this web programming tutorial we will learn that how we can maintain scroll position of the page when page is postback. although asp.net framework provides us MaintainScrollPositionOnPostback but it has been observed that it is not working in Firefox and Chrome browsers. So in order to over come this flaw we have develop below javascript it is working fine in all major browsers.

how to convert text string into an image in asp.net using c#

in this web programming tutorial we will learn that how we can convert text string provided by user into an image in asp.net using c#. this will help us to make our own captcha images instead to use third party tools.

HTML Code to get text string from user


    


    

we need to inherit following namespaces in our .cs file
using System.Drawing.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
Now below code will help us to genereate .jpg file from user input string.
protected void btnConvert_Click(object sender, EventArgs e)
{
    string text = txtText.Text.Trim();
    Bitmap bitmap = new Bitmap(1, 1);
    Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel);
    Graphics graphics = Graphics.FromImage(bitmap);
    int width = (int)graphics.MeasureString(text, font).Width;
    int height = (int)graphics.MeasureString(text, font).Height;
    bitmap = new Bitmap(bitmap, new Size(width, height));
    graphics = Graphics.FromImage(bitmap);
    graphics.Clear(Color.White);
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
    graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0);
    graphics.Flush();
    graphics.Dispose();
    string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";
    bitmap.Save(Server.MapPath("~/images/") + fileName, ImageFormat.Jpeg);
    imgText.ImageUrl = "~/images/" + fileName;
    imgText.Visible = true;
}

how to use ASP.Net CompareValidator to compare dates in dd/mm/yyyy format

in this web programming tutorial we will learn that how to use ASP.Net CompareValidator to compare dates in dd/mm/yyyy format.

By default the ASP.Net CompareValidator does not work for dd/mm/yyyy format hence we will need to change the Culture property of the page to en-GB in the @Pagedirective of the ASP.Net Web Page as show below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Culture = "en-GB" %>
 

 


    


    
Start Date:   End Date:

how to Export data into Text/CSV file from grid view in asp.net using c#

To export the GridView as CSV, I am running a two for loops. While looping through the GridView columns and appending comma after each column and while looping through rows appending new line character. Refer the code below.
protected void btnExportCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";
 
    GridView1.AllowPaging = false;
    GridView1.DataBind();
 
    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}
To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export data into excel file from grid view in asp.net using c#

In this web programming tutorial we will learn that how we can export grid view data into a pdf file in asp.net using c#.

For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.


Then import the following Namespaces

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
code for .cs file

By default the iTextSharp Library does not support background color of table cells or table rows

Hence when you render it as PDF your GridView is rendered without any formatting.

Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.



For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End(); 
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export grid view data into MS excel file in asp.net using c#

In this web programming tutorial we will learn that how we can export grid view data into MS excel file in asp.net using c#

Code for .cs file
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
 
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
 
GridView1.AllowPaging = false;
GridView1.DataBind();
 
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
 
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  
 
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];
 
    //Change Color back to white
    row.BackColor = System.Drawing.Color.White;
 
    //Apply text style to each Row
    row.Attributes.Add("class", "textmode");
 
    //Apply style to Individual Cells of Alternating Row
    if (i % 2 != 0)
    {
        row.Cells[0].Style.Add("background-color", "#C2D69B");
        row.Cells[1].Style.Add("background-color", "#C2D69B");
        row.Cells[2].Style.Add("background-color", "#C2D69B");
        row.Cells[3].Style.Add("background-color", "#C2D69B");  
    }
}
GridView1.RenderControl(hw);
 
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export data into MS Word File from grid view in asp.net using c#

In this web programming tutorial we will learn that how we can export data into MS word file from grid view by clicking a button in asp.net using c#
Code for .aspx file

   
    
    
    
    
   

Code for .CS file
protected void btnExportWord_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw= new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

Thursday, March 15, 2012

how to validate image at client side in asp.net

In this web Programming tutorial we will learn that how we can validate the image at client side before uploading it that it is according to our required format i.e. png, jpg or bmp.

 Upload a valid image;

how to re size the image while uploading in asp.net using c#

In this web programming tutorial we will learn that how can we resize the image while uploading to the server as per our requirements.
code for .cs file
using System;  
using System.Data;  
using System.Configuration;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.HtmlControls;  
using System.Web.UI.WebControls;  
using System.Drawing;  
using System.Drawing.Drawing2D;  
using System.Drawing.Imaging;  
using System.IO;  
///   
/// Summary description for clsImageUpload : Credits : http://prajeeshkk.blogspot.com  
///   
public class clsImageUpload  
{  
string fileName;  
public clsImageUpload()  
{  
//  
// TODO: Add constructor logic here  
//  
}  
//This function is called from aspnet page, it takes directory name as parameter  
public string HandleUploadedFile(string directory)  
{  
// To get the root of the web site  
string root = HttpContext.Current.Server.MapPath("~/");  
// clean up the path  
if (!root.EndsWith(@"\"))  
root += @"\";  
// make a folder to store the images in  
string fileDirectory = root + @"\" + directory + "\\";  
// create the folder if it does not exist  
// make a link to the new file  
  
// loop through the file in the request  
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)  
{  
// get the file instance  
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);  
// create a byte array to store the file bytes  
byte[] fileBytes = new byte[fi.ContentLength];  
// fill the byte array  
using (System.IO.Stream stream = fi.InputStream)  
{  
stream.Read(fileBytes, 0, fi.ContentLength);  
}  
// create a random file name  
fileName = Guid.NewGuid().ToString();  
  
// write the resized file to the file system  
File.WriteAllBytes(fileDirectory + fileName + "_thumb.jpg", ResizeImageFile(fileBytes, 75));  
fileBytes = null;  
}  
return (fileName + "_thumb.jpg");  
}  
public void HandleUploadedFileUseExistingName(string directory, string fname)  
{  
// get the root of the web site  
string root = HttpContext.Current.Server.MapPath("~/");  
// clean up the path  
if (!root.EndsWith(@"\"))  
root += @"\";  
// make a folder to store the images in  
string fileDirectory = root + @"\" + directory + "\\";  
// loop through the file in the request  
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)  
{  
// get the file instance  
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);  
// create a byte array to store the file bytes  
byte[] fileBytes = new byte[fi.ContentLength];  
// fill the byte array  
using (System.IO.Stream stream = fi.InputStream)  
{  
stream.Read(fileBytes, 0, fi.ContentLength);  
}  
// create a random file name  
fileName = fname;  
// write the resized file to the file system  
File.WriteAllBytes(fileDirectory + fileName, ResizeImageFile(fileBytes, 75));  
fileBytes = null;  
}  
}  
/// This fuction returns a Byte array containing the resized file  
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)  
{  
using (System.Drawing.Image oldImage =  
System.Drawing.Image.FromStream(new MemoryStream(imageFile)))  
{  
//If you want to maintain the propotion use following code  
//Size newSize = CalculateDimensions(oldImage.Size, targetSize);  
//If you want to use a fixed size use following one  
Size newSize = GetDimension();  
using (Bitmap newImage =  
new Bitmap(newSize.Width,  
newSize.Height, PixelFormat.Format24bppRgb))  
{  
using (Graphics canvas = Graphics.FromImage(newImage))  
{  
canvas.SmoothingMode = SmoothingMode.AntiAlias;  
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;  
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;  
canvas.DrawImage(oldImage,  
new Rectangle(new Point(0, 0), newSize));  
MemoryStream m = new MemoryStream();  
newImage.Save(m, ImageFormat.Jpeg);  
return m.GetBuffer();  
}  
}  
}  
}  
/// This function Calculates the new size of the image based on the target size  
private static Size CalculateDimensions(Size oldSize, int targetSize)  
{  
Size newSize = new Size();  
if (oldSize.Height > oldSize.Width)  
{  
newSize.Width =  
(int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));  
newSize.Height = targetSize;  
}  
else  
{  
newSize.Width = targetSize;  
newSize.Height =  
(int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));  
}  
return newSize;  
}  
//Dimension of the images can be set here  
private static Size GetDimension()  
{  
Size newSize = new Size();  
newSize.Width = 100;  
newSize.Height = 100;  
return newSize;  
}  
}  

how to reset all form elements in asp.net using c#

In this web programming tutorial we will learn that how we can reset all web form controls in one click ie (by clicking on reset button) in asp.net using c#.
code for .cs file.

public  static void ResetControls(ControlCollection pagecontrols, bool txtbox, bool dropdownlist, bool label)  
  {  
      foreach (Control cntrl in pagecontrols)  
      {  
          foreach (Control mycontrols in cntrl.Controls)  
          {  
              if (txtbox)  
              {  
                  if (mycontrols is TextBox)  
                  {  
                      (mycontrols as TextBox).Text = string.Empty;  
                  }  
              }  
              if (dropdownlist)  
              {  
                  if (mycontrols is DropDownList)  
                  {  
                      (mycontrols as DropDownList).SelectedIndex = 0;  
                  }  
              }  
              if (label)  
              {  
                  if (mycontrols is Label)  
                  {  
                      (mycontrols as Label).Text = string.Empty;  
                  }  
              }  
          }  
      }  
  }  
now we will call above function in order to reset all form elements except lables as below
FormControl.ResetControls(this.Controls, true, true, false);  

Javascript Validation in ASP.net

in this web programming tutorial we will learn that how we can validate asp.net form fields using javascript. See the below function and use it as per your requirements.

function validateregform()
{

if (document.getElementById("<%=txtName.ClientID%>").value=="")
{
alert("Name Field can not be blank");
document.getElementById("<%=txtName.ClientID%>").focus();
return false;
}

if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Email id can not be blank"); document.getElementById("<%=txtEmail.ClientID%>").focus();
return false;
}
var emailPat = /^(\".*\"[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}][A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById("<%=txtEmail.ClientID%>").value;
var matchArray = emailid.match(emailPat);
if (matchArray == null)
{
alert("Your email address seems incorrect. Please try again.");
document.getElementById("<%=txtEmail.ClientID%>").focus();
return false;
}

if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")
{
alert("Web URL can not be blank");
document.getElementById("<%=txtWebURL.ClientID%>").value="http://" document.getElementById("<%=txtWebURL.ClientID%>").focus(); return false;
}
var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$" ;
var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
var matchURL=tempURL.match(Url); if(matchURL==null)
{
alert("Web URL does not look valid");
document.getElementById("<%=txtWebURL.ClientID%>").focus();
return false;
}

if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
{
alert("Zip Code is not valid");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
var digits="0123456789";
var temp;
for (var i=0;i<%=txtzip.clientid%>").value.length;i++)
{
temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
if (digits.indexOf(temp)==-1) {
alert("Please enter correct zip code");
document.getElementById("<%=txtZIP.ClientID%>").focus(); return false;
}
} return true;
} 

how to Export Grid View Data into Excel in asp.net using c#

In this web programming tutorial we will learn that how we can export grid view's Data into an excel sheet in asp.net using c#.

protected void BtnExport_Click1(object sender, ImageClickEventArgs e)
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

how to Export/Import Excel data into SQL Server Database in asp.net using C#

In this web programming tutorial we will learn that how we can import export excel data in to sql server database in asp.net using c#. In certain occasions we may need to export / import large excel spreadsheet to SQL server database.
Step 1:
I am assuming you have created a folder and uploaded your Microsoft Excel worksheet in that folder.
Step 2:
You can create class for creating an export function:
code for .cs file


using System;
using System.Data;
using System.Configuration;
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.Data.OleDb;
///

/// Class for Exporting Excel Data to SQL server
///

public class clsExcelToSqlServer
{
public clsExcelToSqlServer()
{
//
// TODO: Add constructor logic here
//
}
private string _FilePath;
public String FilePath
{
get { return _FilePath; }
set { _FilePath = value; }
}
public DataTable getDataFromExcelSheet()
{
try
{
//File path of Excel Spread sheet
FilePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) +
"/ExcelFolder/ExcelAppliance.xls";
//Connection string to connect Excel data
string strConnectionString = string.Empty; strConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ FilePath + @";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""";
OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
cnCSV.Open();
//Selecting all rows from excel sheet
OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Sheet1$]", cnCSV);
OleDbDataAdapter daCSV = new OleDbDataAdapter();
daCSV.SelectCommand = cmdSelect;
DataTable dtCSV = new DataTable();
//Filling excel data into data table
daCSV.Fill(dtCSV);
cnCSV.Close();
daCSV = null;
return dtCSV;
}
catch (Exception ex)
{
return null;
}
finally { }
}
}
getDataFromExcelSheet() function returns a Data Table and you can use this Data table to export data into to SQL Server.

how to Read and write text file in asp.net using c#

In this web programming tutorial we will learn that how we can read a text file in asp.net using c# and how we can write some text or data on a text file in asp.net using c#.

Reading and writing (File manipulation) is a very easy task in asp.net, in this tutorial we will learn that how simply write data on a text file and read data from a text file.
suppose we have a Text file named "abc.txt" in the root folder of our web application.

if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/abc.txt")))
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
sw.Write("Hello world");
sw.Dispose();
}
if you want to Append data in the Text file then you have to set append parameter true in StramWriter object constructor.
Eg:-
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"),true);

we need to create a streamwriter object to write lines of data into a text file, follow this MSDN article to understand more about StreamWriter class.

Read Data From Text File:
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.txt")))
{
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
string strdata = sr.ReadToEnd();
sr.Dispose();
}

how to Disable the text selection and drag and drop

in this web programming tutorial we will learn that how we can disable the drag and drop and text selection facility on our web pages. in order to do so just put the below code in body section of your code:

but there is one drawback of the above code, it will not work in firefox web browser. In order to make it workable in firefox we need to use below code we have just added a onmousedown event:
 

Wednesday, March 14, 2012

how to check all check boxes using jquery

In this web programming tutorial we will learn that how we can check all check boxes in a page using jquery.

Reason for Celebrity Famous on the internet
Committed a crime
Dates a super model
Hosts a TV show
Big in Japan

Check all
Jquery Code to check all check boxes
$('.check-all:checkbox').change(function() {
var group = ':checkbox[name=' + $(this).attr('name') + ']';
$(group).attr('checked', $(this).attr('checked'));
});

how to redirect page after some time delay in asp.net using c#

In this web programming tutorial you will learn how to redirect user after some time delay in asp.net using c#. Normally people use redirection process after showing some message to their users, for example a message can be "Thank you for visiting our website" or after getting feedback from user you can display a message "Thank you for providing us your valuable feedback" and then redirect user to another page. It's just up to you in which scenario you want to use it. In asp.net normally we have three options to redirect user after some time delay.


  1. Use javascript code in your c# code
  2. Use Meta tag in your c# code
  3. Use Response.AddHeader().

Redirection after some time delay in asp.net using c#
Let's have a look over these methods

  1. Use javascript function in your c# code.

I have already written a post related how to write and execute the javascript code from c# code behind. You just have to put your javascript code in c# code behind and that's it. Let’s have a look over example given below

Yourpage1.aspx
In my .aspx page I have an asp:button control and using it’s onClick event I am redirecting user.
Yourpage1.aspx.cs

protected void btnRedirect_Click(object sender, EventArgs e)  
{  
string redirectionScript = "";  
Page.RegisterStartupScript("Startup", redirectionScript);  
}   
It will redirect user to yourpage2.aspx after 5 seconds

2) Use meta tag in your c# code

I have already written a post for Implementing meta tags with master page in asp.net using c#. Let’s have a look over how to redirect user after some time delay by using meta tag in c# code behind.

protected void btnRedirect_Click(object sender, EventArgs e)  
{  
HtmlMeta equiv = new HtmlMeta();  
equiv.HttpEquiv = "refresh";  
equiv.Content = "5; url= yourpage2.aspx";  
Header.Controls.Add(equiv);  
} 
OR
protected void btnRedirect_Click(object sender, EventArgs e)  
{  
Page.Header.Controls.Add(new LiteralControl(""));  
}   
It will redirect user to yourpage2.aspx after 5 seconds.

3) Use Response.AddHeader()

Use c# built-in method AddHeader() of Response Class to redirect user after some time delay. Let's have a look over how to do so

protected void btnRedirect_Click(object sender, EventArgs e)  
{  
Response.AddHeader("REFRESH", "5;URL=yourpage2.aspx");  
}  
It will redirect user to yourpage2.aspx after 5 seconds.

This AddHeader() function takes two Parameters. First one is HeaderName which is a string indicating the name of the new header. The second parameter is HeaderValue which is a string that indicates the initial value of the new header. It doesn't return any value.

how to register DLL in asp.net

In this programming tutorial you will learn how to register dll. It is quite easy as you just have to execute a simple command, but before knowing the command you must have Administrator rights over the operating system (Windows).
You just have to run the following command

regsrv32 dllname-with-its-complete-path

you have to give dll name and its complete path where it exists, let's suppose we have a dll iTextSharp and it exists in project folder located in our D drive then the command will be

regsvr32 D:\Project\iTextSharp.dll

Tuesday, March 13, 2012

how to call methods in asp.net using c#

In this web programming tutorial we will learn that how we can call or invoke our methods in asp.net using c#.
Invoking your methods is straightforward—you simply type the name of the method, followed
by parentheses. If your method returns data, you have the option of using the data it
returns or just ignoring it:
// This call is allowed.
MyMethodNoReturnedData();
// This call is allowed.
MyMethodReturnsData();
// This call is allowed.
int myNumber;
myNumber = MyMethodReturnsData();

how to declare private method in asp.net using c#

In this web programming tutorial we will learn that how to declare a private method in asp.net using c#.

When you declare a method in C#, the first part of the declaration specifies the data type
of the return value, and the second part indicates the method name. If your method doesn’t
return any information, you should use the void keyword instead of a data type at the beginning
of the declaration.
private void MyMethodNoReturnedData()
{
// Code goes here.
}

how to declare a method with return type in asp.net using c#

In this web programming tutorial we will learn that how to declare a method with return type in asp.net using c#.

When you declare a method in C#, the first part of the declaration specifies the data type
of the return value, and the second part indicates the method name. If your method doesn’t
return any information, you should use the void keyword instead of a data type at the beginning
of the declaration.

// This method returns an integer.
int MyMethodReturnsData()
{
// As an example, return the number 10.
return 10;
}

how to declare methods in asp.net using c#

In this web programming tutorial we will learn that how we can declare methods in asp.net using c#.
When you declare a method in C#, the first part of the declaration specifies the data type
of the return value, and the second part indicates the method name. If your method doesn’t
return any information, you should use the void keyword instead of a data type at the beginning
of the declaration.

// This method doesn't return any information.
void MyMethodNoReturnedData()
{
// Code goes here.
}

how to use Do while loop in asp.net using c#

in this web programming tutorial we will learn that how we can use do while loop in asp.net using c#. You can also place the condition at the end of the loop using the do . . . while syntax. In
this case, the condition is tested at the end of each pass through the loop:
int i = 0;
do
{
i += 1;
// This code executes ten times.
}
while (i < 10);

how to use The while loop in asp.net using c#


Finally, C# supports a while loop that tests a specific condition before or after each pass
through the loop. When this condition evaluates to false, the loop is exited.
int i = 0;
while (i < 10)
{
i += 1;
// This code executes ten times.
}

how to use The for Loop in asp.net using c#


In this web programming tutorial we will learn that how we can use The for loop is a basic ingredient in many programs. It allows you to repeat a block of code a
set number of times, using a built-in counter. To create a for loop, you need to specify a starting
value, an ending value, and the amount to increment with each pass. Here’s one example:
for (int i = 0; i < 10; i++)
{
// This code executes ten times.
System.Diagnostics.Debug.Write(i);
}

how to use The switch Statement in asp.net using c#

In this web programming tutorial we will learn that how we can use switch statement in asp.net using c#.
C# also provides a switch statement that you can use to evaluate a single variable or expression
for multiple possible values. The only limitation is that the variable you’re evaluating

must be an integer-based data type, a bool, a char, a string, or a value from an enumeration.
Other data types aren’t supported.
In the following code, each case examines the myNumber variable and tests whether it’s
equal to a specific integer:
switch (myNumber)
{
case 1:
// Do something.
break;
case 2:
// Do something.
break;
default:
// Do something.
break;
}

how to use if Statement in asp.net using c#

The if statement is the powerhouse of conditional logic, able to evaluate any combination of
conditions and deal with multiple and different pieces of data. Here’s an example with an if
statement that features two conditions:
if (myNumber > 10)
{
// Do something.
}
else if (myString == "hello")
{
// Do something.
}
else
{
// Do something.
}

Operators in asp.net using C#

in this we programming tutorial we will know the list of operators in asp.net using c#

Operator
Description
==
Equal to.

!=
Not equal to.

< 
Less than.

> 
Greater than.

<=
Less than or equal to.

>=
Greater than or equal to.

&&
Logical and (evaluates to true only if both expressions are true). If the first expression
is false, the second expression is not evaluated.

||
Logical or (evaluates to true if either expression is true). If the first expression is true,
the second expression is not evaluated.