Web Development with Visual Web Developer 2005 Express Edition and SQL Server 2005 Express Edition, Part 1
Dan Burman
Progressive Systems Consulting
March 2005
Updated June 2005
Applies to:
Microsoft Visual Web Developer 2005 Express Edition
Microsoft SQL Server 2005 Express Edition
Summary: Part 1 of a three-part series on creating Web applications with Visual Web Developer 2005 Express Edition and SQL Server Express covers setting up a project and creating a SQL Server Express database, and explores the use of the ASP.NET Web Site Administration tool to set up roles, users, and providers. It also covers utilizing security controls such as Login, LoginStatus, LoginView, CreateUserWizard, PasswordRecovery, and ChangePassword. (16 printed pages)
Note This article is based on the May 2004 Alpha release of Visual Web Developer 2005 Express Edition and SQL Server 2005 Express Edition Technical Preview. All information contained herein is subject to change.
Download the associated ExpressWebDevelopment.exe sample code.
| Download the ExpressWebDevelopment.exe code sample. |
Contents
Introduction
Overview
Setting Up Your Project
ASP.NET Web Site Administration Tool
Setting Up Forms Authentication in the Web.config File
Setting Up Data Connections Within Data Explorer
Security Server Controls
Summary
Introduction
Welcome to the first installment in a series of white papers in which I'll be examining many of the new features that are offered to developers within Visual Web Developer 2005 Express Edition and SQL Server 2005 Express Edition Technical Preview. Throughout the series, I will take you through a step-by-step process where I will be constructing a sample application of a student activity registration. This application will allow students to sign up for activities and view a calendar of activities that they're signed up for. Student Activities Board members (administrators) will be able to add new activities to the system and view the enrollment for each existing activity. Students would be able to enter and edit personal information. Privileged users would be able to run reports on student information for use by school administration. There will also be a public area of this site that would advertise events on campus.
The first article in the series will look at all of the components that Visual Web Developer 2005 Express Edition offers in conjunction with SQL Server Express. I will look at the new Web Site Administration tool that allows site administrators to manage various data providers, application roles, and user accounts. You will see how seamlessly these integrate with the new security-based server controls offered in ASP.NET 2.0.
Part 2 explores data access with SQL Server Express. You will see how to create tables and stored procedures, implement an n-tier architecture through the use of data components, and interface with the presentation layer through the ObjectDataSource.
The third article in the series will take the user through a step-by-step construction of the key pages of the Web site. You will learn how to create template-driven sites with the use of master pages and content pages, and then learn how to bind server controls to integrate with the data access layer. Finally you will learn what's involved in deploying the applications.
Overview
New security features offered to developers are one of the most profound improvements introduced by the powerful integration of Visual Web Developer 2005 Express Edition with SQL Server Express. ASP.NET 2.0 offers membership services that support a database of user accounts and hashed passwords, a role manager, and several server-side controls that integrate with the user accounts to handle forms authentication, with zero coding involved by the developer. Also offered is a powerful ASP.NET Web Site Administration tool that interfaces with the security model to manage user accounts, manage roles, and establish data providers.
This article will take you step-by-step through the process of setting up SQL Server Express as the application provider to manage user roles, establishing forms authentication, setting up application user accounts and roles, and building Web pages to take advantage of the powerful server-side controls integration with Membership Services.
Setting Up Your Project
It is simple to create a new project using Visual Web Developer 2005 Express Edition. Open the application, and on the File menu, click New Web Site, and then select ASP.NET Web Site from the list of installed Visual Studios templates. Name the Web folder "StudentActivities" and click OK. Once Visual Web Developer 2005 Express Edition is finished creating and loading the Web folder, you'll see the Web folder opened in the Solution Explorer window. Next you will set up a folder structure to better organize the code to be developed. In Solution Explorer, right-click the root folder, and click New Folder. Rename this folder "Code." ASP.NET 2.0 recognizes this folder as containing data components that will be accessible to the other forms in the application. (The second article in this series) includes more information on data components.)
Next, add two more folders to the project: "MasterPages" and "ContentPages." These names don't have any special significance to ASP.NET 2.0, but they'll be used to organize master pages and content pages, respectively. (The third article in this series will have more on master/content pages). Finally, add a database to the Web project. Right-click the "Data" directory, which should have been added when you created a new Web site, and then click Add New Item. From the list of file types, select Database, and rename it "StudentActivities.mdf." Upon adding the database, the Data Explorer window opens and a data connection will be created to access the new blank database.
Problems can occur when trying to connect to the database if the login credentials of your .MDF file don't match those used to set up SSE during installation. To ensure that the login credentials match, you may need to update the connection string of your StudentActivities.mdf. To do this, right-click the data connection in the Data Explorer window and select Modify Connection... When the Connection Property designer opens, set the login credentials to match those of SSE during installation. If mixed mode was used at installation time, it needs to be used here as well. Once all of the credentials are set, click Test Connection, and the once the connection has succeeded, click OK.
.gif)
Figure 1. View of project folder structure in Solution Explorer
Now that the basic folder structure has been constructed and the database has been added, we'll need to set up the Membership provider, user roles, and application users.
ASP.NET Web Site Administration Tool
The ASP.NET Web Site Administration tool (WSA) is one of the most powerful improvements that ASP.NET 2.0 introduces. It provides a simple yet powerful graphical interface that allows developers to maintain and manage many different aspects of the Web application. Although the ability to administer other features of ASP.NET 2.0 can be handled within the WSA, we'll just be looking at three features for the purpose of this article: administering a default Membership provider, managing roles, and managing account users.
To open the ASP.NET Web Site Administration tool from within Visual Web Developer 2005 Express Edition, on the main menu, click Web Site and select ASP.NET Configuration.
.gif)
Figure 2. The ASP.NET Web Site Administration tool main screen
Once the administration tool opens, you will be presented with four different options.
- Security—Enables you to set up and edit users, roles, and access permissions for your site.
- Profile—Enables you to manage a set of profile properties, whose values are stored separately for each visitor to your site.
- Application Configuration—Enables you to manage your application's configuration settings.
- Provider Configuration—Enables you to specify where and how to store administration data used by your Web site.
For the purposes of this article, we'll only be dealing with the "Security" and "Provider Configuration" options.
Setting Up a Provider
The first administrative task that we'll be performing is the set up of the Membership provider. By default, Visual Web Developer 2005 Express Edition imports an Access database called "AspNetDB.mdb" which is located in the "Data" folder within the Solution Explorer. Since this is an article showcasing the powerful integration of Visual Web Developer 2005 Express Edition with SQL Server Express, we'll be using SQL Server Express to handle our provider instead of Access.
ASP.NET 1.X applications often incorporated the use of databases to store and retrieve user credentials, user roles, and user personalization settings. Visual Web Developer 2005 Express Edition has made it far easier for Web developers by providing a series of user tables, built into ASP.NET, that store all of this information that developers use to spend a good amount of time implementing.
To set up a provider, on the Provider tab, click the Provider Configuration link at the top of the screen, and then click the Select a single provider for all site management data link. You will be directed to a screen that manages various providers. By default, there are two providers set up: AspNetAccessProvider and AspNetSqlProvider. As stated before, Access is the default provider, so AspNetAccessProvider will be selected when you see this screen for the first time. You will be using the SQL Server 2005 Express Edition provider to access the "StudentActivities" database, so you'll need to add a new provider. To do this, click the Add a new provider link.
You will be directed to a screen where you can begin to supply the provider information. To the left-hand side of the screen, there are two options: SQL Server Database and Access Database. Make sure that SQL Server Database is selected. Next, supply the SQL Server connection information. In the Server name field, type (local)\SQLExpress. SQL Server Express is intended to be a lightweight, file-based database that is installed locally. At installation time, a SQL Server Express instance called "SQLExpress" is created. It is this instance that you will attach to. In the Friendly name field, type SQL Express Provider. In the Database name field, type the physical path is to the .MDF file that we added (c:\Websites\StudentActivities\Data\StudentActivities.mdf). If you're not sure what this path is, you can go to the Data Explorer window in Visual Web Developer 2005 Express Edition and view the data connection that was created. The data connection should be "[machine name]\SQLExpress:[MDF file path]." Take this MDF file path and put it in the Database name field. Next, supply the authentication information. It should match the login information that we set up for our .MDF database. Click Save.
Note For more information on installing SQL Server Express in a secure manner, see the "Installing SQL Server Express Edition" section of Securing Your SQL Server 2005 Express Edition.
.gif)
Figure 3. Setting up the Membership provider with the Administration tool
You will be presented with a number of options regarding the storage and retrieval of certain membership information. Briefly take a look at these options. The first option allows administrators to determine whether only unique e-mails are permitted to be stored. If this check box is selected, users will not be permitted to store identical e-mail addresses for multiple accounts. The next option allows administrators to determine whether or not users can retrieve a password once they've forgotten it. If this is checked, users can have their passwords e-mailed to them. The next option allows users to request that a new password be randomly generated and e-mailed to them. The last option requires users to correctly answer a question before having their passwords sent to them. ASP.NET 2.0 provides all the functionality that these options imply; the developer need not implement such security-related features though code!
For the purpose of our demo application, select the Required unique e-mail, Allow password retrieval, and Require question and answer check boxes, then clear the Save password in secure format check box and click Save.
The next screen that you'll see allows control of site and page counter settings. These counters record the number of times that users click on specific links or visit specific pages. An administrator can optimize the application's performance by adjusting the frequency that the site counter is saved to the database from memory. In addition, administrators can specify how long they want the site counter service to wait while writing out data before logging an error in the event log.
For the purpose of our application, keep the default settings and click Save.
The next screen allows you to set up the cookie domain to determine when the browser will send the Role Manager cookie. If you are using both Forms Authentication and Role Manager in your application, the cookie domain should be set to the same value for both features.
We won't be using cookies right now, so keep the default and click Save.
Next you should see a message that says you have successfully set up your provider. Behind the scenes, a series of SQL scripts ran that caused the generation of several security-related tables and stored procedures. These tables and stored procedures that were generated will be used by the Membership service to manage the user accounts, roles, and user credentials (we will cover how to connect to SQL Server Express within Visual Web Developer 2005 Express Edition and see these new tables later in this article). Finally, the web.config file is updated with a connection string to your provider, along with some provider-specific elements. Below is a sample of the provider snippet that is added to the web.config file:
<providers>
<add connectionStringName="SSE_Connection"
applicationName="/StudentActivities" requiresUniqueEmail="true"
enablePasswordRetrieval="true" enablePasswordReset="false"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed" name="SSE_ACtivities"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.3500.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx"/>
</providers>
Click OK to get back to the provider section of the administration tool. You should see your provider added to the list of providers and its radio button selected.
Setting Up Roles with the Role Manager
The next thing that we want to do is set up the application's user roles. Our application will have two basic roles: "Administrator" and "Student." In the Web Site Administration tool, click the Security tab. The table on this tab has three columns: one for users, one for roles, and one for access rules.
.gif)
Figure 4. Security view of the Administration tool
To enable rows, in the "Roles" column, click Enable roles. To create a new role, click the Create roles link. This will take you to a simple screen where you type in the role name, type Administrator in the text box, and then click Add Role. Once the role is created, you'll see it in a list of roles available to the application. Repeat the previous step to add a "Student" role to the application. Behind the scenes, these roles were added to the aspnet_Roles table within the StudentActivities database.
Setting Up User Accounts
We are now going to add some users to the application. We'll be adding students from within the application itself, but we'll add one through the administration tool to show what needs to be done. In the "Users" column, click the Create User hyperlink. This will take you to a form where you can create a new user and assign it to a role. Before we add any students, let's first create a user account that's assigned to the "Administrator" role. Create a dummy account called "admin1." Enter the user name, password, the confirmed password, a unique e-mail, and a security question and answer. The security question and answer ties into the provider option of requiring a question and answer to recover a user's password. Had that option not been selected, these fields wouldn't be available. To assign this user to the "Administrator" role, select the Administrator check box within the "Roles" column.
You'll also notice three check boxes at the bottom of the screen. The Send Password check box will automatically cause the password to be e-mailed to the new account upon completion. The Autogenerate Password check box will autogenerate a password for the newly created user login account. Choosing this option will cause the password to be automatically generated and then e-mailed to the user.
The Active User check box will flag the user account as an active user. In the context of our application, students generally will have an account life of no more than four years. Rather than deleting a student's credentials upon graduation or leave of absence, an administrator can render the student inactive by clearing this check box. The account remains, but the user will no longer be able to log into the application. If at a later date, the student returns to pursue an advanced degree or end the leave of absence, the administrator can render the user active again by selecting this check box. The administrator won't have to create a new account for the student.
.gif)
Figure 5. Create a new user account in the Administration tool
Once all of the user information is entered, click Create User. When saving this user, a new row will be saved into the aspnet_Users table in the "StudentActivities" database. In addition, a row will also be entered into the aspnet_UsersInRoles table, thus storing the role information for that particular user. Now that an "Administrator" has been created, go through the same steps to create a "Student" user named "student1." Obviously, you'll want to select the Student check box in the "Roles" column to assign them the role of "Student."
We have now successfully added a provider to our SQL Server Express database, created two application roles ("Administrator" and "Student"), and we've created two application users ("admin1" and "student1"). Let's now set up a connection to SQL Server Express from within Visual Web Developer 2005 Express Edition so that we can view the tables that we've just created. Let's now tweak the web.config file to establish Forms authentication.
Setting Up Forms Authentication in the Web.config File
Forms-based authentication is the process of having forms determine whether or not certain users should be provided access to privileged application resources based on their login criteria. In a form-based authentication design, developers construct a login form used to collect user identification information, such as user name, password, and associated roles. Once users supply a valid user name and password, they will be able to access all forms to which they've been granted permission. If they attempt to access a page that they are not authorized to access, they will be sent back out to the login screen.
To implement forms authentication, open the web.config file that appear in the root folder of our "StudentActivities" directory. Place the following code in the Web form, overwriting the existing default <authorization> and <authentication> tags:
<authorization>
<deny users="?" />
</authorization>
<authentication mode="Forms">
<forms loginUrl="~/ContentPages/login.aspx" />
</authentication>
Within the <authorization> tag, you'll see a <deny users="?" /> element. This is essentially saying that all anonymous (not logged in) users should be denied access to this privileged folder. The <authentication mode="Forms"> tag means that we'll be implementing forms authentication. The <forms loginUrl="~/ContentPages/login.aspx"/> tag tells the server to redirect any anonymous access to protected portions of the site to the login screen at "~/ContentPages/login.aspx." Users that attempt to bypass the login process will be pushed out to the login screen until their credentials can be verified.
Setting Up Data Connections Within Data Explorer
One of the great features of SQL Server Express over MSDE 2000 is that SQL Server Express sports a handy GUI for database management. At the time of writing this article, the interface is not yet implemented, so to view and manage your database, use the Data Explorer window from within Visual Web Developer 2005 Express Edition.
To open Data Explorer in Visual Web Developer 2005 Express Edition, on the View menu, click Data Explorer. You should see a tree view display of your database "StudentActivities" under your "Data Connections" root. If you navigate down into the database tree view, you'll see a folder labeled "Tables." Inside it you'll see all of the tables that were generated when you set up the Membership provider. If no tables are visible, highlight the data connection and click Refresh to refresh the view. To view the contents of a table, right-click aspnet_Users and select Show Table Data. You should see a record for both "admin1" and "student1." One last thing to do before moving on is to look into the "Stored Procedures" folder of "StudentActivities." You should see a number of stored procedures that were generated at the time the provider was set up. The "aspnet_Membership_CreateUser" stored procedure is called to create a new login user account. The "aspnet_UsersInRoles_AddUsersToRoles" stored procedure adds a user to a role. The are unfortunately too many stored procedures to list in this article, but I'd encourage you to explore each of then to get an idea of what functionality is possible at little cost to the developer.
These stored procedures are accessed by the Membership service to maintain user credentials, personalization settings, roles, and application settings. I won't go into detail about the inner workings of SQL Server Express; for details on how to manually create tables and stored procedures in SQL Server Express, read the next installment in this series that deals primarily with SQL Server 2005 Express Edition.
The entire environment is set up, and you can start building the application.
Security Server Controls
Since this article is specific to security, I'll deal primarily with security server controls. Visual Web Developer 2005 Express Edition offers developers a broad array of useful server controls that automatically integrates with the Membership service. Below is a list of the primary security server controls and a brief description of each:
- Login—Authenticates user's credentials against the Membership provider
- LoginView—Displays different output based on the role associated with the logged-in user
- LoginStatus—Displays whether or not the user is currently logged in
- CreateUserWizard—Allows users to create login accounts
- PasswordRecovery—Allows users to easily recover forgotten passwords
- ChangePassword—Allows users to change their passwords
Each of these server controls integrates with the Membership provider to authenticate and authorize users' credentials, and requires no code to do so. I will take a look at each control within the context of a series of screens for our student activity registration Web site.
Login, LoginStatus, and LoginView Controls
Each page of the Student Activities Web site will be built, step-by-step, throughout my series of articles.
To begin building this application, first add a master page called BaseForm.master. Master pages are the base template in the new template-driven architecture provided by ASP.NET 2.0. (The upcoming third article in this series will have more on master pages.) To create a master page in Solution Explorer, right-click the "MasterPages" folder , click Add New Item... and then click Master Page. Rename the file BaseForm.master and click OK.
Once the new master page is added, depending on your default settings in Visual Web Developer 2005 Express Edition, you'll either see the source code of BaseForm.master in the coding pane, or you'll see the master page in Design view. If the source code is displayed, to review this master page in Design view, click Design in the coding pane.
You'll see that there is an instance of the ContentPlaceHolder control placed on the form. Rename this control to "cphMain." We'll come back to this master page in the third article in this series to add greater aesthetics and functionality to this master page, as well as further explain its purpose, but for now, let's just deal with the issue of security.
On BaseForm.master, we will be using three separate security-related server controls: Login, LoginStatus, and LoginView.
First, drop a LoginStatus control (found under the Login tab of the toolbox) onto the main form and rename it "lsLogin." Set its LogoutAction property to "Redirect" the LogoutPageUrl property to "~/ContentPages/Logout.aspx" and the LoginText property to "." The LoginStatus control is a navigation control that is tied in to the login status of the application. So if the Web user is anonymous (meaning the user hasn't logged in), the LoginText value is displayed. In our case, we made this value blank to hide the link in the case of an anonymous user. If the user is logged in, then the LogoutText is displayed. If the user clicks the Logout link, then the user goes to the URL defined in the LogoutPageUrl property.
Next, we need to add a way for registered users to log in to the Web site. First drag-and-drop a LoginView control (found under the Login tab of the toolbox); rename it "lvMain." The LoginView control is used to display different output based on the user's login status. Right-click the LoginView control, and on the context menu, click Edit Template, and then click AnonymousTemplate. Any controls that are placed within the AnonymousTemplate will be displayed whenever the user viewing the page is unauthenticated (hasn't logged in). Conversely, the LoggedInTemplate content will display when an authenticated user views the page. In addition, you can further define the LoggedInTemplate by assigning roles to the LoginView control. This will only display content for users that are logged in under a matching role. You will put this feature to use in the third article in the series. For now, open the AnonymousTemplate and drag-and-drop a Login control onto the template.
.gif)
Figure 6. Design view of BaseForm with Login, LoginView, and LoginStatus controls
The Login control authenticates the user's credentials against the default Membership provider. There is nothing that needs to be done from a development standpoint. ASP.NET automatically checks the user's credentials and authenticates the user based on the password and username. This is put in the AnonymousTemplate so that only unauthenticated users see a Login control. Once the user logs in, the user's login status changes, and that affects the output of the LoginView control.
CreateUserWizard Control
Next you will build a screen to permit administrators to create new students. ASP.NET 2.0 introduces the CreateUserWizard control, which is a server control that is integrated into the Membership service to add new login users. This control is a breeze to use—there is little to do but drop the control on the form.
You will add a new content page to accommodate this control, and call it "LoginCreateUser.aspx." Content pages are the derived form that is modeled after the master page template in the new template-driven architecture provided by ASP.NET 2.0. (The upcoming third article in this series will have more on content pages.) Next, drop an instance of the CreateUserWizard control and rename it "cuwUser," then set the ContinueDestinationPageUrl property to "~/ContentPages/Activity.aspx." That's all that is required to have this page integrate with the Membership service. When a Web user supplies the necessary user information to this control, a new user is generated in the aspnet_Users table.
.gif)
Figure 7. Design view of the CreateUserWizard control
Within the context of this application, administrators can add new users to the "Student" role. If there is one limitation to this control, it is that there is no built-in functionality to read and assign user roles to the new login users. Luckily, ASP.NET 2.0 provides developers with a simple Roles API that makes the addition of a user to the "Student" role very simple.
Double-click the "cuwUser" control from within the Design view of "LoginCreateUser.aspx." This will cause Visual Web Developer Express to generate an empty event code stub called "cuwUser_CreatedUser" in the CodeBehind file along with its event handler. This event will fire once the user has supplied valid login credentials to create a new user, and then clicks Create User. Within the event procedure, place the following line of code:
Roles.AddUserToRole(cuwUser.UserName, "Student")
This line of code makes a call to the AddUserToRole() method of the Roles API. This method requires two parameters: the user name and the role name. We can access the user name from the UserName property of cuwUser, and then we pass in a hard-coded "Student" string to the role parameter, since only students will be added from within the application. It should be noted that this "Student" string is not case sensitive. We could have very easily extended this page out to allow the administrator to select a role, instead of hard-coding one. All that would be needed to achieve this is the addition of a data source control bound to the aspnet_Roles table and another control (such as a combo box) bound to the data source control. The code would then be changed to pass the combo box's selected value into the AddUserToRole() method instead of the hard-coded "Student" string.
PasswordRecovery Control
Often Web users forget their passwords. Fortunately for developers, ASP.NET 2.0 also has a control called PasswordRecovery to handle this situation. This control integrates with the Membership service and e-mails the user's e-mail account with the forgotten password. Obviously, this functionality will only work if the administrator sets up the provider to e-mail recovered passwords to users.
.gif)
Figure 8. Design view of the PasswordRecovery control
To see this control in action, let's add a new content page and call it "LoginPasswordRecovery.aspx." Next drop a PasswordRecovery control onto the page, rename the control as "prUser" and set its SuccessPageURL property to "~/ContentPages/Login.aspx." Also in the MailDefinition:From property, enter the e-mail address of the domain from which this e-mail is being sent. We are using the fictitious account admin@studentrec.com, but you'll want to modify this to put your administrator's e-mail account. In simple cases, when the user comes to this page and enters a valid user name, the user password will be e-mailed to the user. If the user enters an incorrect user name, then an error is displayed as defined in the control's UserNameFailureText property.
For added security, recall that when you set up the Membership provider, you set a property requiring that the user first answer a security question associated with that user account. Because of this, after the user has entered a valid user name, the user will then be prompted to answer the security question associated with the user account. If the user answers the question correctly, the user will be e-mailed the password and then redirected to the URL defined in the SuccessPageURL property. If the answer is incorrect, the password request is denied and an error is displayed, as defined in the control's QuestionFailureText property.
ChangePassword Control
The last control that I'll be looking at is the ChangePassword control. This control allows the logged-in user to change the user password.
.gif)
Figure 9. Design view of the ChangePassword control
Next, you will add a new content page and call it LoginChangePassword.aspx. On the form, drop a ChangePassword control and rename it "cpUser." Doing this will implement a UI where the user will be required to enter the existing password, enter a new password, and then confirm the new password.
If the user fails to enter the correct existing password, then the request to change the password will not be honored, and an error will be displayed as defined in the ChangePasswordFailureText property. If the password is correct and the new password is valid and confirmed, then the user's account will be updated with the new password by the Membership service.
Summary
The ASP.NET 2.0 introduction of the Membership service dramatically simplifies developer responsibilities to create properly secured Web applications. The integration of a powerful Web Site Administration tool, the SQL Server 2005 Express Edition Technical Preview, and an array of security server controls to manage user credentials and authentication, provides developers with a security-based solution that requires little or no code.
Part 2 further explores how to work with SQL Server Express, create a data access layer with data components, and bridge data components with server controls in the presentation layer by using ObjectDataSource.
About the author
Dan Burman is a consultant for Progressive Systems Consulting, a New York-based custom software firm, specializing in Microsoft .NET and SQL Server. Visit Progressive (http://www.progsys.com) on the Web.