Example 1: Chamber Project with User Authentication

A video version of this example is available on our weblog.

The output of this exercise will be a very basic website showing an updateable list of Chambers in the United States. It will make use of UnifiedASP’s User Authentication and Authorization modules so only users with correct permissions will be able to add, update, or delete new chamber records.

Before we get into building it, take a look http://sample.unifiedasp.net/USChamberSample1 so you can get a feel for the requirements. You can log in with the credentials admin/password. This data is reloaded every 30 minutes so any changes you make will be reset.

To complete this exercise, you’ll need to following downloads:

  1. UnifiedASP Framework VB.Net Solution
  2. UnifiedASP Code Generator Application
  3. Chamber Tables and Seed Data.sql SQL Script

You’ll need access to a SQL Server database and Visual Studio will be helpful but you can extract the files from the solution into whatever IDE you prefer.

High-level steps for this exercise:

  1. Download the framework and make a copy for this sample
  2. Create a database and run the framework and seed data SQL scripts
  3. Run the code generator against your new database
  4. Tweak and run the generated SQL scripts
  5. Copy the generated classes to your project and tweak them
  6. Copy the generated Chamber pages to the project
  7. Make a couple of minor configuration changes to the application
  8. Add a menu item for the Chambers module
  9. Make a small permission modification since you want all users to view Chambers
  10. At this point, the application will function but we’ll have a couple of additional minor modifications to make
  11. Use the application to add permissions

Here are detailed, step-by-step instructions for this exercise:

  • Download the files above and unzip them
  • Create a new database. In this case we named it USChamberSample1 and assigned a user account to it. (You can use an existing database if needed but any existing Chamber or State tables will need to be removed)
  • In local file system, make a copy of the downloaded folder UnifiedASP Framework VB.Net.
  • Rename your copied folder and its solution file to the desired solution name, in this case we used USChamberSample1.
  • In the just-copied USChamberSample1 folder, there is a SQL Script named UnifiedASP Framework with Users.sql. Double click this file, log into the database you just created, and execute the script.
  • Normally at this point, you would create any database tables including foreign keys and might add some seed or sample data. For the purpose of this example, run the Chamber Tables and Seed Data.sql script against your database. This will create two tables: Chamber and State.
  • To create the base stored procedures, domain classes, and CRUD pages for the Chamber module, you’ll use our code generator.
  • Open the UnifiedASP Code Generator folder and double-click on UnifiedASPCodeGenerator.exe and you will see the following screen.


First, you’ll need to change the Connection String to point to your USChamberSample1 database.

When the code generator creates stored procedures, it prefaces them with a code so it’s easier for them to sort together if you have different teams or applications using the same database. In the Sproc Prefix field, type in whatever prefix you would like for stored procedures. In this case, we changed it to “ch”.

The code generator also places all classes in a namespace. You can specify the namespace in the Namespace field. In this case, we changed it to “USChamber”.

The code generator will work through a series of templates to create the stored procedures, classes, and pages for the tables you specify in the next step. By default, the template folder is at the root of the folder containing this executable. If you’ve moved the template folder or have different templates for different sites, you can change the folder here.

You can also specify a folder that the code generator will use to write the completed files. By default it will write to the Output folder at the root of the folder containing the executable.

For now, just leave these paths as the defaults.

If you will be generating code for the same application in batches, you can click on the Update Configuration button and it will store this as your default configuration.

After entering the appropriate information, click the next button. If anything is not correct, the application will throw errors and you can fix it. Now you should see the screen below:


From this screen, you can select tables you’d like to generate code for. Stored Procedures, Classes and Pages already exist for the App* tables, so you can just select Chamber and State and move to the box on the right. Your screen should now look like:


Now click your next button to see the screen below.


From this screen, you will configure how the code generator will handle the columns for each table. The code generator has set defaults for certain fields based on the meta-data in the database. You’ll need to make a few changes.

If you click on the ChamberName column in the Table Columns select list, it will replace the information in the Column Data box with data specific to the ChamberName column. The only change we are going to make now is to change the Label from “ChamberName” to “Chamber Name” because that is how we’d like the field labeled on the generated screens.

Now click on the City column. We would like this column to be a filter on the Chamber Search screen so you need to check the Include in Filters checkbox.

Now click on the StateId column, change its label to State, and click the Include in Filters checkbox so it too will be a filter.

Click on ZipCode and change its label to Zip, click on Phone Number and change its label to Phone Number, click on FaxNumber and change its label to Fax Number, and finally click on WebsiteURL and change its label to URL.

We are not going to make any changes to the State table or its columns because we will not use the generated screens.

Now, just click the Finish button and you should quickly see an alert of “The Code Generation has finished.” Click OK.

From here, you can close the code generator by clicking Cancel or the X button.
Now, if you look in the Output folder specified on the first screen, you will see four folders:

  • _class contains two classes, one for each table
  • _sproc contains two SQL scripts, one for each table
  • Chamber which contains the CRUD files for the Chamber table
  • State which contains the CRUD files for the State table

Let’s start by adding the generated stored procedures to your database:

  • Open the _sproc folder and double click on the State-sprocs.sql file and log into the database you are using for this exercise.
  • For the State table, we only need one stored procedure to populate the list of states on the Chamber search and edit screens so remove all stored procedures except for chState_GetAll. The script should now look like:
CREATE  PROCEDURE dbo.chState_GetAll
AS
BEGIN

set nocount on

	select
		s.StateId
		, s.StateAbbr
		, s.StateName
	from
		State s with (nolock)
	order by
		s.StateName

END
GO
 
  • Run the script and close it
  • Open the Chamber-sprocs.sql file against your database and execute it. No changes are needed.

Your database is now ready to use so let’s turn our attention to the classes.

  • Open the _class folder in the code generator’s output folder and copy the Chamber.vb and State.vb into the App_Code/Domain folder of your USChamberSample1 project.
  • Just like with the database, we need to remove methods from the State class so it matches what is available in the database. Open /App_Code/Domain/State.vb and we’ll start there.
  • Remove the LoadMe, Save, and Remove sub routines, and save and close the file

Now that the database and classes are in place, let’s get started on the pages:

  • Copy the “Chamber” folder from the code generator output folder into the root of your project. Your solution should now look like the image below.


Configuration Changes:

  • Open the web.config file
  • The first change we need to make in the project is to tell the application to make the Chamber/Default.aspx page the default page. You’ll do this by changing the AppSetting UrlStart from “AppUser/Default.aspx” to “Chamber/Default.aspx”
  • Next, we need to tell the application to take the user to the Chamber module after logging in. You’ll do this by changing the AppSetting UrlAfterLogin from AppUser/Default.aspx to Chamber/Default.aspx
  • Next, you need to change the ConnectionString from its default to one that will work with your database
  • Save and close the web.config file

Now, we need to add the Chambers menu item. Since the look-and-feel of websites varies so widely, we fully expect you to build your own menuing for your applications. The framework does provide a simple menu that can be controlled in the MasterPage. We’ll add the Chambers link to this menu.

  • Open the UnifiedASP.master file found in the Asset/MasterPage folder
  • Add the following line before the other menu items starting on line 30
<%=getMenuLink("Chamber/Default.aspx", "Chambers", Nothing)%>
 
  • Your menu block should now look like:
<ul>
	<%=getMenuLink("Chamber/Default.aspx", "Chambers", Nothing)%>
	<%=getMenuLink("AppUser/Default.aspx", "Users", "AppUser.Read")%>
	<%=getMenuLink("AppGroup/Default.aspx", "Groups", "AppGroup.Read")%>
	<%=getMenuLink("AppPermission/Default.aspx", "Permissions", "AppPermission.Read")%>
</ul>
 
  • Save and close UnifiedASP.master

Now, we need to make sure all users can see the Chamber list and detail screens. In many modules, you will want users who use the search and detail screens to be logged in and have the correct permissions so the code generator does this by default. That’s not the case in the Chamber module so we need to make a couple of small changes.

  • Open the Chamber/Default.aspx.vb file. Currently this file inherits from UnifiedASP.Base.PageAuth. This base class will redirect users to the login screen if they are not logged in. You’ll need to change line 5 from Inherits UnifiedASP.Base.PageAuth to UnifiedASP.Base.Page.
  • Next, there’s an if statement in the Page_Load event handler that tests if the user has the correct permissions. We need to remove this If statement completely so Page_Load will look like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

	If IsGridEvent = True Then
		DoLoadData()
	End If

End Sub
 
  • Save and close this file and open Chamber/Detail.aspx.vb
  • Just like with Chamber/Default.aspx.vb, we need to change the class this page inherits from by changing line 5 from Inherits UnifiedASP.Base.PageAuth to UnifiedASP.Base.Page
  • Next, we need to change the If statement in the Page_Load event hander removing the or myPermission.HasPermission(”Chamber.Read”) = False condition. Leave the myChamber.HasRecords = False condition so the user will be taken back to the search screen if the requested record is not found. The If statement should now look like:
If myChamber.HasRecords = False Then
	SmartRedirect("Chamber/default.aspx")
End If
 
  • Save and close Chamber/Detail.aspx.vb

The application will now function correctly so let’s fire it up. The other changes will make as we review the application.

Press F5 to launch the project in debug mode and you should see the Chambers list screen Chamber/Default.aspx.

As you can see, there are more columns in the grid than in the example you reviewed before. This is because the Code Generator adds a column for all columns in the table since it’s easier to remove ones you don’t need than add them. Let’s clean it up.

  • Open Chamber/Default.aspx
  • The grid columns start on line 35. Remove all columns except for the HyperLinkField, and the BoundFields for Address, City, and State. Your grid should now look like:
<asp:GridViewX runat="server" ID="grdChamber">
	<columns>
		<asp:HyperLinkField HeaderText="Chamber" DataTextField="ChamberName" SortExpression="ChamberName" DataNavigateUrlFields="ChamberId" DataNavigateUrlFormatString="~/Chamber/Detail.aspx?ChamberId={0}" />
		<asp:BoundField HeaderText="Address" DataField="Address" SortExpression="Address" />
		<asp:BoundField HeaderText="City" DataField="City" SortExpression="City" />
		<asp:BoundField HeaderText="State" DataField="StateName" SortExpression="StateName" />
	</columns>
</asp:GridViewX>
 
  • Save and close the file
  • Return to your browser and refresh it and you should see only the columns you need

Once you are back on the search screen, click on one of the chamber names to view a detail record. The next requirement we need to take care of is to make the Website Url field a link instead of a label.

  • Open Chamber/Detail.aspx
  • On line 33, you will see the label for WebsiteUrl. Change this from an asp:Label to an asp:HyperLink that looks like:
<asp:HyperLink runat="server" id="hlnkWebsiteUrl" />
 
  • Save and close Chamber/Detail.aspx
  • Open Chamber/Detail.aspx.vb
  • Now, let’s change the code that populated the label with code that will populate the HyperLink
  • Change line 43 from lblWebsiteUrl.Text = myChamber.WebsiteUrl to hlnkWebsiteUrl.Text = myChamber.WebsiteUrl
  • You also need to add lines to set the NavigateUrl and the Target. The population of hlnkWebSiteUrl should now look like:
hlnkWebsiteUrl.Text = myChamber.WebsiteUrl
hlnkWebsiteUrl.NavigateUrl = myChamber.WebsiteUrl
hlnkWebsiteUrl.Target = "_blank"
 
  • Save and close this file
  • Return to your browser and refresh it and you should see Website Url as a link instead of a label

Now all of the basic functions are in place. All that’s left to do is log in and add the permissions for the Chamber module.

  • Click on the Log In link in the header
  • Enter “admin” for Username and “password” for Password and press enter or click the login button
  • You will be taken back to the Chamber search screen but will see menu items for Users, Groups, and Permissions
  • Click the “Permissions” menu item
  • Click on “Add New Permission” and type “Chamber.Create” in the Name field and press enter.
  • Click on “Add New Permission” again and type “Chamber.Read” in the Name field and press enter.
  • Click on “Add New Permission” again and type “Chamber.Update” in the Name field and press enter.
  • Click on “Add New Permission” again and type “Chamber.Delete” in the Name field and press enter.

Now, when you go back to the Chambers module, you will see a link for “Add New Chamber”. If you click on it, it will take you to the add screen. You will also see Edit and Remove buttons from the Detail screens.

At this point, the application is functional and is exactly the same code as you saw in the sample application.

Is it perfect, production-ready code?

No way! But it’s a huge head start.

Share It:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Reddit
  • StumbleUpon
  • Technorati