public void Bind(WorkflowState state) { var worflowType = _instance.GetType(); foreach (var name in state.Keys) { var val = state[name]; if (val != null) { var prop = worflowType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance); if (prop != null && prop.CanRead && prop.CanWrite) { if (prop.PropertyType.IsAssignableFrom(val.GetType())) { prop.SetValue(_instance, val, null); } else { var converter = TypeDescriptor.GetConverter(prop.PropertyType); if (converter != null && converter.CanConvertFrom(val.GetType())) { val = converter.ConvertFrom(val); } prop.SetValue(_instance, val, null); } } } } }
public void Given_simple_workflow_instance() { _instance = new FooWorkflow(); var state = new WorkflowState {{"Test1", "Value #1"}, {"Test2", "Value #2"}}; new WorkflowBinder(_instance).Bind(state); }
public void TestInitialize() { _userId = 0; _revisionId = 0; _userName = ""; _transactionId = 123; _workflowEventTriggers = new WorkflowEventTriggers(); _baseArtifactVersionControlInfo = new WorkflowMessageArtifactInfo(); _projectName = ""; _modifiedProperties = new Dictionary <int, IList <Property> >(); _currentState = new WorkflowState(); _artifactUrl = ""; _baseUrl = ""; _ancestorArtifactTypeIds = new int[] { }; _mockUsersRepository = new Mock <IUsersRepository>(MockBehavior.Strict); _mockServiceLogRepository = new Mock <IServiceLogRepository>(MockBehavior.Strict); _mockWebhooksRepository = new Mock <IWebhooksRepository>(MockBehavior.Strict); _mockProjectMetaRepository = new Mock <IProjectMetaRepository>(MockBehavior.Strict); }
public String GetStateName(ContentItem contentItem) { String stateName = String.Empty; if (contentItem.StateID != -1) { if (_workflowManager.GetWorkflow(contentItem) != null) { WorkflowState workflow = _workflowManager.GetWorkflow(contentItem).States.Where(i => i.StateID == contentItem.StateID).FirstOrDefault(); if (workflow != null) { stateName = workflow.StateName; } } } return(stateName); }
/// <summary> /// Enters a new media navigation context by modifying the list of available screens. This is used for /// presenting the result of a filter, where the menu must be changed. /// </summary> /// <param name="subViewSpecification">Specification for the sub view to be shown in the new navigation context.</param> /// <param name="currentMenuItemLabel">Current menu item label needed for distinction of available screens.</param> /// <param name="navbarDisplayLabel">Display label to be shown in the navigation bar for the new navigation context.</param> /// <returns>Newly created navigation data.</returns> public NavigationData StackAutonomousNavigationContext(ViewSpecification subViewSpecification, string currentMenuItemLabel, string navbarDisplayLabel) { AbstractScreenData currentScreen = AvailableScreens.FirstOrDefault(screen => screen.MenuItemLabel == currentMenuItemLabel); ICollection <AbstractScreenData> remainingScreens = new List <AbstractScreenData>(AvailableScreens.Where(screen => screen != currentScreen)); WorkflowState newState = WorkflowState.CreateTransientState( "View: " + subViewSpecification.ViewDisplayName, subViewSpecification.ViewDisplayName, false, null, false, WorkflowType.Workflow, null); string nextScreenName; AbstractScreenData nextScreen = null; // Try to load the prefered next screen from settings. if (LoadScreenHierarchy(CurrentScreenData.GetType().ToString(), out nextScreenName)) { nextScreen = remainingScreens.FirstOrDefault(s => s.GetType().ToString() == nextScreenName); } // Default way: always take the first of the available screens. if (nextScreen == null) { nextScreen = remainingScreens.First(s => s != currentScreen); } ScreenConfig nextScreenConfig; LoadLayoutSettings(nextScreen.GetType().ToString(), out nextScreenConfig); Sorting.Sorting nextSortingMode = AvailableSortings.FirstOrDefault( sorting => sorting.GetType().ToString() == nextScreenConfig.Sorting && sorting.IsAvailable(nextScreen)) ?? _currentSorting; Sorting.Sorting nextGroupingMode = String.IsNullOrEmpty(nextScreenConfig.Grouping) ? null : AvailableGroupings.FirstOrDefault( grouping => grouping.GetType().ToString() == nextScreenConfig.Grouping && grouping.IsAvailable(nextScreen)) ?? _currentGrouping; NavigationData newNavigationData = new NavigationData(this, subViewSpecification.ViewDisplayName, newState.StateId, newState.StateId, subViewSpecification, nextScreen, remainingScreens, nextSortingMode, nextGroupingMode) { LayoutType = nextScreenConfig.LayoutType, LayoutSize = nextScreenConfig.LayoutSize }; PushNewNavigationWorkflowState(newState, navbarDisplayLabel, newNavigationData); return(newNavigationData); }
public ActionResult Delete(int StateID) { ActionResult ActionResult = new ActionResult(); Dictionary <string, dynamic> data = new Dictionary <string, dynamic>(); WorkflowState wState = Managers.WorkflowManager.GetStateByID(StateID); if (wState != null && (Managers.WorkflowManager.IsWorkflowStateDeleted(wState.WorkflowID, wState))) { Managers.WorkflowManager.DeleteWorkflowState(wState.StateID, wState.WorkflowID); data.Add("IsDeleted", true); } else { data.Add("IsDeleted", false); } ActionResult.Data = data; return(ActionResult); }
public void UpdateMenuActions(NavigationContext context, IDictionary <Guid, WorkflowAction> actions) { IConfigurationManager configurationManager = ServiceRegistration.Get <IConfigurationManager>(); string configLocation = GetConfigLocation(context); WorkflowState mainState; ServiceRegistration.Get <IWorkflowManager>().States.TryGetValue(new Guid(CONFIGURATION_MAIN_STATE_ID_STR), out mainState); IConfigurationNode currentNode = configurationManager.GetNode(configLocation); foreach (IConfigurationNode childNode in currentNode.ChildNodes) { if (childNode.ConfigObj is ConfigSection) { bool supportedSettings = NumSettingsSupported(childNode) > 0; // Hint (Albert): Instead of skipping, we could disable the transition in case there are no supported // settings contained in it if (!supportedSettings) { continue; } ConfigSection section = (ConfigSection)childNode.ConfigObj; // Create transient state for new config section WorkflowState newState = WorkflowState.CreateTransientState( string.Format("Config: '{0}'", childNode.Location), section.SectionMetadata.Text, false, CONFIGURATION_SECTION_SCREEN, false, WorkflowType.Workflow); // Add action for menu IResourceString res = LocalizationHelper.CreateResourceString(section.Metadata.Text); WorkflowAction wa = new PushTransientStateNavigationTransition( Guid.NewGuid(), context.WorkflowState.Name + "->" + childNode.Location, null, new Guid[] { context.WorkflowState.StateId }, newState, res) { DisplayCategory = ACTIONS_WORKFLOW_CATEGORY, SortOrder = childNode.Sort ?? res.Evaluate(), WorkflowNavigationContextVariables = new Dictionary <string, object> { { CONFIG_LOCATION_KEY, childNode.Location } } }; actions.Add(wa.ActionId, wa); } } }
public async override Task <RunResult> Run(WorkflowState workflowState) { var currentlyConnectedPlayers = (ICollection <MinecraftPlayer>)workflowState.Payload; UntrackOldPlayers(currentlyConnectedPlayers); var newlyConnectedPlayers = currentlyConnectedPlayers.Where(currentlyConnectedPlayer => !WasPreviouslyConnected(currentlyConnectedPlayer)).ToList(); if (!newlyConnectedPlayers.Any()) { return(new RunResult(false)); } var firstNewPlayer = newlyConnectedPlayers.First(); //workflowParameters.Add("MinecraftPlayerConnected", new WorkflowParameter<string>("MinecraftPlayerConnected", firstNewPlayer.Name)); TrackNewPlayer(firstNewPlayer); return(new RunResult()); }
public async void TestProcessNoData() { // Arrange var stepName = "processorName"; var step = new Step <SimpleWorkflowState>(name: stepName, processor: _testProcessor); var state = new WorkflowState <SimpleWorkflowState>(); // Act var result = await step.Process(state); var chain = result.WorkflowChain; var firstLink = chain.First(); // Assert Assert.Single(chain); Assert.Equal(stepName, firstLink.StepName); Assert.Equal(0, firstLink.SequenceNumber); }
public async void TestWorfklowException() { // Arrange var stepName = "processorName"; var mockProcessor = new Mock <IProcessor <SimpleWorkflowState> >(); mockProcessor.Setup(x => x.Process(It.IsAny <SimpleWorkflowState>())) .Throws(new Exception()); var step = new Step <SimpleWorkflowState>(name: stepName, processor: mockProcessor.Object); var link1 = new WorkflowChainLink() { SequenceNumber = 0, StepName = "first" }; link1.SetStateSnapshot(5); var workflowChain = new LinkedList <WorkflowChainLink>(); workflowChain.AddLast(link1); var workflowState = new WorkflowState <SimpleWorkflowState> { State = new SimpleWorkflowState() { MyInteger = 1 }, WorkflowChain = workflowChain }; // Act var result = await Assert.ThrowsAsync <WorkflowActionException <SimpleWorkflowState> >(async() => await step.Process(workflowState)); var link = result.WorkflowState.WorkflowChain.Last.Value; // Assert Assert.Equal(workflowState.State.MyInteger, result.WorkflowState.State.MyInteger); Assert.Equal(StepActivityStages.Executing, link.StepActivities.First().Activity); Assert.Equal(StepActivityStages.ExecutionFailed, link.StepActivities.Last().Activity); }
internal static void DeleteWorkflowState(int WorkflowStateId, int WorkflowId) { try { WorkflowState wState = GetAllStatesbyWorkflowID(WorkflowId).Where(a => a.StateID == WorkflowStateId).FirstOrDefault(); if (wState != null && !wState.IsFirst && !wState.IsLast) { ClearAllWorkflowStatePermissionsByStateID(wState.StateID); wState.Delete(); List <WorkflowState> wStates = GetAllStatesbyWorkflowID(WorkflowId).OrderBy(o => o.Order).ToList(); if (wStates.Count >= 2) { Workflow wflow = GetWorkflowbyID(WorkflowId); UpdateSatesOrder(wStates, wflow, false, wState.Order); CacheFactory.Clear(CacheFactory.Keys.Workflow); } } } catch (Exception ex) { Exceptions.LogException(ex); } }
public ItemWorkflowModel(Item i) { if (i != null) { _contextItem = i; _database = i.Database; if (_database != null) { _workflowProvider = _database.WorkflowProvider; if (_workflowProvider != null) { _workflow = _workflowProvider.GetWorkflow(ContextItem); if (_workflow != null) { _workflowState = _workflow.GetState(ContextItem); } } } } }
protected virtual void DisplayState(IWorkflow workflow, WorkflowState state, DataUri[] items, Control control, int offset, int pageSize) { if (items.Length > 0) { int length = offset + pageSize; if (length > items.Length) { length = items.Length; } for (int i = offset; i < length; i++) { DataUri uri = items[i]; Item item = Context.ContentDatabase.Items[uri]; if (item != null) { this.CreateItem(workflow, item, control); } } Border child = new Border { Background = "#e9e9e9" }; control.Controls.Add(child); child.Margin = "0px 4px 0px 16px"; child.Padding = "2px 8px 2px 8px"; child.Border = "1px solid #999999"; foreach (WorkflowCommand command in WorkflowFilterer.FilterVisibleCommands(workflow.GetCommands(state.StateID))) { XmlControl webControl = Resource.GetWebControl("WorkboxCommand") as XmlControl; webControl["Header"] = command.DisplayName + " " + Translate.Text("(selected)"); webControl["Icon"] = command.Icon; webControl["Command"] = "workflow:sendselected(command=" + command.CommandID + ",ws=" + state.StateID + ",wf=" + workflow.WorkflowID + ")"; child.Controls.Add(webControl); webControl = Resource.GetWebControl("WorkboxCommand") as XmlControl; webControl["Header"] = command.DisplayName + " " + Translate.Text("(all)"); webControl["Icon"] = command.Icon; webControl["Command"] = "workflow:sendall(command=" + command.CommandID + ",ws=" + state.StateID + ",wf=" + workflow.WorkflowID + ")"; child.Controls.Add(webControl); } } }
public async override Task <RunResult> Run(WorkflowState workflowState) { using (_client = new TcpClient()) { if (!Connect()) { return(new RunResult(false)); } SendHandshakePacket(); //Send a "Status Request" packet //http://wiki.vg/Server_List_Ping#Ping_Process Flush(0); var buffer = new byte[4096]; _stream.Read(buffer, 0, buffer.Length); try { var length = ReadVarInt(buffer); var packet = ReadVarInt(buffer); var jsonLength = ReadVarInt(buffer); var json = ReadString(buffer, jsonLength); var ping = JsonConvert.DeserializeObject <PingPayload>(json); if (ping.Players.Online > 0) { workflowState.Payload = ping.Players.Sample.Select(t => new MinecraftPlayer { Name = t.Name, Id = t.Id }).ToList(); } } catch (IOException) { //If an IOException is thrown then the server didn't //send us a VarInt or sent us an invalid one. return(RunResult.Failed); } finally { Disconnect(); } return(RunResult.Passed); } }
private void SendNotificationsToReviewers(ContentItem contentItem, WorkflowState state, StateTransaction stateTransaction, WorkflowActionTypes workflowActionType, PortalSettings portalSettings) { try { if (!state.SendNotification && !state.SendNotificationToAdministrators) { return; } var reviewers = GetUserAndRolesForStateReviewers(portalSettings, state); if (!reviewers.Roles.Any() && !reviewers.Users.Any()) { return; // If there are no receivers, the notification is avoided } var workflowAction = GetWorkflowActionInstance(contentItem, workflowActionType); if (workflowAction == null) { return; } var message = workflowAction.GetActionMessage(stateTransaction, state); var notification = new Notification { NotificationTypeID = _notificationsController.GetNotificationType(ContentWorkflowNotificationType).NotificationTypeId, Subject = message.Subject, Body = message.Body, IncludeDismissAction = true, SenderUserID = stateTransaction.UserId, Context = GetWorkflowNotificationContext(contentItem, state) }; _notificationsController.SendNotification(notification, portalSettings.PortalId, reviewers.Roles.ToList(), reviewers.Users.ToList()); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); } }
public WorkflowState AutoInvoke() { if (CanAutoTrigger()) { var toState = ToState; var newWorkflowState = new WorkflowState(toState, Workflow.CurrentState.Initiator); if (ResetInitiator) { newWorkflowState.Initiator = newWorkflowState.Initiator; //auto never changes initiatior i think.. } if (_onTransitioned != null) { _onTransitioned(this); } return(newWorkflowState); } return(null); }
public void UpdateWorkflowState(WorkflowState state) { Requires.NotNull("state", state); Requires.PropertyNotNegative("state", "StateID", state.StateID); Requires.PropertyNotNullOrEmpty("state", "StateName", state.StateName); using (var context = DataContext.Instance()) { var rep = context.GetRepository <WorkflowState>(); if (DoesExistWorkflowState(state, rep)) { throw new WorkflowStateNameAlreadyExistsException(); } rep.Update(state); } DataCache.RemoveCache(GetWorkflowStateKey(state.StateID)); DataCache.RemoveCache(WorkflowRepository.GetWorkflowItemKey(state.WorkflowID)); CacheWorkflowState(state); }
private void onHostChanged(WorkflowState state, List <Project> projects) { Debug.Assert(comboBoxProjects.Items.Count == 0); foreach (var project in projects) { comboBoxProjects.Items.Add(project); } if (comboBoxProjects.Items.Count > 0) { enableComboBox(comboBoxProjects); } labelWorkflowStatus.Text = "Projects loaded"; Trace.TraceInformation(String.Format( "[MainForm.Workflow] Host changed. Loaded {0} projects", projects.Count)); Trace.TraceInformation(String.Format( "[MainForm.Workflow] Current user details: Id: {0}, Name: {1}, Username: {2}", state.CurrentUser.Id.ToString(), state.CurrentUser.Name, state.CurrentUser.Username)); }
protected void InternalContinue(WorkflowContinuation <T> wc, T data) { while ((wc.WorkflowStep < workflowItems.Count) && !wc.Abort && !wc.Defer && !wc.Done) { WorkflowState state = workflowItems[wc.WorkflowStep++].Execute(wc, data); switch (state) { case WorkflowState.Abort: wc.Abort = true; break; case WorkflowState.Defer: wc.Defer = true; break; case WorkflowState.Done: wc.Done = true; break; } } }
/// <summary> /// Route the request. If no route exists, the workflow continues, otherwise, we return the route handler's continuation state. /// </summary> public WorkflowState Route(WorkflowContinuation <ContextWrapper> workflowContinuation, ContextWrapper wrapper) { WorkflowState ret = WorkflowState.Continue; RouteEntry entry = null; Session session = sessionManager != null ? sessionManager[wrapper.Context] : null; PathParams parms = null; // Makes debugging easier to declare these variable here. string verb = wrapper.Context.Verb(); string path = wrapper.Context.Path(); if (routeTable.TryGetRouteEntry(verb, path, wrapper.Context.Request.ContentType, out entry, out parms)) { if (entry.RouteHandler != null) { ret = entry.RouteHandler(workflowContinuation, wrapper, session, parms); } } return(ret); }
private void WritePreHistory(Guid demandId, Budget2DataContext context, WorkflowState initialState, WorkflowState destinationState, Guid?expectedInitiatorId, WorkflowCommand command, WorkflowState startState) { if (initialState.Order < startState.Order) { return; } var billDemndHistoryItem = new DemandTransitionHistory { Id = Guid.NewGuid(), DemandId = demandId, DestinationStateId = destinationState.DbStateId.Value, InitialStateId = initialState.DbStateId.Value, TransitionExpectedInitiatorId = expectedInitiatorId, CommandId = command.Id, Comment = string.Empty, Description = string.Empty }; context.DemandTransitionHistories.InsertOnSubmit(billDemndHistoryItem); }
public bool AppointmentsUpdate(string globalId, WorkflowState workflowState, string body, string expectionString, string response) { try { using (var db = GetContextO()) { var match = db.appointments.SingleOrDefault(x => x.global_id == globalId); if (match == null) { return(false); } match.workflow_state = workflowState.ToString(); match.updated_at = DateTime.Now; match.completed = 0; #region match.body = body ... if (body != null) { match.body = body; } #endregion match.response = response; match.expectionString = expectionString; match.version = match.version + 1; db.SaveChanges(); db.appointment_versions.Add(MapAppointmentVersions(match)); db.SaveChanges(); return(true); } } catch (Exception ex) { log.LogException("Not Specified", t.GetMethodName() + " failed", ex, false); return(false); } }
private void SendNotificationToAuthor(StateTransaction stateTransaction, WorkflowState state, Entities.Workflow workflow, ContentItem contentItem, WorkflowActionTypes workflowActionType) { try { var user = GetUserThatHaveStartedOrSubmittedDraftState(workflow, contentItem, stateTransaction); if (user == null) { Services.Exceptions.Exceptions.LogException(new WorkflowException(Localization.GetExceptionMessage("WorkflowAuthorNotFound", "Author cannot be found. Notification won't be sent"))); return; } if (user.UserID == stateTransaction.UserId) { return; } var workflowAction = GetWorkflowActionInstance(contentItem, workflowActionType); if (workflowAction == null) { return; } var message = workflowAction.GetActionMessage(stateTransaction, state); var notification = new Notification { NotificationTypeID = _notificationsController.GetNotificationType(ContentWorkflowNotificationNoActionType).NotificationTypeId, Subject = message.Subject, Body = message.Body, IncludeDismissAction = true, SenderUserID = stateTransaction.UserId }; _notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); } }
/// <summary> /// Gets the workflow history for the current item /// </summary> /// <returns>A list of all workflow events.</returns> /// <remarks>Because of versioning, there are duplicate item created workflow events. This method filters /// those duplicates out.</remarks> public List <Tuple <DateTime, string, bool> > GetWorkflowHistory(ID itemID) { var completeWorkflowHistory = new List <Tuple <DateTime, string, bool> >(); try { var masterDb = Sitecore.Data.Database.GetDatabase(Informa.Library.Utilities.References.Constants.MasterDb); var currentItem = masterDb.GetItem(itemID); bool addedFirstEvent = false; // versions are in a 1-based array; if you give it "0", it will give you the most recent. for (int i = 1; i < currentItem.Versions.Count + 1; i++) { Item thisVersion = currentItem.Versions[new Sitecore.Data.Version(i)]; IWorkflow workflow = masterDb.WorkflowProvider.GetWorkflow(thisVersion[FieldIDs.Workflow]); if (workflow != null) { List <WorkflowEvent> events = workflow.GetHistory(thisVersion).ToList(); if (addedFirstEvent) { WorkflowState firstState = workflow.GetStates()[0]; events.RemoveAll(e => e.OldState == "" && e.NewState == firstState.StateID); addedFirstEvent = true; } addedFirstEvent = true; completeWorkflowHistory.AddRange(events.Select(s => new Tuple <DateTime, string, bool>(s.Date, s.NewState, workflow.GetStates()[0].FinalState))); } } } catch (Exception exception) { Sitecore.Diagnostics.Log.Error(exception.ToString(), this); } return(completeWorkflowHistory); }
private WorkflowEvent[] AddItemHistory(Mock <Item> item, ID[] workflowStates) { WorkflowEvent[] events = null; if (workflowStates.Length == 0) { events = new WorkflowEvent[0]; } else { events = new WorkflowEvent[workflowStates.Length - 1]; for (var i = 0; i < workflowStates.Length - 1; i++) { events[i] = new WorkflowEvent(workflowStates[i].ToString(), workflowStates[i + 1].ToString(), "comment", "user", DateTime.UtcNow); } } var workflow = Mock.Of <IWorkflow>(x => x.GetHistory(item.Object) == events ); var initialStateId = ID.NewID.ToString(); if (workflowStates.Length > 0) { initialStateId = workflowStates[workflowStates.Length - 1].ToString(); } var workflowState = new WorkflowState(initialStateId, "state", "icon", true); var itemState = new Mock <ItemState>(item.Object); itemState.Setup(x => x.GetWorkflow()).Returns(workflow); itemState.Setup(x => x.GetWorkflowState()).Returns(workflowState); item.Setup(x => x.State).Returns(itemState.Object); return(events); }
protected override async Task <WorkflowState <T> > ExecuteExtensionProcess(WorkflowState <T> workflowState) { for (var i = 0; i < _iterationCount; i++) { try { await Iterate(workflowState); } catch (ContinueException) { _currentIteration++; continue; } catch (BreakException) { break; } _currentIteration++; } return(workflowState); }
private WorkflowState GetNextWorkflowState(Entities.Workflow workflow, int stateId) { WorkflowState nextState = null; var states = workflow.States.OrderBy(s => s.Order); int index; // locate the current state for (index = 0; index < states.Count(); index++) { if (states.ElementAt(index).StateID == stateId) { break; } } index = index + 1; if (index < states.Count()) { nextState = states.ElementAt(index); } return(nextState ?? workflow.FirstState); }
public async Task <T> Run(IWorkflowManager manager = null) { if (manager == null) { manager = new DefaultWorkflowManager(); } Logger.SetContext(Id); manager.StartWorkflow(this); Logger.Info("Start workflow"); Logger.Info("Validate"); Validate(); Logger.Info("Workflow pending"); try { var result = await Execute(); if (Aborted) { manager.EndWorkflow(this); Logger.Warn("Workflow aborted"); return(result); } State = WorkflowState.Resolved; manager.EndWorkflow(this); Logger.Info("Workflow completed"); return(result); } catch (Exception error) { State = WorkflowState.Failed; manager.EndWorkflow(this); Logger.Warn($"Workflow failed: {error}"); throw; } }
public async void TestSelectorSetOptionsInConstructorAndSelect() { // Arrange var selector = new Selector <SimpleWorkflowState>(stepSettings: new StepSettings() { AutoProgress = true }, stepSelector: _stepSelector); var selectedStepName = "selectedStepName"; var options = new List <Step <SimpleWorkflowState> >() { new Step <SimpleWorkflowState>(), new Step <SimpleWorkflowState>(name: selectedStepName, processor: _processor) }; var workflowState = new WorkflowState <SimpleWorkflowState>(); // Act selector.SetOptions(options); await selector.Process(workflowState); // Assert Assert.Equal(2, workflowState.WorkflowChain.Count); Assert.Equal(selectedStepName, workflowState.WorkflowChain.Last.Value.StepName); }
private void MoveState(WorkflowState state, int targetIndex, int currentIndex) { if (currentIndex == targetIndex) { return; } var moveUp = currentIndex < targetIndex; var numberOfMovements = moveUp ? targetIndex - currentIndex : currentIndex - targetIndex; for (var i = 0; i < numberOfMovements; i++) { if (moveUp) { MoveWorkflowStateUp(state.StateID); } else { MoveWorkflowStateDown(state.StateID); } } }
// The main datasource and its subitem updates public void datasourceUpdate(Item item, WorkflowState newState) { bool canWrite = Sitecore.Data.Database.GetDatabase("master").SelectItems(item.Paths.FullPath)[0].Security.CanWrite(Sitecore.Context.User); if (item == null || !canWrite) { return; } Helper.UpdateItemInformation(item, newState); if (item.HasChildren) { // First child of Datasource foreach (Item child1 in item.Children) { Helper.UpdateItemInformation(child1, newState); // Second Child if (child1.HasChildren) { foreach (Item child2 in child1.Children) { Helper.UpdateItemInformation(child2, newState); // Third Child if (child2.HasChildren) { foreach (Item child3 in child2.Children) { Helper.UpdateItemInformation(child3, newState); } } } } } } }
public async Task <WorkflowState <TState> > Execute(WorkflowState <TState> workflowState) { var currentLink = CreateWorkflowChainLink(workflowState); try { workflowState.State = await Process(workflowState.State); if (_stepSettings?.TrackStateChanges ?? false) { TakeDataSnapShot(workflowState, currentLink); } await ExecuteExtensionProcess(workflowState); AddActivityToWorkflowChainLink(StepActivityStages.ExecutionCompleted, currentLink); } catch (LoopJumpException) { throw; } catch (TerminateWorkflowException) { AddActivityToWorkflowChainLink(StepActivityStages.ExecutionTerminated, currentLink); } catch (Exception exception) { AddActivityToWorkflowChainLink(StepActivityStages.ExecutionFailed, currentLink); throw new WorkflowActionException <TState>("Exception in Process Flow execution. See InnerException for details.", exception, workflowState); } if (_stepSettings?.AutoProgress ?? false) { return(await ExecuteNext(workflowState)); } return(workflowState); }
internal static void stateTransition(ActorApprovalType approvalType, SNAP_Workflow wf, WorkflowState from, WorkflowState to) { // // !!! if the state completion date is null, it is the WF current state !!! // // a brand new apporval WF has from not-active to not-active state and have not pref state yet, // such as when creating a new manager, team and techical approval workflow. // Rememeber that: the accessTeamWF has prev state because it being inserted by the // store procedure when inserting the request the first time var prevDueDate = DateTime.Now; SNAP_Workflow_State prevWFState=null; if (from != WorkflowState.Not_Active) { // complete current/prev state prevWFState = wf.SNAP_Workflow_States.Single( s => s.workflowStatusEnum == (byte)from && s.completedDate == null); // To prevent looping in old state, null date is the latest state if (prevWFState != null) { prevWFState.completedDate = DateTime.Now; prevDueDate = prevWFState.dueDate ?? DateTime.Now; } } // create new state var newState = new SNAP_Workflow_State() { completedDate = null, //notifyDate = DateTime.Now, dueDate = getDueDate(approvalType, from, to), workflowStatusEnum = (byte)to }; // we don't need to notify workflow admin/access team. they have to monitor the open request constantly if (approvalType == ActorApprovalType.Workflow_Admin) { newState.notifyDate = DateTime.Now; } else if (from == WorkflowState.Not_Active && to == WorkflowState.Pending_Approval) { // approval wf from not-active -> pending approval, we alread send the email out newState.notifyDate = DateTime.Now; } if (prevWFState != null) { newState.notifyDate = prevWFState.notifyDate; // just propergate the notify date to new state...it is primarily for approval manager } // for end/close states set the completion date checkToCloseWorkflowAdimStates(approvalType, to, newState, prevDueDate); // workflowstate.approved is end state for manger, team approval and techical aproval but not for workflow adim checkToCloseMangerOrTeamOrTechnicalWorkflowStates(approvalType, to, newState, prevDueDate); // go to new state wf.SNAP_Workflow_States.Add(newState); }
private static void checkToCloseMangerOrTeamOrTechnicalWorkflowStates(ActorApprovalType approvalType, WorkflowState to, SNAP_Workflow_State newState, DateTime dueDate) { if (approvalType != ActorApprovalType.Workflow_Admin) { if (to == WorkflowState.Approved || to == WorkflowState.Closed_Denied) { newState.completedDate = DateTime.Now; newState.dueDate = dueDate; } } }
private static void checkToCloseWorkflowAdimStates(ActorApprovalType approvalType, WorkflowState to, SNAP_Workflow_State newState, DateTime dueDate) { if (approvalType == ActorApprovalType.Workflow_Admin) { if (to == WorkflowState.Closed_Cancelled || to == WorkflowState.Closed_Completed || to == WorkflowState.Closed_Denied || to == WorkflowState.Closed_Abandon) { newState.completedDate = DateTime.Now; newState.dueDate = dueDate; } } }
public void AddHistoryChange(WorkflowState state) { StateChangeHistory.Add(new StateHistory {State = state, Changed = DateTime.Now}); }
private void verifyWorkflowTransition(SNAP_Workflow wf, WorkflowState fr, WorkflowState to) { verifyWorkflowStateComplete(wf, fr); verifyWorkflowState(wf, to); }
private bool reqStateTransition(SNAP_Request req, RequestState reqFr, RequestState reqTo, SNAP_Workflow accessTeamWF, WorkflowState wfFr, WorkflowState wfTo) { var result = false; if (req.statusEnum == (byte)reqFr) { var accessTeamWFState = accessTeamWF.SNAP_Workflow_States.Single(s => s.completedDate == null); if (accessTeamWFState.workflowStatusEnum == (byte)wfFr) { stateTransition(ActorApprovalType.Workflow_Admin, accessTeamWF,wfFr,wfTo); if (reqFr != reqTo) { req.statusEnum = (byte) reqTo; req.lastModifiedDate = DateTime.Now; } result = true; } } return result; }
private void verifyWorkflowState(SNAP_Workflow wf, WorkflowState state) { Assert.IsTrue(wf.SNAP_Workflow_States.Count( s => s.workflowStatusEnum == (byte) state) == 1); }
public BuilderActor(int actorId, string userId, string displayName, bool isDefault, bool isSelected, ActorGroupType actorGroupType, WorkflowState workflowState) { this.ActorId = actorId; this.UserId = userId; this.DisplayName = displayName; this.IsDefault = isDefault; this.IsSelected = isSelected; this.ActorGroupType = actorGroupType; this.WorkflowState = workflowState; }
private DataUri[] GetItems(WorkflowState state, IWorkflow workflow) { ArrayList list = new ArrayList(); DataUri[] items = workflow.GetItems(state.StateID); if (items != null) { foreach (DataUri uri in items) { Item item = Context.ContentDatabase.Items[uri]; if ((((item != null) && item.Access.CanRead()) && (item.Access.CanReadLanguage() && item.Access.CanWriteLanguage())) && ((Context.IsAdministrator || item.Locking.CanLock()) || item.Locking.HasLock())) { list.Add(uri); } } } return (list.ToArray(typeof(DataUri)) as DataUri[]); }
public void Store(string key, WorkflowState state) { _store[key] = state; }
private void verifyWorkflowStateComplete(SNAP_Workflow wf, WorkflowState state) { Assert.IsTrue(wf.SNAP_Workflow_States.Single(s => s.workflowStatusEnum == (byte)state).completedDate != null); }
/// <summary> /// Displays the state. /// </summary> /// <param name="workflow"> /// The workflow. /// </param> /// <param name="state"> /// The state. /// </param> /// <param name="items"> /// The items. /// </param> /// <param name="control"> /// The control. /// </param> /// <param name="offset"> /// The offset. /// </param> /// <param name="pageSize"> /// Size of the page. /// </param> protected virtual void DisplayState(IWorkflow workflow, WorkflowState state, DataUri[] items, System.Web.UI.Control control, int offset, int pageSize) { Assert.ArgumentNotNull(workflow, "workflow"); Assert.ArgumentNotNull(state, "state"); Assert.ArgumentNotNull(items, "items"); Assert.ArgumentNotNull(control, "control"); if ((int)items.Length > 0) { int length = offset + pageSize; if (length > (int)items.Length) { length = (int)items.Length; } for (int i = offset; i < length; i++) { DataUri dataUri = items[i]; Item item = Context.ContentDatabase.Items[dataUri]; if (item != null) { this.CreateItem(workflow, item, control); } } Border border = new Border(); border.Background = "#e9e9e9"; Border border1 = border; control.Controls.Add(border1); border1.Margin = "0px 4px 0px 16px"; border1.Padding = "2px 8px 2px 8px"; border1.Border = "1px solid #999999"; WorkflowCommand[] workflowCommandArray = WorkflowFilterer.FilterVisibleCommands(workflow.GetCommands(state.StateID)); for (int j = 0; j < (int)workflowCommandArray.Length; j++) { WorkflowCommand workflowCommand = workflowCommandArray[j]; XmlControl webControl = Resource.GetWebControl("WorkboxCommand") as XmlControl; Assert.IsNotNull(webControl, "workboxCommand is null"); webControl["Header"] = string.Concat(workflowCommand.DisplayName, " ", Translate.Text("(selected)")); webControl["Icon"] = workflowCommand.Icon; string[] commandID = new string[] { "workflow:sendselected(command=", workflowCommand.CommandID, ",ws=", state.StateID, ",wf=", workflow.WorkflowID, ")" }; webControl["Command"] = string.Concat(commandID); border1.Controls.Add(webControl); webControl = Resource.GetWebControl("WorkboxCommand") as XmlControl; Assert.IsNotNull(webControl, "workboxCommand is null"); webControl["Header"] = string.Concat(workflowCommand.DisplayName, " ", Translate.Text("(all)")); webControl["Icon"] = workflowCommand.Icon; string[] strArrays = new string[] { "workflow:sendall(command=", workflowCommand.CommandID, ",ws=", state.StateID, ",wf=", workflow.WorkflowID, ")" }; webControl["Command"] = string.Concat(strArrays); border1.Controls.Add(webControl); } } }
/// <summary> /// Gets the items. /// </summary> /// <param name="state"> /// The state. /// </param> /// <param name="workflow"> /// The workflow. /// </param> /// <returns> /// Array of item DataUri. /// </returns> private DataUri[] GetItems(WorkflowState state, IWorkflow workflow) { Assert.ArgumentNotNull(state, "state"); Assert.ArgumentNotNull(workflow, "workflow"); ArrayList arrayLists = new ArrayList(); DataUri[] items = workflow.GetItems(state.StateID); if (items != null) { DataUri[] dataUriArray = items; for (int i = 0; i < (int)dataUriArray.Length; i++) { DataUri dataUri = dataUriArray[i]; Item item = Context.ContentDatabase.Items[dataUri]; if (item != null && item.Access.CanRead() && item.Access.CanReadLanguage() && item.Access.CanWriteLanguage() && (Context.IsAdministrator || item.Locking.CanLock() || item.Locking.HasLock())) { arrayLists.Add(dataUri); } } } return arrayLists.ToArray(typeof(DataUri)) as DataUri[]; }
public static bool SendTaskEmail(EmailTaskType taskType, string toEmailAddress, string toName, long requestId, string affectedEndUser, WorkflowState workflowState, string reason) { string recipientName = string.Empty; string followPageName = string.Empty; string subjectAction = GetSubjectAction; string templatePath = Utilities.AbsolutePath; switch (taskType) { case EmailTaskType.AccessTeamAcknowledge: recipientName = "Access Team"; followPageName = PageNames.ACCESS_TEAM; subjectAction += "Acknowledgement Needed"; templatePath += ConfigurationManager.AppSettings["Acknowledgement"]; break; case EmailTaskType.OverdueApproval: recipientName = toName; followPageName = PageNames.APPROVING_MANAGER; subjectAction += "Approval Reminder"; templatePath += ConfigurationManager.AppSettings["NagApproval"]; break; /* case EmailTaskType.OverdueApprovalCC: recipientName = toName; followPageName = PageNames.APPROVING_MANAGER; subjectAction = string.Format("{0}Approval is Overdue (FYI: You are copied on this email)", subjectAction); templatePath += ConfigurationManager.AppSettings["NagApproval"]; break; */ case EmailTaskType.OverdueChangeRequested: recipientName = toName; followPageName = PageNames.USER_VIEW; subjectAction += "Change Requested Reminder"; templatePath += ConfigurationManager.AppSettings["NagChangeRequested"]; break; case EmailTaskType.AssignToApprover: recipientName = toName; followPageName = PageNames.APPROVING_MANAGER; subjectAction += "Approval Needed"; templatePath += ConfigurationManager.AppSettings["Approval"]; break; case EmailTaskType.ProxyForAffectedEndUser: recipientName = toName; followPageName = PageNames.USER_VIEW; subjectAction += "Submitted"; templatePath += ConfigurationManager.AppSettings["RequestorForAEU"]; break; case EmailTaskType.TransitionToPendingProvisioning: recipientName = "Access Team"; followPageName = PageNames.ACCESS_TEAM; subjectAction += "Pending Provisioning"; templatePath += ConfigurationManager.AppSettings["TransitionToPendingProvisioning"]; break; case EmailTaskType.UpdateRequester: recipientName = toName; switch (workflowState) { case WorkflowState.Pending_Acknowledgement: subjectAction += "Submitted"; followPageName = PageNames.USER_VIEW; templatePath += ConfigurationManager.AppSettings["ConfirmSubmitToSubmitter"]; break; case WorkflowState.Closed_Completed: subjectAction += "Completed"; followPageName = PageNames.USER_VIEW; templatePath += ConfigurationManager.AppSettings["CompleteToSubmitter"]; break; case WorkflowState.Change_Requested: subjectAction += "Change Has Been Requested"; followPageName = PageNames.REQUEST_FORM; templatePath += ConfigurationManager.AppSettings["RequestChangeToSubmitter"]; break; case WorkflowState.Closed_Denied: subjectAction += "Denied"; followPageName = PageNames.USER_VIEW; templatePath += ConfigurationManager.AppSettings["DenyToSubmitter"]; break; case WorkflowState.Closed_Cancelled: subjectAction += "Cancelled"; followPageName = PageNames.USER_VIEW; templatePath += ConfigurationManager.AppSettings["DenyToSubmitter"]; break; case WorkflowState.Closed_Abandon: subjectAction += "Abandoned"; followPageName = PageNames.USER_VIEW; templatePath += ConfigurationManager.AppSettings["DenyToSubmitter"]; break; } break; } Hashtable bodyParameters = new Hashtable() { {"ROOT_PATH", Utilities.WebRootUrl}, {"IMAGE_PATH", Utilities.ImagePath}, {"RECIPIENT_NAME", recipientName}, {"AFFECTED_END_USER", affectedEndUser}, {"FOLLOW_URL", Utilities.WebRootUrl + followPageName + ".aspx?requestId=" + requestId}, {"REASON", reason}, {"REQUEST_ID", requestId} }; return SendEmail(toEmailAddress, subjectAction, templatePath, bodyParameters); }
protected bool wfStateChange(ActorApprovalType approvalType, WorkflowState toState) { var wf = db.SNAP_Workflows.Single(w => w.pkId == Id); if (wf.SNAP_Request.statusEnum != (byte)RequestState.Pending) return false; var currentState = wf.SNAP_Workflow_States.Single(s => s.completedDate == null); AccessRequest.stateTransition(approvalType, wf, (WorkflowState)currentState.workflowStatusEnum, toState); // !!! because of this we are force to use TransactionScope // !!! so we can make sure every technical approver has approved which moves the request approved state db.SubmitChanges(); return true; }
private void initializeData(SNAPDatabaseDataContext db, WorkflowState state, out SNAP_Request req, out SNAP_Workflow accessTeamWF, out DateTime? dueDate) { req = db.SNAP_Requests.Single(r => r.pkId == _id); accessTeamWF = req.SNAP_Workflows.Single(x => x.actorId == AccessTeamActorId); dueDate = accessTeamWF.SNAP_Workflow_States.Single( s => s.completedDate == null && s.workflowStatusEnum == (byte)state).dueDate; }
/// <summary> /// Gets the state of the workflow items of. /// </summary> /// <param name="workFlow">The work flow.</param> /// <param name="workFlowState">State of the work flow.</param> /// <returns></returns> public static Hashtable GetWorkflowItemsOfState(IWorkflow workFlow, WorkflowState workFlowState) { Hashtable hashtable = new Hashtable(); foreach (DataUri dataUri in workFlow.GetItems(workFlowState.StateID)) { try { if (!hashtable.Contains((object)dataUri.ItemID.ToString())) hashtable.Add((object)dataUri.ItemID.ToString(), (object)dataUri.ItemID.ToString()); } catch (Exception ex) { Log.Error("GetWorkflowItemsOfState", ex, typeof(SitecoreHelper)); } } return hashtable; }
public void CopyFrom(PeopleContact peopleContact) { DistrictId = peopleContact.DistrictId; PhoneNumberPrefix2Id = peopleContact.PhoneNumberPrefix2Id; RegistrarId = peopleContact.RegistrarId; PhoneNumber2 = peopleContact.PhoneNumber2; Email1 = peopleContact.Email1; Email2 = peopleContact.Email2; Created = peopleContact.Created; FirstContacted = peopleContact.FirstContacted; Presented = peopleContact.Presented; BusinessInfoParticipated = peopleContact.BusinessInfoParticipated; TeamMeetingParticipated = peopleContact.TeamMeetingParticipated; Registrated = peopleContact.Registrated; PremiumMembershipGranted = peopleContact.PremiumMembershipGranted; Potential = peopleContact.Potential; MobileApplicationInstalledAndTrained = peopleContact.MobileApplicationInstalledAndTrained; ContactDead = peopleContact.ContactDead; FirstName = peopleContact.FirstName; LastName = peopleContact.LastName; Title = peopleContact.Title; City = peopleContact.City; PhoneNumberPrefix1Id = peopleContact.PhoneNumberPrefix1Id; PhoneNumber1 = peopleContact.PhoneNumber1; Skype = peopleContact.Skype; TrackingEmailSent = peopleContact.TrackingEmailSent; SecondContacted = peopleContact.SecondContacted; SecondMeeting = peopleContact.SecondMeeting; SecondTrackingEmailSent = peopleContact.SecondTrackingEmailSent; ThirdMeeting = peopleContact.ThirdMeeting; LoyaltySystemExplained = peopleContact.LoyaltySystemExplained; AccessGranted = peopleContact.AccessGranted; MoneyToPurchaseAccountSended = peopleContact.MoneyToPurchaseAccountSended; AbleToPurchase = peopleContact.AbleToPurchase; AutoCashback = peopleContact.AutoCashback; ShoppingPlanBackSet = peopleContact.ShoppingPlanBackSet; OwnUnitsContained = peopleContact.OwnUnitsContained; Tasks = peopleContact.Tasks; Note = peopleContact.Note; LyonessId = peopleContact.LyonessId; WorkflowState = peopleContact.WorkflowState; WorkflowStatePrevious = peopleContact.WorkflowStatePrevious; ConfirmTermsAndConditions = peopleContact.ConfirmTermsAndConditions; ConfirmPersonalData = peopleContact.ConfirmPersonalData; }
/// <summary> /// Gets the state of the workflow items of. /// </summary> /// <param name="workFlow">The work flow.</param> /// <param name="workFlowState">State of the work flow.</param> /// <param name="language">The language.</param> /// <returns></returns> public static List<string> GetWorkflowItemsOfState(IWorkflow workFlow, WorkflowState workFlowState, Language language) { List<string> list = new List<string>(); foreach (DataUri dataUri in workFlow.GetItems(workFlowState.StateID)) { try { if (dataUri.Language == language) { if (!list.Contains(dataUri.ItemID.ToString())) list.Add(dataUri.ItemID.ToString()); } } catch (Exception ex) { Log.Error("GetWorkflowItemsOfState", ex, typeof(SitecoreHelper)); } } return list; }
// Returns state's specific field or null if absent public static Field GetStateField(WorkflowState state, string fieldName) { using (new SecurityModel.SecurityDisabler()) { Database masterDb = Factory.GetDatabase(DbName); Item item = masterDb.GetItem(new ID(state.StateID)); return item != null ? item.Fields[fieldName] : null; } }
private static DateTime getDueDate(ActorApprovalType approvalType, WorkflowState fr, WorkflowState to) { int day = 1; DateTime due; SLAConfiguration slaCfg = new SLAConfiguration((NameValueCollection)ConfigurationManager.GetSection( "Apollo.AIM.SNAP/Workflow.SLA")); switch (approvalType) { case ActorApprovalType.Manager: day = System.Convert.ToInt16(slaCfg.ManagerApprovalInDays); break; case ActorApprovalType.Team_Approver: day = System.Convert.ToInt16(slaCfg.TeamApprovalInDays); break; case ActorApprovalType.Technical_Approver: day = System.Convert.ToInt16(slaCfg.TechnicalApprovalInDays); break; case ActorApprovalType.Workflow_Admin: if (to == WorkflowState.Workflow_Created) // same as the due day for technical approval since workflow admin depend on it day = System.Convert.ToInt16(slaCfg.TechnicalApprovalInDays); break; } using (var db = new SNAPDatabaseDataContext()) { due = db.udf_get_next_business_day(DateTime.Now, day) ?? DateTime.Now.AddDays(-1); } return due; }
public void SetCurrentState(WorkflowState workflowState) { _commentDocument.State = workflowState; _repository.Save(); }
public void RecordStateExit(WorkflowState workflowState) { _commentDocument.AddHistoryChange(workflowState); _repository.Save(); }
// Returns state's specific field value or null if absent public static string GetStateFieldValue(WorkflowState state, string fieldName) { Field field = GetStateField(state, fieldName); return field != null ? field.Value : null; }