public Task Add(Task t)
 {
     using (var context = new TaskContext()) {
         context.Tasks.Add(t);
         context.SaveChanges();
         onTasksUpdated();
         return t;
     }
 }
        public Task Get(int id)
        {
            using (var context = new TaskContext()) {
                var task = from t in context.Tasks
                              where t.id == id
                              select t;

                return task.FirstOrDefault();
            }
        }
        public bool Update(Task t)
        {
            using (var context = new TaskContext()) {

                context.Tasks.Attach(t);
                context.Entry(t).State = System.Data.EntityState.Modified;
                context.SaveChanges();

                onTasksUpdated();

                return true;
            }
        }
예제 #4
0
        public override void Execute(TaskContext taskContext)
        {
            ParameterSet parameters = taskContext.GetParameters();
            XmlDocument _doc = new XmlDocument();
            //string street1 = "";
            //string street2 = "";

            try
            {
                Point location = parameters.GetParameter("Geometry") as Point;
                string coords = parameters.GetParameter("COORDS") as string;
                //string UrlString = "";

                //below commented out for UC
                ////use GeoNames.org to find the nearest intersection to provide a meaningful title for the result and the popup
                //UrlString = "http://ws.geonames.org/findNearestIntersection?lat=" + location.Y.ToString() + "&lng=" + location.X.ToString();
                //_doc.Load(UrlString);
                //XPathNavigator nav = _doc.CreateNavigator();
                //XPathNodeIterator itr = nav.Select("/geonames/intersection");
                //while (itr.MoveNext())
                //{
                //    XPathNodeIterator nodeItrChildren = itr.Current.SelectChildren(XPathNodeType.Element);

                //    XPathNavigator currNode = nodeItrChildren.Current;
                //    street1 = currNode.SelectSingleNode("street1").InnerXml;
                //    street2 = currNode.SelectSingleNode("street2").InnerXml;
                //}
                //above commented out for UC

                // Set up the appearance of the result.
                //PlaceResult newResult = new PlaceResult("StreetViewer", "StreetView at " + street1 +  "&"  + street2,
                PlaceResult newResult = new PlaceResult("StreetViewer", "StreetView",
                    location, "Yellow Pushpin");
                newResult.SubType = "Places";
                newResult.Category = "StreetViewer Results";
                //next line is server that contains the HTML page (getPano.html) that creates the StreetView
                //newResult.Description = "http://www.yoursite.com/folder/getPano.html?lat=" + location.Y.ToString() + "&long=" + location.X.ToString();
                newResult.Description = "http://www.gisconsultancy.com/stview/getPano.html?lat=" + location.Y.ToString() + "&long=" + location.X.ToString();
                //newResult.Title = "StreetView at " + street1 + " + " + street2;
                newResult.Title = "StreetView";
                taskContext.UpdateResult(newResult);

            }
            catch
            {
                // Could investigate the exception thrown here.
                // In this case, do not create a Result, just set the status and message on the TaskContext and return.
                taskContext.SetStatusMessage(esriE2TaskStatus.CompletedNoValue, "StreetViewer did not find that location.");
                taskContext.ExitStatus = esriE2TaskExitStatus.CompletedNoValue;
            }
        }
예제 #5
0
        public void Index()
        {
            using (var context = new TaskContext("TaskSystemWebsite"))
            {

                var userTask = new UserTask() { Description = "test", DueDate = DateTime.Now, TaskPriority = 1, UserId = Guid.NewGuid() };
                context.Save(userTask);
                context.SaveChanges();

                var ret = context.Tasks.First();

                Assert.AreEqual(userTask, ret);
            }
        }
        public void Delete(int id)
        {
            using (var context = new TaskContext()) {
                Task task = (from t in context.Tasks
                                 where t.id == id
                                 select t).FirstOrDefault();

                if (task != null)
                    context.Tasks.Remove(task);

                context.SaveChanges();
                onTasksUpdated();
            }
        }
예제 #7
0
 void IModule.Execute(TaskContext context, ModuleDefinition definition)
 {
     Execute(context, (T)definition);
 }
예제 #8
0
 public HomeController(ILogger <HomeController> logger, TaskContext taskContext)
 {
     _taskContext = taskContext;
     _logger      = logger;
 }
 protected override int Execute(TaskContext context, string input)
 {
     GenerationCount++;
     return(GenerationCount);
 }
예제 #10
0
 /// <summary>
 /// The constructor executed by the parser.
 /// </summary>
 /// <param name="context">The task context.</param>
 /// <param name="subtasks">The children tasks.</param>
 public Prioritize(TaskContext <DataType> context, Task <DataType>[] subtasks)
     : base(context, subtasks)
 {
 }
 public IEnumerable<Task> GetAll()
 {
     using (var context = new TaskContext()) {
         return context.Tasks.ToList();
     }
 }
예제 #12
0
 public TaskListVM()
 {
     _context = new TaskContext();
     Tasks    = _context.Tasks.ToArray();
     OnPropertyChanged(nameof(Tasks));
 }
 public ManageDataController(TaskContext context)
 {
     _context = context;
     _levels  = context.Levels.ToList();
 }
예제 #14
0
 internal void Reclaim(TaskContext ctx)
 {
     lock (this)
       {
     ctx.next_ = taskContextList_;
     taskContextList_ = ctx;
       }
 }
예제 #15
0
 public TaskContext NewTaskContext()
 {
     lock (this)
       {
     if (taskContextList_ == null)
       taskContextList_ = new TaskContext(this);
     TaskContext ret = taskContextList_;
     taskContextList_ = ret.next_;
     ret.next_ = null;
     return ret;
       }
 }
예제 #16
0
 /// <summary>
 /// Add a task to the thread queue. When a thread is available, it will 
 /// dequeue this task and run it. Once complete, the task will be marked 
 /// complete, but your application won't be called back until the next 
 /// time Update() is called (so that callbacks are from the main thread).
 /// </summary>
 /// <param name="function">The function to call within the thread.</param>
 /// <param name="completion">The callback to report results to, or null. If 
 /// you care about which particular task has completed, use a different instance 
 /// for this delegate per task (typically, a delegate on the task itself).</param>
 /// <param name="ctx">A previously allocated TaskContext, to allow for waiting 
 /// on the task, or null. It cannot have been already used.</param>
 /// <returns>A Task identifier for the operation in question. Note: because
 /// of the threaded behavior, the task may have already completed when it 
 /// is returned. However, if you AddTask() from the main thread, the completion 
 /// function will not yet have been called.</returns>
 public Task AddTask(TaskFunction function, TaskComplete completion, TaskContext ctx, object argument)
 {
     if (function == null)
     throw new System.ArgumentNullException("function");
       Worker w;
       lock (this)
       {
     if (disposed_)
       throw new System.ObjectDisposedException("ParallelThreadPool");
     qDepth_++;
     w = NewWorker(function, completion, argument);
     if (ctx != null)
       ctx.Init(w);
     if (workList_ == null)
       workList_ = w;
     else
       workListEnd_.next_ = w;
     workListEnd_ = w;
       }
       workEvent_.Set();
       return w;
 }
예제 #17
0
 public TaskRepository(TaskContext context, ILogger<TaskRepository> logger)
 {
     _context = context;
     _logger = logger;
 }
예제 #18
0
 private void RefreshStatisticsCallback(TaskContext taskContext)
 {
     this.TargetUsage = taskContext.TargetUsage;
     this.ExecutionTime = taskContext.ExecutionTime;
     this.Bottlenecks.Refill(taskContext.Bottlenecks);
     this.LogEvents.Refill(WpfAppender.GetLogs(this.Logger));
     this.IsBusy = false;
 }
예제 #19
0
 public TaskController(TaskContext context)
 {
     _context = context;
 }
예제 #20
0
 public override bool Rollback(TaskContext context)
 {
     return(false);
 }
        protected override TAdapterOutput ReceiveData(TaskContext context, TAdapterInput taskInput)
        {
            SqlReceiveAdapterConfig config = this.GetConfiguration <SqlReceiveAdapterConfig>(taskInput.Orchestration);

            TAdapterOutput res = null;

            base.LogManager.TraceInfMethodStarted("Daenet.System.Integration.SqlReceiveAdapter.RunTask()");

            if (String.IsNullOrEmpty(config.ConnectionString))
            {
                throw new Exception("SqlReceiveAdapter must have valid ConnectionString. Please check your configuration.");
            }
            if (String.IsNullOrEmpty(config.CheckDataCmdText))
            {
                throw new Exception("SqlReceiveAdapter must have valid CheckDataCmdText. Please check your configuration.");
            }
            if (String.IsNullOrEmpty(config.FetchDataCmdText))
            {
                throw new Exception("SqlReceiveAdapter must have valid FetchDataCmdText. Please check your configuration.");
            }
            if (String.IsNullOrEmpty(config.MapperQualifiedName))
            {
                throw new Exception("SqlReceiveAdapter must have valid MapperQualifiedName. Please check your configuration.");
            }

            using (SqlConnection connection = new SqlConnection(config.ConnectionString))
            {
                connection.Open();

                SqlCommand checkCmd = connection.CreateCommand();


                // Start a local transaction.
                SqlTransaction transaction = connection.BeginTransaction("SqlReceiveAdapterTransaction");

                // Must assign both transaction object and connection to Command object for a pending local transaction
                checkCmd.Connection  = connection;
                checkCmd.Transaction = transaction;
                checkCmd.CommandText = config.CheckDataCmdText;

                try
                {
                    var nrOfRecords = checkCmd.ExecuteScalar();

                    if (!(nrOfRecords is int))
                    {
                        throw new Exception("The SqlReceiveAdapter SQL command defined with CheckDataCmdText must return numeric value greater or equal zero. Only if the returned value is greater zero, then the command defined by FetchDataCmdText is going to be executed.");
                    }
                    else
                    {
                        base.LogManager.TraceInfCheckDataCmdTextResults(checkCmd.CommandText, nrOfRecords.ToString());

                        // Only if the CheckDataCmdText statement delivered value greater 0, then we should execute the FetchDataCmdText command to get data.
                        if ((nrOfRecords as int?).HasValue && (nrOfRecords as int?).Value > 0)
                        {
                            SqlCommand fetchCmd = connection.CreateCommand();
                            fetchCmd.Connection  = connection;
                            fetchCmd.Transaction = transaction;
                            fetchCmd.CommandText = config.FetchDataCmdText;

                            SqlDataReader reader = fetchCmd.ExecuteReader();

                            base.LogManager.TraceInfFetchDataCmdTextResults(fetchCmd.CommandText, reader.RecordsAffected.ToString());

                            var mapper = Factory.GetAdapterMapper(config.MapperQualifiedName);

                            res = (TAdapterOutput)mapper.Map(reader);
                        }
                    }

                    // Attempt to commit the transaction.
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // Attempt to roll back the transaction.
                    try
                    {
                        base.LogManager.TraceErryAdapterExecution(ex, "Daenet.System.Integration.ReceiveSqlAdapter");
                        transaction.Rollback();
                        base.LogManager.TraceInfTransactionRolledBack();
                        throw;
                    }
                    catch (Exception ex2)
                    {
                        // This catch block will handle any errors that may have occurred
                        // on the server that would cause the rollback to fail, such as
                        // a closed connection.
                        base.LogManager.TraceErrFailedToCommitTransactionRollback(ex2, "Daenet.System.Integration.SqlReceiveAdapter");
                        throw;
                    }
                }
            }

            base.LogManager.TraceInfMethodCompleted("Daenet.System.Integration.SqlReceiveAdapter.RunTask()");

            return(res);
        }
 public CreateModel(TaskContext db)
 {
     _db = db;
 }
예제 #23
0
        public void Run(TaskContext context)
        {
            var tuning = Tuning.JobBalance;

            if (tuning == null)
            {
                tuning = new JobBalanceTuning();
            }

            //obtain aggregate for all skills
            using (var db = DAFactory.Get())
            {
                var days      = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalDays;
                var limitdays = days - tuning.days_to_aggregate;
                var aggregate = db.DynPayouts.GetSummary(limitdays);

                var missing = TransactionToType.Keys.Where(x => !aggregate.Any(y => y.transaction_type == x));
                var baseSum = (aggregate.Count == 0) ? 1 : 0;
                foreach (var miss in missing)
                {
                    aggregate.Add(new DbTransSummary()
                    {
                        transaction_type = miss, sum = baseSum
                    });
                }
                aggregate = aggregate.OrderBy(x => x.transaction_type).ToList();

                var totalPayouts = aggregate.Sum(x => x.sum);
                //get the percent of all single money payouts that each object gave out
                //since some jobs take longer to complete, their payout counts need to be rescaled,
                //so that one payout counts as like, 1.1.
                int i             = 0;
                var percentIncome = aggregate.Select(x => TypeCompletionTimes[(i++)] / BaseCompletionTime * ((float)x.sum) / totalPayouts);

                var rand = new Random();
                //convert this into our base multipler, with some variation
                var multipliers = percentIncome.Select(x => PercentToBaseMultiplier(x) + tuning.mul_variation * ((float)rand.NextDouble() - 0.5f)).ToList();

                //pick a job that recieves a notable boost. there is a chance that no job gets this boost.
                var bonusJob = rand.Next(TypeCompletionTimes.Length + 1);
                if (bonusJob < TypeCompletionTimes.Length)
                {
                    multipliers[bonusJob] -= tuning.mul_bonus_job + tuning.mul_variation * (float)rand.NextDouble();
                }

                //finally,  scale into the final range.
                var finalMultipliers = multipliers.Select(x => Math.Min(1f, Math.Max(0f, 1 - x)) * (tuning.max_multiplier - tuning.min_multiplier) + tuning.min_multiplier);

                //ace af. lets put these into the database. log the raw multipliers first...
                var dbEntries = new List <DbDynPayout>();
                i = 0;
                foreach (var mul in finalMultipliers)
                {
                    dbEntries.Add(new DbDynPayout()
                    {
                        day        = days,
                        multiplier = mul,
                        skilltype  = i,
                        flags      = (i == bonusJob) ? 1 : 0
                    });
                    i++;
                }
                db.DynPayouts.InsertDynRecord(dbEntries);

                //...then we calculate and replace the object tuning.
                var dbTuning = new List <DbTuning>();
                i = 0;
                foreach (var mul in finalMultipliers)
                {
                    //we need to scale the multiplier by the time it takes to get one payout.
                    //the longer it takes than the base, the more we pay out in one instance.
                    var timeScaledMulti = mul * (TypeCompletionTimes[i] / BaseCompletionTime);
                    dbTuning.Add(new DbTuning()
                    {
                        tuning_type  = "skillobjects.iff",
                        tuning_table = 8207 - 8192,
                        tuning_index = ToTuningIndex[i],
                        value        = (int)Math.Round((100 * timeScaledMulti) - 100),
                        owner_type   = DbTuningType.DYNAMIC,
                        owner_id     = 1
                    });
                    i++;
                }

                db.DynPayouts.ReplaceDynTuning(dbTuning);
            }
        }
예제 #24
0
 public TaskQueueResult(TaskContext context)
 {
     Context = context;
 }
예제 #25
0
 public TaskQueueResult(TaskContext context, long queueId)
 {
     Context = context;
     QueueId = queueId;
 }
예제 #26
0
        private TaskContext RefreshStatisticsAsync()
        {
            var context = new TaskContext();

            context.TargetUsage = this.Component.GetUsageByTargets();
            context.ExecutionTime = this.Component.ExecutionTimeGraph();
            context.Bottlenecks = this.Component.GetBottlenecksArray();
            return context;
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="TeamFiexdAchievementRangModule" /> class.
 /// </summary>
 /// <param name="context">上下文</param>
 /// <param name="config">The configuration.</param>
 public TeamFiexdAchievementRangModule(TaskContext context, TeamFiexdAchievementRangConfig config)
     : base(context, config)
 {
 }
 protected override string Execute(TaskContext context, string user)
 {
     return("Greeting send to " + user);
 }
예제 #29
0
 public AssetAppreciationTaskResult(TaskContext context)
 {
     Context = context;
 }
 protected override string Execute(TaskContext context, string input)
 {
     return("Gabbar");
 }
 protected override string Execute(TaskContext context, string input)
 {
     return("Spartacus");
 }
예제 #32
0
 public HomeController()
 {
     context = new TaskContext();
 }
예제 #33
0
 public abstract void Execute(TaskRequest taskRequest,TaskContext context);
예제 #34
0
 public abstract void Execute(TaskContext context, T definition);
예제 #35
0
        public Task Execute(IJobExecutionContext context)
        {
            _sid = Guid.Parse(context.JobDetail.Key.Name);

            using (var scope = new ScopeDbContext())
            {
                _db = scope.GetDbContext();
                if (!_db.Schedules.Any(x => x.Id == _sid && x.Status == (int)ScheduleStatus.Running))
                {
                    LogHelper.Warn("不存在或没有启动的任务", _sid);
                    throw new JobExecutionException("不存在或没有启动的任务");
                }
                bool getLocked = _db.Database.ExecuteSqlRaw($"UPDATE schedulelocks SET Status=1 WHERE ScheduleId='{_sid.ToString()}' and Status=0") > 0;
                if (getLocked)
                {
                    LogHelper.Info($"节点{node}抢锁成功!准备执行任务....", _sid);
                    IJobDetail job = context.JobDetail;
                    try
                    {
                        if (job.JobDataMap["instance"] is TaskBase instance)
                        {
                            Guid        traceId   = GreateRunTrace();
                            Stopwatch   stopwatch = new Stopwatch();
                            TaskContext tctx      = new TaskContext(instance);
                            tctx.Node       = node;
                            tctx.TaskId     = _sid;
                            tctx.TraceId    = traceId;
                            tctx.ParamsDict = job.JobDataMap["params"] as Dictionary <string, object>;
                            if (context.MergedJobDataMap["PreviousResult"] is object prev)
                            {
                                tctx.PreviousResult = prev;
                            }
                            try
                            {
                                stopwatch.Restart();
                                instance.InnerRun(tctx);
                                stopwatch.Stop();
                                UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), ScheduleRunResult.Success);
                                LogHelper.Info($"任务[{job.JobDataMap["name"]}]运行成功!用时{stopwatch.Elapsed.TotalMilliseconds.ToString()}ms", _sid, traceId);
                                //保存运行结果用于子任务触发
                                context.Result = tctx.Result;
                            }
                            catch (RunConflictException conflict)
                            {
                                stopwatch.Stop();
                                UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), ScheduleRunResult.Conflict);
                                throw conflict;
                            }
                            catch (Exception e)
                            {
                                stopwatch.Stop();
                                UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), ScheduleRunResult.Failed);
                                LogHelper.Error($"任务\"{job.JobDataMap["name"]}\"运行失败!", e, _sid, traceId);
                                //这里抛出的异常会在JobListener的JobWasExecuted事件中接住
                                //如果吃掉异常会导致程序误以为本次任务执行成功
                                throw new BusinessRunException(e);
                            }
                        }
                    }
                    finally
                    {
                        //为了避免各节点之间的时间差,延迟1秒释放锁
                        System.Threading.Thread.Sleep(1000);
                        _db.Database.ExecuteSqlRaw($"UPDATE schedulelocks SET Status=0 WHERE ScheduleId='{_sid.ToString()}'");
                    }
                }
                else
                {
                    //LogHelper.Info($"节点{node}抢锁失败!", _sid);
                    //throw new JobExecutionException("lock_failed");
                }
            }
            return(Task.FromResult(0));
        }
예제 #36
0
 public TaskController(TaskContext taskContext)
 {
     this.taskContext = taskContext;
 }
        /// <summary>
        /// Initializes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public static void Initialize(TaskContext context)
        {
            context.Database.EnsureCreated();

            // Look for any task.
            if (context.Tasks.Any())
            {
                // DB has been seeded
                return;
            }

            var parentTasks = new[]
            {
                new Task
                {
                    Summary     = "Implement Channel Service",
                    Description =
                        "Implement Channel Service for the feature which will invoke the factories",
                    StartDate = DateTime.Parse("2018-07-02"),
                    EndDate   = DateTime.Parse("2018-07-06"),
                    Priority  = Priority.High,
                    Status    = Status.NotStarted
                },
                new Task
                {
                    Summary     = "Implement Front End Service",
                    Description =
                        "Implement Front End Service for the feature which will invoke the Channel Service",
                    StartDate = DateTime.Parse("2018-07-09"),
                    EndDate   = DateTime.Parse("2018-07-13"),
                    Priority  = Priority.High,
                    Status    = Status.NotStarted
                },
                new Task
                {
                    Summary     = "Implement Front End",
                    Description =
                        "Implement Front End for the feature which will invoke the Front End Service",
                    StartDate = DateTime.Parse("2018-07-16"),
                    EndDate   = DateTime.Parse("2018-07-20"),
                    Priority  = Priority.High,
                    Status    = Status.NotStarted
                }
            };

            foreach (Task t in parentTasks)
            {
                context.Tasks.Add(t);
            }

            context.SaveChanges();

            var childTasks = new[]
            {
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Channel Service").TaskID,
                    Summary  = "Create Channel Service Repository"
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Channel Service").TaskID,
                    Summary  = "Create ASP.Net Core WebApi for Channel Service",
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Channel Service").TaskID,
                    Summary  = "Create CI/CD pipeline for Channel Service",
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End Service").TaskID,
                    Summary  = "Create Front End Service Repository"
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End Service").TaskID,
                    Summary  = "Create Node.js service for Front End Service",
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End Service").TaskID,
                    Summary  = "Create CI/CD pipeline for Front End Service",
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End").TaskID,
                    Summary  = "Create Front End Repository"
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End").TaskID,
                    Summary  = "Create React/Redux Implementation of the Front End",
                },
                new Task
                {
                    ParentID = context.Tasks.First(t => t.Summary == "Implement Front End").TaskID,
                    Summary  = "Create CI/CD pipeline for Front End",
                },
            };

            foreach (Task t in childTasks)
            {
                context.Tasks.Add(t);
            }

            context.SaveChanges();
        }
예제 #38
0
 /// <summary>
 /// The constructor executed by the parser.
 /// </summary>
 /// <param name="context">The task context.</param>
 /// <param name="amount">The amount expression.</param>
 public Turn(TaskContext <Actor> context, Expression <float> amount)
     : base(context)
 {
     this.amount = amount;
 }
        protected override Task OnConvertAsync(string srcFilePath, Mime srcMime, string dstFilePath, ImageModifier dstImgMod, TaskContext taskCtx)
        {
            return(Task.Run(() =>
            {
                Exception eError = null;
                try
                {
                    //dstFilePath是任务唯一ID,是判断任务已完成的标志,因此不能存在未完全完成的文件
                    //转换完成前先用临时文件名
                    var dstTmpFilePath = $"{dstFilePath}.cvting.{dstImgMod.Mime.ExtensionNames.First()}";

                    using (var img = new MagickImage(srcFilePath))
                    {
                        img.Thumbnail(dstImgMod.Size.Width, dstImgMod.Size.Height);

                        //magick会自动根据扩展名决定文件格式
                        img.Write(dstTmpFilePath);
                    }

                    File.Move(dstTmpFilePath, dstFilePath);
                }
                catch (Exception ex)
                {
                    eError = ex;
                }
                finally
                {
                    taskCtx.Complete(eError);
                }
            }));
        }
 public override string Run(TaskContext context, string input)
 {
     // This won't get called as long as we've implemented RunAsync.
     throw new NotImplementedException();
 }
예제 #41
0
 public NewOrganizationServerSettingsModule(TaskContext context) : base(context)
 {
 }
예제 #42
0
 public TaskContextSeedData(TaskContext context, UserManager<TaskUser> userManager)
 {
     _context = context;
     _userManager = userManager;
 }
예제 #43
0
        private void RefreshCalendar()
        {
            var context = TaskScheduler.FromCurrentSynchronizationContext();
            var token = new CancellationTokenSource().Token;
            var taskContext = new TaskContext() { DateToDisplay = this.DateToDisplay };

            this.IsBusy = true;

            var task = Task.Factory.StartNew<TaskContext>(e => RefreshCalendarAsync(e), taskContext);
            task.ContinueWith(e => RefreshCalendarCallback(e.Result)
                , token, TaskContinuationOptions.OnlyOnRanToCompletion, context);
            task.ContinueWith(e => this.Handle.Error(e.Exception.InnerException.InnerException)
                , token, TaskContinuationOptions.OnlyOnFaulted, context);
        }
예제 #44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleContextFixture"/> class.
        /// </summary>
        /// <remarks>This constructor is normally used when instantiated in-test.</remarks>
        /// <param name="registerTypes">Call-back function allowing the user to register additional classes.</param>
        public SimpleContextFixture(Action<ContainerBuilder> registerTypes)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<ConsoleExecutionLog>().As<IExecutionLog>();

            if (registerTypes != null)
            {
                registerTypes(builder);
            }

            var container = builder.Build();
            var locator = new AutofacServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => locator);

            this.fixture = new Fixture();

            this.cancellationTokenSource = new CancellationTokenSource();

            this.context = new TaskContext(this.cancellationTokenSource);
        }
예제 #45
0
 public ActionResult <IEnumerable <TaskModel> > GetAllTaskItems()
 {
     _context = HttpContext.RequestServices.GetService(typeof(TaskContext)) as TaskContext;
     //return new string[] { "value1", "value2" };
     return(_context.GetAllTask());
 }
예제 #46
0
 private void RefreshCalendarCallback(TaskContext taskContext)
 {
     this.IsBusy = false;
     this.DayAppointments.RefillAndSort(taskContext.Result);
 }
예제 #47
0
 public ActionResult <IEnumerable <TaskModel> > DeleteTaskItem(String id)
 {
     _context = HttpContext.RequestServices.GetService(typeof(TaskContext)) as TaskContext;
     return(_context.DeleteTask(id));
 }
예제 #48
0
 public TaskController(TaskContext context)
 {
     this._context = context;
 }
예제 #49
0
        private void RefreshStatistics()
        {
            if (!hasLoaded)
            {
                var context = TaskScheduler.FromCurrentSynchronizationContext();
                var token = new CancellationTokenSource().Token;
                var taskContext = new TaskContext();

                var task = Task.Factory.StartNew<TaskContext>(e => this.RefreshStatisticsAsync(), taskContext, token, TaskCreationOptions.None, context);

                this.IsBusy = true;
                task.ContinueWith(e => RefreshStatisticsCallback(e.Result)
                    , token, TaskContinuationOptions.OnlyOnRanToCompletion, context);
                task.ContinueWith(e => this.Handle.Error(e.Exception.InnerException.InnerException)
                    , token, TaskContinuationOptions.OnlyOnFaulted, context);

                hasLoaded = true;
            }
        }