Adds Api Controllers, Models, ViewModels and EF Migrations

This commit is contained in:
Sai Manoj Kumar Yadlapati 2017-06-02 22:08:05 +05:30
Родитель 00269a7ea3
Коммит 30281696a0
18 изменённых файлов: 694 добавлений и 37 удалений

Просмотреть файл

@ -1,5 +1,4 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1

Просмотреть файл

@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using WakeYourPcWebApp.Models;
namespace WakeYourPcWebApp.Controllers.Api.v1
{
public interface IWakeupRepository
{
IEnumerable<User> GetAllUsers();
User GetUser(string username);
IEnumerable<Machine> GetAllMachines(string username);
IEnumerable<Machine> GetMachinesToWakeup(string username);
void AddMachine(Machine machine, string username);
Task<bool> SaveChangesAsync();
void AddUser(User user);
}
}

Просмотреть файл

@ -0,0 +1,80 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.Extensions.Logging;
using WakeYourPcWebApp.Models;
using WakeYourPcWebApp.ViewModels;
namespace WakeYourPcWebApp.Controllers.Api.v1
{
[Route("api/v1/users/{username}/")]
public class MachinesController : Controller
{
private readonly IConfigurationRoot _config;
private readonly IWakeupRepository _repository;
private readonly ILogger<MachinesController> _logger;
public MachinesController(IConfigurationRoot config, IWakeupRepository repository,
ILogger<MachinesController> logger)
{
_config = config;
_repository = repository;
_logger = logger;
}
[HttpGet("machines")]
public IActionResult Machines(string username)
{
try
{
var machines = _repository.GetAllMachines(username);
var machinesViewModel = Mapper.Map<IEnumerable<MachineViewModel>>(machines);
return Ok(machinesViewModel);
}
catch (Exception exception)
{
_logger.LogError($"Error occured while getting list of machines : {exception}");
return BadRequest("Error occured while getting list of machines");
}
}
[HttpGet("wakeup")]
public IActionResult Wakeup(string username)
{
try
{
var machines = _repository.GetMachinesToWakeup(username);
var machinesViewModel = Mapper.Map<IEnumerable<MachineViewModel>>(machines);
return Ok(machinesViewModel);
}
catch (Exception exception)
{
_logger.LogError($"Error occured while getting wakeup machines : {exception}");
return BadRequest("Error occured while getting wakeup machines");
}
}
[HttpPost("machines")]
public async Task<IActionResult> AddMachine([FromBody] MachineViewModel machineViewModel, string username)
{
if (ModelState.IsValid)
{
var machine = Mapper.Map<Machine>(machineViewModel);
_repository.AddMachine(machine, username);
if (await _repository.SaveChangesAsync())
{
return Created($"api/v1/machines/{machineViewModel.MachineName}",
Mapper.Map<MachineViewModel>(machine));
}
_logger.LogError("Error occured while adding a machine");
}
return BadRequest("Failed to save the Machine to database");
}
}
}

Просмотреть файл

@ -0,0 +1,73 @@
using System;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using WakeYourPcWebApp.Models;
using WakeYourPcWebApp.ViewModels;
namespace WakeYourPcWebApp.Controllers.Api.v1
{
[Route("api/v1/users/")]
public class UsersController : Controller
{
private readonly IConfigurationRoot _config;
private readonly IWakeupRepository _repository;
private readonly ILogger<UsersController> _logger;
public UsersController(IConfigurationRoot config, IWakeupRepository repository, ILogger<UsersController> logger)
{
_config = config;
_repository = repository;
_logger = logger;
}
[HttpGet("{username}")]
public IActionResult GetUser(string username)
{
try
{
var user = _repository.GetUser(username);
if(user == null)
{
var json = Json(new { errorMessage = $"username [{username}] not found" });
return BadRequest(json.Value);
}
var userViewModel = Mapper.Map<UserViewModel>(user);
return Ok(userViewModel);
}
catch (Exception exception)
{
_logger.LogError($"Error occured while getting a User {exception}");
return BadRequest("Error occured while getting a User");
}
}
[HttpPost("")]
public async Task<IActionResult> AddUser([FromBody] UserViewModel userViewModel)
{
try
{
var user = Mapper.Map<User>(userViewModel);
_repository.AddUser(user);
if (await _repository.SaveChangesAsync())
{
return Ok(Mapper.Map<UserViewModel>(user));
}
return BadRequest("Error occured while adding a User and saving changes");
}
catch (Exception exception)
{
_logger.LogError($"Error occured while adding a User {exception}");
return BadRequest("Error occured while adding a User");
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WakeYourPcWebApp.Models;
namespace WakeYourPcWebApp.Controllers.Api.v1
{
public class WakeupRepository : IWakeupRepository
{
private readonly WakeupContext _context;
public WakeupRepository(WakeupContext context)
{
_context = context;
}
public IEnumerable<User> GetAllUsers()
{
return _context.Users.ToList();
}
public User GetUser(string username)
{
return _context.Users.FirstOrDefault(x => x != null && x.Username == username);
}
public IEnumerable<Machine> GetAllMachines(string username)
{
return _context.Machines
.Where(x => x != null && x.User.Username == username).ToList();
}
public IEnumerable<Machine> GetMachinesToWakeup(string username)
{
return _context.Machines
.Where(x => x != null && x.User.Username == username
&& x.ShouldWakeup.HasValue && x.ShouldWakeup.Value).ToList();
}
public void AddMachine(Machine machine, string username)
{
machine.User = this.GetUser(username);
_context.Add(machine);
}
public async Task<bool> SaveChangesAsync()
{
return (await _context.SaveChangesAsync()) > 0;
}
public void AddUser(User user)
{
_context.Add(user);
}
}
}

Просмотреть файл

@ -0,0 +1,63 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using WakeYourPcWebApp.Models;
namespace WakeYourPcWebApp.Migrations
{
[DbContext(typeof(WakeupContext))]
[Migration("20161216140633_InitialDatabase")]
partial class InitialDatabase
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("WakeYourPcWebApp.Models.Machine", b =>
{
b.Property<Guid>("Guid")
.ValueGeneratedOnAdd();
b.Property<string>("HostName");
b.Property<string>("MacAddress");
b.Property<string>("MachineName");
b.Property<bool?>("ShouldWakeup");
b.Property<int>("State");
b.Property<string>("Username");
b.HasKey("Guid");
b.HasIndex("Username");
b.ToTable("Machines");
});
modelBuilder.Entity("WakeYourPcWebApp.Models.User", b =>
{
b.Property<string>("Username");
b.Property<string>("Password");
b.HasKey("Username");
b.ToTable("Users");
});
modelBuilder.Entity("WakeYourPcWebApp.Models.Machine", b =>
{
b.HasOne("WakeYourPcWebApp.Models.User", "User")
.WithMany()
.HasForeignKey("Username");
});
}
}
}

Просмотреть файл

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WakeYourPcWebApp.Migrations
{
public partial class InitialDatabase : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Username = table.Column<string>(nullable: false),
Password = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Username);
});
migrationBuilder.CreateTable(
name: "Machines",
columns: table => new
{
Guid = table.Column<Guid>(nullable: false),
HostName = table.Column<string>(nullable: true),
MacAddress = table.Column<string>(nullable: true),
MachineName = table.Column<string>(nullable: true),
ShouldWakeup = table.Column<bool>(nullable: true),
State = table.Column<int>(nullable: false),
Username = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Machines", x => x.Guid);
table.ForeignKey(
name: "FK_Machines_Users_Username",
column: x => x.Username,
principalTable: "Users",
principalColumn: "Username",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Machines_Username",
table: "Machines",
column: "Username");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Machines");
migrationBuilder.DropTable(
name: "Users");
}
}
}

Просмотреть файл

@ -0,0 +1,62 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using WakeYourPcWebApp.Models;
namespace WakeYourPcWebApp.Migrations
{
[DbContext(typeof(WakeupContext))]
partial class WakeupContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("WakeYourPcWebApp.Models.Machine", b =>
{
b.Property<Guid>("Guid")
.ValueGeneratedOnAdd();
b.Property<string>("HostName");
b.Property<string>("MacAddress");
b.Property<string>("MachineName");
b.Property<bool?>("ShouldWakeup");
b.Property<int>("State");
b.Property<string>("Username");
b.HasKey("Guid");
b.HasIndex("Username");
b.ToTable("Machines");
});
modelBuilder.Entity("WakeYourPcWebApp.Models.User", b =>
{
b.Property<string>("Username");
b.Property<string>("Password");
b.HasKey("Username");
b.ToTable("Users");
});
modelBuilder.Entity("WakeYourPcWebApp.Models.Machine", b =>
{
b.HasOne("WakeYourPcWebApp.Models.User", "User")
.WithMany()
.HasForeignKey("Username");
});
}
}
}

Просмотреть файл

@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.ComponentModel.DataAnnotations;
namespace WakeYourPcWebApp.Models
{
public enum MachineState
{
Unknown,
Available,
Asleep,
WakingUp,
}
public class Machine
{
public User User { get; set; }
public string MachineName { get; set; }
public string HostName { get; set; }
[Key]
public Guid Guid { get; set; }
public string MacAddress { get; set; }
public MachineState State { get; set; }
public bool? ShouldWakeup { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,14 @@
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.ComponentModel.DataAnnotations;
namespace WakeYourPcWebApp.Models
{
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace WakeYourPcWebApp.Models
{
public class WakeupContext : DbContext
{
private readonly IConfigurationRoot _configuration;
public WakeupContext(IConfigurationRoot configuration, DbContextOptions dbContextOptions)
: base(dbContextOptions)
{
_configuration = configuration;
}
public DbSet<User> Users { get; set; }
public DbSet<Machine> Machines { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_configuration["ConnectionStrings:Sql"]);
}
}
}

Просмотреть файл

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WakeYourPcWebApp.Models
{
public class WakeupContextSeedData
{
private readonly WakeupContext _context;
public WakeupContextSeedData(WakeupContext context)
{
_context = context;
}
public async Task EnsureSeedData()
{
if (!_context.Machines.Any())
{
var machine = new Machine
{
HostName = "Machine 1",
MachineName = "Machine 1",
Guid = Guid.NewGuid(),
User = new User
{
Username = "saimanoj"
}
};
_context.Users.Add(machine.User);
_context.Machines.Add(machine);
await _context.SaveChangesAsync();
};
}
}
}

Просмотреть файл

@ -2,29 +2,71 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WakeYourPcWebApp.Models;
using Newtonsoft.Json.Serialization;
using WakeYourPcWebApp.Controllers.Api.v1;
using WakeYourPcWebApp.ViewModels;
namespace WakeYourPcWebApp
{
public class Startup
{
private IHostingEnvironment _env;
private readonly IConfigurationRoot _config;
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(_env.ContentRootPath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
_config = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(_config);
services.AddDbContext<WakeupContext>();
services.AddScoped<IWakeupRepository, WakeupRepository>();
services.AddTransient<WakeupContextSeedData>();
services.AddMvc().AddJsonOptions(config =>
{
config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
WakeupContextSeedData seeder)
{
Mapper.Initialize(config =>
{
config.CreateMap<MachineViewModel, Machine>().ReverseMap();
config.CreateMap<UserViewModel, User>().ReverseMap();
});
loggerFactory.AddConsole();
if (env.IsDevelopment())
if (env.IsDevelopment() || true)
{
app.UseDeveloperExceptionPage();
}
@ -36,10 +78,19 @@ namespace WakeYourPcWebApp
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new {controller = "Home", action = "Index"}
defaults: new { controller = "Home", action = "Index" }
);
//config.MapRoute(
// name: "ApiDefault",
// template: "api/v1/{controller}/{username}/{action}",
// defaults: new { action = "GetUser" }
//);
});
//seeder.EnsureSeedData().Wait();
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WakeYourPcWebApp.Models;
namespace WakeYourPcWebApp.ViewModels
{
public class MachineViewModel
{
[Required]
public string MachineName { get; set; }
[Required]
public string HostName { get; set; }
public MachineState State { get; set; }
public bool? ShouldWakeup { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WakeYourPcWebApp.ViewModels
{
public class UserViewModel
{
public string Username { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,6 @@
{
"ConnectionStrings": {
"Sql": "Server=(localdb)\\MSSQLLocalDB;Database=WakeupDb;Trusted_Connection=true;MultipleActiveResultSets=true;"
},
"Password": "Temp Password"
}

Просмотреть файл

@ -1,4 +1,4 @@
{
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
@ -6,15 +6,44 @@
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.1"
"Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.1",
"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview3-final",
"type": "build"
},
"Microsoft.EntityFrameworkCore.Tools.DotNet": {
"version": "1.0.0-preview3-final",
"type": "build"
},
"Microsoft.EntityFrameworkCore.Design": "1.0.1",
"AutoMapper": "5.2.0"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview3-final",
"imports": [
"portable-net45+win8+dnxcore50",
"portable-net45+win8"
]
},
"Microsoft.EntityFrameworkCore.Tools.DotNet": {
"version": "1.0.0-preview3-final",
"imports": [
"portable-net45+win8+dnxcore50",
"portable-net45+win8"
]
}
},
"frameworks": {
@ -47,4 +76,4 @@
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
}

Просмотреть файл

@ -1,13 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>