Membership and Administration
by Erik Reitan
Download Wingtip Toys Sample Project (C#) or Download E-book (PDF)
This tutorial series will teach you the basics of building an ASP.NET Web Forms application using ASP.NET 4.5 and Microsoft Visual Studio Express 2013 for Web. A Visual Studio 2013 project with C# source code is available to accompany this tutorial series.
This tutorial shows you how to update the Wingtip Toys sample application to add a custom role and use ASP.NET Identity. It also shows you how to implement an administration page from which the user with a custom role can add and remove products from the website.
ASP.NET Identity is the membership system used to build ASP.NET web application and is available in ASP.NET 4.5. ASP.NET Identity is used in the Visual Studio 2013 Web Forms project template, as well as the templates for ASP.NET MVC, ASP.NET Web API, and ASP.NET Single Page Application. You can also specifically install the ASP.NET Identity system using NuGet when you start with an empty Web application. However, in this tutorial series you use the Web Formsprojecttemplate, which includes the ASP.NET Identity system. ASP.NET Identity makes it easy to integrate user-specific profile data with application data. Also, ASP.NET Identity allows you to choose the persistence model for user profiles in your application. You can store the data in a SQL Server database or another data store, including NoSQL data stores such as Windows Azure Storage Tables.
This tutorial builds on the previous tutorial titled “Checkout and Payment with PayPal” in the Wingtip Toys tutorial series.
What you’ll learn:
- How to use code to add a custom role and a user to the application.
- How to restrict access to the administration folder and page.
- How to provide navigation for the user that belongs to the custom role.
- How to use model binding to populate a DropDownList control with product categories.
- How to upload a file to the web application using the FileUpload control.
- How to use validation controls to implement input validation.
- How to add and remove products from the application.
These features are included in the tutorial:
- ASP.NET Identity
- Configuration and Authorization
- Model Binding
- Unobtrusive Validation
ASP.NET Web Forms provides membership capabilities. By using the default template, you have built-in membership functionality that you can immediately use when the application runs. This tutorial shows you how to use ASP.NET Identity to add a custom role and assign a user to that role. You will learn how to restrict access to the administration folder. You’ll add a page to the administration folder that allows a user with a custom role to add and remove products, and to preview a product after it has been added.
Adding a Custom Role
Using ASP.NET Identity, you can add a custom role and assign a user to that role using code.
- In Solution Explorer, right-click on the Logic folder and create a new class.
- Name the new class RoleActions.cs.
Modify the code so that it appears as follows:
[!code-csharpMain]1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5:
6: namespace WingtipToys.Logic
7: {
8: internal class RoleActions
9: {
10: }
11: }
- In Solution Explorer, open the Global.asax.cs file.
Modify the Global.asax.cs file by adding the code highlighted in yellow so that it appears as follows:
[!code-csharpMain]1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Optimization;
6: using System.Web.Routing;
7: using System.Web.Security;
8: using System.Web.SessionState;
9: using System.Data.Entity;
10: using WingtipToys.Models;
11: using WingtipToys.Logic;
12:
13: namespace WingtipToys
14: {
15: public class Global : HttpApplication
16: {
17: void Application_Start(object sender, EventArgs e)
18: {
19: // Code that runs on application startup
20: RouteConfig.RegisterRoutes(RouteTable.Routes);
21: BundleConfig.RegisterBundles(BundleTable.Bundles);
22:
23: // Initialize the product database.
24: Database.SetInitializer(new ProductDatabaseInitializer());
25:
26: // Create the custom role and user.
27: RoleActions roleActions = new RoleActions();
28: roleActions.AddUserAndRole();
29: }
30: }
31: }
- Notice that
AddUserAndRole
is underlined in red. Double-click the AddUserAndRole code.
The letter “A” at the beginning of the highlighted method will be underlined. Hover over the letter “A” and click the UI that allows you to generate a method stub for the
AddUserAndRole
method.- Click the option titled:
Generate method stub for "AddUserAndRole" in "WingtipToys.Logic.RoleActions"
- Open the RoleActions.cs file from the Logic folder.
TheAddUserAndRole
method has been added to the class file. Modify the RoleActions.cs file by removing the
NotImplementedeException
and adding the code highlighted in yellow, so that it appears as follows:[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using WingtipToys.Models;
6: using Microsoft.AspNet.Identity;
7: using Microsoft.AspNet.Identity.EntityFramework;
8:
9: namespace WingtipToys.Logic
10: {
11: internal class RoleActions
12: {
13: internal void AddUserAndRole()
14: {
15: // Access the application context and create result variables.
16: Models.ApplicationDbContext context = new ApplicationDbContext();
17: IdentityResult IdRoleResult;
18: IdentityResult IdUserResult;
19:
20: // Create a RoleStore object by using the ApplicationDbContext object.
21: // The RoleStore is only allowed to contain IdentityRole objects.
22: var roleStore = new RoleStore<IdentityRole>(context);
23:
24: // Create a RoleManager object that is only allowed to contain IdentityRole objects.
25: // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
26: var roleMgr = new RoleManager<IdentityRole>(roleStore);
27:
28: // Then, you create the "canEdit" role if it doesn't already exist.
29: if (!roleMgr.RoleExists("canEdit"))
30: {
31: IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" });
32: }
33:
34: // Create a UserManager object based on the UserStore object and the ApplicationDbContext
35: // object. Note that you can create new objects and use them as parameters in
36: // a single line of code, rather than using multiple lines of code, as you did
37: // for the RoleManager object.
38: var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
39: var appUser = new ApplicationUser
40: {
41: UserName = "canEditUser@wingtiptoys.com",
42: Email = "canEditUser@wingtiptoys.com"
43: };
44: IdUserResult = userMgr.Create(appUser, "Pa$$word1");
45:
46: // If the new "canEdit" user was successfully created,
47: // add the "canEdit" user to the "canEdit" role.
48: if (!userMgr.IsInRole(userMgr.FindByEmail("canEditUser@wingtiptoys.com").Id, "canEdit"))
49: {
50: IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("canEditUser@wingtiptoys.com").Id, "canEdit");
51: }
52: }
53: }
54: }
The above code first establishes a database context for the membership database. The membership database is also stored as an .mdf file in the App_Data folder. You will be able to view this database once the first user has signed in to this web application.
[!NOTE]
If you wish to store the membership data along with the product data, you can consider using the same DbContext that you used to store the product data in the above code.
The internal keyword is an access modifier for types (such as classes) and type members (such as methods or properties). Internal types or members are accessible only within files contained in the same assembly (.dll file). When you build your application, an assembly file (.dll) is created that contains the code that is executed when you run your application.
A RoleStore
object, which provides role management, is created based on the database context.
[!NOTE]
Notice that when the
RoleStore
object is created it uses a GenericIdentityRole
type. This means that theRoleStore
is only allowed to containIdentityRole
objects. Also by using Generics, resources in memory are handled better.
Next, the RoleManager
object, is created based on the RoleStore
object that you just created. the RoleManager
object exposes role related API which can be used to automatically save changes to the RoleStore
. The RoleManager
is only allowed to contain IdentityRole
objects because the code uses the <IdentityRole>
Generic type.
You call the RoleExists
method to determine if the “canEdit” role is present in the membership database. If it is not, you create the role.
Creating the UserManager
object appears to be more complicated than the RoleManager
control, however it is nearly the same. It is just coded on one line rather than several. Here, the parameter that you are passing is instantiating as a new object contained in the parenthesis.
Next you create the “canEditUser” user by creating a new ApplicationUser
object. Then, if you successfully create the user, you add the user to the new role.
[!NOTE]
The error handling will be updated during the “ASP.NET Error Handling” tutorial later in this tutorial series.
The next time the application starts, the user named “canEditUser” will be added as the role named “canEdit” of the application. Later in this tutorial, you will login as the “canEditUser” user to display additional capabilities that you will added during this tutorial. For API details about ASP.NET Identity, see the Microsoft.AspNet.Identity Namespace. For additional details about initializing the ASP.NET Identity system, see the AspnetIdentitySample.
Restricting Access to the Administration Page
The Wingtip Toys sample application allows both anonymous users and logged-in users to view and purchase products. However, the logged-in user that has the custom “canEdit” role can access a restricted page in order to add and remove products.
Add an Administration Folder and Page
Next, you will create a folder named Admin for the “canEditUser” user belonging to the custom role of the Wingtip Toys sample application.
- Right-click the project name (Wingtip Toys) in Solution Explorer and select Add -> New Folder.
- Name the new folder Admin.
- Right-click the Admin folder and then select Add -> New Item.
The Add New Item dialog box is displayed. - Select the Visual C#-> Web templates group on the left. From the middle list, select Web Form with Master Page,name it AdminPage.aspx, and then select Add.
- Select the Site.Master file as the master page, and then choose OK.
Add a Web.config File
By adding a Web.config file to the Admin folder, you can restrict access to the page contained in the folder.
- Right-click the Admin folder and select Add -> New Item.
The Add New Item dialog box is displayed. - From the list of Visual C# web templates, select Web Configuration Filefrom the middle list, accept the default name of Web.config, and then select Add.
Replace the existing XML content in the Web.config file with the following:
[!code-xmlMain]
1: <?xml version="1.0"?>
2: <configuration>
3: <system.web>
4: <authorization>
5: <allow roles="canEdit"/>
6: <deny users="*"/>
7: </authorization>
8: </system.web>
9: </configuration>
Save the Web.config file. The Web.config file specifies that only user belonging to the “canEdit” role of the application can access the page contained in the Admin folder.
Including Custom Role Navigation
To enable the user of the custom “canEdit” role to navigate to the administration section of the application, you must add a link to the Site.Master page. Only users that belong to the “canEdit” role will be able to see the Admin link and access the administration section.
- In Solution Explorer, find and open the Site.Master page.
To create a link for the user of the “canEdit” role, add the markup highlighted in yellow to the following unordered list
[!code-htmlMain]<ul>
element so that the list appears as follows:1: <ul class="nav navbar-nav">
2: <li><a runat="server" id="adminLink" visible="false"
3: href="~/Admin/AdminPage">Admin</a></li>
4: <li><a runat="server" href="~/">Home</a></li>
5: <li><a runat="server" href="~/About">About</a></li>
6: <li><a runat="server" href="~/Contact">Contact</a></li>
7: <li><a runat="server" href="~/ProductList">Products</a></li>
8: <li><a runat="server" href="~/ShoppingCart"
9: ID="cartCount"> </a></li>
10: </ul>
Open the Site.Master.cs file. Make the Admin link visible only to the “canEditUser” user by adding the code highlighted in yellow to the
Page_Load
handler. ThePage_Load
handler will appear as follows:[!code-csharpMain]
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if (HttpContext.Current.User.IsInRole("canEdit"))
4: {
5: adminLink.Visible = true;
6: }
7: }
When the page loads, the code checks whether the logged-in user has the role of “canEdit”. If the user belongs to the “canEdit” role, the span element containing the link to the AdminPage.aspx page (and consequently the link inside the span) is made visible.
Enabling Product Administration
So far, you have created the “canEdit” role and added an “canEditUser” user, an administration folder, and an administration page. You have set access rights for the administration folder and page, and have added a navigation link for the user of the “canEdit” role to the application. Next, you will add markup to the AdminPage.aspx page and code to the AdminPage.aspx.cs code-behind file that will enable the user with the “canEdit” role to add and remove products.
- In Solution Explorer, open the AdminPage.aspx file from the Admin folder.
Replace the existing markup with the following:
[!code-aspxMain]1: <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AdminPage.aspx.cs" Inherits="WingtipToys.Admin.AdminPage" %>
2: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
3: <h1>Administration</h1>
4: <hr />
5: <h3>Add Product:</h3>
6: <table>
7: <tr>
8: <td><asp:Label ID="LabelAddCategory" runat="server">Category:</asp:Label></td>
9: <td>
10: <asp:DropDownList ID="DropDownAddCategory" runat="server"
11: ItemType="WingtipToys.Models.Category"
12: SelectMethod="GetCategories" DataTextField="CategoryName"
13: DataValueField="CategoryID" >
14: </asp:DropDownList>
15: </td>
16: </tr>
17: <tr>
18: <td><asp:Label ID="LabelAddName" runat="server">Name:</asp:Label></td>
19: <td>
20: <asp:TextBox ID="AddProductName" runat="server"></asp:TextBox>
21: <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="* Product name required." ControlToValidate="AddProductName" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
22: </td>
23: </tr>
24: <tr>
25: <td><asp:Label ID="LabelAddDescription" runat="server">Description:</asp:Label></td>
26: <td>
27: <asp:TextBox ID="AddProductDescription" runat="server"></asp:TextBox>
28: <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Text="* Description required." ControlToValidate="AddProductDescription" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
29: </td>
30: </tr>
31: <tr>
32: <td><asp:Label ID="LabelAddPrice" runat="server">Price:</asp:Label></td>
33: <td>
34: <asp:TextBox ID="AddProductPrice" runat="server"></asp:TextBox>
35: <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Text="* Price required." ControlToValidate="AddProductPrice" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
36: <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Text="* Must be a valid price without $." ControlToValidate="AddProductPrice" SetFocusOnError="True" Display="Dynamic" ValidationExpression="^[0-9]*(\.)?[0-9]?[0-9]?$"></asp:RegularExpressionValidator>
37: </td>
38: </tr>
39: <tr>
40: <td><asp:Label ID="LabelAddImageFile" runat="server">Image File:</asp:Label></td>
41: <td>
42: <asp:FileUpload ID="ProductImage" runat="server" />
43: <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" Text="* Image path required." ControlToValidate="ProductImage" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
44: </td>
45: </tr>
46: </table>
47: <p></p>
48: <p></p>
49: <asp:Button ID="AddProductButton" runat="server" Text="Add Product" OnClick="AddProductButton_Click" CausesValidation="true"/>
50: <asp:Label ID="LabelAddStatus" runat="server" Text=""></asp:Label>
51: <p></p>
52: <h3>Remove Product:</h3>
53: <table>
54: <tr>
55: <td><asp:Label ID="LabelRemoveProduct" runat="server">Product:</asp:Label></td>
56: <td><asp:DropDownList ID="DropDownRemoveProduct" runat="server" ItemType="WingtipToys.Models.Product"
57: SelectMethod="GetProducts" AppendDataBoundItems="true"
58: DataTextField="ProductName" DataValueField="ProductID" >
59: </asp:DropDownList>
60: </td>
61: </tr>
62: </table>
63: <p></p>
64: <asp:Button ID="RemoveProductButton" runat="server" Text="Remove Product" OnClick="RemoveProductButton_Click" CausesValidation="false"/>
65: <asp:Label ID="LabelRemoveStatus" runat="server" Text=""></asp:Label>
66: </asp:Content>
- Next, open the AdminPage.aspx.cs code-behind file by right-clicking the AdminPage.aspx and clicking View Code.
Replace the existing code in the AdminPage.aspx.cs code-behind file with the following code:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using WingtipToys.Models;
8: using WingtipToys.Logic;
9:
10: namespace WingtipToys.Admin
11: {
12: public partial class AdminPage : System.Web.UI.Page
13: {
14: protected void Page_Load(object sender, EventArgs e)
15: {
16: string productAction = Request.QueryString["ProductAction"];
17: if (productAction == "add")
18: {
19: LabelAddStatus.Text = "Product added!";
20: }
21:
22: if (productAction == "remove")
23: {
24: LabelRemoveStatus.Text = "Product removed!";
25: }
26: }
27:
28: protected void AddProductButton_Click(object sender, EventArgs e)
29: {
30: Boolean fileOK = false;
31: String path = Server.MapPath("~/Catalog/Images/");
32: if (ProductImage.HasFile)
33: {
34: String fileExtension = System.IO.Path.GetExtension(ProductImage.FileName).ToLower();
35: String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
36: for (int i = 0; i < allowedExtensions.Length; i++)
37: {
38: if (fileExtension == allowedExtensions[i])
39: {
40: fileOK = true;
41: }
42: }
43: }
44:
45: if (fileOK)
46: {
47: try
48: {
49: // Save to Images folder.
50: ProductImage.PostedFile.SaveAs(path + ProductImage.FileName);
51: // Save to Images/Thumbs folder.
52: ProductImage.PostedFile.SaveAs(path + "Thumbs/" + ProductImage.FileName);
53: }
54: catch (Exception ex)
55: {
56: LabelAddStatus.Text = ex.Message;
57: }
58:
59: // Add product data to DB.
60: AddProducts products = new AddProducts();
61: bool addSuccess = products.AddProduct(AddProductName.Text, AddProductDescription.Text,
62: AddProductPrice.Text, DropDownAddCategory.SelectedValue, ProductImage.FileName);
63: if (addSuccess)
64: {
65: // Reload the page.
66: string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
67: Response.Redirect(pageUrl + "?ProductAction=add");
68: }
69: else
70: {
71: LabelAddStatus.Text = "Unable to add new product to database.";
72: }
73: }
74: else
75: {
76: LabelAddStatus.Text = "Unable to accept file type.";
77: }
78: }
79:
80: public IQueryable GetCategories()
81: {
82: var _db = new WingtipToys.Models.ProductContext();
83: IQueryable query = _db.Categories;
84: return query;
85: }
86:
87: public IQueryable GetProducts()
88: {
89: var _db = new WingtipToys.Models.ProductContext();
90: IQueryable query = _db.Products;
91: return query;
92: }
93:
94: protected void RemoveProductButton_Click(object sender, EventArgs e)
95: {
96: using (var _db = new WingtipToys.Models.ProductContext())
97: {
98: int productId = Convert.ToInt16(DropDownRemoveProduct.SelectedValue);
99: var myItem = (from c in _db.Products where c.ProductID == productId select c).FirstOrDefault();
100: if (myItem != null)
101: {
102: _db.Products.Remove(myItem);
103: _db.SaveChanges();
104:
105: // Reload the page.
106: string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
107: Response.Redirect(pageUrl + "?ProductAction=remove");
108: }
109: else
110: {
111: LabelRemoveStatus.Text = "Unable to locate product.";
112: }
113: }
114: }
115: }
116: }
In the code that you entered for the AdminPage.aspx.cs code-behind file, a class called AddProducts
does the actual work of adding products to the database. This class doesn’t exist yet, so you will create it now.
- In Solution Explorer, right-click the Logic folder and then select Add -> New Item.
The Add New Item dialog box is displayed. - Select the Visual C# -> Code templates group on the left. Then, select Classfrom the middle list and name it AddProducts.cs.
The new class file is displayed. Replace the existing code with the following:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using WingtipToys.Models;
6:
7: namespace WingtipToys.Logic
8: {
9: public class AddProducts
10: {
11: public bool AddProduct(string ProductName, string ProductDesc, string ProductPrice, string ProductCategory, string ProductImagePath)
12: {
13: var myProduct = new Product();
14: myProduct.ProductName = ProductName;
15: myProduct.Description = ProductDesc;
16: myProduct.UnitPrice = Convert.ToDouble(ProductPrice);
17: myProduct.ImagePath = ProductImagePath;
18: myProduct.CategoryID = Convert.ToInt32(ProductCategory);
19:
20: using (ProductContext _db = new ProductContext())
21: {
22: // Add product to DB.
23: _db.Products.Add(myProduct);
24: _db.SaveChanges();
25: }
26: // Success.
27: return true;
28: }
29: }
30: }
The AdminPage.aspx page allows the user belonging to the “canEdit” role to add and remove products. When a new product is added, the details about the product are validated and then entered into the database. The new product is immediately available to all users of the web application.
Unobtrusive Validation
The product details that the user provides on the AdminPage.aspx page are validated using validation controls (RequiredFieldValidator
and RegularExpressionValidator
). These controls automatically use unobtrusive validation. Unobtrusive validation allows the validation controls to use JavaScript for client-side validation logic, which means the page does not require a trip to the server to be validated. By default, unobtrusive validation is included in the Web.config file based on the following configuration setting:
[!code-xmlMain]
1: <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
Regular Expressions
The product price on the AdminPage.aspx page is validated using a RegularExpressionValidator control. This control validates whether the value of the associated input control (the “AddProductPrice” TextBox) matches the pattern specified by the regular expression. A regular expression is a pattern-matching notation that enables you to quickly find and match specific character patterns. The RegularExpressionValidator control includes a property named ValidationExpression
that contains the regular expression used to validate price input, as shown below:
[!code-aspxMain]
1: <asp:RegularExpressionValidator
2: ID="RegularExpressionValidator1" runat="server"
3: Text="* Must be a valid price without $." ControlToValidate="AddProductPrice"
4: SetFocusOnError="True" Display="Dynamic"
5: ValidationExpression="^[0-9]*(\.)?[0-9]?[0-9]?$">
6: </asp:RegularExpressionValidator>
FileUpload Control
In addition to the input and validation controls, you added the FileUpload control to the AdminPage.aspx page. This control provides the capability to upload files. In this case, you are only allowing image files to be uploaded. In the code-behind file (AdminPage.aspx.cs), when the AddProductButton
is clicked, the code checks the HasFile
property of the FileUpload control. If the control has a file and if the file type (based on file extension) is allowed, the image is saved to the Images folder and the Images/Thumbs folder of the application.
Model Binding
Earlier in this tutorial series you used model binding to populate a ListView control, a FormsView control, a GridView control, and a DetailView control. In this tutorial, you use model binding to populate a DropDownList control with a list of product categories.
The markup that you added to the AdminPage.aspx file contains a DropDownList control called DropDownAddCategory
:
[!code-aspxMain]
1: <asp:DropDownList ID="DropDownAddCategory" runat="server"
2: ItemType="WingtipToys.Models.Category"
3: SelectMethod="GetCategories" DataTextField="CategoryName"
4: DataValueField="CategoryID" >
5: </asp:DropDownList>
You use model binding to populate this DropDownList by setting the ItemType
attribute and the SelectMethod
attribute. The ItemType
attribute specifies that you use the WingtipToys.Models.Category
type when populating the control. You defined this type at the beginning of this tutorial series by creating the Category
class (shown below). The Category
class is in the Models folder inside the Category.cs file.
[!code-csharpMain]
1: public class Category
2: {
3: [ScaffoldColumn(false)]
4: public int CategoryID { get; set; }
5:
6: [Required, StringLength(100), Display(Name = "Name")]
7: public string CategoryName { get; set; }
8:
9: [Display(Name = "Product Description")]
10: public string Description { get; set; }
11:
12: public virtual ICollection<Product> Products { get; set; }
13: }
The SelectMethod
attribute of the DropDownList control specifies that you use the GetCategories
method (shown below) that is included in the code-behind file (AdminPage.aspx.cs).
[!code-csharpMain]
1: public IQueryable GetCategories()
2: {
3: var _db = new WingtipToys.Models.ProductContext();
4: IQueryable query = _db.Categories;
5: return query;
6: }
This method specifies that an IQueryable
interface is used to evaluate a query against a Category
type. The returned value is used to populate the DropDownList in the markup of the page (AdminPage.aspx).
The text displayed for each item in the list is specified by setting the DataTextField
attribute. The DataTextField
attribute uses the CategoryName
of the Category
class (shown above) to display each category in the DropDownList control. The actual value that is passed when an item is selected in the DropDownList control is based on the DataValueField
attribute. The DataValueField
attribute is set to the CategoryID
as define in the Category
class (shown above).
How the Application Will Work
When the user belonging to the “canEdit” role navigates to the page for the first time, the DropDownAddCategory
DropDownList control is populated as described above. The DropDownRemoveProduct
DropDownList control is also populated with products using the same approach. The user belonging to the “canEdit” role selects the category type and adds product details (Name, Description, Price, and Image File). When the user belonging to the “canEdit” role clicks the Add Product button, the AddProductButton_Click
event handler is triggered. The AddProductButton_Click
event handler located in the code-behind file (AdminPage.aspx.cs) checks the image file to make sure it matches the allowed file types (.gif, .png, .jpeg, or .jpg). Then, the image file is saved into a folder of the Wingtip Toys sample application. Next, the new product is added to the database. To accomplish adding a new product, a new instance of the AddProducts
class is created and named products. The AddProducts
class has a method named AddProduct
, and the products object calls this method to add products to the database.
[!code-csharpMain]
1: // Add product data to DB.
2: AddProducts products = new AddProducts();
3: bool addSuccess = products.AddProduct(AddProductName.Text, AddProductDescription.Text,
4: AddProductPrice.Text, DropDownAddCategory.SelectedValue, ProductImage.FileName);
If the code successfully adds the new product to the database, the page is reloaded with the query string value ProductAction=add
.
[!code-csharpMain]
1: Response.Redirect(pageUrl + "?ProductAction=add");
When the page reloads, the query string is included in the URL. By reloading the page, the user belonging to the “canEdit” role can immediately see the updates in the DropDownList controls on the AdminPage.aspx page. Also, by including the query string with the URL, the page can display a success message to the user belonging to the “canEdit” role.
When the AdminPage.aspx page reloads, the Page_Load
event is called.
[!code-csharpMain]
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: string productAction = Request.QueryString["ProductAction"];
4: if (productAction == "add")
5: {
6: LabelAddStatus.Text = "Product added!";
7: }
8:
9: if (productAction == "remove")
10: {
11: LabelRemoveStatus.Text = "Product removed!";
12: }
13: }
The Page_Load
event handler checks the query string value and determines whether to show a success message.
Running the Application
You can run the application now to see how you can add, delete, and update items in the shopping cart. The shopping cart total will reflect the total cost of all items in the shopping cart.
- In Solution Explorer, press F5 to run the Wingtip Toys sample application.
The browser opens and shows the Default.aspx page. Click the Log in link at the top of the page.
The Login.aspx page is displayed. 3. Use the following user name and password:
User name: canEditUser@wingtiptoys.com
Password: Pa$$word1
![Membership and Administration - Log In Page](membership-and-administration/_static/image3.png)
- Click the Log in button near the bottom of the page.
At the top of the next page, select the Admin link to navigate to the AdminPage.aspx page.
To test the input validation, click the Add Product button without adding any product details.
Notice that the required field messages are displayed. 7. Add the details for a new product, and then click the Add Product button.
![Membership and Administration - Add Product](membership-and-administration/_static/image6.png)
Select Products from the top navigation menu to view the new product you added.
- Click the Admin link to return to the administration page.
- In the Remove Product section of the page, select the new product you added in the DropDownListBox.
Click the Remove Product button to remove the new product from the application.
- Select Products from the top navigation menu to confirm that the product has been removed.
Click Log off to exist administration mode.
Notice that the top navigation pane no longer shows the Admin menu item.
Summary
In this tutorial, you added a custom role and a user belonging to the custom role, restricted access to the administration folder and page, and provided navigation for the user belonging to the custom role. You used model binding to populate a DropDownList control with data. You implemented the FileUpload control and validation controls. Also, you have learned how to add and remove products from a database. In the next tutorial, you’ll learn how to implement ASP.NET routing.
Additional Resources
Web.config - authorization Element
ASP.NET Identity
Deploy a Secure ASP.NET Web Forms App with Membership, OAuth, and SQL Database to an Azure Web Site
Microsoft Azure - Free Trial
|