예제 #1
0
        public void Process(ScheduledTaskContext context)
        {
            // We have a task for each type that requires scheduled processing. We could have done
            // this differently, by having a task for each ContentItem. The processing for each of
            // those would have been lighter. However, changes in the configuration for this task
            // would have been much harder to handle.

            string taskTypeStr = context.Task.TaskType;

            if (taskTypeStr.IndexOf(Constants.ScheduledTaskName) == 0)
            {
                // by splitting the string we should get a type name. To be safe, we do ElementAtOrDefault
                var typeName = taskTypeStr
                               .Split(new string[] { "_" }, 2, StringSplitOptions.RemoveEmptyEntries)
                               .ElementAtOrDefault(1);
                if (!string.IsNullOrWhiteSpace(typeName))
                {
                    // get the settings for the type
                    var settings = _contentDefinitionManager.GetTypeDefinition(typeName)
                                   .Parts
                                   .FirstOrDefault(ctpd => ctpd.PartDefinition.Name == "GDPRPart")
                                   ?.Settings
                                   ?.GetModel <GDPRPartTypeSchedulingSettings>()
                                   ?? new GDPRPartTypeSchedulingSettings();

                    if (settings.ScheduleAnonymization)
                    {
                        Process(
                            typeName,
                            settings.EventForAnonymization,
                            settings.AnonymizationDaysToWait,
                            _contentGDPRManager.Anonymize,
                            context.Task.ContentItem == null); // this being null means the task was not created here
                    }

                    if (settings.ScheduleErasure)
                    {
                        Process(
                            typeName,
                            settings.EventForErasure,
                            settings.ErasureDaysToWait,
                            _contentGDPRManager.Erase,
                            context.Task.ContentItem == null);
                    }

                    if (settings.ScheduleAnonymization || settings.ScheduleErasure)
                    {
                        // reschedule
                        _taskManager.CreateTask(
                            taskTypeStr,                               // "same" task
                            _clock.UtcNow + TimeSpan.FromDays(1),      // one day from now
                            _siteService.GetSiteSettings().ContentItem // pass a ContentItem.
                            );
                        // passing a ContentItem there to the new task allows us to discriminate, when we are processing it,
                        // over whether the task being processed was created here or in the other service. This allows us to
                        // better filter over things in the query.
                    }
                }
            }
        }
예제 #2
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != Constants.TakeSnapshotTaskName)
            {
                return;
            }

            try {
                //the default export service impl makes an assumption that there is an associated user, so we need to set the owner here
                var siteOwner = _membershipService.GetUser(_orchardServices.WorkContext.CurrentSite.As <SiteSettingsPart>().SuperUser);
                _authenticationService.SetAuthenticatedUserForRequest(siteOwner);

                _snapshotService.TakeSnaphot();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Failed to generate a scheduled Content Sync Snapshot. An exception was thrown by the task handler.");
            }

            //now reschedule the task
            _scheduledTaskManager.DeleteTasks(null, a => a.TaskType == Constants.TakeSnapshotTaskName);

            var snapshotFrequency = _orchardServices.WorkContext.CurrentSite.As <ContentSyncSettingsPart>().SnapshotFrequencyMinutes;

            if (snapshotFrequency == 0)
            {
                return;
            }

            _scheduledTaskManager.CreateTask(Constants.TakeSnapshotTaskName, _clock.UtcNow.AddMinutes(snapshotFrequency), null);
        }
예제 #3
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType.StartsWith(UPDATEVALUES_TASK + "_"))
     {
         _sweepGenerator.Terminate();
         try {
             // Task name is something like HiddenStringFieldValueUpdate_ContentType_PartName_FieldName
             var partFieldName = context.Task.TaskType.Split('_');
             if (partFieldName.Length == 5)
             {
                 var typeName  = partFieldName[1];
                 var partName  = partFieldName[2];
                 var fieldName = partFieldName[3];
                 HiddenStringFieldUpdateProcessVariant updateType;
                 var validUpdate = Enum.TryParse(partFieldName[4], out updateType);
                 if (validUpdate)
                 {
                     ProcessInternal(updateType, typeName, partName, fieldName);
                 }
             }
         } catch (Exception ex) {
             Logger.Error(ex, "Update Hidden String Values Error: " + context.Task.TaskType + " - " + ex.Message);
         } finally {
             _sweepGenerator.Activate();
         }
     }
 }
        public void Process(ScheduledTaskContext context)
        {
            var part = context.Task.ContentItem.As <ConfigurationPart>();

            if (part == null)
            {
                return;
            }

            var name = GetName(part.Title());

            if (context.Task.TaskType != name)
            {
                return;
            }

            Logger.Information("Running {0}", name);

            if (part.TryCatch)
            {
                try {
                    _tfl.Run(new TransformalizeRequest(part, new Dictionary <string, string>(), null, Logger));
                } catch (Exception ex) {
                    Logger.Error(ex, ex.Message);
                }
            }
            else
            {
                _tfl.Run(new TransformalizeRequest(part, new Dictionary <string, string>(), null, Logger));
            }
        }
예제 #5
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType == "SwitchTheme")
     {
         _themeService.EnableThemeFeatures("Offline");
         _siteThemeService.SetSiteTheme("Offline");
     }
     else if (context.Task.TaskType == "ResetSite")
     {
         Logger.Information("start reseting site data at {2} utc", context.Task.ScheduledUtc);
         var factory = _sessionFactoryHolder.GetSessionFactory();
         using (var session = factory.OpenSession()){
             var connection = session.Connection;
             var dialect    = Dialect.GetDialect(_sessionFactoryHolder.GetConfiguration().Properties);
             var meta       = dialect.GetDataBaseSchema((DbConnection)connection);
             var tables     = meta.GetTables(null, null, null, null);
             try{
                 foreach (DataRow dr in tables.Rows)
                 {
                     _schemaBuilder.DropTable(dr["TABLE_NAME"].ToString());
                 }
                 ExecuteOutSql("~/Modules/Coevery.SiteReset/Sql/create.sql");
             }
             catch (Exception ex) {
                 Logger.Warning(ex, "reset site error");
             }
         }
     }
 }
예제 #6
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType.Equals(TASK_NAME, StringComparison.InvariantCultureIgnoreCase))
     {
         _facebookShopService.SyncProducts();
     }
 }
예제 #7
0
        public void Process(ScheduledTaskContext context)
        {
            try {
                var btnName = ButtonName(context.Task.TaskType);
                if (btnName == null)
                {
                    return;
                }
                if (string.IsNullOrWhiteSpace(btnName))
                {
                    btnName = context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().ButtonName;
                }
                if (string.IsNullOrWhiteSpace(btnName))
                {
                    // failed to figure out a valid button name
                    return;
                }

                _workflowManager.TriggerEvent("DynamicButtonEvent", context.Task.ContentItem, () =>
                                              new Dictionary <string, object> {
                    { "ButtonName", btnName },
                    { "Content", context.Task.ContentItem }
                });
            } catch (Exception ex) {
                Logger.Error(ex,
                             "Error in DynamicButtonToWorflowsScheduledTaskHandler. ContentItem: {0}, ScheduledUtc: {1:yyyy-MM-dd HH.mm.ss}",
                             context.Task.ContentItem, context.Task.ScheduledUtc);
            } finally {
                if (context.Task.ContentItem.Has <DynamicButtonToWorkflowsPart>())
                {
                    context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().ButtonName     = "";
                    context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().MessageToWrite = "";
                }
            }
        }
예제 #8
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == TASK_TYPE)
            {
                try
                {
                    Logger.Information("----------------------------- Check Order Checker task started --------------------------------");
                    // _campaignService.CheckExpiredCampaigns();

                    var _ordersToDelete = _orderService.GetAllOrders().Where(aa => aa.Email == null);//.Where(aa => aa.Created - DateTime.Now.Subtract(new DateTime(0, 0, 0, 0, 31, 0, 0)));

                    foreach (var order in _ordersToDelete)
                    {
                        //System.IO.File.Create("c:\\omid.txt").Write(new byte[] { 1, 5, 7 }, 0, 3);
                        if (order.Created.AddMinutes(15) > DateTime.UtcNow)
                        {
                            continue;
                        }
                        _orderService.DeleteOrder(order.Id);
                    }
                }
                catch (Exception e)
                {
                    this.Logger.Error("Error occured when running Order Checker campaigns task ---------------- >" + e.ToString(), e.Message);
                    var nextTaskDate = DateTime.UtcNow.AddMinutes(10);
                    ScheduleNextTask(nextTaskDate);
                }
                finally
                {
                    Logger.Information("----------------------------- Check Order Checker task finished --------------------------------");
                    var nextTaskDate = DateTime.UtcNow.AddMinutes(10);
                    ScheduleNextTask(nextTaskDate);
                }
            }
        }
예제 #9
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != Constants.CleanupSnapshots)
            {
                return;
            }

            try
            {
                var idsToRetain = new List <int>();

                foreach (var retentionPolicy in _retentionPolicies)
                {
                    idsToRetain.AddRange(retentionPolicy.GetSnapshotIdsToRetain());
                }

                var recordsToDelete = _repository.Table.Where(r => !idsToRetain.Contains(r.Id));

                foreach (var record in recordsToDelete)
                {
                    _repository.Delete(record);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Failed to cleanup Content Sync Snapshots. An exception was thrown by the task handler.");
            }

            //now reschedule the task
            _scheduledTaskManager.DeleteTasks(null, a => a.TaskType == Constants.CleanupSnapshots);
            _scheduledTaskManager.CreateTask(Constants.CleanupSnapshots, _clock.UtcNow.AddMinutes(1), null);
        }
예제 #10
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == TASK_TYPE)
            {
                try
                {
                    Logger.Information("----------------------------- Update Campaigns --------------------------------");

                    /*foreach (var campaign in _campaignRepository.Fetch(aa => aa.WhenDeleted == null))
                     * {
                     *  var orders = _orderRepository.Fetch(aa => aa.Campaign.Id == campaign.Id && (aa.OrderStatusRecord.Name == "Approved" ||
                     *          aa.OrderStatusRecord.Name == "Printing" ||
                     *          aa.OrderStatusRecord.Name == "Shipped" ||
                     *          aa.OrderStatusRecord.Name == "Delivered"));
                     *
                     *  campaign.ProductCountSold = orders.Select(aa => aa.TotalSold).Sum();
                     *  _campaignRepository.Update(campaign);
                     *
                     * }*/
                }
                catch (Exception e)
                {
                    this.Logger.Error("Error occured when running Update Campaigns task ---------------- >" + e.ToString(), e.Message);
                }
                finally
                {
                    Logger.Information("----------------------------- Check Update Campaigns task finished --------------------------------");
                    var nextTaskDate = DateTime.UtcNow.AddMinutes(5);
                    ScheduleNextTask(nextTaskDate);
                }
            }
        }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != TaskType)
            {
                return;
            }
            try {
                string        path = HostingEnvironment.MapPath(_contactsImportRelativePath);
                DirectoryInfo dir  = new DirectoryInfo(path);
                if (dir.Exists == false)
                {
                    dir.Create();
                }
                FileInfo logFile = null;
                foreach (var file in dir.GetFiles("*.csv", SearchOption.TopDirectoryOnly))
                {
                    try {
                        // avvia una nuova transazione per ogni file da elaborare
                        _transactionManager.RequireNew();

                        // importa solo i csv che non hanno già un log corrispondente
                        logFile = new FileInfo(file.FullName + ".log");
                        if (logFile.Exists == false)
                        {
                            byte[]     bufferContent = File.ReadAllBytes(file.FullName);
                            string     fileContent   = Encoding.Unicode.GetString(bufferContent);
                            ImportUtil import        = new ImportUtil(_orchardServices);
                            import.ImportCsv(fileContent);
                            string result    = string.Format("Import result: Errors: {0}, Mails: {1}, Sms: {2}.", import.Errors.Count, import.TotMail, import.TotSms);
                            string strErrors = FormatErrors(import.Errors);
                            byte[] buffer    = Encoding.Unicode.GetBytes(string.Format("{0}{1}{2}", result, Environment.NewLine, strErrors));
                            File.WriteAllBytes(string.Format("{0}{1}{2}.log", dir.FullName, Path.DirectorySeparatorChar, file.Name),
                                               buffer);
                        }
                    } finally {
                        try {
                            // sposta il file in una sottocartella
                            DirectoryInfo archiveDir = new DirectoryInfo(dir.FullName + Path.DirectorySeparatorChar + "history");
                            if (archiveDir.Exists == false)
                            {
                                archiveDir.Create();
                            }
                            string archivePath = archiveDir.FullName + Path.DirectorySeparatorChar + file.Name;
                            file.MoveTo(archivePath);
                        } catch {
                            // se non riesce a spostare il file, lo elimina per non dare fastidio agli import successivi
                            file.Delete();
                        }
                    }
                }
            } catch (Exception ex) {
                string idcontenuto = "nessun id ";
                try {
                    idcontenuto = context.Task.ContentItem.Id.ToString();
                } catch (Exception ex2) { Logger.Error(ex2, ex2.Message); }
                Logger.Error(ex, "Error on " + TaskType + " for ContentItem id = " + idcontenuto + " : " + ex.Message);
            }
        }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != "DemoTask")
            {
                return;
            }

            Debugger.Break();
        }
예제 #13
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != TaskType)
            {
                return;
            }

            Renew(true);
            CleanUp();
        }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == "Unpublish")
            {
                Logger.Information("Unpublishing item #{0} version {1} scheduled at {2} utc",
                                   context.Task.ContentItem.Id,
                                   context.Task.ContentItem.Version,
                                   context.Task.ScheduledUtc);

                _contentManager.Unpublish(context.Task.ContentItem);
            }
        }
        public void Process(ScheduledTaskContext context)
        {
            var taskType = context.Task.TaskType;

            if (Constants.DefaultEventNames.Contains(taskType))
            {
                var contentItem = context.Task.ContentItem;
                _workflowManager.TriggerEvent(taskType, contentItem,
                                              () => new Dictionary <string, object> {
                    { "Content", contentItem }
                });
            }
        }
예제 #16
0
 public void Process(ScheduledTaskContext context)
 {
     try {
         if (context.Task.TaskType != TaskType)
         {
             return;
         }
         // esegue l'allineamento di tutti i contenuti in un task schedulato
         _reactionsService.NormalizeAllSummaries();
     }
     catch (Exception ex) {
         Logger.Error(ex, "Error in Laser.Orchard.UserReactionsSettings.Task. ScheduledUtc: {0:yyyy-MM-dd HH.mm.ss}.", context.Task.ScheduledUtc);
     }
 }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == "TriggerRule")
            {
                Logger.Information("Triggering Rule item #{0} version {1} scheduled at {2} utc",
                                   context.Task.ContentItem.Id,
                                   context.Task.ContentItem.Version,
                                   context.Task.ScheduledUtc);

                var scheduledActionTask = context.Task.ContentItem.As <ScheduledActionTaskPart>();

                _rulesManager.ExecuteActions(scheduledActionTask.ScheduledActions.Select(x => x.ActionRecord), new Dictionary <string, object>());
            }
        }
예제 #18
0
        public void Process(ScheduledTaskContext context)
        {
            try {
                //  this.Logger.Error("sono dentro process");
                string   taskTypeStr = context.Task.TaskType;
                string[] taTypeParts = taskTypeStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (taTypeParts.Length == 2)
                {
                    if (taTypeParts[0] == TaskType)
                    {
                        bool sent = false;
                        try {
                            int gId = int.Parse(taTypeParts[1]);
                            sent = _questionnairesServices.SendTemplatedEmailRanking(gId);
                        } catch (Exception e) {
                            this.Logger.Error(e, e.Message);
                            throw;
                        }
                        if (!sent)
                        {
                            //reschedule
                            DateTime nextDate = ((DateTime)(context.Task.ScheduledUtc)).AddMinutes(5);
                            _taskManager.CreateTask(taskTypeStr, nextDate, context.Task.ContentItem);
                        }
                    }
                }
            } catch (Exception ex) {
                string idcontenuto = "nessun id ";
                try {
                    idcontenuto = context.Task.ContentItem.Id.ToString();
                } catch (Exception ex2) { Logger.Error(ex2, ex2.Message); }
                Logger.Error(ex, "Error on " + TaskType + " analized input: " + context.Task.TaskType + " for ContentItem id = " + idcontenuto + " : " + ex.Message);
            }
            //if (context.Task.TaskType == TaskType) {
            //    try {

            //        bool sended= _questionnairesServices.SendTemplatedEmailRanking();
            //        //The following line does not work here, because the task does not contain the ContentItem
            //       //_questionnairesServices.SendTemplatedEmailRanking(context.Task.ContentItem.Id);
            //    }
            //    catch (Exception e) {
            //        this.Logger.Error(e, e.Message);
            //    }
            //    finally {
            //        DateTime nextTaskDate = DateTime.UtcNow.AddHours(6); //DateTime.UtcNow.AddSeconds(30);//
            //        ScheduleNextTask(nextTaskDate);
            //    }
            //}
        }
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType != TaskType)
     {
         return;
     }
     try {
         Logger.Error("SynchronizeContacts task started.");
         _communicationService.Synchronize();
         Logger.Error("SynchronizeContacts task ended.");
     }
     catch (Exception ex) {
         Logger.Error(ex, "SynchronizeContacts task error." + ex.Message);
     }
 }
        // This method will be called periodically (every minute) with the current task context. Because of this we have to check if the
        // current task is ours. (BTW this way the same taks handler can handle multiple tasks.)
        // Remember that although we scheduled the task to be run 3 minutes in the future it won't run in exactly 3 minutes, but practically
        // in a one minute time frame after the scheduled time, the worst case being one minute after what we scheduled. Also if the Orchard
        // instance is torn down before that (e.g. by an AppPool recycle) the task may run at an even later date. Don't rely on backgroud tasks
        // runnin exactly on schedule!
        void IScheduledTaskHandler.Process(ScheduledTaskContext context)
        {
            // Not our task
            if (context.Task.TaskType != TaskType)
            {
                return;
            }

            // Check out in the debugger: this should be called every 3 minutes.
            _eventHandler.ScheduledTaskFired(new ScheduledTaskFiredContext {
                TaskType = TaskType
            });

            CreateTaskIfNew(true); // Renewing the task
        }
예제 #21
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == TASK_TYPE)
            {
                try
                {
                    Logger.Information("----------------------------- Email Sender task started --------------------------------");
                    // _campaignService.CheckExpiredCampaigns();


                    var api =
                        new MandrillApi(
                            _settingsService.GetSettingByCulture(/*request.BuyerCultureRecord.Culture*/ "en-MY")
                            .List()
                            .First()
                            .ApiKey);

                    var countToSend = 100;

                    var emails = _mailOutBox.Table.Take(countToSend).ToArray();
                    foreach (Outbox outBox in emails)
                    {
                        if (outBox.EmailType == "Purchase")
                        {
                            if (outBox.OrderId.HasValue && _orders.Get(outBox.OrderId.Value).OrderStatusRecord.Name != OrderStatus.Approved.ToString())
                            {
                                continue;
                            }
                        }
                        var message = Newtonsoft.Json.JsonConvert.DeserializeObject <Mandrill.Model.MandrillMessage>(outBox.Data);
                        var result  = api.Messages.Send(message);
                        _mailOutBox.Delete(outBox);
                    }
                }
                catch (Exception e)
                {
                    this.Logger.Error("Error occured when running Order Checker campaigns task ---------------- >" + e.ToString(), e.Message);
                    var nextTaskDate = DateTime.UtcNow.AddMinutes(1).AddSeconds(4);
                    ScheduleNextTask(nextTaskDate);
                }
                finally
                {
                    Logger.Information("----------------------------- Check Order Checker task finished --------------------------------");
                    var nextTaskDate = DateTime.UtcNow.AddMinutes(1).AddSeconds(4);
                    ScheduleNextTask(nextTaskDate);
                }
            }
        }
예제 #22
0
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType == TaskType)
            {
                try {
                    int      id   = 0;
                    DateTime?from = null;
                    DateTime?to   = null;
                    // ricava i parametri
                    string   filters = context.Task.ContentItem.As <TitlePart>().Title;
                    string[] pars    = filters.Split('&');
                    foreach (var parameter in pars)
                    {
                        string[] keyValue = parameter.Split('=');
                        switch (keyValue[0])
                        {
                        case "id":
                            id = Convert.ToInt32(keyValue[1]);
                            break;

                        case "from":
                            if (string.IsNullOrWhiteSpace(keyValue[1]) == false)
                            {
                                from = DateTime.ParseExact(keyValue[1], "yyyyMMdd", CultureInfo.InvariantCulture);
                            }
                            break;

                        case "to":
                            if (string.IsNullOrWhiteSpace(keyValue[1]) == false)
                            {
                                to = DateTime.ParseExact(keyValue[1], "yyyyMMdd", CultureInfo.InvariantCulture);
                            }
                            break;
                        }
                    }
                    // estrae le statistiche su file
                    _questionnairesServices.SaveQuestionnaireUsersAnswers(id, from, to);
                }
                catch (Exception ex) {
                    string idcontenuto = "nessun id ";
                    try {
                        idcontenuto = context.Task.ContentItem.Id.ToString();
                    }
                    catch (Exception ex2) { Logger.Error(ex2, ex2.Message); }
                    Logger.Error(ex, "Error on " + TaskType + " for ContentItem id = " + idcontenuto + " : " + ex.Message);
                }
            }
        }
예제 #23
0
        public void Sweep()
        {
            var taskEntries = _repository.Fetch(x => x.ScheduledUtc <= _clock.UtcNow)
                              .Select(x => new { x.Id, Action = x.TaskType })
                              .ToArray();

            foreach (var taskEntry in taskEntries)
            {
                _transactionManager.RequireNew();

                try {
                    // fetch the task
                    var taskRecord = _repository.Get(taskEntry.Id);

                    // another server or thread has performed this work before us
                    if (taskRecord == null)
                    {
                        continue;
                    }

                    // removing record first helps avoid concurrent execution
                    _repository.Delete(taskRecord);

                    // persisting the change so it takes effect in the other async operations
                    _repository.Flush();

                    var context = new ScheduledTaskContext {
                        Task = new Task(_contentManager, taskRecord)
                    };

                    // dispatch to standard or custom handlers
                    foreach (var handler in _handlers)
                    {
                        handler.Process(context);
                    }
                }
                catch (Exception ex) {
                    if (ex.IsFatal())
                    {
                        throw;
                    }
                    Logger.Warning(ex, "Unable to process scheduled task #{0} of type {1}", taskEntry.Id, taskEntry.Action);
                    _transactionManager.Cancel();
                }
            }
        }
예제 #24
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType == TASK_TYPE_APPEND_MODEL && context.Task.ContentItem != null)
     {
         try
         {
             _blockModelService.AppendModel(context.Task.ContentItem);
         }
         catch (Exception e)
         {
             this.Logger.Error(e, e.Message);
         }
         finally
         {
         }
     }
 }
예제 #25
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType == TASK_TYPE_EMAIL && context.Task.ContentItem != null)
     {
         try
         {
             var em = context.Task.ContentItem.As <EmailPart>();
             _userService.EmailUsers(em.Recipients.SplitStringArray(), em.Subject, em.Body, em.Retry, em.ForwardSupport, em.FromAddress, em.FromName, em.HideRecipients);
         }
         catch (Exception e)
         {
             this.Logger.Error(e, e.Message);
         }
         finally
         {
         }
     }
 }
예제 #26
0
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType == TASK_TYPE_MAIL_API && context.Task.ContentItem != null)
     {
         try
         {
             var p = context.Task.ContentItem.As <MailApiPart>();
             _mailApi.ProcessApiRequest(p);
         }
         catch (Exception e)
         {
             this.Logger.Error(e, e.Message);
         }
         finally
         {
         }
     }
 }
 public void Process(ScheduledTaskContext context)
 {
     if (context.Task.TaskType == "SychronizeUser")
     {
         IUser user = context.Task.ContentItem.As <IUser>();
         this._webStoreServices.UsingClient(
             c =>
         {
             Customer customer = c.CustomerClient.GetCustomer(user.UserName, false);
             if (customer != null)
             {
                 c.CustomerClient.UpdateCustomer(customer.CustomerId, user.UserName, user.Email, true);
                 this._customerEventHandlers.Trigger(h => h.Updated(customer));
             }
         },
             false
             );
     }
 }
 public void Process(ScheduledTaskContext context)
 {
     try {
         if (context.Task.TaskType != TaskType)
         {
             return;
         }
         _workflowManager.TriggerEvent(context.Task.ContentItem.As <ButtonToWorkflowsPart>().ActionToExecute, context.Task.ContentItem, () => new Dictionary <string, object> {
             { "Content", context.Task.ContentItem }
         });
         context.Task.ContentItem.As <ButtonToWorkflowsPart>().MessageToWrite  = "";
         context.Task.ContentItem.As <ButtonToWorkflowsPart>().ActionToExecute = "";
         context.Task.ContentItem.As <ButtonToWorkflowsPart>().ActionAsync     = false;
         context.Task.ContentItem.As <ButtonToWorkflowsPart>().ButtonsDenied   = false;
     }
     catch (Exception ex) {
         Logger.Error(ex, "Error in ButtonToWorflowsScheduledTaskHandler. ContentItem: {0}, ScheduledUtc: {1:yyyy-MM-dd HH.mm.ss}", context.Task.ContentItem, context.Task.ScheduledUtc);
     }
 }
        public void Sweep()
        {
            var taskEntries = _repository.Fetch(x => x.ScheduledUtc <= _clock.UtcNow)
                              .Select(x => new { x.Id, Action = x.TaskType })
                              .ToArray();

            foreach (var taskEntry in taskEntries)
            {
                //TODO: start a dedicated transaction scope

                try {
                    // fetch the task
                    var taskRecord = _repository.Get(taskEntry.Id);

                    // another server or thread has performed this work before us
                    if (taskRecord == null)
                    {
                        continue;
                    }

                    // removing record first helps avoid concurrent execution
                    _repository.Delete(taskRecord);

                    var context = new ScheduledTaskContext {
                        Task = new Task(_contentManager, taskRecord)
                    };

                    // dispatch to standard or custom handlers
                    foreach (var handler in _handlers)
                    {
                        handler.Process(context);
                    }

                    //TODO: commit dedicated scope
                }
                catch (Exception ex) {
                    Logger.Warning(ex, "Unable to process scheduled task #{0} of type {1}", taskEntry.Id, taskEntry.Action);

                    //TODO: handle exception to rollback dedicated xact, and re-delete task record.
                    // does this also need some retry logic?
                }
            }
        }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != TaskType)
            {
                return;
            }

            Renew(true);

            // Clean up old events
            var cleanUpCount = _repository.Table.Count() - 1000;

            if (cleanUpCount <= 0)
            {
                return;
            }
            foreach (var record in _repository.Table.OrderBy(record => record.Id).Take(cleanUpCount))
            {
                _repository.Delete(record);
            }
        }
예제 #31
0
        public void ScheduledTaskFailWhenMaxRetriesReached()
        {
            var exit = false;
            var context = new ScheduledTaskContext(0, () => exit, null, () => exit = true);
            var mockedFailedScheduledTask = new MockedFailedScheduledTask(context);

            mockedFailedScheduledTask.ScheduledTaskExecute(1, Guid.NewGuid(), 1, "TEST", 3, 3);

            Assert.AreEqual(ScheduledTaskStatusType.Failed, mockedFailedScheduledTask.StatusResult);
        }