C# Tutorial

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 41

Visual Studio 2005 Web Application Project

Tutorial 1: Building Your First Web Application Project

The below tutorial walks-through how to create, build and run your first web app using C# and the ASP.NET
Web Application Project support in VS 2005.

Creating a New Project

Select File->New Project within the Visual Studio 2005 IDE. This will bring up the New Project dialog. Click
on the “Visual C#” node in the tree-view on the left hand side of the dialog box and choose the "ASP.NET
Web Application" icon:

Choose where you want the project to be created on disk (note that there is no longer a requirement for web
projects to be created underneath the inetpub\wwwroot directory -- so you can store the project anywhere on
your filesystem). Then name it and hit ok.

Visual Studio will then create and open a new web project within the solution explorer. By default it will have
a single page (Default.aspx), an AssemblyInfo.cs file, as well as a web.config file. All project file-meta-data is
stored within a MSBuild based project file.
Opening and Editing the Page

Double click on the Default.aspx page in the solution explorer to open and edit the page. You can do this using
either the HTML source editor or the design-view. Add a "Hello world" header to the page, along with a
calendar server control and a label control (we'll use these in a later tutorial):

Build and Run the Project


Hit F5 to build and run the project in debug mode. By default, ASP.NET Web Application projects are
configured to use the built-in VS web-server (aka Cassini) when run. The default project templates will run on
a random port as a root site (for example: http://localhost:12345/):

You can end the debug session by closing the browser window, or by choosing the Debug->Stop Debugging
(Shift-F5) menu item.

Looking under the covers

When you compile/build ASP.NET Web Application projects, all code-behind code, embedded resources, and
standalone class files are compiled into a single assembly that is built in the \bin sub-directory underneath the
project root (note: you can optionally change the location if you want to - for example, to build it into a parent
application directory).

If you choose the "Show All Files" button in the solution explorer, you can see what the result of our
compilation output looks like:

This works exactly the same as with Visual Studio 2003 ASP.NET Web Application Projects

Customizing Project Properties


ASP.NET Web Application Projects share the same configuration settings and behaviors as standard VS 2005
class library projects. You access these configuration settings by right-clicking on the project node within the
Solution Explorer in VS 2005 and selecting the "Properties" context-menu item. This will then bring up the
project properties configuration editor. You can use this to change the name of the generated assembly, the
build compilation settings of the project, its references, its resource string values, code-signing settings, etc:

ASP.NET Web Application Projects also add a new tab called "Web" to the project properties list. Developers
use this tab to configure how a web project is run and debugged. By default, ASP.NET Web Application
Projects are configured to launch and run using the built-in VS Web Server (aka Cassini) on a random HTTP
port on the machine.

This port number can be changed if this port is already in use, or if you want to specifically test and run using
a different number:
Alternatively, Visual Studio can connect and debug IIS when running the web application. To use IIS instead,
select the "Use IIS Web Server" option and enter the url of the application to launch, connect-to, and use when
F5 or Control-F5 is selected:
Then configure the url to this application in the above property page for the web project. When you hit F5 in
the project, Visual Studio will then launch a browser to that web application and automatically attach a
debugger to the web-server process to enable you to debug it.

Note that ASP.NET Web Application Projects can also create the IIS vroot and configure the application for
you. To do this click the "Create Virtual Directory" button.

Tutorial 2: Code-Behind with VS 2005 Web Application Projects

The below tutorial helps explain the code-behind model and project structure of pages built within VS 2005
Web Application Projects. Please make sure that you have already completed Tutorial 1: Building Your First
Web Application Project before reviewing this one.

Some Background on the VS 2003 Code-behind Model for ASP.NET Applications

ASP.NET Pages in a VS 2003 web project have two files associated with them -- one is a .aspx file that
contains the html and declarative server control markup, and the other is a .cs "code-behind" file that contains
the UI logic for the page:
Control markup declarations are defined within the .aspx file itself. For example:

And corresponding protected field declarations are added in the .cs code-behind class that match the name and
type of controls defined within the .aspx file. For example:

ASP.NET does the work of wiring up a reference from this code-behind field declaration to point to the
declared control in the .aspx file at runtime. Developers can then program directly against this control within
their code-behind file.

VS 2003 automatically adds/updates these protected control field declarations at the top of the code-behind
file (these are updated everytime a developer switches into WYSIWYG design-view):

VS 2003 also then maintains a hidden region block inside the code-behind of tool-generated code to register
event-handlers and keep them in sync with the design-surface:
There are two common complaints/problems with this:

1) VS 2003 is adding/deleting code in the same file where the developer is authoring their own code -- and
accidental conflicts/mistakes do end up happening (for example: some code that the developer writes can
sometimes get modified or deleted by VS). The tool-generated hidden block above is also a little "messy" for
some people's tastes.

2) The control-declarations are only updated when a developer using VS 2003 activates the WYSIWYG page
designer. If a developer is only using the source-editor to customize the page, they will not get control
updates, and will instead have to add these control declarations manually (which is a pain).

VS 2005 Code-behind Model for ASP.NET Applications

VS 2005 uses a code-behind model conceptually the same as VS 2003. Specifically, each .aspx page continues
to inherit from a code-behind class that contains protected control field references for each control in the .aspx
page:

What is different between VS 2003 and VS 2005 is that Visual Studio no longer injects its tool-specific wire-
up code in the developer's code-behind file. Instead, it takes advantage of a new language feature in C# and
VB called "partial types" (or partial classes) to split the code-behind implementation across two files. One of
these partial class files is the developer-owned code-behind file that contains developer-written event-handlers
and code for the page. The other partial class file is then a tool-generated/maintained file that contains the
protected control field declarations and the other design-time code that Visual Studio requires. The benefit of
splitting them out into two separate files at design-time is that it ensures that the code that VS creates and
maintains never interferes (or deletes) code that a developer writes. At compile-time, these files are compiled
together and generate a single code-behind class.

With the VS 2005 Web Application project model, the design-time partial class is generated and persisted on
disk by VS 2005. This new design-time partial-class file has the filename naming pattern:
PageName.aspx.designer.cs. If you expand any new page created within your VS 2005 Web Application
project, you can see this file listed under the associated Page.aspx file along with the developer-owned code-
behind file:

If you open up the code-behind file of the page (Default.aspx.cs), you'll then see the code-behind logic of the
page -- which contains all of the code and event handlers that a developer writes (and no tool-generated
"code-spit" content -- which means it stays very clean):

If you open the Default.aspx.designer.cs file, you'll then see the design-time code of the page -- which
contains the field declarations for controls within the .aspx page:
Because the MyWebProject._Default class is marked as "partial" in both of the above two files, the compiler
will merge them into a single generated class at compile-time. This means that any variable, method or field
generated in the default.aspx.designer.cs file can be used from the default.aspx.cs code-behind file (just as if it
was declared in the code-behind file itself). For example, within the Page_Load event handler we could easily
add the below code that uses the "Label1" and "Calendar1" control:

This will compile clean and run just fine -- because the "Label1" and "Calendar1" field references have been
defined within the default.aspx.designer.cs file.
When you do a build inside a VS 2005 Web Application project, all pages, user-controls, master pages (and
their associated code-behind files+design-time generated files), along with all other standalone classes within
the project are compiled into a single assembly. This is the same behavior as with VS 2003.

Tutorial 3: Building Pages with VS 2005 Web Application Projects

The below tutorial demonstrates how to build ASP.NET Pages within VS 2005 Web Application Projects.
Please make sure that you have already completed Tutorial 2: Understanding Code-Behind with VS 2005 Web
Application Projects before reviewing this one.

Coding against controls in our Default.aspx page

In the first Hello World Tutorial we edited the Default.aspx page that is added automatically when we create a
new VS 2005 Web Application project.

Specifically we added an <asp:calendar> and <asp:label> control to the page:

You can then program against these controls using your event-handlers within the code-behind file. For
example:
You can then set a breakpoint (press the F9 key on the line to set it on), and then hit F5 to compile, run and
debug the page:
Handling server events from controls in our .aspx page

To handle a server event from a control on your page, you can either manually add an event-handler to the
control yourself (by overridng the OnInit method in your code-behind class and adding the event delegate
there), or by using the WYSIWYG designer to generate an event handler.

To use the WYSIWYG designer, click on the "design" tab of the .aspx page to bring up the design-surface. If
you want to add the "default" event for the control, you can simply double-click on the control to generate an
event handler for it (this is useful for things like buttons, etc). Alternatively, you can select the control on the
design-surface and click on the "events" tab of the property-grid. This will then list the events that are
available to handle:
You can double-click on any of the events to automatically add a default named event handler. Alternatively,
you can type the name of the event handler you wish to generate.

You can then add whatever code you want within the code-behind file:

Press F5 (or Ctrl-F5) to build and run the project. Now, when a user selects a date in the calendar, the selected
date will be output using the Label control:
Tutorial 4: Data Binding against Objects

The below tutorial demonstrates how to build ASP.NET Pages that databind against Objects within VS 2005
Web Application Projects. Please make sure that you have already completed Tutorial 3: Building Pages with
VS 2005 Web Application Projects before reviewing this one.

Adding Classes to the Web Project

In this sample we'll be data-binding a GridView control on a page to a set of classes in our web application
project.

To begin, right-click on the project and select Add->Add New Item to add a new class called "Author" to the
project:
Note that classes can be added into any directory of the web project. There is no requirement that they live
under the /app_code directory.

Make the new Author class public and then add some properties and constructors to it:
Then add a new class file called "Publisher.cs" to the project and have it implement a method called
"GetAuthorsByState":
Note that the above method uses Generics (a new feature in V2.0) to return a strongly typed List collection of
type "Author".

Choose either the "Build->Build Solution" menu item or choose "Ctrl-Shift-B" to build the project. You now
have a set of classes you can use to databind against.

Building a Data-Bound ASP.NET Page

Right-click on the project and select Add->Add New Item to add a new ASP.NET Page called
"DataSample.aspx" to the project:

Switch to design-view on the newly created DataSample.aspx page, add a simple page title, a search Textbox
called "TextBox1", a button, and then drag/drop a GridView control from the "Data" section of the Toolbox:
Select "New DataSource" from the drop-downlist in the "Common Tasks" smart-tag menu. Select "Object" as
the data-source you want to bind-to. This will then bring up a wizard that lists all classes in your project:

Select the "MyWebProject.Publisher" class, and then hit next. Then choose the "GetAuthorsByState" method
as the method to bind against:
Choose to bind the "state" parameter of the "GetAuthorsByState" method to the TextBox1 on the page (note:
change the parameter source to "control" to get this listing):

When you click "finish" the GridView columns will be updated to reflect the public properties in your Author
class. Choose the "Auto format" task on the GridView control to make it look a little better:
To test the page, select the DataSample.aspx page in the solution explorer, right click, and then select the "Set
as Start Page" context menu item. Then hit F5 (or ctrl-f5) to build, run and debug. When you add "wa" as the
state parameter you'll get a list of authors:

Tutorial 5: Using Master Pages and Site Navigation

The below tutorial demonstrates how to create and use the new ASP.NET Master Pages and Site Navigation
features within VS 2005 Web Application Projects. Please make sure that you have already completed Tutorial
4: Data Binding against Objects before reviewing this one.

Add a Master Page to the Web Project

Right-click on the project and select Add->Add New Item to add a new MasterPage called "Site.Master" to
the project:
This will then create a default master page template that you can edit either in WYSIWYG design-mode or in
HTML source mode:

Modify the Site.Master content to have a logo at the top, and then use a table to (or divs with CSS) to create a
two column layout in the page. Place the <asp:contentplaceholder> control with the ID of "MainContent" in
the second column, and leave the first column for a menu we'll add later in this tutorial.
If you switch into WYSIWYG design mode the Site.Master will look like this:

Now we are ready to have pages in our site pick up and use the master-page file.

Update Default.aspx and DataSample.aspx to use the Master Page


Open the default.aspx page we built in an earlier tutorial, and switch to HTML source-view. To update it to
use the master-page go to the top <%@ Page %> directive and add a "MasterPageFile" attribute:

Note that VS 2005 will provide intellisense completion for both the attribute name, as well as provide a list of
all valid master-pages in the project that you can use. Select the new "Site.Master" file that we just created.

Then delete the static html previously on the page, and add an <asp:content> control to the page with an id of
"content1". Note that VS 2005 will provide intellisense on all of the valid contentplaceholders within the
Site.Master file that you can override:

Wrap all previous content on the page with the <asp:content> control:

Click on the "design" tab to switch into WYSIWYG mode. You'll then see the default.aspx page inside the
Master Page:
Select the Default.aspx page in the Solution Explorer and set it as the startup page (right-click and choose "Set
as Startup Page"). Then press F5 (or ctrl-F5) to run it.

Now repeat the above process for the DataSample.aspx page as well:
Add a Web.SiteMap to the Web Project

Right-click on the project and select Add->Add New Item to add a new Site Map file called "Web.SiteMap" to
the project:

Edit the new web.sitemap file to have the below three nodes within the site-map (a root node for the home
page, a sub-node for the data page we built, and another sub-node for a future page we are going to build in
the next tutorial section):
Open the Site.Master page up again and switch to design-mode. Delete the "todo: menu" comment in the left-
most column, and then drag/drop the "Treeview" control from the "navigation" section of the Toolbox in VS:

Select a New Datasource from the drop-down list above, and choose the "Site Map" datasource:

This will then data-bind the Treeview against the web.sitemap file we created above. Choose the auto-format
menu item in the "common tasks" menu and format it as "simple":
Note how the tree-view menu shows the current web.sitemap's hierarchy at design-time.

Press the F5 or Ctrl-F5 key to build and run the site:


Notice how the tree-view menu automatically highlights (by underlining - although you can style it however
you want) the current node in the site-hierarchy as a user navigates around the site.

Tutorial 6: Creating and Using User Control Libraries

The below tutorial demonstrates how to create and use separate user-control library projects with VS 2005
Web Application Projects. Please make sure that you have already completed Tutorial 5: Using Master Pages
and Site Navigation before reviewing this one.

Why Create a User-Control Library

Adding a user-control into an existing web application project is very easy. Simply right-click on the project
and choose the "Add New Item" menu item and pick the "Web User Control" template.

What this tutorial will cover is how you can also use VS 2005 Web Application projects to create re-usable
libraries of user-controls that are potentially referenced and pulled-in from multiple web projects. This
provides additional re-use flexibility with large-scale web-projects, and with VS 2005 Web Application
Projects is now easier than it was with VS 2003.

Create a New User Control Library Project

Select File->Add New Project to add a new project to your existing VS Solution. Name the new project
"MyUsercontrolLibrary" and make it a VS 2005 Web Application Project:
Create it as a peer-directory of the "MyWebProject" project we've been working on - with both project sub-
directories stored immediately below the .sln file (note: this isn't a requirement, but can make things easier to
manage):

Delete the Default.aspx and Web.config files that are added to new projects by default, and then right-click
and add a new user-control to the MyUserControlLibrary project (name it "samplecontrol.ascx"):
Your solution explorer will then look like:

Open up the SampleControl.ascx file, and add two textbox controls, a button, and a label into the user-control:
Then create and add a button event-handler to the User-control code-behind file:

Choose Build->Build Solution or hit Ctrl-Shift-B to build the solution and verify there are no errors. You now
have a user-control library that you can update and maintain as a separate project. You can add any user-
control files, standalone classes, master-pages, or pages in it that you'd like.

Consuming User Control Libraries

There are a couple of different strategies that can be used when consuming user-control library projects. Often
you will have a separate solution for managing these projects, and then make a file-based assembly reference
to them from your web-project. For this sample, though, we will simply use a project-to-project reference.

Within your "MyWebProject" project (which is the web app), right-click on the References node and select
"Add Reference". Click on the "Projects" tab and select the "MyUsercontrollibrary" project. This will copy
and reference the assembly with all the code for our control library.
Then right-click on your root project node, and choose the "Add->New Folder" command. Create an empty
directory called "UserControls".

Right-click on the "MyWebProject" project node and pull up the properties for the project. Select the "Build-
Events" tab so that we can configure a pre-build event on the project:

In the pre-build event command-line field enter this command:

copy $(SolutionDir)\MyUserControlLibrary\*.ascx $(ProjectDir)\UserControls\


This will copy the .ascx files from the UserControlLibrary into the \UserControls\ sub-directory of the web-
application before each build of the project. Choose Build->Build Solution or press Ctrl-Shift-B to build the
solution and the project. Notice that when you run the above command, it will copy the .ascx files into the
project's usercontrols sub-directory, but not add the .ascx files themselves into the project. This means that
they can be easily excluded from source-control for the project.

To see this in action, compare the results of the solution explorer in normal mode:

and then when the "Show All Files" button is clicked (notice that files not part of the project are white):

To use this new user-control, create a new page called "UserControlSample.aspx" in your web application
project. Have it use the Site.Master master-page we created earlier, and then register and use the user-
control .ascx file:
User-controls in VS 2005 are also now supported in WYSIWYG mode. So if you click the "design" tab of
the .aspx page, you will see the user-control rendered correctly (instead of the grey-box that was displayed in
WYSIWYG mode for user-controls in VS 2003):

Right-click on the "UserControlsSample.aspx" file in the Solution Explorer and select the "Set as Start Page"
context menu-item. Then press either F5 or Ctrl-F5 to build and run the web-application:
You can now make any changes you want to the User-Control library (including adding new user-controls and
classes). The consuming web-project will then be kept up-to-date on each build of the solution.

Upgrading VS 2003 Web Projects to be VS 2005 Web Application Projects

The below tutorial helps explain how you can now use the VS 2005 Web Application Project to more easily
migrate existing web projects in VS 2003 to VS 2005.

Migrating from VS 2003 to VS 2005 using the Web Application Project

There are a couple of different strategies you can take when migrating a VS 2003 Web Project to VS 2005.
One option (which is the default with the shipping VS 2005 bits) is to migrate the project to use the new VS
2005 Web Site project model. For more information click here

An alternative (and now much easier) approach, is to migrate a VS 2003 Web Application Project to use the
VS 2005 Web Application Project option instead. The VS 2005 Web Application Project model uses the same
conceptual approach as VS 2003 (project file to include/exclude files, and compilation to a single assembly,
etc), and so doesn't require any architectural changes (the only things that might impact you are deprecated
API warnings -- which can optionally be ignored -- and/or language changes).

Once VS 2005 Web Application Project RC1 is installed, the default migration wizard in VS 2005 is to
migrate VS 2003 Web Projects to VS 2005 Web Application Projects. This model is much less invasive and
requires fewer changes.

Please follow the below steps in exact order. If you have problems using the below steps, please post in this
forum and VS team members will be able to help.

Step 0: Install the VS 2005 Web Application Project Preview

VS 2005 Web Application Project support is not built-into the shipping VS 2005 (although it will be included
with the SP1 release). So the first step (if you haven't done it already) is to install it.

You can learn more about it and install the release candidate build from here. After installing it, please spend a
few minutes following the tutorials on this site to test it out and learn the basics of how it works.

Step 1: Backup Your VS 2003 Projects

Please make sure to save a backup of your VS 2003 Web Projects and Solutions before attempting any of the
below steps. There is the chance that you might need to roll-back to the VS 2003 solution if you run into
issues, or start over from any step.

Step 2: Copy Remote Frontpage Projects to your local machine

If you use Frontpage Server Extensions to access your project on a remote server, you will need to copy it
locally before migration (if your web projects run locally then you can skip this step). VS 2005 Web
Application Projects do not support accessing projects remotly via the Frontpage Server Extensions. If you do
not copy the project locally first, migration will convert the project to a VS 2005 Web Site project instead.

To copy the remote site locally use the VS 2003 Copy Project menu command under the project menu. This
will lauch the copy project dialog.
Change the destination to "http://localhost/ProjectName" and be sure to select "All project files".

After the project has been copied locally you should remove the remote one from the solution and use "Add
Existing Project" navigating to the c:\inetpub\wwwroot\VS03Web folder where your project was copied.

Make sure the project still builds in the IDE.

Step 3: Open Your VS 2003 Web Project and Make Sure it Compiles Clean

Before attempting to migrate anything, please make sure that you open up your existing VS 2003 solution and
perform a clean-re-compile of the entire solution -- and then run the application. Spending 2 minutes to verify
everything is working before you migrate can save a lot of grief later (especially if the cause is because of a
last-minute directory move, etc).

Step 4: Temporarily remove the VS 2003 Solution from Source Control


If your project is currently under source control, you should temporarily remove/unbind it from source control
prior to converting it. Once converted, you can then add it back under source control.

Step 5: Open the solution or project in VS 2005 and perform a project migration

Close the solution in VS 2003, and start VS 2005. Choose "File->Open Project" from the File menu, and
select the .sln or .csproj file for the solution you wish to migrate. This will cause the VS 2005 Migration
Wizard dialog to launch:

Choose a location to backup the project:


The conversion wizard will then perform a few steps:

1) Update the project file to be a VS 2005 MSBuild based project file

2) Add an xhtmlcompliance section within your web.config file to enable "legacy" html rendering

3) Update your web project to go directly against IIS instead of use FrontPage Server Extensions

4) Fixup any language changes between .NET 1.1 and .NET 2.0

When complete, the solution will open up within VS 2005:

Step 6: Compiling and Running your Web Project

You are now ready to compile your web project. Choose "Build->Build Solution" or Ctrl-Shift-B to do this.
The most common issue I've seen people run into at this stage are compile conflicts with new class names
introduced with V2.0. For example: ASP.NET now has a built-in menu and treview control (as well as built-in
profile, membership and rolemanagent APIs) -- so if you declare these types in your VS 2003 web projects
today you may get an "ambiguous type" compiler error when you compile (note: the compiler lists each line
and typename for you). If this happens, you should update your declarations to fully qualify the
TreeView/Menu/Etc. you want to use (for example: change "TreeView" to
"MyCompany.MyControls.TreeView").

You may or may not also run into some API changes when moving to V2. This site lists the known set of
breaking API or functionality changes that were made between V1.1 and V2.0. You should consult this if you
run into a problem.

Once your project is compiling clean, you should be able to run and debug in on IIS using ASP.NET 2.0.

Step 7: Run the Web Application

Run the application to verify that the application is working fine. Fix up any runtime issues that you find. This
site lists the known set of breaking API or functionality changes that were made between V1.1 and V2.0, and
will be able to help if you run into any issues.

Step 8: Convert to Partial Classes

When you migrate your project using the above steps, none of your code-behind page code or classes are
modified. This means that the code should look (and work) just like it did in VS 2003. This makes it much
easier to migrate existing code to VS 2005.

You can optionally choose to keep your code in this format. Doing so will require you to manually update the
control field declarations within your code-behind file -- but everything else will work just fine in VS 2005.

Alternatively, you can update your pages/controls to use the new partial-class support in VS 2005 to more
cleanly organize the tool-generated code from your code-behind logic. This is done by separating out your
current code-behind files into two separate files -- one for your code and event handlers, and the other a
.designer.cs file that contains the control field declarations for the code-behind. Please review this tutorial for
more details on how this new code-behind model works.

To migrate your code to use this new model you should follow these two steps:

1) Make sure your web project is compiling clean without errors. You want to make sure that all code is
compiling clean without problems before attempting to update it to use partial classes. Please test this before
proceeding.

2) Right click on the root web project node within the solution explorer and choose the "Convert to Web
Application" menu item. This will then iterate through each page or user control within your project and
migrate all control declarations to be declared within the .designer.cs file, and event handlers to be
declaratively specified on the controls in the .aspx markup.
You should then do a clean re-build of your web solution. This should hopefully compile clean without errors
(the cases where I've seen errors are situations where you've done custom modification of the control
declarations within your code-behind class, and the upgrade wizard mishandles them). If you have any errors
in your task list, you can navigate to the appropriate page in the solution explorer and choose the "View Code"
and "View CodeGen" context menu items to examine the code and fix any issues.

If for some reason the .designer.cs file doesn't have a control declaration added, you can manually declare it
within the code-behind file of the page (just like you would in VS 2003). One issue we've sometimes seen
reported are cases where a developer has specifically overriden the type of a Usercontrol declaration in a VS
2003 code-behind file (for example: MyControl1 instead of the generic UserControl base class), and the type
isn't correctly transferred to the .designer.cs file (producing a compile error). If the correct user-control type
declaration isn't added to the .designer.cs file, you can optionally just delete it from the .designer.cs and add it
the code-behind file of the page instead. VS 2005 will then avoid re-adding it to the .designer.cs file (it first
looks in the code-behind file for declarations before updating the .designer.cs file on changes).

Note: as an advanced option, you can also upgrade each page on a page-by-page basis (just right-click on the
page and choose the "Convert to Web Application" option on it). You might consider doing this if you want to
watch closely the changes made on each page.

You might also like