Entity Framework core + OData 8.0.1 CRUD Operations ASP.Net core 5 - entity-framework-core

public class Books
{
public int Id{get;set;}
public string Name{get;set;}
}
public class BookController : ODataController
{
private readonly IBookRepository _bookRepository;
private readonly IMapper _mapper;
public BookController(IBookRepository bookRepository, IMapper mapper)
{
_bookRepository = bookRepository;
_mapper = mapper;
}
[EnableQuery]
[HttpGet]
public ActionResult Get()
{
try
{
IQueryable<BookDto> res = _bookRepository.Books().ProjectTo<BookDto>(_mapper.ConfigurationProvider);
if (res.Count() == 0)
return NotFound();
return Ok(res);
}
catch(Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Unable to get Book");
}
}
[HttpGet("{Id}")]
public async Task<ActionResult<Book>> GetBookById(string Id)
{
var book = await _bookRepository.GetBookById(Id);
if (book == null)
return NotFound();
return book;
}
[HttpPost]
public async Task<ActionResult<Book>> Post([fr]CreateBookDto createBookDto)
{
try
{
if (createBookDto == null)
return BadRequest();
Book book = _mapper.Map<Book>(createBookDto);
var result = await _bookRepository.Book(book);
return CreatedAtAction(nameof(GetBookById), new { id = book.UserId }, result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,"Failed to save Book information");
}
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connectionStr = Configuration.GetConnectionString("ConnectionString");
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddControllers().AddOData(opt => opt.AddRouteComponents("api",GetEdModel()).Select().Filter().Count().Expand());
services.AddDbContext<AppDbContext>(options => options.UseMySql(connectionStr,ServerVersion.AutoDetect(connectionStr)));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Book_api", Version = "v1" });
});
services.AddScoped<IBookRepository, BookRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Book_api v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
private IEdmModel GetEdModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<User>("User");
builder.EntitySet<BookDto>("Book");
return builder.GetEdmModel();
}
}
Hi Guys. I'm trying to implement OData on my ASP.Net Core 5 API. I can retrieve books using the Get. But I am struggling to do a POST. When I try to use the POST on Postman, the CreateBookDto properties all return null. I tried to add [FromBody] that does not work also. The only time this seems to work is when I decorate the controller with [ApiController] but that in turn affects my GET. I'm not sure what to do anymore.

Related

How to write NUnit test for dependency injection service .net core

I have a service class with some injected services. It's dealing with my Azure storage requests. I need to write NUnit tests for that class.
I'm new to NUnit and I'm struggling with making the object of that my AzureService.cs
Below AzureService.cs. I have used some injected services
using System;
using System.Linq;
using System.Threading.Tasks;
using JohnMorris.Plugin.Image.Upload.Azure.Interfaces;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Media;
using Nop.Services.Logging;
namespace JohnMorris.Plugin.Image.Upload.Azure.Services
{
public class AzureService : IAzureService
{
#region Constants
private const string THUMB_EXISTS_KEY = "Nop.azure.thumb.exists-{0}";
private const string THUMBS_PATTERN_KEY = "Nop.azure.thumb";
#endregion
#region Fields
private readonly ILogger _logger;
private static CloudBlobContainer _container;
private readonly IStaticCacheManager _cacheManager;
private readonly MediaSettings _mediaSettings;
private readonly NopConfig _config;
#endregion
#region
public AzureService(IStaticCacheManager cacheManager, MediaSettings mediaSettings, NopConfig config, ILogger logger)
{
this._cacheManager = cacheManager;
this._mediaSettings = mediaSettings;
this._config = config;
this._logger = logger;
}
#endregion
#region Utilities
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
public virtual async Task DeleteFileAsync(string prefix)
{
try
{
BlobContinuationToken continuationToken = null;
do
{
var resultSegment = await _container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.All, null, continuationToken, null, null);
await Task.WhenAll(resultSegment.Results.Select(blobItem => ((CloudBlockBlob)blobItem).DeleteAsync()));
//get the continuation token.
continuationToken = resultSegment.ContinuationToken;
}
while (continuationToken != null);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file delete error", e);
}
}
public virtual async Task<bool> CheckFileExistsAsync(string filePath)
{
try
{
var key = string.Format(THUMB_EXISTS_KEY, filePath);
return await _cacheManager.Get(key, async () =>
{
//GetBlockBlobReference doesn't need to be async since it doesn't contact the server yet
var blockBlob = _container.GetBlockBlobReference(filePath);
return await blockBlob.ExistsAsync();
});
}
catch { return false; }
}
public virtual async Task SaveFileAsync(string filePath, string mimeType, byte[] binary)
{
try
{
var blockBlob = _container.GetBlockBlobReference(filePath);
if (!string.IsNullOrEmpty(mimeType))
blockBlob.Properties.ContentType = mimeType;
if (!string.IsNullOrEmpty(_mediaSettings.AzureCacheControlHeader))
blockBlob.Properties.CacheControl = _mediaSettings.AzureCacheControlHeader;
await blockBlob.UploadFromByteArrayAsync(binary, 0, binary.Length);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file upload error", e);
}
}
public virtual byte[] LoadFileFromAzure(string filePath)
{
try
{
var blob = _container.GetBlockBlobReference(filePath);
if (blob.ExistsAsync().GetAwaiter().GetResult())
{
blob.FetchAttributesAsync().GetAwaiter().GetResult();
var bytes = new byte[blob.Properties.Length];
blob.DownloadToByteArrayAsync(bytes, 0).GetAwaiter().GetResult();
return bytes;
}
}
catch (Exception)
{
}
return new byte[0];
}
#endregion
}
}
This is my test class below, I need to create new AzureService(); from my service class. But in my AzureService constructor, I'm injecting some service
using JohnMorris.Plugin.Image.Upload.Azure.Services;
using Nop.Core.Caching;
using Nop.Core.Domain.Media;
using Nop.Services.Tests;
using NUnit.Framework;
namespace JohnMorris.Plugin.Image.Upload.Azure.Test
{
public class AzureServiceTest
{
private AzureService _azureService;
[SetUp]
public void Setup()
{
_azureService = new AzureService( cacheManager, mediaSettings, config, logger);
}
[Test]
public void App_settings_has_azure_connection_details()
{
var url= _azureService.GetAzureStorageUrl();
Assert.IsNotNull(url);
Assert.IsNotEmpty(url);
}
[Test]
public void Check_File_Exists_Async_test(){
//To Do
}
[Test]
public void Save_File_Async_Test()(){
//To Do
}
[Test]
public void Load_File_From_Azure_Test(){
//To Do
}
}
}
Question is, what exactly do you want to test? If you want to test if NopConfig is properly reading values from AppSettings, then you do not have to test AzureService at all.
If you want to test that GetAzureStorageUrl method is working correctly, then you should mock your NopConfig dependency and focus on testing only AzureService methods like this:
using Moq;
using Nop.Core.Configuration;
using NUnit.Framework;
namespace NopTest
{
public class AzureService
{
private readonly NopConfig _config;
public AzureService(NopConfig config)
{
_config = config;
}
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
}
[TestFixture]
public class NopTest
{
[Test]
public void GetStorageUrlTest()
{
Mock<NopConfig> nopConfigMock = new Mock<NopConfig>();
nopConfigMock.Setup(x => x.AzureBlobStorageEndPoint).Returns("https://www.example.com/");
nopConfigMock.Setup(x => x.AzureBlobStorageContainerName).Returns("containername");
AzureService azureService = new AzureService(nopConfigMock.Object);
string azureStorageUrl = azureService.GetAzureStorageUrl();
Assert.AreEqual("https://www.example.com/containername", azureStorageUrl);
}
}
}

oData - aspnetcore - custom controller routes

I can use this attribute to custom route aspnetcore api controllers:
[Route("test")]
but oData won't recognize it.
How can I fix this?
As Requested here is all the code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(mvcOptions => mvcOptions.EnableEndpointRouting = false);
services.AddOData();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseMvc(routeBuilder =>
{
routeBuilder.EnableDependencyInjection();
routeBuilder.Expand().Filter().OrderBy().Select().SkipToken();
routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
}
private IEdmModel GetEdmModel()
{
var edmBuilder = new ODataConventionModelBuilder();
edmBuilder.EntitySet<DivUser>("Users");
edmBuilder.EntitySet<DivClaim>("Claims");
edmBuilder.EntitySet<DivUserRole>("UserRoles");
edmBuilder.EntitySet<DivUserType>("UserTypes");
return edmBuilder.GetEdmModel();
}
}
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
[EnableQuery]
public IEnumerable<DivUser> Get()
{
IEnumerable<DivUser> users;
using (var context = new DivDbContext())
{
users = context.Users.Include(user => user.UserClaims).ThenInclude(userClaim => userClaim.Claim).ToList();
}
return users;
}
[HttpGet]
[EnableQuery]
[Route("test")]
public IEnumerable<DivUser> Test()
{
IEnumerable<DivUser> users;
using (var context = new DivDbContext())
{
users = context.Users.Include(user => user.UserClaims).ToList();
}
return users;
}
}
https://localhost:44354/users WORKS
https://localhost:44354/users/test WORKS
https://localhost:44354/odata/users WORKS
https://localhost:44354/odata/users/test DOES NOT

Best way to handle complex entities (relational) with Generic CRUD functions

I have tried using this generic functions to insert-update Entities but I always thought that maybe I am doing this totally wrong so therefore I would like to have your opinions/suggestions.
These are my Insert & Update functions:
public static bool Insert<T>(T item) where T : class
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
try
{
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// ...
}
}
}
public static bool Update<T>(T item) where T : class
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
try
{
Type itemType = item.GetType();
// switch statement to perform actions according which type we are working on
ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// ...
}
}
}
I have learned that i can use ctx.Entry(item).State = EntityState.Modified; and I have seen so many ways of inserting-updating entities that I am very curious on what is the easiest most manageable way of performing CRUD actions ?
I know about the repository pattern and so on but i don't have much experience with interfaces or I don't seem to fully understand whats used so I prefer not to use it till I fully get it.
my approach for that is to use IRepository pattern to wrap CRUD and to make dependencies injection easier in my application, here an example on how i do it:
Define your contract like following:
(i am simplifying the example and admitting that all your tables have an integer id -i mean it is not guid or string or whatever- )
public interface IGenericRepository<TEntity> where TEntity : class
{
#region ReadOnlyRepository
TEntity GetById(int id);
ICollection<TEntity> GetAll();
ICollection<TEntity> GetAll(params Expression<Func<TEntity, object>>[] includeProperties);
ICollection<TEntity> Query(Expression<Func<TEntity, bool>> expression, params Expression<Func<TEntity, object>>[] includeProperties);
PagedModel<TEntity> Query(Expression<Func<TEntity, bool>> expression, SortOptions sortOptions, PaginateOptions paginateOptions, params Expression<Func<TEntity, object>>[] includeProperties);
int Max(Expression<Func<TEntity, int>> expression);
#endregion
#region PersistRepository
bool Add(TEntity entity);
bool AddRange(IEnumerable<TEntity> items);
bool Update(TEntity entity);
bool Delete(TEntity entity);
bool DeleteById(int id);
#endregion
}
and then the implementation:
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
#region Fields
protected DbContext CurrentContext { get; private set; }
protected DbSet<TEntity> EntitySet { get; private set; }
#endregion
#region Ctor
public GenericRepository(DbContext context)
{
CurrentContext = context;
EntitySet = CurrentContext.Set<TEntity>();
}
#endregion
#region IReadOnlyRepository Implementation
public virtual TEntity GetById(int id)
{
try
{
//use your logging method (log 4 net used here)
DomainEventSource.Log.Info(string.Format("getting entity {0} with id {1}", typeof(TEntity).Name, id));
return EntitySet.Find(id); //dbcontext manipulation
}
catch (Exception exception)
{
/// example of error handling
DomainEventSource.Log.Error(exception.Message);
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);// this is specific error formatting class you can do somthing like that to fit your needs
}
}
public virtual ICollection<TEntity> GetAll()
{
try
{
return EntitySet.ToList();
}
catch (Exception exception)
{
//... Do whatever you want
}
}
public virtual ICollection<TEntity> GetAll(params Expression<Func<TEntity, object>>[] includeProperties)
{
try
{
var query = LoadProperties(includeProperties);
return query.ToList();
}
catch (Exception exception)
{
//... Do whatever you want
}
}
public virtual ICollection<TEntity> Query(Expression<Func<TEntity, bool>> expression, params Expression<Func<TEntity, object>>[] includeProperties)
{
try
{
var query = LoadProperties(includeProperties);
return query.Where(expression).ToList();
}
catch (Exception exception)
{
//... Do whatever you want
}
}
// returning paged results for example
public PagedModel<TEntity> Query(Expression<Func<TEntity, bool>> expression,SortOptions sortOptions, PaginateOptions paginateOptions, params Expression<Func<TEntity, object>>[] includeProperties)
{
try
{
var query = EntitySet.AsQueryable().Where(expression);
var count = query.Count();
//Unfortunatly includes can't be covered with a UT and Mocked DbSets...
if (includeProperties.Length != 0)
query = includeProperties.Aggregate(query, (current, prop) => current.Include(prop));
if (paginateOptions == null || paginateOptions.PageSize <= 0 || paginateOptions.CurrentPage <= 0)
return new PagedModel<TEntity> // specific pagination model, you can define yours
{
Results = query.ToList(),
TotalNumberOfRecords = count
};
if (sortOptions != null)
query = query.OrderByPropertyOrField(sortOptions.OrderByProperty, sortOptions.IsAscending);
var skipAmount = paginateOptions.PageSize * (paginateOptions.CurrentPage - 1);
query = query.Skip(skipAmount).Take(paginateOptions.PageSize);
return new PagedModel<TEntity>
{
Results = query.ToList(),
TotalNumberOfRecords = count,
CurrentPage = paginateOptions.CurrentPage,
TotalNumberOfPages = (count / paginateOptions.PageSize) + (count % paginateOptions.PageSize == 0 ? 0 : 1)
};
}
catch (Exception exception)
{
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);
}
}
#endregion
#region IPersistRepository Repository
public bool Add(TEntity entity)
{
try
{
// you can do some extention methods here to set up creation date when inserting or createdBy etc...
EntitySet.Add(entity);
return true;
}
catch (Exception exception)
{
//DomainEventSource.Log.Failure(ex.Message);
//or
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);
}
}
public bool AddRange(IEnumerable<TEntity> items)
{
try
{
foreach (var entity in items)
{
Add(entity);
}
}
catch (Exception exception)
{
//DomainEventSource.Log.Failure(ex.Message);
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);
}
return true;
}
public bool Update(TEntity entity)
{
try
{
CurrentContext.Entry(entity).State = EntityState.Modified;
}
catch (Exception exception)
{
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);
}
return true;
}
public bool Delete(TEntity entity)
{
try
{
if (CurrentContext.Entry(entity).State == EntityState.Detached)
{
EntitySet.Attach(entity);
}
EntitySet.Remove(entity);
}
catch (Exception exception)
{
var errors = new List<ExceptionDetail> { new ExceptionDetail { ErrorMessage = exception.Message } };
throw new ServerException(errors);
}
return true;
}
public bool DeleteById(TKey id)
{
var entityToDelete = GetById(id);
return Delete(entityToDelete);
}
#endregion
#region Loading dependancies Utilities
private IQueryable<TEntity> LoadProperties(IEnumerable<Expression<Func<TEntity, object>>> includeProperties)
{
return includeProperties.Aggregate<Expression<Func<TEntity, object>>, IQueryable<TEntity>>(EntitySet, (current, includeProperty) => current.Include(includeProperty));
}
#endregion
}
I am admitting that your model classes are already created and decorated.
After this , you need to create your entityRepository like following : this is an example of managing entity called Ticket.cs
public class TicketRepository : GenericRepository<Ticket>, ITicketRepository
{
// the EntityRepository classes are made in case you have some ticket specific methods that doesn't
//have to be in generic repository
public TicketRepository(DbContext context)
: base(context)
{
}
// Add specific generic ticket methods here (not business methods-business methods will come later-)
}
After this comes the UnitOfWork class which allows us to unify entry to the database context and provides us an instance of repositories on demand using dependency injection
public class UnitOfwork : IUnitOfWork
{
#region Fields
protected DbContext CurrentContext { get; private set; }
private ITicketRepository _tickets;
#endregion
#region ctor
public UnitOfwork(DbContext context)
{
CurrentContext = context;
}
#endregion
#region UnitOfWorkBaseImplementation
public void Commit()
{
try
{
CurrentContext.SaveChanges();
}
catch (Exception e)
{
/// catch
}
}
public void Rollback()
{
foreach (var entry in CurrentContext.ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Modified:
case EntityState.Deleted:
entry.State = EntityState.Modified; //Revert changes made to deleted entity.
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Detached:
break;
case EntityState.Unchanged:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
#region complete RollBack()
private void RejectScalarChanges()
{
foreach (var entry in CurrentContext.ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Modified:
case EntityState.Deleted:
entry.State = EntityState.Modified; //Revert changes made to deleted entity.
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Detached:
break;
case EntityState.Unchanged:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private void RejectNavigationChanges()
{
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
var deletedRelationships = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted).Where(e => e.IsRelationship && !this.RelationshipContainsKeyEntry(e));
var addedRelationships = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Where(e => e.IsRelationship);
foreach (var relationship in addedRelationships)
relationship.Delete();
foreach (var relationship in deletedRelationships)
relationship.ChangeState(EntityState.Unchanged);
}
private bool RelationshipContainsKeyEntry(System.Data.Entity.Core.Objects.ObjectStateEntry stateEntry)
{
//prevent exception: "Cannot change state of a relationship if one of the ends of the relationship is a KeyEntry"
//I haven't been able to find the conditions under which this happens, but it sometimes does.
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
var keys = new[] { stateEntry.OriginalValues[0], stateEntry.OriginalValues[1] };
return keys.Any(key => objectContext.ObjectStateManager.GetObjectStateEntry(key).Entity == null);
}
#endregion
public void Dispose()
{
if (CurrentContext != null)
{
CurrentContext.Dispose();
}
}
#endregion
#region properties
public ITicketRepository Tickets
{
get { return _tickets ?? (_tickets = new TicketRepository(CurrentContext)); }
}
#endregion
}
Now for the last part we move to our business service layer and make a ServiceBase class which will be implemented by all business services
public class ServiceBase : IServiceBase
{
private bool _disposed;
#region IServiceBase Implementation
[Dependency]
public IUnitOfWork UnitOfWork { protected get; set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
var disposableUow = UnitOfWork as IDisposable;
if (disposableUow != null)
disposableUow.Dispose();
}
_disposed = true;
}
#endregion
}
and finally one example of business service class and how to use your CRUD and play with your business rules (i am using properties injection which is not the best to do so i suggest to change it and use constructor injection instead)
public class TicketService : ServiceBase, ITicketService
{
#region fields
private IUserService _userService;
private IAuthorizationService _authorizationService;
#endregion
#region Properties
[Dependency]
public IAuthorizationService AuthorizationService
{
set { _authorizationService = value; }
}
[Dependency]
public IUserService UserService
{
set { _userService = value; }
}
public List<ExceptionDetail> Errors { get; set; }
#endregion
#region Ctor
public TicketService()
{
Errors = new List<ExceptionDetail>();
}
#endregion
#region IServiceBase Implementation
/// <summary>
/// desc
/// </summary>
/// <returns>array of TicketAnomalie</returns>
public ICollection<Ticket> GetAll()
{
return UnitOfWork.Tickets.GetAll();
}
/// <summary>
/// desc
/// </summary>
/// <param name="id"></param>
/// <returns>TicketAnomalie</returns>
public Ticket GetTicketById(int id)
{
return UnitOfWork.Tickets.GetById(id);
}
/// <summary>
/// description here
/// </summary>
/// <returns>Collection of Ticket</returns>
public ICollection<Ticket> GetAllTicketsWithDependencies()
{
return UnitOfWork.Tickets.Query(tick => true, tick => tick.Anomalies);
}
/// <summary>
/// description here
/// </summary>
/// <param name="id"></param>
/// <returns>Ticket</returns>
public Ticket GetTicketWithDependencies(int id)
{
return UnitOfWork.Tickets.Query(tick => tick.Id == id, tick => tick.Anomalies).SingleOrDefault();
}
/// <summary>
/// Add new ticket to DB
/// </summary>
/// <param name="anomalieId"></param>
/// <returns>Boolean</returns>
public bool Add(int anomalieId)
{
var anomalie = UnitOfWork.Anomalies.Query(ano => ano.Id.Equals(anomalieId), ano => ano.Tickets).FirstOrDefault();
var currentUser = WacContext.Current;
var superv = _userService.GetSupervisorUserProfile();
var sup = superv.FirstOrDefault();
if (anomalie != null)
{
var anomalies = new List<Anomalie>();
var anom = UnitOfWork.Anomalies.GetById(anomalieId);
anomalies.Add(anom);
if (anomalie.Tickets.Count == 0 && sup != null)
{
var ticket = new Ticket
{
User = sup.Id,
CreatedBy = currentUser.GivenName,
Anomalies = anomalies,
Path = UnitOfWork.SearchCriterias.GetById(anom.ParcoursId),
ContactPoint = UnitOfWork.ContactPoints.GetById(anom.ContactPointId)
};
UnitOfWork.Tickets.Add(ticket);
UnitOfWork.Commit();
}
}
else
{
Errors.Add(AnomaliesExceptions.AnoNullException);
}
if (Errors.Count != 0) throw new BusinessException(Errors);
return true;
}
public bool Update(Ticket ticket)
{
if (ticket == null)
{
Errors.Add(AnomaliesExceptions.AnoNullException);
}
else
if (!Exists(ticket.Id))
{
Errors.Add(AnomaliesExceptions.AnoToUpdateNotExistException);
}
if (Errors.Count != 0) throw new BusinessException(Errors);
UnitOfWork.Tickets.Update(ticket);
UnitOfWork.Commit();
return true;
}
public bool Exists(int ticketId)
{
var operationDbEntity =
UnitOfWork.Tickets.Query(t => t.Id.Equals(ticketId)).ToList();
return operationDbEntity.Count != 0;
}
#endregion
#region Business Implementation
//play with your buiness :)
#endregion
}
Finally,
i suggest that you redo this using asynchronous methods (async await since it allows a better management of service pools in the web server)
Note that this is my own way of managing my CRUD with EF and Unity. you can find a lot of other implementations that can inspire you.
Hope this helps,

ApplicationUser within an ActionFilter in Asp.Net Core 2.0?

How can I access the current ApplicationUser (or UserManager) within an ActionFilter in Asp.Net Core 2.0?
I am trying to lock down the entire application until the user accepts the EULA (End User License Agreement), changes their password, and fills out required personal information.
public class ApplicationUser : IdentityUser
{
...
public DateTime? DateEULAAccepted { get; set; }
...
}
Here is the ActionFilter code:
public class ProfileRequiredActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = UserManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}
I am instantiating the ActionFilter in the Startup > ConfigureServices as follows:
...
services.AddMvc(options =>
{
options.Filters.Add(new ProfileRequiredActionFilter());
});
...
Try adding your filter in ConfigureServices() as follows:
services.AddMvc(options => {
options.Filters.Add<ProfileRequiredActionFilter>();
});
You can then inject your UserManager into the filter as follows:
public class ProfileRequiredActionFilter : IActionFilter
{
private UserManager<ApplicationUser> _userManager;
public ProfileRequiredActionFilter(UserManager<ApplicationUser> userManager)
{
_userManager = userManager
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = _userManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}

Troubles with dependency injection

I am working on an ASP.NET WebAPI using OWIN. To manage the instances of DBContext (Entity Framework), I try to use Ninject. However, when I call a controller, the programm returns an error:
The controller cannot be created, missing constructor.
Could you tell me what is going wrong here?
My Controller Class:
public class Testcontroller
{
private IApplicationDbContext _context;
public Testcontroller(IApplicationDbContext context)
{
_context = context;
}
}
This is the Ninject-File:
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Bind<IApplicationDbContext>().To<ApplicationDbContext>();
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
}
}
Ninject Dependency Scope:
public class NinjectDependencyScope : IDependencyScope
{
IResolutionRoot resolver;
public NinjectDependencyScope(IResolutionRoot resolver)
{
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.TryGet(serviceType);
}
public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.GetAll(serviceType);
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
}
// This class is the resolver, but it is also the global scope
// so we derive from NinjectScope.
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
IKernel kernel;
public NinjectDependencyResolver(IKernel kernel) : base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
The Entity Framework DbContext-Class:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<Models.Team> Teams { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public interface IApplicationDbContext
{
DbSet<Models.Team> Teams { get; set; }
int SaveChanges();
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
I tried to follow this tutorial: http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api
What have I done wrong here?
Thanks in advance!
Unless there was a serious omission in you controller code, your controller is not inheriting from ApiController, as is expected with Web Api
public class TestController : ApiController {
private IApplicationDbContext _context;
public Testcontroller(IApplicationDbContext context) {
_context = context;
}
}
UPDATE
I tried to set up everything from scratch using this: http://www.alexzaitzev.pro/2014/11/webapi2-owin-and-ninject.html
For some reason, it now works out perfectly fine.
Thank you for your support!