270 likes | 397 Views
Concepts on this Unit are Excluded from final exam. Unit 8.3. Learning Objectives Insert users into the ASP.NET Membership system from code Capture data being sent to the database Capture Exceptions that happen at the database. ASP.Net Membership.
E N D
Concepts on this Unit are Excluded from final exam Unit 8.3 Learning Objectives • Insert users into the ASP.NET Membership system from code • Capture data being sent to the database • Capture Exceptions that happen at the database
ASP.Net Membership • Unit 7 demonstrated ASP.NET Membership controls to • Configure security using the ASP.NET Configuration option • Create users • Create roles • Create access rules • Use .NET controls • Create new users • Login • Display login status and login name
Adding Users using Custom Code • Import a library of special tools (i.e. namepsace) • Namespace contains “Membership” functionality • MemberShipCreateStatus • Membership • using System.Web.Security; • MemberShipCreateStatus status; • MemberShip.CreateUser (username, password, …, status)
A great example… “user”, “password”, “passwordQuestion”, and “passwordAnswer” are all string variables and all have values This means that the status is returned from the method, all other data is sent into the method This could mean bad data, duplicate user names, missing or weak password Things can always go wrong so attempting to create a user in code should always be in a try/catch block. If an Exception does occur, show it to the user.
Events related to Data Controls • Occur with Insert, Update (Edit), or Delete • With Data bound controls (e.g. DetailsView) • In the following order • <DetailsView> ItemInserting(or IteamUpdating, or ItemDeleting) • <DetailsView> Inserting • <DetailsView> Inserted • <DetailsView>ItemInserted • ….
How the event method handles user info This shows how you can get to the same data in code if you know the database field name
More event processing • Event methods ending in “ed” occur after the event and provide a way for us to see what happened as in this DetailsViewItemInserted even method… Number of rows affected by command This lets you see the Exception was, i.e. an attempt to insert a duplicate key i.e. the user was already in the database
Testing for an Exception test to see if an exception occurred • Tell the system that you took care of the exception and it doesn’t need to crash • Display the Exception Message
Unit 8 L2.2 In this exercise you will add a user to a database you create and to the membership database at the same time • Create a new table in your MIS3200 database with the following fields • UserEmail – nvarchar(100), primary key • UserFirstName – nvarchar(50) • UserLastName – nvarchar(50) • UserStreet- nvarchar(50)
U8L2.2-2 • UserCity – nvarchar(50) • UserZip – nvarchar(10) • UserState – nchar(2) • UserPhone – nvarchar(50) • UserPasswordRequest – nvarchar(50) No fields should allow nulls except the Password field • Save the table as RegistrationData • Create a new web page – YourlastnameU8L22.aspx
U8L2.2-3 • Add an H2 heading: “Creating customers and adding them to the ASP.NET membership database” • Under the heading add a message “If you are already registered with us, please click the login button above. If you would like to register, please click the Register link below.” • Add a TextBox to your page • Change its ID to txtCurrentUser • Set its Visible property = False • Add a DetailsView below the TextBox • Change the ID to dvRegistration You will see what we are going to do with this TextBox later.
U8L2.2-4 • Create a DataSource called sdsRegistration • Select your new RegistrationData table • Select all fields from the table, one at a time • Click the Where… button • Set Column to UserEmail • Set Operator to = • Set Source to Control • Select ControlID = txtCurrentUser • Click Add and OK • From the Configure the Select Statement window, click Advanced… • Click Generate Insert, Update, … and then click OK • Click Next, then Finish
U8L2.2-5 • Click Refresh Schema from the DetailsView’s smart menu • Set the width of dvRegistration to 300px • Click Auto Format and select an appropriate format • Click the Enable Editing and Inserting check boxes • Edit Fields • Change headings to be easier to read • i.e. First Name instead of FirstName
U8L2.2-6 • Convert all fields to Templates and then click OK • Click Edit Templates from the DetailsView’s smart menu • Add required field validators to ALL edit and insert fields. • Set the Text of each to * and the ErrorMessage to something appropriate • Put all update validators in an Update validation group • Put all insert validators in an Insert validation group • Add a Regular Expression Validator to the email field (both insert and update templates) • Click the ValidationExpression property • Click … • Select Internet e-mail address
U8L2.2-7 • Select the Password field (in my setup it is field #9) • Delete the TextBox from the EditItem Template • In the InsertItem Template • Click after the TextBox (and validators if you have them in) • Press Enter • Add a new TextBox • Add a required field validator to the new TextBox • Add a compare validator to the new TextBox • Set the ControlToCompare to the first TextBox • Set the TextMode of both password TextBoxes to Password • Select the last field, the one with the new and edit buttons • Add a ValidationSummary to the EditItem Template • Set the ValidationGroup to Edit • Set ShowMessageBox to True and ShowSummary to False • Set the ValidationGroup of the Edit LinkButton to Edit
U8L2.2-8 • Add a ValidationSummary to the InsertItem Template • Set the ValidationGroup to Insert • Set ShowMessageBox to True and ShowSummary to False • Set the ValidationGroup of the Insert LinkButton to Insert • Select the EmptyData Template • Add a LinkButton to the template • Change its ID to lbRegister • Change its Text to Register • Change its CommandName to New • Click End Template Editing
U8L2.2-9 • We are going to save the user’s password in the membership database, not this table so we need to edit the data source • Select the registration DataSource • In the Properties window, select the InsertQuery and then click the … button • The Command and Parameter Editor should show an Insert statement something like this • Since we don’t want to save the Password we need to remove it from both the list of fields and the list of values as shown here
U8L2.2-10 Be sure that you delete the commas that were before the field name and the parameter name! • After removing the password information the query should look like this • You no longer need the @UserPasswordRequest parameter so delete it from the Parameter list • Click on UserPasswordRequest • Click the delete button (the X) and then click OK
U8L2.2-11 • Select UpdateQuery from the sdsRegistration properties • Delete the part of the query that updates the password and also delete the password parameter • When you are done click OK
U8L2.2-12 • If you have done everything correctly you should be able to insert people into the Registration Database now so lets try it • Run the page • Click the Register button (link) • Fix any errors you find and then test the validators • Try inserting a record with no data • Try inserting a record with an bad email address • Try entering different passwords • Once you receive no errors and it looks like the data was entered • Close the page • Switch to the Database Explorer • Select the RegistrationData table and Show Table Data • Verify that the person you entered is there with no password
U8L2.2-13 • Delete the user you just created • Click the right facing arrow on the left side of the table to select the row • Press the Delete key • Click on Yes • Close the data window
U8L2.2-14 • Add a user to the membership database at the same time s/he is added to RegistrationData • First, we need a place to display a message so • Add a Label after sdsRegistration • Change the ID to lblMessage • Change the ForeColor to Red • Delete the Text • Select dvRegistration • Click the Events icon ( ) on the Properties window • Double-click next to ItemInserting This event occurs just before the data is sent to the database to be inserted
U8L2.2-15 • Add the following namespace at the top of the page … • Enter the code first seen on slide #6 – Event processing methods, in the ItemInserting method This is new and says to cancel the current operation, insert, if we were unable to insert the user in the membership system.
U8L2.2-16 • Switch back to the aspx page, select dvRegistration, click the Event icon and double click on ItemInserted • This event happens after the database call and gives us a way to see if anything bad happened • Add the code first show on slide #8 – Testing for an Exception
U8L2.2-17 • Try running the page again • Add a new user • Do you get an error message? • InvalidPassword may mean the password is too short • DuplicateUserName means that user is already in the membership system • If successful, try to login as that user • Try to add the same user, the same email, a second time • Did you get an error message or a crash? • Does the error message hang around when it shouldn’t? • Add a line that says to your Page_Load method.
U8L2.2-18 • Allow the user to edit most of their information • Need a way to select the current user and display registration data in dvRegistration • Remember that the DetailsView select statement is linked to the contents of the TextBox, txtCurrentUser • We can determine the ID of the current user with a special object called the HttpContext. The following line gets the Name of the user and copies it into the txtCurrentUser textbox • Put this line of code in your Page_Load • Run the page, login with the user you created • Y ou should see, and be able to edit, most of the Registration data
U8L2.2-19 • Link you U8L22 page to your class page • Copy everything back to ASPNET • Run the application from ASPNET, starting with your Profile page to be sure it all works • Post a link to you ASPNET homepage in the dropbox