public void FluentTest1() { //Verify output. Should see one or two 10-second ticks, one or two 1,6 ticks, and one or two 2,7 ticks. var s = new Schedule() .AtSeconds(0, 10, 20, 30, 40, 50) .WithLocalTime() .Execute<TenSecTask>(); SchedulerRuntime.Start(s); Thread.Sleep(new TimeSpan(0, 0, 2)); SchedulerRuntime.AddSchedule(new Schedule().WithName("OneSix").AtSeconds(1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56).Execute<OneSixTask>()); Thread.Sleep(new TimeSpan(0, 0, 6)); SchedulerRuntime.UpdateSchedule(new Schedule().WithName("OneSix").AtSeconds(2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57).Execute<TwoSevenTask>()); Thread.Sleep(new TimeSpan(0, 0, 6)); SchedulerRuntime.Stop(); Console.WriteLine("Stopped"); Assert.IsTrue(TenSecTask.Ticked); Assert.IsTrue(OneSixTask.Ticked); Assert.IsTrue(TwoSevenTask.Ticked); }
public MinuteUnit(Schedule schedule, int duration) { this.Schedule = schedule; this.Duration = duration; this.Schedule.CalculateNextRun = x => x.AddMinutes(Duration); }
///<summary>Inserts one Schedule into the database. Provides option to use the existing priKey.</summary> internal static long Insert(Schedule schedule,bool useExistingPK) { if(!useExistingPK && PrefC.RandomKeys) { schedule.ScheduleNum=ReplicationServers.GetKey("schedule","ScheduleNum"); } string command="INSERT INTO schedule ("; if(useExistingPK || PrefC.RandomKeys) { command+="ScheduleNum,"; } command+="SchedDate,StartTime,StopTime,SchedType,ProvNum,BlockoutType,Note,Status,EmployeeNum) VALUES("; if(useExistingPK || PrefC.RandomKeys) { command+=POut.Long(schedule.ScheduleNum)+","; } command+= POut.Date (schedule.SchedDate)+"," + POut.Time (schedule.StartTime)+"," + POut.Time (schedule.StopTime)+"," + POut.Int ((int)schedule.SchedType)+"," + POut.Long (schedule.ProvNum)+"," + POut.Long (schedule.BlockoutType)+"," +"'"+POut.String(schedule.Note)+"'," + POut.Int ((int)schedule.Status)+"," + POut.Long (schedule.EmployeeNum)+")"; //DateTStamp can only be set by MySQL if(useExistingPK || PrefC.RandomKeys) { Db.NonQ(command); } else { schedule.ScheduleNum=Db.NonQ(command,true); } return schedule.ScheduleNum; }
///<summary>Inserts one Schedule into the database. Returns the new priKey.</summary> internal static long Insert(Schedule schedule) { if(DataConnection.DBtype==DatabaseType.Oracle) { schedule.ScheduleNum=DbHelper.GetNextOracleKey("schedule","ScheduleNum"); int loopcount=0; while(loopcount<100){ try { return Insert(schedule,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ schedule.ScheduleNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(schedule,false); } }
public void load_schedule(string f) { videoList = new VideoFile[1024]; for (int i = 0; i < 7; i++) { dailyList[i] = new DailyVideoFiles(); } Schedule s = new Schedule(); s = XMLReader.ReadSchedule(f); List<DailyVideoFiles> list = s.DailyVideoFilesList; list.CopyTo(dailyList, 0); foreach (DailyVideoFiles dailyFile in list) { //MessageBox.Show("how many days?" + dailyFile.VideoFileList.Count); foreach (VideoFile v in dailyFile.VideoFileList) { int index = v.Index; videoList[index] = v; } } get_diff(dailyList); }
public void MarkConflictingAppointmentsUponCreation() { var schedule = new Schedule(Guid.NewGuid(), testDateTimeRange, testClinicId, new List<Appointment>() { testAppointment1, testAppointment2 }); Assert.IsTrue(testAppointment1.IsPotentiallyConflicting); Assert.IsTrue(testAppointment2.IsPotentiallyConflicting); }
public FrmSelectStaff(Staff staff,Schedule schedule,int status) { InitializeComponent(); this.staff = staff; this.schedule = schedule; this.statusButton = status; }
public void CreateConflictCompilation(Schedule schedule, ConflictCriteria criteria) { switch (criteria) { case ConflictCriteria.All: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.SearchAllConflicts(schedule)); break; case ConflictCriteria.GreaterThanFourClassesPerDay: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.GreaterThanFourClassesPerDay(schedule)); break; case ConflictCriteria.CardsWithBlankFields: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.CardsWithBlankFields(schedule)); break; case ConflictCriteria.GroupsInDifferentClassrooms: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.GroupsInDifferentClassrooms(schedule)); break; case ConflictCriteria.LecturersInDifferentClassrooms: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.LecturersInDifferentClassrooms(schedule)); break; case ConflictCriteria.LecturersOnDifferentClasses: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.LecturersInDifferentClassrooms(schedule)); break; case ConflictCriteria.NextClassesAtDifferentAddress: Conflicts = new ObservableCollection<Conflict>(ConflictSearchEngine.NextClassesAtDifferentAddress(schedule)); break; } }
internal YearOnDayOfYearUnit(Schedule schedule, int duration, int dayOfYear) { _duration = duration; _dayOfYear = dayOfYear; Schedule = schedule; At(0, 0); }
public static void CopyValidEvents(Schedule schedule, ScheduleEventCollection eventList, string postfix) { if (eventList.Count == 0) return; ScheduleEventCollection newEventsList = new ScheduleEventCollection(); foreach (ScheduleEvent srcEvent in eventList) { StringBuilder sb = new StringBuilder(); sb.Append(DescriptionHeaderName); sb.AppendLine(Resources.CrossSyncDescription); if (!string.IsNullOrEmpty(srcEvent.Description)) { sb.AppendLine(); sb.Append(srcEvent.Description); } ScheduleEvent newEvent = new ScheduleEvent(); newEvent.EventType = srcEvent.IsBanner ? ScheduleEventType.Banner : ScheduleEventType.Normal; newEvent.PublicType = srcEvent.IsPublic ? SchedulePublicType.Public : SchedulePublicType.Private; newEvent.Start = srcEvent.Start; newEvent.End = srcEvent.End; newEvent.AllDay = srcEvent.AllDay; newEvent.StartOnly = srcEvent.StartOnly; newEvent.Plan = srcEvent.Plan; newEvent.Detail = srcEvent.Detail + postfix; newEvent.Description = sb.ToString(); newEvent.UserIds.Add(schedule.App.UserId); newEventsList.Add(newEvent); } if (newEventsList.Count == 0) return; schedule.AddEvents(newEventsList); }
public void Copy_Schedule() { // Arange int scheduleId = 1; string scheduleName = "ScheduleName1"; int pierId = 1; string pierName = "PierName1"; Pier pier = new Pier { Id = pierId, Name = pierName }; int routeId = 1; string routeCode = "RouteCode1"; string routeName = "RouteName1"; Route route = new Route { Id = routeId, Code = routeCode, Name = routeName }; TimeSpan time = new TimeSpan(0, 10, 0); Schedule oldSchedule = new Schedule { Id = scheduleId, Name = scheduleName, Pier = pier, Route = route, Time = time }; // Act Schedule newSchedule = oldSchedule.Copy(); // Assert Assert.AreNotSame(newSchedule, oldSchedule); // Not the same object // Check properties Assert.AreEqual(newSchedule.Id, scheduleId); Assert.AreEqual(newSchedule.Name, scheduleName); Assert.AreEqual(newSchedule.Route, route); Assert.AreEqual(newSchedule.Pier, pier); Assert.AreEqual(newSchedule.Time, time); }
public void VerifyParsingBadDatesToSchedule() { List<string> filenames = new List<string>(); filenames.Add("Tests\\Data\\GoodXML_malformedDate.xml"); var schedule = new Schedule(); var _emptyEvents = new ObservableCollection<Event>(); ObservableCollection<Event> Events = schedule.GetXMLEvents(true, filenames); //read from xap Assert.IsNotNull(Events); //events with malformed dates should be added to the schedule with a fake date Assert.AreNotEqual(_emptyEvents, Events); Assert.IsNotNull(Events, "event collection"); var enumerator = Events.GetEnumerator(); enumerator.MoveNext(); var firstEvent = enumerator.Current; Assert.IsNotNull(firstEvent, "first event in collection"); Assert.AreEqual("Panel", firstEvent.Kind); Assert.AreEqual("Datetime 08272011 110000", firstEvent.Name); Assert.IsNotNull(firstEvent.StartTime, "datetime"); Assert.AreEqual(TestValues.FriendlyTime, firstEvent.friendlyStartTime); Assert.AreEqual(false, firstEvent.Star); enumerator.MoveNext(); var secondEvent = enumerator.Current; Assert.IsNotNull(secondEvent, "first event in collection"); Assert.AreEqual("Panel", secondEvent.Kind); Assert.IsNotNull(secondEvent.StartTime, "datetime"); Assert.AreEqual(TestValues.FriendlyTime, secondEvent.friendlyStartTime); Assert.AreEqual("Datetime Friday 10 November", secondEvent.Name); Assert.AreEqual(false, secondEvent.Star); //check for little watson file in isolated storage? }
public const string DescriptionHeaderName = "# CrossSync: "; // Don't modify this. #endregion Fields #region Methods public static bool CanSync(out CybozuException ex) { ex = null; Properties.Settings settings = Properties.Settings.Default; if (!IsConfigured(settings)) return false; App firstApp, secondApp; Schedule firstSchedule, secondSchedule; try { firstApp = new App(settings.FirstUrl); firstApp.Auth(settings.FirstUsername, settings.FirstPassword); firstSchedule = new Schedule(firstApp); secondApp = new App(settings.SecondUrl); secondApp.Auth(settings.SecondUsername, settings.SecondPassword); secondSchedule = new Schedule(secondApp); } catch (CybozuException e) { // fail to auth ex = e; return false; } catch (Exception) { return false; } return true; }
private void DeleteEmptyScheduler(Schedule schedule) { if (schedule != null && schedule.ID != ID.Null.ToString()) { CalendarActions.DeleteScheduler(schedule); } }
public void Announce(Schedule schedule) { var timeboxes = _timeBoxRepository.GetTimeBoxesFrom(schedule.Campaign, schedule.Start, schedule.End); foreach (var timeBox in timeboxes) { foreach (var term in timeBox.TermSet) { var hrDate = term.GetLowestTerm().SaftyGetProperty<DateTime, IAssignment>(o => o.SaftyGetHrDate()); if (!hrDate.IsInTheRange(schedule)) continue; //backupTerm var backup = new BackupTerm(term.Id, timeBox.Agent.Id, term.Start, term.End, term.Text, term.Background, term.Level) { HrDate = hrDate }; if (term.ParentTerm != null) backup.ParentTermId = term.ParentTerm.Id; term.SaftyInvoke<AssignmentBase>(o => backup.WorkingTotals = o.WorkingTotals); _timeBoxRepository.SaveOrUpdate(backup); } } }
public FNode(Schedule _data, float _key) { right = this; left = this; data = _data; key = _key; }
internal MonthOnDayOfMonthUnit(Schedule schedule, int duration, int dayOfMonth) { _duration = duration; _dayOfMonth = dayOfMonth; Schedule = schedule; At(0, 0); }
public String ValidateSchedule(Schedule.Schedule schedule, Registration.Registration vehicle) { String information = ""; try { if (comboBoxCountry.SelectedItem.ToString() == Registration.Country.country_name.Ecuador.ToString()) { vehicle = new Registration.EcuadorRegistration(this.textBoxRegistration.Text); schedule = new Schedule.EcuadorSchedule(); DateTime dt = new DateTime(); dt = Convert.ToDateTime(dateTimePicker.Text); if (!(schedule as Schedule.EcuadorSchedule).EcuadorValidator(vehicle, dt)) information = "El vehículo con matrícula " + vehicle.Number + " no puede conducir en la ciudad de Quito entre las las 7:00 y las 9:30 en la mañana y entre las 16:00 y las 19:30 en la tarde y noche."; else information = "El vehículo con matrícula " + vehicle.Number + " puede conducir libremente en la ciudad de Quito en la fecha seleccionada."; } else information = "Información solo disponible para " + Registration.Country.country_name.Ecuador.ToString(); } catch (Exception exception) { information = exception.Message; } return information; }
public void AssignSchedule(Schedule schedule=null) { if (schedule == null) Schedule = NewSchedule(); else Schedule = schedule; }
public void UpdateSnapshots(Schedule schedule) { _snapshots.Clear(); pnLeftColumn.Controls.Clear(); pnRightColumn.Controls.Clear(); int columnIndex = 0; foreach (PrintProduct publication in schedule.PrintProducts) { if (publication.Inserts.Count > 0) { var snapshot = new PublicationSnapshotControl(publication); if (columnIndex == 0) { pnLeftColumn.Controls.Add(snapshot); snapshot.BringToFront(); columnIndex++; } else { pnRightColumn.Controls.Add(snapshot); snapshot.BringToFront(); columnIndex = 0; } _snapshots.Add(snapshot); } } UpdateColumns(schedule); }
public DateTime Day(DayOfWeek dayOfWeek, Schedule schedule) { switch (schedule) { case Schedule.Second: FindDate(dayOfWeek, _indexes[schedule]); break; case Schedule.Third: FindDate(dayOfWeek, _indexes[schedule]); break; case Schedule.Fourth: FindDate(dayOfWeek, _indexes[schedule]); break; case Schedule.Last: FindDate(dayOfWeek, _indexes[schedule]); break; case Schedule.Teenth: FindDate(dayOfWeek, _indexes[schedule]); break; case Schedule.First: FindDate(dayOfWeek, _indexes[schedule]); break; default: throw new ArgumentOutOfRangeException(nameof(schedule), schedule, null); } return _date; }
public void ClearAndReplace(NPC npc, Schedule newSchedule) { _schedulesToDo.Clear(); current = null; Add(new DefaultSchedule(npc)); Add(newSchedule); }
private Schedule ConfigureSchedulerSeedData() { var scheduleRepository = Container.Resolve<IRepository<Schedule>>(); var globalSchedule = scheduleRepository.CreateQuery().FirstOrDefault(x => x.Name == _globalScheduleName); if (globalSchedule == null) { globalSchedule = new Schedule { GlobalDefault = true, Name = _globalScheduleName, StartOnWeekends = false, StartCron = "* 8 * * 1-5", // 8 AM, Monday through Friday StopCron = "* 18 * * 1-5", // 6 PM, Monday through Friday }; scheduleRepository.Add(globalSchedule); } foreach (var schedule in GetAdditionalSchedules()) { var scopedSchedule = schedule; var existingSchedule = scheduleRepository.CreateQuery().FirstOrDefault(x => x.Name == scopedSchedule.Name); if (existingSchedule == null) { scheduleRepository.Add(scopedSchedule); } } return globalSchedule; }
internal void Add(Schedule schedule) { lock (_lock) { _schedules.Add(schedule); } }
internal bool Remove(Schedule schedule) { lock (_lock) { return _schedules.Remove(schedule); } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail( string itemKey, int itemKeyValue, int? parentCategoryId ) { pnlDetails.Visible = false; if ( itemKey != "ScheduleId" ) { return; } var scheduleService = new ScheduleService( new RockContext() ); Schedule schedule = null; if ( !itemKeyValue.Equals( 0 ) ) { schedule = scheduleService.Get( itemKeyValue ); } else { schedule = new Schedule { Id = 0, CategoryId = parentCategoryId }; } if ( schedule == null ) { return; } pnlDetails.Visible = true; hfScheduleId.Value = schedule.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Schedule.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( schedule ); } else { btnEdit.Visible = true; string errorMessage = string.Empty; btnDelete.Visible = scheduleService.CanDelete( schedule, out errorMessage ); if ( schedule.Id > 0 ) { ShowReadonlyDetails( schedule ); } else { ShowEditDetails( schedule ); } } }
public void SetUp() { defaultScheduler = new DefaultScheduler(bus); container.Register<IBus>(() => bus); container.Register<DefaultScheduler>(() => defaultScheduler); schedule = new Schedule(container); }
private void BuildAllStatistic(Schedule schedule) { BuildGroupStatistics(schedule); BuildLecturerStatistics(schedule); BuildSubjectStatistics(schedule); BuildClassroomStatistics(schedule); BuildClassTimeStatistics(schedule); }
protected override Schedule GetSchedule() { //Schedule schedule = new DefaultSchedule(this); //return (schedule); Schedule schedule = new Schedule(this, Schedule.priorityEnum.Low); schedule.Add(new TimeTask(120f, new AbstractAnimationState(this, currentIdlePose))); return (schedule); }
public Schedule createScheduleFromAgentsTxt() { var agents = JsonConvert.DeserializeObject<List<Agent>>(Resources.AgentsJson); var start = new DateTime(2014, 7, 28); var schedule = new Schedule(agents, start, start + new TimeSpan(28, 0, 0, 0)); schedule.FillUp(); return schedule; }
public CallableFixedRateBond(int settlementDays, double faceAmount, Schedule schedule, DoubleVector coupons, DayCounter accrualDayCounter, BusinessDayConvention paymentConvention, double redemption, Date issueDate, CallabilitySchedule putCallSchedule) : this(NQuantLibcPINVOKE.new_CallableFixedRateBond(settlementDays, faceAmount, Schedule.getCPtr(schedule), DoubleVector.getCPtr(coupons), DayCounter.getCPtr(accrualDayCounter), (int)paymentConvention, redemption, Date.getCPtr(issueDate), CallabilitySchedule.getCPtr(putCallSchedule)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public frmAddNewApprenticeshipAssessmentReport(CurriculumCourseEnrollment CurrentlySelectedCurriculumCourseEnrollment) { this.CurrentlySelectedCurriculumCourseEnrollment = CurrentlySelectedCurriculumCourseEnrollment; AssessmentReportList = new List <AssessmentReport>(); iCurrentPosition = 0; InitializeComponent(); /*Loadup the Selected Assesment * *****************************/ using (var Dbconnection = new MCDEntities()) { CurrentlySelectedAssessment = (from a in Dbconnection.Assessments where a.CurriculumCourseEnrollmentID == this.CurrentlySelectedCurriculumCourseEnrollment.CurriculumCourseEnrollmentID select a) .Include(a => a.AssessmentModules) .Include(a => a.AssessmentModules.Select(b => b.CurriculumCourseModule)) .Include(a => a.AssessmentModules.Select(b => b.CurriculumCourseModule.Module)) .Include(a => a.AssessmentModules.Select(b => b.AssessmentModuleActivities)) //.Include(a => a.AssessmentModules.Select(b => b.LookupPracticalAssessmentStatus.PracticalAssessmentStatus)) .FirstOrDefault <Assessment>(); if (CurrentlySelectedAssessment == null) { CurrentlySelectedAssessment = new Assessment(); Schedule CurrentConfiguredSchedule = (from a in Dbconnection.Schedules where a.CurriculumCourseEnrollmentID == this.CurrentlySelectedCurriculumCourseEnrollment.CurriculumCourseEnrollmentID select a).FirstOrDefault <Schedule>(); /*Set the start and end date controls on the first page. * ***************************************************/ CurrentlySelectedAssessment.AssessmentDateStarted = CurrentConfiguredSchedule.ScheduleStartDate.Date; CurrentlySelectedAssessment.AssessmentDateCompleted = CurrentConfiguredSchedule.ScheduleCompletionDate.Date; CurrentlySelectedAssessment.AssessmentDateSubmitted = DateTime.Now; CurrentlySelectedAssessment.CurriculumCourseEnrollmentID = this.CurrentlySelectedCurriculumCourseEnrollment.CurriculumCourseEnrollmentID; foreach (CurriculumCourseModule CCM in (from a in Dbconnection.CurriculumCourseModules where a.CurriculumCourseID == this.CurrentlySelectedCurriculumCourseEnrollment.CurriculumCourseID select a) .Include(a => a.Module) .ToList <CurriculumCourseModule>()) { CCM.ObjectState = Data.Models.Enum.EntityObjectState.Unchanged; // CCM.CurriculumCours.Course CurrentlySelectedAssessment.AssessmentModules.Add(new AssessmentModule() { CurriculumCourseModuleID = CCM.CurriculumCourseModuleID, PracticalAssessmentStatusID = (int)Common.Enum.EnumPracticalAssessmentStatuses.Not_Yet_Competent, TheoriticalAssessmentStatusID = (int)Common.Enum.EnumTheoriticalAssesmentStatuses.Not_Yet_Competent, Notes = "", AssessmentID = 0, CurriculumCourseModule = CCM }); } //foreach (AssessmentModule AM in CurrentlySelectedAssessment.AssessmentModules) //{ // Dbconnection.Entry(AM).Reference(a => a.LookupPracticalAssessmentStatus).Load(); // Dbconnection.Entry(AM).Reference(a => a.LookupTheoriticalAssesmentStatus).Load(); //} /*********************************************** * Load the Currently Loaded Course Name * *********************************************/ lblSelectedCourseName.Text = (from a in Dbconnection.CurriculumCourses where a.CurriculumCourseID == this.CurrentlySelectedCurriculumCourseEnrollment.CurriculumCourseID select a).FirstOrDefault <CurriculumCourse>().Course.CourseName; } }; /*END of Loading Assessment * ************************/ }
public void Run(int width, int height, CDFG graph, bool alreadyOptimized) { if (CanOptimizeCDFG(graph) && EnableOptimizations && !alreadyOptimized) { CDFG optimizedCDFG = new CDFG(); optimizedCDFG.StartDFG = OptimizeCDFG <T>(width, height, graph, KeepRunning.Token, EnableGarbageCollection); optimizedCDFG.AddNode(null, optimizedCDFG.StartDFG); graph = optimizedCDFG; } DFG <Block> runningGraph = graph.StartDFG; Stack <IControlBlock> controlStack = new Stack <IControlBlock>(); Stack <List <string> > scopedVariables = new Stack <List <string> >(); Rectangle[] oldRectangles = null; bool firstRun = true; Dictionary <string, List <IDropletSource> > sumOutputtedDropelts = new Dictionary <string, List <IDropletSource> >(); controlStack.Push(null); scopedVariables.Push(new List <string>()); Schedule scheduler = new Schedule(width, height); scheduler.SHOULD_DO_GARBAGE_COLLECTION = EnableGarbageCollection; List <StaticDeclarationBlock> staticModuleDeclarations = runningGraph.Nodes.Where(node => node.value is StaticDeclarationBlock) .Select(node => node.value as StaticDeclarationBlock) .ToList(); if (staticModuleDeclarations.Count > 0) { scheduler.PlaceStaticModules(staticModuleDeclarations); scopedVariables.Peek().AddRange(scheduler.NewVariablesCreatedInThisScope.Distinct()); } while (runningGraph != null) { int time = scheduler.ListScheduling(runningGraph, Executor); scopedVariables.Peek().AddRange(scheduler.NewVariablesCreatedInThisScope.Distinct().Where(x => !x.Contains("#@#Index"))); foreach (var item in scheduler.OutputtedDroplets) { if (sumOutputtedDropelts.ContainsKey(item.Key)) { sumOutputtedDropelts[item.Key].AddRange(item.Value); } else { sumOutputtedDropelts.Add(item.Key, item.Value); } } List <Command>[] commandTimeline = CreateCommandTimeline(scheduler.ScheduledOperations, time); if (firstRun) { bool[] usedElectrodes = GetusedElectrodes(width, height, commandTimeline, EnableSparseElectrodes); StartExecutor(graph.StartDFG, scheduler.StaticModules.Select(pair => pair.Value).ToList(), usedElectrodes); firstRun = false; } SendCommands(commandTimeline, ref oldRectangles, scheduler.rectanglesAtDifferentTimes); if (KeepRunning.IsCancellationRequested) { return; } runningGraph.Nodes.ForEach(x => x.value.Reset()); (runningGraph, _) = GetNextGraph(graph, runningGraph, Executor, scheduler.Variables, controlStack, scopedVariables, scheduler.FluidVariableLocations); } Executor.UpdateDropletData(sumOutputtedDropelts.Values.SelectMany(x => x.Select(y => y.GetFluidConcentrations())).ToList()); }
private void Schedule_MouseDown(object sender, MouseEventArgs e) { mySelectedScheduleNode = Schedule.GetNodeAt(e.X, e.Y); }
public void Increment() { LastRunTime = NextRunTime; NextRunTime = Schedule.GetNextOccurrence(NextRunTime); }
public Schedule InitializeScheduleForSection(Section section, ScheduleConfiguration scheduleConfiguration, IList <WeekDay> weekDays, AcademicSemester academicSemester) { var schedule = new Schedule(section, scheduleConfiguration, weekDays, academicSemester); foreach (var courseOffering in section.CourseOfferings) { var lecture = courseOffering.Course.Lecture; var tutor = courseOffering.Course.Tutor; var lab = courseOffering.Course.Lab; while (lecture > 0) { var randDay = Helper.GetRandomInteger(scheduleConfiguration.NumberOfDaysPerWeek); var lectureInstructor = GetInstructor(courseOffering, LECTURE_ID); var lectureRoom = GetRoom(courseOffering, LECTURE_ID); var scheduleEntry = CreateScheduleEntry(courseOffering.Course, lectureInstructor, lectureRoom, LECTURE_ID); if (lecture >= GeneticAlgorithmConf.MAX_CONSECUTIVE_LECTURE) { scheduleEntry.Duration = GeneticAlgorithmConf.MAX_CONSECUTIVE_LECTURE; lecture -= schedule.AddScheduleEntry(scheduleEntry, randDay); } else if (lecture > 0) { scheduleEntry.Duration = GeneticAlgorithmConf.MAX_CONSECUTIVE_LECTURE - 1; lecture -= schedule.AddScheduleEntry(scheduleEntry, randDay); } } while (tutor > 0) { var randDay = Helper.GetRandomInteger(scheduleConfiguration.NumberOfDaysPerWeek); var tutorInstructor = GetInstructor(courseOffering, TUTOR_ID); var tutorRoom = GetRoom(courseOffering, TUTOR_ID); var scheduleEntry = CreateScheduleEntry(courseOffering.Course, tutorInstructor, tutorRoom, TUTOR_ID, duration: 1); tutor -= schedule.AddScheduleEntry(scheduleEntry, randDay); } while (lab > 0) { var randDay = Helper.GetRandomInteger(scheduleConfiguration.NumberOfDaysPerWeek); var labInstructor = GetInstructor(courseOffering, LAB_ID); var labRoom = GetRoom(courseOffering, LAB_ID); var scheduleEntry = CreateScheduleEntry(courseOffering.Course, labInstructor, labRoom, LAB_ID); if (lab >= GeneticAlgorithmConf.MAX_CONSECUTIVE_LAB) { scheduleEntry.Duration = GeneticAlgorithmConf.MAX_CONSECUTIVE_LAB; lab -= schedule.AddScheduleEntry(scheduleEntry, randDay); } else if (lab >= (GeneticAlgorithmConf.MAX_CONSECUTIVE_LAB - 1)) { scheduleEntry.Duration = GeneticAlgorithmConf.MAX_CONSECUTIVE_LAB - 1; lab -= schedule.AddScheduleEntry(scheduleEntry, randDay); } } } return(schedule); }
public async Task <Schedule> Create(Schedule entity) { return(await _scheduleNonQueryDataService.Create(entity)); }
public async Task <Schedule> Update(int id, Schedule entity) { return(await _scheduleNonQueryDataService.Update(id, entity)); }
static void Main(string[] args) { try { DateTime timer = DateTime.Now; Option.Type type = Option.Type.Put; double underlying = 36.0; double spreadRate = 0.005; double dividendYield = 0.02; double riskFreeRate = 0.06; double volatility = 0.2; int settlementDays = 3; int length = 5; double redemption = 100.0; double conversionRatio = redemption / underlying; // at the money // set up dates/schedules Calendar calendar = new TARGET(); Date today = calendar.adjust(Date.Today); Settings.setEvaluationDate(today); Date settlementDate = calendar.advance(today, settlementDays, TimeUnit.Days); Date exerciseDate = calendar.advance(settlementDate, length, TimeUnit.Years); Date issueDate = calendar.advance(exerciseDate, -length, TimeUnit.Years); BusinessDayConvention convention = BusinessDayConvention.ModifiedFollowing; Frequency frequency = Frequency.Annual; Schedule schedule = new Schedule(issueDate, exerciseDate, new Period(frequency), calendar, convention, convention, DateGeneration.Rule.Backward, false); DividendSchedule dividends = new DividendSchedule(); CallabilitySchedule callability = new CallabilitySchedule(); List <double> coupons = new InitializedList <double>(1, 0.05); DayCounter bondDayCount = new Thirty360(); int[] callLength = { 2, 4 }; // Call dates, years 2,4. int[] putLength = { 3 }; // Put dates year 3. double[] callPrices = { 101.5, 100.85 }; double[] putPrices = { 105.0 }; // Load call schedules for (int i = 0; i < callLength.Length; i++) { SoftCallability s = new SoftCallability( new Callability.Price(callPrices[i], Callability.Price.Type.Clean), schedule.date(callLength[i]), 1.20); callability.Add(s); } for (int j = 0; j < putLength.Length; j++) { Callability s = new Callability(new Callability.Price(putPrices[j], Callability.Price.Type.Clean), Callability.Type.Put, schedule.date(putLength[j])); callability.Add(s); } // Assume dividends are paid every 6 months . for (Date d = today + new Period(6, TimeUnit.Months); d < exerciseDate; d += new Period(6, TimeUnit.Months)) { Dividend div = new FixedDividend(1.0, d); dividends.Add(div); } DayCounter dayCounter = new Actual365Fixed(); double maturity = dayCounter.yearFraction(settlementDate, exerciseDate); Console.WriteLine("option type = " + type); Console.WriteLine("Time to maturity = " + maturity); Console.WriteLine("Underlying price = " + underlying); Console.WriteLine("Risk-free interest rate = {0:0.0%}", riskFreeRate); Console.WriteLine("Dividend yield = {0:0.0%}%", dividendYield); Console.WriteLine("Volatility = {0:0.0%}%", volatility); Console.WriteLine(""); // write column headings int[] widths = { 35, 14, 14 }; int totalWidth = widths[0] + widths[1] + widths[2]; string rule = new string('-', totalWidth); string dblrule = new string('=', totalWidth); Console.WriteLine(dblrule); Console.WriteLine("Tsiveriotis-Fernandes method"); Console.WriteLine(dblrule); Console.WriteLine("Tree Type European American "); Console.WriteLine(rule); Exercise exercise = new EuropeanExercise(exerciseDate); Exercise amexercise = new AmericanExercise(settlementDate, exerciseDate); Handle <Quote> underlyingH = new Handle <Quote>(new SimpleQuote(underlying)); Handle <YieldTermStructure> flatTermStructure = new Handle <YieldTermStructure>(new FlatForward(settlementDate, riskFreeRate, dayCounter)); Handle <YieldTermStructure> flatDividendTS = new Handle <YieldTermStructure>(new FlatForward(settlementDate, dividendYield, dayCounter)); Handle <BlackVolTermStructure> flatVolTS = new Handle <BlackVolTermStructure>(new BlackConstantVol(settlementDate, calendar, volatility, dayCounter)); BlackScholesMertonProcess stochasticProcess = new BlackScholesMertonProcess(underlyingH, flatDividendTS, flatTermStructure, flatVolTS); int timeSteps = 801; Handle <Quote> creditSpread = new Handle <Quote>(new SimpleQuote(spreadRate)); Quote rate = new SimpleQuote(riskFreeRate); Handle <YieldTermStructure> discountCurve = new Handle <YieldTermStructure>(new FlatForward(today, new Handle <Quote>(rate), dayCounter)); IPricingEngine engine = new BinomialConvertibleEngine <JarrowRudd>(stochasticProcess, timeSteps); ConvertibleFixedCouponBond europeanBond = new ConvertibleFixedCouponBond(exercise, conversionRatio, dividends, callability, creditSpread, issueDate, settlementDays, coupons, bondDayCount, schedule, redemption); europeanBond.setPricingEngine(engine); ConvertibleFixedCouponBond americanBond = new ConvertibleFixedCouponBond(amexercise, conversionRatio, dividends, callability, creditSpread, issueDate, settlementDays, coupons, bondDayCount, schedule, redemption); americanBond.setPricingEngine(engine); Console.WriteLine("Jarrow-Rudd {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <CoxRossRubinstein>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <CoxRossRubinstein>(stochasticProcess, timeSteps)); Console.WriteLine("CoxRossRubinstein {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <AdditiveEQPBinomialTree>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <AdditiveEQPBinomialTree>(stochasticProcess, timeSteps)); Console.WriteLine("AdditiveEQPBinomialTree {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <Trigeorgis>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <Trigeorgis>(stochasticProcess, timeSteps)); Console.WriteLine("Trigeorgis {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <Tian>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <Tian>(stochasticProcess, timeSteps)); Console.WriteLine("Tian {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <LeisenReimer>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <LeisenReimer>(stochasticProcess, timeSteps)); Console.WriteLine("LeisenReimer {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); americanBond.setPricingEngine(new BinomialConvertibleEngine <Joshi4>(stochasticProcess, timeSteps)); europeanBond.setPricingEngine(new BinomialConvertibleEngine <Joshi4>(stochasticProcess, timeSteps)); Console.WriteLine("Joshi4 {0:0.000000} {1:0.000000}", europeanBond.NPV(), americanBond.NPV()); Console.WriteLine("==========================================================================="); Console.WriteLine(" \nRun completed in {0}", DateTime.Now - timer); Console.WriteLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Write("Press any key to continue ..."); Console.ReadKey(); }
public void Create(Schedule schedule) { Specs.AggregateIsNew.ThrowDomainErrorIfNotStatisfied(this); Emit(new VoyageCreatedEvent(schedule)); }
public static DFG <Block> OptimizeCDFG <T>(int width, int height, CDFG graph, CancellationToken keepRunning, bool useGC) { DFG <Block> runningGraph = graph.StartDFG; Stack <IControlBlock> controlStack = new Stack <IControlBlock>(); Stack <List <string> > scopedVariables = new Stack <List <string> >(); controlStack.Push(null); scopedVariables.Push(new List <string>()); DFG <Block> bigDFG = new DFG <Block>(); Dictionary <string, string> renamer = new Dictionary <string, string>(); Dictionary <string, string> variablePostfixes = new Dictionary <string, string>(); Schedule scheduler = new Schedule(width, height); scheduler.SHOULD_DO_GARBAGE_COLLECTION = useGC; List <StaticDeclarationBlock> staticModuleDeclarations = runningGraph.Nodes.Where(node => node.value is StaticDeclarationBlock) .Select(node => node.value as StaticDeclarationBlock) .ToList(); if (staticModuleDeclarations.Count > 0) { scheduler.PlaceStaticModules(staticModuleDeclarations); scopedVariables.Peek().AddRange(scheduler.NewVariablesCreatedInThisScope.Distinct()); } int nameID = 0; while (runningGraph != null) { int time = scheduler.ListScheduling <T>(runningGraph, null); scopedVariables.Peek().AddRange(scheduler.NewVariablesCreatedInThisScope.Distinct().Where(x => !x.Contains("#@#Index"))); runningGraph.Nodes.ForEach(x => x.value.IsDone = false); Assay fisk = new Assay(runningGraph); foreach (Block toCopy in fisk) { if (toCopy is FluidBlock fluidBlockToCopy) { if (!variablePostfixes.ContainsKey(toCopy.OutputVariable)) { variablePostfixes.Add(toCopy.OutputVariable, $"##{nameID++}"); } Block copy = fluidBlockToCopy.CopyBlock(bigDFG, renamer, variablePostfixes[toCopy.OutputVariable]); bigDFG.AddNode(copy); } fisk.UpdateReadyOperations(toCopy); } runningGraph.Nodes.ForEach(x => x.value.Reset()); var dropPositionsCopy = scheduler.FluidVariableLocations.ToDictionary(); List <string> variablesOutOfScope; (runningGraph, variablesOutOfScope) = GetNextGraph(graph, runningGraph, null, scheduler.Variables, controlStack, scopedVariables, scheduler.FluidVariableLocations); if (useGC) { AddWasteBlocks(variablesOutOfScope, bigDFG, renamer, dropPositionsCopy, staticModuleDeclarations); } foreach (var item in variablesOutOfScope) { renamer.Remove(item); variablePostfixes.Remove(item); } if (keepRunning.IsCancellationRequested) { return(null); } } if (useGC) { AddWasteBlocks(scopedVariables.Pop(), bigDFG, renamer, scheduler.FluidVariableLocations, staticModuleDeclarations); } bigDFG.FinishDFG(); return(bigDFG); }
public ActionResult Edit([Bind(Include = "id,GameDate,Leagueid,Cancelled,rowversion")] Schedule schedule) { try { if (ModelState.IsValid) { if (db.Schedules.Any(x => x.GameDate == schedule.GameDate && x.id != schedule.id)) { ModelState.AddModelError(string.Empty, "Duplicate date is not allowed"); } else { db.Entry(schedule).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", new { id = schedule.Leagueid })); } } } catch (DbUpdateConcurrencyException ex) { var entry = ex.Entries.Single(); var clientValues = (Schedule)entry.Entity; var databaseEntry = entry.GetDatabaseValues(); if (databaseEntry == null) { ModelState.AddModelError(string.Empty, "Unable to save changes. The schedule record was deleted by another user."); } else { var databaseValues = (Schedule)databaseEntry.ToObject(); if (databaseValues.WeekDate != clientValues.WeekDate) { ModelState.AddModelError("Game Date", "Current value: " + databaseValues.GameDate.ToShortDateString()); } if (databaseValues.Cancelled != clientValues.Cancelled) { ModelState.AddModelError("Cancelled", "Current value: " + databaseValues.Cancelled); } if (databaseValues.Leagueid != clientValues.Leagueid) { ModelState.AddModelError("League", "Current value: " + databaseValues.Leagueid); } ModelState.AddModelError(string.Empty, "The record you attempted to edit " + "was modified by another user after you got the original value. The " + "edit operation was canceled and the current values in the database " + "have been displayed. If you still want to edit this record, click " + "the Save button again. Otherwise click the Back to List hyperlink."); schedule.rowversion = databaseValues.rowversion; } } catch (Exception dex) { while (dex.InnerException != null) { dex = dex.InnerException; } //Log the error (uncomment dex variable name and add a line here to write a log.) ModelState.AddModelError("", $"Unable to save changes. {dex.Message}"); ErrorSignal.FromCurrentContext().Raise(dex); } ViewBag.Schedule = db.Schedules.Where(x => x.Leagueid == schedule.Leagueid).OrderBy(x => x.GameDate); return(View(schedule)); }
public async Task EditSchedule(Schedule schedule) { await this.EditSchedule(SCHEDULE_NAMESPACE, schedule); }
public int UpdateSchedule(Schedule model) { this._scheduleRepository.Update(model); return(this._scheduleRepository.SaveChanges()); }
public async Task AddSchedule(Schedule schedule) { await this.AddSchedule(SCHEDULE_NAMESPACE, schedule); }
public int SaveSchedule(Schedule model) { this._scheduleRepository.Add(model); return(this._scheduleRepository.SaveChanges()); }
private Schedule CreateSchedule(DateTime date) { Schedule schedule = new Schedule(); DateTime monday = date.AddDays(-(int)date.DayOfWeek); schedule.Start = monday; schedule.End = monday.AddDays(6); int year; int month; int day; for (int i = 0; i < 6; i++) { monday = monday.AddDays(1); year = monday.Year; month = monday.Month; day = monday.Day; List <Slot> slots = new List <Slot> { new Slot(new DateTime(year, month, day).AddHours(8).AddMinutes(30), new DateTime(year, month, day).AddHours(9).AddMinutes(15), true), new Slot(new DateTime(year, month, day).AddHours(9).AddMinutes(30), new DateTime(year, month, day).AddHours(10).AddMinutes(15), false), new Slot(new DateTime(year, month, day).AddHours(10).AddMinutes(45), new DateTime(year, month, day).AddHours(11).AddMinutes(30), true), new Slot(new DateTime(year, month, day).AddHours(11).AddMinutes(45), new DateTime(year, month, day).AddHours(12).AddMinutes(30), false), new Slot(new DateTime(year, month, day).AddHours(13).AddMinutes(30), new DateTime(year, month, day).AddHours(14).AddMinutes(15), true), new Slot(new DateTime(year, month, day).AddHours(14).AddMinutes(30), new DateTime(year, month, day).AddHours(15).AddMinutes(15), true), new Slot(new DateTime(year, month, day).AddHours(15).AddMinutes(30), new DateTime(year, month, day).AddHours(16).AddMinutes(15), true), new Slot(new DateTime(year, month, day).AddHours(16).AddMinutes(30), new DateTime(year, month, day).AddHours(17).AddMinutes(15), false), new Slot(new DateTime(year, month, day).AddHours(19), new DateTime(year, month, day).AddHours(19).AddMinutes(45), false) }; slots.ForEach(s => { db.Slots.Add(s); }); db.SaveChanges(); switch (i) { case 0: schedule.Monday = slots; break; case 1: schedule.Tuesday = slots; break; case 2: schedule.Wednesday = slots; break; case 3: schedule.Thursday = slots; break; case 4: schedule.Friday = slots; break; case 5: schedule.Saturday = slots; break; } } db.Schedules.Add(schedule); db.SaveChanges(); return(schedule); }
private static Dictionary <Point, string[]> GenerateTimeTable(Schedule solution, Dictionary <Point, int[]> slotTable) { int numberOfRooms = solution.Configuration.NumberOfRooms; int daySize = Constant.DAY_HOURS * numberOfRooms; int ci = 0; var classes = solution.Classes; var timeTable = new Dictionary <Point, string[]>(); foreach (var cc in classes.Keys) { // coordinate of time-space slot var reservation = classes[cc]; int day = reservation.Day + 1; int time = reservation.Time + 1; int room = reservation.Room; var key = new Point(time, room); var roomDuration = slotTable.ContainsKey(key) ? slotTable[key] : null; if (roomDuration == null) { roomDuration = new int[ROOM_COLUMN_NUMBER]; slotTable[key] = roomDuration; } roomDuration[day] = cc.Duration; for (int m = 1; m < cc.Duration; ++m) { var nextRow = new Point(time + m, room); if (!slotTable.ContainsKey(nextRow)) { slotTable.Add(nextRow, new int[ROOM_COLUMN_NUMBER]); } if (slotTable[nextRow][day] < 1) { slotTable[nextRow][day] = -1; } } var roomSchedule = timeTable.ContainsKey(key) ? timeTable[key] : null; var sb = new StringBuilder(); if (roomSchedule == null) { roomSchedule = new string[ROOM_COLUMN_NUMBER]; timeTable[key] = roomSchedule; } sb.Append(cc.Course.Name).Append("<br />").Append(cc.Professor.Name).Append("<br />"); sb.Append(string.Join("/", cc.Groups.Select(grp => grp.Name).ToArray())); sb.Append("<br />"); if (cc.LabRequired) { sb.Append("Lab<br />"); } for (int i = 0; i < CRITERIAS.Length; ++i) { sb.Append("<span style='color:"); if (solution.Criteria[ci + i]) { sb.Append(COLOR1).Append("' title='"); sb.Append(string.Format(CRITERIAS_DESCR[i], (i == 1 || i == 2) ? "" : "no ")); } else { sb.Append(COLOR2).Append("' title='"); sb.Append(string.Format(CRITERIAS_DESCR[i], (i == 1 || i == 2) ? "not " : "")); } sb.Append("'> ").Append(CRITERIAS[i]); sb.Append(" </span>"); } roomSchedule[day] = sb.ToString(); ci += CRITERIAS.Length; } return(timeTable); }
private void ReadEffectiveWeeklySchedule() { Schedule.BeginUpdate(); Schedule.Nodes.Clear(); byte[] InOutBuffer = null; try { if (comm.RawEncodedDecodedPropertyConfirmedRequest(adr, schedule_id, BacnetPropertyIds.PROP_WEEKLY_SCHEDULE, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, ref InOutBuffer)) { int offset = 0; byte tag_number; uint len_value_type; // Tag 3 offset += ASN1.decode_tag_number(InOutBuffer, offset, out tag_number); if (tag_number != 3) { return; } for (int i = 1; i < 8; i++) { TreeNode tday = null; tday = new TreeNode("[" + (i - 1).ToString() + "] : " + System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.DayNames[i % 7], 0, 0); Schedule.Nodes.Add(tday); // Tag 0 offset += ASN1.decode_tag_number(InOutBuffer, offset, out tag_number); while (!ASN1.IS_CLOSING_TAG(InOutBuffer[offset])) { BacnetValue value; String s; // Time offset += ASN1.decode_tag_number_and_value(InOutBuffer, offset, out tag_number, out len_value_type); offset += ASN1.bacapp_decode_data(InOutBuffer, offset, InOutBuffer.Length, (BacnetApplicationTags)tag_number, len_value_type, out value); DateTime dt = (DateTime)value.Value; // Value offset += ASN1.decode_tag_number_and_value(InOutBuffer, offset, out tag_number, out len_value_type); offset += ASN1.bacapp_decode_data(InOutBuffer, offset, InOutBuffer.Length, (BacnetApplicationTags)tag_number, len_value_type, out value); if (value.Tag != BacnetApplicationTags.BACNET_APPLICATION_TAG_NULL) { s = dt.ToString("T") + " = " + Property.SerializeValue(value, value.Tag); // Second value is the ... value (Bool, Int, Uint, Float, double or null) ScheduleType = value.Tag; // all type must be the same for a valid schedule (maybe, not sure !), so remember it } else { s = dt.ToString("T") + " = null"; } tday.Nodes.Add(new TreeNode(s, 1, 1)); } offset++; } offset += ASN1.decode_tag_number(InOutBuffer, offset, out tag_number); if (tag_number != 3) { Schedule.Nodes.Clear(); } } } catch { } finally { Schedule.EndUpdate(); Schedule.Sort(); // Time entries are not necesserary sorted, so do it (that's also why days are assign to [0], .. [6]) Schedule.ExpandAll(); Schedule.LabelEdit = true; } }
private void BindReminders() { Mediachase.IBN.Business.ToDo.ToDoSecurity sec = Mediachase.IBN.Business.ToDo.GetSecurity(ToDoID); bool IsMember = sec.IsManager || sec.IsResource || sec.IsCreator; if (IsMember && TargetStartDate > DateTime.UtcNow) { int Lag = -1; bool IsActive = false; using (IDataReader reader = Schedule.GetReminderSubscriptionPersonalForObject(DateTypes.Todo_StartDate, ToDoID)) { if (reader.Read()) { Lag = (int)reader["Lag"]; IsActive = (bool)reader["IsActive"]; } } if (IsActive) { imgReminderStart.ToolTip = String.Format("{0}: {1}", LocRM2.GetString("Start"), CommonHelper.GetIntervalString(Lag)); } else { imgReminderStart.ToolTip = CommonHelper.GetIntervalString(-1); if (imgReminderStart.ToolTip.StartsWith("[")) { imgReminderStart.ToolTip = imgReminderStart.ToolTip.Substring(1); } if (imgReminderStart.ToolTip.EndsWith("]")) { imgReminderStart.ToolTip = imgReminderStart.ToolTip.Substring(0, imgReminderStart.ToolTip.Length - 1); } imgReminderStart.ImageUrl = "~/Layouts/Images/reminder2.gif"; } } else { imgReminderStart.Visible = false; } if (IsMember && TargetFinishDate > DateTime.UtcNow) { int Lag = -1; bool IsActive = false; using (IDataReader reader = Schedule.GetReminderSubscriptionPersonalForObject(DateTypes.Todo_FinishDate, ToDoID)) { if (reader.Read()) { Lag = (int)reader["Lag"]; IsActive = (bool)reader["IsActive"]; } } if (IsActive) { imgReminderFinish.ToolTip = String.Format("{0}: {1}", LocRM2.GetString("Finish"), CommonHelper.GetIntervalString(Lag)); } else { imgReminderFinish.ToolTip = CommonHelper.GetIntervalString(-1); if (imgReminderFinish.ToolTip.StartsWith("[")) { imgReminderFinish.ToolTip = imgReminderFinish.ToolTip.Substring(1); } if (imgReminderFinish.ToolTip.EndsWith("]")) { imgReminderFinish.ToolTip = imgReminderFinish.ToolTip.Substring(0, imgReminderFinish.ToolTip.Length - 1); } imgReminderFinish.ImageUrl = "~/Layouts/Images/reminder2.gif"; } } else { imgReminderFinish.Visible = false; } }
} // BuildDescription public void BuildDescription(bool pastTime, bool withBasicDescription, bool withFullDescription, bool withChannel, bool withSchedule, bool withDuration, TimeSpan?overrideTotalRecordTime, StringBuilder buffer) { if ((withBasicDescription) || (withFullDescription)) { var taskFormat = withFullDescription ? Properties.Texts.BuildDescriptionTaskDescription : Properties.Texts.BuildDescriptionTaskName; buffer.AppendFormat(taskFormat, Description.Name, Description.Description); buffer.AppendLine(); } // if if (withChannel) { buffer.AppendFormat(Properties.Texts.BuildDescriptionChannel, Channel.LogicalNumber, Channel.Name, Channel.ChannelUrl, Channel.ServiceName); buffer.AppendLine(); } // if withChannel if (withSchedule) { buffer.AppendLine(Properties.Texts.BuildDescriptionScheduleHeader); Schedule.Verbalize(pastTime, buffer); buffer.AppendLine(); } // if withSchedule if (withDuration) { buffer.AppendLine(Properties.Texts.BuildDescriptionDurationHeader); var startSafetyMargin = Schedule.SafetyMarginTimeSpan; var endSafetyMargin = Duration.SafetyMarginTimeSpan; var recordDuration = Duration.Length; var totalRecordTime = startSafetyMargin + recordDuration + endSafetyMargin; if (overrideTotalRecordTime.HasValue) { totalRecordTime = overrideTotalRecordTime.Value; } var formatDuration = pastTime ? Properties.Texts.BuildDescriptionDurationPast : Properties.Texts.BuildDescriptionDuration; buffer.AppendFormat(formatDuration, recordDuration, (int)endSafetyMargin.TotalMinutes, totalRecordTime); buffer.AppendLine(); if (Schedule.Kind != RecordScheduleKind.RightNow) { string format; var startDate = Schedule.StartDate - Schedule.SafetyMarginTimeSpan; var endDate = startDate + totalRecordTime; if (startDate.Day == endDate.Day) { format = pastTime ? Properties.Texts.BuildDescriptionDurationEndsSameDay : Properties.Texts.BuildDescriptionDurationEndsToday; } else { format = pastTime ? Properties.Texts.BuildDescriptionDurationEndsNextDay : Properties.Texts.BuildDescriptionDurationEndsTomorrow; } // if-else buffer.AppendFormat(format, endDate); } else { } // if-else buffer.AppendLine(); } // if withDuration // remove last CRLF if (buffer.Length > 2) { buffer.Remove(buffer.Length - 2, 2); } // if } // BuildDescription
public void TaskStarting_Canceled_Success() { bool TaskStartingExecuted = false; Scheduler <BlockingScheduledAction> scheduler = new Scheduler <BlockingScheduledAction>(TimeSpan.FromSeconds(0.1)); scheduler.TaskStarting += (sender, e) => { e.Cancel = true; TaskStartingExecuted = true; }; BlockingScheduledAction action1 = new BlockingScheduledAction(); ScheduledTask <BlockingScheduledAction> task = new ScheduledTask <BlockingScheduledAction>(Schedule.CreateOneTime(DateTimeOffset.Now), action1, true, null, null); scheduler.Tasks.Add(task); scheduler.Start(); SpinWait.SpinUntil(() => { return(TaskStartingExecuted); }); scheduler.Stop(); Assert.IsNull(task.LastEndTime); scheduler.Dispose(); }