Introduction
In this article, you will learn how to complete the album's information and leearn how to use the forms authentication to manage the albums.
Details of Album
First of all, let's begin with the details page. When we click one of the albums, we should enter the details page, such as the top selling albums in the index page. In the last article, we did not give the real link for the albums, just used JavaScript.
- <ul id="album-list">
- @foreach (var album in Model)
- {
- <li>
- <a href="javascript:;">
- <img alt="@album.Title" src="@album.AlbumArtUrl" />
- <span>@album.Title</span>
- </a>
- </li>
- }
- </ul>
Now, let's use the real link to replace JavaScript that is same as the MVC MusicStore.
- <a href="/store/details/@album.AlbumId">
- <img alt="@album.Title" src="@album.AlbumArtUrl" />
- <span>@album.Title</span>
- </a>
The link means that we should visit the details page via a link which looks like http://domain.com/store/details/id.
We should add something new to the constructor of StoreModule, so that we can return the valid view of the user.
- Get["details/{id:int}"] = _ =>
- {
- int id = 0;
- if (int.TryParse(_.id, out id))
- {
- string cmd = "public.get_album_details_by_aid";
- var album = DBHelper.QueryFirstOrDefault<AlbumDetailsViewModel>(cmd, new
- {
- aid = id
- }, null, null, CommandType.StoredProcedure);
- if (album != null)
- {
- return View["Details", album];
- }
- }
- return View["Shared/Error"];
- };
Pay attention to the route of the details where we limit the parameter Id that can only be an integer. This is the Route Segment constraints of Nancy. We can use _.id to get its value, then visit the database to find out the first row of the data.
What about the view of the details page?
- @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<NancyMusicStore.ViewModels.AlbumDetailsViewModel>
- @{
- ViewBag.Title = "Album - " + Model.Title;
- }
- <h2>@Model.Title</h2>
- <p>
- <img alt="@Model.Title" src="@Model.AlbumArtUrl" />
- </p>
- <div id="album-details">
- <p>
- <em>Genre:</em>
- @Model.GenreName
- </p>
- <p>
- <em>Artist:</em>
- @Model.ArtistName
- </p>
- <p>
- <em>Price:</em>
- @String.Format("{0:F}", Model.Price)
- </p>
- <p class="button">
- <a href="/ShoppingCart/AddToCart/@Model.AlbumId">Add to cart</a>
- </p>
- </div>
It's very simple. Just show little information of the album. Let's run the Application and click one of the top selling albums in the index page. Then, you can see something like the screenshot, as shown below.
Genres of Albums
In the layout page, we also do not use the real link to take place of JavaScript, so we should replace it at first.
- $("#categories").append('<li><a href="/store/browse/">' + res[i].name + '</a></li>');
We also add something new to the constructor of StoreModule, so that we can browse albums of some genres.
- Get["browse/{genre}"] = _ =>
- {
- string genre = _.genre;
- ViewBag.Genre = genre;
- string cmd = "public.get_album_list_by_gname";
- var albumList = DBHelper.Query<AlbumListViewModel>(cmd, new
- {
- gname = genre
- }, null, true, null, CommandType.StoredProcedure).ToList();
- return View["Browse", albumList];
- };
The view of this HTTP request is very similar with the top selling albums. The difference between them is their number.
- @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<List<NancyMusicStore.ViewModels.AlbumListViewModel>>
- @{
- ViewBag.Title = "Browse Albums";
- }
- <div class="genre">
- <h3><em>@ViewBag.Genre</em> Albums</h3>
- <ul id="album-list">
- @foreach (var album in Model)
- {
- <li>
- <a href="/store/details/@album.AlbumId">
- <img alt="@album.Title" src="@album.AlbumArtUrl" />
- <span>@album.Title</span>
- </a>
- </li>
- }
- </ul>
- </div>
For example, here is the list view of Disco.
So far we have completed the details page and the list page. What we should do next is see how to manage the albums.
Management of The Albums
In MusicStore Project , the management of the albums is just CRUD. I will show you how to query and create in this article. As far as the update and delete goes, you can find them in the source code on my GitHub page.
Create a StoreManagerModule class in the Modules.
- using Nancy;
- using Nancy.ModelBinding;
- using Nancy.Security;
- using NancyMusicStore.Common;
- using NancyMusicStore.Models;
- using NancyMusicStore.ViewModels;
- using System;
- using System.Data;
-
- namespace NancyMusicStore.Modules
- {
- public class StoreManagerModule : NancyModule
- {
- public StoreManagerModule() : base("/storemanager")
- {
- Get["/"] = _ =>
- {
- string cmd = "get_all_albums";
- var list = DBHelper.Query<AlbumListViewModel>(cmd, null, null, true, null, CommandType.StoredProcedure);
- return View["Index", list];
- };
-
- Get["/create"] = _ =>
- {
- return View["Create"];
- };
-
- Post["/create"] = _ =>
- {
- var album = this.Bind<Album>();
-
- string cmd = "public.add_album";
- var res = DBHelper.ExecuteScalar(cmd, new
- {
- gid = album.GenreId,
- aid = album.AlbumId,
- t = album.Title,
- p = album.Price,
- aurl = album.AlbumArtUrl
- }, null, null, CommandType.StoredProcedure);
-
- if (Convert.ToInt32(res) > 0)
- {
- return Response.AsRedirect("/storemanager");
- }
- ViewBag.Err = "Some Error Occurred";
- return View["Create"];
- };
-
- Get["/details/{id:int}"] = _ =>{};
- Get["/edit/{id:int}"] = _ =>{};
- Post["/edit"] = _ =>{};
- Get["/delete/{id:int}"] = _ =>{};
- Post["/delete/{id:int}"] = _ =>{};
- Get["/getallgenres"] = _ =>{};
- Get["/getallartists"] = _ =>{};
- }
- }
- }
When we enter the index page of management, we will get a table of the albums. We query the result and return them in the view.
Here, the index page of the management is given below.
When we post a new album in the create view, the Post["/Create"] will deal with the request. We need to use another feature of Nancy - ModelBinding. The details of the album which we want to create will be bound to the parameter album. Now, we call the storeprocedure to create a new album in PostgreSQL.
Here, the create view is given below.
Now, the management is finished but everybody can update the details of the albums via the Admin link .
It's very unreasonable to think that everybody will be able to update the details of the albums. It should be updated by the user, who has already logged in. In MVC MusicStore, MemberShip is a good way to solve this problem. In NancyFX , Forms authentication is a good way as well.
Add a new appSetting in web.config to indicate the logon url.
- <add key="logonUrl" value="~/account/logon" />
Configuring the Forms authentication in CustomerBootstrapper class is given below.
- protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
- {
- base.RequestStartup(container, pipelines, context);
-
- var formsAuthConfiguration = new FormsAuthenticationConfiguration
- {
- RedirectUrl = ConfigHelper.GetAppSettingByKey("logonUrl"),
- UserMapper = container.Resolve<IUserMapper>(),
- };
- FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
- }
-
- protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
- {
- base.ConfigureRequestContainer(container, context);
- container.Register<IUserMapper, UserMapper>();
- }
We create an instance of formauthenticationconfiguration, whichindicates the redirected URL and the mapper of the user first. Now, we use the FormsAuthentication.Enable to enable the authentication.
Customer UserMapper is very important for the authentication. The implementation of the UserMapper demonstrates, as shown below.
- internal class UserMapper : IUserMapper
- {
- public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
- {
- string cmd = "public.get_user_by_userid";
- var user = DBHelper.QueryFirstOrDefault<SysUser>(cmd, new
- {
- uid = identifier.ToString()
- }, null, null, CommandType.StoredProcedure);
- return user == null
- ? null
- : new UserIdentity
- {
- UserName = user.SysUserName,
- Claims = new[] { "SystemUser" }
- };
- }
- }
We have completed the configuration of forms authentication and we must add the code given below in the constructor of StoreManagerModule class.
- this.RequiresAuthentication();
It is a little different with the Authorize Attribute, when we use ASP.NET MVC.
Now, it will ask us to login.
We can see the returnUrl parameter in the URL. It will help us to redirect after someone logs in.
Create a new module class named AccountModule to deal with logon and registration.
- Get["/logon"] = _ =>
- {
- var returnUrl = this.Request.Query["returnUrl"];
- ViewBag.returnUrl = returnUrl;
- return View["LogOn"];
- };
-
- Post["/logon"] = _ =>
- {
- var logonModel = this.Bind<LogOnModel>();
-
- string cmd = "public.get_user_by_name_and_password";
- var user = DBHelper.QueryFirstOrDefault<SysUser>(cmd, new
- {
- uname = logonModel.SysUserName,
- upwd = logonModel.SysUserPassword
- }, null, null, CommandType.StoredProcedure);
-
- if (user == null)
- {
- return View["LogOn"];
- }
- else
- {
- MigrateShoppingCart(user.SysUserName);
-
- var redirectUrl = string.IsNullOrWhiteSpace(logonModel.ReturnUrl) ? "/" : logonModel.ReturnUrl;
- return this.LoginAndRedirect(Guid.Parse(user.SysUserId), fallbackRedirectUrl: redirectUrl);
- }
- };
I stored the returnUrl in the ViewBag, when we open the login page. When someone posts a login request, the returnurl will be posted as a part of LogOnModel class and we use modelbinding again.
The details of LogOnModel are given below.
- public class LogOnModel
- {
- public string SysUserName { get; set; }
- public string SysUserPassword { get; set; }
- public string ReturnUrl { get; set; }
- }
What Next?
In my next article, I will go to complete the shopping cart.