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

If you’ve been following this mini-series so far, you’ll know that we only have one basic database operation left to explore. We have looked at inserting, reading and removing data from a database table, all we need to do now is update our data. You’ll find that there are elements from nearly every page we have created so far in the updating page, even just a simple password update.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 17
October 18, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

To get started then, we need to build the visual elements of the page.  Open the Web Matrix, and in design view drag the following elements from the web controls toolbox onto the page: on the first line drag a label, a textbox and another label.  Onto the second and third lines, drag the same elements, then below these, drag a button onto the page.  Finally, drag another label to the line below the button.

Obviously, you need to edit some of the properties of these elements.  If you didn’t already know, this is done in the Properties pane at the left-hand side of the document window.  First, set the text of the first label to Username: and then select the first textbox and set the ID to txtUsername.  Now select the label element following the textbox and set the ID to lblUsernameError, the Fore color to Red and clear the Text value.

On the second line, set the Text of the first label to New Password:, set the textbox ID to txtNewPassword,  and set the ID of the second label to lblNewPasswordError. Then set the fore color to Red and clear the Text value.  Follow this format for the third line of the page, but set the Text to Verify New Password: and the ID values to txtVerifyNewPassword and lblVerifyNewPasswordError respectively.  Additionally, as the bottom two textboxes will contain passwords, you should set the TextMode property to Password to make the contents hidden when the page is used.  The button ID can be set to btnUpdate, while the Text value can be Update.  Finally, the label element on the last line should have the following properties: an ID of lblSuccess, a fore color of Green and an empty Text value.

Important Details and Updates

   

Some of these ID values may seem a little long, but whenever you find yourself application programming you should stick to the rule that anyone that hasn’t worked with you that has to debug your applications, should be able to do so easily and intuitively.  All elements should be labelled according to their specific functions in a consistent way.  If you looked at the code for an application for the first time that you were trying to update, and had a function that changed the value of a textbox, wouldn’t it be easier if you could pretty reliably guess what the textbox was called rather than figure out whether it’s textbox58 or not?   

So anyway, your page should now look a little like this:

 

Now switch to the code view and drag an UPDATE onto the page.  The UPDATE Data Code Wizard will open, and the database you are connected to will show.  Click the Next button to move on to the Construct section.  You need to tell it which column of the table you want to update; for this example, select the Password checkbox.  You now need to construct the Where clause; click the WHERE button and make sure Username is highlighted, then click Ok.

 

Click the Next button twice and then give the function a name, such as updateUserPass and click Finish.  Your code will be created and placed on the page. 

To provide the visitor with a success message, find the Finally statement of the Try code block near the bottom of the function you just created and add the following line after the call to close the database connection:

lblSuccess.Text = "Password updated!"

Calling the Function

You now need a sub to call the function, so switch back to Design view and double-click the Update button element.  We will use the same code to blank any message text at the beginning of the sub to reset any error messages that the user may have already received when viewing the page. Add the following code to the sub:

lblUsernameError.Text = ""
lblPasswordLengthError.Text = ""
lblNewPasswordError.Text = ""

If you remember the Registration page we created a couple of examples ago, you’ll know that the password a user chooses is written to the database table in an MD5 encrypted format, so we will also need to build that capability into this page.  The code in this is exactly the same as it was in the Registration page:

Dim hashMethod as string
    hashMethod = "MD5"
    Dim encryptPassword as string
    encryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile
(txtNewPassword.Text, hashMethod)

All we need now is an If statement to either display an error message, or execute the data operation if the username exists and the new password meets the predefined criteria.  These criteria are essentially the same as the ones in the Registration page; namely that the two password fields must match, and that the new password should be more than seven characters long:

If txtNewPassword.Text.Length < 7 then
      lblPasswordLengthError.Text = "* Your password is not
secure, please ensure it is 7 characters or more"
Else if txtNewPassword.Text <> txtVerifyNewPassword.Text Then
      lblNewPasswordError.Text = "* Verify password must match
password"
Else if updateUserPass(txtUsername.Text, encryptPassword) = 0
Then
      lblUsernameError.Text = "* Your username does not appear to
exist"
Else
      updateUserPass(txtUsername.Text, encryptPassword)
End If

That is all we need.  Save the file in the private folder of the site’s directory structure; as with the previous example page, we will insist that only authenticated visitors can access the page.  To test the page properly, you may find it useful to register two different usernames with the same password so that they show up in your database table with the same MD5 hash.  This way, you will know for sure when you update the password of one of the usernames, because it will no longer exactly match the hash of the other username.

Taking Care of Security

After your exhaustive testing, you may have noticed a pretty severe security issue that has cropped up with both of the pages in our private folder, namely the unsubscribe page from the previous article and the update page we have just created.  Say you have two registered users, Bob and Bill.  As our pages stand currently, once Bob has successfully logged in, he can then go on to update Bill’s password, effectively locking him out of the private folder, or unsubscribe and remove him from the database altogether.  We need to have a way of ensuring that users can only update their own information, and this means that our pages need to know the identity of the current user.  Fortunately, ASP.NET has a built in security infrastructure that you can use in your web applications to obtain details of the currently logged in user.

To make use of this feature, you need to add just a small bit of code to each of the pages in the private folder.  On the current page, encapsulate the existing If statement with the following code:

If txtUsername.Text = HttpContext.Current.User.Identity.Name Then
      ‘rest of the statement block
Else
      lblUsernameError.Text = "You are not authorized to perform
that action"
End If

This is an article about using the ASP.NET Matrix to produce dynamic web pages easily and quickly.  It is not about the inner workings of ASP.NET and it is not a security white paper, so I won’t go into things in too great a detail, but basically, the HTTPContext class allows you to access properties that are set when a successful login occurs, one of those properties being the name of the user that has logged in.  Testing this property against the value used in the database query (the Username), we can ensure that users can only update their own information in the database.

As this is a pretty useful piece of code that you may not want to manually add to an increasing number of pages, you can create a snippet to add to the snippets collection in the Web Matrix.  To do this, you’ll need to highlight the above code (removing the commented line of course), and right-click it.  From the menu that appears, select Add Snippet.  Open the My Snippets tool set and you should see a button referring to the code.  The name for this code is taken from the first line of the snippet so it may be wise to rename this to something more memorable like LoggedInUserName or similar. 

To secure the unsubscribe page created in the last article, open the unsubscribe.aspx page and drag the snippet onto the page.  Copy the existing If block in between the If and Else lines.  Test the two pages again and you should find that if you login as Bob, you can’t change Bill’s password.

So you have now used the Web Matrix to facilitate the four basic database operations.  Functions utilizing each of these operations have been quickly and easily added through the cunning use of the built-in code wizards.  You should by this time have a fully operational web application offering encrypted database storage and a reasonable security process.  It’s not bullet-proof, but if you’re new to ASP.NET, it’s not bad going.  As you’ll have seen, there is one more code wizard that has not yet been explored –- the email message function generator.  This requires more that just a database to make operational, but the code wizard helps make light work of building this facility into your application.  

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 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials