コード例 #1
0
        public async void TestPostTodoToDb()
        {
            ToDoDbContext _context;
            DbContextOptions <ToDoDbContext> options = new DbContextOptionsBuilder <ToDoDbContext>()
                                                       .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            TestServer _server;
            HttpClient _client;

            _server = new TestServer(new WebHostBuilder()
                                     .UseStartup <Startup>());
            _client = _server.CreateClient();

            using (_context = new ToDoDbContext(options))
            {
                List <ToDo> testTodos = GetTodosObjects();

                // Arrange
                TaskManagerController taskManagerController = new TaskManagerController(_context);

                // Act
                var result = taskManagerController.Post(testTodos[0]);
                //var response = await _client.PostAsync("", HttpResponseMessage(StatusCodeResult))

                // Assert
                Assert.NotNull(result);
            }
        }
コード例 #2
0
        public async void CanReadAToDoList()
        {
            DbContextOptions <ToDoDbContext> options =
                new DbContextOptionsBuilder <ToDoDbContext>()
                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                ToDoList list = new ToDoList
                {
                    ID     = 1,
                    Name   = "test list",
                    IsDone = true
                };

                ToDoListController tdlc = new ToDoListController(context);
                await tdlc.Create(list);

                var findList = await tdlc.GetById(list.ID);

                var result   = (ObjectResult)findList.Result;
                var readList = (ToDoList)result.Value;

                Assert.Equal(list.Name, readList.Name);
            }
        }
コード例 #3
0
ファイル: UnitTest1.cs プロジェクト: Inkh/Lab19WebAPI
        public async void ToDoListUpdateTest()
        {
            DbContextOptions <ToDoDbContext> options =
                new DbContextOptionsBuilder <ToDoDbContext>()
                .UseInMemoryDatabase("todoListUpdate")
                .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                //CREATE
                //Arrange
                ToDoList myList = new ToDoList();
                myList.Name = "new list";

                context.ToDoList.Add(myList);
                context.SaveChanges();

                //READ
                var list = await context.ToDoList.FirstOrDefaultAsync(t => t.Name == myList.Name);

                list.Name = "another name";
                context.Update(list);
                context.SaveChanges();

                var newList = await context.ToDoList.FirstOrDefaultAsync(t => t.Name == myList.Name);

                Assert.Equal("another name", newList.Name);
            }
        }
コード例 #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var todoIdStr = Request.QueryString["Id"];
            var todoId    = Convert.ToInt32(todoIdStr);

            if (!IsPostBack)
            {
                var connStr = ConfigurationManager
                              .ConnectionStrings["DefaultConnection"].ConnectionString;
                using (var db = new ToDoDbContext(connStr))
                {
                    var todo = db.ToDoItems.Single(a => a.Id == todoId);

                    ToDoId.Value      = todo.Id.ToString();
                    ToDoText.Value    = todo.Item;
                    Completed.Checked = todo.Completed;

                    Session["Hello"] = "World";
                    Helpers.LogWebDiagnostic("ToDos", "WebForms",
                                             "Checking on Edit Load method",
                                             new Dictionary <string, object> {
                        { "Watch", "This" }
                    });
                }
            }
        }
コード例 #5
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            // Set up the databases for the sample if needed.
            var env = host.Services.GetService <IWebHostEnvironment>();

            if (env.EnvironmentName == "Development")
            {
                using (var db = new ToDoDbContext(new TenantInfo {
                    ConnectionString = "Data Source=Data/ToDoList.db"
                }))
                {
                    db.Database.MigrateAsync().Wait();
                }

                using (var db = new ToDoDbContext(new TenantInfo {
                    ConnectionString = "Data Source=Data/Initech_ToDoList.db"
                }))
                {
                    db.Database.MigrateAsync().Wait();
                }
            }

            host.Run();
        }
コード例 #6
0
        public void Test_Delete(ToDoDbContext context)
        {
            var entry  = AddEntry(DateTime.Now);
            var result = _todoController.DeleteToDoItem(entry.Id);

            Assert.Equals(result.Value.Title, entry.Title);
        }
コード例 #7
0
        private void CheckForExpirations(object state)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                _dbContext = scope.ServiceProvider.GetService <ToDoDbContext>();

                DateTime today = DateTime.Today;

                //loop through to do lists and check if their reminder date expired
                _dbContext.ToDoLists
                .ToList()
                .ForEach(list =>
                {
                    if (list.IsReminded && list.EndDate.HasValue && today > list.EndDate.Value)
                    {
                        _logger.LogInformation($"ReminderService -> Found expired list with title '{list.Title}'");

                        SendEmail($"{_options.LinkToExpiredList}/{list.Id}", list.Owner);
                        list.IsReminded = false;
                    }
                });

                _dbContext.SaveChanges();
            }
        }
コード例 #8
0
 public HomeController(IMapper mapper, IUnitOfWork unitOfWork, IToDoRepository repository, ToDoDbContext context)
 {
     this.unitOfWork = unitOfWork;
     this.repository = repository;
     this.context    = context;
     this.mapper     = mapper;
 }
コード例 #9
0
 public async Task <List <ToDo> > GetAllToDos()
 {
     using (var toDoDbContext = new ToDoDbContext())
     {
         return(await toDoDbContext.ToDos.ToListAsync());
     }
 }
コード例 #10
0
ファイル: TestDataSeeder.cs プロジェクト: vietandy/ToDo
        public TestDataSeeder(ToDoDbContext context)
        {
            _context = context;

            _context.Database.EnsureDeleted();
            _context.Database.EnsureCreated();
        }
コード例 #11
0
        public IActionResult Post([FromBody] SignIn s)
        {
            // เช็ค userid, password
            var    db = new ToDoDbContext();
            var    u  = db.User.Find(s.UserId);
            string p  = Convert.ToBase64String(KeyDerivation.Pbkdf2(password: s.Password, salt: Convert.FromBase64String(u.Salt), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8));

            if (u.Password != p)
            {
                throw new Exception("รหัสผ่านไม่ถูกต้อง");
            }
            // สร้าง token
            var d = new SecurityTokenDescriptor();

            d.Subject            = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, u.Id), new Claim(ClaimTypes.Role, "user") });
            d.NotBefore          = DateTime.UtcNow;
            d.Expires            = DateTime.UtcNow.AddHours(3);
            d.IssuedAt           = DateTime.UtcNow;
            d.Issuer             = "ocsc";
            d.Audience           = "public";
            d.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567812345678")), SecurityAlgorithms.HmacSha256Signature);
            var    h     = new JwtSecurityTokenHandler();
            var    token = h.CreateToken(d);
            string t     = h.WriteToken(token);

            return(Ok(new { token = t }));
        }
コード例 #12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ToDoDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                DbSeeder.Migrate(context);
            }

#pragma warning disable 618
            Mapper.Initialize(cfg =>
#pragma warning restore 618
            {
                cfg.CreateMap <ToDo, ToDoDto>().ForMember(dest => dest.ToDoPriority, opt =>
                                                          opt.MapFrom(src => src.ToDoPriority.Name))
                .ForMember(dest => dest.Status, opt => opt.MapFrom(src =>
                                                                   src.Status.ToString()))
                .ForMember(dest => dest.ToDoTime, opt => opt.MapFrom(src =>
                                                                     src.ToDoTime.ToString("dd MMM yy HH:mm")))
                .ForMember(dest => dest.CreatedAt, opt => opt.MapFrom(src =>
                                                                      src.CreatedAt.ToString("dd MMM yy HH:mm")));
                cfg.CreateMap <AddNewToDoCommand, ToDo>().ForMember(dest => dest.ToDoTime,
                                                                    opt => opt.MapFrom(src => src.ConvertTime()))
                .ForMember(dest => dest.CreatedAt, opt => opt.MapFrom(
                               src => DateTime.Now))
                .ForMember(dest => dest.Status, opt => opt.MapFrom(
                               src => ToDoStatus.Open));
            });

            app.UseMvc();

            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
コード例 #13
0
ファイル: Activities.cs プロジェクト: bellmcp/todo-backend
        public IActionResult Get(uint id)
        {
            var db = new ToDoDbContext();
            var a  = db.Activity.Find(id);

            return(Ok(a));
        }
コード例 #14
0
ファイル: Activities.cs プロジェクト: bellmcp/todo-backend
        public IActionResult Get()
        {
            var db         = new ToDoDbContext();
            var activities = db.Activity.Select(s => s);

            return(Ok(activities));
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: Xealia/ToDoDb
        static void Main(string[] args)
        {
            var db   = new ToDoDbContext();
            var task = db.Task.First();

            Console.WriteLine(task.Description);
        }
コード例 #16
0
 public async Task <ToDo> GetToDoById(int id)
 {
     using (var toDoDbContext = new ToDoDbContext())
     {
         return(await toDoDbContext.ToDos.FindAsync(id));
     }
 }
コード例 #17
0
        public async void ListNumber()
        {
            //database set up
            DbContextOptions <ToDoDbContext> options = new DbContextOptionsBuilder <ToDoDbContext>()
                                                       .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                                       .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                // Arrange
                await context.TodoLists.AddRangeAsync(
                    new TodoList()
                {
                    Name = "Get Milk",
                },

                    new TodoList()
                {
                    Name = "Throw Away Milk",
                }
                    );

                await context.SaveChangesAsync();

                To_ListController controller = new To_ListController(context);

                // Act
                OkObjectResult   result = controller.Getall() as OkObjectResult;
                DbSet <TodoList> lists  = result.Value as DbSet <TodoList>;

                // Assert. Counts how many list number do you have
                Assert.Equal(2, await lists.CountAsync());
            }
        }// End of List number
コード例 #18
0
 public async Task <ToDo> GetToDoByName(string name)
 {
     using (var toDoDbContext = new ToDoDbContext())
     {
         return(await toDoDbContext.ToDos.FirstOrDefaultAsync(x => x.Name.ToLower() == name.ToLower()));
     }
 }
コード例 #19
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                // Remove the app's ApplicationDbContext registration.
                ServiceDescriptor descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions <ToDoDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                // Add ApplicationDbContext using an in-memory database for testing.
                services.AddDbContext <ToDoDbContext>(options =>
                {
                    options.UseSqlite("Data Source=ToDoTest.db");
                });

                ServiceProvider sp = services.BuildServiceProvider();

                using (IServiceScope scope = sp.CreateScope())
                {
                    IServiceProvider scopedServices = scope.ServiceProvider;
                    ToDoDbContext db = scopedServices.GetRequiredService <ToDoDbContext>();
                    db.Database.EnsureDeleted();
                    db.Database.Migrate();
                    db.LoadFixtures();
                }
            });
        }
コード例 #20
0
ファイル: TaskRepository.cs プロジェクト: mugtea/todoapi
        private Task GetTaskById(int id)
        {
            var todoContext = new ToDoDbContext();       //create instance dbcontext
            var isExist     = todoContext.Task.Find(id); //find list task by id

            return((Task)isExist);                       //return the result
        }
コード例 #21
0
        public GetToDoTest(InfraFixture infraFixture)
        {
            _httpClient = infraFixture.InfraInstance.HttpClient;
            var scope = infraFixture.InfraInstance.ServiceProvider.CreateScope();

            _dbContext = scope.ServiceProvider.GetRequiredService <ToDoDbContext>();
        }
コード例 #22
0
ファイル: TaskRepository.cs プロジェクト: mugtea/todoapi
        public Task GetTaskByTitle(string title)
        {
            var todoContext = new ToDoDbContext();                                     //create instance dbcontext
            var isExist     = todoContext.Task.Where(x => x.Title.ToLower() == title); //find list task by title

            return(isExist.FirstOrDefault());                                          //return the result
        }
コード例 #23
0
ファイル: ItemRepository.cs プロジェクト: trhasankara/ToDo
 public Item Update(Item item)
 {
     using var todoDbContext = new ToDoDbContext();
     todoDbContext.Items.Update(item);
     todoDbContext.SaveChanges();
     return(item);
 }
コード例 #24
0
ファイル: TaskRepository.cs プロジェクト: mugtea/todoapi
        public List <Task> GetIncomingTask(string status)
        {
            var temp        = new List <Task>();                                                                //create instance list task
            var todoContext = new ToDoDbContext();                                                              //create instance dbcontext
            var allTask     = todoContext.Task.ToList();                                                        //get all task from db

            if (status.ToLower() == "currentweek")                                                              //check if status
            {
                var todaydate     = DateTime.Now;                                                               //get date today
                var thisWeekStart = todaydate.AddDays(-(int)todaydate.DayOfWeek);                               //get start week date
                var thisWeekEnd   = thisWeekStart.AddDays(7).AddSeconds(-1);                                    //get latest week date
                temp = allTask.Where(x => x.ExpireDate > thisWeekStart && x.ExpireDate < thisWeekEnd).ToList(); //filter alltask where expiredate in current week
            }
            else if (status.ToLower() == "nextday")
            {
                var todaydate = DateTime.Now.AddDays(1).ToShortDateString();                            //get next day
                temp = allTask.Where(x => x.ExpireDate.ToShortDateString().Equals(todaydate)).ToList(); //filter alltask where expired date is next day
            }
            else if (status.ToLower() == "today")
            {
                var todaydate = DateTime.Now.ToShortDateString();                                       //get next day
                temp = allTask.Where(x => x.ExpireDate.ToShortDateString().Equals(todaydate)).ToList(); //filter alltask where expired date is to day
            }

            return(temp);
        }
コード例 #25
0
        public void CanDeleteAToDoList()
        {
            DbContextOptions <ToDoDbContext> options =
                new DbContextOptionsBuilder <ToDoDbContext>()
                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                ToDoList list = new ToDoList
                {
                    ID     = 1,
                    Name   = "test list",
                    IsDone = true
                };

                ToDoListController tdlc = new ToDoListController(context);
                var result = tdlc.Create(list).Result;

                var results = context.ToDoLists.Where(i => i.Name == "test list");
                Assert.Equal(1, results.Count());

                var remove = tdlc.Delete(list.ID);
                Assert.True(remove.IsCompletedSuccessfully);
            }
        }
コード例 #26
0
        public IActionResult Edit(Task edittedTask)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ToDoDbContext())
                {
                    var entityToEdit = db.Tasks.FirstOrDefault(t => t.Id == edittedTask.Id);
                    entityToEdit.Title    = edittedTask.Title;
                    entityToEdit.Comments = edittedTask.Comments;
                    db.SaveChanges();
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                ViewData["Error"] = "Leaving empty title or comment is not allowed!";
                if (string.IsNullOrWhiteSpace(edittedTask.Title))
                {
                    ViewData["TitleError"] = "bg-danger";
                }

                if (string.IsNullOrWhiteSpace(edittedTask.Comments))
                {
                    ViewData["CommentsError"] = "bg-danger";
                }

                return(View());
            }
        }
コード例 #27
0
ファイル: UnitTest1.cs プロジェクト: Inkh/Lab19WebAPI
        public async void ToDoDeleteTest()
        {
            DbContextOptions <ToDoDbContext> options =
                new DbContextOptionsBuilder <ToDoDbContext>()
                .UseInMemoryDatabase("todoDelete")
                .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                //CREATE
                //Arrange
                ToDo taskOne = new ToDo();
                taskOne.Name      = "Finish homework";
                taskOne.Completed = false;

                context.ToDos.Add(taskOne);
                context.SaveChanges();

                //READ
                var myTask = await context.ToDos.FirstOrDefaultAsync(t => t.Name == taskOne.Name);

                context.ToDos.Remove(myTask);
                context.SaveChanges();

                var deletedTask = await context.ToDos.FirstOrDefaultAsync(t => t.Name == myTask.Name);

                Assert.True(deletedTask == null);
            }
        }
コード例 #28
0
 public ActionResult <IEnumerable <string> > Get()
 {
     using (var db = new ToDoDbContext())
     {
     }
     return(new string[] { "value1", "value2" });
 }
コード例 #29
0
ファイル: UnitTest1.cs プロジェクト: Inkh/Lab19WebAPI
        public async void ToDoListDeleteTest()
        {
            DbContextOptions <ToDoDbContext> options =
                new DbContextOptionsBuilder <ToDoDbContext>()
                .UseInMemoryDatabase("todoListDelete")
                .Options;

            using (ToDoDbContext context = new ToDoDbContext(options))
            {
                //CREATE
                //Arrange
                ToDoList myList = new ToDoList();
                myList.Name = "new list";

                context.ToDoList.Add(myList);
                context.SaveChanges();

                //READ
                var list = await context.ToDoList.FirstOrDefaultAsync(t => t.Name == myList.Name);

                context.ToDoList.Remove(list);
                context.SaveChanges();

                var deletedList = await context.ToDoList.FirstOrDefaultAsync(t => t.Name == myList.Name);

                Assert.True(deletedList == null);
            }
        }
コード例 #30
0
        public void TestGettingAllTodosInDb()
        {
            ToDoDbContext _context;
            DbContextOptions <ToDoDbContext> options = new DbContextOptionsBuilder <ToDoDbContext>()
                                                       .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            using (_context = new ToDoDbContext(options))
            {
                List <ToDo> testTodos = GetTodosObjects();

                // Adding two objects into the context to check if both are stored in database
                foreach (ToDo x in testTodos)
                {
                    _context.ToDos.AddAsync(x);
                }
                _context.SaveChangesAsync();

                // Arrange
                TaskManagerController taskManagerController = new TaskManagerController(_context);

                // Act
                IEnumerable <ToDo> result     = taskManagerController.Get();
                List <ToDo>        resultList = result.ToList();

                // Assert
                Assert.Equal(testTodos.Count, resultList.Count);
            }
        }