public override void Execute(MaintenanceWorkItem workItem, ITaskExecutionContext context)
        {
            DateTimeOffset utcNow         = Time.UtcNow;
            DateTimeOffset dateTimeOffset = utcNow.Subtract(workItem.Configuration.CleanUpTaskLogEntriesOlderThan);

            utcNow = Time.UtcNow;
            DateTimeOffset dateTimeOffset1 = utcNow.Subtract(workItem.Configuration.CleanUpErrorLogEntriesOlderThan);

            using (IDbSession dbSession = this._db.OpenSession())
            {
                using (IDbTransaction dbTransaction = dbSession.BeginTransaction(null))
                {
                    Tuple <int, string> tuple  = this.DeleteEntries(dbSession, "TaskLog", dateTimeOffset);
                    Tuple <int, string> tuple1 = this.DeleteEntries(dbSession, "ErrorLog", dateTimeOffset1);
                    dbTransaction.Commit();
                    if (tuple.Item1 > 0 || tuple1.Item1 > 0)
                    {
                        ArchiveCreated archiveCreated = this._archiver.Archive("IntegrationDb-Maintenance", (BeginArchive a) => {
                            a.Options.GroupedBy("Backup").ExpiresAfterMonths(12);
                            a.IncludeContent(string.Format("TaskLog_{0:yyyyMMdd}.csv", dateTimeOffset), tuple.Item2, null);
                            a.IncludeContent(string.Format("ErrorLog_{0:yyyyMMdd}.csv", dateTimeOffset1), tuple1.Item2, null);
                        });
                        context.Log.Message("Deleted {0} task entries older than '{1}'. \r\nDeleted {2} error entries older than '{3}'\r\nArchive: {4}", new object[] { tuple.Item1, dateTimeOffset, tuple1.Item1, dateTimeOffset1, archiveCreated });
                    }
                }
            }
        }
Example #2
0
        public override MonitorWorkItem Start(ITaskExecutionContext context)
        {
            MonitorConfiguration monitorConfiguration = this._configuration.Get <MonitorConfiguration>();

            monitorConfiguration.Assert();
            return((new MonitorWorkItem(monitorConfiguration)).AddIgnoreFilter(new MessageContainsText(monitorConfiguration.IgnoreErrorsWithMessagesContaining)).AddTargetRedirect(new RedirectForMonitorTargets(monitorConfiguration.Targets)).AddMessageGroupingPatterns(monitorConfiguration.MessageGroupingPatterns));
        }
        private IList <INumericRangeBlockContext> GetNumericRangeBlocks(ITaskExecutionContext taskExecutionContext)
        {
            using (var cs = taskExecutionContext.CreateCriticalSection())
            {
                if (cs.TryStart())
                {
                    long startNumber;
                    var  lastBlock    = taskExecutionContext.GetLastNumericRangeBlock(LastBlockOrder.LastCreated);
                    var  maxJourneyId = _travelDataService.GetMaxJourneyId();

                    // if this is the first run then just process the last 1000
                    if (lastBlock == null)
                    {
                        startNumber = maxJourneyId - 1000;
                    }
                    // if there is no new data then just return any old blocks that have failed or died
                    else if (lastBlock.EndNumber == maxJourneyId)
                    {
                        return(taskExecutionContext.GetNumericRangeBlocks(x => x.OnlyOldNumericBlocks()));
                    }
                    // startNumber is the next unprocessed id
                    else
                    {
                        startNumber = lastBlock.EndNumber + 1;
                    }

                    int maxBlockSize = 500;
                    return(taskExecutionContext.GetNumericRangeBlocks(x => x.WithRange(startNumber, maxJourneyId, maxBlockSize)));
                }
                throw new Exception("Could not acquire a critical section, aborted task");
            }
        }
Example #4
0
        private void SendTo(MonitorTarget target, ITaskExecutionContext <MonitorWorkItem> context)
        {
            MonitorEntry[] entries = context.WorkItem.GetEntries(target);

            if (entries.Length > 0)
            {
                if (target.Recipients == null || target.Recipients.Length == 0)
                {
                    context.Log.Warning(Target.Service, "No recipients found for target '{0}'.", target);
                    return;
                }

                context.Log.Message("Sending {0} entries to {1}.", entries.Length, target);

                var subject = new StringBuilder();

                ApplicationEnvironment environment = _runtimeSettings.Environment;

                if (environment != null)
                {
                    subject.AppendFormat("[{0}] ", environment);
                }

                if (!string.IsNullOrWhiteSpace(context.WorkItem.Configuration.SubjectPrefix))
                {
                    subject.AppendFormat("{0}: ", context.WorkItem.Configuration.SubjectPrefix);
                }

                subject.AppendFormat("Monitoring ({0})", context.WorkItem.CheckRange);

                _emailService.Send(new MonitorEmailTemplate(subject.ToString(), entries, target), target.Recipients);
            }
        }
Example #5
0
        public void Run(string data, string config, byte[] binData, ITaskExecutionContext executionContext)
        {
            var    itms     = data.Split('/');
            string language = itms[0];
            string state    = itms[1];

            var syncer = _configuration.GetSyncer(language, state);

            if (syncer.EnterSyncAll(LockTimeoutInMs))
            {
                try
                {
                    if (_importer.ValidateInstance(language, state))
                    {
                        _manager.DeleteAllASync(language, state, _stores).Wait();
                        _importer.ImportAsync(executionContext, language, state, _stores).Wait();
                    }
                    else
                    {
                        throw new Exception($"Unable to validate InstanceId");
                    }
                }
                finally
                {
                    syncer.LeaveSyncAll();
                }
            }
            else
            {
                throw new Exception($"Unable to enter into EnterSyncAll during {LockTimeoutInMs} ms");
            }
        }
Example #6
0
            public override void StartTask(ITaskExecutionContext context)
            {
                var failingTaskA = System.Threading.Tasks.Task.Factory.StartNew(() => throw new InvalidOperationException());
                var failingTaskB = System.Threading.Tasks.Task.Factory.StartNew(() => throw new DivideByZeroException());

                System.Threading.Tasks.Task.WaitAll(failingTaskA, failingTaskB);
            }
Example #7
0
        public override void StartTask(ITaskExecutionContext context)
        {
            uint count;

            if (!uint.TryParse(context.Arguments["Iterations"], out count))
            {
                count = 10;
            }

            int[] iterations = Enumerable.Range(1, (int)count).ToArray();

            IProgressBar progressBar = _hangfireContextProvider.Current.WriteProgressBar();

            foreach (int i in iterations.WithProgress(progressBar))
            {
                context.ThrowIfCancelled();

                // Everything we log will be outputted in the Hangfire UI/dashboard
                //  - This was enabled by the .EnableConsole() method on .UseHangfire()
                context.Log.Message("Iteration: [{0}/{1}]", i, iterations.Length);

                if (i != iterations.Length)
                {
                    context.CancellationToken.WaitHandle.WaitOne(TimeSpan.FromMilliseconds(500));
                }
            }

            context.Log.Message("Done");
            context.Log.Message("...");
        }
        public Task ExecuteAsync(AlwaysFailingTask payload, ITaskExecutionContext executionContext)
        {
            TestExecutorEventBus <AlwaysFailingTask> .Instance
            .NotifyExecutorCompleted();

            throw new InvalidOperationException($"Sample invalid operation during {nameof( AlwaysFailingTask )}");
        }
        public override void StartTask(ITaskExecutionContext context)
        {
            int iterations = 10;

            for (int i = 1; i <= iterations; i++)
            {
                context.ThrowIfCancelled();

                // Everything we log will be outputted in the Hangfire UI/dashboard
                //  - This was enabled by the .EnableConsole() method on .UseHangfire()
                context.Log.Message("Iteration: [{0}/{1}]", i, iterations);

                if (i != iterations)
                {
                    context.CancellationToken.WaitHandle.WaitOne(TimeSpan.FromMilliseconds(500));
                }
            }

            if (Interlocked.Increment(ref _iterations) % 4 == 0)
            {
                throw new InvalidOperationException("Simulating that the task is throwing an exception. {json}");
            }

            context.Log.Message("Done - including some {json}");
            context.Log.Message("...");
        }
        public override void Execute(ITaskExecutionContext <MaintenanceWorkItem> context)
        {
            ElmahConfiguration configuration = context.TypedBag <ElmahConfiguration>(ConfigurationName);

            DateTime lowerBound = DateTime.UtcNow.Date.Subtract(configuration.CleanUpEntriesOlderThan);
            int      batchSize  = configuration.BatchSize;

            using (var connection = new SqlConnection(configuration.GetConnectionString()))
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();

                    command.CommandTimeout = 0;
                    command.CommandText    = DeleteSql;

                    command.Parameters.AddWithValue("time", lowerBound);
                    command.Parameters.AddWithValue("batchSize", batchSize);

                    var count = (int)command.ExecuteScalar();

                    if (count > 0)
                    {
                        context.Log.Message("Deleted {0} entries older than '{1}'.", count, lowerBound);
                    }
                }
        }
Example #11
0
 public override void Execute(MonitorWorkItem workItem, ITaskExecutionContext context)
 {
     Uri[] uriArray = PingUrlsStep.ParseUrls(workItem.Configuration.PingUrls.Urls, context.Log);
     if (uriArray.Length == 0)
     {
         return;
     }
     try
     {
         Parallel.ForEach <Uri>(uriArray, new ParallelOptions()
         {
             MaxDegreeOfParallelism = 4
         }, (Uri url) => {
             Stopwatch stopwatch = Stopwatch.StartNew();
             try
             {
                 System.Threading.Tasks.Task <HttpResponseMessage> task = this.HttpGet(url, workItem.Configuration.PingUrls.MaximumWaitTimeSeconds);
                 task.Wait();
                 task.Result.EnsureSuccessStatusCode();
             }
             catch (Exception exception)
             {
                 throw new PingUrlsStep.PingException(url, stopwatch, exception);
             }
         });
     }
     catch (AggregateException aggregateException)
     {
         PingUrlsStep.PingException[] pingExceptionArray = PingUrlsStep.AssertExceptions(aggregateException);
         for (int i = 0; i < (int)pingExceptionArray.Length; i++)
         {
             this.AddException(pingExceptionArray[i], workItem);
         }
     }
 }
 public override void Execute(MonitorWorkItem workItem, ITaskExecutionContext context)
 {
     MonitorConfiguration.MonitorFoldersConfiguration.Folder[] enabledFolders = workItem.Configuration.MonitorFolders.GetEnabledFolders();
     context.Log.Message("Folder(s) monitored:\r\n{0}", new object[] { string.Join(Environment.NewLine,
                                                                                   from x in (IEnumerable <MonitorConfiguration.MonitorFoldersConfiguration.Folder>) enabledFolders
                                                                                   select string.Concat(" - ", x.ToString())) });
     MonitorConfiguration.MonitorFoldersConfiguration.Folder[] folderArray = enabledFolders;
     for (int i = 0; i < (int)folderArray.Length; i++)
     {
         MonitorConfiguration.MonitorFoldersConfiguration.Folder folder = folderArray[i];
         IEnumerable <string> strs = Directory.EnumerateFiles(folder.Path, folder.SearchPattern ?? "*", (folder.IncludeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
         MonitorConfiguration.MonitorFoldersConfiguration.FileCriteria criteria = folder.Criteria;
         string[] array = strs.Where <string>(new Func <string, bool>(criteria.IsSatisfiedBy)).ToArray <string>();
         if (array.Length != 0)
         {
             context.Log.Message("{0} file(s) matched by '{1}'.", new object[] { (int)array.Length, folder });
             StringBuilder stringBuilder = new StringBuilder();
             stringBuilder.AppendFormat("{0} file(s) matching criteria: '{1}'.", (int)array.Length, folder.Criteria);
             stringBuilder.AppendLine();
             stringBuilder.AppendLine(string.Join(Environment.NewLine,
                                                  from x in array.Take <string>(10)
                                                  select string.Format(" - {0}", x)));
             if ((int)array.Length > 10)
             {
                 stringBuilder.AppendLine("...");
             }
             workItem.Add(Time.UtcNow, this.Name(), stringBuilder.ToString(), new Target[] { folder.Target });
         }
     }
 }
Example #13
0
        public Task ExecuteAsync(FailsNTimesBeforeSucceeding payload, ITaskExecutionContext executionContext)
        {
            int currentFailCount;

            if (!mFailCount.TryGetValue(payload.Id, out currentFailCount))
            {
                currentFailCount = 0;
            }

            currentFailCount++;
            mFailCount.AddOrUpdate(payload.Id,
                                   addValueFactory: (id) => currentFailCount,
                                   updateValueFactory: (id, old) => currentFailCount);

            TestExecutorEventBus <FailsNTimesBeforeSucceeding> .Instance
            .NotifyExecutorCompleted();

            if (currentFailCount <= payload.FailuresBeforeSuccess)
            {
                throw new InvalidOperationException($"Sample invalid operation during {nameof( FailsNTimesBeforeSucceeding )}");
            }
            else
            {
                executionContext.NotifyTaskCompleted();
            }

            return(Task.CompletedTask);
        }
Example #14
0
        public override void Execute(ITaskExecutionContext <TaskThatHasStepsWorkItem> context)
        {
            context.WorkItem.Register(this);

            ExtremelyExpensiveObject expensiveObject = context.TypedBag <ExtremelyExpensiveObject>("SomeExpensiveObject");

            context.Log.Message(Encoding.Default.GetString(expensiveObject.Data));
        }
Example #15
0
 /// <summary>
 /// Sets the execution context of the task processor
 /// </summary>
 /// <param name="context">Task execution context</param>
 public void SetContext(ITaskExecutionContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     Context = context;
 }
 private DateTime GetDateRangeStartDate(ITaskExecutionContext taskExecutionContext)
 {
     var lastBlock = taskExecutionContext.GetLastDateRangeBlock(LastBlockOrder.LastCreated);
     if (lastBlock == null)
         return _configuration.FirstRunDate;
     else
         return lastBlock.EndDate;
 }
Example #17
0
 public virtual void Activate(ITaskExecutionContext ctx, ProcessDef processDef, IProcessScriptRuntime scriptRuntime)
 {
     Context = ctx;
     ProcessDefinition = processDef;
     TaskDefinition = processDef.GetRequiredTask(this.TaskId);
     ScriptRuntime = scriptRuntime;
     if (TaskDefinition == null) throw new Exception("Task not found in process definition: " + this.TaskId);
 }
Example #18
0
        public override bool IsDisabled(ITaskExecutionContext context)
        {
            MonitorConfiguration configuration = _configuration.Get <MonitorConfiguration>();

            context.TypedBag(ConfigurationName, configuration);

            return(configuration.Disabled);
        }
 private DateTime GetDateRangeStartDate(ITaskExecutionContext taskExecutionContext)
 {
     var lastBlock = taskExecutionContext.GetLastListBlock<Journey, BatchDatesHeader>();
     if (lastBlock == null)
         return _configuration.FirstRunDate;
     else
         return lastBlock.Header.ToDate;
 }
Example #20
0
 public override EmptyWorkItem Start(ITaskExecutionContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     this.StartTask(context);
     return(new EmptyWorkItem());
 }
Example #21
0
        public override Execution ContinueWith(ITaskExecutionContext <MonitorWorkItem> context)
        {
            if (!context.WorkItem.Configuration.PingUrls.ShouldExecute)
            {
                return(Execution.StepOver);
            }

            return(Execution.Execute);
        }
        public override void Execute(MaintenanceWorkItem workItem, ITaskExecutionContext context)
        {
            int num = this._archive.DeleteExpired();

            if (num > 0)
            {
                context.Log.Message("Deleted {0} expired archive(s).", new object[] { num });
            }
        }
        public override void Execute(ITaskExecutionContext <MaintenanceWorkItem> context)
        {
            int count = _archive.DeleteExpired();

            if (count > 0)
            {
                context.Log.Message("Deleted {0} expired archive(s).", count);
            }
        }
Example #24
0
        public async override Task Execute(ITaskExecutionContext context)
        {
            await Task.Run(() =>
            {
                _logger.Error("任务写入日志出现错误!");

                System.IO.File.AppendAllText(@"D:\test.txt", DateTime.Now + context.TaskId.ToString() + Environment.NewLine);
            });
        }
        public override Execution ContinueWith(ITaskExecutionContext <MonitorWorkItem> context)
        {
            if (context.WorkItem.Configuration.MonitorFolders.GetEnabledFolders().Length == 0)
            {
                return(Execution.StepOver);
            }

            return(Execution.Execute);
        }
Example #26
0
        public override Execution ContinueWith(ITaskExecutionContext <MaintenanceWorkItem> context)
        {
            if (_configuration.Disabled)
            {
                return(Execution.StepOver);
            }

            return(Execution.Execute);
        }
Example #27
0
        public override Execution ContinueWith(ITaskExecutionContext <TaskThatHasStepsWorkItem> context)
        {
            ExtremelyExpensiveObject expensiveObject = context.TypedBag("SomeExpensiveObject", new ExtremelyExpensiveObject());

            if (expensiveObject.Data.Length > 0)
            {
                return(Execution.Execute);
            }

            return(Execution.StepOut);
        }
        public override Execution ContinueWith(ITaskExecutionContext <MaintenanceWorkItem> context)
        {
            UCommerceMaintenanceConfiguration configuration = context.EnsureConfiguration(_configuration);

            if (!configuration.IndexMaintenance.Enabled)
            {
                return(Execution.StepOver);
            }

            return(base.ContinueWith(context));
        }
Example #29
0
        public override void Execute(ITaskExecutionContext <MaintenanceWorkItem> context)
        {
            DateTimeOffset olderThanOneDay = Time.UtcNow.AddHours(-24);

            int deletions = _deleteCommand.Value.Execute(olderThanOneDay);

            if (deletions > 0)
            {
                context.Log.Message("Deleted {0} records locked before {1}", deletions, olderThanOneDay);
            }
        }
Example #30
0
        public override MonitorWorkItem Start(ITaskExecutionContext context)
        {
            MonitorConfiguration configuration = context.TypedBag <MonitorConfiguration>(ConfigurationName);

            configuration.Assert();

            return(new MonitorWorkItem(configuration)
                   .AddIgnoreFilter(new MessageContainsText(configuration.IgnoreErrorsWithMessagesContaining))
                   .AddTargetRedirect(new RedirectForMonitorTargets(configuration.Targets))
                   .AddMessageGroupingPatterns(configuration.MessageGroupingPatterns));
        }
Example #31
0
 public virtual void Activate(ITaskExecutionContext ctx, ProcessDef processDef, IProcessScriptRuntime scriptRuntime)
 {
     Context           = ctx;
     ProcessDefinition = processDef;
     TaskDefinition    = processDef.GetRequiredTask(this.TaskId);
     ScriptRuntime     = scriptRuntime;
     if (TaskDefinition == null)
     {
         throw new Exception("Task not found in process definition: " + this.TaskId);
     }
 }
Example #32
0
        public bool EvalFlowCondition(TaskInstance ti, ProcessModel.FlowDef fd, ITaskExecutionContext ctx)
        {
            _pd.SetTaskInstanceInfo(ti, ctx);
            string k = DslUtil.FlowConditionKey(fd.Parent.Id, fd.From, fd.To);

            if (!_pd._flowConditions.ContainsKey(k))
            {
                throw new Exception("!no flow cond..");
            }
            _pd.SetTaskInstanceInfo(ti, ctx);
            return(_pd._flowConditions[k]());
        }
Example #33
0
        public override async Task ExecuteAsync(HashFileByHandle payload, ITaskExecutionContext executionContext)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                FileHandle fileHandle   = ResolveFileHandle(payload.HandleId);
                byte[]     fileContents = await ReadFileAsync(fileHandle);

                FileHashInfo fileHashInfo = ComputeHash(fileHandle, fileContents);

                StoreFileHashAndNotifyCompletion(fileHashInfo);
            }
        }
        private IList<IDateRangeBlockContext> GetDateRangeBlocks(ITaskExecutionContext taskExecutionContext)
        {
            using (var cs = taskExecutionContext.CreateCriticalSection())
            {
                if (cs.TryStart())
                {
                    var startDate = GetDateRangeStartDate(taskExecutionContext);
                    var endDate = DateTime.Now;

                    return taskExecutionContext.GetDateRangeBlocks(x => x.WithRange(startDate, endDate, TimeSpan.FromMinutes(30)));
                }
                throw new Exception("Could not acquire a critical section, aborted task");
            }
        }
        private void RunTask(ITaskExecutionContext taskExecutionContext)
        {
            try
            {
                var dateRangeBlocks = GetDateRangeBlocks(taskExecutionContext);
                foreach (var block in dateRangeBlocks)
                    ProcessBlock(block);

                taskExecutionContext.Complete();
            }
            catch (Exception ex)
            {
                taskExecutionContext.Error(ex.ToString(), true);
            }
        }
        private IList<IListBlockContext<Journey, BatchDatesHeader>> GetListBlocks(ITaskExecutionContext taskExecutionContext)
        {
            using (var cs = taskExecutionContext.CreateCriticalSection())
            {
                if (cs.TryStart())
                {
                    var startDate = GetDateRangeStartDate(taskExecutionContext);
                    var endDate = DateTime.Now;

                    var journeys = _travelDataService.GetJourneys(startDate, endDate).ToList();
                    var batchHeader = new BatchDatesHeader()
                    {
                        FromDate = startDate,
                        ToDate = endDate
                    };

                    short blockSize = 500;
                    return taskExecutionContext.GetListBlocks<Journey, BatchDatesHeader>(x => x.WithPeriodicCommit(journeys, batchHeader, blockSize, BatchSize.Fifty));
                }
                throw new Exception("Could not acquire a critical section, aborted task");
            }
        }
Example #37
0
 /// <summary>
 /// Creates a new task processor and binds it to the specified context.
 /// </summary>
 /// <param name="context">Task execution context</param>
 protected TaskProcessorBase(ITaskExecutionContext context)
     : this()
 {
     SetContext(context);
 }
Example #38
0
 /// <summary>
 /// Sets up the task that will be run in the specified context.
 /// </summary>
 /// <param name="context">Task execution context</param>
 public virtual void Setup(ITaskExecutionContext context)
 {
     Context = context;
 }
 public Dictionary<string, object> GatherOutputData(TaskInstance ti, ITaskExecutionContext ctx)
 {
     _pd.SetTaskInstanceInfo(ti, ctx);
     string ks = DslUtil.TaskScriptKey(ti.TaskId, "AfterComplete");
     if (_pd._stmts.ContainsKey(ks)) _pd._stmts[ks]();
     var td = _def.GetRequiredTask(ti.TaskId);
     
     foreach (var bd in td.OutputParameterBindings)
     {
         string k = DslUtil.TaskParamOutBindingKey(td.Id, bd.Target);
         if (bd.BindType == DataBindingType.Expr)
         {
             ti.TaskData[bd.Target] = _pd._exprs[k]();
         }
         else if (bd.BindType == DataBindingType.CopyVar)
         {
             var pi = ti.GetType().GetProperty(bd.Source);
             if (pi == null) throw new NGinnBPM.ProcessModel.Exceptions.TaskParameterInvalidException(bd.Source, "Property not found: " + bd.Source).SetTaskId(ti.TaskId);
             ti.TaskData[bd.Target] = pi.GetValue(ti, null);
         }
         else if (bd.BindType == DataBindingType.Literal)
         {
             ti.TaskData[bd.Target] = bd.Source; //todo: type convert
         }
         else throw new Exception();
     }
     
     string k2 = DslUtil.TaskOutputDataBindingKey(td.Id);
     if (_pd._exprs.ContainsKey(k2))
     {
         SC.IDictionary dic = (SC.IDictionary)_pd._exprs[k2]();
         return ToTaskData(dic);
     }
     Dictionary<string, object> ret = new Dictionary<string, object>();
     foreach (var vd in td.Variables.Where(x => x.VariableDir == ProcessModel.Data.VariableDef.Dir.Out || x.VariableDir == ProcessModel.Data.VariableDef.Dir.InOut))
     {
         ret[vd.Name] = ti.TaskData[vd.Name];
     }
     return ret;
 }
 public override void Setup(ITaskExecutionContext context)
 {
     Console.WriteLine("Setup: {0:hh:mm:ss,fff}", DateTime.Now);
     s_SetupAutoResetEvent.Set();
     Thread.Sleep(20);
 }
 public void ExecuteTaskScriptBlock(TaskInstance ti, string blockName, ITaskExecutionContext ctx)
 {
     throw new NotImplementedException();
 }
Example #42
0
 /// <summary>
 /// Sets the execution context this peek policy is used within.
 /// </summary>
 /// <param name="context">Task execution context</param>
 /// <remarks>The policy can use the context to access its properties.</remarks>
 public void SetTaskExecutionContext(ITaskExecutionContext context)
 {
     _waitTime = context == null ? 0 : context.GetProperty(PEEK_WAIT_TIME, 0);
 }
        public IEnumerable<Dictionary<string, object>> PrepareMultiInstanceTaskInputData(CompositeTaskInstance cti, TaskDef childTask, ITaskExecutionContext ctx)
        {
            if (!childTask.IsMultiInstance) throw new Exception();
            var k = DslUtil.TaskMultiInstanceSplitKey(childTask.Id);
            Func<object> fun = _pd._exprs[k];
            if (fun == null) throw new Exception();
            _pd.SetTaskInstanceInfo(cti, ctx);
            SC.IEnumerable enu;
            var val = fun();
            enu = val is SC.IEnumerable ? (SC.IEnumerable) val : new object[] { val };
            List<Dictionary<string, object>> ret = new List<Dictionary<string, object>>();
            foreach (object item in enu)
            {
                if (item is Dictionary<string, object>) 
                {
                    ret.Add((Dictionary<string, object>) item);
                }
                else if (item is SC.IDictionary)
                {
                    ret.Add(ToTaskData((SC.IDictionary)item));
                }
                else
                {
                    throw new Exception();
                }
            }
            return ret;
            
            /*
            ITaskScript scr = Context.ScriptManager.GetTaskScript(this.ParentProcess, taskId);
            Task tsk = MyTask.RequireTask(taskId);
            scr.TaskContext = Context;
            Dictionary<string, object> srcData = new Dictionary<string, object>(TaskData);
            scr.SourceData = srcData;
            object obj = scr.EvalMultiInstanceSplitQuery();
            IEnumerable enu;
            if (obj is IEnumerable)
                enu = (IEnumerable)obj;
            else
            {
                ArrayList al = new ArrayList();
                al.Add(obj);
                enu = al;
            }
            List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();

            foreach (object v in enu)
            {
                srcData[tsk.MultiInstanceItemAlias] = v;
                lst.Add(ExecuteInputDataBindings(scr, tsk));
            }
            return lst;
            */
            throw new NotImplementedException();
        }
 /// <summary>
 /// Sets up the task that will be run in the specified context.
 /// </summary>
 /// <param name="context">Task execution context</param>
 public override void Setup(ITaskExecutionContext context)
 {
     base.Setup(context);
     _batchSize = context.GetProperty(BATCH_SIZE_PROPERTY, 100);
 }
 public void ExecuteChildTaskOutputDataBinding(CompositeTaskInstance ti, TaskDef childTask, Dictionary<string, object> childOutputData, ITaskExecutionContext ctx)
 {
     if (string.IsNullOrEmpty(ti.InstanceId) ||
         string.IsNullOrEmpty(ti.TaskId) ||
         string.IsNullOrEmpty(ti.ProcessDefinitionId) ||
         string.IsNullOrEmpty(ti.ProcessInstanceId))
         throw new Exception("Task not inited properly");
     _pd.SetTaskInstanceInfo(ti, ctx);
     _pd.SetOutputData(childOutputData);
     _pd.SetInputData(null);
     
     var ctd = childTask.Parent;
     if (childTask.AutoBindVariables && ctd.Variables != null)
     {
         foreach (var vd in ctd.Variables)
         {
             if (childOutputData.ContainsKey(vd.Name))
             {
                 ti.TaskData[vd.Name] = childOutputData[vd.Name];
             }
         }
     }
     if (childTask.OutputDataBindings != null)
     {
         foreach (var bd in childTask.OutputDataBindings)
         {
             switch (bd.BindType)
             {
                 case DataBindingType.CopyVar:
                     ti.TaskData[bd.Target] = childOutputData[bd.Source];
                     break;
                 case DataBindingType.Literal:
                     ti.TaskData[bd.Target] = bd.Source;
                     break;
                 case DataBindingType.Expr:
                     string k = DslUtil.TaskVarOutBindingKey(childTask.Id, bd.Target);
                     if (!_pd._exprs.ContainsKey(k)) throw new Exception("!");
                     ti.TaskData[bd.Target] = _pd._exprs[k]();
                     break;
             }
         }
     }
 }
 public void InitializeNewTask(TaskInstance ti, Dictionary<string, object> inputData, ITaskExecutionContext ctx)
 {
     if (string.IsNullOrEmpty(ti.InstanceId) ||
         string.IsNullOrEmpty(ti.TaskId) ||
         string.IsNullOrEmpty(ti.ProcessDefinitionId) ||
         string.IsNullOrEmpty(ti.ProcessInstanceId))
         throw new Exception("Task not inited properly");
     _pd.SetTaskInstanceInfo(ti, ctx);
     
     TaskDef td = _def.GetRequiredTask(ti.TaskId);
     if (td.Variables != null)
     {
         foreach (var vd in td.Variables)
         {
             if (vd.VariableDir == ProcessModel.Data.VariableDef.Dir.In ||
                 vd.VariableDir == ProcessModel.Data.VariableDef.Dir.InOut)
             {
                 if (inputData.ContainsKey(vd.Name))
                     ti.TaskData[vd.Name] = inputData[vd.Name];
             }
             if (!ti.TaskData.ContainsKey(vd.Name))
             {
                 var k = DslUtil.TaskVariableDefaultKey(td.Id, vd.Name);
                 if (_pd._exprs.ContainsKey(k))
                 {
                     ti.TaskData[vd.Name] = _pd._exprs[k]();
                 }
                 else if (!string.IsNullOrEmpty(vd.DefaultValueExpr))
                 {
                     ti.TaskData[vd.Name] = vd.DefaultValueExpr; //TODO: add type conversion
                 }
                 else if (vd.IsRequired)
                     throw new NGinnBPM.ProcessModel.Exceptions.DataValidationException("Required variable missing: " + vd.Name).SetTaskId(ti.TaskId).SetProcessDef(ti.ProcessDefinitionId);
             }
         }
     }
     //now initialize task parameters
     if (td.InputParameterBindings != null)
     {
         foreach (var bd in td.InputParameterBindings)
         {
             var pi = ti.GetType().GetProperty(bd.Target);
             if (pi == null)
             {
                 throw new NGinnBPM.ProcessModel.Exceptions.TaskParameterInvalidException(bd.Target, "Property not found: " + bd.Target).SetTaskId(ti.TaskId);
             }
             string k = DslUtil.TaskParamInBindingKey(td.Id, bd.Target);
             if (bd.BindType == DataBindingType.Expr)
             {
                 pi.SetValue(ti, _pd._exprs[k](), null);
             }
             else if (bd.BindType == DataBindingType.CopyVar)
             {
                 pi.SetValue(ti, ti.TaskData.ContainsKey(bd.Source) ? ti.TaskData[bd.Source] : null, null);
             }
             else if (bd.BindType == DataBindingType.Literal)
             {
                 pi.SetValue(ti, Convert.ChangeType(bd.Source, pi.PropertyType), null);
             }
             else throw new Exception();
         }
     }
     string ks = DslUtil.TaskScriptKey(ti.TaskId, "BeforeEnable");
     if (_pd._stmts.ContainsKey(ks))
         _pd._stmts[ks]();
 }
Example #47
0
 /// <summary>
 /// Sets the execution context of the task processor
 /// </summary>
 /// <param name="context">Task execution context</param>
 public void SetContext(ITaskExecutionContext context)
 {
     if (context == null) throw new ArgumentNullException("context");
     Context = context;
 }
        public Dictionary<string, object> PrepareChildTaskInputData(CompositeTaskInstance cti, TaskDef childTask, ITaskExecutionContext ctx)
        {
            _pd.SetTaskInstanceInfo(cti, ctx);
            
            string k1 = DslUtil.TaskInputDataBindingKey(childTask.Id);
            if (_pd._exprs.ContainsKey(k1))
            {
                //get full data record
                SC.IDictionary dic = (SC.IDictionary)_pd._exprs[k1]();
                return ToTaskData(dic);
            }

            Dictionary<string, object> ret = new Dictionary<string, object>();
            if (childTask.Variables != null)
            {
                if (childTask.AutoBindVariables)
                {
                    foreach (var vd in childTask.Variables)
                    {
                        if (vd.VariableDir == ProcessModel.Data.VariableDef.Dir.In ||
                            vd.VariableDir == ProcessModel.Data.VariableDef.Dir.InOut)
                        {
                            //TODO add type conversion/control
                            if (cti.TaskData.ContainsKey(vd.Name)) ret[vd.Name] = cti.TaskData[vd.Name];
                        }
                    }
                }
                if (childTask.InputDataBindings != null)
                {
                    foreach (var bd in childTask.InputDataBindings)
                    {
                        if (bd.BindType == DataBindingType.CopyVar)
                        {
                            ret[bd.Target] = cti.TaskData[bd.Source];
                        }
                        else if (bd.BindType == DataBindingType.Literal)
                        {
                            ret[bd.Target] = bd.Source;
                        }
                        else if (bd.BindType == DataBindingType.Expr)
                        {
                            string k = DslUtil.TaskVarInBindingKey(childTask.Id, bd.Target);
                            if (!_pd._exprs.ContainsKey(k)) throw new Exception("Fail: missing delegate: " + k);
                            ret[bd.Target] = _pd._exprs[k]();
                        }
                    }
                }
            }
            return ret;
        }
Example #49
0
 /// <summary>
 /// Sets the execution context this peek policy is used within.
 /// </summary>
 /// <param name="context">Task execution context</param>
 /// <remarks>This policy does not use the context.</remarks>
 public void SetTaskExecutionContext(ITaskExecutionContext context)
 {
 }
 public bool EvalFlowCondition(TaskInstance ti, ProcessModel.FlowDef fd, ITaskExecutionContext ctx)
 {
     _pd.SetTaskInstanceInfo(ti, ctx);
     string k = DslUtil.FlowConditionKey(fd.Parent.Id, fd.From, fd.To);
     if (!_pd._conds.ContainsKey(k)) throw new Exception("!no flow cond..");
     _pd.SetTaskInstanceInfo(ti, ctx);
     return _pd._conds[k]();
 }
 public void ExecuteTaskScriptBlock(TaskInstance ti, string blockName, ITaskExecutionContext ctx)
 {
     string k = DslUtil.TaskScriptKey(ti.TaskId, blockName);
     _pd.SetTaskInstanceInfo(ti, ctx);
     try
     {
         Action act;
         if (_pd._stmts.TryGetValue(k, out act) && act != null)
         {
             act();
         }
     }
     catch (Exception ex)
     {
         throw;
     }
 }
 public void SetTaskInstanceInfo(TaskInstance ti, ITaskExecutionContext ctx)
 {
     this.Task = ti;
     this.TaskData = new QuackTaskDataWrapper(ti.TaskData);
     this.Context = ctx;
 }