Pages

Tuesday, January 10, 2012

Inserting Image into Database


Inserting Image into Database

Img_Id
Image_Type
Image_size
http://www.aspdotnetcodes.com/Handler.ashx?id=1
1
image/pjpeg
1672
http://www.aspdotnetcodes.com/Handler.ashx?id=2
2
image/gif
1874
http://www.aspdotnetcodes.com/Handler.ashx?id=3
3
image/gif
3309


To start with, let me explain the SQL Server database table structure we are going to use to insert the image. The table you are going to create to store the image must contain a column of data type IMAGE. This image data type is a Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes. To store the image into this column we are going to convert it into binary string with the help of some IO classes and then insert into the table. For demonstration, we are going to create a table named ImageGallery with four columns in the following structure
Column Name
Description
Data Type
Img_Id
Identity column for Image Id
int
Image_Content
Store the Image in Binary Format
image
Image_Type
Store the Image format (i.e. jpeg, gif, png, etc.)
varchar
Image_Size
Store the Image File Size
bigint

After we create table in the database, we can start the coding part.

1. Open your web application in Visual Studio 2005, drag and drop File Upload control and a Button control into the web page.
2. In the code-behind, add the namespace System.IO.

using System.IO;

3. In the Button’s Button1_Click event, write the following code
if (FileUpload1.PostedFile != null
&& FileUpload1.PostedFile.FileName != "")
{

byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);


SqlConnection myConnection = new SqlConnection(“Your Connection String”);
SqlCommand storeimage = new SqlCommand("INSERT INTO ImageGallery "
+"(Image_Content, Image_Type, Image_Size) "
+" values (@image, @imagetype, @imagesize)", myConnection);
storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value
= FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value
= FileUpload1.PostedFile.ContentLength;

myConnection.Open();
storeimage.ExecuteNonQuery();
myConnection.Close();
}

To upload the image from any location (your local drive) to the server, we have to use HttpPostedFile object. Point the uploaded file to HttpPostedFile object. Then the InputStream.Read method will read the content of the image by a sequence of bytes from the current stream and advances the position within the stream by the number of bytes it read. So myimage contains the image as binary data. Now we have to pass this data into the SqlCommand object, which will insert it into the database table.

Display the Image in a GridView with Handler.ashx

So far, the article explains the way to insert images into the database. The Image is in the database in binary data format. Retrieving this data in an ASP.NET web page is fairly easy, but displaying it is not as simple. The basic problem is that in order to show an image in an apsx page, you need to add an image tag that links to a separate image file through the src attribute or you need to put an Image control in your page and specify the ImageUrl.

For example:
<asp:Image ID="Image1" runat="server" ImageUrl="YourImageFilePath" />
Unfortunately, this approach will not work if you need to show image data dynamically. Although you can set the ImageUrl attribute in code, you have no way to set the image content programmatically. You could first save the data to an image file on the web server’s hard drive, but that approach would be dramatically slower, wastes space, and raises the possibility of concurrency errors if multiple requests are being served at the same time and they are all trying to write the same file.

In these situations, the solution is to use a separate ASP.NET resource that returns the binary data directly from the database. Here HTTP Handler class comes to center stage.
What is Handler?

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance. A handler class implements the IHttpHandler interface.

For this article demonstration, we are going to display the image in the GridView control along with the data we stored in the table. Here are the steps required to accomplish this:

1. Create a Handler.ashx file to perform image retrieval. This Handler.ashx page will contain only one method called ProcessRequest. This method will return binary data to the incoming request. In this method, we do normal data retrieval process and return only the Image_Content field as bytes of array.

The sample code follows
public void ProcessRequest (HttpContext context)
{
  SqlConnection myConnection = new SqlConnection(“YourConnectionString”);
  myConnection.Open();
  string sql = "Select Image_Content, Image_Type from ImageGallery where Img_Id=@ImageId";
  SqlCommand cmd = new SqlCommand(sql, myConnection);
  cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
  cmd.Prepare();
  SqlDataReader dr = cmd.ExecuteReader();
  dr.Read();
  context.Response.ContentType = dr["Image_Type"].ToString();
  context.Response.BinaryWrite((byte[])dr["Image_Content"]);
  dr.Close();
  myConnection.Close();
 
}

2. Place a GridView control in your aspx page, with one TemplateField column, add an Image control into the TemplateField's ItemTemplate section. Specify the ImageUrl property as
<asp:TemplateField>
 <ItemTemplate>
    <asp:Image ID="Image1" runat="server" ImageUrl='<%#    "Handler.ashx?id=" + Eval("Img_Id")  %>' />
 </ItemTemplate>
</asp:TemplateField>
3. Now we can bind the GridView control to display all the records in the table as follows
GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();

Before you bind the GridView, you should write the FetchAllImagesInfo method to return all the records with their image data from the table and then you have to load the images into the GridView control. The code for FetchAllImagesInfo is
public DataTable FetchAllImagesInfo())
{
  string sql = "Select * from ImageGallery";
  SqlDataAdapter da = new SqlDataAdapter(sql, "Your Connection String");
  DataTable dt = new DataTable();
  da.Fill(dt);
  return dt;
}

That's it. When you run your project, you can see the images got loaded into the GridView control.

This is a very simple explanation to store images into the data source and to retrieve it back to display in the webpage. You can make the logic even simpler and even elaborate it upto your requirements.



Asp.Net GridView Control Custom Sorting and Paging with Image Indicator
Previous
1
2
Alex
M
35
alex@yahoo.com
Alabama
Christiana
F
39
chisbell@southbell.com
New York
Flintoff
M
27
flintoff@gmail.com
Alabama
Jeniffer
F
28
jeni007@aol.com
Florida
Leverlock
M
30
leverlockjj@msn.com
Texas
Mark
M
42
markavon@hotmail.com
Florida
Brent
F
78
brent@aol.com
Montana
Paul
M
23
paul4995@rediff.com
Rhode Island
Dorotee
M
45
doro1999@gmail.com
South Carolina
Julien
F
29
julien@startubmail.com
South Carolina
Introduction
This article takes pleasure in explaining the concept of custom sorting and custom paging of a GridView control in depth. We found numerous questions and forums that are speaking about GridView sorting with TemplateField columns. So we took the opportunity to explain the custom sorting of the GridView control in our own and simple way. Besides, that it explains how an Image can be toggled in the header row of the GridView control, to indicate which column is sorted and in which order (ascending or descending) it has been sort. By the way, to enhance the richness of the article we have added custom paging for the GridView control along with the custom Sorting. So you can sort the GridView control, navigate through the GridView pages, without sort order being reset.
For demonstration purpose, we are going to display Customer Information in a GridView control and we are going to perform sorting in the GridView control, which also got custom paging in it. So place a GridView control in the Aspx page, specify its AutoGenerateColumns="False". Then add TemplateFields columns to the GridView as many as columns you want to display. In our case, we are going to display Customer Name [Cus_Name], Gender [Cus_Gender], Age [Cus_Age], EmailId [Cus_Email] and State [Cus_State]. Every TemplateField column will contains a ItemTemplate section, AlternatingItemTemplate section, EditItemTemplate section, HeaderTemplate section and FooterTemplate section. For the purpose of this article, we are going to work on Only ItemTemplate and HeaderTemplate sections. And we will explain you, simply for only one TemplateField column, so that you can do the same for all columns in the GridView.

Point you MUST NOT DO
  • Don’t change the GridView’s AllowSorting property to True.
  • Don’t change the GridView’s AllowPaging property to True.
  • Don’t write any code in GridView’s PageIndexChanging event.
  • Don’t write any code in GridView’s Sorting event.
Concentrate in First TemplateField Column : Customer Name [Cus_Name]

In HeaderTemplate section, add a LinkButton, and change some of its properties as stated in the table below. The below table shows the property of the LinkButton, the value of the property you have to change and a brief note to explain the field's requirement.
Property
Change as
Note
ID
lnkbtnCusName
name of the LinkButton, must be unique for every LinkButton.
Text
Name
text to display at the Header row.
CommandName
Sort
actually this is the Command we need to execute. Keep this value unchanged for all the LinkButton controls in the Header row.
CommandArgument
Cus_Name
Customer Name Field Name in the Customer Table. Set this property accordingly for every column.

Next you have add a PlaceHolder control near the LinkButton control and specify its ID as ‘placeholderName’. You must assign unique ID for every PlaceHolders on each and every TemplateField columns.

Abstract Reminder:

You have to add a LinkButton and a PlaceHolder in each and every column of the TemplateField’s Header section that you want to do custom sorting and do the above-specified settings for every LinkButton and the PlaceHolder controls.

In the ItemTemplate section, add a Label control and bind its Text property to Customer Name [Cus_Name]. So the Label control in the ItemTemplate section of the GridView will look like,
<asp:Label id="Label1" runat="server" Text='<%# Bind("Cus_Name") %>'>
</asp:Label>

Just repeat the above steps for all the columns you want to display in the GridView control as custom sorting column. As per our requirement, the GridView’s Html code will be as follows

<asp:GridView id="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand"
AutoGenerateColumns="False" width="100%">
<Columns>

<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton id="lnkbtnCusName" runat="server" CommandName="Sort"
CommandArgument="Cus_Name">Name</asp:LinkButton>
<asp:PlaceHolder id="placeholderName" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="Label1" runat="server" Text='<%# Bind("Cus_Name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton id="lnkbtnGender" runat="server" CommandName="Sort"
CommandArgument="Cus_Gender">Gender</asp:LinkButton>
<asp:PlaceHolder id="placeholderGender" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="Label4" runat="server" Text='<%# Bind("Cus_Gender") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton id="lnkbtnAge" runat="server" CommandName="Sort" CommandArgument="Cus_Age">Age</asp:LinkButton>
<asp:PlaceHolder id="placeholderAge" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="Label5" runat="server" Text='<%# Bind("Cus_Age") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="lnkbtnCusEmail" runat="server"
CommandArgument="Cus_Email" CommandName="Sort">Email Id
</asp:LinkButton>
<asp:PlaceHolder ID="placeholderEmail" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Cus_Email") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton id="lnkbtnCusState" runat="server" CommandName="Sort"
CommandArgument="Cus_State">State</asp:LinkButton>
<asp:PlaceHolder id="placeholderState" runat="server"> </asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:Label id="Label3" runat="server" Text='<%# Bind("Cus_State") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Concentrate on designing of the Custom Paging

To create custom paging for the GridView control, we are going add a DataList control and name it as dlPaging. In its ItemTemplate section, add a LinkButton, name it as lnkbtnPaging. Set its CommandName property as lnkbtnPaging. Then choose End Template Editing and add two more LinkButton controls on either side of the DataList control. Name it as lnkbtnPrevious and lnkbtnNext and change its Text property as Previous and Next respectively. Better I suggest you to put an Html Table control and place these controls in it properly so that it will look nicely aligned. The Html source of these controls is given below.
<asp:LinkButton id="lnkbtnPrevious"
onclick="lnkbtnPrevious_Click" runat="server"> Previous </asp:LinkButton>

<asp:DataList id="dlPaging" runat="server"
RepeatDirection="Horizontal"
OnItemDataBound="dlPaging_ItemDataBound"
OnItemCommand="dlPaging_ItemCommand">
<ItemTemplate>

<asp:LinkButton ID="lnkbtnPaging" runat="server"
CommandArgument='<%# Eval("PageIndex") %>'
CommandName="lnkbtnPaging"

Text='<%# Eval("PageText") %>'></asp:LinkButton>

</ItemTemplate>
</asp:DataList>

<asp:LinkButton id="lnkbtnNext"
onclick="lnkbtnNext_Click" runat="server">Next</asp:LinkButton>
The LinkButton ‘lnkbtnPaging’ has to be binded with a DataSource to display page numbers. So bind its CommandArgument as ‘PageIndex’ and its Text property with ‘PageText’. The method to bind this DataList will be given and explained at the Code-Behind section, as doPaging method.

Code-behind Section

Declaration Section:

For the purpose of this article, we have collaborated both paging and sorting for a single GridView control. So every section of the source code explained below will cover both custom paging and sorting concept. Just concentrate bit more from here. For the purpose of custom paging, we are creating an instance of PagedDataSource class as follows
PagedDataSource pds = new PagedDataSource();

For maintaining the Page Index of the GridView control, we are going to maintain a ViewState variable called ‘CurrentPage’. It has to be declared and initialize as follows
public int CurrentPage
{

  get {
    if (this.ViewState["CurrentPage"] == null)
       return 0;
    else
       return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
  }

 set {
   this.ViewState["CurrentPage"] = value;
 }

}
Page Load Event:

In the Page Load event, we are going to bind the GridView with the data from the database using a private method called BindGrid.
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
     BindGrid();
  }
}


The complete source code for BindGrid method is explained below.
private void BindGrid()
{
  string sql = "Select * from Customer Order By Cus_Name";
  SqlDataAdapter da = new SqlDataAdapter(sql, “YourConnectionString”);
  DataTable dt = new DataTable();
  da.Fill(dt);
  DataView dv = dt.DefaultView;

  if (this.ViewState["SortExp"] != null)
  {
    dv.Sort = this.ViewState["SortExp"].ToString()
             + " " + this.ViewState["SortOrder"].ToString();
  }

  pds.DataSource = dv;
  pds.AllowPaging = true;
  pds.PageSize = 10;
  pds.CurrentPageIndex = CurrentPage;
  lnkbtnNext.Enabled = !pds.IsLastPage;
  lnkbtnPrevious.Enabled = !pds.IsFirstPage;

  GridView1.DataSource = pds;
  GridView1.DataBind();

  doPaging();
}

The above method fetches data from the Customer table, fill it in a DataTable, and set it to a DataView for purpose of Sorting and Paging concurrently. Next there is two ViewState variables such as SortExp and SortOrder, which stands for Sort Expression (the field to sort the GridView) and Sorting Order (Ascending or Descending order) respectively. Since the GridView works for sorting and paging concurrently, we have to maintain the Sort Expression and Sorting Order in the ViewState variables. So if the Sort Expression is available, then the DataView’s Sort property will be set with the ViewState’s SortExp and SortOrder values.

Next, we are binding PagedDataSource objects with the DataView, set its property AllowPaging to True, set its PageSize to 10, and initialize its CurrentPageIndex with our CurrentPage variable. By default CurrentPage will be 0. Then we set the Enabled property of the Previous and Next LinkButton controls with the PagedDataSource objects IsFirstPage and IsLastPage property. This is to make the Previous and Next LinkButton controls disable when the PageIndex reaches first and last page respectively.
Last, we bind the GridView control with PagedDataSource object to display the records and call another private method ‘doPaging’ for building custom Paging page numbers. The code for doPaging method is as follows
private void doPaging()
{
  DataTable dt = new DataTable();
  dt.Columns.Add("PageIndex");
  dt.Columns.Add("PageText");
  for (int i = 0; i < pds.PageCount; i++)
  {
     DataRow dr = dt.NewRow();
     dr[0] = i;
     dr[1] = i + 1;
     dt.Rows.Add(dr);
  }

  dlPaging.DataSource = dt;
  dlPaging.DataBind();
}


So the doPaing method has a DataTable with two columns such as PageIndex and PageText. The PageIndex column is the selected index value and PageText column is the display value in the dlPaging. So this DataTable has to be binded with dlPaging DataList control.

Source Code for Custom Sorting

In the GridView’s RowCommand event, we are going to do sort operation for the GridView control as follows

protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
  if (e.CommandName.Equals("Sort"))
  {
     if (this.ViewState["SortExp"] == null)
     {
        this.ViewState["SortExp"] = e.CommandArgument.ToString();
        this.ViewState["SortOrder"] = "ASC";
     }
     else
    {
       if (this.ViewState["SortExp"].ToString() == e.CommandArgument.ToString())
       {
          if (this.ViewState["SortOrder"].ToString() == "ASC")
            this.ViewState["SortOrder"] = "DESC";
          else
            this.ViewState["SortOrder"] = "ASC";
       }
       else
       {
         this.ViewState["SortOrder"] = "ASC";
         this.ViewState["SortExp"] = e.CommandArgument.ToString();
       }
    }

       BindGrid();
  }
}
First we have to check the CommandName is equals “Sort” command, if so, we can initialize the ViewState variable “SortExp” with the CommandArgument (which contains the field name to sort) and “SortOrder” with “ASC” for ascending or “DESC” for descending order sorting. The above code got two conditions of assignment.

1. First time, the ViewState of SortExp will be nothing, so initialize it with the CommandArgument and set its SortOrder as “ASC”.

2. Next time, the ViewState of SortExp will have any field name, so we have to compare both the CommandArgument and the ViewState SortExp value.
  1. If both are same, then check the ViewState SortOrder contains value as “ASC” or “DESC”. If the value is “ASC”, then change the SortOrder value as “DESC” and vice versa.

  1. If both are not same, the keep the SortOrder as “ASC” and change the ViewState of SortExp to the new CommandArgument.

After all the checking and assignment, call the BindGrid event to re-arrange the GridView rows according to the above specified Sort Expression and Sort Order.

Source Code for Image Indicator in Header Row

The specialty of this article is an Image Indicator in the header row, indicates which column has sorted and in which order it has been sorted. We are going to do the coding in the GridView control RowDataBound event as follows.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.Header
     && this.ViewState["SortExp"] != null)
   {
     Image ImgSort = new Image();
        if (this.ViewState["SortOrder"].ToString() == "ASC")
                ImgSort.ImageUrl = "~/Images/downarrow.gif";
        else
                ImgSort.ImageUrl = "~/Images/uparrow.gif";

 switch (this.ViewState["SortExp"].ToString())
 {
  case "Cus_State":
    PlaceHolder placeholderState = (PlaceHolder)
                                               e.Row.FindControl("placeholderState");
    placeholderState.Controls.Add(ImgSort);
    break;

case "Cus_Email":
    PlaceHolder placeholderEmail = (PlaceHolder)
                                               e.Row.FindControl("placeholderEmail");
    placeholderEmail.Controls.Add(ImgSort);
    break;

case "Cus_Name":
    PlaceHolder placeholderName = (PlaceHolder)
                                               e.Row.FindControl("placeholderName");
    placeholderName.Controls.Add(ImgSort);
    break;

case "Cus_Sex":
    PlaceHolder placeholderGender = (PlaceHolder)
                                            e.Row.FindControl("placeholderGender");        
    placeholderGender.Controls.Add(ImgSort);
    break;

case "Cus_Age":
    PlaceHolder placeholderAge = (PlaceHolder)
                                         e.Row.FindControl("placeholderAge");
    placeholderAge.Controls.Add(ImgSort);
    break;
 }
}
}
The explanation for the above code is pretty simple. In the RowDataBound event’s Header row part, we have two sections, one for identifying the sort order and other for indicating the sort expression column. So we create an Image control at run-time and based on the SortOrder, we set the ImageUrl property. If the SortOrder is “ASC”, then set the ImageUrl with a down arrow image and for “DESC” SortOrder, set the ImageUrl with an up arrow image. Next based on the SortExp, we find the PlaceHolder control that is placed beside the LinkButton, and add the Image control into it. Thus, when the user clicks on the Header row LinkButton, the GridView will be sorted and an image will appear near the LinkButton and indicates that clicked column is sorted in Ascending or Descending order.
Source Code for Custom Paging

We have already completed the designing part of the Custom Paging for the GridView control. The DataList dlPaging will display page numbers. When it is clicked, the corresponding page will be appeared in the GridView control without disturbing the Sorting. For this we have to write code at the dlPaging ItemCommand event as follows
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
  if (e.CommandName.Equals("lnkbtnPaging"))
  {
    CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
    BindGrid();
  }
}


Here we just set the CurrentPage value from the CommandArgument, which is actually the PageIndex, then call the BindGrid event. Thus we have integrated the DataList and the GridView control to perform Custom Paging.

To highlight the selected Page Number (PageIndex) in different style, do the following code in ItemDataBound event of the dlPaging datalist.
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
  LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
  if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
  {
    lnkbtnPage.Enabled = false;
    lnkbtnPage.Font.Bold = true;
  }
}


Source Code for Next and Previous LinkButton controls

When Next LinkButton is clicked, we have to increment the CurrentPage value and when Previous LinkButton is clicked, we have to decrease the value of the CurrentPage variable, then call the BindGrid method to display the records in the corresponding page.

protected void lnkbtnNext_Click(object sender, EventArgs e)
{
  CurrentPage += 1;
  BindGrid();
}

protected void lnkbtnPrevious_Click(object sender, EventArgs e)
{
  CurrentPage -= 1;
  BindGrid();
}


Since we are maintaining the Sort Expression, Sort Order and Page Index in the ViewState of the Page, Custom Sorting and Custom Paging is easily achievable at the same time, without one disturbing the other.

Now, save the changes you have done and run this page in the browser. For sure, the GridView control will be populated with data, if the records are more than 10, paging numbers will appear. When you click the any LinkButton in the GridView Header Row, GridView will re-arrange the records in Ascending Order, and an image with down arrow will appear in the header row of that column. Click the same LinkButton again, now the GridView will re-arrange the records Descending Order and the image will show an up arrow denotes it is descending order. Click on the page number, you can see the GridView navigates to the page number you clicked without the Sorting being disturbed.

This article is to give you an abstract idea of doing custom paging and sorting in GridView control. There will be many ways to do this. It is up to you, to choose the right one, that suite your requirement.

Introduction
This article explains the two best ways to create thumbnail images dynamically in Asp.Net.
Explanation
There are several situations in website development that deals with images and to display it in Thumbnail sizes. Its really hectic to display the thumbnail images without any distortion and to maintain the quality same as the original image is not also easy. So this article is contributed to those web programmers struggling to create thumbnail images using several logics. This article explains the two ways of creating thumbnail images, which we considered the best.

To upload images to the server, we need a File Upload control and a button control. Asp.Net simplifies the process of uploading images to the server with the FileUpload control. To start with, place a FileUpload control and a button control on your webpage. For readability, change the text of the button control as ‘Upload’.


Method 1:

In this method, we are going to use Size Structure class library. It is a .NET class library structure, stores an ordered pair of integers, normally the width and height of a rectangle. By using this Size Structure we are going to scale the original image, to its appropriate thumbnail size without any disturbances in the quality of the thumbnail image. Size structure class library is available in System.Drawing namespace.

To achieve this, we have a write a general method called ‘NewImageSize’. This method takes 3 parameters such as the original height, original width of the original image and the target thumbnail size you want to resize the original image.
public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
{
  Size NewSize;
  double tempval;

  if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
  {
    if (OriginalHeight > OriginalWidth)
        tempval = FormatSize / Convert.ToDouble(OriginalHeight);
    else
        tempval = FormatSize / Convert.ToDouble(OriginalWidth);

    NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
  }
  else
    NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
}
By passing those parameters, the above method will be proportionately scale the original image and returns the exact size of the thumbnail. We can use this new size to create the thumbnail images and store it in the server.

In the click event of the Upload button, write the following code.
if (FileUpload1.PostedFile != null)
{
 string ImageName ="SampleImage.jpg";
 FileUpload1.SaveAs(Server.MapPath("Images\\") + ImageName);
 string ThumbnailPath = (Server.MapPath("ThumbnailImages\\") + ImageName;

 using (System.Drawing.Image Img =
      System.Drawing.Image.FromFile(Server.MapPath("Images\\") + ImageName))
  {
        Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 150);

        using (System.Drawing.Image ImgThnail =
            new Bitmap(Img, ThumbNailSize.Width,  ThumbNailSize.Height))
       {
            ImgThnail.Save(ThumbnailPath, Img.RawFormat);
            ImgThnail.Dispose();
       }
        Img.Dispose();
}

Here we take the image path from the FileUpload control and save the original image inside “Images” folder. Then we declare another path to save the thumbnail image.

To know the original height and width of the Original Image, we have to create an Image instance and load it by using the ‘FromFile’ method. Passes the Height and Width to the NewImageSize method along with your desired Thumbnail size in pixel. In the above code, the thumbnail size is 150 pixels height and width.

So the proportionate thumbnail size will be returned to ThumbnailSize Size Structure. Now the Original Image and the size for the thumbnail is ready with us. Last we are going to create another Image object as ImgThnail, which is initialized as a BitMap Image with the Height and Width of the Thumbnail size. Now call the Save method of the ImgThnail object, to store the Thumbnail Image in its appropriate size and location. Finally, call Dispose method, this will release the all the resources used by the Image objects.



Method 2:

The second method is by using the GetThumbnailImage method of the Image class. This method returns the thumbnail image for the given original image. The syntax for this method is

public Image GetThumbnailImage
(
  int thumbnail_Width,
  int thumbnail_Height,
  delegate GetThumbnailImageAbort callback,
  IntPtr callbackData
)

The GetThumbnailImage method takes 4 parameters such as the width of the thumbnail, height of the thumbnail image in pixels, an unused delegate and a handle or pointer that must be always Zero. This method retrieves the original image, creates a thumbnail by scaling the original image.

To create thumbnail by this method, first we to have to create a dummy delegate function, which always return false value. The syntax for the delegate function is as follows

public bool ThumbnailCallback()
{
  return false;
}


Then in the Upload button’s click event write the following code.
if (FileUpload1.PostedFile != null)
{
  string ImageName =”SampleImage.jpg”;
  FileUpload1.SaveAs(Server.MapPath("Images\\") + ImageName);

  string ThumbnailPath = (Server.MapPath("ThumbnailImages\\") + ImageName;
  System.Drawing.Image.GetThumbnailImageAbort myCallback =
        new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

  using(System.Drawing.Image TargetImage =
        System.Drawing.Image.FromFile(Server.MapPath("Images\\") + FileName))
  {
      using (System.Drawing.Image Thumbnail =
            TargetImage.GetThumbnailImage(100, 200, myCallback, IntPtr.Zero))
        {
            Thumbnail.Save(Server.MapPath("Images\\") + ImageName);
            Thumbnail.Dispose();
        }
        TargetImage.Dispose();
    }
}


By using the FileUpload control’s Save method, we store the original image in the Server. Then we are creating a CallBack delegate by using GetThumbnailImageAbort method. This method provides a callback to the Delegate ThumbnailCallback, when the GetThumbnailImage stops its execution in a premature state. If this happens it will return a true value else it will return always false. Might be it is beyond the scope of this article, we shall leave it here.

Next we are create 2 Image objects such as TargetImage and Thumbnail. The first one TargetImage is to retrieve the original Image and the second Thumbnail is to create Thumbnail Image. Call the GetThumbnailImage method of the Thumbnail object to create a thumbnail image by passing the parameters such as width, height, dummy delegate callback and a handle with Zero value. By calling the Save method of the Thumbnail Image object, we can create thumbnail. Finally we call the Dispose method, to release the resources used by our Image objects.



Point to Remember:

If you look carefully in the above block of codes in both the methods, we are creating the all Image objects within a ‘using’ statement. What does this really do?

The answer is simple. The using statement ensures that Dispose method is called without failure. Eventhough we don’t call Dispose explicitly, it is enough to enclose the statement with the using statement. The purpose of using it here is that we create Image objects and access Images that is stored in the server location. So after using the Images, if do not release it completely than it will create some Exceptions. In other case, if an Exception occurs in intermediate of the Image processing, then the .NET framework cannot release the resources used by the Image object. It will raise an Exception as follows

The process cannot access the file because it is being used by another process.

So when you enclose the Image objects between using statement, then the Images and other files used within the using statement block will be released perfectly even though exception is raised. So we always recommend you to use using statement.


The information provided in this article is only simple methods of creating thumbnail images at run-time or on fly. But there can be other methods, which will create thumbnail with simple technique and excellent quality. So we request our readers to provide them to us, so as to help other novice Asp.Net developers.













Sample For Simple Insert, Select, Edit, Update and Delete in GridView
This the sample page for making simple insert, select, edit, update and delete functions in GridView control. You can entered your own data in the controls and click Add New link to add into the GridView control. Then you can do Edit, Update and Delete functions. Even you can try by deleting all the existing records and insert new records from the controls placed in the footer section of the GridView control.
Customer List
Name
Gender
City
State
Type
Edit
Delete
Alex
Male
Oxford
Alabama
Retailer
Christiana
Female
Chester
New York
Retailer
Flintoff
Male
Southside
Alabama
Retailer
Jeniffer
Female
Destin
Florida
Wholesale
Leverlock
Male
Baytown
Texas
Wholesale
Mark
Male
Avon Park
Florida
Retailer
Total Views : 212836
Adding to your Favorites....
Add to my favorites
Email to friend
Introduction
This article explains the methods of binding Asp.Net GridView control with simple DataSet or DataTable, and also explains the methods like Insert, Edit, Update and Delete function in the GridView control.
You can see most of the articles and tutorials in many websites teach you the way to bind a GridView control to the database with some Data Source controls such as SQLDataSource, ObjectDataSource, AccessDataSource and even XMLDatasource. But this article focus on the other way, by binding the GridView control to the database with the help of simple DataTable and perform adding of new records to the database from the footer row of the GridView control. And on each row, we are going to manipulate the records by editing, updating, cancelling and deleting functions.

Sample Scenario

For demonstration, we are going to fill an ASP.NET GridView control with data from a database. Let us take a simple Customer Table. This customer table contains 6 columns such as Customer Unique Code, Name of
the Customer, Gender, City, State and Customer Type. We are going to add new records to the database and populate it in the GridView control. Then record manipulation (edit, update and delete) will be done in each and every column with the server controls such as TextBox and DropDownList. In these 6 columns, we are not going to display Customer Code, and to edit Customer Name and City columns we are going to provide TextBox, to edit Gender and Customer Type we are going to use DropDownList. Additionally, the values for Gender DropDownList will be filled with static values such as Male and Female, other DropDownList for Customer Type, we will be filled dynamically with the values from the Database.
Pre-requisites

Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.
Step 1. Create Class File ‘CustomersCls.cs’

We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section. Let us write five methods in the class file as follows
public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
{
    // Write your own Insert statement blocks
}

public DataTable Fetch()
{
  // Write your own Fetch statement blocks, this method should return a DataTable
}

public DataTable FetchCustomerType()
{
  // Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
}

public void Update(int CustomerCode, string CustomerName, string Gender, string City,  string CustomerType)
{
  // Write your own Update statement blocks.
}

public void Delete(int CustomerCode)
{
  // Write your own Delete statement blocks.
}
Step 2: Make Design File ‘Default.aspx’

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be converted to TemplateField columns except the Delete column.
Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] - Gender

Now again select Edit Template, choose column[1] - Gender, replace the TextBox with a DropDownList, name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval("Gender") to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] - State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.
Column[4] - Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] - Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.

http://www.aspdotnetcodes.com/Images/collapse.jpgClick here to view Source Code of the GridView Control HyperLink
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code, Type" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>

<asp:TemplateField HeaderText="Name" SortExpression="Name"> <EditItemTemplate>
  <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
  <asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("Gender") %>'>
    <asp:ListItem Value="Male" Text="Male"></asp:ListItem>
    <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewGender" runat="server" >
    <asp:ListItem Selected="True" Text="Male" Value="Male"></asp:ListItem>
    <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City">
<EditItemTemplate>
  <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("State") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewState" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />

</Columns>
</asp:GridView>


Step 3: Make Code-behind File ‘Default.aspx.cs’

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows
CustomersCls customer=new CustomersCls();

Then create a private method 'FillCustomerInGrid' to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header, data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.
private void FillCustomerInGrid()
{
   DataTable dtCustomer= customer.Fetch();

 if (dtCustomer.Rows.Count>0)
 {
    GridView1.DataSource = dtCustomer;
    GridView1.DataBind();
 }
 else
 {
      dtCustomer.Rows.Add(dtCustomer.NewRow());
      GridView1.DataSource = dtCustomer;
      GridView1.DataBind();

      int TotalColumns = GridView1.Rows[0].Cells.Count;
      GridView1.Rows[0].Cells.Clear();
      GridView1.Rows[0].Cells.Add(new TableCell());
      GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
      GridView1.Rows[0].Cells[0].Text = "No Record Found";
  }
}

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not. Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as "No Record Found", this text will be displayed if the GridView is empty without any rows and you can see both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,
protected void Page_Load(object sender, EventArgs e)
{
  If (!IsPostBack)
  {
     FillCustomerInGrid();
   }
}

Fill DropDownList in GridView with dynamic values

In column[4] - Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

  if (cmbType != null)
  {
    cmbType.DataSource = customer.FetchCustomerType();
    cmbType.DataBind();
    cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
   }
 }

if (e.Row.RowType == DataControlRowType.Footer)
{
    DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
    cmbNewType.DataSource = customer.FetchCustomerType();
    cmbNewType.DataBind();
 }

}


Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows
cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName.Equals("AddNew"))
  {
   TextBox txtNewName=(TextBox)GridView1.FooterRow.FindControl("txtNewName");
   DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
   TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
   TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
   DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");

   customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue) ;
      FillCustomerInGrid();
  }
}

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database and listed in the GridView control.
Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
  GridView1.EditIndex = e.NewEditIndex;
  FillCustomerInGrid();
}

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
  GridView1.EditIndex = -1;
   FillCustomerInGrid();
}
You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
  DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
  TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
  DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");

 customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text, cmbGender.SelectedValue,txtCity.Text, cmbType.SelectedValue);
  GridView1.EditIndex = -1;
  FillCustomerInGrid();
}

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Delete in GridView

To delete a row from the customer table, add the following lines of code in the GridView’s RowDeleting event. Here you have to pass the unique Code of customer which is in GridView1.DataKeys[e.RowIndex].Values[0].ToString() to the Delete method of the CustomersCls class.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  customer.Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
  FillCustomerInGrid();
}


This article gives you some basic idea of inserting data into database from a GridView control and does all database manipulations within the GridView without binding it with any Asp.Net Data source controls.
Asp.Net AdRotator control with Database Integration
Posted by Moderator1 on 6/30/2007 12:11:33 PM
Category: Asp.Net 2.0
Total Views : 28493
Adding to your Favorites....
Add to my favorites
Email to friend
Introduction
This article explains the concept of Asp.Net AdRotator control fetching ad information from the database and rotates the ads on certain time interval. This article also gives a tip to fetch ad information from an XML file.
The AdRotator Control presents ad images each time a user enters or refreshes a webpage. When the ads are clicked, it will navigate to a new Web location. Each time the page is loaded into the browser, an ad is randomly selected from a predefined list. Previously the predefined list means an XML File, which contains the information about the ads to be displayed. But in Asp.Net 2.0 we can maintain the list in any data source. In this article, we explained the AdRotator control to fetch ads information from both database and XML file, and display those ads in randomly with the help of Timer control. You can say it as an AJAX AdRotator Control.

AdRotator with XML File

Open a project as Asp.Net Ajax enabled website in Microsoft Visual Studio 2005, drag and drop an UpdatePanel and add an AdRotator control and Timer Control into it. Set the UpdateMode property of UpdatePanel to conditional. Set the Timer Control Interval property to your desired time. The Interval is in milliseconds. Double click in the Timer Control, it will create a Timer1_Tick event in your code-behind. Add a single line of code as follows
protected void Timer1_Tick(object sender, EventArgs e)
{
    UpdatePanel1.Update();
}

Now add an XML file into your project, name it as Ads.xml and specify the AdvertisementFile property of the AdRotator control to point this XML file. So your AdRotator control’s html code will like like
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/Ads.xml" />

Now we will fill the Ads.xml file with advertisement information. The AdvertisementFile must have the following attributes.
1. ImageUrl: The location of the ad image file.
2. NavigateUrl: The Web location to navigate to when the image ad is clicked.
3. AlternateText: The text to provide as the ALT attribute of the image control when the ad is rendered. This can also be seen as ToolTip.
4. Keyword: Here you can specify some keyword related with the ads image to fetch.
5. Impressions: An integer number to specify the weight of the ad. If the number is larger, then more time the image ad will appear.

The ImageUrl is the only mandatory attribute, rest is optional. Let us have a look on the XML Advertisement file we create for you.
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>http://www.anyserver.com/ads/859866.jpg</ImageUrl>
<NavigateUrl> http://www.anyserver.com</NavigateUrl>
<AlternateText>anyserver.com</AlternateText>
<Keyword>Servers</Keyword>
<Impressions>80</Impressions>
</Ad>
<Ad>
<ImageUrl>http://www.yourserver.com/ads/309548.gif</ImageUrl>
<NavigateUrl>http://www.yourserver.com</NavigateUrl>
<AlternateText>YourServer.com</AlternateText>
<Keyword>MyServer</Keyword>
<Impressions>80</Impressions>
</Ad>
</Advertisements>
That’s it. Easy and save your project. View your project in browser, you can see the rotation of ads in your webpage, at the interval you fixed in the Timer Control.

Disadvantage of AdRotator with XML File

One of the main disadvantage of AdRotator when functioning with XML file is real time maintainance. Yes if you want to add any new ads or you want to remove any existing ads is not an easy job when your ads is large in number. Everytime to have to find and replace or remove the appropriate tags from the xml file and then you have to upload to the server which is time consuming and hectic. To overcome this difficulty, Asp.Net 2.0 introduce the concept of builing AdRotator control with database. Let us all jump to study how it is easy to integrate an AdRotator with database rather than an XML file.
ComponentArt

AdRotator with Database

AdRotator control can be bind with any data source. For this article, we shall take MS SQL Server as our data source. We need to create a Table with the following columns in it.
Create Table YourAdRotatorTableName
(
  AlternateText VarChar(100),
  ImageUrl VarChar(100),
  NavigateUrl VarChar(200)
)
These columns in the table are already fixed with the AdRotator control’s attributes. So we no need to specify it in the property tab of the AdRotator control. In case, if you change the column name in the database table, then you have to specify it property in the AlternateTextField, ImageUrlField, NavigateUrlField and KeywordFilter attributes of the AdRotator control. But I don’t know why ImpressionField is missing in the property tab.

To start with, add another Aspx file to your project, add a ScriptManager and an UpdatePanel. Drag and drop an AdRotator with a Timer Control into the UpdatePanel. Set the Interval property to your desired time, which is in milliseconds. In the code-behind file, let us write a method to fetch ads information from the above table.
private DataTable FetchAdsFromDB()
{
    string sql = "select * from YourAdRotatorTableName";
    SqlDataAdapter da = new SqlDataAdapter(sql, );
    DataTable dt = new DataTable();
    da.Fill(dt);
    return dt;
}
The above method fetches ads information from the table and returns it as a database. You have to mention the DataSource of the AdRotator to this method in your Page_Load event.
AdRotator1.DataSource = FetchAdsFromDB();
AdRotator1.DataBind();

We should not forget the Timer Control and the AJAX functionality to be implemented with this AdRotator. So double click on the Timer control to create an event Timer1_Tick in your code-behind file. Just bind your FetchAdsFromDB method again to the AdRotator control. Save the changes and run your application, you can see the Ads Rotating in your webpage.
protected void Timer1_Tick(object sender, EventArgs e)
{
    AdRotator1.DataSource = FetchAdsFromDB();
    AdRotator1.DataBind();
}


Advantages of AdRotator with Database

The main advantage of AdRotator with database is easy maintainance of ads. You can activate or deactivate any time you want. You can manage n-number of Ads in you application with any ads size.


using System;
 
using System.Data;
 
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 System.Data.SqlClient;
 
 
 
public partial class _Default : System.Web.UI.Page
 
{
 
SqlDataAdapter da;
 
DataSet ds = new DataSet();
 
SqlConnection con;
 
SqlCommand cmd = new SqlCommand();
 
 
 
protected void Page_Load(object sender, EventArgs e)
 
{
 
if (!Page.IsPostBack)
 
{
 
Binddata();
 
}
 
}
 
 
 
// Define the Edit Command
 
public void editgrid_click(object sender, DataGridCommandEventArgs e)
 
{
 
gridedit.EditItemIndex = e.Item.ItemIndex;
 
Binddata();
 
}
 
 
 
// Define the Cancel Command
 
public void gridcancel_click(object sender, DataGridCommandEventArgs e)
 
{
 
gridedit.EditItemIndex = -1;
 
Binddata();
 
}
 
 
 
//Here we Bind the data
 
public void Binddata()
 
{
 
con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);
 
cmd.CommandText="select * from record order by id Asc";
 
cmd.Connection = con;
 
da = new SqlDataAdapter(cmd);
 
da.Fill(ds);
 
con.Open();
 
cmd.ExecuteNonQuery();
 
gridedit.DataSource = ds;
 
gridedit.DataBind();
 
con.Close();
 
}
 
 
 
//Update Command Defination
 
protected void updategrid_UpdateCommand(object source, DataGridCommandEventArgs e)
 
{
 
try
 
{
 
con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);
 
cmd.CommandText = "Update record set name=@name ,F_name=@F_Name, l_name=@l_name,City=@City,State=@State  where id=@id";
 
cmd.Parameters.Add("@name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
 
cmd.Parameters.Add("@F_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
 
cmd.Parameters.Add("@l_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
 
cmd.Parameters.Add("@City", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
 
cmd.Parameters.Add("@State", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[5].Controls[0]).Text;
 
cmd.Parameters.Add("@id", SqlDbType.Int).Value = gridedit.DataKeys[e.Item.ItemIndex];
 
cmd.Connection = con;
 
cmd.Connection.Open();
 
cmd.ExecuteNonQuery();
 
cmd.Connection.Close();
 
gridedit.EditItemIndex = -1;
 
Binddata();
 
}
 
catch (Exception ex)
 
{
 
Response.Write(ex.Message);
 
}
 
}
 
 
 
// Delete Command Defination
 
public void gridedit_DeleteCommand(object sender, DataGridCommandEventArgs e)
 
{
 
con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);
 
int U_ID = (int)gridedit.DataKeys[(int)e.Item.ItemIndex];
 
cmd.CommandText = " Delete from record where  id=" + U_ID;
 
cmd.Connection = con;
 
cmd.Connection.Open();
 
cmd.ExecuteNonQuery();
 
cmd.ExecuteNonQuery();
 
cmd.Connection.Close();
 
gridedit.EditItemIndex = -1;
 
Binddata();
 
}
 
 
 
// For Paging
 
public void gridedit_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
 
{
 
gridedit.CurrentPageIndex = e.NewPageIndex;
 
Binddata();
 
}
 
 
 
//Link for Insert a new Record in a table
 
public void InsertNewRecord_click(object source, System.EventArgs e)
 
{
 
lblnewname.Visible = true;
 
txtnewname.Visible = true;
 
lblF_name.Visible = true;
 
txtF_name.Visible = true;
 
lblLast_name.Visible = true;
 
txtLast_Nmae.Visible = true;
 
lblcity.Visible = true;
 
txtcity.Visible = true;
 
lblState.Visible = true;
 
txtState.Visible = true;
 
btnnewRecordSubmit.Visible = true;
 
}
 
 
 
// Command for insert a new Record
 
public void Submitnew(object source, System.EventArgs e)
 
{
 
con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);
 
cmd.CommandText = "insert into record(name,F_name,l_name,City,State) values(@name,@F_Name,@l_name,@City,@State)";
 
cmd.Parameters.Add("@name", SqlDbType.Char).Value = txtnewname.Text;
 
cmd.Parameters.Add("@F_Name", SqlDbType.Char).Value = txtF_name.Text;
 
cmd.Parameters.Add("@l_name", SqlDbType.Char).Value = txtLast_Nmae.Text;
 
cmd.Parameters.Add("@City", SqlDbType.Char).Value = txtcity.Text;
 
cmd.Parameters.Add("@State", SqlDbType.Char).Value = txtState.Text;
 
cmd.Connection = con;
 
cmd.Connection.Open();
 
cmd.ExecuteNonQuery();
 
cmd.Connection.Close();
 
gridedit.EditItemIndex = -1;
 
Binddata();
 
txtnewname.Text = "";
 
txtF_name.Text = "";
 
txtLast_Nmae.Text = "";
 
txtcity.Text = "";
 
txtState.Text = "";
 
 
lblnewname.Visible = false;
 
txtnewname.Visible = false;
 
lblF_name.Visible = false;
 
txtF_name.Visible = false;
 
lblLast_name.Visible = false;
 
txtLast_Nmae.Visible = false;
 
lblcity.Visible = false;
 
txtcity.Visible = false;
 
lblState.Visible = false;
 
txtState.Visible = false;
 
btnnewRecordSubmit.Visible = false;
 
}
}
 
to display images in gridview.you have to do the following

in button click just paste the following code

string strSql = "Select ImageId, ImageName, Images, ImageType, ImageSize from Pictures";
SqlDataAdapter daPics = new SqlDataAdapter(strSql, con);
daPics.Fill(dsPics);
dsPics.Tables[0].Columns.Add("imgFile");
foreach (DataRow drPics in dsPics.Tables[0].Rows)
{
    drPics["imgFile"] = ("grabpicture.aspx?ImageId=" + drPics[0]);           
}
gvWithImages.DataSource = dsPics;
gvWithImages.DataBind();

in the above code pictures table is used and its design script is attached.you can find it in the attachment.

and i have used one more aspx page to load the image that is "grabpicture.aspx"

in grabpicture.aspx page global declaration area declare these variables

DataSet dsPics;
SqlDataAdapter daPics;
byte[] ImgContent;
DataRow drPics;
string strSql, strImgContentType;
SqlConnection con = new SqlConnection("user id=<user>;pwd=<password>;data source=<sysname/ipaddress>;database=<dbname>");

in grabpicture.aspx page load event write the following code
strSql = "Select * from Pictures where ImageId = " + Request.QueryString["ImageId"];
daPics = new SqlDataAdapter(strSql, con);
dsPics = new DataSet();
daPics.Fill(dsPics);
drPics = dsPics.Tables[0].Rows[0];
ImgContent = (byte[])drPics["Images"];
strImgContentType = drPics[3].ToString();
Response.ContentType = strImgContentType;
Response.OutputStream.Write(ImgContent, 0, (int)drPics[4]);
Response.End();

private void grid_view()
{
   string s=ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
   string sel = "select * from TableName";
   SqlConnection con = new SqlConnection(s);
   SqlCommand cmd = new SqlCommand(sel, con);
   SqlDataAdapter sda = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   sda.Fill(ds);
   GridView1.DataSource = ds;
   GridView1.DataBind();
}
 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        grid_view();
       
    }
                                                                                   
Saving the image in SQL Server

  

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

con.Open();

byte[] ImgBytes = new byte[flurl.PostedFile.InputStream.Length];

flurl.PostedFile.InputStream.Read(ImgBytes, 0, ImgBytes.Length);

string qry = "Insert into Table1(ImageData) values(@ImageData)";

SqlCommand cmd = new SqlCommand(qry, con);

cmd.Parameters.AddWithValue("@ImageData", ImgBytes);

cmd.ExecuteNonQuery();

con.Close();


page_load()
{
// give sql connections(connection string)
}
protected void Button1_Click(object sender, EventArgs e)
{
int len = FileUpload1.PostedFile.ContentLength;

byte[] pic = new byte[len];
FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
string fup = FileUpload1.PostedFile.FileName;


if (k1 == 0)
{
cmd = new SqlCommand("insert into login_inf(first_name,logo) values (@name,@logo)", conn);


cmd.Parameters.Add("@name", TextBox1.Text.Replace("'", "''"));

cmd.Parameters.Add("@logo", pic);
cmd.ExecuteNonQuery();

}
}


byte[] file = SqlConvert.ToByteArray(dr["FileImage"]);

string fileName = SetupFileName(SqlConvert.ToString(dr["FileName"]));

string filePath = System.Environment.CurrentDirectory + “\\myFiles\\” + fileName;

FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

BinaryWriter bw = new BinaryWriter(fs);

bw.Write(file);

bw.Flush();

bw.Close();

fs.Close();

No comments:

Post a Comment