コード例 #1
0
        public ActionResult Put([FromBody] SchedulerEvent schedulerEvent)
        {
            using var db = new DutyingContext();

            var user = db.Users
                       .Include(user => user.SchedulerEvents)
                       .FirstOrDefault(user => user.Id == schedulerEvent.UserId);

            if (user is null)
            {
                NotFound();
            }

            user.SchedulerEvents
            .Where(e => e.Id == schedulerEvent.Id)
            .Select(e =>
            {
                e.StartsAt = e.StartsAt != schedulerEvent.StartsAt ? schedulerEvent.StartsAt : e.StartsAt;
                e.EndsAt   = e.EndsAt != schedulerEvent.EndsAt ? schedulerEvent.EndsAt : e.EndsAt;
                e.Comment  = e.Comment != schedulerEvent.Comment ? schedulerEvent.Comment : e.Comment;
                return(e);
            }).ToList();
            db.Users.Update(user);
            db.SaveChanges();

            return(Ok());
        }
コード例 #2
0
        internal AppointmentChangedResult AppointmentCancel(int userId, int unitId, SchedulerEvent schedulerEvent)
        {
            var dataService = new QNomyDataService();
            AppointmentChangedResult result = new AppointmentChangedResult();
            int processId = schedulerEvent.ProcessId;
            ProcessCancelCaseResults cancelResult = Process.CancelCase(processId, userId, 0);


            if (cancelResult.CurrentProcessId > 0)
            {
                schedulerEvent.ProcessId = cancelResult.CurrentProcessId;


                CustomizeData customizeData = GetCustomizeData(unitId);

                var calendarStages = dataService.GetClendarStages(customizeData.ConfigId);
                AdjustStageType(schedulerEvent, calendarStages, customizeData);

                result.EventData = schedulerEvent;
            }

            List <AppUser.UserStatus> okStatus = new List <AppUser.UserStatus>()
            {
                AppUser.UserStatus.Idle, AppUser.UserStatus.Unknown, AppUser.UserStatus.SignedOut
            };

            if (!okStatus.Contains(cancelResult.UserStatus))
            {
                throw new DataException($"Not Canceled, user status {cancelResult.UserStatus.ToString()}");
            }
            return(result);
        }
コード例 #3
0
        public ActionResult <SchedulerEvent> Post([FromBody] SchedulerEvent schedulerEvent)
        {
            using var db = new DutyingContext();

            var user = db.Users
                       .Include(user => user.SchedulerEvents)
                       .FirstOrDefault(user => user.Id == schedulerEvent.UserId);

            if (user is null)
            {
                NotFound();
            }

            if (user.SchedulerEvents is null)
            {
                user.SchedulerEvents = new List <SchedulerEvent>();
            }

            user.SchedulerEvents.Add(schedulerEvent);

            db.Users.Update(user);
            db.SaveChanges();

            return(Created("", schedulerEvent));
        }
コード例 #4
0
        public List <SchedulerEvent> GetSchedulerEvents(DateTime?from, DateTime?to, int unitId)
        {
            var result       = new List <SchedulerEvent>();
            var now          = DateTime.Now;
            var dataService  = new QNomyDataService();
            var appointments = dataService.GetAppointments(from, to);

            CustomizeData customizeData  = GetCustomizeData(unitId);
            var           calendarStages = dataService.GetClendarStages(customizeData.ConfigId);
            var           statusMapping  = GetMappingCalendarStageTypeToEntityStatus();

            foreach (var app in appointments)
            {
                app.CalendarStageType = statusMapping[app.CurrentEntityStatus];
                int?stageId = GetStageByServiceId(app.ServiceId, app.CalendarStageType, calendarStages, customizeData);
                if (!stageId.HasValue)
                {
                    continue;
                }

                app.StageId = stageId.Value;
                SchedulerEvent se = ToScheduleEvent(app);
                result.Add(se);
            }
            return(result);
        }
コード例 #5
0
ファイル: Add.cs プロジェクト: moayyaed/YetaWF-Modules
 public SchedulerAddModel()
 {
     Frequency = new SchedulerFrequency()
     {
         TimeUnits = SchedulerFrequency.TimeUnitEnum.Hours, Value = 1
     };
     Event = new SchedulerEvent();
 }
コード例 #6
0
        private async Task <SchedulerEvent> GetEvent(Guid id)
        {
            Event @event = await _eventRepository.GetFirstOrDefaultAsync(
                predicate : t => t.Id == id);

            SchedulerEvent schedulerEvent = _mapper.Map <Event, SchedulerEvent>(@event);

            return(schedulerEvent);
        }
コード例 #7
0
 public SchedulerTask()
 {
     Pair        = null;
     Event       = SchedulerEvent.Manually;
     TimeSpan    = 0;
     LastRunTime = DateTime.MinValue;
     NextRunTime = 1;
     Precedence  = Precedence.None;
     SilentSync  = false;
 }
コード例 #8
0
ファイル: EventParseTests.cs プロジェクト: frialex/perfview
        private void HeaderTest(string source, bool blockedTime,
                                string[] commands,
                                int[] pids,
                                int[] tids,
                                int[] cpus,
                                double[] times,
                                int[] timeProperties,
                                string[] events,
                                string[] eventProperties,
                                EventKind[] eventKinds,
                                ScheduleSwitch[] switches
                                )
        {
            Constants.WaitUntilFileIsReady(source);

            using (Stream stream = File.Open(source, FileMode.Open))
            {
                LinuxPerfScriptEventParser parser  = new LinuxPerfScriptEventParser();
                List <LinuxEvent>          samples = parser.ParseSkippingPreamble(stream).ToList();

                // Need to make sure we have the same amount of samples
                Assert.Equal(commands.Length, parser.EventCount);

                int schedCount = 0;

                for (int i = 0; i < parser.EventCount; i++)
                {
                    LinuxEvent linuxEvent = samples[i];
                    Assert.Equal(commands[i], linuxEvent.Command);
                    Assert.Equal(pids[i], linuxEvent.ProcessID);
                    Assert.Equal(tids[i], linuxEvent.ThreadID);
                    Assert.Equal(cpus[i], linuxEvent.CpuNumber);
                    Assert.Equal(times[i], linuxEvent.TimeMSec);
                    Assert.Equal(timeProperties[i], linuxEvent.TimeProperty);
                    Assert.Equal(events[i], linuxEvent.EventName);
                    Assert.Equal(eventProperties[i], linuxEvent.EventProperty);
                    Assert.Equal(eventKinds == null ? EventKind.Cpu : eventKinds[i], linuxEvent.Kind);

                    SchedulerEvent sched = linuxEvent as SchedulerEvent;
                    if (switches != null && sched != null)
                    {
                        ScheduleSwitch actualSwitch   = sched.Switch;
                        ScheduleSwitch expectedSwitch = switches[schedCount++];
                        Assert.Equal(expectedSwitch.NextCommand, actualSwitch.NextCommand);
                        Assert.Equal(expectedSwitch.NextPriority, actualSwitch.NextPriority);
                        Assert.Equal(expectedSwitch.NextThreadID, actualSwitch.NextThreadID);
                        Assert.Equal(expectedSwitch.PreviousCommand, actualSwitch.PreviousCommand);
                        Assert.Equal(expectedSwitch.PreviousPriority, actualSwitch.PreviousPriority);
                        Assert.Equal(expectedSwitch.PreviousState, actualSwitch.PreviousState);
                        Assert.Equal(expectedSwitch.PreviousThreadID, actualSwitch.PreviousThreadID);
                    }
                }
            }
        }
コード例 #9
0
        private void AdjustStageType(SchedulerEvent theEvent, List <CalendarStage> calendarStages, CustomizeData customizeData)
        {
            var qnomyApp      = Appointment.Get(theEvent.AppointmentId);
            var statusMapping = GetMappingCalendarStageTypeToEntityStatus();

            theEvent.StageType = statusMapping[qnomyApp.CurrentEntityStatus];
            int?stageId = GetStageByServiceId(theEvent.ServiceId, theEvent.StageType, calendarStages, customizeData);

            theEvent.StageId = stageId ?? -1;
            var currentService = Service.Get(theEvent.ServiceId);

            theEvent.ServiceName = currentService.Name;
        }
コード例 #10
0
        private SchedulerEvent ToScheduleEvent(AppointmentInfo app)
        {
            var result = new SchedulerEvent();

            result.CustomerName  = $"{app.CustomerFirstName} {app.CustomerLastName}";
            result.ServiceName   = $"{app.ServiceName}";
            result.Start_date    = app.AppointmentDate;
            result.End_date      = app.AppointmentDate.AddMinutes(app.AppointmentDuration);
            result.AppointmentId = app.AppointmentId;
            result.ServiceId     = app.ServiceId;
            result.StageType     = app.CalendarStageType;
            result.StageId       = app.StageId;
            result.ProcessId     = app.ProcessId;
            return(result);
        }
コード例 #11
0
            /// <exception cref="System.Exception"/>
            public Void Answer(InvocationOnMock invocation)
            {
                SchedulerEvent @event = (SchedulerEvent)(invocation.GetArguments()[0]);

                this._enclosing.eventType = @event.GetType();
                if (this._enclosing.eventType == SchedulerEventType.NodeUpdate)
                {
                    IList <UpdatedContainerInfo> lastestContainersInfoList = ((NodeUpdateSchedulerEvent
                                                                               )@event).GetRMNode().PullContainerUpdates();
                    foreach (UpdatedContainerInfo lastestContainersInfo in lastestContainersInfoList)
                    {
                        Sharpen.Collections.AddAll(this._enclosing.completedContainers, lastestContainersInfo
                                                   .GetCompletedContainers());
                    }
                }
                return(null);
            }
コード例 #12
0
        public IActionResult SetAvailability([Bind("Id,Text,StartDate,EndDate,StudentId,Student")] SchedulerEvent schedulerEvent)
        {
            var userId   = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var teacher  = _context.Teachers.Where(c => c.IdentityUserId == userId).FirstOrDefault();
            var students = _context.Students.Where(x => x.Classroom == teacher.Classroom).ToList();

            foreach (var student in students)
            {
                schedulerEvent.Id        = 0;
                schedulerEvent.StudentId = student.StudentId;
                schedulerEvent.Student   = student;
                SchedulerEvent availabileTime = new SchedulerEvent()
                {
                    Id = schedulerEvent.Id, Text = schedulerEvent.Text, StartDate = schedulerEvent.StartDate, EndDate = schedulerEvent.StartDate, StudentId = schedulerEvent.StudentId, Student = schedulerEvent.Student
                };
                _context.Add(availabileTime);
            }
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
コード例 #13
0
        // do not use it, this method reschedules time
        internal SchedulerEvent SaveAppointment(SchedulerEvent appointment)
        {
            var dataService      = new QNomyDataService();
            var newAppointmentId = dataService.UpdateAppointmentTime(appointment.AppointmentId, appointment.Start_date, appointment.End_date);
            var qnomyApp         = Appointment.Get(newAppointmentId);
            var app = new AppointmentInfo();

            app.AppointmentDate     = qnomyApp.AppointmentDate;
            app.AppointmentDuration = qnomyApp.AppointmentDuration;
            app.AppointmentId       = qnomyApp.Id;
            app.AppointmentTypeName = qnomyApp.AppointmentTypeName;
            app.CurrentEntityStatus = qnomyApp.CurrentEntityStatus;

            app.StageId           = appointment.StageId;
            app.CalendarStageType = appointment.StageType;

            SchedulerEvent se = ToScheduleEvent(app);

            return(se);
        }
コード例 #14
0
        public async Task <ActionResult <int> > Update([FromBody] SchedulerEvent schedulerEvent)
        {
            var oldSchedulerEvent = _context.SchedulerEvent
                                    .FirstOrDefault(x => x.Id == schedulerEvent.Id);

            if (oldSchedulerEvent == null)
            {
                return(NotFound());
            }

            oldSchedulerEvent.Title      = schedulerEvent.Title;
            oldSchedulerEvent.Start      = schedulerEvent.Start;
            oldSchedulerEvent.End        = schedulerEvent.End;
            oldSchedulerEvent.IsApproved = schedulerEvent.IsApproved;
            oldSchedulerEvent.CategoryId = schedulerEvent.CategoryId;

            await _context.SaveChangesAsync();

            return(Ok(oldSchedulerEvent));
        }
コード例 #15
0
        private static void CallUser(int currentUserId, SchedulerEvent theEvent, int delegateId)
        {
            UserCallResults callResult        = AppUser.Call(currentUserId, delegateId, theEvent.ProcessId, theEvent.ServiceId, false, Process.ProcessPromoteAction.Auto, false);
            var             callValidStatuses = new List <UserCallResults.CallStatus>();

            callValidStatuses.Add(UserCallResults.CallStatus.Success);

            if (!callValidStatuses.Contains(callResult.Status))
            {
                if (callResult.Status == UserCallResults.CallStatus.LimitReached)
                {
                    throw new DataException("You are serving the maximum number of cases allowed by the system.");
                }
                throw new DataException(callResult.Status.ToString());
            }

            if (callResult.ServiceId > 0)
            {
                theEvent.ServiceId = callResult.ServiceId;
            }
        }
コード例 #16
0
        public async Task <ActionResult <SchedulerEvent> > Add([FromBody] SchedulerEvent schedulerEvent)
        {
            if (_context.Categories.Where(s => s.Id == schedulerEvent.CategoryId).FirstOrDefault() == null)
            {
                return(BadRequest("ERROR, category with Id: " + schedulerEvent.CategoryId + " doesn't exist"));
            }

            var newSchedulerEvent = new SchedulerEvent()
            {
                Title      = schedulerEvent.Title,
                Start      = schedulerEvent.Start,
                End        = schedulerEvent.End,
                IsApproved = schedulerEvent.IsApproved,
                CategoryId = schedulerEvent.CategoryId
            };

            _context.SchedulerEvent.Add(newSchedulerEvent);
            await _context.SaveChangesAsync();

            return(Ok(newSchedulerEvent));
        }
コード例 #17
0
        public ActionResult MakeSchedulerEvent(int id, DateTime selectedTime)
        {
            var meeting = db.UpcomingMeetings.Include("Author")
                          .Where(m => m.Id == id).FirstOrDefault();
            var schedulerEvent = new SchedulerEvent
            {
                Text      = meeting.Description,
                StartDate = selectedTime,
                EndDate   = selectedTime.AddHours(meeting.Duration.Hours),
                Creator   = meeting.Author.Id
            };

            db.SchedulerEvents.Add(schedulerEvent);
            db.UpcomingMeetings.Remove(meeting);
            var result = db.UsersUpcomingMeetings.Where(m => m.MeetingId.Id == meeting.Id);

            foreach (var item in result)
            {
                db.UsersUpcomingMeetings.Remove(item);
            }
            db.SaveChanges();
            return(RedirectToAction("MeetingInvites"));
        }
コード例 #18
0
        public static async Task ScheduleEvent(this IScheduler scheduler, SchedulerEvent @event)
        {
            JobKey     jobKey     = new JobKey(@event.Id.ToString(), ConstantsStorage.EVENT_GROUP);
            TriggerKey triggerKey = new TriggerKey(@event.Id.ToString(), ConstantsStorage.EVENT_GROUP);

            if (@event.CronExpression != CronExpressionGenerator.TriggerInThePast)
            {
                IJobDetail job = JobBuilder.Create <NotificationJob>()
                                 .WithIdentity(jobKey)
                                 .UsingJobData(NotificationJob.JobDataKey, @event.Id.ToString())
                                 .UsingJobData(NotificationJob.JobActivityTypeKey, ConstantsStorage.EVENT)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity(triggerKey)
                                   .StartAt(DateTime.SpecifyKind(@event.StartTime, DateTimeKind.Utc))
                                   .WithCronSchedule(@event.CronExpression, ce => ce.InTimeZone(TimeZoneInfo.Utc))
                                   .EndAt(DateTime.SpecifyKind(@event.StartTime, DateTimeKind.Utc))
                                   .Build();

                await scheduler.ScheduleJob(job, trigger);
            }
        }
コード例 #19
0
 public abstract void Handle(SchedulerEvent arg1);
コード例 #20
0
 public void RaiseEvent(SchedulerEvent @event)
 {
     _eventTarget.Push(@event);
 }
コード例 #21
0
 public override void Handle(SchedulerEvent @event)
 {
     this._enclosing.scheduler.Handle(@event);
 }
コード例 #22
0
        public async System.Threading.Tasks.Task ScheduleEventById(Guid id)
        {
            SchedulerEvent schedulerEvent = await GetEvent(id);

            await _scheduler.ScheduleEvent(schedulerEvent);
        }
コード例 #23
0
 public SchedulerEditModel()
 {
     Event     = new SchedulerEvent();
     Frequency = new SchedulerFrequency();
 }
コード例 #24
0
ファイル: FifoScheduler.cs プロジェクト: orf53975/hadoop.net
        public override void Handle(SchedulerEvent @event)
        {
            switch (@event.GetType())
            {
            case SchedulerEventType.NodeAdded:
            {
                NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent)@event;
                AddNode(nodeAddedEvent.GetAddedRMNode());
                RecoverContainersOnNode(nodeAddedEvent.GetContainerReports(), nodeAddedEvent.GetAddedRMNode
                                            ());
                break;
            }

            case SchedulerEventType.NodeRemoved:
            {
                NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent)@event;
                RemoveNode(nodeRemovedEvent.GetRemovedRMNode());
                break;
            }

            case SchedulerEventType.NodeResourceUpdate:
            {
                NodeResourceUpdateSchedulerEvent nodeResourceUpdatedEvent = (NodeResourceUpdateSchedulerEvent
                                                                             )@event;
                UpdateNodeResource(nodeResourceUpdatedEvent.GetRMNode(), nodeResourceUpdatedEvent
                                   .GetResourceOption());
                break;
            }

            case SchedulerEventType.NodeUpdate:
            {
                NodeUpdateSchedulerEvent nodeUpdatedEvent = (NodeUpdateSchedulerEvent)@event;
                NodeUpdate(nodeUpdatedEvent.GetRMNode());
                break;
            }

            case SchedulerEventType.AppAdded:
            {
                AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent)@event;
                AddApplication(appAddedEvent.GetApplicationId(), appAddedEvent.GetQueue(), appAddedEvent
                               .GetUser(), appAddedEvent.GetIsAppRecovering());
                break;
            }

            case SchedulerEventType.AppRemoved:
            {
                AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent)@event;
                DoneApplication(appRemovedEvent.GetApplicationID(), appRemovedEvent.GetFinalState
                                    ());
                break;
            }

            case SchedulerEventType.AppAttemptAdded:
            {
                AppAttemptAddedSchedulerEvent appAttemptAddedEvent = (AppAttemptAddedSchedulerEvent
                                                                      )@event;
                AddApplicationAttempt(appAttemptAddedEvent.GetApplicationAttemptId(), appAttemptAddedEvent
                                      .GetTransferStateFromPreviousAttempt(), appAttemptAddedEvent.GetIsAttemptRecovering
                                          ());
                break;
            }

            case SchedulerEventType.AppAttemptRemoved:
            {
                AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent = (AppAttemptRemovedSchedulerEvent
                                                                          )@event;
                try
                {
                    DoneApplicationAttempt(appAttemptRemovedEvent.GetApplicationAttemptID(), appAttemptRemovedEvent
                                           .GetFinalAttemptState(), appAttemptRemovedEvent.GetKeepContainersAcrossAppAttempts
                                               ());
                }
                catch (IOException ie)
                {
                    Log.Error("Unable to remove application " + appAttemptRemovedEvent.GetApplicationAttemptID
                                  (), ie);
                }
                break;
            }

            case SchedulerEventType.ContainerExpired:
            {
                ContainerExpiredSchedulerEvent containerExpiredEvent = (ContainerExpiredSchedulerEvent
                                                                        )@event;
                ContainerId containerid = containerExpiredEvent.GetContainerId();
                CompletedContainer(GetRMContainer(containerid), SchedulerUtils.CreateAbnormalContainerStatus
                                       (containerid, SchedulerUtils.ExpiredContainer), RMContainerEventType.Expire);
                break;
            }

            case SchedulerEventType.ContainerRescheduled:
            {
                ContainerRescheduledEvent containerRescheduledEvent = (ContainerRescheduledEvent)
                                                                      @event;
                RMContainer container = containerRescheduledEvent.GetContainer();
                RecoverResourceRequestForContainer(container);
                break;
            }

            default:
            {
                Log.Error("Invalid eventtype " + @event.GetType() + ". Ignoring!");
                break;
            }
            }
        }
コード例 #25
0
 public static async Task RescheduleEvent(this IScheduler scheduler, SchedulerEvent @event)
 {
     await UnscheduleEvent(scheduler, @event);
     await ScheduleEvent(scheduler, @event);
 }
コード例 #26
0
 public SchedulerItemData()
 {
     Frequency = new SchedulerFrequency();
     Event     = new SchedulerEvent();
     Next      = null;
 }
コード例 #27
0
        private RouteResultData RouteUser(int currentUserId, SchedulerEvent theEvent, QNomyDataService dataService, int delegateId, List <int> servicesInStage, bool callAfterRoute, int?routeId)
        {
            RouteResultData      result          = new RouteResultData();
            List <RouteListItem> availableRoutes = Service.GetAvailableRoutes(theEvent.ServiceId);
            int?transferedFromServiceId          = dataService.GetTranseredFromServiceId(theEvent.ProcessId);

            var  routesToStage  = new List <RouteListItem>();
            var  returnToSender = new List <RouteListItem>();
            bool skipAddRoute   = false;

            foreach (var rout in availableRoutes)
            {
                skipAddRoute = routeId.HasValue && routeId.Value > 0 && routeId.Value != rout.Id;
                if (!skipAddRoute && transferedFromServiceId.HasValue && rout.TargetType == Route.RouteTargetType.ReturnToSender && servicesInStage.Contains(transferedFromServiceId.Value))
                {
                    routesToStage.Add(rout);
                    continue;
                }

                if (!skipAddRoute && servicesInStage.Contains(rout.TargetServiceId))
                {
                    routesToStage.Add(rout);
                    continue;
                }
            }


            if (routesToStage.Count == 0)
            {
                throw new DataException("Route to this stage does not exists.");
            }

            if (routesToStage.Count > 1)
            {
                result.Selection         = new SelectOptionData();
                result.Selection.Options = new List <KeyValuePair <int, string> >();
                foreach (var item in routesToStage)
                {
                    result.Selection.Options.Add(new KeyValuePair <int, string>(item.Id, item.Name));
                }

                return(result);
            }

            var route = routesToStage[0];

            // Route operation.
            ProcessRouteResults routeResult = Process.Route(theEvent.ProcessId, currentUserId, delegateId, route.Id, route.TargetServiceId, 0, 0, "", false, 0);

            if (routeResult.Status != ProcessRouteResults.ProcessRouteResultsStatus.Success)
            {
                throw new DataException(routeResult.Status.ToString());
            }

            if (routeResult.NewServiceId > 0)
            {
                theEvent.ServiceId = routeResult.NewServiceId;
            }

            if (routeResult.NewProcessId > 0)
            {
                theEvent.ProcessId = routeResult.NewProcessId;
            }

            if (callAfterRoute && routeResult.NewEntityStatus == (int)EntityType.EntityStatus.Waiting)
            {
                try
                {
                    CallUser(currentUserId, theEvent, delegateId);
                }
                catch (DataException)
                {
                }
            }
            result.IsRouted = true;
            return(result);
        }
コード例 #28
0
        public static async Task UnscheduleEvent(this IScheduler scheduler, SchedulerEvent @event)
        {
            JobKey jobKey = new JobKey(@event.Id.ToString(), ConstantsStorage.EVENT_GROUP);

            await scheduler.DeleteJob(jobKey);
        }
コード例 #29
0
 private void OnEventEmitted(SchedulerEvent payload)
 {
     EventEmitted?.Invoke(this, new SchedulerEventArgs(payload));
 }
コード例 #30
0
        internal AppointmentChangedResult AppointmentChanged(int currentUserId, int currentUnitId, int previousStageId, int nextStageId, SchedulerEvent theEvent, int?routeId)
        {
            AppointmentChangedResult result = new AppointmentChangedResult();
            var dataService = new QNomyDataService();


            CustomizeData customizeData = GetCustomizeData(currentUnitId);
            // qnomy
            var calendarStages = customizeData.Stages.ToList <CalendarStage>();

            //var allCalendarStageServices = customizeData.GetClendarStageServices();
            var             prevCalendarStageType = GetStageTypeById(previousStageId, calendarStages);
            var             nextCalendarStageType = GetStageTypeById(nextStageId, calendarStages);
            int             previousServiceId     = theEvent.ServiceId;
            RouteResultData routeResult           = null;

            int delegateId = 0;

            if ((nextCalendarStageType == CalendarStageType.InService) || (prevCalendarStageType != nextCalendarStageType))
            {
                // calendar stage type - is old stageType.
                if (prevCalendarStageType == CalendarStageType.Completed)
                {
                    throw new DataException("Already Completed, cannot change");
                }

                switch (nextCalendarStageType)
                {
                case CalendarStageType.Completed:
                    ProcessPromoteResults processPromoteResults = Process.Promote(theEvent.ProcessId, currentUserId, delegateId, Process.ProcessPromoteAction.Complete, false);
                    break;

                case CalendarStageType.Expected:
                    throw new NotSupportedException("Cannot back to expected status");

                case CalendarStageType.InService:
                    var nextStage = customizeData.Stages.Find(x => x.Id == nextStageId);
                    if (nextStage == null)
                    {
                        throw new DataException("stage is not valid");
                    }
                    var servicesInStage = GetServicesIds(nextStage.Services);

                    if (servicesInStage.Count == 0)
                    {
                        throw new DataException("Cannot find any service for this stage");
                    }

                    if (prevCalendarStageType != CalendarStageType.InService)
                    {
                        if (servicesInStage.Contains(theEvent.ServiceId))
                        {
                            CallUser(currentUserId, theEvent, delegateId);
                        }
                        else
                        {
                            routeResult = RouteUser(currentUserId, theEvent, dataService, delegateId, servicesInStage, true, routeId);
                        }
                    }
                    else
                    {
                        routeResult = RouteUser(currentUserId, theEvent, dataService, delegateId, servicesInStage, true, routeId);
                    }

                    break;

                case CalendarStageType.None:
                    throw new InvalidOperationException("Invalid stage is not defined");

                case CalendarStageType.Waiting:
                    if (prevCalendarStageType == CalendarStageType.Expected)
                    {
                        ProcessEnqueueAppointmentResults enqueResult = Process.EnqueueAppointment(theEvent.ProcessId, forceEarly: true, forceLate: true);
                        var enqueValidStatuses = new List <ProcessEnqueueAppointmentResults.ProcessEnqueueAppointmentResultsStatus>();
                        enqueValidStatuses.Add(ProcessEnqueueAppointmentResults.ProcessEnqueueAppointmentResultsStatus.Success);
                        enqueValidStatuses.Add(ProcessEnqueueAppointmentResults.ProcessEnqueueAppointmentResultsStatus.Late);
                        if (!enqueValidStatuses.Contains(enqueResult.Status))
                        {
                            throw DataException.GetDataException(enqueResult.Status);
                        }
                        break;
                    }

                    if (prevCalendarStageType == CalendarStageType.WaitingCustomerAction)
                    {
                        ProcessStopWaitingForCustomerActionResults stopWaitResult = Process.StopWaitingForCustomerAction(theEvent.ProcessId, currentUserId, delegateId);

                        break;
                    }
                    if (prevCalendarStageType == CalendarStageType.Waiting)
                    {
                        break;
                    }
                    if (prevCalendarStageType == CalendarStageType.InService)
                    {
                        ProcessRequeueInServiceResults requeResult = Process.RequeueInService(theEvent.ProcessId, currentUnitId, delegateId);
                        break;
                    }
                    throw new DataException("Waiting stage does not accessible from this stage");

                case CalendarStageType.WaitingCustomerAction:
                    ProcessWaitForCustomerActionResults waitResult = Process.WaitForCustomerAction(theEvent.ProcessId, currentUserId, 0);
                    break;

                default:
                    throw new InvalidOperationException("Stage is not supported");
                }
            }

            if (routeResult != null && !routeResult.IsRouted)
            {
                result.RouteData = routeResult;
                return(result);
            }


            AdjustStageType(theEvent, calendarStages, customizeData);

            result.EventData = theEvent;
            return(result);
        }