Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions Seed.Api.IntegrationTests/Controllers/UserControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,9 @@ public async Task Create_ReturnsCreated()
public async Task Create_ReturnsBadRequest_WhenInvalidInput()
{
// Arrange
var sampleUser = new InputUserDto
{
Email = "invalid-address"
var sampleUser = new InputUserDto
{
Email = "invalid-address"
};

// Act
Expand All @@ -147,7 +147,7 @@ public async Task Create_ReturnsBadRequest_WhenInvalidInput()
public async Task Update_ReturnsNoContent()
{
// Arrange
var sampleUser = GetSampleUser();
var sampleUser = GetSampleUser();
using (var context = CreateContext())
{
await context.Users.AddAsync(sampleUser);
Expand All @@ -163,8 +163,8 @@ public async Task Update_ReturnsNoContent()
};

// Act
var result = await _httpClient.PutAsync($"{ResouceUri}{sampleUser.Id.ToString()}", CreateContent(userToUpdate));
var result = await _httpClient.PutAsync($"{ResouceUri}{sampleUser.Id.ToString()}", CreateContent(userToUpdate));

// Assert
Assert.True(result.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
Expand Down Expand Up @@ -195,18 +195,18 @@ public async Task Update_ReturnsNotFound_WhenUserNotExists()
};

// Act
var result = await _httpClient.PutAsync($"{ResouceUri}{userId.ToString()}", CreateContent(userToUpdate));
// Assert
Assert.False(result.IsSuccessStatusCode);
var result = await _httpClient.PutAsync($"{ResouceUri}{userId.ToString()}", CreateContent(userToUpdate));

// Assert
Assert.False(result.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
}

[Fact(Skip = "Validation attribute is not working")]
public async Task Update_ReturnsBadRequest_WhenInputIsInvalid()
{
// Arrange
var sampleUser = GetSampleUser();
var sampleUser = GetSampleUser();
using (var context = CreateContext())
{
await context.Users.AddAsync(sampleUser);
Expand All @@ -219,8 +219,8 @@ public async Task Update_ReturnsBadRequest_WhenInputIsInvalid()
};

// Act
var result = await _httpClient.PutAsync($"{ResouceUri}{sampleUser.Id.ToString()}", CreateContent(userToUpdate));
var result = await _httpClient.PutAsync($"{ResouceUri}{sampleUser.Id.ToString()}", CreateContent(userToUpdate));

// Assert
Assert.False(result.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
Expand Down
8 changes: 4 additions & 4 deletions Seed.Api/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ public async Task<IActionResult> Create([FromBody]InputUserDto user)
// TODO: Fix validation attribute, it's not working as expected.
if (user == null) return BadRequest();

var userToCreate = new User
var userToCreate = new User
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
UserName = user.UserName
UserName = user.UserName
};

var result = await _userService.CreateAsync(userToCreate);
Expand All @@ -95,13 +95,13 @@ public async Task<IActionResult> Update(Guid id, [FromBody]InputUserDto user)
// TODO: Fix validation attribute, it's not working as expected.
if (user == null) return BadRequest();

var userToUpdate = new User
var userToUpdate = new User
{
Id = id,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
UserName = user.UserName
UserName = user.UserName
};

var result = await _userService.UpdateAsync(userToUpdate);
Expand Down
26 changes: 14 additions & 12 deletions Seed.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Seed.Api.Filters;
using Seed.Api.Middleware;
using Seed.Data.EF;
using Seed.Data.Models;
using Seed.Domain.Services;
using Seed.Domain.Services.Interfaces;
using Seed.Infrastructure.AuthZero;
Expand Down Expand Up @@ -38,7 +39,7 @@ public Startup(IHostingEnvironment env)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<WebApiCoreSeedContext>(options => options.UseInMemoryDatabase(Environment.MachineName));
services.AddDbContext<WebApiCoreSeedContext<BaseEntity>>(options => options.UseInMemoryDatabase(Environment.MachineName));

// Add framework services.
services.AddMvc();
Expand Down Expand Up @@ -76,38 +77,39 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton<IAuthZeroClient>(sp => new AuthZeroClient(sp.GetRequiredService<IRestClient>(), Configuration["auth0:NonInteractiveClientId"], Configuration["auth0:NonInteractiveClientSecret"], Configuration["auth0:domain"]));
services.AddTransient<IAuthZeroService>(sp => new AuthZeroService(sp.GetRequiredService<IAuthZeroClient>()));

services.AddSingleton<UserContext>(sp => new UserContext(options,sp.GetRequiredService<DbSet<User>>()));
// Register Services
services.AddTransient<IUserService>(sp => new UserService(sp.GetRequiredService<WebApiCoreSeedContext>()));
services.AddTransient<IUserService>(sp => new UserService(sp.GetRequiredService<UserContext>()));
}

// 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, WebApiCoreSeedContext dbContext)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UserContext userContext)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseMiddleware(typeof(AuthorizationMiddleware));
app.UseSwagger();
// Enable middleware to serve Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwagger();

// Enable middleware to serve Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
// Sets Swagger UI route on root, "GET {baseUrl}/".
c.RoutePrefix = string.Empty;
c.SwaggerEndpoint("/swagger/v1/swagger.json", ".NET Core API Seed");
});
});

app.UseMvc();

DatabaseSeed.Initialize(dbContext);
DatabaseSeed.Initialize(userContext);
}

private static Info GetSwaggerMetadata()
{
return new Info
{
Title = ".NET Core API Seed",
return new Info
{
Title = ".NET Core API Seed",
Version = "v1",
Description = "Seed for an API using .NET Core",
TermsOfService = "https://github.com/MakingSense/WebApiCore-Seed",
Expand Down
12 changes: 6 additions & 6 deletions Seed.Data/EF/DatabaseSeed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@ public static class DatabaseSeed
/// <summary>
/// Initializes a <see cref="WebApiCoreSeedContext"/> with sample Data
/// </summary>
/// <param name="dbContext">Context to be initialized with sample data</param>
public static void Initialize(WebApiCoreSeedContext dbContext)
/// <param name="userContext">Context to be initialized with sample data</param>
public static void Initialize(UserContext userContext)
{
dbContext.Database.EnsureCreated();
userContext.Database.EnsureCreated();

if (!dbContext.Users.Any())
if (!userContext.Users.Any())
{
var users = new[]
{
new User { CreatedOn = DateTime.Now, Email = "[email protected]", FirstName = "John", LastName = "Doe", UserName = "JohnDoe" },
};

dbContext.Users.AddRange(users);
userContext.Users.AddRange(users);
}

dbContext.SaveChanges();
userContext.SaveChanges();
}
}
}
21 changes: 21 additions & 0 deletions Seed.Data/EF/UserContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.EntityFrameworkCore;
using Seed.Data.Models;

namespace Seed.Data.EF
{
public class UserContext : WebApiCoreSeedContext<User>
{
public DbSet<User> Users;

public UserContext(DbContextOptions options, DbSet<User> users) : base(options, users)
{
Users = users;
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Table names should be singular but DbSet properties should be plural.
modelBuilder.Entity<User>().ToTable("User").HasIndex(x => x.UserName).IsUnique();
}
}
}
20 changes: 6 additions & 14 deletions Seed.Data/EF/WebApiCoreSeedContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,20 @@

namespace Seed.Data.EF
{
public class WebApiCoreSeedContext : DbContext
public class WebApiCoreSeedContext<T> : DbContext where T : BaseEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="WebApiCoreSeedContext"/> class.
///
/// DbContextOptions parameter is required by AspNet core initialization
/// </summary>
/// <param name="options">Options used to create this <see cref="WebApiCoreSeedContext"/> instance </param>
public WebApiCoreSeedContext(DbContextOptions options) : base(options) { }

/// <summary>
/// Initializes a new instance of the <see cref="WebApiCoreSeedContext"/> class without parameters.
/// </summary>
public WebApiCoreSeedContext() : base() { }

/// <summary> All users registered on WebApiCoreSeed database</summary>
public virtual DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
public WebApiCoreSeedContext(DbContextOptions options, DbSet<T> entities) : base(options)
{
// Table names should be singular but DbSet properties should be plural.
modelBuilder.Entity<User>().ToTable("User").HasIndex(x => x.UserName).IsUnique();
Entities = entities;
}

/// <summary> All entities registered on WebApiCoreSeed database</summary>
public virtual DbSet<T> Entities { get; }
}
}
Loading