Adsence750x90

Saturday, November 6, 2010

Image Handling In ASP.Net

Contents
  • Introduction
  • Store Image
    • In Database
    • In Folder        
  • Display Image in Image Control, GridView and DataList 
    • From Database
    • From Folder
  • Creating Thumbnails
  • Adding Watermark Text on Image
  • Adding Image as Watermark

Introduction

             In this Article  I am going to explain how to handle image in ASP.Net. I seen lot of question regarding "How to save and display image from database in ASP.Net"  in different .net discussing forums. I think it must be helpful for beginners to solve their problems regarding images in ASP.Net.  

Store Images

We can store images in Database and project folders. If it is in Database the datatype of image data is "image" , now we can check the Database design

In Database

here I used create a store procedure to save image in database.


CREATE PROCEDURE [dbo].[sp_UploadImage]
@imageData as image
AS
BEGIN
INSERT INTO Images (imageData) VALUES(@imageData)
END

Now we can look how to save image in Database. we need one FileUpload Control to select file. and need to check file extension to verify uploading file is image or not. below script function "valiadate();"  check the file is image or not, ie we check the file extensions with javascript.

Javascript to check Upload file extension

Now check the .aspx page
 
    
Now server side code. Reading bytes value from FileUpload Control and pass that value with store procedure name in to a HashTable. that hashtable send to DataBaseHelper Class file to save image in Database.
 protected void btnUploadImage_Click(object sender, EventArgs e)
    {
        //server side checking
        if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith("image") && FileUpload1.HasFile)
        {
            Hashtable imageHash = new Hashtable();
            imageHash.Add("@imageData", FileUpload1.FileBytes);
            DataBaseHelper DBHelper = new DataBaseHelper();
            //storing image in to DataBase
            DBHelper.ExecuteNonQuery("sp_UploadImage", imageHash);
        }
    } 
Database with image data
In Folder Saving folder is simple to compare saving in Database. FileUpload control have SaveAs() method to save file. here I save images in "savedImages" folder. We are not keeping any values in database. At the time of display image we pick images from folder using DirectoryInfo and FileInfo Class or Directory.GetFiles Methord
protected void btnUploadToFolder_Click(object sender, EventArgs e)
    {
        //save file in folder
        if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith("image") && FileUpload1.HasFile)
        {
            string savelocation = Server.MapPath("savedImages/");
            string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
            //creating filename to avoid file name conflicts.
            string fileName = Guid.NewGuid().ToString();
            //saving file in savedImage folder.
            string savePath = savelocation + fileName + fileExtention;
            FileUpload1.SaveAs(savePath);
        }
    }
Preview of saved images in folder
Display Images in Image Control, GridView and DataList To display image from Database is not simple as displaying from folders. because we previously saved image as byte in Database. From Database To display image, we need to change  byte data to Image, to convert byte data to image we need to use a separate page, here I am using a Generic Handler page to show image from Database.  In that Generic Handler page we take image byte from Database and render in that Handler page and set image controls src or ImageUrl to that Generic Handler page for example it work like this
//from database
Image1.ImageUrl="Handler.aspx?id=1";
//from folder
Image1.ImageUrl="savedImages/ca34fa6c-8321-492c-938b-5413781bdcde.png";
Display image in Generic Handler page Method 1
  
   public void ProcessRequest (HttpContext context) {
        HttpRequest request = context.Request;
        if (!string.IsNullOrEmpty(request.QueryString["id"]))
        {
            //this hash table contain the SP parameter
            Hashtable hash = new Hashtable();
            hash.Add("@imageID", request.QueryString["id"]);
            DataBaseHelper DBHelper = new DataBaseHelper();

            //DBHelper.SQLExecuteNonQuery(procedure_name,command_parameters) return the object data.
            // casting return value to byte[]
            byte[] imageByte = (byte[])DBHelper.SQLExecuteNonQuery("sp_getImage", hash);
            //creating object of image
            System.Drawing.Image b;
            //creating object of bitmap
            Bitmap bitMap = null;
            //checking byte[] 
            if (imageByte != null && imageByte.Length > 0)
            {
                //creating memoryStream object
                using (MemoryStream mm = new MemoryStream())
                {
                    //wrting to memoryStream
                    mm.Write(imageByte, 0, imageByte.Length);
                    b = System.Drawing.Image.FromStream(mm);
                    bitMap = new System.Drawing.Bitmap(b, b.Width, b.Height);
                    //creating graphic object, to produce High Quality images.
                    using (Graphics g = Graphics.FromImage(bitMap))
                    {
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(bitMap, 0, 0, b.Width, b.Height);
                        g.Dispose(); b.Dispose(); mm.Dispose();
                        //changing content type of handler page
                        context.Response.ContentType = "image/jpeg";
                        //saving bitmap image
                        bitMap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        bitMap.Dispose();
                    }
                }
            }
        }
    }
  
Method 2 You can also use this code to render image in Handler page
public void ProcessRequest (HttpContext context) {
        HttpRequest request = context.Request;
        if (!string.IsNullOrEmpty(request.QueryString["id"]))
        {
            //this hash table contain the SP parameter
            Hashtable hash = new Hashtable();
            hash.Add("@imageID", request.QueryString["id"]);
            DataBaseHelper DBHelper = new DataBaseHelper();

            //DBHelper.SQLExecuteNonQuery(procedure_name,command_parameters) return the object data.
            // casting return value to byte[]
            byte[] imageByte = (byte[])DBHelper.SQLExecuteNonQuery("sp_getImage", hash);
            //checking byte[] 
            if (imageByte != null && imageByte.Length > 0)
            {
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(imageByte);
            }
        }
    } 
Example of Handler page displaying image, and check the URL, it display 3rd  image from the Database.
Store procedure used to get Image
CREATE PROCEDURE sp_getImage
@imageID as numeric
AS
BEGIN
SELECT imageData FROM Images WHERE imageId=@imageID
END 
I already said how to display image in Image Conrtol. now we can check how to display in GridView Control form folders and Database. From Database In the aspx page I put a GridView and , then set SqlDataSource, after that I  add a Template column, then drag and drop a Image control in Template column  and set ImageUrl of the image control using Image DataBinding Setting image url 
  Source of GridView Passing imageId to Handler.ashx page. It will display image as I said above.
Preview with HTML Source.
Displaying Image From Folder you need to add a template column in GridView after that put one image control on template column, then set image controls DataImageUrlField from DataTable.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
     <Columns>
         <asp:ImageField  DataImageUrlField="Image">
         </asp:ImageField>
     </Columns>
 </asp:GridView>
Server side code
 private void BindImage()
    {
     
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Image", typeof(string)));
        DataRow dr;
        int i = 0;
  //fetching files from savedImages folder
        foreach (string file in Directory.GetFiles(Server.MapPath(@"savedImages\")))
        {
            dr = dt.NewRow();
            dt.Rows.Add(dr);
            dr["Image"] = "savedImages/" + System.IO.Path.GetFileName(file);
            i += 1;
        }
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }
Now we can check how DataList works. Datalist is more simple control than GridView. Here aslo we call Database image with Generic Handler file Handler.ashx and pass "id" as QueryString. handler file display image, and we point that image in to our DataList Control.
<asp:DataList ID="DataList1" runat="server"
            RepeatColumns="3" RepeatDirection="Horizontal">
            <ItemTemplate>
                <table>
                    <tr>
                        <td valign="middle" align="center" style="background-color:#cccccc;border:1px solid gray;width:150px;height:150px;"><%#DataBinder.Eval(Container.DataItem, "images") %></td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:DataList>
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindDataList();
    }
    private void BindDataList()
    {
        string sqlCmd = "SELECT imageid FROM Images";
        DataBaseHelper DBHelper = new DataBaseHelper();
        DataTable dt = DBHelper.GetTable(sqlCmd);
        //adding new column to disply image
        DataColumn imageCol = new DataColumn("images", typeof(string));
        dt.Columns.Add(imageCol);
        
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][imageCol] = string.Format("<img src='Handler.ashx?id={0}' alt='' style='width:100px' />", dt.Rows[i][0].ToString());
            }
        }
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }
Preview of Images in DataList Control
Creating Thumbnails image To create a thumbnail we need a image. we can pick image from FileUpload Control, then we need to know dimension of image ie [ Width x Height ]. Here I create a UI to handle this. check the UI
To maintain aspect ratio of image with height and width I use a class AspectRatio.cs you can get the source code "Browse Code" or "Download Source" Section. Now we can look the code of thumbnail creating section. As I said above here I call a function to create thumbs. let look at this. Below method returns Bitmap image, I am saving that image in root folder.
 public Bitmap CreateThumbnail(byte[] imageByte, bool maintainAspectRatio, int desiredWidth, int desiredHeight)
    {
        Bitmap bmp = null;
        try
        {
            MemoryStream memStream = new MemoryStream(imageByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

            if (maintainAspectRatio)
            {
                AspectRatio aspectRatio = new AspectRatio();
                aspectRatio.WidthAndHeight(img.Width, img.Height, desiredWidth, desiredHeight);
                bmp = new Bitmap(img, aspectRatio.Width, aspectRatio.Height);
            }
            else
            {
                bmp = new Bitmap(img, desiredWidth, desiredHeight);
            }
            memStream.Dispose();
        }
        catch(Exception ex)
        {
            havException = true;
            ExceptionMessage = ex.Message;
        }
        return bmp;
    }

Server side code of "Create Thumbnail" Button. You can see this button in above image. here I pass image byte[] to CreateThumbnail Method. it return Bitmap Image. and save that file in root folder.
 protected void btnCreateThumb_Click(object sender, EventArgs e)
    {
        int width = 0;
        int height = 0;
        byte[] image = FileUpload1.FileBytes;
        Int32.TryParse(txtDWidth.Text, out width);
        Int32.TryParse(txtDHeight.Text, out height);
        ImageHandler imageHandler = new ImageHandler();
        bool maintainAR = cbxAspectRation.Checked;
        //calling CreateThumbnail Method to create thumb images
        //it returns Bitmap Image. 
        Bitmap bmp = imageHandler.CreateThumbnail(image, maintainAR, width, height);
        if (bmp != null)
        {
            //creating a file name with guid.
            string fileName = Guid.NewGuid().ToString() + ".jpg";
            //saving in current root folder.
            bmp.Save(Server.MapPath(fileName));
            //set image controls ImageUrl to saved Image, this is to view the thumbnail image
            Image1.ImageUrl = fileName;
        }
        else
        {
            //exception part
            if (imageHandler.havException)
            {
                Response.Write(imageHandler.ExceptionMessage);
            }
        }
    }
You can check preview of Thumbnail ,Height and Width of image with the help of Firebug  console.
Creating Watermark Text on Image Now we can discuss how to add Watermark on image. I think you know about Watermark. here I call a method AddWatermarkText to add watermark on image. I pass image byte and watermark text to this method. method create on System.Drawing.Image object from MemoryStream. MemoryStream Hold the image Byte. using System.Drawing.SolidBrush and System.Drawing.Font we create Text after that
 
Graphics.DrawString(string s, Font font, Brush brush, PointF point);
we write text on Image. below method is AddWatermarkText(byte[] imageByte,string textOnImage); you can check that.
 

public Image AddWatermarkText(byte[] imageByte,string textOnImage)
    {
        System.Drawing.Image img = null;
        try
        {
            MemoryStream memStream = new MemoryStream(imageByte);
            img = System.Drawing.Image.FromStream(memStream);
            Graphics g = System.Drawing.Graphics.FromImage(img);
            Font font = new Font("Aril", 30, FontStyle.Bold);

            SolidBrush solidBrush = new SolidBrush(Color.Red);
            Point point = new Point(img.Width / 3, img.Height / 2);
            g.DrawString(textOnImage, font, solidBrush, point);
            g.Save();

            memStream.Dispose();
            g.Dispose();
            solidBrush.Dispose();
            font.Dispose();
        }
        catch(Exception ex)
        {
            havException = true;
            ExceptionMessage = ex.Message;
        }
        return img;
    }
above method return Image. I am saving this image in root folder and display it using a Image control. you can check the UI of add Watermark Page and watermark on resultant Image.
Now we can check the code of Add Watermark button
 protected void btnAddWaterMark_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            byte[] imgbyte = FileUpload1.FileBytes;
            //creating object of ImageHandler Class
            ImageHandler imageHandler = new ImageHandler();
            System.Drawing.Image imageWithWatermark = imageHandler.AddWatermarkText(imgbyte, txtWaterMarkText.Text);
            if (imageWithWatermark != null)
            {
                //file name to save
                string saveFileName = Guid.NewGuid().ToString() + ".jpg";
                //saving image in current root location
                imageWithWatermark.Save(Server.MapPath(saveFileName));
                //displaying image file in a Image Control
                Image1.ImageUrl = saveFileName;
                imageWithWatermark.Dispose();
            }
            else
            {
                if (imageHandler.havException)
                {
                    Response.Write(imageHandler.ExceptionMessage);
                }
            }
        }
    }
Image as Watermark In this section I am explaining how to add Image as watermark. I think you seen same website with images. they have their log on image. we can check how to do something link that first we need a logo image here I take codeproject's logo image to explain this example. I save CP logo image in watermarklogo folder.
I am embedding CP logo image in to an upload image, using Graphics.DrawImage(Image image, Point point); Method. here I add add fading to logo image using TextureBrush
 //add fading to logo image  using TextureBrush
        System.Drawing.Image waterMarkimage = System.Drawing.Image.FromFile(Server.MapPath("watermarklogo/CodeprojectLogo.jpg"));
        Graphics opacity = System.Drawing.Graphics.FromImage(waterMarkimage);
        Rectangle imageRect = new Rectangle(0, 0, waterMarkimage.Width, waterMarkimage.Height);
        Brush brush = new TextureBrush(waterMarkimage, imageRect);
        opacity.FillRectangle(brush, imageRect);
        opacity.Save();
check the sample image
Check the source code
protected void btnAddImageAsWaterMark_Click(object sender, EventArgs e)
    {
        byte[] imageByte = FileUpload1.FileBytes;
        MemoryStream memStream = new MemoryStream(imageByte);
        System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

        //add fading to logo image  using TextureBrush
        System.Drawing.Image waterMarkimage = System.Drawing.Image.FromFile(Server.MapPath("watermarklogo/CodeprojectLogo.jpg"));
        Graphics opacity = System.Drawing.Graphics.FromImage(waterMarkimage);
        Rectangle imageRect = new Rectangle(0, 0, waterMarkimage.Width, waterMarkimage.Height);
        Brush brush = new TextureBrush(waterMarkimage, imageRect);
        opacity.FillRectangle(brush, imageRect);
        opacity.Save();
       
        Graphics g = System.Drawing.Graphics.FromImage(img);
        Point point = new Point(img.Width / 3, img.Height / 2);
        g.DrawImage(waterMarkimage, point);
        string filename = Guid.NewGuid().ToString() + ".jpg";
        img.Save(Server.MapPath(filename));
        
        opacity.Dispose();
        memStream.Dispose();
        g.Dispose();
        waterMarkimage.Dispose();
        img.Dispose();

        Image1.ImageUrl = filename;
    } 
Download full source code

Sunday, September 19, 2010

Delete Data in GridView Using Template Button

This article explain how to delete data from GridView using Template Buttons

Now we look how to add template button in GridView.
first select Edit Columns in GridView.



2nd add template column in GridView.



Now configuring template column, Click Edit Template. Place a LinkButton on Template field. Click Edit Databindings , then select CommandArgument , after that set field binding, bound to "ID" field, this ID field is used to delete data in server side code. Then press ok button.






Now we can configure LinkButton [ Delete button ].
Select Property of Link button. set CommandName and Text as Delete.
We can access this CommandName in GridView1_RowCommand event. After this add GridView events GridView1_RowCommand and GridView1_RowDeleted






The RowDeleted event is raised whenever a Delete button associated with an item in the GridView control is clicked, but after the GridView control deletes the record.

This allows you to provide an event-handling method that performs a custom routine, such as checking the results of a delete operation, whenever this event occurs. To avoid errors we add one custom code in GridView1_RowDeleted event

//handling gridview delete excetion
        e.ExceptionHandled = true;



Now the server side part.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        //handling gridview delete excetion
        e.ExceptionHandled = true;
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "dele")
        {
            //database Helper
            DBHelper objDBHelper = new DBHelper();
            //sql command to delete data from database
            string sqlCmdText = string.Format("DELETE FROM Table WHERE ID='{0}'", e.CommandArgument.ToString());
            //Executeing sql command
            objDBHelper.ExecuteScalar(sqlCmdText);
            //refresh gridview
            GridView1.DataBind();

        }
    }
}



ASPX Page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1" onrowcommand="GridView1_RowCommand"
            onrowdeleted="GridView1_RowDeleted">
            <Columns>
                <asp:BoundField DataField="biInvitationId" HeaderText="biInvitationId"
                    InsertVisible="False" ReadOnly="True" SortExpression="biInvitationId" />
                <asp:BoundField DataField="biEventName" HeaderText="biEventName"
                    SortExpression="biEventName" />
                <asp:BoundField DataField="biHostName" HeaderText="biHostName"
                    SortExpression="biHostName" />
                <asp:BoundField DataField="biTelephone" HeaderText="biTelephone"
                    SortExpression="biTelephone" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server"
                            CommandArgument='<%# Eval("biInvitationId") %>' CommandName="dele">Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Thank you,

Feel free to comment.



.

Saturday, September 4, 2010

Select GridView Row without using Select button

This code snippet Illustrate How to Select GridView Row without using Select Command button.
I think code can do better idea than description. check the snippet.


protected void Button1_Click(object sender, EventArgs e)
    {
        //identifying button
        Button gridBtn = (Button)sender;
       //selecting grid row
        GridViewRow gridRow = (GridViewRow)gridBtn.NamingContainer;
       //setting Index
        int selectedIndex = gridRow.DataItemIndex;
       // Setting Selected Index of GridView1
         GridView1.SelectedIndex = selectedIndex;
        //firing selected Index changed if you need
        //here I used to change color of selected rows
         GridView1_SelectedIndexChanged(GridView1, EventArgs.Empty);
        if (gridBtn != null)
        {
           //changing button text[/color]
            if (gridBtn.Text == "DeSelect")
            { gridBtn.Text = "Select"; }
            else
            { gridBtn.Text = "DeSelect"; }
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int sIndex = GridView1.SelectedIndex;
        if (GridView1.Rows[sIndex].BackColor == System.Drawing.Color.Red)
        {
            GridView1.Rows[sIndex].BackColor = System.Drawing.Color.White;
        }
        else
        {
            GridView1.Rows[sIndex].BackColor = System.Drawing.Color.Red;
        }

    }


ASPX section

I add One Button field as Template field. and add Button text as "Select". when you click on select button in GridView, the selected Row become Red color.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <columns>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Category" HeaderText="Category"
                    SortExpression="Category" />
                <asp:BoundField DataField="Tags" HeaderText="Tags" SortExpression="Tags" />
                <asp:TemplateField>
                    <itemtemplate>
                        <asp:Button ID="Button1" runat="server" Text="Select" onclick="Button1_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


Preview of Output
You can Select or Deselect GridView Rows.






Thank you for Reading this code snippet.
Feel Free to comment. if you have any doubts let me know.

Thursday, September 2, 2010

Ajax AutoComplete in ASP.Net

Without using AjaxControlToolKit we can implement AutoComplete Extender using pure Ajax Call. This article is explaining how to do make AutoComplete Extender.
OnKeyUp event help you to fetch data from Database with Ajax call. Here one Handler.ashx handles the AJAX request form Client. I add a Class file to handle database operations to better coding practice. Below I am explaining the database helper Class. Class have one method GetTable(string sqlQuery) this return DataTable after fetching data from database. And also include Provide Class, this Class help to get SqlConnection string.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// 
/// Summary description for DBHelper
/// 
public class DBHelper
{
    SqlConnection connection;
    SqlDataAdapter adapter;
    SqlCommand command;
    DataTable dataTable;
    public DBHelper()
    {
    }
    /// 
    /// 
    /// 
    /// passing SQL Query here/// DataTable object is returned
    public DataTable GetTable(string sqlQuery)
    {
        //creating new instance of Datatable
        dataTable = new DataTable();
        connection = Provider.GetConnection();
        command = new SqlCommand(sqlQuery, connection);
        //Open SQL Connection
        connection.Open();
            try
            {
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataTable);
            }
            catch
            { }
            finally
            {
                //Closing Sql Connection 
                connection.Close();
            }
        return dataTable;
    }
}
public class Provider
{
    public static SqlConnection GetConnection()
    {
        //creating SqlConnection
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);
    }
} 



Now we can look into Handler file. When request come from Ajax Call from Client it passes the data into our Database helper Class, handler file hold the data in DataTable. Result data are formatted in a table and write in the context. We can add JavaScript function for select the data, here api_helper.AddtoTaxtBox(selectedItem)is managing client section of data. Check Handler file



<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
public class Handler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {

        HttpRequest request = HttpContext.Current.Request;
        //checking string null or empty
        if (!string.IsNullOrEmpty(request.QueryString["name"]))
        {
            string name=request.QueryString["name"];
            //creating instance of new database helper
            DBHelper objDBHelper = new DBHelper();
            //creating Sql Query
            string sqlQuery = string.Format("SELECT Name FROM User WHERE Name LIKE '{0}%'", name);
            //filling data from database
            DataTable dataTable = objDBHelper.GetTable(sqlQuery);

            string table = string.Empty;
            //table for hold data
            table = "";             string td = string.Empty;             //checking datatable                 if (dataTable.Rows.Count > 0)                 {                     for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        //adding table rows
                        td += string.Format("
", dataTable.Rows[i][0].ToString());                     }                 }                 table += td + "
{0}
"; context.Response.Write(table); } } public bool IsReusable { get { return false; } } }

Now we can check how Ajax works. On Textbox onKeyUp event call the ajax code. It send the entered value into server using ajax and result displayed in div control under the search textbox.


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title></title>

<style type="text/css">
      .select{cursor:pointer;height:20px;color:red;}
      .select:hover{cursor:pointer;height:20px;color:black;background-color:#cccccc;}
      #myDiv{position:relative;top: -1px; left: 0px;width:150px; overflow:hidden;}
      #txtName{width:150px}
</style>

</head>
<body>
<form id="form1" runat="server">
<div>

<asp:TextBox ID="txtName" runat="server" onkeyup="api_helper.callAjax();"></asp:TextBox>
<div id="myDiv"></div>


<script language="javascript" type="text/javascript">

            if (typeof (api_helper) == 'undefined') { api_helper = {} }


            api_helper.doAjax = function(HandlerUrl, displayDiv) {
                var Req; try { Req = new XMLHttpRequest(); } catch (e) { try { Req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } Req.onreadystatechange = function() { if (Req.readyState == 4) { var d = document.getElementById(displayDiv); d.innerHTML = Req.responseText; } }
                Req.open("GET", HandlerUrl, true); Req.send(null);
            }


            api_helper.callAjax = function() {
                var text = document.getElementById("txtName").value;
                if (text != "") {
                    var requestUrl = "Handler.ashx?name=" + text;
                    var displayDiv="myDiv";
                    api_helper.doAjax(requestUrl, displayDiv);
                }
            }


            api_helper.AddtoTaxtBox = function(txt) {
                document.getElementById("txtName").value = txt;
                document.getElementById("myDiv").innerHTML = "";
            }
</script>
</div>
</form>
</body>
</html>



Thanks for reading this article and feel free to comment.
Tags Ajax AutoComplete, Ajax Example.

Thursday, July 8, 2010

UpdateProgress Control

This sample illustrate how to implement UpdateProgress Control in ASP.Net

UpdatePanel control enable partial page rendering in ASP.Net. using UpdateProgress control enable  status  when Updating UpdatePanel. UpdateProgress have ProgressTemplate, When updates is happen  UpdateProgress show the content in ProgressTemplate.

  <asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
            <ProgressTemplate>
                <div style="color:Red;font-size:xx-large;">Please wait ......</div>
            </ProgressTemplate>
       </asp:UpdateProgress>


AssociatedUpdatePanelID is enable which update is shown update process. Here i am displaying time in label control. When user click update button  status is shown in UpdateProgress control


protected void UpdateTime_Click(object sender, EventArgs e)
    {
         //sleeps for 2 seconds 
        System.Threading.Thread.Sleep(2000);
        lblDate.Text = DateTime.Now.ToString();
    }

Full Source Code



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
               <asp:ScriptManager ID="ScriptManager1" runat="server">
               </asp:ScriptManager>
               
               <asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
                    <ProgressTemplate>
                        <div style="color:Red;font-size:xx-large;">Please wait ......</div>
                    </ProgressTemplate>
               </asp:UpdateProgress>
                
                <asp:UpdatePanel runat="Server" ID="UpdatePanel1" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:Label ID="lblDate" runat="server"></asp:Label>
                                <asp:Button ID="UpdateTime" runat="server" onclick="UpdateTime_Click" Text="Update" />
                            </ContentTemplate>
                </asp:UpdatePanel>
         </div>
    </form>
</body>
</html>

Server side code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
public partial class Default2 : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblDate.Text = DateTime.Now.ToString();
        }
       
    }
    protected void UpdateTime_Click(object sender, EventArgs e)
    {
        //sleeps for 2 seconds 
        System.Threading.Thread.Sleep(2000);
        lblDate.Text = DateTime.Now.ToString();
    }
}

Output



Download Source

Wednesday, July 7, 2010

How to get Session Variable in Class File

How to get Session Variable in Class (.cs) File 

Normally Session is not accessible in Class file. when  one try to call Session in class file it return "Object reference not set to an instance of an object." error description like " An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code." this error is thrown by System.NullReferenceException. To access Session in class file Microsoft introduce a Interface IRequiresSessionState, derived from System.Web.SessionState



 The metadata of IRequiresSessionState


namespace System.Web.SessionState
{
    // Summary:
    //     Specifies that the target HTTP handler requires read and write access to
    //     session-state values. This is a marker interface and has no methods.
    public interface IRequiresSessionState
    {
    }
}




IRequiresSessionState Specifies that the target HTTP handler requires read and write access to session-state values. IRequiresSessionState has no methods.


How to Use



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
/// 
/// Summary description for GetSessionHelper
/// 
public class SessionHelper : IRequiresSessionState
{
    public SessionHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// 
    /// Get Session values
    /// 
    /// session key    /// object value
    public object GetSession(string key)
    {
        //check session 
        if (HttpContext.Current.Session[key] != null)
        {
            //return session value
            return HttpContext.Current.Session[key];
        }
        else
        {
            //return empty string
            return string.Empty;
        }
    }
}




Calling SessionHelper Class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Creating object of SessionHelper Class
        SessionHelper objSessionHelper = new SessionHelper();
        //setting session value in a variable
        string sessionValue = objSessionHelper.GetSession("test").ToString();
        //writing session value in Page
        Response.Write(sessionValue);
    }
}


Monday, July 5, 2010

Get Value of Dynamically generated TextBox

how to get value of dynamically generated TextBox using javascript


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class placeholderissue : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (TextBox1.Text != string.Empty)
            {
                int count = 0;
                int.TryParse(TextBox1.Text, out count);
                
                for (int i = 0; i < count; i++)
                {
                    TextBox txt = new TextBox();
                    txt.ID = "dynamicText" + i.ToString();
                    if (PlaceHolder1.FindControl(txt.ID) != null)
                    {
                        PlaceHolder1.Controls.Add(txt);
                    }
                }
            }
        }
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text != string.Empty)
        {
            int count=0;
            int.TryParse(TextBox1.Text,out count);
            for (int i = 0; i < count; i++)
            {
                TextBox txt = new TextBox();
                txt.ID = "dynamicText" + i.ToString();
                PlaceHolder1.Controls.Add(txt);
            }
        }
    }
}






HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="placeholderissue.aspx.cs" Inherits="placeholderissue" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />
        <br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <input id="Button2" type="button" value="button" onclick="GetTextBoxValue();" />
        <script language="javascript">
            function GetTextBoxValue() {
                var count = document.getElementById("TextBox1").value;
                if (count > 0) {
                    for (i = 0; i < count; i++) {
                        alert(document.getElementById("dynamicText" + i).value);
                    }
                }
            }
        </script>
    <div>
    </form>
</body>
</html>




Source Code

Insert Image in to Database

Insert Image in to Database

datatype of image in database is Byte[], so we insert image byte in to Database

FileUploader controls is used to select file, FileUploader control have a property FileBytes it return byte array (byte[]) of image, this Byte[] is stored in dataBase

example


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void ImageUploadToDataBase(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Your Connection string");
        try
        {
            con.Open();
            byte[] imageByte = FileUpload1.FileBytes;
            SqlCommand cmd = new SqlCommand("INSERT INTO table (image,imagename) VALUES (@0,@1))", con);
            object[] cmdParams = new object[2];
            cmdParams[0] = imageByte;
            cmdParams[1] = "Name of Image";
            for (int i = 0; i < cmdParams.Length; i++)
            {
                cmd.Parameters.AddWithValue(i.ToString(), cmdParams[i]);
            }
            cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
        }
        finally { con.Close(); }
       
    }
    
}

Multiple File Upload in ASP.Net

ASP.Net Multiple File Upload

Using HttpFileCollection class provide  to access and manage file uploaded from client. But still have the problem of multiple selection of files. With over limitation am am going to explain multiple  uploading by multiple FileUploader Controls. HttpPostedFile class is used to provide properties and methods if single files in HttpFileCollection class.



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:FileUpload ID="FileUpload2" runat="server" />
    <asp:Button ID="btnUpload" runat="server"
        Text="Upload" onclick="btnUpload_Click" />
    </form>
</body>
</html>





 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class generic : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Post file Collection Class
        HttpFileCollection files = Request.Files;
        if (files.Count > 0)
        {
            for (int i = 0; i < files.Count; i++)
            {
                //read Individual files 
                HttpPostedFile p = files[i];
                string path = Server.MapPath(Guid.NewGuid().ToString() + ".jpg");
                p.SaveAs(path);
            }
        }
    }
}

Friday, July 2, 2010

Dynamically Add AJAX Control Toolkit ValidatorCallout Extender

How to add AJAX Control Toolkit  ValidatorCallout Extender to Dynamic TextBox

To add Ajax Control ToolKit ValidatorCallout we need one TextBox and RequiredFieldValidator. Now i am creating all controls are adding dynamically.  For more information, see  ValidatorCallout control.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Dynamically Creating TextBox
        TextBox txtBox = new TextBox();
        txtBox.ID = "TextBox1";
        txtBox.MaxLength = 100;

        //Dynamically Creating RequiredFieldValidator Control
        RequiredFieldValidator requiredFieldValidater = new RequiredFieldValidator();
        requiredFieldValidater.ID = "RequiredFieldValidator1";
        requiredFieldValidater.ControlToValidate = txtBox.ID;
        requiredFieldValidater.ErrorMessage = "Name is required.";
        requiredFieldValidater.Text = "*";

        //Dynamically Creating ValidatorCalloutExtender Control
        AjaxControlToolkit.ValidatorCalloutExtender validatorCalloutExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
        validatorCalloutExtender.ID = "ValidatorCalloutExtender1";
        validatorCalloutExtender.TargetControlID = requiredFieldValidater.ID;

        //Dynamically Adding controls to PlaceHolder Control
        PlaceHolder1.Controls.Add(txtBox);
        PlaceHolder1.Controls.Add(requiredFieldValidater);
        PlaceHolder1.Controls.Add(validatorCalloutExtender);
    }
}




Output Sample









<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%@ 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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Thursday, July 1, 2010

Creating Dynamic Controls in ASP.Net

Server Side Code
Code snippet for creating Dynamic Controls in ASP.Net. adding dynamic contents and reading the values of dynamically generated controls in ASP.Net have little issue. because after PostBack dynamic controls are disappear from the form. to avoid this we can regenerate controls in page.

This is a simple sample to adding and reading Dynamic controls in ASP.Net.
in !IsPostBack i am create a new instance of ASP TextBox Control.then Adding it to the PlaceHolder Control

if (!IsPostBack)
        {
            //bind textBox in placeholder
            TextBox textBox = new TextBox();
            textBox.ID = "TextBox1";
            PlaceHolder1.Controls.Add(textBox);
        }


in IsPostBack Section

Issue come in this part. after PostBack controls are hidden or disappear from the Form. To avoid this am checking the controls are available in PlaceHolder. if it returns null am binding the controls in PlaceHolder.


//if postback dynamic generated controls are invisible
            //so we can bind in each post back
            TextBox textBox = new TextBox();
            if (PlaceHolder1.FindControl("TextBox1") == null)
            {
                textBox.ID = "TextBox1";
                PlaceHolder1.Controls.Add(textBox);
            }



Reading Values From Generated Control

In this section am explaining how to Read Contents from Dynamically generated TextBox.

i think code is more than effective to explain this, Check the code
I am reading TextBox Value in a Button click.
first check the controls is available in PlaceHolder. if available, display the value using Responce.Write.

TextBox text = PlaceHolder1.FindControl("TextBox1") as TextBox;
        if (text != null)
        {
            Response.Write(text.Text);
        }


Full Source Code


HTML Side

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamiccontrols.aspx.cs" Inherits="dynamiccontrols" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </div>
    </form>
</body>
</html>




Server Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class dynamiccontrols : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //bind textBox in placeholder
            TextBox textBox = new TextBox();
            textBox.ID = "TextBox1";
            PlaceHolder1.Controls.Add(textBox);
        }
        else
        { 
            //if postback dynamic generated controls are invisible
            //so we can bind in each post back
            TextBox textBox = new TextBox();
            if (PlaceHolder1.FindControl("TextBox1") == null)
            {
                textBox.ID = "TextBox1";
                PlaceHolder1.Controls.Add(textBox);
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox text = PlaceHolder1.FindControl("TextBox1") as TextBox;
        if (text != null)
        {
            Response.Write(text.Text);
        }
    }
}

How to Find Controls in Content Page

How to find content page control in ASP.NET?
ContentPlaceHolder contentPage = Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
        Button button =contentPage.FindControl("Button1") as Button;
        if (button != null)
        {
            button.Text = "Message";
        }

Friday, May 28, 2010

Add GridView Column Dynamically ASP.Net and C #

Add GridView Column Dynamically 
This code illustrate how to add a new Column in GridView on GridView1_RowCreated and add column value in GridView1_RowDataBound
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class dhilip : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        //instance of a datatable
        DataTable dt = new DataTable();
        //instance of a datarow
        DataRow drow;
        //creating two datacolums Column1 and Column2 
        DataColumn dcol1 = new DataColumn("Column1", typeof(string));
        DataColumn dcol2 = new DataColumn("Column2", typeof(string));
        //adding datacolumn to datatable
        dt.Columns.Add(dcol1);
        dt.Columns.Add(dcol2);
        //loop for 10 rows
        for (int i = 0; i < 10; i++)
        {
            //instance of a datarow
            drow = dt.NewRow();
            //add rows to datatable
            dt.Rows.Add(drow);
            //add Column values
            dt.Rows[i][dcol1] = i.ToString();
            dt.Rows[i][dcol2] = i.ToString();
        }
        //set gridView Datasource as dataTable dt.
        GridView1.DataSource = dt;
        //Bind Datasource to gridview
        GridView1.DataBind();
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //create a instance of table cell
        // this table cell is going to add gridview as new column
        TableCell tc = new TableCell();
        //first cell must be -1 ie the header of gridview. if it header
        if (e.Row.RowIndex == -1)
        {
            //add header column name. you can add more styles in this section
            tc.Text = "Multiple";
            //add style for header column
            tc.Style.Add(HtmlTextWriterStyle.FontWeight, "bold");
        }
        //cell add to gridview row
        e.Row.Cells.Add(tc);
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if header column we dont need multiplication
        if (e.Row.RowIndex != -1)
        {
            //taking values from first cell. my first cell contain value, you can change
            string id = e.Row.Cells[0].Text;
            //taking values from second cell. my second cell contain value, you can change
            string id2 = e.Row.Cells[1].Text;
            //multiplication
            double mult = int.Parse(id) * int.Parse(id2);
            //adding result to last column. coz we add new column in last.
            e.Row.Cells[e.Row.Cells.Count - 1].Text = mult.ToString();
        }
    }
}

Sunday, May 2, 2010

Find Master Page Content From Content Page ASP.Net

Find Master Page Content From Content Page

for example to find a Panel in the Master Page. we want to find the Panel from Content Page
// Casting Panel1 form MasterPage as Panel
Panel panel = (Panel)Master.FindControl("Panel1");
        if (panel != null)
        {
            panel.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
        }

Wednesday, April 28, 2010

Dynamic DataTable ASP.Net

This Article for How to Create a DataTable Dynamically.

DataTable is Derived from System.Data namespace


//Create a object of Datatable
        DataTable dynamicTable = new DataTable();

        //DataRow
        DataRow dynamicRow;
        //DataColumn for Name and Time
        DataColumn NameColumn = new DataColumn("Name", typeof(string));
        DataColumn TimeColumn = new DataColumn("Time", typeof(string));

        //add Column to Datatable
        dynamicTable.Columns.Add(NameColumn);
        dynamicTable.Columns.Add(TimeColumn);
        //loop for 10 item in DataTable
        for (int i = 0; i < 10; i++)
        {
            dynamicRow = dynamicTable.NewRow();
            //Add Rows to dymanicTable
            dynamicTable.Rows.Add(dynamicRow);
            //Assign Column value
            dynamicTable.Rows[i][NameColumn] = Guid.NewGuid().ToString();
            dynamicTable.Rows[i][TimeColumn] = DateTime.Now.ToString();
        }

        //Bind DynamicTable into a GridView
        GridView1.DataSource = dynamicTable;
        GridView1.DataBind();

Monday, April 26, 2010

Read E Mails from ASP.NET

Read Mails from ASP.NET

This article Illustrate How to read mails from ASP.Net. Using POP commands you can access you email inbox from ASP.Net. Basic POP commands are USER, PASS, LIST, QUIT, RETR.
More details POP command help you can check these links


http://www.nthelp.com/pop_commands.htm
http://www.faqs.org/rfcs/rfc1939


         //Creating Object for POPHelper
        //Parameters are Gmail,Yahoo or MSN Pop Server,
        //Port number
        //bool isSSL
        POPHelper objPopHelper = new POPHelper("pop.gmail.com", 995, true);
        objPopHelper.UserName = "Your Gmail Username eg:youremail@gmail.com";
        objPopHelper.Password = "GmailPassword";
        objPopHelper.Connect();
        GridView1.DataSource = p.DataSource;
        GridView1.DataBind();


Code Of Connect Method 

public void Connect()
        {
            string response = string.Empty;
            ArrayList arrList = new ArrayList();
            try
            {
                //Connect to Host server
                #region Connect Host
                TcpClient _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(_hostname, _port);
                    //if login is ssl
                    if (_isSsl)
                    {
                        _stream = new SslStream(_tcpClient.GetStream());
                        ((SslStream)_stream).AuthenticateAsClient(_hostname);
                    }
                    else
                    {
                        _stream = _tcpClient.GetStream();
                    }
                }
                catch (Exception ex)
                {
                    throw new POPCommandException("Connection to " + _hostname + " Port: " + _port + " failed. Error Details"+ex.Message);
                }
                #endregion
                // Send POP Commands (USER, PASS, LIST) to Host
                #region POP Commands
                _streamWriter = new StreamWriter(_stream, Encoding.ASCII);
                _streamReader = new StreamReader(_stream, Encoding.ASCII);

                //POP command for send Username
                _streamWriter.WriteLine(POPCommands.USER.ToString()+" "+ UserName);
                //send to server
                _streamWriter.Flush();

                //POP command for send  Password
                _streamWriter.WriteLine(POPCommands.PASS.ToString() + " " + Password);
                //send to server
                _streamWriter.Flush();

                //POP command for List mails
                _streamWriter.WriteLine(POPCommands.LIST.ToString());
                //send to server
                _streamWriter.Flush();
                #endregion
                //Read Response Stream from Host
                #region Read Response Srteam
                //Read Response Stream
                response = null;
                string resText = string.Empty;
                while ((resText = _streamReader.ReadLine()) != null)
                {
                    if (resText == ".")
                    { break; }
                    if (resText.IndexOf("-ERR") != -1)
                    { break; }
                    response += resText;
                    arrList.Add(resText);
                }
                #endregion
                //Binding Properties
                #region Bindings
                //Bind Message count
                BindMailCount(arrList);
                //mails returns List
                _mail = ReadMail(messagecount);
                //get  mails Subjects returns List
                _mailsub = FilterContent(_mail,FiltersOption.Subject);
                _from = FilterContent(_mail, FiltersOption.From);
                _to = FilterContent(_mail, FiltersOption.To);
                SetDataSource(_mailsub, _from);
                #endregion
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
        }


Class Diagram of POPHelper

Reading Mails Using POP Command RETR from ASP.NET

private List ReadMail(int Count)
        {
            List lst = new List();
            try
            {
                for (int i = 1; i <= Count; i++)
                {
                    _streamWriter.WriteLine(POPCommands.RETR+" " + i.ToString());
                    _streamWriter.Flush();
                    string resText = string.Empty;
                    while ((resText = _streamReader.ReadLine()) != null)
                    {
                        if (resText == ".")
                        { break; }
                        if (resText.IndexOf("-ERR") != -1)
                        { break; }
                        lst.Add(resText);
                    }
                }
               
            }
            catch(Exception ex)
            {
                errors.Add(ex.Message);
            }
            return lst;
        }



Enumerates for Filer message subject and From Address and ToAddress 

Method for Filer Content


private List FilterContent(List Mails,FiltersOption filter)
        {
            List filterItems = new List();
            try
            {
                for (int i = 0; i < Mails.Count; i++)
                {
                    if (Mails[i].StartsWith(filter.ToString() + ":"))
                    {
                        string sub = Mails[i].Replace(filter.ToString() + ":", "");
                        filterItems.Add(sub);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return filterItems;
        }

Creating DataSource for GridView

private DataTable SetDataSource(Listsubject,Listsender)
        {
            int messageCount = messagecount;
            dataTab = new DataTable();
            DataRow drow;
            DataColumn Sender = new DataColumn("Sender", typeof(string));
            DataColumn Subject = new DataColumn("Subject", typeof(string));
            dataTab.Columns.Add(Sender);
            dataTab.Columns.Add(Subject);
            for (int i = 0; i < subject.Count; i++)
            {
                drow = dataTab.NewRow();
                dataTab.Rows.Add(drow);
                dataTab.Rows[i][Sender] = sender[i].ToString();
                dataTab.Rows[i][Subject] = subject[i].ToString();
            }
            return dataTab;
        }


Download SOURCE

Monday, April 19, 2010

Tracing ASP.NET

Tracing

ASP.NET tracing enable diagnostic information about requested asp.net page.
Tracing Help to follow

•    Page's execution path,
•    Display diagnostic information at run time
•    debug your application

Tracing appends diagnostic information and custom tracing messages to the output of the page and sends this information to the requesting browser. Optionally, you can view this information from a separate trace viewer (Trace.axd) that displays trace information for every page in an ASP.NET Web application. Tracing information can help you investigate errors or unwanted results while ASP.NET processes a page request.

Trace information can enable for single page and hole pages/ application level by configure the application's Web.config. Trace statements are processed and displayed only when tracing is enabled.

Code for Application Level tracing
in web.config file   

<configuration>
  <system.web>
<trace enabled="true" requestLimit="40" pageOutput="true"             localOnly="false" />
  </system.web>
</configuration>

Page level tracing

Add Trace="true" in @page Directives

Eg : <%@ Page Trace="true" %>

Trace Configuration Attributes

PageOutput -  true to display trace both in pages and in the trace viewer (Trace.axd); otherwise, false. The default is false.

requestLimit - The number of trace requests to store on the server. The default is 10.

localOnly - true to make the trace viewer (Trace.axd) available only on the host Web server; otherwise, false. The default is true.

When tracing is enabled for a page, trace information is displayed in any browser requests that page. Tracing displays sensitive information, such as the values of server variables, and can therefore represent a security threat. Be sure to disable page tracing before porting your application to a production server. You can do this by setting the Trace attribute to false or by removing it. You can also configure tracing in the Web.config file by setting the enabled, localOnly, and pageOutput attributes of the trace Element

Source  from MSDN