Example #1
0
        public async Task UpdateTodo()
        {
            var fakeUserid = Guid.NewGuid();
            var fakeType   = new TodoType
            {
                Name = "活动"
            };

            fakeType.AddModel(fakeUserid);
            var fakeTodo = new Todo
            {
                Title    = "更新明日社区活动",
                TodoType = fakeType,
                OffTime  = DateTime.Now
            };

            fakeTodo.AddModel(fakeUserid);
            _inMemoryContext.Add <TodoType>(fakeType);
            _inMemoryContext.Add <Todo>(fakeTodo);
            await _inMemoryContext.SaveChangesAsync();

            fakeTodo.Title = "更新明日团队活动1";
            fakeTodo.UpdateModel(fakeUserid);
            await _todoService.UpdateTodoAsync(fakeTodo);

            var title = (await _inMemoryContext.Todos.FindAsync(fakeTodo.Id)).Title;

            Assert.Equal("更新明日团队活动1", title);
        }
        public async Task OverrideIOCContextResultsInChanges()
        {
            // Setup the TODO Db Context
            altTodoContext.RemoveRange(altTodoContext.TodoItems);
            altTodoContext.Add <TodoItem>(new TodoItem()
            {
                Id = 1, IsComplete = true, Name = "Make an override"
            });
            altTodoContext.Add <TodoItem>(new TodoItem()
            {
                Id = 2, IsComplete = false, Name = "Test the override"
            });
            altTodoContext.Add <TodoItem>(new TodoItem()
            {
                Id = 3, IsComplete = false, Name = "Document override"
            });
            altTodoContext.Add <TodoItem>(new TodoItem()
            {
                Id = 4, IsComplete = true, Name = "Make test project"
            });
            altTodoContext.Add <TodoItem>(new TodoItem()
            {
                Id = 5, IsComplete = true, Name = "Run test project"
            });
            altTodoContext.SaveChanges();
            var ctrllr    = this.GetTodoController(useAlt: true);
            int itemCount = (await ctrllr.GetTodoItems()).Value.ToList().Count;

            Assert.AreEqual(altTodoContext.TodoItems.Count(), itemCount);
        }
        public void Setup()
        {
            _contextOptions = new DbContextOptionsBuilder <TodoContext>()
                              .UseInMemoryDatabase("ToDoList")
                              .Options;
            using (var context = new TodoContext(_contextOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                context.Add(new TodoItem()
                {
                    Name = "Doing Something", IsCompleted = true
                });
                context.Add(new TodoItem()
                {
                    Name = "Learn Something", IsCompleted = true
                });
                context.Add(new TodoItem()
                {
                    Name = "Delete Something", IsCompleted = false
                });

                context.SaveChanges();
            }
        }
Example #4
0
        public async Task OverrideIOCContextResultsInChanges()
        {
            // Setup the TODO Db Context
            var optionsBuilder = new DbContextOptionsBuilder <TodoContext>();

            optionsBuilder.UseInMemoryDatabase("TodoList");

            var filledList = new TodoContext(optionsBuilder.Options);

            filledList.Add <TodoItem>(new TodoItem()
            {
                IsComplete = true, Name = "Make an override"
            });
            filledList.Add <TodoItem>(new TodoItem()
            {
                IsComplete = false, Name = "Test the override"
            });
            filledList.Add <TodoItem>(new TodoItem()
            {
                IsComplete = false, Name = "Document override"
            });
            filledList.Add <TodoItem>(new TodoItem()
            {
                IsComplete = true, Name = "Make test project"
            });
            filledList.Add <TodoItem>(new TodoItem()
            {
                IsComplete = true, Name = "Run test project"
            });
            filledList.SaveChanges();
            var ctrllr    = Get <TodoController>(filledList);
            int itemCount = (await ctrllr.GetTodoItems()).Value.ToList().Count;

            Assert.AreEqual(filledList.TodoItems.Count(), itemCount);
        }
Example #5
0
        public int AddList(string name)
        {
            var existing = _todoContext.Lists
                           .Select(l => new { l.Id, l.Name })
                           .FirstOrDefault(l => l.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));

            if (existing != null)
            {
                _logger?.LogInformation("Did not add list {ListName}, because list {ListId} did already exist.", name, existing.Id);
                return(existing.Id);
            }

            var entity = new TodoList()
            {
                Name = name,
            };

            _logger.LogDebug("Adding list {ListName}", name);

            _todoContext.Add(entity);
            _todoContext.SaveChanges();

            _pushService.SendListCreated(entity.Id, entity.Name);

            return(entity.Id);
        }
        public async Task <ActionResult <TodoItem> > PostTodoType(TodoType todoType)
        {
            _context.Add(todoType);
            await _context.SaveChangesAsync();

            //return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
            return(CreatedAtAction(nameof(GetTodoType), new { id = todoType.Id }, todoType));
        }
Example #7
0
        public async Task <int> CreateTodo(Todo todo)
        {
            _context.Add(todo);
            await _context.SaveChangesAsync();

            return(todo.Id);
        }
Example #8
0
            public async Task <Guid> Handle(Command c, CancellationToken ct)
            {
                if (c is null)
                {
                    throw new ArgumentNullException(nameof(c));
                }

                var strategy = _context.Database.CreateExecutionStrategy();

                var id = await strategy.ExecuteAsync(async (ct) => {
                    var newTodoId = Guid.NewGuid();

                    var newTodo = new DbTodo {
                        Done       = false,
                        DueDateUtc = c.DueDate,
                        Id         = newTodoId,
                        Name       = c.Name,
                        Priority   = c.Priority.Value
                    };

                    _context.Add(newTodo);

                    await _context.SaveChangesAsync(ct).ConfigureAwait(false);

                    return(newTodoId);
                }, ct).ConfigureAwait(false);

                return(id);
            }
Example #9
0
        public IActionResult Register(UserVM userVM)
        {
            using (TodoContext _context = new TodoContext())
            {
                if (userVM == null || string.IsNullOrEmpty(userVM.Username) || string.IsNullOrEmpty(userVM.Password))
                {
                    return(BadRequest());
                }

                if (_context.Users.SingleOrDefault(u => u.Username == userVM.Username) != null)
                {
                    return(Conflict("Username is already registered."));
                }

                try
                {
                    _context.Add(new User
                    {
                        Username = userVM.Username,
                        Password = userVM.Password
                    });
                    _context.SaveChanges();

                    return(Ok());
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Example #10
0
        public async Task <ActionResult <TodoItem> > PostTodoItem(TodoItem item)
        {
            _context.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item));
        }
Example #11
0
        public TodoItem Add(TodoItem todoItem)
        {
            EntityEntry <TodoItem> entityEntry = _todoContext.Add(todoItem);

            _todoContext.SaveChanges();
            return(entityEntry.Entity);
        }
Example #12
0
        public async Task <int> CreateUser(AppUser appUser)
        {
            _context.Add(appUser);
            await _context.SaveChangesAsync();

            return(appUser.Id);
        }
Example #13
0
        public async Task <TodoItem> Add(TodoItem todoItem)
        {
            _todoContext.Add(todoItem);
            await _todoContext.SaveChangesAsync();

            return(todoItem);
        }
        public async Task <TodoItem> createItem(TodoItem itemModel)
        {
            _dbCotentext.Add(itemModel);
            await _dbCotentext.SaveChangesAsync();

            return(itemModel);
        }
Example #15
0
        public IActionResult RegisterUser(RegisterUser newuser)
        {
            User CheckEmail = _tContext.users
                              .Where(u => u.email == newuser.email)
                              .SingleOrDefault();

            if (CheckEmail != null)
            {
                ViewBag.errors = "That email already exists";
                return(RedirectToAction("Register"));
            }
            if (ModelState.IsValid)
            {
                PasswordHasher <RegisterUser> Hasher = new PasswordHasher <RegisterUser>();
                User newUser = new User
                {
                    user_id    = newuser.user_id,
                    first_name = newuser.first_name,
                    last_name  = newuser.last_name,
                    email      = newuser.email,
                    password   = Hasher.HashPassword(newuser, newuser.password)
                };
                _tContext.Add(newUser);
                _tContext.SaveChanges();
                ViewBag.success = "Successfully registered";
                return(RedirectToAction("Login"));
            }
            else
            {
                return(View("Register"));
            }
        }
        public async Task CreateAsync(TodoItem todoItem)
        {
            todoItem.Created = DateTime.Now;

            _context.Add(todoItem);
            await _context.SaveChangesAsync();
        }
Example #17
0
        public async Task <IActionResult> AddLangue(string id, [FromBody] Langue langue)
        {
            var user = await GetCandidat(id);

            if (user != null)
            {
                langue.candidat = user;
                _context.Add(langue);
                _context.SaveChanges();
                return(Ok(new
                {
                    langue = langue
                }));
            }
            return(NotFound());
        }
Example #18
0
        public async Task <IActionResult> AddCompetence(string id, [FromBody] Competence comp)
        {
            Candidat user = (Candidat)await userManager.FindByIdAsync(id);

            if (user != null)
            {
                comp.candidat = user;
                _context.Add(comp);
                _context.SaveChanges();
                return(Ok(new
                {
                    comp = comp
                }));
            }
            return(NotFound());
        }
Example #19
0
        private static void Seed(TodoContext todoContext)
        {
            string[] words = ("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque condimentum a libero ultrices congue. Vestibulum tellus lectus, gravida non fringilla at, scelerisque nec neque. Proin non nulla et nisl porta pharetra ut id massa. Pellentesque sit amet ante quam. Proin a maximus urna, at sagittis odio. Ut auctor urna ac nibh tempus porta. In eu orci felis. Nullam tempus justo ligula, ut dignissim mauris dictum ullamcorper. Morbi fermentum dictum tempor. Sed dictum enim quis pharetra consequat. Sed tempus quis lorem sit amet facilisis. Suspendisse sollicitudin lacus ac ultricies viverra. Etiam efficitur imperdiet mi. Praesent non dapibus lectus, venenatis congue urna. Praesent egestas hendrerit semper." +
                              "Phasellus ut laoreet neque. In dictum luctus libero vitae aliquet. Nulla eu velit orci. Vivamus libero ante, condimentum eget felis vel, aliquam viverra enim. Nulla nibh odio, rhoncus sed ex a, efficitur ullamcorper dolor. Ut tempor semper est, in lobortis nisi bibendum non. Nullam interdum, elit nec vehicula lobortis, nulla erat consequat ipsum, ac dapibus nisi nibh ut lectus." +
                              "Nam mattis nulla tincidunt tempor tincidunt. Sed vitae luctus neque. Duis nunc turpis, condimentum et enim nec, malesuada vehicula leo. Nullam in ligula feugiat, viverra nibh et, ultricies ipsum. Proin rhoncus congue nisi, eu interdum est. Etiam ornare, leo ac imperdiet malesuada, nisl quam dapibus justo, eu convallis neque metus nec urna. Fusce hendrerit dolor ut risus consequat semper. Sed sed enim lacus. Sed eget lorem lobortis, mollis urna vel, feugiat magna. Ut cursus erat massa, interdum cursus neque vulputate at. Aliquam luctus dictum augue a convallis." +
                              "Quisque molestie faucibus nisi a efficitur. Nam accumsan porta tellus, vel dictum nunc vulputate nec. In consectetur pulvinar sem, sit amet pharetra justo varius in. Nulla placerat pretium ultrices. Curabitur eu ex ultricies, commodo enim dapibus, bibendum purus. Aliquam suscipit eget quam eu imperdiet. Proin iaculis sollicitudin ante, quis porttitor nisl euismod ut. Proin lacinia ipsum quis elementum lobortis. Proin luctus mi eu congue tempus. Morbi commodo porta lacus a pharetra. Pellentesque ullamcorper sem arcu, a bibendum mi feugiat maximus. Suspendisse potenti." +
                              "Proin commodo felis tempor, maximus sem ac, volutpat ante. Nullam sed sollicitudin eros. Nulla nec lacus nibh. Quisque bibendum neque eu neque condimentum, eleifend mollis arcu sagittis. Etiam volutpat nunc orci, sit amet laoreet dolor commodo quis. Duis a tellus ultrices, consequat dui et, gravida dolor. Proin eu mi ac lacus malesuada ullamcorper. Duis pulvinar tortor quis bibendum blandit. Sed auctor porttitor risus sodales molestie. Cras quam nibh, tincidunt quis augue a, dapibus efficitur diam. Aliquam id tortor eget ante aliquet commodo non a nulla. Quisque mattis augue id urna pharetra rutrum. Nulla ipsum ante, molestie eu imperdiet in, semper et massa. Aenean velit ipsum, feugiat quis est nec, gravida fermentum lorem.")
                             .Split(' ');

            List <Todo> ts = new List <Todo>();
            Random      r  = new Random();

            for (int i = 0; i < 15; i++)
            {
                int    start = r.Next(0, words.Length - 11);
                int    end   = r.Next(start + 5, start + 10);
                string title = "";
                for (int j = start; j < end; j++)
                {
                    title += words[j] + " ";
                }
                Todo todo = new Todo
                {
                    UserId      = r.Next(0, 10) + 1,
                    IsCompleted = r.Next(0, 2) == 0,
                    Title       = title.Trim()
                };
                todoContext.Add(todo);
            }

            todoContext.SaveChanges();
        }
Example #20
0
        public async Task <IActionResult> Create([Bind("Username,JoinDate")] User user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(user);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(user));

            /*if (ModelState.IsValid)
             * {
             *  _context.Add(user);
             *  await _context.SaveChangesAsync();
             *  return RedirectToAction(nameof(Index));
             * }
             * return View(user);*/
        }
        public async Task <Entities.Todo> AddAsync(Entities.Todo todo)
        {
            todo.Id = todo.Id == Guid.Empty ? Guid.NewGuid() : todo.Id;
            _todoContext.Add(todo);
            await _todoContext.SaveChangesAsync();

            return(todo);
        }
Example #22
0
        public IActionResult AddList(Todolist obj)
        {
            db.Add(obj);
            //db.Entry(obj).State = EntityState.Added;
            db.SaveChanges();

            return(new ObjectResult("Task Added successfully!"));
        }
Example #23
0
        public async Task <IActionResult> Login([FromBody] Candidat model)
        {
            var user = await userManager.FindByEmailAsync(model.Email);

            if (user != null && await userManager.CheckPasswordAsync(user, model.password))
            {
                if (user != null && user.EmailConfirmed != true)
                {
                    return(Ok(new
                    {
                        status = "500"
                    }));
                }
                var userRoles = await userManager.GetRolesAsync(user);

                var authClaims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.Email),
                    new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                foreach (var userRole in userRoles)
                {
                    authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                }
                var token        = GenerateToken(authClaims);
                var reftoken     = GenerateRefreshToken();
                var refreshtoken = new RefreshToken
                {
                    refresh_token = reftoken,
                    access_token  = token,
                    candidat      = (Candidat)user
                };
                _context.Add(refreshtoken);
                _context.SaveChanges();

                /*  var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
                 * var email = "";
                 * var token = new JwtSecurityToken(
                 *    issuer: _configuration["JWT:ValidIssuer"],
                 *    audience: _configuration["JWT:ValidAudience"],
                 *    expires: DateTime.Now.AddMinutes(5),
                 *    claims : authClaims,
                 *    signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                 *    );*/
                return(Ok(new
                {
                    token = token,
                    refreshtoken = reftoken,
                    user = user
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }
Example #24
0
        async public void saveChanges(Todo todo)
        {
            using (DbContext db = new TodoContext()){
                db.Add(todo);
                await db.SaveChangesAsync();

                Console.WriteLine("Done Writing to db");
            }
        }
Example #25
0
        public ActionResult <TodoItem> PostTodoItem([FromBody] TodoItem todoItem)
        {
            System.Diagnostics.Debug.WriteLine("api/TodoItems/ as called");
            System.Diagnostics.Debug.WriteLine(todoItem.Content);

            _context.Add(todoItem);
            _context.SaveChanges();
            return(CreatedAtAction(nameof(GetTodoItems), new { id = todoItem.Id }, todoItem));
        }
Example #26
0
 public IActionResult Post([FromBody] TodoItem item)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     _context.Add(item);
     _context.SaveChanges();
     return(CreatedAtAction("GetById", new { id = item.Id }, item));
 }
        public async Task <ActionResult <TodoItem> > PostTodoItem(TodoItem todoItem)
        {
            _context.Add(todoItem);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTodoItem", new TodoItem()
            {
                Id = todoItem.Id
            }, todoItem));
        }
Example #28
0
        internal void Add(IFormCollection formCollection)
        {
            Todo todo = new Todo();

            todo.Title = formCollection["title"];

            todoContext.Add(todo);

            todoContext.SaveChanges();
        }
Example #29
0
        public IActionResult Create(string Birthday, string Name)
        {
            Person p = new Person();

            p.Birthday = Birthday;
            p.Name     = Name;
            _context.Add(p);
            _context.SaveChanges();
            return(View(_context.People.Find(p.Id)));
        }
Example #30
0
        public async Task <IActionResult> Create([Bind("ID,Subject,Category,Goal,PlannedSessions, ExecutedSessions,PercentageAccomplished,DueDate,Comments")] Todo todo)
        {
            if (ModelState.IsValid)
            {
                _context.Add(todo);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(todo));
        }