Catching up MusicStore app with code generated with latest templates

This commit is contained in:
Praburaj 2014-05-23 14:35:08 -07:00
parent d4303238e9
commit 8409e9518b
12 changed files with 200 additions and 163 deletions

View File

@ -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

View File

@ -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 =

View File

@ -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"
}
}
}

View File

@ -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<ApplicationUser>
public class ApplicationDbContext : IdentitySqlContext<ApplicationUser>
{
private readonly IConfiguration _configuration;
public ApplicationDbContext(IServiceProvider serviceProvider, IConfiguration configuration)
: base(serviceProvider)
public ApplicationDbContext(IServiceProvider serviceProvider, IOptionsAccessor<IdentityDbContextOptions> 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; }
}
}

View File

@ -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<MusicStoreDbContextOptions> optionsAccessor)
: base(serviceProvider, optionsAccessor.Options.BuildConfiguration())
{
_configuration = configuration;
}
public DbSet<Album> Albums { get; set; }
@ -23,10 +20,6 @@ namespace MusicStore.Models
public DbSet<CartItem> CartItems { get; set; }
public DbSet<OrderDetail> 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<OrderDetail>().Key(o => o.OrderDetailId);
}
}
public class MusicStoreDbContextOptions : DbContextOptions
{
}
}

View File

@ -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<DbContext>() as ApplicationDbContext)
using (var db = serviceProvider.GetService<ApplicationDbContext>())
{
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
}
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
var options = serviceProvider.GetService<IOptionsAccessor<IdentityDbContextOptions>>().Options;
//const string adminRole = "Administrator";
var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
// TODO: Identity SQL does not support roles yet
//var roleManager = serviceProvider.GetService<ApplicationRoleManager>();
//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<string, Genre> genres, Dictionary<string, Artist> artists)
{
var albums = new Album[]

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="__ToolsVersion__" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>
@ -35,8 +35,6 @@
<Content Include="Images\logo.svg" />
<Content Include="Images\placeholder.png" />
<Content Include="Images\placeholder.svg" />
<Content Include="k.ini" />
<Content Include="LKG.json" />
<Content Include="LocalConfig.json" />
<Content Include="Project.json" />
<Content Include="Scripts\bootstrap.js" />
@ -88,10 +86,6 @@
<Compile Include="Controllers\ShoppingCartController.cs" />
<Compile Include="Controllers\StoreController.cs" />
<Compile Include="Controllers\StoreManagerController.cs" />
<Compile Include="Interfaces\AssemblyNeutralAttribute.cs" />
<Compile Include="Interfaces\IApplicationEnvironment.cs" />
<Compile Include="Logging\NullLogger.cs" />
<Compile Include="Logging\NullLoggerFactory.cs" />
<Compile Include="Models\AccountViewModels.cs" />
<Compile Include="Models\Album.cs" />
<Compile Include="Models\Artist.cs" />

View File

@ -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<IConfiguration>(configuration);
//Add all MVC related services to IoC.
services.AddMvc();
/*Add all EF related services to IoC.*/
services.AddEntityFramework().AddSqlServer();
services.AddTransient<MusicStoreContext>();
//Add all Identity related services to IoC.
services.AddTransient<DbContext, ApplicationDbContext>();
services.AddIdentity<ApplicationUser, IdentityRole>(s =>
app.UseServices(services =>
{
s.AddEntity();
// Add EF services to the services container
services.AddEntityFramework()
.AddSqlServer();
services.AddScoped<MusicStoreContext>();
// Configure DbContext
services.SetupOptions<IdentityDbContextOptions>(options =>
{
options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername");
options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword");
options.UseSqlServer(configuration.Get("Data:IdentityConnection:ConnectionString"));
});
services.SetupOptions<MusicStoreDbContextOptions>(options =>
options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString")));
// Add Identity services to the services container
services.AddIdentity<ApplicationUser>()
.AddEntityFramework<ApplicationUser, ApplicationDbContext>()
.AddHttpSignIn();
// Add MVC services to the services container
services.AddMvc();
});
services.AddTransient<SignInManager<ApplicationUser>>();
});
/* 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();
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private async Task CreateAdminUser(IServiceProvider serviceProvider)
{
var configuration = serviceProvider.GetService<IConfiguration>();
var userName = configuration.Get("DefaultAdminUsername");
var password = configuration.Get("DefaultAdminPassword");
//const string adminRole = "Administrator";
var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
// Todo: identity sql does not support roles yet
//var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>();
//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();
}
}
}

View File

@ -1,7 +1,7 @@
@using System.Security.Principal
@model MusicStore.Models.ManageUserViewModel
<p>You're logged in as <strong>@Context.HttpContext.User.Identity.GetUserName()</strong>.</p>
<p>You're logged in as <strong>@User.Identity.GetUserName()</strong>.</p>
@using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{

View File

@ -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 @@
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + Context.HttpContext.User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>

View File

@ -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": {
}
}
}
}

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="__ToolsVersion__" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>a319acce-060b-4385-9534-9f2202f6180e</ProjectGuid>
<OutputType>Library</OutputType>
</PropertyGroup>
<PropertyGroup Condition="$(OutputType) == 'Console'">
<DebuggerFlavor>ConsoleDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="$(OutputType) == 'Web'">
<DebuggerFlavor>WebDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'" Label="Configuration">
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" Label="Configuration">
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Content Include="Project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="DeploymentUtility.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="HostType.cs" />
<Compile Include="HtmlDOMHelper.cs" />
<Compile Include="KreFlavor.cs" />
<Compile Include="SmokeTests.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>