Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

September 2010 - Posts

Using profile in ASP.Net applications

We all want when we visit a website to have some unique treatment (personalisation). Developers on the other side must devise mechanisms to remember our personal settings and preferences. This makes it more likely for us to return. ASP.Net developers must track users and save somehow their preferences between visits.

There are many ways to do that. Some are easy and some more complex. A lot of people seem not to know the profile feature that is in our disposal from ASP.NET 2.0.

With Profile we store user specific data that is accessible anywhere in our ASP.Net application.

We define properties using the web.config file. We use standard XML code to do that. ASP.NET reads the schema defined in web.config and automatically generates a class that is accessible from the Profile property on a page.

I am going to show you a small example of the Profile property.

I will be using VS 2010 Ultimate edition and C# to create a simple asp.net application.

1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.

2) Create a web site with an appropriate name.

3) In the default.aspx  add four TextBox controls and a button. Leave the default names.The markup should look like this

Name: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
Age:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
Url:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
Comments: <asp:TextBox ID="TextBox4" runat="server" TextMode=MultiLine>
</asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Save to Profile" 
        onclick="Button1_Click" />

 

4) Inside the web.config, in the <system.web> section add these lines of code

 <profile>
        <properties>
          <add name="Name"/>
          <add name="Age"/>
          <add name="Url"/>
          <add name="Comments"/>
        </properties>
      </profile>

 

5) In the Button1_Click event handling routine type

 Profile.Name = TextBox1.Text;
 Profile.Age = TextBox2.Text;
 Profile.Url = TextBox3.Text;
 Profile.Comments = TextBox4.Text;
 

6) Run your application and fill in the textbox values that will eventually be stored in the Profile.

7) Add another page in your site. Leave the default name. Add 4 Labels in the new page. The markup should look like this

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br />
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label><br />

 

8) In the Page_Load event handling routine, type

 Label1.Text = Profile.Name ;
 Label2.Text=Profile.Age ;
 Label3.Text=Profile.Url;
 Label4.Text=Profile.Comments;

 9) Run your application( Set the Default.aspx as the start page ). Fill in the texboxes and click the button. Close the web browser.

10) Run the default2.aspx page. You will see the values from the Profile object appearing in the label controls.

You can use the Profile object to hard code values in the web.config that are important to your site. Do not forget that you can encrypt your site.

Imagine if you have a website and it has 100 pages. If the admin's email changes then you need to update all 100 pages with the new admin's email. I have seen that happening in one web site where

  • It did not use a master page.

  • The admin's email was not retrieved from the database.

Email me if you need the source code.

Hope it helps!!!

Posted: Sep 23 2010, 10:12 PM by nikolaosk | with 8 comment(s) |
Filed under: , ,
How to populate web server controls in ASP.Net applications from a web service

In this post I would like to present you with a very simple example on how to create a simple web service that access data from a database.

Then we will create a consuming application that will consume the web service. I will use VS 2010 Ultimate edition and C# as the development language.

I know that web services are explained in many places over the web but I will have a go.

They are small units of code that handle specific tasks (they convert kilometers to miles ) and are based on XML communication protocols.

They are great because they are independent of operating systems,languages,systems and devices.

Before you read on, I assume that you understand terms like SOAP, WSDL and XML .

1) Use VS 2010/2008/2005. Express editions will suffice. I am going to use the Pubs database. You can download the installation scripts of the Pubs database from here.

I am going to retrieve all the data from the Authors table.

2) Create a new project and choose asp.net web service application. You have this option from the available templates when you click File->New Project.

3) Add these namespaces at the top of the Service.cs

using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
 

Also note that our web service class inherits from WebService base class and not from the Page class

public class Service : System.Web.Services.WebService

4) In the web.config file in the <connectionStrings> add

  <connectionStrings>
    <add name="pubs" connectionString="Data Source=.;
Initial Catalog=pubs;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

 

5) Delete the Helloworld method. Under the [WebMethod]

 public DataSet GetAuthors()
    {
        SqlConnection conn = new SqlConnection
(WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString);
        SqlDataAdapter myAdapter;
        DataSet productDataSet;
        string commandString = "Select * from Authors";
        myAdapter = new SqlDataAdapter(commandString, conn);
        productDataSet = new DataSet();
        myAdapter.Fill(productDataSet);
        return productDataSet;


    }

I just get the connection string from the web.config using the WebConfigurationManager class and create a new connection object. I store my SQL Query in a string and then use the connection object and the string that stores the SQL query as paramaters when creating an Adapter object.Then I create a dataset and fill this dataset using the adapter object.

6) Build and run your application. You will see the service running and Invoke the GetAuthors method. Make sure it works.

7) Add a new item to your project, a web form.Leave the default name.

8) Add a Gridview web server control in the default.aspx page. Now we need to add a reference to the web service.Add Web Reference-> Select Web services in this solution and type in the web reference the name, AuthService

9) In the Page_Load event handling routine, type

 AuthorService.Service auth = new AuthorService.Service();
 GridView1.DataSource = auth.GetAuthors();
 GridView1.DataBind();

We just create an object of the AuthorService.Service class (auth) and then it is very easy(we call the GetAuthors() method) to bind the results to the GridView.

10) Run your application and see the author data populating the GridView control.

Email me if you want the source code.

Hope it helps!!!!

Reading data from Office applications in ASP.Net

In this post I will show you with a hands-on example on how to accompish a common task. We will use an asp.net application to read data from an excel file. I have excel 2007 installed and I have several .xlsx files with data.

A lot of people believe that most of the data nowdays are stored in databases. You cannot imagine how much data is saved in excel files.

We will connect to the excel file with the appropriate provider. 

I will be using VS 2010 Ultimate edition and VB.Net to create a simple asp.net application.

1) Launch Visual Studio 2010/2008.Express edition will suffice.

2) Create a web site with an appropriate name. Use VB.Net as the development language.

3) Create an excel file ( I assume you have excel 2007 or 2003 ) and give it an appropriate name. Insert some data in it.

4) Open your web.config file and type in the  <connectionStrings> section and type

 

<connectionStrings>		
<add name="excel2003" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Users\fofo\Desktop\test.xls;Extended Properties=Excel 8.0"/>
<add name="excel2007" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\fofo\Desktop\test.xlsx;Extended Properties=Excel 12.0"/>	
</connectionStrings>

5) As you can see we have information in our <connectionStrings> section that will help us read from an .xls or .xlsx file.I have a file that is called test.xls and another one called test.xlsx

6) Add a GridView web server control in the default.aspx page and a button. Name them as you like.

7) Click the button and in the event handling routine type

 Dim myconstring As String = _
 ConfigurationManager.ConnectionStrings("excel2003").ConnectionString
      
 Dim oledbConnection As OleDbConnection = New OleDbConnection(myconstring)


 Try
 
 oledbConnection.Open()

           
 Dim mycommand As OleDbCommand _
New OleDbCommand("SELECT * FROM [Sheet1$]", oledbConnection)

           
 Dim oledadapter As OleDbDataAdapter = New OleDbDataAdapter()

 oledadapter.SelectCommand = mycommand

 Dim ds As DataSet = New DataSet()

          
 oledadapter.Fill(ds, "Marks")

         
 GridView1.DataSource = ds.Tables(0).DefaultView
 GridView1.DataBind()
 Catch ex As Exception

 Label1.Text = ex.Message()

 Finally
 
 oledbConnection.Close()
 End Try

 

 8) I will try to explain what I am doing in the code.

  • I find the connection string using the ConfigurationManager class
  • I create the connection object

  • I put my main bit of code in a Try Catch statement

  • I open the connection
  • I create a command object and select the data
  • I create an adapter object and then I create a dataset
  • I fill in the Dataset and bind the data to the GridView
  • Then I close the connection


9) Run your application and see the data from the excel file appearing in the GridView control. If you have Excel 2007 installed just change this line of code.

 Dim myconstring As String = _
 ConfigurationManager.ConnectionStrings("excel2007").ConnectionString

 

Email me if you need the code.

Hope it helps!!!!!

Posted: Sep 23 2010, 07:58 PM by nikolaosk | with 2 comment(s) |
Filed under: , ,
How to obtain browser information from an asp.net application

In this post I am going to explain how to get information about the user's browser. This is the browser that the user uses to access the web application.

You can accomplish what i am going to show you with javascript. But I approached it differently and i will show you how to do that with .Net code.

I will be using VS 2010 Ultimate edition and VB.Net to create a simple asp.net application.


1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.

2) Create a web site with an appropriate name. Use VB.Net as the development language.

3) In the Page_Load event handling routine type

Dim myusersbrowser As HttpBrowserCapabilities = Request.Browser

 Response.Write("general browser family" + " : " + _
                       myusersbrowser.Browser)
        Response.Write("</br>")
        Response.Write("browser type" + " : " + myusersbrowser.Type)
        Response.Write("</br>")
        Response.Write("supports javascript" + " : " + _
                       myusersbrowser.EcmaScriptVersion.ToString())
        Response.Write("</br>")
        Response.Write("javascript version" + " : " + _
                       myusersbrowser.JScriptVersion.ToString())
        Response.Write("</br>")
        Response.Write("does the browser support cookies?" + " : " + _
                       myusersbrowser.Cookies.ToString())
        Response.Write("</br>")
        Response.Write("search engine web crawler?" + " : " + _
                       myusersbrowser.Crawler.ToString())
        Response.Write("</br>")
        Response.Write("is this a mobile browser?" + " : " + _
                       myusersbrowser.IsMobileDevice.ToString())
        Response.Write("</br>")
        Response.Write("Active X controls enabled?" + " : " + _
                       myusersbrowser.ActiveXControls.ToString())
        Response.Write("</br>")
        Response.Write("Platform" + " : " + myusersbrowser.Platform)

I will try to explain what happens here. It is really simple.

We first have to create an instance(object) of the HttpBrowserCapabilities class. This class lives in the System.Web namespace.

In order to get an instance of this class we need to get hold of the Browser property of the Request object.

Dim myusersbrowser As HttpBrowserCapabilities = Request.Browser

then I use Response object and the Write method to write the information to the page using the various properties of the browser object I just created.

Response.Write(“browser type” + ” : ” + myusersbrowser.Type)


The line above gives us the Browser type, in my case IE8.

4) Run the web application and you will see all the information. In my case it is

general browser family : IE
browser type : IE8
supports javascript : 1.2
javascript version : 5.6
does the browser support cookies? : True
search engine web crawler? : False
is this a mobile browser? : False
Active X controls enabled? : True
Platform : WinNT


Please note that you can experiment with dozens of other properties of the  browser object.

This information can become very handy if ,for example, we have an Ajax enabled website but we still care for those people who have Javascript disabled.

We can use portion of the code above to redirect our users accordingly. Those who have Javascript disabled they are redirected to our simple non-Ajax website.

Hope it helps!!!

Posted: Sep 23 2010, 07:13 PM by nikolaosk | with 3 comment(s) |
Filed under: , ,
Linq to XML & ASP.Net - part 8

This is the eighth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here . You can read the fourth post here . You can find the fifth post here . You can find the sixth post here . You can find the seventh post here.

In this post I would like to show on how to use conditions to find a specific element using Linq to XML.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

Add the existing students.xml file in your website. You can find this file in the first post. 

We try to find the number of female students.

3) In the Page_Load  event handling routine of the default.aspx.cs file, type the following

 

 XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");

        var femaleCnt = from sex in xelement.Elements("Student")
                    where (string)sex.Element("Sex") == "Female"
                    select sex;
        Response.Write(femaleCnt.Count());

 

4) Run your application and see in the browser the number of female students.

Email me if you need the source code.

Hope it helps!!!

Posted: Sep 23 2010, 04:27 PM by nikolaosk | with 4 comment(s) |
Filed under: , ,
Linq to XML & ASP.Net - part 7

This is the seventh post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here . You can read the fourth post here . You can find the fifth post here . You can find the sixth post here .

In this post I would like to show on how to add new elements at runtime using Linq to XML.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

 

Add the existing students.xml file in your website. You can find this file in the first post.

3) In the Page_Load  event handling routine of the default.aspx.cs file, type the following

 XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");

     xelement.Add(new XElement("Student",
     new XElement("StudenId", 5),
     new XElement("Name""Emily"),
     new XElement("Sex""Female"),
     new XElement("Seminar","ASP.NET"new XAttribute("Type","E-Learning")),
     new XElement("Seminar","WPF"new XAttribute("Type","Blended Learning"))
        
     ));

        Response.Write(xelement);

 

4) You can add a new Element to an XML document at runtime by using the Add() method of XElement.

The new element gets added as the last element of the XML document.If you want to add the Element as the First Child, use the AddFirst() method.

5) Run your application and see in the browser the new item added.

Email me if you need the source code.

Hope it helps!!!

Posted: Sep 23 2010, 03:55 PM by nikolaosk | with no comments |
Filed under: , ,
Session State in ASP.Net

In this post I will talk about ASP.Net State management. I will provide a hands on example with VS and VB.Net.

Before I go on with my example I would like to give a short introduction first.

Web applications are built on Hypertext Transfer Protocol (HTTP).  HTTP is a stateless protocol and each request to the server from the client is understood as an independent request.

ASP.NET provides a powerful way to store a user’s session specific data using the Session State which is accessible as long as the user’s session is alive. 

At some point we might need to access complex information such as custom objects.Obviously we can’t persist them to cookies.In our application we could have strict security requirements that prevents us  from storing information about a client in view state or in a custom cookie. In cases like that, we must use the built-in session state facility.We can store any type of data in memory on the server. The information is protected, because it is never transmitted to the client, and it’s uniquely bound to a specific session. Every client that accesses
the application has a different session and a distinct collection of information. We could store in session state things such as the items in the current user’s shopping basket when the
user browses from one page to another.

One might ask, "What is the mechanism for session tracking?"

 
ASP.NET uses a unique 120-bit identifier and produces a unique value  that  evil people can’t reverse-engineer or “hack”, the session ID a given client is using. This is the only piece of session-related information that is transmitted between the web server and the client.

The client presents the session ID, then what happens is that ASP.NET looks up the corresponding session, retrieves the objects stored and places them into a special collection so they can be accessed by our code.

The client must present the appropriate session ID with each request.

We can accomplish this in two ways:

Cookies: In this case, the session ID is transmitted in a special cookie (named
ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is
used.
Using URLs: In this case, the session ID is transmitted in a specially modified URL. This allows you to create applications that use session state with clients
that don’t support cookies.


Session state can slow down our application. It solves many of the problems associated with other forms of state management but places a heavy load on the server in terms of memory.
If we have hundreds or thousands of clients access the site then the performance will be very bad.
The last thing we want is to have an application that cannot scale gracefully.


I will be using VS 2010 Ultimate edition and VB.Net to create a simple asp.net application.


We will use in our next example session state to store several Car objects.

1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.

2) Create a web site with an appropriate name.

3) Add a class file in your site and name it Car.vb. The code should be like this

 

Public Class Car
    Public Name As String
    Public Colour As String
    Public Cost As Double
    Public Sub New(ByVal name As String, _
    ByVal colour As StringByVal cost As Double)
        Me.Name = name
        Me.Colour = Colour
        Me.Cost = cost
    End Sub
End Class
 

4) Add a listbox,2 label controls and a button in the default.aspx page. Name the listbox control as lstItems, the 2 labels as lblSessionInfo and lblCarInfo. Leave the default name for the button control.

5) In the Page_Load event handling routine type

If Me.IsPostBack = False Then
           
           
            Dim car1 As New Car("BMW", _
            "Blue", 32000)
            Dim car2 As New Car("VW Polo", _
            "Black", 18667)
            Dim car3 As New Car("Audi", _
            "Red", 30345)
            Dim car4 As New Car("Citroen", _
            "Gray", 9878)
          
            Session("mycar1") = car1
            Session("mycar2") = car2
            Session("mycar3") = car3
            Session("mycar4") = car4
        
            lstItems.Items.Add(car1.Name)
            lstItems.Items.Add(car2.Name)
            lstItems.Items.Add(car3.Name)
            lstItems.Items.Add(car4.Name)
        End If
      
        lblSessionInfo.Text = "Session ID: " & Session.SessionID
        lblSessionInfo.Text &= "<br />Number of Objects: "
        lblSessionInfo.Text &= Session.Count.ToString()
        lblSessionInfo.Text &= "<br />Mode: " & Session.Mode.ToString()
        lblSessionInfo.Text &= "<br />Is Cookieless: "
        lblSessionInfo.Text &= Session.IsCookieless.ToString()
        lblSessionInfo.Text &= "<br />Is New: "
        lblSessionInfo.Text &= Session.IsNewSession.ToString()
        lblSessionInfo.Text &= "<br />Timeout (minutes): "
        lblSessionInfo.Text &= Session.Timeout.ToString()

 

The Car objects are created the first time when the page is loaded, and they’re stored in
session state. The user can then choose from a list of car names. When a selection
is made, the corresponding object will be retrieved, and its information will be displayed.The code is very simple.

6) Double click on the button and in the event handling routine type

  If lstItems.SelectedIndex = -1 Then
            lblCarInfo.Text = "No item selected."
        Else
           
            Dim Key As String
            Key = "mycar" & _
        (lstItems.SelectedIndex + 1).ToString()
           
            Dim TheCar As Car = CType(Session(Key), Car)
           
            lblCarInfo.Text = "Name: " & TheCar.Name
            lblCarInfo.Text &= "<br />Color: "
            lblCarInfo.Text &= TheCar.Colour
            lblCarInfo.Text &= "<br />Cost: " & TheCar.Cost.ToString("c")
 

We retrieve the current Car object from Session like this

 Dim TheCar As Car = CType(Session(Key), Car)

 

7) Run your application and see the names of the Car objects stored in the Session listed in the ListBox control. You will also see when the page loads useful information about the Session.

Select one car name and hit the button. You will see whole information about the specific car object stored in the session state.

Email me if you want the source code.

Hope it helps!!!

ASP.NET Page lifecycle

In this post i am going to try to give you an overview of the events that take place in asp.net lifecycle. Page Life Cycle in ASP.NET is essential knowledge for developing applications.

When a web page is sent to the Web Server for processing, it goes through a sequence of steps before it finally gets displayed in the Web Browser.

Without understanding the Page Life Cycle, developing asp.net apps will be more difficult than it should be.

In order to backup my previous statement I will present you a problem a friend of mine was facing.

I got an email the other day from a friend saying,

 "I want to change themes in an asp.net application depending on user's choice. I have set a cookie and read user's preferences. I have the code implemented but it doesn't work."

His code was more or less like this:

 
 protected void Page_Load(object sender, EventArgs e)
    {

        if (Request.Cookies["theme"] != null)
        {
            this.Theme = Request.Cookies["theme"].Value;
        }
    } 

 Of course the above code would never work. The problem lies in the Page events lifecyle.

He should handle the PreInit event. This event occurs before a page is initialized.

You can only change the theme of a page during this event. Once a page becomes initialized, its theme is set and cannot be changed.

He should not type his code in the Load event. This event occurs after a page is initialized and once a page becomes initialised, its theme is set and cannot be changed. 


There are 3 phases in page construction also known as page lifecycle. These are:

  • Initialisation
  • Event Handler Execution
  • Rendering

 

We are going to look into those 3 major phases. We must keep in mind that page lifecycle is just a part of the entire Application lifecycle.

Initialisation


In this phase the objects that represent the page controls are instantiated and set to their initial properties.

3 main events happen in this phase:

PreInit(In this event we can write code to set dynamically a theme or a master page)
Init
InitComplete

You can use the Page_Init event to create or re-create the controls that need to be created or re-created dynamically.


Event Handler Execution


Afer everything is being lodaded in its inital state, the control’s specific events fire. The order of events is this

Preload
Page_Load (We write lots of initialisation code in this event)
Controls events (Changed events, PostBackEvent and validation events are fired)
Load Complete

Page_Load

At this phase the OnLoad event method on the Page is called and then the same applies for each child control, which does the same for each of its child controls until the page and all controls are loaded.

Rendering


In this phase the control tree is translated into HTML. Keep in mind that our browser understands HTML only…. The main events in this phase are:

PreRender - Use the Pre_Render event to make any last minute changes to the contents of the web page or any of its controls.
SaveState - happens after the ViewState for the page has been created and set
Render - Each control calls its Render method and outputs HTML
Unload - After the markup is created for the whole page and sent back to the http application each object that was instantiated is unloaded and is available for garbage collection


You cannot remember all these events.But having a clue about the basic course of events helps a lot when you have debugging issues and have architectural dilemmas about your application.



Hope it helps!!!

Web server controls in ASP.Net - part 4

This is the fourth post in a series of posts regarding web server controls.

You can find the first post here , the second post here and the third post here.  In this post, I am going to look into the Wizard web server control.

This control allow us to create a mechanism when we want to collect information  over a number of steps. You can do that with multiple pages but in this case you need to manage the state and the data between the pages.

This wizard contains a number of steps that are easiy configurable.

I will be using VS 2010 Ultimate edition to create a simple asp.net application.

1) Launch Visual Studio 2010/2005/2008. Express editions will be fine.


2) Create an asp.net web site and choose an appropriate name

3) Place a wizard control from the Toolbox on the Default.aspx page. Leave the default name.Select the wizard control and click the smart tag (the arrow in the right-hand upper corner) and choose Auto format.

Choose a format of your choice from the available ones. You can always change the colors and fonts of a pre-decided format from the styles area of the properties window.

4) Run your application.

You will see that you have Previous,Next and Finish buttons.

Close the page and in your default.aspx just select the wizard control.From the properties window, find the wizardsteps, Collection.

Click on the ellipsis and you will see the WizardStep Collection Editor window popping up.

I have created a step-by step navigation scheme to create a feedback form.

In this window you can create as many steps you want and call them as you wish. Pay more attention to the StepType property.

After you finish adding steps, click the OK button.

Select the wizard control again. Click the smart tag (the arrow in the right-hand upper corner).

Select the step you want and drag and drop the controls you want onto this step. In my example I have a step called Name and i place a textbox control in this step. I follow the same pattern for all the other steps.

If you notice carefully  in the properties window you will see 2 properties CancelDestinationPageUrl, FinishDestinationPageUrl.

You can create 2 new .aspx pages and name them, Cancel.aspx and Finish.aspx.

In the Cancel.aspx write something like “you have chosen to cancel…”

In the Finish.aspx write something like “Thank you”

Then you just set the values of the above properties to the respective pages.

Now you can run your application and see all the steps(and in each step the controls you have added) you have created and click the Next and Previous,Finish,Cancel buttons on the wizard.

Hope it helps!!!

Web server controls in ASP.Net - part 3

This is the third post in a series of posts regarding web server controls.

You can find the first post here and the second post here.  In this post, I am going to look into the FileUpload web server control.

Basically with this control you try to give the user the same functionailty with a ftp client.

I will try show how to upload one file and how to upload multiple files using the FileUpload control. .

I will be using VS 2010 Ultimate edition and C# to create a simple asp.net application.


1) Launch Visual Studio 2010/2005/2008. Express editions will be fine.

2) Create a new asp.net web site and call it “uploadcontrol”.

3) Drag and drop in the default.aspx page a FileUpload control from the Toolbox

4) If you run your application now , you will see a page that does not do much, just a textbox and “Browse” button that are part of the FileUpload control

5) Stop your application and place a button in the default.aspx page

6) Add a Label control in your application. Leave the default names for all the controls on the page.

7) Create a folder in the C drive and call it “myUploads”

8) Double click on the button and in the event handling routine and type

if (FileUpload1.HasFile) {
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
else
{
Label1.Text = “You have not selected a file or the file has not been found.”;
}


First of all let’s explain the lines above.

Initially we use the HasFile Property which returns a value indicating whether the FileUploadcontrol contains a file.

9) Run your application again and try to upload a file

If that is true we append in the text property of the Label control , the following information

  •    filename
  •    file size
  •    type of the document, e.g image,word document, e.t.c


We achieve that by using the PostedFile property , which holds the file that is being uploaded.

Before going to show more things regarding the FileUpload control, I will add a Try Catch statement in the code above to provide some sort of exception handling.


if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}


Now let’s see how you can upload mutliple files from a single page.

1) Create a new .aspx page and add it to your project, by adding a new item from the Solutions window.

2) Place 3 FileUpload controls on the page. Also add a button and a label control.

3) In the event handling routine for the click event of the button, type

thefileupload(FileUpload1);
thefileupload(FileUpload2);
thefileupload(FileUpload3);


In order to upload the three files at once, I make 3 seperate calls to the method, thefileupload.

So I have created a method of my own which I call thefileupload. This is the code for the method


private void thefileupload(FileUpload upload)
{
if (upload.HasFile)
try
{
upload.SaveAs(“C:\\myUploads\\” + upload.FileName);
}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}
}

Now, some very important notes for you to keep in mind. If you want the file upload functionality to work make sure that the destination folder on the server is  writable for the account used by ASP.NET.

If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder’s properties.

If you want to permit your users to upload large files you should overwrite in the web.config file, the default size limitation which is 4MB (4096kb)

<httpRuntime
    maxRequestLength="1048576"
  
  />

If you want the source code you can email me.

Hope it helps!!!


More Posts Next page »