public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem) { var item = commandItem.InnerItem; if(item["active"] != "1") return; Log("Starting task"); MultilistField mf = item.Fields["reports"]; if (mf == null) return; var force = item["sendempty"] == "1"; var filePaths = mf.GetItems().Select(i => runReport(i,force)); var mailMessage = new MailMessage { From = new MailAddress(item["from"]), Subject = item["subject"], }; var senders = item["to"].Split(','); foreach (var sender in senders) { mailMessage.To.Add(sender); } mailMessage.Body = Sitecore.Web.UI.WebControls.FieldRenderer.Render(item, "text"); mailMessage.IsBodyHtml = true; foreach (var path in filePaths.Where(st=>!string.IsNullOrEmpty(st))) { mailMessage.Attachments.Add(new Attachment(path)); } Log("attempting to send message"); MainUtil.SendMail(mailMessage); Log("task finished"); }
/// <summary> /// /// </summary> /// <param name="items"></param> /// <param name="command"></param> /// <param name="schedule"></param> public void SetXmLsitemap(Item[] items, CommandItem command, ScheduleItem schedule) { if (ConfigurationHelper.IsAuthoringServer()) { try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); XmlElement rootNode = xmlDoc.CreateElement("urlset"); rootNode.SetAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(rootNode); //we will take only approved items / pages string databaseName = "web"; string startItemPath = ConfigurationHelper.GetSitecoreSetting("rootPath"); Database database = Factory.GetDatabase(databaseName); UrlOptions urlOptions = UrlOptions.DefaultOptions; urlOptions.AlwaysIncludeServerUrl = false; Item item = database.GetItem(startItemPath); AddUrlEntry(item, xmlDoc, rootNode, urlOptions); xmlDoc.Save(System.Web.Hosting.HostingEnvironment.MapPath("/sitemap.xml")); } catch (Exception ex) { Log.Error("Error at sitemap xml handler.", ex, this); } } }
protected override void ProcessItem(Item item) { ScheduleItem schedule = null; if (item != null) { if (!CheckItemTypeMatch(item)) { return; } schedule = new ScheduleItem(item); } if (Schedule != null) { schedule = Schedule; } if (schedule != null) { if (ShouldProcess(item.GetProviderPath(), "Start task defined in schedule")) { schedule.Execute(); WriteObject(schedule); } } }
protected override void ProcessRecord() { ScheduleItem schedule = null; if (Item != null) { schedule = new ScheduleItem(Item); } if (Schedule != null) { schedule = Schedule; } if (Path != null) { var curItem = PathUtilities.GetItem(Path, CurrentDrive, CurrentPath); schedule = new ScheduleItem(curItem); } if (schedule != null) { schedule.Execute(); } WriteObject(schedule); }
public void SendTasks(DietPlan dietPlan, Action<ResponseMessage, DietPlan> callback) { if (_connectionStore.IsConnectionEstablished) { TransferModelToTaskItem(dietPlan); var scheduleItems = new ScheduleItemCollection(); foreach (var taskItem in TodayTasks) { var scheduleItem = new ScheduleItem() { UserId = dietPlan.User.Id, ConnectionId = _connectionStore.ConnectionId, StartTime = taskItem.StartTime, Message = TransferTaskItemToXml(taskItem) }; scheduleItems.Add(scheduleItem); } AsychronousLoadHelper.AsychronousCall(() => { var scheduleService = new ScheduleService(); var response = scheduleService.AddSchedule(scheduleItems); callback(response, dietPlan); }); } }
public static void Main() { // roll your own ScheduleItem and add to schedule ScheduleItem manualAppt = new ScheduleItem(); manualAppt.Name = "SchedItem 1 - manually created schedule item (1 min, non-recurring)"; manualAppt.Recurring = false; manualAppt.ScheduledAt = DateTime.Now.Add(SecondsSpan(60)); // non-recurring, sheduled at (now + 3 min) manualAppt.OnScheduledAt = OnScheduledAt_1; mfSchedule.AddToSchedule(manualAppt); // create ScheduleItem object and add to schedule ScheduleItem createItemAndAppt = mfSchedule.AddToSchedule("SchedItem 2 - Created ScheduleItem and placed on schedule in one step (30 sec, recurs 30 sec)", true, new TimeSpan(0, 0, 30), // recur every 30 seconds DateTime.Now.Add(SecondsSpan(30)), // schedule at (now + 30 sec) OnScheduledAt_2, new TestState()); // create a new ScheduleItem by copying existing object ScheduleItem copiedAppt = manualAppt.Copy(); copiedAppt.Name = "SchedItem 3 - Copy created from SchedItem 1: " + manualAppt.Id.ToString() + " (1 min, non-recurring)"; copiedAppt.OnScheduledAt = OnScheduledAt_3; mfSchedule.AddToSchedule(copiedAppt); // create an ScheduleItem, copy it, then delete it, add copy to schedule (verify orginal (#4) is gone, copy (#5) remains ScheduleItem copyDeleteAppt = mfSchedule.AddToSchedule("SchedItem 4 - Create, copy and delete this appt", true, new TimeSpan(0, 0, 20), DateTime.Now.Add(SecondsSpan(20)), OnScheduledAt_4, null); // no state being passed ScheduleItem copiedAppt2 = copyDeleteAppt.Copy(); copiedAppt2.Name = "SchedItem 5 - Keeper copy of SchedItem 4 (20 sec, recurs 20 sec)"; copiedAppt2.OnScheduledAt = OnScheduledAt_5; mfSchedule.AddToSchedule(copiedAppt2); mfSchedule.DeleteFromSchedule(copyDeleteAppt); // view resulting schedule Debug.Print(""); Debug.Print(""); ArrayList mySchedule = mfSchedule.GetSchedule(); foreach (ScheduleItem item in mySchedule) { Debug.Print("Id=" + item.Id + " ScheduledAt=" + item.ScheduledAt.ToString() + " - Name=" + item.Name); } Debug.Print(""); Debug.Print(""); // test schedule execution Debug.Print("Done setting up, taking a loooong nap while waiting for scheduled items..."); while (true) { // waiting for schedule events Thread.Sleep(1000); } }
public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem) { var item = commandItem.InnerItem; if (item["active"] != "1") return; Log("Starting report email task"); MultilistField mf = item.Fields["reports"]; if (mf == null) return; var force = item["sendempty"] == "1"; var filePaths = mf.GetItems().Select(i => runReport(i, force)); MailMessage mailMessage; try { mailMessage = new MailMessage { From = new MailAddress(item["from"]), Subject = item["subject"], }; } catch (Exception ex) { LogException("FROM email address error."); return; } var senders = item["to"].Split(','); foreach (var sender in senders) { // test that each email address is valid. Continue to the next if it isn't. try { var toAddress = new MailAddress(sender); mailMessage.To.Add(toAddress); } catch (Exception) { LogException("TO email address error. " + sender); } } mailMessage.Body = Sitecore.Web.UI.WebControls.FieldRenderer.Render(item, "text"); mailMessage.IsBodyHtml = true; foreach (var path in filePaths.Where(st => !string.IsNullOrEmpty(st))) { mailMessage.Attachments.Add(new Attachment(path)); } Log("attempting to send message"); MainUtil.SendMail(mailMessage); Log("task report email finished"); }
public void Process(Item[] items, Sitecore.Tasks.CommandItem commandItem, ScheduleItem schedule) { CheckboxField active = commandItem.InnerItem.Fields["active"]; if (active.Checked) { //prepare email message string from = commandItem["from"]; string to = commandItem["to"]; string subject = commandItem["subject"]; MailMessage message = new MailMessage(from, to) { Subject = subject, }; //attach reports in excel format MultilistField reportReferences = commandItem.InnerItem.Fields["reports"]; foreach (Item item in reportReferences.GetItems()) { ReportItem reportItem = null; Report report = null; try { reportItem = Director.LoadObjectFromItem<ReportItem>(item); report = new Report(); foreach (var sItem in reportItem.Scanners) { report.AddScanner(sItem); } foreach (var vItem in reportItem.Viewers) { report.AddViewer(vItem); } foreach (var fItem in reportItem.Filters) { report.AddFilter(fItem); } report.Run(); //attach to mail message string tempPath = new ASR.Export.HtmlExport(report, reportItem).SaveFile("Automated report " + reportItem.Name, "xls"); Attachment newAttachment = new Attachment(tempPath); message.Attachments.Add(newAttachment); } catch (Exception ex) { message.Body += String.Format("An error occured while running '{0}'\n{1}\n\n", reportItem.Name, ex.ToString()); } } MainUtil.SendMail(message); } }
public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem) { //MultilistField mf = commandItem.InnerItem.Fields["reports"]; //if (mf != null) //{ // foreach (Item item in mf.GetItems()) // { // runReport(item); // } //} }
private void SetData(ScheduleItem scheduleItem) { if(scheduleItem != null) { _scheduleItem = scheduleItem; SetSlider(); SetTeamLogos(); SetTeamNames(); SetTeamRecords(); SetTeamBGs(); SetTeamButtons(); } }
public void NextSchedule(float _time) { nextScheduleItem = null; foreach(ScheduleItem _scheduleItem in scheduleItems){ if(_scheduleItem.day == -1 || _scheduleItem.day == TimeManager.master.currentDayReference){ if(_scheduleItem.time > _time && _scheduleItem.time < (nextScheduleItem!=null?nextScheduleItem.time:25f)){ nextScheduleItem = _scheduleItem; } } } }
public void SetData(ScheduleItem scheduleItem) { if(scheduleItem != null) { _scheduleItem = scheduleItem; SetTeamLogos(); SetTeamNameLabels(); SetDateLabel(); SetTimeLabel(); SetHomeAwayLabel(); SetWinLossLabel(); SetButton(); } }
public override void Execute(CommandContext context) { if (context.Items.Length == 1) { var item = context.Items[0]; var schedule = new ScheduleItem(item); Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBox.Execute( "Running scheduled command: " + item.Paths.Path, "Running scheduled command: " + item.Paths.Path, new Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBoxMethod(RunSchedule), new object[] { schedule }); } }
public virtual void UnlockIdleUserItems(Item[] items, CommandItem command, ScheduleItem schedule) { if (ElapsedTimeWhenIdle == TimeSpan.Zero) { return; } IEnumerable<Item> lockedItems = GetLockedItems(schedule.Database); foreach (Item lockedItem in lockedItems) { UnlockIfApplicable(lockedItem); } }
public object ScheduleToRunEveryTimeIntervalInMilliseconds( int interval, Action actionToExecute) { var item = new ScheduleItem { Action = actionToExecute, Interval = interval }; this.Items.Add(item); return item; }
public void Update(Item[] items, CommandItem command, ScheduleItem schedule) { using (var session = new ScriptSession(ApplicationNames.Default)) { foreach (Item item in items) { string script = item["Script"]; if (!String.IsNullOrEmpty(script)) { session.ExecuteScriptPart(script); } } } }
public void Update(Item[] items, CommandItem command, ScheduleItem schedule) { using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true)) { foreach (var item in items) { var script = item[ScriptItemFieldNames.Script]; if (!String.IsNullOrEmpty(script)) { session.SetExecutedScript(item); session.SetItemLocationContext(item); session.ExecuteScriptPart(script); } } } }
protected void FillTaskList() { XmlNodeList configNodes = Factory.GetConfigNodes("scheduling/agent"); if (configNodes != null) { int count = configNodes.Count; for (int i = 0; i <= (count - 1); i++) { XmlNode node = configNodes.Item(i); if (ShowNode(node)) { var item = new ListviewItem(); Context.ClientPage.AddControl(AgentTaskList, item); item.ID = Control.GetUniqueID("I"); item.Icon = ""; item.ColumnValues["Name"] = item.Header = item.Value = node.Attributes["type"] == null ? Translate.Text("No type is defined") : node.Attributes["type"].Value; item.ColumnValues["MethodName"] = node.Attributes["method"] == null ? Translate.Text("No method name is defined") : node.Attributes["method"].Value; item.ColumnValues["Interval"] = node.Attributes["interval"] == null ? Translate.Text("No interval is defined") : node.Attributes["interval"].Value; } } } string query = string.Format("/sitecore/*[@@id='{0}']//*[@@templateid='{1}']", ItemIDs.SystemRoot, TemplateIDs.Schedule); Item[] items = Context.ContentDatabase.SelectItems(query); if ((items != null) && items.Any()) { foreach (Item item2 in items) { var item3 = new ScheduleItem(item2); if (item3 != null) { var item = new ListviewItem(); Context.ClientPage.AddControl(ScheduledTaskList, item); item.ID = Control.GetUniqueID("I"); item.Icon = item3.Icon; item.ColumnValues["Name"] = item.Header = item3.DisplayName; item.ColumnValues["CommandName"] = (item3.CommandItem != null) ? item3.CommandItem.DisplayName : "No Command Item Defined"; item.ColumnValues["LastRun"] = item3.LastRun.ToString("MM/dd/yyyy HH:mm:ss"); item.Value = item3.ID.ToString(); } } } }
protected override void ProcessRecord() { if (Item != null) { ScheduleItem schedule = new ScheduleItem(Item); WriteObject(schedule); } else if (Path != null) { var curItem = PathUtilities.GetItem(Path, CurrentDrive, CurrentPath); ScheduleItem schedule = new ScheduleItem(curItem); WriteObject(schedule); } else { base.ProcessRecord(); } }
public void AddScheduleItem(int day, float time, Location location) { ScheduleItem _scheduleItem = new ScheduleItem(); _scheduleItem.day = day; _scheduleItem.time = time; _scheduleItem.location = location; scheduleItems.Add(_scheduleItem); if(day == -1 || TimeManager.master.currentDayReference == day){ if(TimeManager.master.time >= time){ if(nextScheduleItem == null){ nextScheduleItem = _scheduleItem; TimeManager.master.scheduleHeap.Add(this); } else if (nextScheduleItem.time >= time){ nextScheduleItem = _scheduleItem; TimeManager.master.scheduleHeap.Delete(fNode); TimeManager.master.scheduleHeap.Add(this); } } } }
/// <summary> /// Start point of the command /// </summary> /// <param name="items">Passed items</param> /// <param name="command">Passed command</param> /// <param name="schedule">Passed schedule item</param> public void Run(Item[] items, CommandItem command, ScheduleItem schedule) { Log.Info("Scheduled Publish: started", this); _scheduledPublishRepo = new ScheduledPublishRepo(); Stopwatch commandStopwatch = new Stopwatch(); commandStopwatch.Start(); //Publish all scheduled for the last hour DateTime publishToDate = DateTime.Now; DateTime publishFromDate = publishToDate.AddHours(-1); PublishSchedules(publishFromDate, publishToDate); //Alerts for failed schedules 2 hours ago DateTime alertToDate = publishFromDate.AddHours(-1).AddSeconds(-1); DateTime alertFromDate = publishFromDate.AddHours(-2); AlertForFailedSchedules(alertFromDate, alertToDate); _scheduledPublishRepo.CleanBucket(); commandStopwatch.Stop(); Log.Info("Scheduled Publish: Total Run " + commandStopwatch.ElapsedMilliseconds, this); }
public IEnumerable <File> GetFiles(ScheduleItem scheduleItem) { //TODO: (erikpo) Add caching return(repository.GetFiles(scheduleItem.ID)); }
private ScheduleItem CreateSchedule(int i) { var item = new ScheduleItem(); return(AdjustProperties(item, Content.Schedules)); }
private void ScheduleNextRun(ArrayList list, ScheduleItem item) { bool fAdded = false; for (int i = 0; i < list.Count; ++i) { if (((ScheduleItem)list[i]).RunAt > item.RunAt) { list.Insert(i, item); fAdded = true; break; } } if (!fAdded) list.Add(item); }
// PUT api/ScheduleItems/5 public async Task<IHttpActionResult> PutScheduleItem(int id, ScheduleItem venueScheduleLocation) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != venueScheduleLocation.ScheduleItemID) { return BadRequest(); } await repository.UpdateAsync(venueScheduleLocation, venueScheduleLocation.ScheduleItemID); return StatusCode(HttpStatusCode.NoContent); }
public ModelResult <File> EditFile(ScheduleItem scheduleItem, File fileToEdit, FileContentInput fileInput) { throw new System.NotImplementedException(); }
public void UpdateScheduleItem(ScheduleItem scheduleItem) { //no code in this implementation }
public JsonResult CreateSchedule(ScheduleModel model) { if (model.Items == null || model.Items.Count() <= 0) { return(Json(new { Status = Constant.RESPONSE_ERROR, Description = "At least one schedule item must be specified." })); } if (_dataContext.Schedules.Where(p => p.UserId == model.UserId && p.Decided == false && p.Deleted == false).Count() > 0) { return(Json(new { Status = Constant.RESPONSE_ERROR, Description = "There is already a schedule that is awaiting approval." })); } var userEntity = _dataContext.Users.Find(model.UserId); using (var transaction = _dataContext.Database.BeginTransaction()) { var schedule = new Schedule(); schedule.UserId = model.UserId; schedule.WeekType = "1 Week"; schedule.Notes = model.Notes; _dataContext.Schedules.Add(schedule); _dataContext.SaveChanges(); foreach (var item in model.Items) { ScheduleItem scheduleItem = new ScheduleItem(); scheduleItem.ScheduleId = schedule.ScheduleId; scheduleItem.CHGSiteId = item.CHGSiteId; scheduleItem.ContactId = item.ContactId; scheduleItem.Day = item.Day; scheduleItem.ReferralSourceId = item.ReferralSourceId; scheduleItem.Time = item.Time; scheduleItem.WeekNumber = 1; _dataContext.ScheduleItems.Add(scheduleItem); } _dataContext.SaveChanges(); Dictionary <string, string> values = null; List <User> users = null; List <long> CHGSiteIds = model.Items.Select(p => p.CHGSiteId).Distinct().ToList(); //Approval process. if (_dataContext.UserHasRole(_dataContext.UserId.Value, "CRO")) { _dataContext.ApproveSchedule(schedule.ScheduleId); _dataContext.SaveChanges(); foreach (var chgSiteId in CHGSiteIds) { values = new Dictionary <string, string>(); values.Add("TMP_SUBJECT", "CALL_CYCLE_APPROVAL_REQUEST_APPROVED_SUBJECT"); values.Add("TMP_BODY", "CALL_CYCLE_APPROVAL_REQUEST_APPROVED_BODY"); values.Add("LIASON_NAME", $"{userEntity.Contact.FirstName} {userEntity.Contact.LastName}"); values.Add("EMAIL_FROM_ADDRESS", ConfigurationManager.AppSettings["SupportEmail"]); values.Add("EMAIL_FROM_NAME", "CRA"); values.Add("DECISION_NOTES", ""); users = _dataContext.GetRoleUsersForCHGSite(chgSiteId, "CEO").Union(_dataContext.GetRoleUsersForCHGSite(chgSiteId, "DBD")).Union(_dataContext.GetRoleUsersForCHGSite(chgSiteId, "AVP")).Distinct().ToList(); if (users != null) { foreach (var user in users) { _dataContext.CreateEmailAlert(user.UserId, values); _dataContext.CreateNotification("Success", "Approved", $"Call cycle request for {userEntity.Contact.FirstName} {userEntity.Contact.LastName} approved.", user.UserId); } } } } else { foreach (var chgSiteId in CHGSiteIds) { string approvalLevel = ""; if (_dataContext.IsUserRoleForCHGSite(_dataContext.UserId.Value, chgSiteId, "CEO") || _dataContext.IsUserRoleForCHGSite(_dataContext.UserId.Value, chgSiteId, "DBD")) { //Start three layer. users = _dataContext.GetRoleUsersForCHGSite(chgSiteId, "AVP"); approvalLevel = "AVP"; } if (_dataContext.IsUserRoleForCHGSite(_dataContext.UserId.Value, chgSiteId, "AVP")) { //Start 2 layer. //Send approval task to CRO. users = _dataContext.GetRoleUsers("CRO"); approvalLevel = "CRO"; } if (users != null) { //Get the CRO and create the task, alert and email for it. foreach (var user in users) { //Create a new task for the user with the required parameters. var task = _dataContext.CreateTask("Call Cycle Approval", user.UserId, "Created", "Call Cycle Approval Request"); _dataContext.SaveChanges(); _dataContext.UpdateTaskParameter(task.UserTaskId, "APPROVAL_LEVEL", approvalLevel); _dataContext.UpdateTaskParameter(task.UserTaskId, "SCHEDULE_ID", schedule.ScheduleId.ToString()); _dataContext.UpdateTaskParameter(task.UserTaskId, "CHGSITE_ID", chgSiteId.ToString()); _dataContext.SaveChanges(); //Send task and alert. values = new Dictionary <string, string>(); values.Add("TMP_SUBJECT", "CALL_CYCLE_APPROVAL_REQUEST_CREATED_SUBJECT"); values.Add("TMP_BODY", "CALL_CYCLE_APPROVAL_REQUEST_CREATED_BODY"); values.Add("EMAIL_FROM_ADDRESS", ConfigurationManager.AppSettings["SupportEmail"]); values.Add("EMAIL_FROM_NAME", "CRA"); values.Add("LIASON_NAME", $"{userEntity.Contact.FirstName} {userEntity.Contact.LastName}"); values.Add("TASK_URL", ConfigurationManager.AppSettings["APP_URL"] + "/Task/Resolve/" + task.UserTaskId); _dataContext.CreateEmailAlert(user.UserId, values); _dataContext.CreateNotification("Info", "Request", $"New call cycle request for {userEntity.Contact.FirstName} {userEntity.Contact.LastName}.", user.UserId); _dataContext.SaveChanges(); } } } } _dataContext.SaveChanges(); transaction.Commit(); var pendingSchedule = _dataContext.Schedules.Where(p => p.ScheduleId == schedule.ScheduleId && p.Deleted == false && p.Decided == false).SingleOrDefault(); bool isPendingSchedule = false; if (pendingSchedule != null) { isPendingSchedule = true; } return(Json(new { Status = Constant.RESPONSE_OK, Description = "Schedule saved successfully.", ViewPending = isPendingSchedule, ScheduleId = schedule.ScheduleId })); } }
/// <remarks/> public System.IAsyncResult BegingetCommentsForScheduleItem(ScheduleItem scheduleItem, System.AsyncCallback callback, object asyncState) { return(this.BeginInvoke("getCommentsForScheduleItem", new object[] { scheduleItem }, callback, asyncState)); }
public void Config() { List <string> listTopics = new List <string>() { "5d247a04eff1030d7c5209a3" }; postFilter = new PostFilter() { LocationId = "5sd239asdd8fass7", Search = "ha noi", TimePeriod = "Tuan qua", Topics = listTopics }; ArticleDestinationItem articleDestinationItem = new ArticleDestinationItem() { Id = "5d33f09863c6060b5a8c519c", Name = "Đi du lịch Hạ Long" }; List <ArticleDestinationItem> listArticleDestinationItem = new List <ArticleDestinationItem>(); listArticleDestinationItem.Add(articleDestinationItem); List <string> estimatedCostItems = new List <string>(); ScheduleItem scheduleItem = new ScheduleItem() { Content = "Đi du lịch Hạ Long", Day = DateTime.Parse("11/08/2019"), Title = "Đi du lịch Hạ Long" }; List <ScheduleItem> listScheduleItems = new List <ScheduleItem>(); listScheduleItems.Add(scheduleItem); Author author = new Author() { Id = "5d15941f197c3400015db0aa", DisplayName = "PhongTV", ProfileImage = @"https://storage.googleapis.com/trip-sharing-final-image-bucket/image-201907131748509069-dy8beuyj1kfgwx98.png" }; companionPostJoinRequest = new CompanionPostJoinRequest() { Id = "5d15941f197c3400015db0aa", CompanionPostId = "5d15941f197c3400015db0aa", Date = DateTime.Parse("11/08/2019"), UserId = "", User = author }; List <CompanionPostJoinRequest> listcompanionPostJoinRequest = new List <CompanionPostJoinRequest>(); listcompanionPostJoinRequest.Add(companionPostJoinRequest); post = new Post() { Id = "5d07d847a2c5f845707dc69a", Content = "<p>Post Test</p>", AuthorId = "5d0b2b0b1c9d440000d8e9a1", CommentCount = 0, IsActive = true, IsPublic = true, LikeCount = 0, CoverImage = @"https://storage.googleapis.com/trip-sharing-final-image-bucket/image-201907131748509069-dy8beuyj1kfgwx98.png", PostType = "article", PubDate = DateTime.Now, liked = false, Title = "Post Test", }; estimatedCostItems.Add("Ăn,ngủ,nghỉ"); companionPost = new CompanionPost() { Id = "", EstimatedCost = 1000000, ExpiredDate = DateTime.Parse("10/08/2019"), MaxMembers = 10, MinMembers = 5, From = DateTime.Parse("10/08/2019"), To = DateTime.Parse("12/08/2019"), ConversationId = "5d0b2b0b1c9d440000d8e9ax", EstimatedCostItems = estimatedCostItems, ScheduleItems = listScheduleItems, Destinations = listArticleDestinationItem, PostId = "5d33f09763c6060b5a8c519b", Post = post, JoinRequests = listcompanionPostJoinRequest, Requested = true }; _mockICompanionPostRepository = new Mock <ICompanionPostRepository>(); }
private ScheduleItem BuildScheduleItem(TimeSpan eventTime, string eventName, Vector3 from, Vector3 to, int priority) { ScheduleItem newScheduleItem = new ScheduleItem(eventTime, eventName, from, to, priority); return(newScheduleItem); }
public ScheduleItemViewModel(ScheduleItem item) { _ScheduleItem = item; OnClickCommand = new RelayCommand(OnClick); }
public void ClearCurrentScheduleItem() { CurrentScheduleItem = null; }
public void Execute(Item[] items, CommandItem command, ScheduleItem schedule) { Sitecore.Diagnostics.Log.Info("Action Logger runs OK!", this); }
// The entry point of the agent public void Run(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem) { Logger.Info(string.Format("Started on {0}", DateTime.Now), this); // Association between users and items:key - user email, value - items to include in notification Dictionary <string, List <Item> > recipientItemsDictionary = new Dictionary <string, List <Item> >(); try { EmailUtility emailUtility = new EmailUtility(); var allWorkflows = WorkflowHelper.GetAllWorkflows(); foreach (var workflow in allWorkflows) { var worklowStates = WorkflowHelper.GetNonFinalStatesByTemplate(workflow, StateTemplateName); foreach (var state in worklowStates) { string timeFrameString = WorkflowHelper.GetStateFieldValue(state, TimeFiledName); if (string.IsNullOrEmpty(timeFrameString)) { Logger.Warn( string.Format("{0} field isn't specified for state {1}", TimeFiledName, state.DisplayName), this); continue; } TimeSpan timeFrame = DateUtil.ParseTimeSpan(timeFrameString, TimeSpan.Zero); if (timeFrame == TimeSpan.Zero) { Logger.Warn( string.Format("{0} field isn't well formatted for state {1}", TimeFiledName, state.DisplayName), this); continue; } Field recipientsField = WorkflowHelper.GetStateField(state, RecipientsFieldName); if (recipientsField == null || string.IsNullOrEmpty(recipientsField.Value)) { Logger.Warn( string.Format("{0} field isn't specified for state {1}", RecipientsFieldName, state.DisplayName), this); continue; } List <string> recepients = GetEmailsForUsersAndRoles(recipientsField); if (recepients.Count == 0) { Logger.Warn( string.Format("There's no users with valid email addresses to notify for state {0}", state.DisplayName), this); continue; } var itemsInState = WorkflowHelper.GetItemsInState(workflow, state.StateID); foreach (var item in itemsInState) { if (WorkflowHelper.IsTimeLimitExceeded(item, workflow, timeFrame)) { AddToResultSet(item, recipientItemsDictionary, recepients.ToArray()); } } } } ProcessResultSet(recipientItemsDictionary, emailUtility); } catch (Exception exc) { Logger.Error("Unspecified error ocurred", exc, this); } finally { Logger.Info("Stopped", this); } }
public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem) { var item = commandItem.InnerItem; if (item["active"] != "1") { return; } Log("Starting report email task"); MultilistField mf = item.Fields["reports"]; if (mf == null) { return; } var force = item["sendempty"] == "1"; var isHtmlExportType = item["Export Type"].ToLower() == "html"; var filePaths = mf.GetItems().Select(i => runReport(i, force, isHtmlExportType)); MailMessage mailMessage; try { mailMessage = new MailMessage { From = new MailAddress(item["from"]), Subject = setDate(item["subject"]), }; } catch (Exception) { LogException("FROM email address error." + item["from"]); return; } var senders = item["to"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var sender in senders) { // test that each email address is valid. Continue to the next if it isn't. try { var toAddress = new MailAddress(sender); mailMessage.To.Add(toAddress); } catch (Exception) { LogException("TO email address error. " + sender); } } string[] ccAddressList = item["cc"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (ccAddressList.Any()) { foreach (var ccAddress in ccAddressList) { try { // test that each email address is valid. Continue to the next if it isn't. MailAddress ccMailAddress = new MailAddress(ccAddress); mailMessage.CC.Add(ccMailAddress); } catch (Exception) { LogException("CC email address error. " + ccAddress); } } } string[] bccAddressList = item["bcc"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (bccAddressList.Any()) { foreach (var bccAddress in bccAddressList) { try { // test that each email address is valid. Continue to the next if it isn't. MailAddress bccMailAddress = new MailAddress(bccAddress); mailMessage.Bcc.Add(bccMailAddress); } catch (Exception) { LogException("BCC email address error. " + bccAddress); } } } mailMessage.Body = setDate(Sitecore.Web.UI.WebControls.FieldRenderer.Render(item, "text")); mailMessage.IsBodyHtml = true; foreach (var path in filePaths.Where(st => !string.IsNullOrEmpty(st))) { mailMessage.Attachments.Add(new Attachment(path)); } Log("attempting to send message"); MainUtil.SendMail(mailMessage); Log("task report email finished"); }
public void AddSchedule(ScheduleItem scheduleItem) { Schedules.Add(scheduleItem); }
///'''''''''''''''''''''''''''''''''''''''''''''''' //Add a queue request to Threadpool with a //callback to RunPooledThread which calls Run() ///'''''''''''''''''''''''''''''''''''''''''''''''' public void AddQueueUserWorkItem( ScheduleItem s ) { numberOfProcessesInQueue++; numberOfProcesses++; ScheduleHistoryItem obj = new ScheduleHistoryItem(); obj.TypeFullName = s.TypeFullName; obj.ScheduleID = s.ScheduleID; obj.TimeLapse = s.TimeLapse; obj.TimeLapseMeasurement = s.TimeLapseMeasurement; obj.RetryTimeLapse = s.RetryTimeLapse; obj.RetryTimeLapseMeasurement = s.RetryTimeLapseMeasurement; obj.ObjectDependencies = s.ObjectDependencies; obj.CatchUpEnabled = s.CatchUpEnabled; obj.Enabled = s.Enabled; obj.NextStart = s.NextStart; obj.ScheduleSource = s.ScheduleSource; obj.ThreadID = s.ThreadID; obj.ProcessGroup = s.ProcessGroup; obj.RetainHistoryNum = s.RetainHistoryNum; try { // Create a callback to subroutine RunPooledThread WaitCallback callback = new WaitCallback( RunPooledThread ); // And put in a request to ThreadPool to run the process. ThreadPool.QueueUserWorkItem( callback, ( (object)obj ) ); Thread.Sleep( 1000 ); } catch( Exception exc ) { Exceptions.Exceptions.ProcessSchedulerException( exc ); } }
/// <summary> /// Loads the schedules /// </summary> private void LoadDropdowns() { var scheduleEntityType = EntityTypeCache.Read(typeof(Schedule)); var currentSchedule = RockPage.GetCurrentContext(scheduleEntityType) as Schedule; var scheduleIdString = Request.QueryString["scheduleId"]; if (scheduleIdString != null) { var scheduleId = scheduleIdString.AsInteger(); if (currentSchedule == null || currentSchedule.Id != scheduleId) { currentSchedule = SetScheduleContext(scheduleId, false); } } if (currentSchedule != null) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("ScheduleName", currentSchedule.Name); lCurrentSelection.Text = GetAttributeValue("CurrentItemTemplate").ResolveMergeFields(mergeObjects); } else { lCurrentSelection.Text = GetAttributeValue("NoScheduleText"); } var schedules = new List <ScheduleItem>(); if (GetAttributeValue("ScheduleGroup") != null) { var selectedSchedule = GetAttributeValue("ScheduleGroup"); var selectedScheduleList = selectedSchedule.Split(',').AsGuidList(); schedules.AddRange(new ScheduleService(new RockContext()).Queryable() .Where(a => selectedScheduleList.Contains(a.Guid)) .Select(a => new ScheduleItem { Name = a.Name, Id = a.Id }) .OrderBy(s => s.Name) .ToList() ); } var formattedSchedule = new Dictionary <int, string>(); // run lava on each campus foreach (var schedule in schedules) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Clear(); mergeObjects.Add("ScheduleName", schedule.Name); schedule.Name = GetAttributeValue("DropdownItemTemplate").ResolveMergeFields(mergeObjects); } // check if the schedule can be unselected if (!string.IsNullOrEmpty(GetAttributeValue("ClearSelectionText"))) { var blankCampus = new ScheduleItem { Name = GetAttributeValue("ClearSelectionText"), Id = Rock.Constants.All.Id }; schedules.Insert(0, blankCampus); } rptSchedules.DataSource = schedules; rptSchedules.DataBind(); }
public override void UpdateSchedule( ScheduleItem objScheduleItem ) { Scheduler.CoreScheduler.RemoveFromScheduleQueue( objScheduleItem ); SchedulingController s = new SchedulingController(); s.UpdateSchedule( objScheduleItem.ScheduleID, objScheduleItem.TypeFullName, objScheduleItem.TimeLapse, objScheduleItem.TimeLapseMeasurement, objScheduleItem.RetryTimeLapse, objScheduleItem.RetryTimeLapseMeasurement, objScheduleItem.RetainHistoryNum, objScheduleItem.AttachToEvent, objScheduleItem.CatchUpEnabled, objScheduleItem.Enabled, objScheduleItem.ObjectDependencies, objScheduleItem.Servers ); ScheduleHistoryItem objScheduleHistoryItem = new ScheduleHistoryItem( objScheduleItem ); if( objScheduleHistoryItem.TimeLapse != Null.NullInteger && objScheduleHistoryItem.TimeLapseMeasurement != Null.NullString && objScheduleHistoryItem.Enabled ) { objScheduleHistoryItem.ScheduleSource = ScheduleSource.STARTED_FROM_SCHEDULE_CHANGE; Scheduler.CoreScheduler.AddToScheduleQueue( objScheduleHistoryItem ); } DataCache.RemoveCache( "ScheduleLastPolled" ); }
/// <summary> /// Load this Layout from its File /// </summary> /// <param name="scheduleItem"></param> public void loadFromFile(ScheduleItem scheduleItem) { // Store the Schedule and LayoutIds this.ScheduleItem = scheduleItem; this.ScheduleId = scheduleItem.scheduleid; this._layoutId = scheduleItem.id; this.isOverlay = scheduleItem.IsOverlay; this.isInterrupt = scheduleItem.IsInterrupt(); // Get this layouts XML XmlDocument layoutXml = new XmlDocument(); // try to open the layout file try { using (FileStream fs = File.Open(scheduleItem.layoutFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (XmlReader reader = XmlReader.Create(fs)) { layoutXml.Load(reader); reader.Close(); } fs.Close(); } } catch (IOException ioEx) { Trace.WriteLine(new LogMessage("MainForm - PrepareLayout", "IOException: " + ioEx.ToString()), LogType.Error.ToString()); throw; } layoutModifiedTime = File.GetLastWriteTime(scheduleItem.layoutFile); // Attributes of the main layout node XmlNode layoutNode = layoutXml.SelectSingleNode("/layout"); XmlAttributeCollection layoutAttributes = layoutNode.Attributes; // Set the background and size of the form _layoutWidth = int.Parse(layoutAttributes["width"].Value, CultureInfo.InvariantCulture); _layoutHeight = int.Parse(layoutAttributes["height"].Value, CultureInfo.InvariantCulture); // Are stats enabled for this Layout? isStatEnabled = (layoutAttributes["enableStat"] == null) ? true : (int.Parse(layoutAttributes["enableStat"].Value) == 1); // Scaling factor, will be applied to all regions _scaleFactor = Math.Min(Width / _layoutWidth, Height / _layoutHeight); // Want to be able to center this shiv - therefore work out which one of these is going to have left overs int backgroundWidth = (int)(_layoutWidth * _scaleFactor); int backgroundHeight = (int)(_layoutHeight * _scaleFactor); double leftOverX; double leftOverY; try { leftOverX = Math.Abs(Width - backgroundWidth); leftOverY = Math.Abs(Height - backgroundHeight); if (leftOverX != 0) { leftOverX = leftOverX / 2; } if (leftOverY != 0) { leftOverY = leftOverY / 2; } } catch { leftOverX = 0; leftOverY = 0; } // We know know what our Layout controls dimensions should be SetDimensions((int)leftOverX, (int)leftOverY, backgroundWidth, backgroundHeight); // New region and region options objects RegionOptions options = new RegionOptions(); options.PlayerWidth = (int)Width; options.PlayerHeight = (int)Height; options.LayoutModifiedDate = layoutModifiedTime; // Deal with the color // unless we are an overlay, in which case don't put up a background at all if (!isOverlay) { this.BackgroundColor = Brushes.Black; try { if (layoutAttributes["bgcolor"] != null && layoutAttributes["bgcolor"].Value != "") { var bc = new BrushConverter(); this.BackgroundColor = (Brush)bc.ConvertFrom(layoutAttributes["bgcolor"].Value); options.backgroundColor = layoutAttributes["bgcolor"].Value; } } catch { // Default black options.backgroundColor = "#000000"; } // Get the background try { if (layoutAttributes["background"] != null && !string.IsNullOrEmpty(layoutAttributes["background"].Value)) { string bgFilePath = ApplicationSettings.Default.LibraryPath + @"\backgrounds\" + backgroundWidth + "x" + backgroundHeight + "_" + layoutAttributes["background"].Value; // Create a correctly sized background image in the temp folder if (!File.Exists(bgFilePath)) { GenerateBackgroundImage(layoutAttributes["background"].Value, backgroundWidth, backgroundHeight, bgFilePath); } Background = new ImageBrush(new BitmapImage(new Uri(bgFilePath))); options.backgroundImage = @"/backgrounds/" + backgroundWidth + "x" + backgroundHeight + "_" + layoutAttributes["background"].Value; } else { // Assume there is no background image options.backgroundImage = ""; Background = this.BackgroundColor; } } catch (Exception ex) { Trace.WriteLine(new LogMessage("MainForm - PrepareLayout", "Unable to set background: " + ex.Message), LogType.Error.ToString()); // Assume there is no background image Background = this.BackgroundColor; options.backgroundImage = ""; } } // Get the regions XmlNodeList listRegions = layoutXml.SelectNodes("/layout/region"); XmlNodeList listMedia = layoutXml.SelectNodes("/layout/region/media"); // Check to see if there are any regions on this layout. if (listRegions.Count == 0 || listMedia.Count == 0) { Trace.WriteLine(new LogMessage("PrepareLayout", string.Format("A layout with {0} regions and {1} media has been detected.", listRegions.Count.ToString(), listMedia.Count.ToString())), LogType.Info.ToString()); if (Schedule.ActiveLayouts == 1) { Trace.WriteLine(new LogMessage("PrepareLayout", "Only 1 layout scheduled and it has nothing to show."), LogType.Info.ToString()); throw new Exception("Only 1 layout schduled and it has nothing to show"); } else { Trace.WriteLine(new LogMessage("PrepareLayout", string.Format(string.Format("An empty layout detected, will show for {0} seconds.", ApplicationSettings.Default.EmptyLayoutDuration.ToString()))), LogType.Info.ToString()); // Put a small dummy region in place, with a small dummy media node - which expires in 10 seconds. XmlDocument dummyXml = new XmlDocument(); dummyXml.LoadXml(string.Format("<region id='blah' width='1' height='1' top='1' left='1'><media id='blah' type='text' duration='{0}'><raw><text></text></raw></media></region>", ApplicationSettings.Default.EmptyLayoutDuration.ToString())); // Replace the list of regions (they mean nothing as they are empty) listRegions = dummyXml.SelectNodes("/region"); } } // Parse the regions foreach (XmlNode region in listRegions) { // Is there any media if (region.ChildNodes.Count == 0) { Debug.WriteLine("A region with no media detected"); continue; } // Region loop setting options.RegionLoop = false; XmlNode regionOptionsNode = region.SelectSingleNode("options"); if (regionOptionsNode != null) { foreach (XmlNode option in regionOptionsNode.ChildNodes) { if (option.Name == "loop" && option.InnerText == "1") { options.RegionLoop = true; } } } //each region XmlAttributeCollection nodeAttibutes = region.Attributes; options.scheduleId = ScheduleId; options.layoutId = _layoutId; options.regionId = nodeAttibutes["id"].Value.ToString(); options.width = (int)(Convert.ToDouble(nodeAttibutes["width"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.height = (int)(Convert.ToDouble(nodeAttibutes["height"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.left = (int)(Convert.ToDouble(nodeAttibutes["left"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.top = (int)(Convert.ToDouble(nodeAttibutes["top"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.scaleFactor = _scaleFactor; // Store the original width and original height for scaling options.originalWidth = (int)Convert.ToDouble(nodeAttibutes["width"].Value, CultureInfo.InvariantCulture); options.originalHeight = (int)Convert.ToDouble(nodeAttibutes["height"].Value, CultureInfo.InvariantCulture); // Set the backgrounds (used for Web content offsets) options.backgroundLeft = options.left * -1; options.backgroundTop = options.top * -1; // All the media nodes for this region / layout combination options.mediaNodes = region.SelectNodes("media"); Region temp = new Region(); temp.DurationElapsedEvent += new Region.DurationElapsedDelegate(Region_DurationElapsedEvent); temp.MediaExpiredEvent += Region_MediaExpiredEvent; // ZIndex if (nodeAttibutes["zindex"] != null) { temp.ZIndex = int.Parse(nodeAttibutes["zindex"].Value); } Debug.WriteLine("loadFromFile: Created new region", "Layout"); // Dont be fooled, this innocent little statement kicks everything off temp.loadFromOptions(options); // Add to our list of Regions _regions.Add(temp); Debug.WriteLine("loadFromFile: Adding region", "Layout"); } // Order all Regions by their ZIndex _regions.Sort((l, r) => l.ZIndex < r.ZIndex ? -1 : 1); // Add all Regions to the Scene foreach (Region temp in _regions) { // Add this Region to our Scene LayoutScene.Children.Add(temp); } // Null stuff listRegions = null; listMedia = null; }
private string BuildSchedule(string agentName, TimeSpan workStart, TimeSpan workEnd, bool needsGroceries, bool needsGas, bool wannaPlay) { string outputSked = agentName + "'s plan, Day: " + simTime.ToShortDateString() + ". "; if (!(simTime.DayOfWeek == DayOfWeek.Saturday || simTime.DayOfWeek == DayOfWeek.Sunday)) { TimeSpan breakfast = MathHelpers.FuzzyTime(workStart.Subtract(TimeSpan.FromHours(.75)), 13); //TimeSpan lunch = MathHelpers.FuzzyTime(workStart.Add(TimeSpan.FromHours(5)), 20); //TimeSpan dinner = MathHelpers.FuzzyTime(lunch.Add(TimeSpan.FromHours(5)), 25); //TimeSpan leaveHome = MathHelpers.FuzzyTime(workStart.Subtract(TimeSpan.FromMinutes(commute)), 4); TimeSpan leaveWork = MathHelpers.FuzzyTime(workEnd, 4); //TimeSpan breakfast = workStart; TimeSpan lunch = workStart; TimeSpan dinner = workStart; TimeSpan leaveHome = workStart; //TimeSpan leaveWork = workEnd; string breakfastString = (breakfast).ToString(); string leaveHomeString = (leaveHome).ToString(); string lunchString = (lunch).ToString(); string dinnerString = (dinner).ToString(); string leaveWorkString = (leaveWork).ToString(); if (homeNeedsGroceries) { leaveWorkString = leaveWorkString + " and get groceries"; } //build the sequence of events as a string outputSked = (outputSked + " Breakfast: " + breakfastString + "Leave for Work at:" + leaveHomeString + " Lunch: " + lunchString + " Dinner: " + dinnerString + " Leave work at:" + leaveWorkString); //clear the last day's schedule gameObject.GetComponent <ScheduleBuilder>().Refresh(); //build and populate the schedule items from recurring schedule items ScheduleItem hopper1 = BuildScheduleItem(leaveHome, "Leave Home", thisAgentData.homePlaceTransform.position, thisAgentData.workPlaceTransform.position, 1); gameObject.GetComponent <ScheduleBuilder>().AddIn(hopper1); if (!homeNeedsGroceries) { ScheduleItem hopper2 = BuildScheduleItem(leaveWork, "Leave Work to Home", thisAgentData.workPlaceTransform.position, thisAgentData.homePlaceTransform.position, 1); gameObject.GetComponent <ScheduleBuilder>().AddIn(hopper2); } else { //uses hard code location for grocery - need to change to data driven ScheduleItem hopper3 = BuildScheduleItem(leaveWork, "Leave Work to Grocery", thisAgentData.workPlaceTransform.position, new Vector3(8, 0, 7), 1); gameObject.GetComponent <ScheduleBuilder>().AddIn(hopper3); //uses hard code location for grocery - need to change to data driven //uses hard code time for grocery time duration - need to change to data driven ScheduleItem hopper4 = BuildScheduleItem(leaveWork.Add(TimeSpan.FromHours(.5f)), "Leave Groc to Home", new Vector3(8, 0, 7), thisAgentData.homePlaceTransform.position, 1); gameObject.GetComponent <ScheduleBuilder>().AddIn(hopper4); } } else { string partyPlan; int choice = MathHelpers.MakeAChoice(1, 4); switch (choice) { case 1: partyPlan = "beach"; break; case 2: partyPlan = "bar"; break; case 3: partyPlan = "houseparty"; break; default: partyPlan = "movies"; break; } outputSked = outputSked + partyPlan; } return(outputSked); }
public abstract bool AppliesTo(ScheduleItem item);
public void Execute(Item[] items, CommandItem commandItem, ScheduleItem schedule) { var scheduleTask = (ICommand)SimpleInjectorBootstrapper.Container.GetInstance(typeof(TCommand)); scheduleTask.Execute(items, commandItem, schedule); }
public abstract double Rate(ScheduleItem item);
private static void ProcessOnOffControlledSchedule(ScheduleItem currentScheduleItem, ZoneState zoneState) { zoneState.ScheduleState.DesiredTemperature = null; zoneState.ScheduleState.HeatingEnabled = currentScheduleItem != null; }
protected void StartScheduledAction(ScheduleItem item) { //StartAction(item.action); AddSubAction(item.action); }
public async Task <IActionResult> CreateConversation(string title, List <string> userNames, DateTime dateStarted, int?announcementID, List <int> scheduleItemsIDs, bool readOnly = false) { // Validation if (string.IsNullOrEmpty(title) || userNames == null || userNames.Count() == 0 || dateStarted == null || dateStarted.Date < DateTime.Today.AddDays(-1).Date || dateStarted.Date > DateTime.Today.AddDays(1).Date || title.Count() > IoCContainer.DbSettings.Value.MaxConversationTitleLength) { return(Json(null)); } List <User> conversationRelatedUsers = context.Users.Where(u => userNames.Contains(u.UserName)).ToList(); if (conversationRelatedUsers == null || conversationRelatedUsers.Count() == 0) { return(Json(null)); } Announcement announcement = null; if (announcementID != null) { announcement = await context.Announcements.Where(a => a.ID == announcementID).SingleOrDefaultAsync(); if (announcement == null) { return(Json(null)); } } List <ScheduleItem> scheduleItems = new List <ScheduleItem>(); if (scheduleItemsIDs.Count() != 0) { foreach (int scheduleItemID in scheduleItemsIDs) { ScheduleItem sh = await context.ScheduleItems.Where(s => s.ScheduleItemID == scheduleItemID).SingleOrDefaultAsync(); if (sh == null) { return(Json(null)); } scheduleItems.Add(sh); } } // Adding new conversation and its relations. Conversation addedConversation = new Conversation() { DateStarted = dateStarted, ReadOnly = readOnly, Title = title, Announcement = announcement }; await context.Conversations.AddAsync(addedConversation); List <UserToConversation> userToConversationRelations = new List <UserToConversation>(); foreach (User user in conversationRelatedUsers) { userToConversationRelations.Add(new UserToConversation() { Conversation = addedConversation, User = user, }); } await context.UserToConversations.AddRangeAsync(userToConversationRelations); List <ScheduleItemToConversation> scheduleItemToConversations = new List <ScheduleItemToConversation>(); foreach (ScheduleItem scheduleItem in scheduleItems) { scheduleItemToConversations.Add(new ScheduleItemToConversation() { Conversation = addedConversation, ScheduleItem = scheduleItem, }); } await context.ScheduleItemToConversations.AddRangeAsync(scheduleItemToConversations); int result = await context.SaveChangesAsync(); return(Json(addedConversation.ConversationID)); }
private static void AssertSchedule(ScheduleItem itemA, ScheduleItem itemB) { Assert.Equal(itemA.End, itemB.End); Assert.Equal(itemA.Start, itemB.Start); Assert.Equal(itemA.Location, itemB.Location); }
Task IJob.Execute(IJobExecutionContext context) { try { //get job parameters JobDataMap dataMap = context.JobDetail.JobDataMap; //get the datamap from the Quartz job var job = (SitecronJob)dataMap[SitecronConstants.ParamNames.SitecronJob]; //get the SitecronJob from the job definition if (job == null) { throw new Exception("Unable to load SiteCron Job Definition"); } string contextDbName = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronContextDB, "master"); Database contextDb = Factory.GetDatabase(contextDbName); Item jobItem = contextDb.GetItem(new ID(job.SitecoreScheduleJob)); if (jobItem == null) { throw new Exception("Unable to load Sitecore Schedule Job Item: " + job.SitecoreScheduleJob); } ScheduleItem scheduleItem = new ScheduleItem(jobItem); if (scheduleItem == null) { throw new Exception("Invalid Sitecore Job item specified: " + job.SitecoreJobType); } Type type = Type.GetType(scheduleItem.CommandItem.InnerItem[SitecronConstants.FieldNames.Type]); if (type == null) { throw new Exception("Unable to resolve the Sitecore Job Type specified: " + job.SitecoreJobType); } object instance = Activator.CreateInstance(type); if (instance == null) { throw new Exception("Unable to instantiate the Sitecore Job Type specified: " + job.SitecoreJobType); } DefaultJobOptions options = new DefaultJobOptions(job.SitecoreJobName, job.SitecoreJobCategory, job.SitecoreJobSiteName, instance, scheduleItem.CommandItem.InnerItem[SitecronConstants.FieldNames.Method], new object[] { scheduleItem.Items, scheduleItem.CommandItem, scheduleItem }); ThreadPriority jobPriority; if (Enum.TryParse <ThreadPriority>(job.SitecoreJobPriority, out jobPriority)) { options.Priority = jobPriority; } else { options.Priority = ThreadPriority.Normal; } JobManager.Start(options); context.JobDetail.JobDataMap.Put(SitecronConstants.ParamNames.SitecronJobLogData, "Sitecron: RunAsSitecoreJob: Done"); } catch (Exception ex) { Log.Error("SiteCron: SitecoreScheduleCommandJob: ERROR something went wrong - " + ex.Message, ex, this); context.JobDetail.JobDataMap.Put(SitecronConstants.ParamNames.SitecronJobLogData, "Sitecron: SitecoreScheduleCommandJob: ERROR something went wrong - " + ex.Message); } return(Task.FromResult <object>(null)); }
public async Task<IHttpActionResult> PostScheduleItem(ScheduleItem venueScheduleLocation) { if (!ModelState.IsValid) { return BadRequest(ModelState); } await repository.AddAsync(venueScheduleLocation); return CreatedAtRoute("DefaultApi", new { id = venueScheduleLocation.ScheduleItemID }, venueScheduleLocation); }
public File GetFile(ScheduleItem scheduleItem, FileAddress fileAddress) { //TODO: (erikpo) Add caching return(repository.GetFile(scheduleItem.ID, fileAddress.Url)); }
/// <summary> /// Loads the schedules /// </summary> private void LoadDropdowns() { var scheduleEntityType = EntityTypeCache.Read( typeof( Schedule ) ); var currentSchedule = RockPage.GetCurrentContext( scheduleEntityType ) as Schedule; var scheduleIdString = Request.QueryString["scheduleId"]; if ( scheduleIdString != null ) { var scheduleId = scheduleIdString.AsInteger(); if ( currentSchedule == null || currentSchedule.Id != scheduleId ) { currentSchedule = SetScheduleContext( scheduleId, false ); } } if ( currentSchedule != null ) { var mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "ScheduleName", currentSchedule.Name ); lCurrentSelection.Text = GetAttributeValue( "CurrentItemTemplate" ).ResolveMergeFields( mergeObjects ); } else { lCurrentSelection.Text = GetAttributeValue( "NoScheduleText" ); } var schedules = new List<ScheduleItem>(); if ( GetAttributeValue( "ScheduleGroup" ) != null ) { var selectedSchedule = GetAttributeValue( "ScheduleGroup" ); var selectedScheduleList = selectedSchedule.Split( ',' ).AsGuidList(); schedules.AddRange( new ScheduleService( new RockContext() ).Queryable() .Where( a => selectedScheduleList.Contains( a.Guid ) ) .Select( a => new ScheduleItem { Name = a.Name, Id = a.Id } ) .OrderBy( s => s.Name ) .ToList() ); } var formattedSchedule = new Dictionary<int, string>(); // run lava on each campus foreach ( var schedule in schedules ) { var mergeObjects = new Dictionary<string, object>(); mergeObjects.Clear(); mergeObjects.Add( "ScheduleName", schedule.Name ); schedule.Name = GetAttributeValue( "DropdownItemTemplate" ).ResolveMergeFields( mergeObjects ); } // check if the schedule can be unselected if ( !string.IsNullOrEmpty( GetAttributeValue( "ClearSelectionText" ) ) ) { var blankCampus = new ScheduleItem { Name = GetAttributeValue( "ClearSelectionText" ), Id = Rock.Constants.All.Id }; schedules.Insert( 0, blankCampus ); } rptSchedules.DataSource = schedules; rptSchedules.DataBind(); }
public void SendYesterdays(Item[] items, CommandItem command, ScheduleItem schedule) { new SendYesterday().Execute(CommandContext.Empty); }
public void RunSingleTask( ScheduleItem s ) { numberOfProcessesInQueue++; numberOfProcesses++; ScheduleHistoryItem obj = new ScheduleHistoryItem(); obj.TypeFullName = s.TypeFullName; obj.ScheduleID = s.ScheduleID; obj.TimeLapse = s.TimeLapse; obj.TimeLapseMeasurement = s.TimeLapseMeasurement; obj.RetryTimeLapse = s.RetryTimeLapse; obj.RetryTimeLapseMeasurement = s.RetryTimeLapseMeasurement; obj.ObjectDependencies = s.ObjectDependencies; obj.CatchUpEnabled = s.CatchUpEnabled; obj.Enabled = s.Enabled; obj.NextStart = s.NextStart; obj.ScheduleSource = s.ScheduleSource; obj.ThreadID = s.ThreadID; obj.ProcessGroup = s.ProcessGroup; try { Run( obj ); Thread.Sleep( 1000 ); } catch( Exception exc ) { Exceptions.Exceptions.ProcessSchedulerException( exc ); } }
/// <summary> /// Loads the schedules /// </summary> private void LoadScheduleDropdowns() { var scheduleEntityType = EntityTypeCache.Get(typeof(Schedule)); var currentSchedule = RockPage.GetCurrentContext(scheduleEntityType) as Schedule; var scheduleIdString = Request.QueryString["ScheduleId"]; if (scheduleIdString != null) { var scheduleId = scheduleIdString.AsInteger(); // if there is a query parameter, ensure that the Schedule Context cookie is set (and has an updated expiration) // note, the Schedule Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated currentSchedule = SetScheduleContext(scheduleId, false); } if (currentSchedule != null) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("ScheduleName", currentSchedule.Name); lCurrentScheduleSelection.Text = GetAttributeValue(AttributeKey.ScheduleCurrentItemTemplate).ResolveMergeFields(mergeObjects); _currentScheduleText = GetAttributeValue(AttributeKey.ScheduleCurrentItemTemplate).ResolveMergeFields(mergeObjects); } else { lCurrentScheduleSelection.Text = GetAttributeValue(AttributeKey.NoScheduleText); _currentScheduleText = GetAttributeValue(AttributeKey.NoScheduleText); } var schedules = new List <ScheduleItem>(); if (GetAttributeValue(AttributeKey.ScheduleGroup) != null) { var selectedSchedule = GetAttributeValue(AttributeKey.ScheduleGroup); var selectedScheduleList = selectedSchedule.Split(',').AsGuidList(); schedules.AddRange(new ScheduleService(new RockContext()).Queryable() .Where(a => selectedScheduleList.Contains(a.Guid)) .Select(a => new ScheduleItem { Name = a.Name, Id = a.Id }) .OrderBy(s => s.Name) .ToList() ); } var formattedSchedule = new Dictionary <int, string>(); // run lava on each campus foreach (var schedule in schedules) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Clear(); mergeObjects.Add("ScheduleName", schedule.Name); schedule.Name = GetAttributeValue(AttributeKey.ScheduleDropdownItemTemplate).ResolveMergeFields(mergeObjects); } // check if the schedule can be unselected if (!string.IsNullOrEmpty(GetAttributeValue(AttributeKey.ScheduleClearSelectionText))) { var blankCampus = new ScheduleItem { Name = GetAttributeValue(AttributeKey.ScheduleClearSelectionText), Id = Rock.Constants.All.Id }; schedules.Insert(0, blankCampus); } rptSchedules.DataSource = schedules; rptSchedules.DataBind(); }
public void Run(Item[] items, CommandItem command, ScheduleItem schedule) { lock (_sync) { if (_IsRunning) return; _IsRunning = true; this.CommandItem = command; } var disableIndexing = this.DisableIndexing && Sitecore.Configuration.Settings.Indexing.Enabled; try { // Get the root var root = this.RootItem; Assert.ArgumentNotNull(root, "RootItem"); if (disableIndexing) { Log.Info("Temporarily disable indexing...", this); Sitecore.Configuration.Settings.Indexing.Enabled = false; } Log.Info(string.Format("Start prune search from root item: {0}", root.Paths.Path), this); ProcessItemTree(root); } catch (Exception ex) { Log.Error("VersionPruner exception", ex, this); throw; } finally { _IsRunning = false; if (disableIndexing) { Sitecore.Diagnostics.Log.Info("Re-enabled indexing...", this); Sitecore.Configuration.Settings.Indexing.Enabled = true; } } }
public static void UpdateScheduleItem(ScheduleItem item) { var provider = SchedulingProvider.Instance(); provider.UpdateSchedule(item); }
public override void DeleteSchedule( ScheduleItem objScheduleItem ) { SchedulingController s = new SchedulingController(); s.DeleteSchedule( objScheduleItem.ScheduleID ); Scheduler.CoreScheduler.RemoveFromScheduleQueue( objScheduleItem ); DataCache.RemoveCache( "ScheduleLastPolled" ); }
public void Edit(ScheduleItem entity) { throw new NotImplementedException(); }