public List <IBaseModel> Save(List <IBaseModel> model) { IBaseEntity mappedEntity = null; List <IBaseEntity> returnedEntities = new List <IBaseEntity>(); Type modelType = null; Type entityType; try { var toSave = model.Cast <IBaseModel>().ToList(); if (model.Select(x => x.GetType()) .Distinct() .Count() > 1) { throw new Exception("Paramenter Dto must contain list of same type"); } modelType = model.First().GetType(); entityType = _mapper.ConfigurationProvider.GetAllTypeMaps() .Where(x => x.SourceType == modelType) .FirstOrDefault() .DestinationType; using (ToDoContext context = new ToDoContext()) { foreach (var baseItem in model) { mappedEntity = _mapper.Map(baseItem, baseItem.GetType(), entityType) as IBaseEntity; if (baseItem.ID == 0) { mappedEntity.CreatedDate = DateTime.UtcNow; context.Add(mappedEntity); } returnedEntities.Add(mappedEntity); } context.SaveChanges(); } } catch (Exception) { throw; } return(returnedEntities.Select(x => _mapper.Map(x, entityType, modelType) as IBaseModel).ToList()); }
public async Task Test_Updating_The_ToDo_Title_Completed_Order() { /* * Given that I have a command to update a ToDo's title, complete, & order * When I handle that command * Then I should update the ToDo * */ const string NEW_TITLE = "New Title"; const bool NEW_COMPLETED = false; const int NEW_ORDER = 523; var options = new DbContextOptionsBuilder <ToDoContext>() .UseInMemoryDatabase("order_title_completed_writes_to_database") .Options; var fakeCommandProcessor = new FakeCommandProcessor(); var toDoItem = new ToDoItem { Title = "Title", Completed = true, Order = 10 }; using (var context = new ToDoContext(options)) { context.ToDoItems.Add(toDoItem); context.SaveChanges(); } var command = new UpdateToDoCommand(toDoItem.Id, NEW_TITLE, NEW_COMPLETED, NEW_ORDER); var handler = new UpdateToDoCommandHandlerAsync(options, fakeCommandProcessor); await handler.HandleAsync(command); using (var context = new ToDoContext(options)) { Assert.AreEqual(1, context.ToDoItems.Count()); Assert.AreEqual(NEW_TITLE, context.ToDoItems.Single().Title); Assert.AreEqual(NEW_COMPLETED, context.ToDoItems.Single().Completed); Assert.AreEqual(NEW_ORDER, context.ToDoItems.Single().Order); } // Should not send task complete event Assert.IsFalse(fakeCommandProcessor.SentCompletedEvent); }
private void SeedKlienci(ToDoContext context) { for (int i = 1; i <= 5; i++) { var klient = new Klient() { KlientID = i, Nazwa = "darek" + i.ToString(), Addres = "Lodz_" + i.ToString(), Komorka = "12345678" + i.ToString(), DataUrodzenia = DateTime.Now.AddDays(-i - 40), EmailID = "darek" + i.ToString() + "@o2.pl" }; context.Set <Klient>().AddOrUpdate(klient); } context.SaveChanges(); }
public TodoController(ToDoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { // Create a new TodoItem if collection is empty, // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Fügen Sie ein neues ToDo hinzu. ", DueDate = DateTime.Today.AddDays(1), Operator = "Sie" }); _context.SaveChanges(); } }
public void Delete(IEnumerable <ToDo> todos) { using (var db = new ToDoContext()) { foreach (var todo in todos) { var existing = db.ToDos.FirstOrDefault(t => t.ToDoId == todo.ToDoId); if (existing != null) { db.ToDos.Remove(existing); } } db.SaveChanges(); } }
public ActionResult UserInfoModify([Bind(Include = "UserId,Name,Email,Password,ConfirmPassword,SecretWord")] UserModel userModel) { if (Session["LOGGED_USERID"] == null || Session["LOGGED_USERNAME"] == null) { return(RedirectToAction("Index", "Login")); } userModel.ModifiedDate = DateTime.Now; if (ModelState.IsValid) { db.Entry(userModel).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "ToDoList")); } return(View(userModel)); }
private void SeedZadania(ToDoContext context) { var idUzytkownika = context.Set <Uzytkownik>().Where(u => u.UserName == "*****@*****.**").FirstOrDefault().Id; for (int i = 1; i <= 5; i++) { var zad = new Zadanie() { Id = i, Nazwa = "Zadanie" + i.ToString(), Opis = "Opis zadania" + i.ToString(), Termin = DateTime.Now.AddDays(-i), Status = (((i % 2 + 2) % 2 == 0) ? true : false) }; context.Set <Zadanie>().AddOrUpdate(zad); } context.SaveChanges(); }
private void SaveListItem(ViewModel model, string state) { using (ToDoContext db = new ToDoContext()) { var item = db.ListItems.Find(model.item.Id); item.Id = model.item.Id; if (state == null) { item.State = model.item.State; } else { item.State = state; } item.Deadline = model.item.Deadline; db.SaveChanges(); } }
public static void seedUsers(ToDoContext context) { if (!context.Users.Any()) { var userData = System.IO.File.ReadAllText("Data/UserSeedData.json"); var users = JsonConvert.DeserializeObject <List <User> >(userData); foreach (var user in users) { byte[] passwordHash, passwordSalt; CreatPasswordHash("password", out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.UserName = user.UserName.ToLower(); context.Users.Add(user); } context.SaveChanges(); } }
public ActionResult Index(ViewModel model, string submitButton) { if (ModelState.IsValid) { if (model.item.Id == null) { using (ToDoContext db = new ToDoContext()) { model.item.State = "new"; db.ListItems.Add(model.item); db.SaveChanges(); } } else { switch (submitButton) { case "Save": SaveListItem(model, null); break; //case "Delete": // using (ToDoContext db = new ToDoContext()) // { // db.ListItems.Attach(model.item); // db.ListItems.Remove(model.item); // db.SaveChanges(); // } // break; case "Start": SaveListItem(model, "in progress"); break; case "Complete": SaveListItem(model, "complete"); break; } } } List <ListItem> listItems = GetListItems("new", "in progress").ToList(); model.listItems = listItems; return(View(model)); }
public async Task Test_Retrieving_All_Tasks() { /* * Given that I have a database with many ToDos * When I retrieve a a page of those todos * Then I should get an interable view model for them * */ var options = new DbContextOptionsBuilder <ToDoContext>() .UseInMemoryDatabase(databaseName: "Retrieving_tasks_from_database") .Options; using (var context = new ToDoContext(options)) { context.ToDoItems.Add(new ToDoItem() { Title = "Make test pass" }); context.ToDoItems.Add(new ToDoItem() { Title = "Make test pass" }); context.ToDoItems.Add(new ToDoItem() { Title = "Make test pass" }); context.ToDoItems.Add(new ToDoItem() { Title = "Make test pass" }); context.ToDoItems.Add(new ToDoItem() { Title = "Make test pass" }); context.SaveChanges(); } var retriever = new ToDoQueryAllHandlerAsync(options); var request = await retriever.ExecuteAsync(new ToDoQueryAll(1, 3)); Assert.AreEqual(request.ToDoItems.Count(), 3); request = retriever.Execute(new ToDoQueryAll(2, 3)); //only two available on this page Assert.AreEqual(request.ToDoItems.Count(), 2); }
public async Task Test_Updating_a_ToDo_Title_and_Completed() { /* * Given that I have a command to pdate add a ToDo's Title and Completed * When I handle that command * Then I should update the ToDo * */ const string TODO_TITLE = "test_title"; var options = new DbContextOptionsBuilder <ToDoContext>() .UseInMemoryDatabase("titlecompleted_writes_to_database") .Options; var fakeCommandProcessor = new FakeCommandProcessor(); var toDoItem = new ToDoItem { Title = "This title will be changed" }; using (var context = new ToDoContext(options)) { context.ToDoItems.Add(toDoItem); context.SaveChanges(); } var command = new UpdateToDoCommand(toDoItem.Id, TODO_TITLE, true); var handler = new UpdateToDoCommandHandlerAsync(options, fakeCommandProcessor); await handler.HandleAsync(command); using (var context = new ToDoContext(options)) { Assert.AreEqual(1, context.ToDoItems.Count()); Assert.AreEqual(TODO_TITLE, context.ToDoItems.Single().Title); Assert.AreEqual(true, context.ToDoItems.Single().Completed); } // Has sent task complete event Assert.IsTrue(fakeCommandProcessor.SentCompletedEvent); }
public async void GetAll_gets_all_lists() { using (var context = new ToDoContext(_options)) { context.ToDoLists.Add(new ToDoList { Title = "12345", Items = new List <ToDoItem>() { new ToDoItem() { Title = "345", Description = "any", Position = 1 } } }); context.SaveChanges(); } using (var context = new ToDoContext(_options)) { var sut = new ListsController(context); var actionResult = await sut.GetAll(); Assert.NotEmpty(actionResult.Value); var list = actionResult.Value.First(); Assert.Equal(1, list.Id); Assert.Equal("12345", list.Title); Assert.Collection(list.Items, item => { Assert.Equal(1, item.Id); Assert.Equal("345", item.Title); Assert.Equal("any", item.Description); Assert.Equal(1, item.Position); } ); } }
private void OkBtn_Click(object sender, RoutedEventArgs e) { if (AreInputsValid()) { if (!isEdited) { item = new ToDoItem(); } SaveInputDataToObj(item); db.ToDoItems.AddOrUpdate(item); db.SaveChanges(); MainWindow.dataGrid.ItemsSource = db.ToDoItems.ToList(); Hide(); } else { MessageBox.Show("Plese complete all data"); } }
public void Handle(ToDoListMementoPropagatedEvent @event) { using (var db = new ToDoContext()) { int itemId = _identityMapper.GetModelId <ToDoList>(@event.Memento.Id); if (itemId.Equals(0)) { //ToDoList Not exists var _list = new Model.ToDoList() { Title = @event.Memento.Title, Description = @event.Memento.Description }; db.Lists.Add(_list); db.SaveChanges(); _identityMapper.Map <ToDoList>(_list.Id, @event.Memento.Id); } // otherwise it could be used for maintenance purposes } }
public void Map <TEntity>(int modelId, Guid aggregateId) { using (var db = new ToDoContext()) { var map = db.IdMap.FirstOrDefault(im => im.AggregateId == aggregateId) ?? new IdentityMap() { AggregateId = aggregateId }; var typeName = typeof(TEntity).Name; map.TypeName = typeName; map.ModelId = modelId; db.IdMap.Add(map); SaveToCache(modelId, aggregateId, typeName); db.SaveChanges(); } }
public async Task Test_Updating_The_ToDo_Order() { /* Given that I have a command to update a ToDo's complete When I handle that command Then I should update the ToDo */ const int NEW_ORDER = 523; var options = new DbContextOptionsBuilder<ToDoContext>() .UseInMemoryDatabase(databaseName: "order_writes_to_database") .Options; var fakeCommandProcessor = new FakeCommandProcessor(); var toDoItem = new ToDoItem() { Title = "This title won't be changed", Completed = true, Order = 10}; using (var context = new ToDoContext(options)) { context.ToDoItems.Add(toDoItem); context.SaveChanges(); } var command = new UpdateToDoCommand(toDoItem.Id, order: NEW_ORDER); var handler = new UpdateToDoCommandHandlerAsync(options, fakeCommandProcessor); await handler.HandleAsync(command); using (var context = new ToDoContext(options)) { Assert.AreEqual(1, context.ToDoItems.Count()); Assert.AreEqual(toDoItem.Title, context.ToDoItems.Single().Title); Assert.AreEqual(true, context.ToDoItems.Single().Completed); Assert.AreEqual(NEW_ORDER, context.ToDoItems.Single().Order); } // Should not send task complete event Assert.IsFalse(fakeCommandProcessor.SentCompletedEvent); }
public IActionResult RegisterUser([FromBody] RegisterUserDto usertodo) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else { User newuser = new User { Email = usertodo.Email, FirstName = usertodo.FirstName, LastName = usertodo.LastName }; var _passwordHash = _passwordHasher.HashPassword(newuser, usertodo.Password); newuser.PasswordHash = _passwordHash; _todoContext.Users.Add(newuser); _todoContext.SaveChanges(); return(Ok()); } }
public IActionResult Create([FromBody] TodoItem item) { try { if (item == null || !ModelState.IsValid) { return BadRequest(ErrorCode.TodoItemNameAndNotesRequired.ToString()); } bool itemExists = _toDoRepository.DoesItemExist(item.Id); if (itemExists) { return StatusCode(StatusCodes.Status409Conflict, ErrorCode.TodoItemIDInUse.ToString()); } _toDoRepository.Insert(item); _DbContext.SaveChanges(); } catch (Exception) { return BadRequest(ErrorCode.CouldNotCreateItem.ToString()); } return CreatedAtRoute("GetSingleItem", new { id = item.Id }, item); }
public void Put(IEnumerable <ToDo> todos) { using (var db = new ToDoContext()) { foreach (var todo in todos ?? Enumerable.Empty <ToDo>()) { var existing = db.ToDos.FirstOrDefault(t => t.ToDoId == todo.ToDoId); if (existing == null) { db.ToDos.Add(todo); } else { existing.Title = todo.Title; existing.Completed = todo.Completed; } } db.SaveChanges(); } }
private void Button_Click(object sender, RoutedEventArgs e) { if (TxtName.Text.Length == 0) { errormessage.Text = "Enter an naeme."; TxtName.Focus(); } else if (TxtDescription.Text.Length == 0) { errormessage.Text = "Enter an description."; TxtDescription.Focus(); } else { string name = TxtName.Text; string description = TxtDescription.Text; var status = cmbStatus.SelectedValue; var deadline = dtdeadline.DisplayDate; var boardCard = new BoardCard { Description = description, Name = name, Status = (Status)status, Deadline = deadline, UserId = Globals.LoggedInUser.Id, CreatedDate = DateTime.Now, UpdatedDate = DateTime.Now }; errormessage.Text = ""; _dbContext.Boards.Add(boardCard); _dbContext.SaveChanges(); MessageBox.Show("Added Successfully"); BoardCards boardCards = new BoardCards(); boardCards.Show(); this.Close(); } }
public IActionResult Brisanje(long id) { Uredjaj uredjaj = _context.Uredjaji.Find(id); if (uredjaj == null) { return(NotFound()); } var mozda = (from nn in _context.OsobaUredjaj where nn.UredjajId == id select new { Uredjaj = nn.Uredjaj.Naziv }).FirstOrDefault(); if (mozda != null) { return(BadRequest("Uredjaj nije izbrisan zato sto je nekada vec bio koriscen.")); } _context.Uredjaji.Remove(uredjaj); _context.SaveChanges(); return(Ok("Uredjaj je izbrisan iz baze podataka.")); }
public void EnsureSeedData() { if (_DbContext.AllMigrationsApplied()) { if (!_DbContext.TodoItems.Any()) { var todoItem1 = new TodoItem { //Id = "6bb8a868-dba1-4f1a-93b7-24ebce87e243", Name = "Learn app development", Notes = "Attend Xamarin University", Done = true }; var todoItem2 = new TodoItem { //Id = "b94afb54-a1cb-4313-8af3-b7511551b33b", Name = "Develop apps", Notes = "Use Xamarin Studio/Visual Studio", Done = false }; var todoItem3 = new TodoItem { //Id = "ecfa6f80-3671-4911-aabe-63cc442c1ecf", Name = "Publish apps", Notes = "All app stores", Done = false, }; _repository.Insert(todoItem1); _repository.Insert(todoItem2); _repository.Insert(todoItem3); _DbContext.SaveChanges(); } } }
public async Task Delete_All_ToDos() { /* * Given that I have ToDos in my database * When I issue a command to delete all of them * Then I should remove the ToDos from the database */ var options = new DbContextOptionsBuilder <ToDoContext>() .UseInMemoryDatabase(databaseName: "Add_writes_to_database") .Options; using (var context = new ToDoContext(options)) { context.ToDoItems.Add(new ToDoItem() { Title = "Make delete test pass" }); context.ToDoItems.Add(new ToDoItem() { Title = "Make delete test pass" }); context.SaveChanges(); } var command = new DeleteAllToDosCommand(); var handler = new DeleteAllToDosCommandHandlerAsync(options); await handler.HandleAsync(command); using (var context = new ToDoContext(options)) { Assert.IsFalse(context.ToDoItems.Any()); } }
public User Registration(UserVM registrationUser) { var users = _toDoContext.Users.ToList(); User newUser = new User() { Username = registrationUser.Username, Password = registrationUser.Password, UserRole = "User" }; for (int i = 0; i < users.Count; i++) { if (newUser.Username == users[i].Username) // it makes the usernames unique { return(null); } } _toDoContext.Users.Add(newUser); _toDoContext.SaveChanges(); return(newUser); }
public TodoController(ToDoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { // Create a new TodoItem if collection is empty, // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.TodoItems.Add(new TodoItem { Name = "Item2" }); _context.TodoItems.Add(new TodoItem { Name = "Item3" }); _context.TodoItems.Add(new TodoItem { Name = "Item3", IsComplete = true }); _context.SaveChanges(); } }
public void TestSettingsList() { SmartList list = new SmartList { Title = "Test List", HideCompleted = true }; db.SmartLists.Add(list); db.SaveChanges(); SmartList newlist = new SmartList { Id = list.Id, Title = "Test List", HideCompleted = false }; controller.SettingsList(newlist); db = new ToDoContext(); var lists = db.SmartLists.ToList(); newlist = lists.Last(l => l.Id == list.Id); var result = newlist.HideCompleted != list.HideCompleted; Assert.IsTrue(result); //list = db.SmartLists.ToList().Last(l => l.Id == list.Id); db.Entry(newlist).State = EntityState.Deleted; db.SaveChanges(); }
public ActionResult Index([Bind(Include = "Name,Email,Password,ConfirmPassword,SecretWord")] UserModel userModel) { var userInfo = db.User.Where(x => x.Email == userModel.Email).FirstOrDefault(); if (userInfo != null) { return(Json(new { responseCode = "400", responseText = "Email Already Exist" }, JsonRequestBehavior.AllowGet)); } userModel.CreatedDate = DateTime.Now; userModel.ModifiedDate = DateTime.Now; if (ModelState.IsValid) { db.User.Add(userModel); db.SaveChanges(); return(Json(new { responseCode = "200", responseText = "Success" }, JsonRequestBehavior.AllowGet)); } return(Json(new { responseCode = "400", responseText = "Something Went Wrong" }, JsonRequestBehavior.AllowGet)); }
public void Save() { _context.SaveChanges(); }
public void Create(User obj) { _dbContext.Users.Add(obj); _dbContext.SaveChanges(); }