public TodoUoW(IRepoProvider provider) { DbContext = new TodoDbContext(); DbContext.Configuration.ProxyCreationEnabled = false; DbContext.Configuration.LazyLoadingEnabled = false; DbContext.Configuration.ValidateOnSaveEnabled = false; provider.DbContext = DbContext; RepoProvider = provider; }
public async Task Update(TodoItemLabel label, TodoItem todo) { using (var db = new TodoDbContext(_connectionString)) { var l = await db.TodoLabel.SingleOrDefaultAsync(t => t.Value.Equals(label.Value)); var i = await db.TodoItem.Include(t => t.Labels).SingleAsync(t => t.Id.Equals(todo.Id)); if (l == null) { l = label; } i.Labels.Add(l); db.Entry(i).State = EntityState.Modified; db.SaveChanges(); } }
static async Task GetTodo(HttpContext context) { if (!context.Request.RouteValues.TryGet("id", out int id)) { context.Response.StatusCode = 400; return; } using var db = new TodoDbContext(); var todo = await db.Todos.FindAsync(id); if (todo == null) { context.Response.StatusCode = 404; return; } await context.Response.WriteJsonAsync(todo); }
public async void CanReadAList() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("GetTodoListName") .Options; using (TodoDbContext context = new TodoDbContext(options)) { TodoList list = new TodoList(); list.ListTitle = "test"; context.TodoLists.Add(list); context.SaveChanges(); var listContents = await context.TodoLists.FirstOrDefaultAsync(x => x.ListTitle == list.ListTitle); Assert.Equal("test", listContents.ListTitle); } }
public void AddTodoItem_ShouldReturnSingleTodoItem_WhenOneTodoItemAdded() { // Arrange var options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(databaseName: "TodoDb") .Options; var context = new TodoDbContext(options); var repository = new TodoRepository(context); // Act repository.Add(new TodoItem() { Name = "Go to sleep! it's already super late..." }); var result = repository.GetAll().ToList(); // Assert Assert.Single(result); }
public async void CanReadTodo() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("GetTodoName") .Options; using (TodoDbContext context = new TodoDbContext(options)) { Todo task = new Todo(); task.Title = "test"; context.Todos.Add(task); context.SaveChanges(); var taskTitle = await context.Todos.FirstOrDefaultAsync(x => x.Title == task.Title); Assert.Equal("test", taskTitle.Title); } }
public virtual async Task <IEnumerable <TEntity> > ExecuteQueryAsync <TEntity>(string procNameWithParamNames, KeyValuePair <string, object>[] inData, bool isEntitySet = false) where TEntity : class { try { using (var context = new TodoDbContext()) { var parameterString = string.Join(",", inData.Select(k => !(k.Value.GetType() != typeof(string)) ? $"'{k.Value}'" : k.Value).ToArray()); var query = $"call {procNameWithParamNames} ({parameterString})"; IEnumerable <TEntity> queryResult = isEntitySet ? await context.Set <TEntity>().FromSql(query).ToListAsync() : await context.Query <TEntity>().FromSql(query).ToListAsync(); return(queryResult); } } catch (Exception) { throw; } }
public AppUserAuth AuthenticateUser(AppUser user) { AppUserAuth ret = new AppUserAuth(); AppUser authUser = null; using (var db = new TodoDbContext()) { // Attempt to validate user authUser = db.Users.Where(u => u.UserName.ToLower() == user.UserName.ToLower() && u.Password == user.Password).FirstOrDefault(); } if (authUser != null) { // Build User Security Object ret = BuildUserAuthObject(authUser); } return(ret); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TodoDbContext db) { db.Database.EnsureCreated(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public static void Init(IServiceProvider serviceProvider) { using (var context = new TodoDbContext( serviceProvider.GetRequiredService <DbContextOptions <TodoDbContext> >())) { // look for any existing Todos if (context.Todos.Any()) { return; } context.Todos.Add(new Models.TODO() { Id = 1, Description = "Sample Todo Item" }); context.SaveChanges(); } }
public void DeleteTodoItem_ShouldReturnDecrementedCounter_WhenOneOfTheTodoItemsWereRemoved() { // Arrange var options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(databaseName: "TodoDb") .Options; var context = new TodoDbContext(options); var repository = new TodoRepository(context); // Act InitializeTodos(context); var result = repository.GetAll().ToList(); repository.Delete(result.First()); var resultAfterDeletePerformed = repository.GetAll().ToList(); // Assert Assert.Equal(resultAfterDeletePerformed.Count, result.Count - 1); }
public async void CanRemoveItemsFromList() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; using (TodoDbContext context = new TodoDbContext(options)) { // Arrange TodoList todoList = new TodoList(); todoList.Name = "Daily"; TodoList todoList2 = new TodoList(); todoList.Name = "Replacement"; TodoListController todoListController = new TodoListController(context); await todoListController.Post(todoList); await todoListController.Post(todoList2); TodoItem todoItem = new TodoItem() { Name = "Water the plants", IsComplete = true, TodoListID = 1 }; TodoItemController todoItemController = new TodoItemController(context); var y = todoItemController.Post(todoItem); todoItem.TodoListID = 2; var x = todoItemController.Put(2, todoItem); // Act var results = await context.TodoItems.Where(i => i.TodoListID == 1).ToListAsync(); // Assert Assert.Empty(results); } }
public async void CanDeleteTodoItem() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("Test4Database").Options; using (TodoDbContext context = new TodoDbContext(options)) { // Arrange // Note: For this test, the ID has to be different // than 1 because async is forcing the ic controller // to create a dummy todo with an ID of 1 TodoItem datItem1 = new TodoItem(); datItem1.ID = 2; datItem1.Name = "walk the dog"; datItem1.IsComplete = false; TodoItem datItem2 = new TodoItem(); datItem2.ID = 3; datItem2.Name = "wash the dishes"; datItem2.IsComplete = true; TodoController ic = new TodoController(context); // Act - note: create and delete need to be async // in order for the result value to display as null // for the deleted playlist var created1 = await ic.Create(datItem1); var created2 = await ic.Create(datItem2); var deletedItem = await ic.Delete(datItem1.ID); var result1 = ic.GetById(datItem1.ID); var result2 = ic.GetById(datItem2.ID); // Assert Assert.Null(result1.Result.Value); Assert.NotNull(result2); } }
public bool EditTodo(Todo todo) { using (todoDbContext = new TodoDbContext()) { var _todo = todoDbContext.Todos.Where(t => t.id == todo.id).FirstOrDefault(); if (_todo != null) { _todo.todo = todo.todo; _todo.isCompleted = todo.isCompleted; todoDbContext.SaveChanges(); return(true); } else { return(false); } } }
private TodoDbContext SetupDatabase(string dbname) { var builder = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(databaseName: dbname); var dbContext = new TodoDbContext(builder.Options); dbContext.Users.Add(new ToDoItems.Entities.User { UserId = 1, UserName = "******", FullName = "ashwanikumar", Email = "*****@*****.**", Password = "******", UserRole = "admin" }); dbContext.SaveChanges(); return(dbContext); }
public async Task Handle_WhenTodoCreated_ShouldNotifiyUser() { // Arrange var userId = Guid.NewGuid(); var command = new CreateTodoCommand { UserId = userId, Name = "todo one", IsComplete = true }; var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { var sut = new CreateTodoCommandHandler(context, mapper, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); // Act await sut.Handle(command, new CancellationToken(false)); } // Assert rpcNotificationsMock.ClientMock.Verify(x => x.SendEmail(It.IsAny <SendEmailRequest>(), It.IsAny <CallOptions>()), Times.Once); }
protected TodoDbContext SetupDatabase(string dbname) { var builder = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(databaseName: dbname); var dbContext = new TodoDbContext(builder.Options); var saltAndHash = CryptographyHelper.GetSaltAndHash("asdf"); var user = new User { UserId = 1, UserName = "******", FullName = "testuser", Email = "*****@*****.**", Password = "******", UserRole = "admin" }; dbContext.Users.Add(user); dbContext.SaveChanges(); return(dbContext); }
private static void RunMigrations(string databaseName, TodoDbContext todoDbContext, ILogger logger) { logger.LogInformation("About to delete test database {TestDatabaseName} ...", databaseName); bool hasDeleteDatabase = todoDbContext.Database.EnsureDeleted(); // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (hasDeleteDatabase) { logger.LogInformation("Test database {TestDatabaseName} has been successfully deleted", databaseName); } else { logger.LogInformation("Could not find any test database {TestDatabaseName} to delete", databaseName); } logger.LogInformation("About to run migrations against test database {TestDatabaseName} ...", databaseName); IMigrator databaseMigrator = todoDbContext.GetInfrastructure().GetRequiredService <IMigrator>(); databaseMigrator.Migrate(); logger.LogInformation("Migrations have been successfully run against test database {TestDatabaseName}", databaseName); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TodoDbContext dbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Todo V1"); c.RoutePrefix = string.Empty; }); app.UseExceptionHandling(); app.UseCorrelationId(); app.UseRequestLogging(); app.UseContentLocation(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseGraphQL().UsePlayground(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // Seed database only if seeding is enabled in appsettings (default = true) if (Configuration.GetValue <bool>(Constants.SeedKey)) { dbContext.Seed(); } }
public TodosController(TodoDbContext context) { _context = context; //if (context.TodoItems.Count() == 0) //{ // context.TodoItems.Add(new TodoItem // { // Id = 1, // Name = "Wakup at 6", // Description = "This is a wake up at 6 description", // IsCompleted = false // }); // context.TodoItems.Add(new TodoItem // { // Id = 2, // Name = "Exercise at 7", // Description = "Exercise at 7", // IsCompleted = false // }); // context.SaveChanges(); //} }
public MainWindow() { InitializeComponent(); if (!DesignerProperties.GetIsInDesignMode(this)) { using (var dbContext = new TodoDbContext()) { dbContext.Database.Migrate(); } var newTodoItemViewModel = new NewTodoItemViewModel(() => new TodoDbContext()); NewTodoItemView.DataContext = newTodoItemViewModel; var showTodoListViewModel = new ShowTodoListViewModel(() => new TodoDbContext()); ShowTodoListView.DataContext = showTodoListViewModel; showTodoListViewModel.Observe(newTodoItemViewModel); showTodoListViewModel.Initialize(); Resources.Add("RemoveTodoItemCommand", new RemoveTodoItemCommand(() => new TodoDbContext())); } }
public async void AddItemToDatabase_ItemCountOne_ReturnOneItem() { var options = new DbContextOptionsBuilder <TodoDbContext>() .UseCosmos( accountEndpoint: "https://localhost:8081", accountKey: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", databaseName: "TodoList") .UseLoggerFactory(new LoggerFactory( new[] { new LogToActionLoggerProvider((log) => { _output.WriteLine(log); }) })) .Options; //Arrange using (var context = new TodoDbContext(options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var item = new quickstartcore31.Models.Item(); item.Completed = false; item.Description = "Todo 123"; item.Name = "Todo"; item.Id = Guid.NewGuid().ToString(); context.Add(item); context.SaveChanges(); } //act using (var context = new TodoDbContext(options)) { var inMemoryRepository = new CosmoDBEFRepository <Models.Item>(context); Expression <Func <Models.Item, bool> > all = (i) => true; var fetchedItem = await inMemoryRepository.GetItemsAsync(all); //Assert Assert.Single(fetchedItem); } //Assert.Equal(EntityState.Added, context.Entry(item).State); }
public async Task Handle_WhenUserHasPermission_ShouldNotThrowException() { // Arrange var userId = Guid.NewGuid(); var command = new CreateTodoCommand { UserId = userId, Name = "todo one", IsComplete = true }; var rpcResponse = new IsUserAllowedResponse { IsAllowed = true }; rpcPermissionsMock.ClientMock.Setup(x => x.IsUserAllowed(It.IsAny <IsUserAllowedRequest>(), It.IsAny <CallOptions>())).Returns(rpcResponse); var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { var sut = new CreateTodoCommandHandler(context, mapper, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); // Act var result = await sut.Handle(command, new CancellationToken(false)); } }
static async Task DeleteTodo(HttpContext http) { if (!http.Request.RouteValues.TryGet("id", out int id)) { http.Response.StatusCode = 400; return; } using var db = new TodoDbContext(); var todo = await db.Todos.FindAsync(id); if (todo == null) { http.Response.StatusCode = 404; return; } db.Todos.Remove(todo); await db.SaveChangesAsync(); http.Response.StatusCode = 204; }
public async void AddItemToDatabase_ItemCountOne_ReturnOneItem() { var options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase($"TodoList{Guid.NewGuid()}") .UseLoggerFactory(new LoggerFactory(new[] { new LogToActionLoggerProvider((log) => { _output.WriteLine(log); }) })) .Options; //Arrange using (var context = new TodoDbContext(options)) { context.Database.OpenConnection(); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var item = new quickstartcore31.Models.Item(); item.Completed = false; item.Description = "Todo 123"; item.Name = "Todo"; item.Id = Guid.NewGuid().ToString(); context.Add(item); context.SaveChanges(); } //act using (var context = new TodoDbContext(options)) { var inMemoryRepository = new CosmoDBEFRepository <Models.Item>(context); Expression <Func <Models.Item, bool> > all = (i) => true; var fetchedItem = await inMemoryRepository.GetItemsAsync(all); //Assert Assert.Single(fetchedItem); } //Assert.Equal(EntityState.Added, context.Entry(item).State); }
public async void CanDeleteTodo() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("GetTodoName") .Options; using (TodoDbContext context = new TodoDbContext(options)) { Todo task = new Todo(); task.Title = "test"; context.Todos.Add(task); context.SaveChanges(); context.Todos.Remove(task); context.SaveChanges(); var taskTitle = await context.Todos.ToListAsync(); Assert.DoesNotContain(task, taskTitle); } }
public void CanReadTodoList() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; using (TodoDbContext context = new TodoDbContext(options)) { // Arrange TodoList todoList = new TodoList(); todoList.Name = "Daily"; TodoListController todoListController = new TodoListController(context); var y = todoListController.Post(todoList); // Act var x = todoListController.Get(); // Assert Assert.Single(x); } }
public async void CanDeleteAList() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("GetTodoListName") .Options; using (TodoDbContext context = new TodoDbContext(options)) { TodoList list = new TodoList(); list.ListTitle = "test"; context.TodoLists.Add(list); context.SaveChanges(); context.TodoLists.Remove(list); context.SaveChanges(); var listContents = await context.TodoLists.ToListAsync(); Assert.DoesNotContain(list, listContents); } }
public async Task SeedAsync(TodoDbContext context, ILogger <TodoDbContextSeed> logger, int?retry = 0) { int retryForAvaiability = retry.Value; try { if (!context.Todos.Any()) { context.Todos.AddRange(new List <Todo> { new Todo { Name = "Test name 1", Content = "Test content 1" }, new Todo { Name = "Test name 2", Content = "Test content 2" }, new Todo { Name = "Test name 3", Content = "Test content 3" }, new Todo { Name = "Test name 4", Content = "Test content 4" }, }); await context.SaveChangesAsync(); } } catch (Exception ex) { if (retryForAvaiability < 5) { retryForAvaiability++; logger.LogError(ex, "EXCEPTION ERROR while migrating {DbContextName}", nameof(TodoDbContext)); await SeedAsync(context, logger, retryForAvaiability); } } }
private static void SetupDatabase(IServiceCollection services) { ServiceProvider serviceProvider = services.BuildServiceProvider(); using IServiceScope serviceScope = serviceProvider.CreateScope(); TodoDbContext todoDbContext = serviceScope.ServiceProvider.GetRequiredService <TodoDbContext>(); ILogger logger = serviceProvider.GetRequiredService <ILogger <TestWebApplicationFactory> >(); string databaseName = todoDbContext.Database.GetDbConnection().Database; logger.LogInformation("About to setup test database {TestDatabaseName} ...", databaseName); try { RunMigrations(databaseName, todoDbContext, logger); } catch (Exception exception) { logger.LogError("Failed to run migrations against test database {TestDatabaseName}", exception, databaseName); throw; } logger.LogInformation("Test database {TestDatabaseName} has been successfully setup", databaseName); }
public void CanUpdateTodoItem() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("Test3Database").Options; using (TodoDbContext context = new TodoDbContext(options)) { // Arrange TodoItem datItem1 = new TodoItem(); datItem1.ID = 1; datItem1.Name = "walk the dog"; datItem1.IsComplete = false; datItem1.DatListID = 1; // note: ID must be the same in order to update TodoItem datItem2 = new TodoItem(); datItem2.ID = 1; datItem2.Name = "pet the dog"; datItem2.IsComplete = true; datItem2.DatListID = 2; TodoController ic = new TodoController(context); // Act var created1 = ic.Create(datItem1); var result1 = ic.Update(datItem1.ID, datItem2); var result2 = ic.GetById(datItem1.ID); // Assert Assert.Equal(datItem2.Name, result2.Result.Value.Name); Assert.Equal(datItem2.IsComplete, result2.Result.Value.IsComplete); Assert.Equal(datItem2.DatListID, result2.Result.Value.DatListID); } }
public TodoUow(TodoDbContext context) { InitialiseDbContext(context); }