internal WorkflowAction FirstJoint(WorkflowItem jumptedItem) { var trigger = new TriggerWorkflowAction(_triggeringItem); trigger.SetJumpedItem(jumptedItem); return(trigger); }
public InputOutputMismatchException(WorkflowItem from, WorkflowItem to, string fromName, string toName) { this.from = from; this.to = to; this.fromName = fromName; this.toName = toName; }
public static WorkflowBase Convert(Session Session, Type ConvertToType, WorkflowBase CurrentObject) { object newObject = Activator.CreateInstance(ConvertToType, Session); CurrentObject.CopyProperties(newObject); for (int i = CurrentObject.Items.Count - 1; i >= 0; i--) { var workflowItem = new WorkflowItem(Session); CurrentObject.Items[i].CopyProperties(workflowItem); (newObject as WorkflowBase).Items.Add(workflowItem); } for (int i = CurrentObject.Attachments.Count - 1; i >= 0; i--) { var workFlowAttachment = new WorkFlowAttachment(Session); CurrentObject.Attachments[i].CopyProperties(workFlowAttachment); (newObject as WorkflowBase).Attachments.Add(workFlowAttachment); } (newObject as WorkflowBase).ChildItems.Add(CurrentObject); (newObject as WorkflowBase).Tracking.Add(CreateTracking(newObject as WorkflowBase, string.Format("Converted from {0}", CurrentObject.No))); return(newObject as WorkflowBase); }
/// <summary> /// Submits a membership request to the specified group's /// moderation workflow for approval. /// </summary> /// <param name="member">The member information for the membership request</param> public void AddAModeratedMember(CommunityMember member) { // Define a unique reference representing the entity // under moderation. Note that this entity may be // transient or may not yet have been assigned a // unique identifier. Defining an item reference allows // you to bridge this gap. // For example: "members:/{group-id}/{user-reference}" var targetReference = CreateUri(member.GroupId, member.User); // Retrieve the workflow supporting moderation of // membership for the group to which the user is // being added. var moderationWorkflow = GetWorkflowFor(member.GroupId); // The workflow defines the intial (or 'start') state // for moderation. var initialState = moderationWorkflow.InitialState; // Create a new workflow item... var workflowItem = new WorkflowItem( WorkflowId.Create(moderationWorkflow.Id), // ...under the group's moderation workflow new WorkflowState(initialState), // ...in the workflow's initial state Reference.Create(targetReference) // ...identified with this reference ); var memberRequest = _memberAdapter.Adapt(member); try { _workflowItemService.Add(workflowItem, memberRequest); } catch (SocialAuthenticationException ex) { throw new SocialRepositoryException("The application failed to authenticate with Episerver Social.", ex); } catch (MaximumDataSizeExceededException ex) { throw new SocialRepositoryException( "The application request was deemed too large for Episerver Social.", ex); } catch (SocialCommunicationException ex) { throw new SocialRepositoryException("The application failed to communicate with Episerver Social.", ex); } catch (SocialException ex) { throw new SocialRepositoryException("Episerver Social failed to process the application request.", ex); } }
private WorkflowItem GetNextWorkflowItem(Repository repository, Workflow workflow, int workflowItemSequence) { WorkflowItem nextWorkflowItem = null; if (workflow != null && workflow.Items != null && workflow.Items.Length > 0) { nextWorkflowItem = workflow.Items.Where(it => it.Sequence == workflowItemSequence).FirstOrDefault(); } return(nextWorkflowItem); }
/// <summary> /// This method checks if Upload method should be executed. /// </summary> /// <param name="workflow">WorkflowItem to save</param> /// <returns>true if pre-condition check passed</returns> public static Tuple<bool, StoreActivitiesDC> CheckCanUpload(IWorkflowsQueryService proxy, WorkflowItem workflow) { StoreActivitiesDC workflowDC = DataContractTranslator.ActivityItemToStoreActivitiyDC(workflow); var workflowList = proxy.StoreActivitiesGetByName(workflowDC); //a new created workflow with duplicated name to be saved. if ((!workflow.IsOpenFromServer || workflow.Name != workflow.OriginalName) && workflowList.Count > 0) { MessageBoxService.CannotSaveDuplicatedNameWorkflow(workflow.Name); return new Tuple<bool, StoreActivitiesDC>(false, null); } StoreActivitiesDC latestWorkflow = workflowList.FirstOrDefault(); bool shouldContinue = false; StoreActivitiesDC workflowToOpen = null; if (latestWorkflow == null || latestWorkflow.InsertedDateTime <= workflowDC.UpdatedDateTime) { if (AuthorizationService.IsAdministrator(AuthorizationService.CurrentPrincipalFunc()) || (latestWorkflow == null) || (workflowDC.LockedBy == Environment.UserName)) { shouldContinue = true; } else { MessageBoxService.CannotSaveLockedActivity(); shouldContinue = false; } } else // there is a new version saved on server after user checked current one out { if (AuthorizationService.IsAdministrator(AuthorizationService.CurrentPrincipalFunc())) { if (MessageBoxService.CreateNewActivityOnSaving() == MessageBoxResult.Yes) { shouldContinue = true; } } else { if (MessageBoxService.DownloadNewActivityOnSaving() == MessageBoxResult.Yes) { workflowToOpen = latestWorkflow; } } } return new Tuple<bool, StoreActivitiesDC>(shouldContinue, workflowToOpen); }
public WorkflowItem GetWorkflowItemBySN(string serialNumber, String impersonateUser) { // if the serial number is null or empty we do not want to do any of this if (!string.IsNullOrEmpty(serialNumber)) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) { k2Connection.ImpersonateUser(impersonateUser); } var workCriteria = new WorklistCriteria { NoData = false, Platform = "ASP" }; if (!string.IsNullOrEmpty(serialNumber)) { workCriteria.AddFilterField(WCField.SerialNumber, WCCompare.Equal, serialNumber); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); WorkflowItem retItem = null; foreach (WorklistItem item in k2Worklist) { retItem = new WorkflowItem(item); } // now that we have the workflow item get the count of the related documents if ((retItem != null) && (!string.IsNullOrEmpty(retItem.PolicyID))) { using (DocumentService.DocumentServiceClient client = new DocumentService.DocumentServiceClient()) { retItem.RelatedDocumentCount = client.GetDocumentsCountForPolicy(retItem.PolicyID); } } return(retItem); } } return(null); }
public InitialConnection(WorkflowItem to, string toName) { if (!to.Inputs.ContainsKey(toName)) { throw new OutputNotFoundException(to, toName); } if (typeof(T) != to.Inputs[toName]) { throw new InputMismatchException(to, toName, typeof(T)); } To = to; ToName = toName; ContentType = to.Inputs[toName]; }
public WorkflowConnection(WorkflowItem from, WorkflowItem to, string fromName, string toName) { if (!from.Outputs.ContainsKey(fromName)) { throw new InputNotFoundException(from, fromName); } if (!to.Inputs.ContainsKey(toName)) { throw new OutputNotFoundException(to, toName); } if (from.Outputs[fromName] != to.Inputs[toName] && !from.Outputs[fromName].IsSubclassOf(to.Inputs[toName])) { throw new InputOutputMismatchException(from, to, fromName, toName); } From = from; To = to; FromName = fromName; ToName = toName; ContentType = from.Outputs[fromName]; }
public WorkflowItem BuildItem(HistoryEvent historyEvent, IEnumerable<HistoryEvent> history) { var eventId = historyEvent.GetInitialEventId(); var state = GetStatus(eventId, history); var item = new WorkflowItem { EventId = historyEvent.EventId, Kind = WorkflowItemKind.ActivityCancellation, State = state, Result = state == WorkflowItemState.Completed ? history.GetActivityResult(eventId) : null, Reason = state == WorkflowItemState.Failed ? history.GetActivityReason(eventId) : null, Details = state == WorkflowItemState.Failed || state == WorkflowItemState.Canceled ? history.GetActivityDetails(eventId) : null }; if (state == WorkflowItemState.CancelRequested) { var attributes = historyEvent.ActivityTaskCancelRequestedEventAttributes; var decisionId = historyEvent.ActivityTaskCancelRequestedEventAttributes.DecisionTaskCompletedEventId; item.Order = decisionId; item.Id = attributes.ActivityId; } else if (state == WorkflowItemState.CancelFailed) { var attributes = historyEvent.RequestCancelActivityTaskFailedEventAttributes; var decisionId = historyEvent.RequestCancelActivityTaskFailedEventAttributes.DecisionTaskCompletedEventId; item.Order = decisionId; item.Id = attributes.ActivityId; item.Reason = attributes.Cause; } return item; }
public static void Setup(IDocumentStore documentStore) { using (var storeSession = documentStore.OpenSession()) { var rootDocument = new WorkflowItem { Id = "rootDocumentId", Text = "Workflow 3", DisplayOrder = 0, }; storeSession.Store(rootDocument); var subTask1Start = new WorkflowItem { Id = "subTask1StartId", WorkflowId = rootDocument.Id, Text = "SubTask1", DisplayOrder = 0, }; storeSession.Store(subTask1Start); storeSession.SaveChanges(); } }
/// <summary> /// Save a workflow to an image representation /// </summary> /// <param name="workflow"></param> public void SaveToImageFile(WorkflowItem workflow) { if (workflow == null) { throw new ArgumentNullException("workflow"); } if (workflow.WorkflowDesigner != null) workflow.WorkflowDesigner.SaveWorkflowToBitmap(); }
/// <summary> /// Save focused workflow to server. /// </summary> /// <param name="workflow">The workflow to be saved.</param> // TODO: Changed to new Composite DataContract, needs to be verified public bool SaveToServer(WorkflowItem workflow) { bool isSuccess; IsBusy = true; BusyCaption = string.Format(UploadAsPrivateBusyMessage, workflow.Name, workflow.Version); isSuccess = this.UploadWorkflowWithBusy(workflow); workflow.HasMajorChanged = false; IsBusy = false; BusyCaption = String.Empty; return isSuccess; }
private void CreatePendingWorkflowItem(Repository repository, TextContent content, string userName, Workflow workflow, WorkflowItem workflowItem, string previousComment) { PendingWorkflowItem pendingWorkflowItem = new PendingWorkflowItem() { Repository = repository, Name = content.UUID, WorkflowName = workflow.Name, WorkflowItemSequence = workflowItem.Sequence, ItemDisplayName = workflowItem.DisplayName, RoleName = workflowItem.RoleName, ContentFolder = content.FolderName, ContentUUID = content.UUID, ContentSummary = content.GetSummary(), CreationUtcDate = DateTime.UtcNow, CreationUser = userName, PreviousComment = previousComment }; PendingWorkflowItemProvider.Add(pendingWorkflowItem); }
internal TriggerActions(WorkflowItem triggeringItem) { _triggeringItem = triggeringItem; }
public virtual void ProcessPendingWorkflowItem(Repository repository, string workflowName, string roleName, string pendingWorkflowItemId, string userName, bool passed, string comment) { var pendingItem = PendingWorkflowItemProvider.Get(new PendingWorkflowItem() { RoleName = roleName, Name = pendingWorkflowItemId, Repository = repository }); if (pendingItem != null) { var content = new TextFolder(repository, pendingItem.ContentFolder).CreateQuery().WhereEquals("UUID", pendingItem.ContentUUID).FirstOrDefault(); if (content != null) { var workflow = Get(repository, workflowName); bool finished = false; if (workflow != null) { WorkflowItem nextWorkflowItem = null; if (passed) { nextWorkflowItem = GetNextWorkflowItem(repository, workflow, pendingItem.WorkflowItemSequence + 1); if (nextWorkflowItem == null) { finished = true; } } else { nextWorkflowItem = GetNextWorkflowItem(repository, workflow, pendingItem.WorkflowItemSequence - 1); } if (nextWorkflowItem != null) { CreatePendingWorkflowItem(repository, content, userName, workflow, nextWorkflowItem, comment); } } if (finished) { var published = content.Published.HasValue ? content.Published.Value : false; if (passed && !published) { ServiceFactory.TextContentManager.Update(repository, new Schema(repository, content.SchemaName), content.UUID , new string[] { "Published" }, new object[] { true }, userName); } } WorkflowHistory history = new WorkflowHistory() { Id = WorkflowHistoryProvider.All(content).Count() + 1, Repository = repository, WorkflowName = pendingItem.WorkflowName, WorkflowItemSequence = pendingItem.WorkflowItemSequence, ItemDisplayName = pendingItem.ItemDisplayName, ContentFolder = pendingItem.ContentFolder, ContentUUID = pendingItem.ContentUUID, ContentSummary = content.GetSummary(), RoleName = pendingItem.RoleName, Passed = passed, ProcessingUtcDate = DateTime.UtcNow, ProcessingUser = userName, Finished = finished, Comment = comment }; WorkflowHistoryProvider.Add(history); } PendingWorkflowItemProvider.Remove(pendingItem); } }
/// <summary> /// Gets the detailed workflow view with items /// </summary> /// <param name="id">The workflow identifier.</param> /// <returns>DetailedWorkflow view with items.</returns> public DetailedWorkflow GetDetailedWorkflow(string id) { var response = new DetailedWorkflow(); var wfItem = this._masterDatabase.GetItem(new ID(id)); response.Id = wfItem.ID.ToString(); response.Name = wfItem.Name; List <Item> items = new List <Item>(); var index = ContentSearchManager.GetIndex(Constants.IndexNames.SitecoreMasterIndex); if (index != null) { foreach (var wfState in wfItem.Children.Where(t => t.TemplateID == Templates.WorkflowState.TemplateId)) { var state = new DetailedWorkflowState { Id = wfState.ID.ToString(), IsFinal = wfState[Templates.WorkflowState.Fields.Final] == "1", Name = wfState.Name }; using (var context = index.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck)) { var wfStateId = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(wfState.ID); var resultItems = context.GetQueryable <WorkflowSearchItem>().Where(p => p.WorkflowState == wfStateId && p.IsLatestVersion); var searchResultItems = resultItems.GetResults(); foreach (var resultItem in searchResultItems.Hits) { var item = this._masterDatabase.GetItem(resultItem.Document.ItemId, Language.Parse(resultItem.Document.Language)); if (item != null) { var workflowItem = new WorkflowItem() { ID = item.ID.ToString(), Name = item.Name, Language = resultItem.Document.Language ?? string.Empty, LastUpdated = item.Statistics?.Updated ?? DateTime.MinValue, LastUpdatedBy = item.Statistics?.UpdatedBy ?? string.Empty, TemplateName = item.TemplateName, HasLayout = item.Visualization?.Layout != null, CurrentVersion = item.Version.Number, Icon = GetIconUrl(item), NextStates = GetNextStates(item, wfState) }; var currentDbState = item[Constants.StandardFieldNames.WorkflowState]; if (currentDbState.Equals(wfState.ID.ToString(), StringComparison.OrdinalIgnoreCase)) { state.Items.Add(workflowItem); } else { // State is not matching in the index and in the db, maybe due to the async indexing operations // We still need to ensure the proper state var previousState = response.States.FirstOrDefault(t => t.Id.Equals(currentDbState)); if (previousState != null) { // Item state should point to a previous state previousState.Items.Add(new WorkflowItem() { ID = item.ID.ToString(), Name = item.Name, Language = resultItem.Document.Language ?? string.Empty, LastUpdated = item.Statistics?.Updated ?? DateTime.MinValue, LastUpdatedBy = item.Statistics?.UpdatedBy ?? string.Empty, TemplateName = item.TemplateName, HasLayout = item.Visualization?.Layout != null, CurrentVersion = item.Version.Number, Icon = GetIconUrl(item), NextStates = GetNextStates(item, this.GetItem(currentDbState)) }); } else { // Item itemsInWrongState.Add(new MemoryStoreItem { ItemId = item.ID.ToString(), State = currentDbState, Language = item.Language.Name }); } } } } foreach (var itemInWrongState in itemsInWrongState.Where(t => t.State.Equals(state.Id))) { var item = this._masterDatabase.GetItem(itemInWrongState.ItemId, Language.Parse(itemInWrongState.Language)); if (item != null) { var workflowItem = new WorkflowItem() { ID = item.ID.ToString(), Name = item.Name, Language = item.Language?.Name ?? string.Empty, LastUpdated = item.Statistics?.Updated ?? DateTime.MinValue, LastUpdatedBy = item.Statistics?.UpdatedBy ?? string.Empty, TemplateName = item.TemplateName, HasLayout = item.Visualization?.Layout != null, CurrentVersion = item.Version.Number, Icon = GetIconUrl(item), NextStates = GetNextStates(item, wfState) }; state.Items.Add(workflowItem); } } response.States.Add(state); } } } response.QuickFilters.Add("TemplateName", response.States?.SelectMany(t => t.Items).Select(t => t.TemplateName).Distinct()); response.QuickFilters.Add("LastUpdatedBy", response.States?.SelectMany(t => t.Items).Select(t => t.LastUpdatedBy).Distinct()); return(response); }
public OutputNotFoundException(WorkflowItem to, string toName) { this.to = to; this.toName = toName; }
public bool UploadWorkflowWithBusy(WorkflowItem workflow) { bool result = false; Utility.DoTaskWithBusyCaption("Saving...", () => { result = WorkflowsQueryServiceUtility.UsingClientReturn(client => { return UploadWorkflow(client, workflow); }); }, false); return result; }
public void CloseWorkflowItem(int index, WorkflowItem itemToClose) { RemoveWorkflowItemAndSetFocusedWorkflowItem(itemToClose); WorkflowItems.RemoveAt(index); }
public bool UploadWorkflow(IWorkflowsQueryService client, WorkflowItem workflow, bool shouldBeLoose = true) { StoreActivitiesDC workflowDC = null; ActivityAssemblyItem fakeLibrary = null; var checkResult = WorkflowUploader.CheckCanUpload(client, workflow); if (!checkResult.Item1 && checkResult.Item2 == null) { return false; } else if (!checkResult.Item1 && checkResult.Item2 != null) { workflowDC = checkResult.Item2; fakeLibrary = GetActivityLibraries(client, workflowDC); } if (shouldBeLoose) workflow.SetXamlCode(); var upResult = WorkflowUploader.Upload(client, workflow); if (upResult.Errorcode != 0) { ErrorMessageType = "Error Saving to Server"; ErrorMessage = upResult.ErrorMessage + "\r\n\r\nYour changes were not successfully saved to the server."; return false; } else { OnStoreActivitesUnlock(workflow, false); workflow.OriginalName = workflow.Name; workflow.OldVersion = workflow.Version; } if (workflowDC != null && fakeLibrary != null) { OpenStoreActivitiesDC(workflowDC, fakeLibrary); } if (this.FocusedWorkflowItem.Name == workflow.Name && this.FocusedWorkflowItem.Version == workflow.Version) this.FocusedWorkflowItem.TaskActivityGuid = workflow.TaskActivityGuid; return true; }
/// <summary> /// Unlock a workflow on query service /// </summary> /// <param name="workflowDC"></param> public void StoreActivitesUnlockWithBusy(WorkflowItem workflow, bool shouldUpdateNewVersion) { Utility.WithContactServerUI(() => { StoreActivitesUnlock(workflow, shouldUpdateNewVersion); }); }
public void StoreActivitesUnlock(WorkflowItem workflow, bool shouldUpdateNewVersion) { if (!workflow.IsReadOnly) { StoreActivitiesDC workflowDC = DataContractTranslator.ActivityItemToStoreActivitiyDC(workflow); WorkflowsQueryServiceUtility.UsingClient(client => { workflowDC.Name = workflow.OriginalName; workflowDC.Incaller = Assembly.GetExecutingAssembly().GetName().Name; workflowDC.IncallerVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); workflowDC.Locked = false; workflowDC.LockedBy = Environment.UserName; workflowDC.UpdatedDateTime = DateTime.UtcNow; workflowDC.Version = shouldUpdateNewVersion ? workflow.Version : workflow.OldVersion; var reply = client.StoreActivitiesSetLock(workflowDC, workflowDC.UpdatedDateTime); reply.CheckErrors(); }); } }
public void RegisterPostRouterWorkflow(WorkflowItem <PostRouteWorkflowData> item) { postRouteWorkflow.AddItem(item); }
public static WorkflowItem CreateWorkflowItem(int workflowItemID, int decision, string message, global::System.DateTime decisionDate) { WorkflowItem workflowItem = new WorkflowItem(); workflowItem.WorkflowItemID = workflowItemID; workflowItem.Decision = decision; workflowItem.Message = message; workflowItem.DecisionDate = decisionDate; return workflowItem; }
public InputMismatchException(WorkflowItem to, string toName, Type type) { this.to = to; this.toName = toName; this.type = type; }
public void AddToWorkflowItems(WorkflowItem workflowItem) { base.AddObject("WorkflowItems", workflowItem); }
private WorkflowItem GetBlankProject() { WorkflowItem workflowItem = null; workflowItem = new WorkflowItem(WorkflowClassName, WorkflowName, Properties.Resources.EmptyWorkflowTemplate, string.Empty) { CachingStatus = CachingStatus.None, Category = DefaultCategory, Name = WorkflowClassName, DisplayName = WorkflowName, Description = WorkflowName, FullName = WorkflowClassName, HasCodeBehind = false, IsSavedToServer = true, Version = DefaultVersion, IsDataDirty = false, Tags = DefaultTags, WorkflowType = DefaultWorkflowType, }; return workflowItem; }
public static StoreLibraryAndTaskActivityRequestDC WorkflowToStoreLibraryAndTaskActivityRequestDC(WorkflowItem workflow, IEnumerable<ActivityAssemblyItem> assemblyItemsUsed) { string libraryName = workflow.Name; var library = GetActivityLibraryDC(libraryName, workflow.Category, workflow.Description, workflow.CreatedBy, workflow.Version, workflow.Status); var dependencyList = new List<StoreActivityLibraryDependenciesGroupsRequestDC>( assemblyItemsUsed.Select(asm => new StoreActivityLibraryDependenciesGroupsRequestDC { Name = asm.Name, Version = asm.Version.ToString(), }.SetIncaller()) ); return new StoreLibraryAndTaskActivityRequestDC { Incaller = Utility.GetCallerName(), IncallerVersion = Utility.GetCallerVersion(), InInsertedByUserAlias = !String.IsNullOrEmpty(workflow.CreatedBy) ? workflow.CreatedBy : Utility.GetCurrentUserName(), InUpdatedByUserAlias = Utility.GetCurrentUserName(), EnforceVersionRules = true, ActivityLibrary = library, StoreActivityLibraryDependenciesGroupsRequestDC = new StoreActivityLibraryDependenciesGroupsRequestDC() { Name = libraryName, Version = workflow.Version, List = dependencyList }.SetIncaller(), TaskActivitiesList = new List<TaskActivityDC>() { new TaskActivityDC() { Guid = workflow.TaskActivityGuid.Value, AssignedTo = Utility.GetCurrentUserName(), Activity = ActivityItemToStoreActivitiyDC(workflow), Status = workflow.TaskActivityStatus.Value } } }; }
public ActionResult _Preview(String Id) { WorkflowItem w = this._bm.GetWorkflowItemBySN(Id); return(PartialView(w)); }
/// <summary> /// Close the workflowItem passed in from the designer. /// </summary> /// <param name="itemToClose">workflowItem To close</param> public void CloseWorkflowCommandExecute(WorkflowItem itemToClose) { // We'll allow it without prompt if it's saved either to server or locally SavingResult? result = null; bool isSaveToLocal = false; //open from server and make the changes if (itemToClose.IsReadOnly) { CloseWorkflowItem(itemToClose); } else { if (itemToClose.IsOpenFromServer && itemToClose.IsDataDirty) { result = MessageBoxService.ShowClosingComfirmation(itemToClose.Name); } else if (itemToClose.IsOpenFromServer && !itemToClose.IsDataDirty) //open from server and not make the changes { result = MessageBoxService.ShowKeepLockedComfirmation(itemToClose.Name); } else if (!itemToClose.IsOpenFromServer && itemToClose.IsDataDirty)//open from local and make the changes { result = MessageBoxService.ShowLocalSavingComfirmation(itemToClose.Name); isSaveToLocal = true; } else//open from local and not make the changes { CloseWorkflowItem(itemToClose); } if (result != null) { bool shouldCancel = false; if (isSaveToLocal && result.Value.HasFlag(SavingResult.Save)) { shouldCancel = !SaveToLocal(itemToClose, true); } else if (!isSaveToLocal && result.Value.HasFlag(SavingResult.Save)) { shouldCancel = !SaveToServer(itemToClose); } if (result.Value.HasFlag(SavingResult.Unlock)) { OnStoreActivitesUnlockWithBusy(itemToClose, result.Value.HasFlag(SavingResult.Save)); } if (!shouldCancel) { CloseWorkflowItem(itemToClose); } } } }
private void RemoveWorkflowItemAndSetFocusedWorkflowItem(WorkflowItem itemToClose) { itemToClose.Close(); FocusedWorkflowItem = WorkflowItems.FirstOrDefault(w => w != itemToClose); }
private void CloseWorkflowItem(WorkflowItem itemToClose) { RemoveWorkflowItemAndSetFocusedWorkflowItem(itemToClose); WorkflowItems.Remove(itemToClose); }
/// <summary> /// Logic for Compile button, after WorkflowCompiler has done its work. Separated out for testability. /// </summary> private void CompileCommandExecutePostCompile(WorkflowItem compiledWorkflow, CompileResult compileResult) { if (compiledWorkflow == null) { throw new ArgumentNullException("compiledWorkflow"); } if (compileResult == null) { throw new ArgumentNullException("compileResult"); } // Import compile result. We signal to the UX that there has been a change, and it should respond by running the // import process try { Compiler.AddToCaching(compileResult.FileName); MessageBoxService.CompileSuccessed(compiledWorkflow.Name); } catch (Exception ex) { throw new UserFacingException(ex.Message); } }
public static WorkflowItem StoreActivitiyDCToWorkflowItem( StoreActivitiesDC dc, ActivityAssemblyItem parentAssemblyItem, List<ActivityAssemblyItem> references = null, bool isTask = false) { var workflowItem = new WorkflowItem(dc.Name, dc.Name, dc.Xaml, dc.WorkflowTypeName, references); workflowItem.CachingStatus = CachingStatus.None; workflowItem.Category = dc.ActivityCategoryName; workflowItem.CreateDateTime = dc.InsertedDateTime; workflowItem.CreatedBy = dc.InsertedByUserAlias; workflowItem.Description = dc.Description; workflowItem.FullName = dc.Name; workflowItem.Name = dc.Name; workflowItem.DisplayName = dc.ShortName ?? dc.Name; workflowItem.HasCodeBehind = dc.IsCodeBeside; workflowItem.ParentAssemblyItem = parentAssemblyItem; workflowItem.Status = dc.StatusCodeName; workflowItem.UpdatedBy = dc.UpdatedByUserAlias; workflowItem.UpdateDateTime = dc.UpdatedDateTime; workflowItem.IsSavedToServer = true; workflowItem.Version = workflowItem.OldVersion = dc.Version; workflowItem.IsDataDirty = false; workflowItem.Tags = dc.MetaTags; workflowItem.XamlCode = dc.Xaml; workflowItem.WorkflowType = dc.WorkflowTypeName; workflowItem.IsOpenFromServer = true; workflowItem.IsTask = isTask; return workflowItem; }
public void RunWorkflow() { WorkflowResult finalResult = new WorkflowResult(); String LastItemRun = ""; int LastRunResultID = 0; try { RunWorkflow run = db.RunWorkflows.Where(r => r.RunID == RunID).FirstOrDefault(); run.StartTime = DateTime.Now; db.SaveChanges(); List <vwRunItem> items = db.vwRunItems.Where(i => i.RunID == RunID).OrderBy(i => i.RunOrder).ToList(); RunPayload pl = run.RunPayloads.FirstOrDefault(); foreach (vwRunItem item in items) { DateTime StartTime = DateTime.Now; LibraryItem li = db.LibraryItems.Where(l => l.ItemID == item.ItemID).FirstOrDefault(); if (!String.IsNullOrEmpty(item.HtmlAnswers)) { pl = util.SetPayload(RunID, li.ItemID, item.HtmlAnswers); } LastItemRun = li.ItemName; WorkflowItem wfi = db.WorkflowItems.Where(w => w.ItemID == item.ItemID).FirstOrDefault(); RunResult rr = new RunResult { ResultString = "", RunID = RunID, ResultID = 1, TimeStarted = DateTime.Now, WFItemID = wfi.WFItemID }; db.RunResults.Add(rr); db.SaveChanges(); LastRunResultID = rr.RunResultID; Assembly assembly = Assembly.LoadFrom(li.LibraryPath); Type type = assembly.GetType("ItemToRun.RunWorkflowItem"); object instanceOfMyType = Activator.CreateInstance(type); var result = type.InvokeMember("RunItem", BindingFlags.Default | BindingFlags.InvokeMethod, null, instanceOfMyType, new Object[] { run.EmpID, pl == null ? new RunPayload() : pl }); IEnumerable <PropertyInfo> props = result.GetType().GetRuntimeProperties(); int ResultID = Convert.ToInt32(props.ElementAt(0).GetValue(result, null)); String ResultText = props.ElementAt(1).GetValue(result, null).ToString(); DateTime TimeDone = Convert.ToDateTime(props.ElementAt(2).GetValue(result, null)); RunResult rrDone = db.RunResults.Where(r => r.RunResultID == rr.RunResultID).FirstOrDefault(); rrDone.TimeCompleted = DateTime.Now; rrDone.ResultID = ResultID; rrDone.ResultString = ResultText; db.SaveChanges(); finalResult = new WorkflowResult { Success = true, ResultString = "" }; } } catch (Exception ex) { finalResult = new WorkflowResult { Success = false, ResultString = String.Format("There was an error during the run in the {0} item.", LastItemRun), FullError = ex }; RunResult rrError = db.RunResults.Where(r => r.RunResultID == LastRunResultID).FirstOrDefault(); rrError.ResultID = 4; rrError.ResultString = String.Format("Error: {0}", ex.Message); rrError.TimeCompleted = DateTime.Now; db.SaveChanges(); } }
/// <summary> /// Persists a workflow to disk, in various formats, such as: /// wf binary serialized /// jpg image /// xaml straight XAML text only, no metadata /// </summary> /// <param name="workflow">The workflow to be persisted to disk.</param> /// <param name="forceSaveAs">If true, forces the save as dialog to appear.</param> /// <returns>If true then the file was saved</returns> public bool SaveToLocal(WorkflowItem workflow, bool forceSaveAs) { bool isSuccess = false; // This will be set to true on a successful save. string targetFileName; string fileExtension; // If the file name is null, or forceSaveAs is true, show the dialog and get the file name. if (string.IsNullOrEmpty(workflow.LocalFileFullName) || forceSaveAs) { string filter = "Workflow files (*.wf)|*.wf|XAML Text files (*.xaml)|*.xaml|JPEG Image files (*.jpg)|*.jpg"; targetFileName = DialogService.ShowSaveDialogAndReturnResult(workflow.Name, filter); if (!string.IsNullOrEmpty(targetFileName)) { fileExtension = Path.GetExtension(targetFileName); if (string.IsNullOrEmpty(fileExtension)) { targetFileName += "." + DefaultSaveFileLocalExtension; fileExtension = DefaultSaveFileLocalExtension; } switch (fileExtension.ToLower()) { case ".wf": using (var stream = File.Open(targetFileName, FileMode.Create)) { var formatter = new BinaryFormatter(); workflow.SetXamlCode(); workflow.SetReferences(); formatter.Serialize(stream, workflow); isSuccess = true; } break; case ".jpg": if (workflow.WorkflowDesigner != null) { workflow.WorkflowDesigner.SaveWorkflowToBitmap(targetFileName); isSuccess = true; } break; case ".xaml": workflow.WorkflowDesigner.Save(targetFileName); isSuccess = true; break; default: throw new UserFacingException("The file type is not recognized. The save to local could not be completed."); } } } return isSuccess; }
/// <summary> /// The main method of WorkflowUploader. Upload the given workflow and its dependencies to server using the default WorkflowsQueryService, as a new activityLibrary. /// </summary>; /// <param name="workflow">WorkflowItem to save</param> /// <returns>true if uploaded succeeded, else CommunicationException</returns> /// <exception cref="CommunicationException">WCF layer exceptions and error codes from the workflow query service will be wrapped as CommunicationExceptions</exception> public static StatusReplyDC Upload(IWorkflowsQueryService proxy, WorkflowItem workflow) { var assemblyActivitiyItemsUsed = workflow.WorkflowDesigner.DependencyAssemblies; // Database requires that we upload dependencies first so the DB is always in a consistent state Upload(proxy, assemblyActivitiyItemsUsed); // Now, upload the actual workflow StoreActivitiesDC result = null; if (workflow.TaskActivityGuid.HasValue) { result = proxy.UploadActivityLibraryAndTaskActivities( DataContractTranslator.WorkflowToStoreLibraryAndTaskActivityRequestDC(workflow, assemblyActivitiyItemsUsed) )[0].Activity; } else { List<TaskAssignment> tasks = workflow.WorkflowDesigner.Tasks; Guid[] newTaskIds = tasks.Where(t => t.TaskStatus == TaskActivityStatus.New).Select(t => t.TaskId).ToArray(); if (newTaskIds.Any()) { workflow.WorkflowDesigner.SetNewTasksToAssigned(newTaskIds); workflow.SetXamlCode(); // Publication has removed all tasks from workflow } try { result = proxy.UploadActivityLibraryAndDependentActivities( DataContractTranslator.WorkflowToStoreLibraryAndActivitiesRequestDC(workflow, assemblyActivitiyItemsUsed, tasks) )[0]; } catch (Exception) { if (newTaskIds.Any()) workflow.WorkflowDesigner.RollbackAssignedTasks(newTaskIds); } } result.StatusReply.CheckErrors(); // No exception = success. Disable the Save button, clean up, return true to report success. workflow.FinishTaskAssigned(); workflow.CreateDateTime = result.InsertedDateTime; workflow.UpdateDateTime = result.UpdatedDateTime; workflow.Version = result.Version; workflow.IsOpenFromServer = true; workflow.IsSavedToServer = true; workflow.IsDataDirty = false; return result.StatusReply; }
/// <summary> /// Checks to see if the WorkflowItem is already in the editor active and adds it if it is not /// </summary> /// <param name="itemToCheck">Workflow to check</param> public bool CheckIsAlreadyInListOrAdd(WorkflowItem itemToCheck) { Contract.Requires(itemToCheck != null); var itemToFind = WorkflowItems.FirstOrDefault(wfi => 0 == wfi.CompareTo(itemToCheck)); if (null != itemToFind) { FocusedWorkflowItem = itemToFind; return false; } else { WorkflowItems.Add(itemToCheck); FocusedWorkflowItem = itemToCheck; return true; } }
/// <summary> /// Take a WorkflowItem and the computed list of ActivityAssemblyItems it depends on and translate them into DC form for an upload /// </summary> /// <param name="workflow"></param> /// <param name="assemblyItemsUsed">Assemblies list (computed by WorkflowUploader.ComputeDependencies())</param> /// <returns></returns> public static StoreLibraryAndActivitiesRequestDC WorkflowToStoreLibraryAndActivitiesRequestDC(WorkflowItem workflow, IEnumerable<ActivityAssemblyItem> assemblyItemsUsed, List<TaskAssignment> tasks) { string libraryName = workflow.Name; var library = GetActivityLibraryDC(libraryName, workflow.Category, workflow.Description, workflow.CreatedBy, workflow.Version, workflow.Status); var dependencyList = new List<StoreActivityLibraryDependenciesGroupsRequestDC>( assemblyItemsUsed.Select(asm => new StoreActivityLibraryDependenciesGroupsRequestDC { Name = asm.Name, Version = asm.Version.ToString(), }.SetIncaller()) ); return new StoreLibraryAndActivitiesRequestDC { Incaller = Utility.GetCallerName(), IncallerVersion = Utility.GetCallerVersion(), InInsertedByUserAlias = !String.IsNullOrEmpty(workflow.CreatedBy) ? workflow.CreatedBy : Utility.GetCurrentUserName(), InUpdatedByUserAlias = Utility.GetCurrentUserName(), EnforceVersionRules = true, ActivityLibrary = library, StoreActivitiesList = new List<StoreActivitiesDC> { // There is only one activity in this "library", = the workflow itself ActivityItemToStoreActivitiyDC(workflow) }, StoreActivityLibraryDependenciesGroupsRequestDC = new StoreActivityLibraryDependenciesGroupsRequestDC() { Name = libraryName, Version = workflow.Version, List = dependencyList }.SetIncaller(), TaskActivitiesList = tasks.Select(t => new StoreLibraryAndTaskActivityRequestDC() { EnforceVersionRules = true, ActivityLibrary = GetActivityLibraryDC(t.GetFriendlyName(workflow.Name), workflow.Category, workflow.Description, workflow.CreatedBy, t.Version, workflow.Status), StoreActivityLibraryDependenciesGroupsRequestDC = new StoreActivityLibraryDependenciesGroupsRequestDC() { Name = t.GetFriendlyName(workflow.Name), Version = t.Version, List = dependencyList }, TaskActivitiesList = new List<TaskActivityDC>() { new TaskActivityDC() { Guid = t.TaskId, AssignedTo = t.AssignTo, Activity = ActivityItemToStoreActivitiyDC(workflow, t), Status = t.TaskStatus == TaskActivityStatus.Unassigned ? TaskActivityStatus.Unassigned : TaskActivityStatus.Assigned, } } }.SetIncaller()).ToList() }; }
/// <summary> /// Separated out for testability /// </summary> public PublishingReply PublishCommandExecute_Implementation(IWorkflowsQueryService client, WorkflowItem workflow) { // Now, start the Publish process. In general this may take arbitrarily long. return client.PublishWorkflow(new PublishingRequest { Incaller = Environment.UserName, IncallerVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(), WorkflowName = workflow.Name, WorkflowVersion = workflow.Version }); }
public InputNotFoundException(WorkflowItem from, string fromName) { this.from = from; this.fromName = fromName; }
/// <summary> /// Processes the node collection. /// </summary> /// <param name="activity">The activity.</param> private void ProcessNodeCollection(Activity activity, Control Parent) { if (activity == null) return; WorkflowItem item = new WorkflowItem(this); item.CurrentActivity = activity; _counter++; item.ID = String.Format("{1}_wi_{0}", _counter, this.ID); item.DataBind(); Parent.Controls.Add(item); if (activity is CompositeActivity) { foreach (Activity innerActivity in ((CompositeActivity)activity).Activities) { ProcessNodeCollection(innerActivity, item); } } }
/// <summary> /// Takes action on the specified workflow item, representing a /// membership request. /// </summary> /// <param name="workflowId">The id of the workflow </param> /// <param name="action">The moderation action to be taken</param> /// <param name="userId">The unique id of the user under moderation.</param> /// <param name="communityId">The unique id of the community to which membership has been requested.</param> public void Moderate(string workflowId, string action, string userId, string communityId) { var membershipRequest = GetMembershipRequest(userId, communityId); var populatedWorkflowId = WorkflowId.Create(workflowId); var requestReference = Reference.Create(CreateUri(membershipRequest.Group, membershipRequest.User)); try { var transitionToken = _workflowService.BeginTransitionSession(populatedWorkflowId, requestReference); try { // Retrieve the moderation workflow associated with // the item to be acted upon. var workflow = _workflowService.Get(populatedWorkflowId); // Leverage the workflow to determine what the // resulting state of the item will be upon taking // the specified action. //retrieve the current state of the workflow item once the begintransitionsession begins. var filter = new WorkflowItemFilter { Target = requestReference }; var criteria = new Criteria <WorkflowItemFilter> { Filter = filter }; var workflowItem = _workflowItemService.Get(criteria).Results.Last(); // Example: Current State: "Pending", Action: "Approve" => Transitioned State: "Approved" var transitionedState = workflow.Transition(workflowItem.State, new WorkflowAction(action)); var subsequentWorkflowItem = new WorkflowItem( workflow.Id, transitionedState, requestReference ); _workflowItemService.Add(subsequentWorkflowItem, membershipRequest, transitionToken); // Perform any application logic given the item's // new state. if (IsApproved(subsequentWorkflowItem.State)) { _memberRepository.Add(_memberAdapter.Adapt(membershipRequest)); } } finally { _workflowService.EndTransitionSession(transitionToken); } } catch (SocialAuthenticationException ex) { throw new SocialRepositoryException("The application failed to authenticate with Episerver Social.", ex); } catch (MaximumDataSizeExceededException ex) { throw new SocialRepositoryException( "The application request was deemed too large for Episerver Social.", ex); } catch (SocialCommunicationException ex) { throw new SocialRepositoryException("The application failed to communicate with Episerver Social.", ex); } catch (SocialException ex) { throw new SocialRepositoryException("Episerver Social failed to process the application request.", ex); } }
public void RegisterPreRouterWorkflow(WorkflowItem<PreRouteWorkflowData> item) { preRouteWorkflow.AddItem(item); }