ASP.NET

Error logging using Elmah

INTRODUCTION
Developers mostly use the third party controls for logging errors in asp.net applications or some may write custom code for logging errors.

In this article I will mentioned such third party control for logging errors. It is very handy, easy to use and useful control for logging errors in asp.net application.

This tool is developed by Google and it is free and open source. The name of the tool is ELMAH.

OVERVIEW
To integrate Elmah tool in your application you need to download the file from the google code site.
To download the file http://code.google.com/p/elmah/.
The zip file contains the source code and bin file. You need to add the Elmah.dll, ElmahErrorLog.dll, VistaDB.NET20.dll, System.Data.SQLite.dll, Elmah.xml file in your applications bin folder.
Add the reference for above dll files.
Error can be logged in many ways.

  1. In memory
  2. Store error in sql server.

In memory store the error in memory. You can view the error at runtime and the error does not gets stores anywhere.

To make sure the data gets store in somewhere, you need to create the table in sql server.
The source code which you download contains the sql server file. Just run the query and the table will be created automatically as shown below.

As shown above it will create ELMAG_error table in your database. IT also creates couple of procedures for inserting data.

Now we need to configure your web.config file to put elmah to work. Add elmah module to your web.config file.

Just specify the data source, user name and password in your connection string and rest of the settings for elmah you need to specify as shown above.

Now we need to make use of elmah for logging the error in the database you have created.

For testing the Elmah error log create a method that will generate the error as shown below.

using System;
using System.Web.UI;
using Elmah;
public partial class ElmahErrorLog : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Division();
}
}

private void Division()
{
try
{
int i = 0;
int j = 2;
int x = j / i;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}

ErrorSignal.FromCurrentContext().Raise(ex) is used to log error and store it in database.

To check the error, just open the browser and type the URL of your web application followed by elmah.axd. Below is the screenshot.

You can see the screen in the grid format displaying the details of your error.

To view more details related to your error click on the details link next to your error. The details explanation of the error will be displayed as shown below.

This is how you can use elmah error logging for logging errors.

This is just the short description of elmah error logging. For more details for elmah error logging click here.

To download the source code click here.

Introduction to Webparts

INTRODUCTION
In this article I will show you to use various aspects of webparts in ASP.net. Using webparts you can provide user with the option to drag and drop objects, changing the CSS at runtime.

EXAMPLE
There are 2 basic things in Webparts:-
1. WebPartManager
2. Webparts Zone

WebPartManager
All Webparts is managed under WebPartManager. You are required to use WebPartManager where ever you are using Webparts in your project. Webparts will not work without WebPartManager.

Webparts Zone
There are 4 kind of zone in web part that is required to build a web part. The 4 zones are:
1. WebPartZone
2. EditorZone
3. CatalogZone
4. ConnectionZone

To use different zones add a dropdown list to your webform and add the following items to it.
• Browse
• Design
• Edit
• Catalog
• Connect

You need to write the code on the selectedIndexChange event of dropdownlist.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text == “Select”)
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Design”)
{
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Browse”)
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Catalog”)
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Edit”)
{
WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Connect”)
{
WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode;
}
}

BROWSE MODE
First we will look at the browse mode. It is the default mode in your webpart. No actions such as drag and drop, changing CSS etc can be performed using browse mode. In case of browse mode only 2 options are seen i.e. minimize and close. Using minimize options you can minimize the webpart and using close option you can close the webpart which can only be restored while being in catalog mode which we will discuss later in this article. Below is the screenshot of sample webpart displayed below.

DESIGN MODE
In design mode we can drag drop objects from one webpart zone to another webpart zone. For that purpose select Design from the dropdown menu and then drag the object from one zone to another zone. In the below screenshots we are dragging control from “Display name “webpart zone to “Enter name” webpart zone.

EDIT MODE
In this mode we can edit the webpart at runtime.  We can perform various actions such as changing the size, color etc of the textbox. Edit mode is further divided in to 4 parts. They are Appearance, behavior, Property and layout. We will first look at the Appearance and Layout part.
First, place an editor zone into the web form. Then place an AppearanceEditorPart and LayoutEditorPart inside the editor zone. Run the application and select the “Edit” mode from the dropdown list.
On selecting the Edit mode from the dropdown menu, the webpart will appear with one more option of Edit. Click edit from the menu available for webparts.

On selecting Edit mode you will get the below output.
You can perform various actions such as changing the title name, specifying the chrome type, changing the width and height of the control etc.
For e.g. if you want to change the title name just specify the title name and then click on the ok button provided below. On clicking the ok button changes will be reflected.
The below is the screenshot.

Now, suppose if you want to change the property of the object in webpart such as changing the CSS of the object in a webpart. This can be achieved using PropertyGridEditorPart.
For that purpose create a user control with textbox and button and place that user control inside the webpart zone.
In this case we will change the CSS class of textbox and button. For that create one css class and give the reference of that css class in your page.
The below is the CSS class.

.textbox_1
{
background-color:White;
color:Blue;
border:solid 2px blue;
}

.button_1
{
background-color:White;
color:Blue;
border:solid 2px blue;
}

.textbox_2
{
background-color:White;
color:Black;
border:solid 2px black;
}

.button_2
{
background-color:White;
color:Black;
border:solid 2px black;
}

In the code behind of the user control write the following code.

string _cssClasstextbox = string.Empty;
string _cssClassbutton = string.Empty;
[WebBrowsable(), Personalizable(true)]
public string CssClassTextbox
{
get { return _cssClasstextbox; }
set { txtname.CssClass = value;}
}
[WebBrowsable(), Personalizable(true)]
public string CssClassButton
{
get { return _cssClassbutton; }
set { btnclick.CssClass = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
txtname.CssClass = CssClassTextbox;
btnclick.CssClass = CssClassButton;
}

The above code changes the CssClass of the TextBox and button. This property will now be available in the webparts edit mode and we will be able to change this at run-time as well. Besides setting the CssClass we have also used two additional attributes in the class declaration:

  • WebBrowsable – It allows a webpart to display a user defined property in edit mode.
  • Personalizable – It allows a property to be editable.

Now run this page. If we choose the edit mode from the webpart menu, we will see the following edit button in options menu of the webpart. The screenshot below illustrates this.

On selecting edit mode from the option, we will have the CSS property in the edit mode. The below is the screenshot.

Currently Textbox and button is using the default Css property. Now we will apply the new CSS class from the stylesheet for e. g textbox_2 and button_2 and click on the ok button.
The style of the textbox and button will get change as shown below.

CATALOG MODE
The catalog zone gives us the option to add/remove, hide/show the webparts at runtime. For example say there are few webparts on Webform such as webpart showing weather condition, time, daily horoscope etc. Now if the user wants to remove or hide the webpart at runtime, then it can be accomplished using catalog mode.
To use catalog mode you need to catalog zone. The catalog zone is further divided in to three parts. They are PageCatalogPart, DeclarativeCatalogPart and ImportCatalogPart.
On the Webform add one catalog zone and add all the above catalog part in to it.

Page catalog
Suppose if you want to remove Enter name webpart from the page at runtime. You can do it by just by selecting close option from the webpart options.

Now you want the same webpart to appear in your page again. To do that select catalog options from the dropdown list. You will see the catalog zone with the all the above three parts as shown below.

You can see in the above screen shot that Enter Name webpart appears in the Page Catalog zone. Select the Enter Name webpart and select the zone from the dropdown list to which you want to add the selected webpart.
The selected webpart will be added to the respective zone which you have selected.

Imported Web part catalog
Suppose user want to add new external webpart. He can do that by importing webpart. We can import files with the extension .webpart. To export a file as a .webpart type, add the following line to your web.config inside the <system.web> tag.

<webParts enableExport=”true“></webParts>

To import webpart, click on the “Imported web part catalog” link in catalog zone.  It will display the fileupload control from where you can upload the file. Once the file is uploaded it will below fileupload control. Select the webpart and select the zone from the dropdown list to which you want to add the webpart. The below is the screenshot.

Selected webpart get added to your webpart zone.

CONNECT MODE
Connect mode allows webpart to connect with each other. We can make static connections through code or we can make connections at runtime according to the requirement. Here webpart is not connecting to database. Instead it is connecting to another webpart.
In our example we will create 2 controls b y name “name.ascx” and “Displayname.ascx”. One is for passing the text and another is for receiving the text.
Add a new class in the App_Code directory and name it ITextProvider. Add the following code to it.

public class ITextProvider
{
public interface ITextToPass
{
string GetText();
}
}

We are going to use this interface in both user controls to pass text between these two entities.
Add one textbox and a button in the name.ascx control. Add the below code in “name.ascx” page just above the page load.

[ConnectionProvider(“TextToPass”, “TextProvider”)]
public ITextProvider.ITextToPass GetTextTransferInterface()
{
return ((ITextProvider.ITextToPass)(this));
}

public string GetText()
{
return txtname.Text;
}

Add one label in another control in “Displayname.ascx”. Add the below code in “Disaplayname.ascx” page just above the page load.

[ConnectionConsumer(“Text”, “TextConsumer”)]
public void GetTextTransferInterface(ITextProvider.ITextToPass provider)
{
lblName.Text = provider.GetText();
}

Run the example. Select connect mode from the dropdown list.  Then select connect option from the webpart, connection zone appears. Then click on the Create a connection to a Consumer link in the connection zone as shown below.

On clicking the hyperlink it will display the below screen.

Select the webpart as a consumer from the dropdown list and click on the connect button.

Once the connection is established you can test the connect mode. Enter any text in name webpart and click on the button. It will display the entered string in another webpart as shown below.

SAVING PAGE STATE IN DATABASE
Suppose there are multiple users accessing your application and you need to save page setting for each users. In that case you need a store the users setting in database.
In this case we will create a database to store users setting. We are going to use the default asp.net database called ASPNETDB.mdf which is automatically created in applications app_data folder. This database already has the appropriate schema to save the page state for every user.
To create the default database for webparts you need to run the utilitynamed as aspnet_regsql.exe which is located in the C:\Windows\Microsoft.NET\Framework\v2.0.50727. This utility helps us to create tables and stored procedures required to customize database. The below is the screenshots.

Just follow the wizard to create the default database. It will create the following tables in database.

That’s it.

To download the source code click here.

Encryption and Decryption using UTF8encoding, MD5 and SHA1 algorithm

INTRODUCTION
Many times you must have seen that the programmers use a technique to encode or decode the text especially the password while storing or retrieving. In this article I will show you to encode and decode the text.

EXAMPLE
In this article I will show you to encode and decode the text using UTFencoding, MD5 and SHA1.To start we will take example of simple example as shown below for encoding and decoding text.

1

First we will encode or decode the text using UTFencoding. The below is the method for encoding text using UTFencoding.

private void EncodeText(string strtext)
{
try
{
byte[] strlength = new byte[strtext.Length];
strlength = System.Text.Encoding.UTF8.GetBytes(strtext);
lblenc.Text = Convert.ToBase64String(strlength);
}
catch (Exception ex)
{
throw ex;
}
}

The below is the code for decoding the text.

private void DecodeText(string strtext)
{
try
{
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
System.Text.Decoder dec = enc.GetDecoder();
byte[] byttext = Convert.FromBase64String(strtext);
int intcharcount = dec.GetCharCount(byttext, 0, byttext.Length);
char[] chrdecchar = new char[intcharcount];
dec.GetChars(byttext, 0, byttext.Length, chrdecchar, 0);
string result = new String(chrdecchar);
lblDec.Text = result;
}
catch (Exception ex)
{
throw ex;
}
}

Call above both the methods on the click event of a button.

protected void btnEntext_Click(object sender, EventArgs e)
{
EncodeText(TextBox1.Text.Trim());
}

protected void btnDecText_Click(object sender, EventArgs e)
{
DecodeText(TextBox2.Text.Trim());
}

Second way of encoding the text is by using MD5 algorithm. The below is the method for encoding text using MD5.

private string MD5TextEncrypt(string strEncText)
{
string strmd5string = null;
byte[] byeEncText = null;
UTF8Encoding Encoder = new UTF8Encoding();
MD5CryptoServiceProvider MD5Hasher = new MD5CryptoServiceProvider();
byeEncText = Encoder.GetBytes(strEncText);
byeEncText = MD5Hasher.ComputeHash(byeEncText);
strmd5string = BitConverter.ToString(byeEncText);
strmd5string = strmd5string.Replace(“-“, “”);
return strmd5string;
}

Third way of encoding text is by SHA1 algorithm. The below method is the method for encoding text using SHA1.

FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text.Trim(), “SHA1”);

The namespace required for UTF8encoding, MD5 and SHA1 algorithm are

using System.Security.Cryptography;
using System.Text;

As far as decryption is concerned in case of MD5 and SHA1 it is not possible. SHA1 and MD5 is a hash algorithm. Since MD5 is a one-way encryption, it is not made to be decrypted. If you want to validate the text such as password entered by a user, just encrypt that text that user entered and compare the encrypted string with the password you had stored. If they match, the user has entered the correct password.

You can download the demo project from the following link.

Autocomplete textbox using AJAX AutoCompleteExtender

INTRODUCTION
Now a days you must be familiar with the auto complete functionality that many sites are providing in textbox. When you type something in the textbox the data will be populated in the form of dropdown in the textbox. That is auto complete. In this article I will show you to implement auto complete functionality on textbox.

EXAMPLE
Auto complete functionality can be implemented in many ways. In this article I will show to implement auto complete functionality using Ajax control and web services.  The name of that control is Ajax AutoCompleteExtender. This extender is available in the ajax tool kit. You can download the tool kit from the codeplex site along with the example from the following link http://www.codeplex.com/AjaxControlToolkit/ Release/ProjectReleases.aspx?ReleaseId=4941. The toolkot contains AjaxControlToolkit.dll which has to be included in the bin folder of your application. For your reference I have already included the AjaxControlToolkit.dll file in the bin folder.
Now let’s begin with the example. Our auto complete textbox will look something like this.

1

Step1:-
First create the table in your sample database from where the data (first name and last name) will be displayed. The following is the table structure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[UserName](
[User_id] [int] IDENTITY(1,1) NOT NULL,
[F_name] [varchar](50) NULL,
[L_Name] [varchar](50) NULL,
CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED
(
[User_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF

Insert some data in to the table. The following are the insert scripts for the table.

SET NOCOUNT ON
GO
SET IDENTITY_INSERT [dbo].[UserName] ON
GO
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (1,‘Anish’,’John’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (2,‘Andrew’,’Symonds’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (3,‘Anthony’,’Gonzalves’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (4,‘Armand’,’Hammer’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (5,‘Bill’,’Gates’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (6,‘Bronx’,’Wentz’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (7,‘Breece’,’Pancake’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (8,‘Cajus’,’Caesar)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (9,‘Camera’,’Ashe’)
INSERT [dbo].[UserName]([User_id],[F_name],[L_Name]) VALUES (10,‘Christine’,’Daaé’)
SET IDENTITY_INSERT [dbo].[UserName] OFF
GO

Run both of these scripts i.e. first create a table and then run the insert scripts to insert data. (I have already included the db script in the example.)

Step2:-
Secondly include the script manager and update panel and a textbox to your html page. Your HTML page will look something like this as shown below.

2

Add the service reference to your script manager of your web service (.asmx file).

Step3:-
Our third steps go with creating a web services. In this web service we will be retrieving data from the database and display it when some data is entered in to the textbox.
When you add new web service to your project the following line is commented by default in .asmx.cs file. Your auto complete textbox will not work if the following line is commented.
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//[System.Web.Script.Services.ScriptService]

To make your auto complete functionality work uncomment the above line of code.
Now write the logic for getting data from database. The following string array method is used to retrieve data from database.

[WebMethod]
public string[] GetName(string prefixText)
{
DataSet dtst = new DataSet();
string con = ConfigurationManager.ConnectionStrings[“conn”].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string strSql = “select F_name + ‘ ‘ + L_Name as [name] from UserName where F_name + ‘ ‘ + L_Name  like ‘” + prefixText + “%’ “;
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr[“name”].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}

The above methos is called on the .aspx page on the webform.
That’s it. It’s all done. Now you are ready to work with your auto complete textbox.
You can download the demo project from the following link.

Export/Upload data from Excel to sql server table.

INTRODUCTION
In this article I will show you to upload data from excel to sqlserver table.

EXAMPLE
I will export the data from excel to sqlserver table using SqlBulkCopy.
Webform will look something similar to below image.

page

First create a table in your sql server database for exporting data. The table structure is as follows.

CREATE TABLE [dbo].[UploadDetails]
(
[F_name] [varchar](50) NULL,
[L_name] [varchar](50) NULL,
[Address] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[City] [varchar](50) NULL,
[ZipCode] [varchar](50) NULL
)

In the .aspx.cs file add the following code for export excels functionality.

private void uploaddata()
{
try
{
if (FileUpload1.HasFile)
{
string path =
System.Web.Configuration.WebConfigurationManager.AppSettings[“path”]  +  Path.GetFileName(FileUpload1.PostedFile.FileName);
ViewState[“filename”] =
Path.GetFileName(FileUpload1.PostedFile.FileName);
string pFullPath = Server.MapPath(path);
if (Directory.Exists(Path.GetDirectoryName(pFullPath)) != true)
{
Directory.CreateDirectory(Path.GetDirectoryName(pFullPath));
}
string strExtn = Path.GetExtension(FileUpload1.FileName);
if (strExtn.ToLower() != “.xls”)
{
lblMsg.Text = “Invalid file type”;
return;
}
else
{
FileUpload1.PostedFile.SaveAs(pFullPath);
insertdata();
deletefiles();
}
}
else
{
lblMsg.Text = “select a file to upload”;
return;
}
}
catch (Exception)
{
}
}
The above code is used to upload the excel file to folder.
string path = System.Web.Configuration.WebConfigurationManager.AppSettings[“path
] + Path.GetFileName(FileUpload1.PostedFile.FileName);
The above code is used to get the connection string as metioned from the web.config file and addfilename to it.
ViewState[“filename”] = Path.GetFileName(FileUpload1.PostedFile.FileName);
The above code is used to get the filename and stored it in a viewstate.
string pFullPath = Server.MapPath(path);
if (Directory.Exists(Path.GetDirectoryName(pFullPath)) != true)
{
Directory.CreateDirectory(Path.GetDirectoryName(pFullPath));
}
The above code is used to check wheather the directory for saving excel file exists or not.If directory does not exists then it will create a directory.
string strExtn = Path.GetExtension(FileUpload1.FileName);
if (strExtn.ToLower() != “.xls”)
{
lblMsg.Text = “Invalid file type”;
return;
}
else
{
FileUpload1.PostedFile.SaveAs(pFullPath);
insertdata();
deletefiles();
}

The above code is used to check the file extension of excel file.If the file does not contains .xls extension then it is not a valid excel file otherwise it is a excel file.

private void insertdata()
{
string strfilename = string.Empty;
string strexcelConnectionString = string.Empty;
string strsqlConnectionString = string.Empty;
strfilename = “~\\ExcelFile\\” + ViewState[“filename”];
strexcelConnectionString = @“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Server.MapPath(strfilename) +; Extended Properties=\”Excel 8.0;HDR=YES;IMEX=1;\””;
strsqlConnectionString = ConfigurationManager.ConnectionStrings[“conn”].ToString();
using (OleDbConnection connection = new OleDbConnection(strexcelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand(“Select [FirstName], [LastName], [Address], [Country], [City], [Zipcode] FROM [Sheet1$]”, connection);
//truncate the table before inserting new data.
SqlConnection cnntrunc = new SqlConnection(strsqlConnectionString);
//open the connection.
cnntrunc.Open();
//begin the transaction.
SqlTransaction myTrans = cnntrunc.BeginTransaction();//New a transaction
SqlCommand truntble = new SqlCommand();
truntble.Transaction = myTrans;
truntble.Connection = cnntrunc;
try
{
//Create DbDataReader to Data Worksheet.
using (DbDataReader dr = command.ExecuteReader())
{
//truncate the table.
truntble.CommandText = “DELETE FROM UploadDetails”;
truntble.ExecuteNonQuery();
//Bulk Copy to SQL Server.
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(strsqlConnectionString))
{
bulkCopy.DestinationTableName = “UploadDetails”;
bulkCopy.WriteToServer(dr);
}
//commit the transaction.
myTrans.Commit();
lblMsg.Text = “File uploaded successfully”;
}
}
catch (OleDbException ex)
{
myTrans.Rollback();
throw ex;
}
catch (InvalidOperationException ex)
{
myTrans.Rollback();
throw ex;
}
finally
{
cnntrunc.Close();
}
}
}

The above code is used to insert data from excel to sql server table.
strfilename = “~\\ExcelFile\\” + ViewState[“filename”];
The above code is used to get the filename of recently uploaded file
strexcelConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Server.MapPath(strfilename) + “; Extended Properties=\”Excel 8.0;HDR=YES;IMEX=1;\””;
strcommand = “Select [FirstName], [LastName], [Address], [Country], [City], [Zipcode] FROM [Sheet1$]”;
The above code is used to provide connection string for excel file.
strsqlConnectionString = ConfigurationManager.ConnectionStrings[“conn”].ToString();
The above is used to specify the connection string.
“DELETE FROM UploadDetails” is used for deleting data from table befor inserting new data.
“UploadDetails” specifies the table name.

The above code is used to export data.In the above code the transaction is created and the code is written to delete data from sql table and export data from excel in to the sql table.
If the transaction is successful then it will delete the existing data from table and upload the new data from excel sheet.
If the transaction is not successful then it will rollback the transaction.
The user can skip the delete table code if they wish to not to delete the data from the table.
Once the data is exported then the excel file is deleted in order to save the disk spaceThe below code is used to delete the excel file.

private void deletefiles()
{
try
{
string strdel = System.Web.Configuration.WebConfigurationManager.AppSettings[“path”] + Path.GetFileName(FileUpload1.PostedFile.FileName);
strdel = Server.MapPath(strdel);
if (File.Exists(strdel) == true)
File.Delete(strdel);
}
catch (Exception ex)
{
lblMsg.Text = “Error in deleting File.The following Error occured:- “ + ex;
}
}

call the upload method on the click event of  a button as shown below.
protected void Button1_Click(object sender, EventArgs e)
{
uploaddata();
}

You can download the sample file from the following link.

Cropping/resizing image online

INTRODUCTION
We have come across many sites that upload the images and allow us to do cropping of images online. In this article I will show you, how to crop images online according to the requirement.

EXAMPLE

In this example I have made use of library file which has been provided by http://www.codeplex.com for cropping images. This example has been developed using this library file and jQuery.The library file can be accessed through the following link http://webcropimage.codeplex.com/.

Here I will demonstrate here a small example of cropping image using this library file.

In this example I will make use of file upload control to upload the image file and then crop the image using this library file.

The page will look somewhat like this.

mainpage

First include the library (CS.WebControls.WebCropImage.dll) in to the project and add a reference to it.Add the library file to the toolbox.

Add the file upload control, two buttons, image control and webcropimage control in to the page.

Add the following property to the webcropimage control as shown below.

1

Add the following method to the .aspx.cs file.

2

The above method will check for the file type while uploading images files.

3

The above method will check for the file type and then upload a valid image file and show it in an image control.

4

The above code will crop the image and save it to a destination folder.

All the functionality is carried out by the library file, except some additional functionality which you will be requiring to upload image file.

You just need to set the required property of webcropimage control and the rest of the thing will be carried out by just adding few lines of code.

The demo project can be downloaded by accessing the following link

Display images in a thumbnail view

INTRODUCTION
Sometimes it might so happened that developers want to upload photos and display it in a web form in a thumbnail view.

SOLUTION
I will demonstrate here a small example of uploading photos through file upload control and displaying it in a datalist control without use of database.

To start with create a small demo project .Add one image folder to it where the photos will get uploaded.

The demo project will look something like this.

1

First add one web form page to the solution and add one file upload control and datalist control as shown above.

The following is your HTML page.

2

Secondly, add the following method to the aspx.cs file.

3

The above method is used to check the file type of the images while uploading. The images with the following displayed extension will be allowed to get uploaded.

4

The following code on the click event of a button is used to upload files to the respective folder. In this example the images are uploaded and saved in the images folder.

5

As soon as the images is uploaded it is displayed on the webform page in a form of a thumbnail view.

In the above code the datalist control is map with the images folder where the images are uploaded.

Then the datalist control is bind to the directory(folder) where it is saved.

So as soon as the images are uploded it will start displaying in datalist control in form of a thumbnail.

You can download the demo project from the following link