Database Storage with the ASP.NET Web Matrix: Unsubscribe Page

Using the Microsoft ASP.NET Web Matrix application along with a SQL variant database allows developers to create dynamic, data-driven websites. This article focuses on deleting data from a database table.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
September 28, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

I’m continuing the recent series on using the Microsoft ASP.NET Web Matrix application in conjunction with a SQL variant database server to create dynamic, data-driven web sites.  So far, we have looked at adding data to a database table and retrieving that data in order to run queries on it. This article will focus on deleting data from the table.

Like the two preceding examples, the page created during this tutorial will consist purely of the elements needed to get the job done; there will be no aesthetics, I’m afraid.  Before we start building the page, ensure that the database connection we’ve been using so far is connected by checking the Data pane at the right-hand side of the application window. 

First then, open a new standard ASP.NET page from the general section of the available templates.  The page should open in design view, but if not, switch to it, and from the web controls toolbox drag a label a textbox and another label control onto the page.  On the next line down, drag a button control, and finally, on the next line down from that, drag another label control on to the page.

These are the only elements we will need on this relatively simple page.  Don’t forget that in a pre-production scenario you would have to consider other elements in keeping with your site layout and theme such as a navigation system.

Setting up the Page

Use the Properties pane in the bottom-right of the application to set the text of the first label control to Username: and the ID of the textbox to txtUsername. Set the ID of the label following the textbox to lblUsernameError, change the color to red and clear the Text property. This control will display an error if the username entered does not appear in the database.  Next, set the ID and Text properties of the button to btnSubmit and Submit respectively.  The final label will be used to display a message when the action is successful, so change the Forecolour property to Green and the ID to lblSuccess.  Remove the Text property.  The page should look a little like this:

You will notice that we are not asking the user for their password, only their username.  The reason for this is that we are also going to implement an authentication system that uses a session cookie to determine whether a user has already logged in to the site.  If a user is not logged in, we will not let them access the unsubscribe page, and will instead redirect them to the login page that was created in the last article.  The username field is still needed in this case in order to specify the string used in the database query. This is not the only way to do it; we could for example use the session cookie to store the username and read from this instead. 

The security aspects will be discussed later. For now, switch to the Code view of the Web Matrix, and we can build the logic of the page.  The toolbox will automatically change to the code wizards. Drag the DELETE Data Method onto the page to open the DELETE Data Code Wizard.  Make sure that the database we’ve been working with so far is highlighted on the first page and click Next.   On the second page of the wizard, click the Where button to open the Where clause builder dialog box and just click Ok to accept the default.  A preview of the Where clause and data operation will be shown:

 

Click the Next button twice and in the final screen of the wizard, enter a name for the function like removeUser, before clicking the Finish button.   This will insert the code needed to remove entries from the database.  All you need now is a way of calling the function you have just created.

Calling the Function

Switch back to the Design view and double-click the submit button.  The following If statement will do everything we need when placed in between the Sub and End Sub lines of code:

If removeUser(txtUsername.Text) <> 0 Then
        lblSuccess.Text = "You have been removed"
Else
        lblUsernameError.Text = "* Your username does not appear
to exist"
End If

This will call the function and output a success message when data is removed, or an error message advising that the Username was not found in the database.  Use the play button to test the page and have a go at removing people from the database table.

So that is the unsubscribe page itself created, but at the moment (if this were a live page instead of a development page) anyone could access the page and run data operations without even entering a password.  To rectify this, you can create a special XML file to tell the web server who is allowed to view the unsubscribe page.  The file that can do this is of course the web.config file.  The Web Matrix has a template for a web.config file in the Security section of the page templates, so click the new file button and create one.  Note that this file can only be called web.config, so don’t worry about choosing a file name for it.

This will create a commented file containing some of the most common tags. There are others, but these will not be mentioned as we have no use for them.

 

As you can see, the configuration is separated into common sections that control different aspects of the web server’s behavior in different situations.  The section we are interested in at this point is the authentication section.  You will need to uncomment the following code block and change it so that it appears like this:

<authentication mode="Forms">

              <forms name=".ASPXAUTH"
                           loginUrl="login.aspx"
                           protection="Validation"
                           timeout="999999" />

</authentication>

This will set the authentication mode to Forms (case-sensitive) and specify the name of the login page that users will need to be redirected to when trying to access a protected resource.  Save this page for now and close the file. What you could do now is add an authorization code block and set it so that all pages in the same folder as the web.config file are protected until a registered user logs in, or specify a particular page that is protected using the location tag.  The problems with these approaches is that either all of your pages are protected (no good for a product catalogue or similar), or that you need to add a new location tag each time you create a protected page (not much fun if there are 50 protected pages, for example.

Setting up a Web Directory Structure

 

When the Web Matrix is installed, a folder called Web Matrix Projects is created in the My Documents folder.  This is the folder where the pages you have been making so far will probably be held.  This has been fine up until now, but to test the configuration we have almost completed, a proper web directory structure can be set up that includes a virtual site root.  This will enable us to maintain a folder structure more similar to that of a live web application and will give you better management of document organization.

Anyway, in Explorer, create a new folder in the Web Matrix Projects folder and call it dataSite.  Drag the login, register and web.config files into this folder and then, also in the folder, create a new folder called private.  Now drag the unsubscribe page into the private folder. 

Open IIS if you have it installed and navigate to the default web site in the tree-veiw at the far left of the management console.  Right-click on the default web site and select New --> Virtual directory.  This will open the Virtual Directory Creation wizard.  Click Next on the first page to begin and type the alias as dataSite.  Click the Next button again and use the Browse button to navigate to the dataSite folder in the Web Matrix Projects folder that we just created.  Click the Next button, accept the defaults and click the Next button again.  The wizard should notify you that the operation was a success so simply click the Finish button to go back to IIS.  Your folder will now be set up as a virtual directory:

 

If you don’t have IIS installed, when playing pages in the Web Matrix, you can choose to use either the built in server, or the option to Use or create an IIS Virtual Root.  Selecting this option will do automatically what we have just done in IIS.  If you have IIS installed, I would recommend using it simply to give yourself a better overview and understanding of the management console.

So that is the directory structure taken care of, to complete the task, you just need to create a second web.config file and make a small change to the login page.  Make sure the first config file is closed and open a new one.  Remove all of the existing text, except for the XML declaration at the top, and add the following code:

<configuration>
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
 </system.web>
</configuration>

Save the file.  The <deny users="?" /> line tells the server to deny any unknown (people that are not logged in) users access to any file in the folder it sits in (the private folder in this case).

There is just one thing left to do. As IIS will redirect unauthenticated users to the login page, we will need a way to redirect them back to the page they requested once they have logged in.  To this, open up the login page and change the successful login action from displaying a success message to redirecting a visitor:

If userDetailsName.Tables(0).Rows.Count <> 1 Then
  lblUsernameError.Text = "* Username not known, please <a
href='register.aspx'>Register</a> with us"
Else If userDetailsPass.Tables(0).Rows.Count <> 1 Then
  lblPasswordError.Text = "* Password incorrect"
Else
  FormsAuthentication.RedirectFromLoginPage
(txtUsername.Text,false)
End If

The FormsAuthentication method is what controls the redirect, the txtUsername.Text parameter can be used to specify a default page for the particular user and the Boolean value indicates whether the cookie that is created is a permanent cookie that hangs around on the user's computer after the browser is closed, or a session cookie that is destroyed once the session is over.

You can test this page by using the play button to open the Unsubscribe page.  If everything goes according to plan, however, the Unsubscribe page should not load.  Instead, the Login page should open, with the referring page appended to the URL as a query string.  Upon a successful login, the web server will redirect back to the page in the query string.  If you get errors when testing this page, you may need to shut down the Web Matrix application, then re-open it and open the login page.  View the login page but don’t actually log in.  Then open the Unsubscribe page and play it.  It would seem that the built-in web server of the Web Matrix still needs a little tweaking, as occasionally it may need to be coerced into doing what you want it to!  After you have successfully tested it, check the database table to check that the user has been removed. 

So now we have covered inserting, reading and deleting from a data source using the preconfigured wizards. The next article will discuss updating data, such as when a user wants to change their password or account information.

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 4 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials