public IActionResult Edit(Models.Task task, int?id)
        {
            if (task == null || id == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var db = new TaskDbContext())
            {
                var taskToEdit = db.Tasks.Find(id);
                if (taskToEdit == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                taskToEdit.Title = task.Title;
                db.SaveChanges();
            }
            return(RedirectToAction("Index", "Home"));
        }
        public IActionResult Details(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var db = new TaskDbContext())
            {
                var task = db.Tasks.Find(id);

                if (task == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                return(View(task));
            }
        }
        public IActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var db = new TaskDbContext())
            {
                var task = db.Tasks.Find(id);
                if (task == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                db.Tasks.Remove(task);
                db.SaveChanges();
            }
            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 4
0
        public async Task <IHttpActionResult> PendingQuery()
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var queries = await db.Queries.Where(q => q.QueryStatus == QueryStatus.Pending).ToListAsync();

                    if (queries.Count != 0)
                    {
                        return(Ok(queries));
                    }
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }
            return(NotFound());
        }
Exemplo n.º 5
0
        public async Task <IHttpActionResult> IsBusyWorker(int workerId)
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var worker = await db.Workers.FirstOrDefaultAsync(q => q.Id == workerId);

                    if (worker != null)
                    {
                        return(Ok(worker));
                    }
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }
            return(NotFound());
        }
Exemplo n.º 6
0
        public void TaskService_GetsAllTasks_GivenTheyExist()
        {
            var options = new DbContextOptionsBuilder <TaskDbContext>()
                          .UseInMemoryDatabase("gets_all").Options;

            using var context = new TaskDbContext(options);

            var sut = new TaskService(context);

            sut.Create(new Data.Models.Task {
                Id = 1
            });
            sut.Create(new Data.Models.Task {
                Id = 2
            });

            var allTasks = sut.GetAll();

            allTasks.Count.Should().Be(2);
        }
Exemplo n.º 7
0
        public async Task <IHttpActionResult> BusyWorkers()
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var workers = await db.Workers.Where(q => q.IsBusy).ToListAsync();

                    if (workers.Count != 0)
                    {
                        return(Ok(workers));
                    }
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }
            return(NotFound());
        }
Exemplo n.º 8
0
        public async Task <IHttpActionResult> StatusQuery(int id)
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var query = await db.Queries.FirstOrDefaultAsync(q => q.Id == id);

                    if (query == null)
                    {
                        return(NotFound());
                    }

                    return(Ok(query.QueryStatus));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 9
0
        public void PutTask()
        {
            using (_context = new TaskDbContext(options))
            {
                List <Tasks> testTasks = GetTestTasks();
                foreach (Tasks x in testTasks)
                {
                    _context.AllTasks.Add(x);
                }
                _context.SaveChanges();
                testTasks[0].Title = "Eek Help! Oh no, Molly.";

                // Arrange
                TaskController controller = new TaskController(_context);
                // Act
                controller.Put(1, testTasks[0]);
                Tasks resultGet = controller.Get(1);
                // Assert
                Assert.Equal(testTasks[0], resultGet);
            }
        }
Exemplo n.º 10
0
        public async Task <IHttpActionResult> Worker([FromBody] Worker worker)
        {
            if (worker == null)
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }

            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    db.Workers.Add(worker);
                    await db.SaveChangesAsync();
                }
                return(StatusCode(HttpStatusCode.Created));
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
        public async Task GetTaskAll_ShouldExecuteRepository_GetTaskAll()
        {
            using (var context = new TaskDbContext(contextOptions, configuration, DataBaseFlags.Test))
            {
                //Arrange
                var textService = new Services.TaskService(context, _mapper, _cacheTaskService.Object);
                var controller  = new TaskController(textService);

                //Act
                var actionResultFromController = await controller.GetAllTask();

                //Assert
                var objectResult = actionResultFromController.Result as OkObjectResult;
                var taskResults  = objectResult.Value as List <TaskResultModel>;

                Assert.NotNull(objectResult);
                Assert.NotNull(taskResults);
                Assert.Equal(200, objectResult.StatusCode);
                Assert.Equal(_textTaskResult[0].Count, taskResults[0].ListGuids[0].ListFoundWord[0].Count);  // 1
                Assert.Equal(_textTaskResult[1].Count, taskResults[0].ListGuids[0].ListFoundWord[1].Count);  // 21
            }
        }
Exemplo n.º 12
0
        public async Task AddUserTest()
        {
            var user = await _serviceFactory.Invoke().AddUser("Иван", "Иванов");

            Assert.NotNull(user);

            user = await _serviceFactory.Invoke().AddUser("Иван", "Петров");

            Assert.NotNull(user);

            user = await _serviceFactory.Invoke().AddUser("Петр", "Иванов");

            Assert.NotNull(user);

            Assert.CatchAsync(() => _serviceFactory.Invoke().AddUser("Иван", "Иванов"));

            using (var db = new TaskDbContext())
            {
                var usersCount = db.Users.Count();
                Assert.AreEqual(usersCount, 3);
            }
        }
Exemplo n.º 13
0
        public async Task <IHttpActionResult> CountPendingByQuery(int id)
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var query = await db.Queries.FirstOrDefaultAsync(q => q.Id == id && q.QueryStatus == QueryStatus.Pending);

                    if (query == null)
                    {
                        return(NotFound());
                    }
                    var count = await db.Queries.Where(q => q.QueryStatus == QueryStatus.Pending).CountAsync(q => q.CreatedAt < query.CreatedAt);

                    return(Ok(count));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 14
0
        public static void Init()
        {
            Queue = new BufferQueue <SystemLogEntity>();
            var td = new System.Threading.Thread(() =>
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    while (true)
                    {
                        Queue.Read((item, index) =>
                        {
                            db.SystemLog.Add(item);
                        });
                        db.SaveChanges();
                        System.Threading.Thread.Sleep(5000);
                    }
                }
            });

            td.IsBackground = true;
            td.Start();
        }
Exemplo n.º 15
0
        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            SQLHelper.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConn"].ConnectionString;

            LogManager.Init();
            Common.QuartzManager.InitScheduler();

            using (TaskDbContext db = new TaskDbContext())
            {
                var list = db.Task.Where(m => m.Status == (int)TaskStatus.Running).ToList();
                foreach (var task in list)
                {
                    Common.QuartzManager.StartWithRetry(task);
                }
            }
        }
Exemplo n.º 16
0
        public async System.Threading.Tasks.Task AddAsync_ValidRequest_CreateListAndTask()
        {
            using (var context = new TaskDbContext(_options))
            {
                var taskListRepo = new TaskListRepository(context);
                var taskRepo     = new TaskRepository(context);

                var taskList = new TaskList
                {
                    Title       = "New List",
                    OwnerId     = Guid.NewGuid().ToString(),
                    CreatedDate = DateTimeOffset.Now
                };

                var newTaskList = context.TaskLists.Add(taskList).Entity;

                var task = new TaskModel
                {
                    Description = "Write a Task List",
                    TaskList    = newTaskList,
                    CreatedDate = DateTimeOffset.Now,
                    Start       = DateTimeOffset.Now,
                    End         = DateTimeOffset.Now.AddMinutes(45),
                    Status      = Domain.Enums.TaskModelStatus.Open
                };

                var newTask = context.Tasks.Add(task).Entity;
                context.SaveChanges();

                var getListTasks = await context.TaskLists.AsNoTracking().Include(x => x.Tasks).ToListAsync();

                Assert.IsNotNull(newTaskList);
                Assert.IsNotNull(newTask);
                Assert.AreEqual(1, getListTasks.Count);
                Assert.AreEqual(1, getListTasks[0].Tasks.Count);
                Assert.AreEqual(newTask.Id, getListTasks[0].Tasks[0].Id);
            }
        }
Exemplo n.º 17
0
        public async Task RemoveUserTest()
        {
            const int userId = (int)UserIdPool.RemoveId;

            await AddUser(new User
            {
                Id      = userId,
                Name    = "Иван",
                Surname = "Иванов",
            });

            var returnedId = await _serviceFactory.Invoke().RemoveUser(userId);

            User user;

            using (var db = new TaskDbContext())
            {
                user = await db.Users.FindAsync(userId);
            }

            Assert.IsNull(user);
            Assert.AreEqual(userId, returnedId);
        }
Exemplo n.º 18
0
        public async Task <IHttpActionResult> CancelQuery(int id)
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var query = await db.Queries.FirstOrDefaultAsync(q => q.Id == id && (q.QueryStatus == QueryStatus.Pending));

                    if (query == null)
                    {
                        return(NotFound());
                    }
                    query.QueryStatus = QueryStatus.Cance;
                    await db.SaveChangesAsync();

                    return(Ok(query));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 19
0
 public ApiResponseMessage StopTask(Guid id)
 {
     using (TaskDbContext db = new TaskDbContext())
     {
         var task = db.Task.FirstOrDefault(m => m.Id == id);
         if (task != null && task.Status > (int)TaskStatus.Stop)
         {
             bool success = false;
             var  list    = db.ServerNodes.Where(m => m.Status == 1).ToList();
             var  header  = Header;
             foreach (var node in list)
             {
                 var result = HttpRequest.Send($"http://{node.Host}/api/Quartz/Stop/{task.Id.ToString()}", "post", null, header);
                 success = success || result.Key == System.Net.HttpStatusCode.OK;
             }
             if (success)
             {
                 //更新任务状态为已停止
                 _repositoryFactory.Tasks.ModifyBy(m => m.Id == task.Id, m => new Task
                 {
                     Status      = (int)TaskStatus.Stop,
                     NextRunTime = null
                 });
                 if (db.SaveChanges() > 0)
                 {
                     return(ServiceResult(ResultStatus.Success, "任务已停止运行!"));
                 }
                 return(ServiceResult(ResultStatus.Failed, "更新任务状态失败!"));
             }
             else
             {
                 return(ServiceResult(ResultStatus.Failed, "任务停止失败!"));
             }
         }
     }
     return(ServiceResult(ResultStatus.Failed, "当前任务状态下不能停止!"));
 }
Exemplo n.º 20
0
        static async Task Main(string[] args)
        {
            using (var context = new TaskDbContext())
            {
                try
                {
                    int lastDbTimestamp = context.ExchangeRates.Select(x => x.Timestamp).Max();

                    if (lastDbTimestamp < GetLastTimestampYesterday())
                    {
                        ExchangeRate currentRate = MapExchangeRate(await Rates.GetRate(
                                                                       Constants.BaseCurrency, Constants.TargetCurrency, null));

                        if (currentRate != null)
                        {
                            context.ExchangeRates.Add(currentRate);
                            context.SaveChanges();
                            Console.WriteLine("Database was updated.");
                        }
                        else
                        {
                            Console.WriteLine("Database was not updated.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Database is up to date.");
                    }
                }
                catch (Exception ex)
                {
                    //add to log ex.Message
                    Console.WriteLine("Error: DB Update failed");
                }
            }
        }
Exemplo n.º 21
0
        public async Task <IHttpActionResult> Login([FromBody] Login login)
        {
            try
            {
                using (TaskDbContext db = new TaskDbContext())
                {
                    var worker = await db.Workers.FirstOrDefaultAsync(w => w.NickName == login.NickName && w.Password == login.Password);

                    if (worker != null)
                    {
                        login.Role     = Role.Worker;
                        login.Id       = worker.Id;
                        worker.IsLogin = true;
                        await db.SaveChangesAsync();

                        return(Ok(login));
                    }
                    else
                    {
                        var user = await db.Users.FirstOrDefaultAsync(u => u.UserName == login.NickName && u.Password == login.Password);

                        if (user != null)
                        {
                            login.Role = Role.User;
                            login.Id   = user.Id;
                            return(Ok(login));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
            return(NotFound());
        }
Exemplo n.º 22
0
 public UserRepository(TaskDbContext dbContext) : base(dbContext)
 {
 }
Exemplo n.º 23
0
 public EFRepository(TaskDbContext dbContext)
 {
     _dbContext = dbContext;
 }
Exemplo n.º 24
0
        public static List <T> ObtenerTodoInclude <T, I>(Expression <Func <T, I> > expresion) where T : class where I : class
        {
            var ctx = new TaskDbContext();

            return(ctx.Set <T>().Include <T, I>(expresion).ToList());
        }
Exemplo n.º 25
0
 public LoginRepository(TaskDbContext context, IOptions <AppSettings> appSettings)
 {
     this._appSettings = appSettings.Value;
     this.context      = context;
 }
Exemplo n.º 26
0
        public static List <T> ObtenerTodo <T>() where T : class
        {
            var ctx = new TaskDbContext();

            return(ctx.Set <T>().ToList <T>());
        }
Exemplo n.º 27
0
 public static void InsertarSinGuardar <T>(T elemento, TaskDbContext ctx) where T : class
 {
     ctx.Add <T>(elemento);
 }
Exemplo n.º 28
0
 public TaskRepository()
 {
     context = new TaskDbContext();
 }
Exemplo n.º 29
0
 public HomeController(ILogger <HomeController> logger,
                       TaskDbContext context)
 {
     _logger  = logger;
     _context = context;
 }
Exemplo n.º 30
0
 public TaskService(TaskDbContext dbContext)
 {
     _db = dbContext;
 }