From 8409e9518b1ee211485ced1481a70ceb5281f365 Mon Sep 17 00:00:00 2001 From: Praburaj Date: Fri, 23 May 2014 14:35:08 -0700 Subject: [PATCH] Catching up MusicStore app with code generated with latest templates --- MusicStore.sln | 14 +- .../Controllers/AccountController.cs | 7 - src/MusicStore/LocalConfig.json | 4 +- src/MusicStore/Models/IdentityModels.cs | 23 ++- src/MusicStore/Models/MusicStoreContext.cs | 22 ++- src/MusicStore/Models/SampleData.cs | 42 +++++- src/MusicStore/MusicStore.kproj | 8 +- src/MusicStore/Startup.cs | 132 ++++++++---------- .../Account/_ChangePasswordPartial.cshtml | 2 +- .../Views/Shared/_LoginPartial.cshtml | 4 +- src/MusicStore/project.json | 68 ++++----- test/E2ETests/E2ETests.kproj | 37 +++++ 12 files changed, 200 insertions(+), 163 deletions(-) create mode 100644 test/E2ETests/E2ETests.kproj diff --git a/MusicStore.sln b/MusicStore.sln index fef99b818b..201156ad69 100644 --- a/MusicStore.sln +++ b/MusicStore.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.21706.0 +VisualStudioVersion = 14.0.21722.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvcMusicStore", "src\MvcMusicStore\MvcMusicStore.csproj", "{25CE8290-EF24-4818-B009-68DC903163D3}" EndProject @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvcMusicStore.Spa", "src\Mv EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "MusicStore.Spa", "src\MusicStore.Spa\MusicStore.Spa.kproj", "{9BCEB29B-7E09-4B4C-A466-498EFC602331}" EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "E2ETests", "test\E2ETests\E2ETests.kproj", "{A319ACCE-060B-4385-9534-9F2202F6180E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -63,6 +65,16 @@ Global {9BCEB29B-7E09-4B4C-A466-498EFC602331}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9BCEB29B-7E09-4B4C-A466-498EFC602331}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9BCEB29B-7E09-4B4C-A466-498EFC602331}.Release|x86.ActiveCfg = Release|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Debug|x86.ActiveCfg = Debug|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Release|Any CPU.Build.0 = Release|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {A319ACCE-060B-4385-9534-9F2202F6180E}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/MusicStore/Controllers/AccountController.cs b/src/MusicStore/Controllers/AccountController.cs index 4bfa524bce..b98da81495 100644 --- a/src/MusicStore/Controllers/AccountController.cs +++ b/src/MusicStore/Controllers/AccountController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Security; using Microsoft.AspNet.Mvc; -using Microsoft.AspNet.Mvc.ModelBinding; using MusicStore.Models; using System.Security.Principal; using System.Threading.Tasks; @@ -24,8 +23,6 @@ namespace MusicStore.Controllers // // GET: /Account/Login [AllowAnonymous] - //Bug: https://github.com/aspnet/WebFx/issues/339 - [HttpGet] public IActionResult Login(string returnUrl=null) { ViewBag.ReturnUrl = returnUrl; @@ -63,8 +60,6 @@ namespace MusicStore.Controllers // // GET: /Account/Register [AllowAnonymous] - //Bug: https://github.com/aspnet/WebFx/issues/339 - [HttpGet] public IActionResult Register() { return View(); @@ -98,8 +93,6 @@ namespace MusicStore.Controllers // // GET: /Account/Manage - //Bug: https://github.com/aspnet/WebFx/issues/339 - [HttpGet] public IActionResult Manage(ManageMessageId? message=null) { ViewBag.StatusMessage = diff --git a/src/MusicStore/LocalConfig.json b/src/MusicStore/LocalConfig.json index 04a1af7dd1..275809424a 100644 --- a/src/MusicStore/LocalConfig.json +++ b/src/MusicStore/LocalConfig.json @@ -3,10 +3,10 @@ "DefaultAdminPassword": "YouShouldChangeThisPassword1!", "Data": { "DefaultConnection": { - "Connectionstring": "Server=(localdb)\\v11.0;Database=MusicStore;Trusted_Connection=True;MultipleActiveResultSets=true" + "Connectionstring": "Server=(localdb)\\v11.0;Database=MusicStore7;Trusted_Connection=True;MultipleActiveResultSets=true" }, "IdentityConnection": { - "Connectionstring": "Server=(localdb)\\v11.0;Database=MusicStoreIdentity;Trusted_Connection=True;MultipleActiveResultSets=true" + "Connectionstring": "Server=(localdb)\\v11.0;Database=MusicStoreIdentity7;Trusted_Connection=True;MultipleActiveResultSets=true" } } } \ No newline at end of file diff --git a/src/MusicStore/Models/IdentityModels.cs b/src/MusicStore/Models/IdentityModels.cs index b673f96706..d8ffbda9e8 100644 --- a/src/MusicStore/Models/IdentityModels.cs +++ b/src/MusicStore/Models/IdentityModels.cs @@ -1,25 +1,24 @@ using System; using Microsoft.AspNet.Identity.Entity; using Microsoft.Data.Entity; -using Microsoft.Framework.ConfigurationModel; +using Microsoft.Framework.DependencyInjection; namespace MusicStore.Models { public class ApplicationUser : User { } - public class ApplicationDbContext : IdentitySqlContext + public class ApplicationDbContext : IdentitySqlContext { - private readonly IConfiguration _configuration; - - public ApplicationDbContext(IServiceProvider serviceProvider, IConfiguration configuration) - : base(serviceProvider) + public ApplicationDbContext(IServiceProvider serviceProvider, IOptionsAccessor optionsAccessor) + : base(serviceProvider, optionsAccessor.Options.BuildConfiguration()) { - _configuration = configuration; - } - - protected override void OnConfiguring(DbContextOptions builder) - { - builder.UseSqlServer(_configuration.Get("Data:IdentityConnection:ConnectionString")); } } + + public class IdentityDbContextOptions : DbContextOptions + { + public string DefaultAdminUserName { get; set; } + + public string DefaultAdminPassword { get; set; } + } } \ No newline at end of file diff --git a/src/MusicStore/Models/MusicStoreContext.cs b/src/MusicStore/Models/MusicStoreContext.cs index b1faad3bfb..cc50687c3a 100644 --- a/src/MusicStore/Models/MusicStoreContext.cs +++ b/src/MusicStore/Models/MusicStoreContext.cs @@ -1,19 +1,16 @@ -using Microsoft.Framework.ConfigurationModel; +using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; -using Microsoft.Data.Entity.SqlServer; -using System; +using Microsoft.Framework.DependencyInjection; namespace MusicStore.Models { public class MusicStoreContext : DbContext { - private readonly IConfiguration _configuration; - - public MusicStoreContext(IServiceProvider serviceProvider, IConfiguration configuration) - : base(serviceProvider) + public MusicStoreContext(IServiceProvider serviceProvider, IOptionsAccessor optionsAccessor) + : base(serviceProvider, optionsAccessor.Options.BuildConfiguration()) { - _configuration = configuration; + } public DbSet Albums { get; set; } @@ -23,10 +20,6 @@ namespace MusicStore.Models public DbSet CartItems { get; set; } public DbSet OrderDetails { get; set; } - protected override void OnConfiguring(DbContextOptions builder) - { - builder.UseSqlServer(_configuration.Get("Data:DefaultConnection:ConnectionString")); - } protected override void OnModelCreating(ModelBuilder builder) { @@ -38,4 +31,9 @@ namespace MusicStore.Models builder.Entity().Key(o => o.OrderDetailId); } } + + public class MusicStoreDbContextOptions : DbContextOptions + { + + } } \ No newline at end of file diff --git a/src/MusicStore/Models/SampleData.cs b/src/MusicStore/Models/SampleData.cs index 0882dc6e63..3be8ce9c6f 100644 --- a/src/MusicStore/Models/SampleData.cs +++ b/src/MusicStore/Models/SampleData.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNet.Identity; using Microsoft.Data.Entity; using Microsoft.Data.Entity.SqlServer; using Microsoft.Framework.DependencyInjection; @@ -33,12 +35,19 @@ namespace MusicStore.Models public static async Task InitializeIdentityDatabaseAsync(IServiceProvider serviceProvider) { - using (var db = serviceProvider.GetService() as ApplicationDbContext) + using (var db = serviceProvider.GetService()) { var sqlServerDataStore = db.Configuration.DataStore as SqlServerDataStore; if (sqlServerDataStore != null) { - await db.Database.EnsureCreatedAsync(); + if (await db.Database.EnsureCreatedAsync()) + { + await CreateAdminUser(serviceProvider); + } + } + else + { + await CreateAdminUser(serviceProvider); } } } @@ -78,6 +87,35 @@ namespace MusicStore.Models } } + + /// + /// Creates a store manager user who can manage the inventory. + /// + /// + /// + private static async Task CreateAdminUser(IServiceProvider serviceProvider) + { + var options = serviceProvider.GetService>().Options; + //const string adminRole = "Administrator"; + + var userManager = serviceProvider.GetService>(); + // TODO: Identity SQL does not support roles yet + //var roleManager = serviceProvider.GetService(); + //if (!await roleManager.RoleExistsAsync(adminRole)) + //{ + // await roleManager.CreateAsync(new IdentityRole(adminRole)); + //} + + var user = await userManager.FindByNameAsync(options.DefaultAdminUserName); + if (user == null) + { + user = new ApplicationUser { UserName = options.DefaultAdminUserName }; + await userManager.CreateAsync(user, options.DefaultAdminPassword); + //await userManager.AddToRoleAsync(user, adminRole); + await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed")); + } + } + private static Album[] GetAlbums(string imgUrl, Dictionary genres, Dictionary artists) { var albums = new Album[] diff --git a/src/MusicStore/MusicStore.kproj b/src/MusicStore/MusicStore.kproj index 6d5385ef17..ce45ee8fd8 100644 --- a/src/MusicStore/MusicStore.kproj +++ b/src/MusicStore/MusicStore.kproj @@ -1,4 +1,4 @@ - + 12.0 @@ -35,8 +35,6 @@ - - @@ -88,10 +86,6 @@ - - - - diff --git a/src/MusicStore/Startup.cs b/src/MusicStore/Startup.cs index 6e43c9c14d..9f88fd4431 100644 --- a/src/MusicStore/Startup.cs +++ b/src/MusicStore/Startup.cs @@ -1,3 +1,4 @@ +using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Diagnostics; using Microsoft.AspNet.Http; @@ -9,99 +10,80 @@ using Microsoft.Data.Entity; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using MusicStore.Models; -using System; -using System.Security.Claims; -using System.Threading.Tasks; -public class Startup +namespace MusicStore { - public void Configure(IBuilder app) + public class Startup { - app.UseServices(services => + public void Configure(IBuilder app) { /* Adding IConfiguration as a service in the IoC to avoid instantiating Configuration again. - * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, - * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. + * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, + * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. */ var configuration = new Configuration(); configuration.AddJsonFile("LocalConfig.json"); configuration.AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. - services.AddInstance(configuration); - //Add all MVC related services to IoC. - services.AddMvc(); - - /*Add all EF related services to IoC.*/ - services.AddEntityFramework().AddSqlServer(); - services.AddTransient(); - - //Add all Identity related services to IoC. - services.AddTransient(); - services.AddIdentity(s => + app.UseServices(services => { - s.AddEntity(); + // Add EF services to the services container + services.AddEntityFramework() + .AddSqlServer(); + + services.AddScoped(); + + // Configure DbContext + services.SetupOptions(options => + { + options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername"); + options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword"); + options.UseSqlServer(configuration.Get("Data:IdentityConnection:ConnectionString")); + }); + + services.SetupOptions(options => + options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"))); + + // Add Identity services to the services container + services.AddIdentity() + .AddEntityFramework() + .AddHttpSignIn(); + + // Add MVC services to the services container + services.AddMvc(); }); - services.AddTransient>(); - }); + /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. + * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. + */ + app.UseErrorPage(ErrorPageOptions.ShowAll); - /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. - * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. - */ - app.UseErrorPage(ErrorPageOptions.ShowAll); + // Add static files to the request pipeline + app.UseStaticFiles(); - //Serves static files in the application. - app.UseFileServer(); + // Add cookie-based authentication to the request pipeline + app.UseCookieAuthentication(new CookieAuthenticationOptions + { + AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, + LoginPath = new PathString("/Account/Login"), + }); - app.UseCookieAuthentication(new CookieAuthenticationOptions() - { - AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, - LoginPath = new PathString("/Account/Login"), - }); + // Add MVC to the request pipeline + app.UseMvc(routes => + { + routes.MapRoute( + name: "default", + template: "{controller}/{action}/{id?}", + defaults: new { controller = "Home", action = "Index" }); - app.UseMvc(routes => - { - routes.MapRoute( - null, - "{controller}/{action}", - new { controller = "Home", action = "Index" }); - }); + routes.MapRoute( + name: "api", + template: "{controller}/{id?}"); + }); - //Populates the MusicStore sample data - SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); - SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait(); - - //Creates a Store manager user who can manage the store. - CreateAdminUser(app.ApplicationServices).Wait(); - } - - /// - /// Creates a store manager user who can manage the inventory. - /// - /// - /// - private async Task CreateAdminUser(IServiceProvider serviceProvider) - { - var configuration = serviceProvider.GetService(); - var userName = configuration.Get("DefaultAdminUsername"); - var password = configuration.Get("DefaultAdminPassword"); - //const string adminRole = "Administrator"; - - var userManager = serviceProvider.GetService>(); - // Todo: identity sql does not support roles yet - //var roleManager = serviceProvider.GetService>(); - //if (!await roleManager.RoleExistsAsync(adminRole)) - //{ - // await roleManager.CreateAsync(new IdentityRole(adminRole)); - //} - - var user = await userManager.FindByNameAsync(userName); - if (user == null) - { - user = new ApplicationUser { UserName = userName }; - await userManager.CreateAsync(user, password); - //await userManager.AddToRoleAsync(user, adminRole); - await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed")); + //Populates the MusicStore sample data + SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); + SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait(); } } } \ No newline at end of file diff --git a/src/MusicStore/Views/Account/_ChangePasswordPartial.cshtml b/src/MusicStore/Views/Account/_ChangePasswordPartial.cshtml index 298f4a5fa6..7c84c7e291 100644 --- a/src/MusicStore/Views/Account/_ChangePasswordPartial.cshtml +++ b/src/MusicStore/Views/Account/_ChangePasswordPartial.cshtml @@ -1,7 +1,7 @@ @using System.Security.Principal @model MusicStore.Models.ManageUserViewModel -

You're logged in as @Context.HttpContext.User.Identity.GetUserName().

+

You're logged in as @User.Identity.GetUserName().

@using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { diff --git a/src/MusicStore/Views/Shared/_LoginPartial.cshtml b/src/MusicStore/Views/Shared/_LoginPartial.cshtml index f4710663e9..d8368a8a7d 100644 --- a/src/MusicStore/Views/Shared/_LoginPartial.cshtml +++ b/src/MusicStore/Views/Shared/_LoginPartial.cshtml @@ -1,6 +1,6 @@ @using System.Security.Principal -@if (Context.HttpContext.User.Identity.IsAuthenticated) +@if (User.Identity.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @@ -8,7 +8,7 @@ diff --git a/src/MusicStore/project.json b/src/MusicStore/project.json index 28fdd059b1..8b0023f90d 100644 --- a/src/MusicStore/project.json +++ b/src/MusicStore/project.json @@ -1,46 +1,30 @@ { - "name": "MusicStore", - "authors": [ - "Microsoft" - ], - "description": "Music store application on K", - "version": "0.1-alpha-*", - "dependencies": { - "Helios": "0.1-alpha-*", - "Microsoft.AspNet.Hosting": "0.1-alpha-*", - "Microsoft.AspNet.Server.WebListener": "0.1-alpha-*", - "Microsoft.AspNet.Mvc": "0.1-alpha-*", - "Microsoft.AspNet.Diagnostics": "0.1-alpha-*", - "Microsoft.AspNet.Identity.Entity": "0.1-alpha-*", - "Microsoft.AspNet.Identity.Security": "0.1-alpha-*", - "Microsoft.AspNet.Security.Cookies": "0.1-alpha-*", - "Microsoft.AspNet.Security.DataProtection": "0.1-alpha-*", - "Microsoft.AspNet.RequestContainer": "0.1-alpha-*", - "Microsoft.AspNet.StaticFiles": "0.1-alpha-*", - "Microsoft.Data.Entity.SqlServer": "0.1-alpha-*", - "Microsoft.Framework.ConfigurationModel.Json": "0.1-alpha-*" - }, - "commands": { - "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5002", - "run": "run server.urls=http://localhost:5003" - }, - "configurations": { - "net45": { - "dependencies": { - "System.ComponentModel.DataAnnotations": "", - "System.Data": "", - "System.Runtime": "" - } + "name": "MusicStore", + "authors": [ + "Microsoft" + ], + "description": "Music store application on K", + "version": "0.1-alpha-*", + "dependencies": { + "Helios": "0.1-alpha-*", + "Microsoft.AspNet.Mvc": "0.1-alpha-*", + "Microsoft.AspNet.Server.WebListener": "0.1-alpha-*", + "Microsoft.AspNet.Diagnostics": "0.1-alpha-*", + "Microsoft.AspNet.Identity.Entity": "0.1-alpha-*", + "Microsoft.AspNet.Identity.Security": "0.1-alpha-*", + "Microsoft.AspNet.Security.Cookies": "0.1-alpha-*", + "Microsoft.AspNet.StaticFiles": "0.1-alpha-*", + "Microsoft.Data.Entity.SqlServer": "0.1-alpha-*", + "Microsoft.Framework.ConfigurationModel.Json": "0.1-alpha-*" }, - "k10": { - "dependencies": { - "Microsoft.DataAnnotations": "0.1-alpha-*", - "System.Collections": "4.0.0.0", - "System.ComponentModel": "4.0.0.0", - "System.Console": "4.0.0.0", - "System.Runtime": "4.0.20.0", - "System.Threading.Tasks": "4.0.10.0" - } + "commands": { + "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5002", + "run": "run server.urls=http://localhost:5003" + }, + "configurations": { + "net45": { + }, + "k10": { + } } - } } \ No newline at end of file diff --git a/test/E2ETests/E2ETests.kproj b/test/E2ETests/E2ETests.kproj new file mode 100644 index 0000000000..71d8d47fea --- /dev/null +++ b/test/E2ETests/E2ETests.kproj @@ -0,0 +1,37 @@ + + + + 12.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + a319acce-060b-4385-9534-9f2202f6180e + Library + + + ConsoleDebugger + + + WebDebugger + + + + + + + 2.0 + + + + + + + + + + + + + + \ No newline at end of file