My ASP.NET Tutorial

First thing is What Is an Application Design?

An application design is a written model of a system that
can be used as a guide when you actually construct a working version of the
system. The components of an application design can vary, but the complete
design typically includes the following:
 A statement of the purpose and scope of the system: This statement
of purpose and scope is often written in the form of a use case, which
describes the actors and actions (users and uses) that make up the
system and shows what it’s for. Sometimes the use case is a graphic
diagram; most often it’s plain text.
 A data model: Normally this is an outline of the database structure, consisting
of a set of Entity-Relationship Diagrams (ERDs) or other diagrams.
These describe the details of how the application’s database will be put
together. Each application in this book uses a database and includes an
ERD, which describes how the database tables relate to each other.
 Data Flow Diagrams (DFDs): Some application designs include these diagrams,
which show the major processes that make up the application
and how data flows among the processes. The data flow is pretty
straightforward for most of the applications presented in this book, so I
don’t include Data Flow Diagrams for them.
 User Interface Flow Diagrams: These are sometimes called storyboards
and are often used to plan the application’s user interface. I include a
User Interface Flow Diagram for each application in this book so you can
see how the application flows from one page to the next.

The life cycle of an
application-development project typically goes something like this:

1. Feasibility study: This is the conception phase, in which the decision to
undertake a new computer system is made based on the answers to
questions such as:
• What business problem will the new system solve?
• Will the new system actually be an improvement over the current
system?
• If so, can the value of this improvement be quantified?
• Is the new system possible?
• What will the new system cost to develop and run?
• How long will the system take to develop?
The result of the feasibility study is a charter for the new project that
defines the scope of the project, user requirements, budget constraints,
and so on.
2. Analysis: This is the process of deciding exactly what a computer
system is to do. The traditional approach to analysis is to thoroughly
document the existing system that the new system is intended to
replace, even if the existing system is entirely manual and rife with inefficiency
and error. Then, a specification for a new system to replace the
old system is created. This specification defines exactly what the new
system will do, but not necessarily how it will do it.
3. Design: This process creates a plan for implementing the specification
for a new system that results from the analysis step. It focuses on how
the new system will work.
4. Implementation: Here’s where the programs that make up the new system
are coded and tested, the hardware required to support the system is purchased
and installed, and the databases required for the system are
defined and loaded.
5. Acceptance testing: In this phase, all pieces of the system are checked
out to make sure that the system works the way it should.
10 Part I: Introducing ASP.NET 2.0 Application Development
6. Production: This is another word for “put into action.” If the system
works acceptably, it’s put into production: Its users actually begin using it.
7. Maintenance: The moment the computer system goes into production, it
needs maintenance. In this dreaded phase, errors — hopefully minor —
that weren’t caught during the implementation and acceptance phases are
corrected. As the users work with the system, they invariably realize that
what they really need isn’t what they said they wanted, so they request
enhancements — which are gradually incorporated into the system.
The biggest challenge of this phase is making sure that corrections and
enhancements don’t create more problems than they solve.
8. Obsolescence: Eventually, the new system becomes obsolete. Of course,
this doesn’t mean the system dies; it probably remains in use for years,
perhaps even decades, after it becomes “obsolete.” Many obsolete
COBOL systems are still in production today, and Web applications being
built today will be in production long after ASP.NET becomes passe.

ASP.NET is the powerful technology for Web developers from the Microsoft .It is not simply the next-generation of ASP; in fact, it is a completely re-produced and enhanced technology that offers much, much more than traditional ASP and can increase productivity significantly. ASP.NET comes with .NET framework, some items look very familiar, and they remind us of ASP. But concepts like Web Forms, Web Services, or Server Controls gives ASP.NET the power to build real Web applications. Like ASP, ASP.NET is a server-side technology.

WHY ASP.NET came in market..?

Drawbacks of ASP

There are many problems with ASP if you think of needs for Today’s powerful Web applications.

  1. Interpreted and Loosely-Typed Code
    ASP scripting code is usually written in languages such as JScript or VBScript. The script-execution engine that Active Server Pages relies on interprets code line by line, every time the page is called. In addition, although variables are supported, they are all loosely typed as variants and bound to particular types only when the code is run. Both these factors impede performance, and late binding of types makes it harder to catch errors when you are writing code.
  2. Mixes HTML and scripting code
    ASP files frequently combine script code with HTML. This results in ASP scripts that are lengthy, difficult to read, and switch frequently between code and HTML. The interspersion of HTML with ASP code is particularly problematic for larger web applications, where content must be kept separate from business logic.
  3. Limited Development and Debugging Tools
    Microsoft Visual InterDev, Macromedia Visual Untraded, and other tools have attempted to increase the productivity of ASP programmers by providing graphical development environments. However, these tools never achieved the ease of use or the level of acceptance achieved by Microsoft Windows application development tools, such as Visual Basic or Microsoft Access. ASP developers still rely heavily or exclusively on Notepad.

Debugging is an unavoidable part of any software development process, and the debugging tools for ASP have been minimal. Most ASP programmers resort to embedding temporary Response. Write statements in their code to trace the progress of its execution.

  • No real state management
    Session state is only maintained if the client browser supports cookies. Session state information can only be held by using the ASP Session object. And you have to implement additional code if you, for example, want to identify a user.
  • Update files only when server is down
    If your Web application makes use of components, copying new files to your application should only be done when the Web server is stopped. Otherwise it is like pulling the rug from under your application’s feet, because the components may be in use (and locked) and must be registered.
  • Vague Configuration Settings
    The configuration information for an ASP web application (such as session state and server timeouts) is stored in the IIS metabase. Because the metabase is stored in a proprietary format, it can only be modified on the server machine with utilities such as the Internet Service Manager. With limited support for programmatically manipulating or extracting these settings, it is often an arduous task to port an ASP application from one server to another.

 ASP.NET Technology

ASP.NET was developed in direct response to the problems that developers had with classic ASP. Also .NET Framework can adopt all ASP Scripts without any enhancement on machine.

Features in ASP.NET

  1. Separation of Code from HTML
    With ASP.NET you have the ability to completely separate layout and business logic. This makes it much easier for teams of programmers and designers to collaborate efficiently. This makes it much easier for teams of programmers and designers to collaborate efficiently.
  2. Support for compiled languages
    Developer can use VB.NET and access features such as strong typing and object-oriented programming. Using compiled languages also means that ASP.NET pages do not suffer the performance penalties associated with interpreted code. ASP.NET pages are precompiled to byte-code and Just In Time (JIT) compiled when first requested. Subsequent requests are directed to the fully compiled code, which is cached until the source changes.
  3. Use services provided by the .NET Framework
    The .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services, data access, or even debugging. We will go into more detail on some of them in this module.
  4. Rich Graphical Development Environment
    Visual Studio .NET provides a very rich development environment for Web
    developers. You can drag and drop controls and set properties the way you do in Visual Basic 6. And you have full IntelliSense support, not only for your code, but also for HTML and XML.
  5. State Management
    To refer to the problems mentioned before, ASP.NET provides solutions for session and application state management. State information can, for example, be kept in memory or stored in a database. It can be shared across Web farms, and state information can be recovered, even if the server fails or the connection breaks down.
  6. Update files while the server is running!
    Components of your application can be updated while the server is online and clients are connected. The Framework will use the new files as soon as they are copied to the application. Removed or old files that are still in use are kept in memory until the clients have finished.
  7. XML-Based Configuration Files
               Configuration settings in ASP.NET are stored in XML files that you can easily read and edit. You can                                  also easily copy these to another server, along with the other files that comprise your application.

 8.Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls.

 9. Web Forms are designed to make building web-based applications as easy as building Visual Basic applications.

ASP.Net life cycle specifies, how:

  • ASP.Net processes pages to produce dynamic output
  • The application and its pages are instantiated and processed
  • ASP.Net compiles the pages dynamically

The ASP.Net life cycle could be divided into two groups:

  1. Application Life Cycle
  2. Page Life Cycle

ASP.Net Application Life Cycle:

The application life cycle has the following stages:

  • User makes a request for accessing application resource, a page. Browser sends this request to the web server.
  • A unified pipeline receives the first request and the following events take place:
    • An object of the ApplicationManager class is created.
    • An object of the HostingEnvironment class is created to provide information regarding the resources.
    • Top level items in the application are compiled.
  • Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.
  • An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= “true” to the Page directive. We will cover page directives and tracing under ‘directives’ and ‘error handling’.

The page life cycle phases are:

  • Initialization
  • Instantiation of the controls on the page
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page rendering

Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.Net page:

  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page’s Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.

Following are the page life cycle events:

  • PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  • InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  • LoadViewState . LoadViewState event allows loading view state information into the controls.
  • LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.
  • PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  • Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  • LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
  • PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  • PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  • SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  • UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

 

Requirements

• Windows XP Professional with Service Pack 2/Windows Vista
• Internet Explorer 6 or later/Any Web Browser
• Visual Studio 2005/2008 Professional
• SQL Server 2005/2008 Developer Edition
• IIS (Internet Information Service) version 5.0 or later

Here we have set up the example with Visual Studio 2008 and SQL Server 2005 environment. But you can also proceed with VS 2005 version.

Installation

Both Visual Studio and SQL Server are not free. You need to purchase it from Microsoft but you can download the trial versions of both of these software from Microsoft. Here are the links:

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b (Visual Studio 2008 Professional Edition Trial Version)
http://www.microsoft.com/sqlserver/2005/en/us/trial-software.aspx (Download the developer version of SQL Server 2005)

If you are working in Windows XP then you need to install IIS in your machine. Go to ‘Start->Settings->Control Panel’. Click On ‘Add/Remove Programs’ and then select ‘Add/Remove Windows Components’. Now from the Windows Component Wizard select Internet Information Services and click ‘next’ to proceed. You need to insert Windows XP Professional CD to complete the set up.
IIS 7.0 is included with Windows Vista.

Creating the Web Application

Once you launch the VS 2008 you will be presented with a window similar to the screen shot below:

Figure-1: Start Page of VS 2008

Figure-1: Start Page of VS 2008

The Start Page is the first page you see whenever you launch Visual Studio 2008 and this page guides you as you start projects, as well as search for help or resources. From the screen shot you can see the Recent Projects box at the left side of the page. This box contains the latest projects on which we have worked. From this box you can also create a new project or open an existing project that is not listed. The Getting Started box allows you to create new projects from existing code , create new web sites, pull up the MSDN help application. If you close the Start page from Document Window you can reactivate the Start Page by selecting View->Other Windows->Start Page option.

Now close the Start Page and from the Visual Studio Menu go to File->New->Web Site like Figure-2(below)

Figure-2: Create New Web site from the Menu

Figure-2: Create New Web site from the Menu

Now you will see another window appears to select the template. Select the ASP.Net Web Site template and name it as “TutorialExample” like the screenshot below. Set the Language at the right side as Visual C# (it is the language that will be used at the code behind page which will be discussed later). You may also set it as Visual Basic but here we have used C# to show the example.

Figure-3: Create the “TutorialExample” web site

Now the Default.aspx page will be opened like the screenshot below. The Solution Explorer (at the right side) which provides an organized view of the project contains one folder (App_Data) and two files.

Figure-4: Default page and the Solution Explorer

Figure-4: Default page and the Solution Explorer

The App_Data folder is the default directory for database but here we will not use this folder as we will use separate SQL Server database. Application and directory level settings are stored in Web.Config file. Each Web Application has at least one Web.config file.
Now select the Default.aspx file in the Solution explorer and press F2 to rename it as Login.aspx (Screen shot below).

Figure-5: Rename Default.aspx as Login.aspx

The document window is where you create the ASP.NET pages. This section of the IDE enables you to create ASP.NET pages either by dragging and dropping elements onto a design surface or by directly coding them. Visual Studio 2008 offers three views of a page: Design, Split and Source view but Visual Studio 2005 offers only two views: Design and Source. Figure-6 shows the document window in VS 2008 with Split View.

Figure-6: Split View of Login.aspx page in the document window

Figure-6: Split View of Login.aspx page in the document window

Now we will add server controls in our Login page. But before doing that we will briefly discuss what is a server control. ASP.NET server controls are components that run on the server and encapsulate UI and other related functionality . Server controls include Buttons, Text Boxes, Drop Down Lists etc. The following is an example of Button server control:

Server controls have a runat=”server” attribute. This means that the logic in the control runs on the server and not on the user’s browser. Server controls are different from HTML controls in that they run only on the client’s browser and have no action on the server. Another feature of server controls is that the view state, the settings and the user input of the control are automatically saved when the page is sent back and forth between the client and the server. Traditional HTML controls are stateless and revert to their default setting when the page is returned from the server to client.

Now let’s add web server controls within a table in our Login page. Place the following code in the source view to create a table first. Please look at Figure-7 to add a table.

Figure-7: Add a 3x3 table in the Login Page

Figure-7: Add a 3×3 table in the Login Page

Now if you go to the Design view you will find a table like Figure-8.

Figure-8: Table in the Design view

Figure-8: Table in the Design view

You can also change the style of this table (like set border, change border color ,width etc.) from the Design view. As an example we will just set a border for this table. Select the table in the design view and press ‘F4’. It will open the Properties Window which controls the properties of any item that is a part of your application. Now change the border type as shown in Figure-9:

Figure-9: Change the Border type of the table

Figure-9: Change the Border type of the table

You may also change the other properties from this window as experiment.

Now we will add controls within this table. At the right bottom of the page you can find an icon called ‘ToolBox’ which basically allows you to use a drag and drop operation on the controls in this application. When you click on it , you can find the available tools grouped by category. Please have a look on Figure-10 for details.

Figure-10: Tools grouped by Category in the Toolbox

Figure-10: Tools grouped by Category in the Toolbox

Now expand the standard category which consists of Web Server Controls and drag a ‘TextBox’ control from it and drop it in the second column of the first row like Figure-11.

Figure-11: A TextBox is added in the second column of first row

Figure-11: A TextBox is added in the second column of first row

Now add another TextBox in the column below and a Button at the last like Figure-12.

Figure-12: Text Box and Button Controls are added

Figure-12: Text Box and Button Controls are added

Then write ‘Name’ and ‘Password’ like Figure-13: in the Table

Figure-13: Name and Password added

Figure-13: Name and Password added

Now Select the button control and press F4 to view the properties window. In properties change the ‘Text’ property from ‘Button’ to ‘Submit’ (shown in Figure-14)

Figure-14: Change the Text property of the Button control

Figure-14: Change the Text property of the Button control

After changing this property the design view of Login page will be like Figure-15

Figure-15: ‘Submit’ button  Added

Figure-15: ‘Submit’ button Added

At last we will add validation controls for two text boxes. The ASP.Net page framework includes different types of validation controls . Here we are adding small description of different types of validation controls:

•CompareValidator: Compares an input control to another input control
•CustomValidator: Allows you to write your own code to create the validation expression.
•RangeValidator: This can verify that the user input is between two values.
•RegularExpressionValidator: Verifies that the entry matches a pattern that has been specified by a regular expression.
•RequiredFieldValidator: Checks whether a value has been entered into a control or not.
•ValidationSummary: Displays a summary of all of the validation errors for all of the validation controls on the page.

In our application user need to provide both ‘Name’ and ‘Password’ and these are required fields. So we will add two RequiredFieldValidator for the two TextBoxes. Now drag two ‘RequiredFieldValidator’ from the ‘Validation’ category of ToolBox and place them at the last column of the first two rows of the table.
Here is the screenshot:

Figure-16: Two RequiredFieldValidators are added

Figure-16: Two RequiredFieldValidators are added

Now select the two RequiredFieldValidators one by one and set the ‘ControlToValidate’ property as ‘TextBox1’ and ‘TextBox2’ respectively . Set the ‘ErrorMessage’ property of both of them as ‘Required’. Please look at the screenshot below for details:

Figure-17: Change the properties of the RequiredFieldValidator1 (same for the second)

Figure-17: Change the properties of the RequiredFieldValidator1 (same for the second)

As a result of this if an user press the ‘Submit’ button keeping the TextBox1 or TextBox2 blank, then he/she will get a ‘Required’ message beside the appropriate TextBox .

At last we will add a asp:label control below the table. If a user enters a wrong ‘Name’ or ‘Password’ then this control will show the proper error message. From the properties window set the ‘ForeColor’
‘Red’ and leave ‘Text’ blank as shown in Figure-18.

Figure-18: Change the ‘ForeColor’ and ‘Text’ properties of ’ Label1’

Figure-18: Change the ‘ForeColor’ and ‘Text’ properties of ’ Label1’

So our Login.aspx page is ready. Now we will add another web page called ‘Welcome.aspx’ into our project. This page will contain just one one ‘label’ control which will show a welcome message after successful login.

To add another web page in our project just right click on the project in the Solution Explorer and select ‘Add New Item’ (Shown in Figure-19)

Figure-19: Select ‘Add New Item’ to add another page

Figure-19: Select ‘Add New Item’ to add another page

From the appeared templates select ‘Web Form’ and Name it as ‘Welcome.aspx’ (screenshot below)

Figure-20: Add ‘Welcome.aspx’ page in the project

Figure-20: Add ‘Welcome.aspx’ page in the project

Now in the design view drag and drop a ‘Label’ control from the toolbox and change the properties like the attached snapshot.

Figure-21: Add welcome label in ‘Welcome.aspx’ page

Figure-21: Add welcome label in ‘Welcome.aspx’ page

Now designs of both the pages are ready now and it is the end for Part-I. We will create the required table in SQL Server and show how to connect the web application with the database in Part-II.

Advertisements

One thought on “My ASP.NET Tutorial

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s