public void AddWorkflowWithConstraint() { var childWorkflow = Workflow<string>.Definition() as IWorkflow<string>; _parentWorkflow = Workflow<string>.Definition().Do(childWorkflow, If.IsTrue(true)) as Workflow<string>; _parentWorkflow.RegisteredOperations.Tasks.Count.ShouldBe(1); }
/// <summary> /// Processes the specified <see cref="Rock.Model.Workflow" /> /// </summary> /// <param name="workflow">The <see cref="Rock.Model.Workflow" /> instance to process.</param> /// <param name="errorMessages">A <see cref="System.Collections.Generic.List{String}" /> that contains any error messages that were returned while processing the <see cref="Rock.Model.Workflow" />.</param> public void Process( Workflow workflow, out List<string> errorMessages ) { workflow.IsProcessing = true; this.Context.SaveChanges(); var rockContext = (RockContext)this.Context; workflow.LoadAttributes( rockContext ); workflow.Process( rockContext, out errorMessages ); if ( workflow.IsPersisted ) { this.Context.WrapTransaction( () => { this.Context.SaveChanges(); workflow.SaveAttributeValues( rockContext ); foreach ( var activity in workflow.Activities ) { activity.SaveAttributeValues( rockContext ); } } ); workflow.IsProcessing = false; this.Context.SaveChanges(); } }
public void TestSavePerson() { var workflow = new Workflow(); var person = new Person(); Assert.IsTrue(workflow.SavePerson(new Person() { Name = "Kevin", Age = 26 })); }
public void ShouldDeserializeComplexWorkflowConfiguration3() { var workFlow = new Workflow(); workFlow.Configuration = "{\"default_filter\":{\"queue\":\"WQccc\"},\"filters\":[{\"expression\":\"1==1\",\"friendly_name\":\"Prioritizing Filter\",\"targets\":[{\"priority\":\"1\",\"queue\":\"WQccc\",\"timeout\":\"300\"}]}]}"; var workFlowConfiguration = new WorkflowConfiguration(); var filter = new Filter { FriendlyName = "Prioritizing Filter", Expression = "1==1", Targets = new List<Target>() { new Target { Queue="WQccc", Priority="1", Timeout="300" } } }; workFlowConfiguration.Filters.Add(filter); workFlowConfiguration.DefaultFilter = new Target() { Queue = "WQccc" }; var config = workFlow.WorkflowConfiguration; Assert.AreEqual(workFlowConfiguration.ToString(), config.ToString()); }
public void Init() { _workStepRepository = new MemoryWorkStepRepository(); _workItemRepository = new MemoryWorkItemRepository(); _workflowRepository = new WorkflowRepository(_workItemRepository, _workStepRepository); _wp = new Workflow(_workflowRepository); }
public void TestMethod1() { // Arrange WorkflowTestTrace.Arrange(); var activity = new FileReadToEnd() { FileName = Constants.Workflow1Xaml }; var tracking = new ListTrackingParticipant(); var workflow = new Workflow(activity) { Tracking = tracking }; try { // Act WorkflowTestTrace.Act(); var result = workflow.Start().Result.Output.Result; // Assert WorkflowTestTrace.Assert(); Assert.AreEqual(2113, result.Length); } finally { WorkflowTestTrace.Finally(); workflow.Trace(); } }
/// <summary> /// Processes the specified <see cref="Rock.Model.Workflow" /> /// </summary> /// <param name="workflow">The <see cref="Rock.Model.Workflow" /> instance to process.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">A <see cref="System.Collections.Generic.List{String}" /> that contains any error messages that were returned while processing the <see cref="Rock.Model.Workflow" />.</param> /// <returns></returns> public bool Process( Workflow workflow, object entity, out List<string> errorMessages ) { var rockContext = (RockContext)this.Context; if ( workflow.IsPersisted ) { workflow.IsProcessing = true; rockContext.SaveChanges(); } bool result = workflow.ProcessActivities( rockContext, entity, out errorMessages ); if ( workflow.IsPersisted || workflow.WorkflowType.IsPersisted ) { if ( workflow.Id == 0 ) { Add( workflow ); } rockContext.WrapTransaction( () => { rockContext.SaveChanges(); workflow.SaveAttributeValues( rockContext ); foreach ( var activity in workflow.Activities ) { activity.SaveAttributeValues( rockContext ); } } ); workflow.IsProcessing = false; rockContext.SaveChanges(); } return result; }
public void TestFindAllPeople() { var workflow = new Workflow(); workflow.SavePerson(new Person() { Name = "Bubba" }); Assert.AreNotEqual(0, workflow.FindAllPeople().Count); }
public WorkflowMapping GetCurrentApproverByWorkflowAndLevel(Workflow workflow, int level) { Dictionary<string, object> parameter = new Dictionary<string, object>(); parameter.Add("Workflow", workflow); parameter.Add("LevelId", level); WorkflowMapping workflowMapping = this.workflowMappingRepository.GetFilteredData(parameter).FirstOrDefault(); return workflowMapping; }
public bool CheckDataAndCodeIfExist(Workflow entity) { if (CheckDataIfExists(entity) || CheckDataIfExists(entity.Code)) { return true; } return false; }
public void ShouldCheckIfConstraintIsNull() { ICheckConstraint expression = null; _pipe = new Workflow<string>(); var method = new Func<string, string>((s) => { return "result"; }); Assert.Throws<ArgumentNullException>(() => _pipe.Do(method, expression), "Exception not thrown"); }
public void ShouldRepeatOperation() { IWorkflow<Colour> workflow = new Workflow<Colour>(); workflow.Do<DuplicateName>().Repeat().Twice(); var result = workflow.Start(new Colour("Red")); result.Name.ShouldBe("RedRedRedRedRedRedRedRed"); }
public Freeze(Workflow p, IntPtr windowHandle) { if (p.ActiveWindowGDIFreezeWindow) { NativeMethods.GetWindowThreadProcessId(windowHandle, out processId); FreezeThreads((int)processId); } }
public void ShouldNotRetrySuccessfulOperation() { var workflow = new Workflow<Colour>(); workflow.Do<DuplicateName>().Retry().Twice(); var result = workflow.Start(new Colour("Red")); result.Name.ShouldBe("RedRed"); }
public void TestRemovedPersonsShouldNoLongerBeFindable() { var workflow = new Workflow(); workflow.SavePerson(new Person() { Name = "Levi"}); workflow.RemovePerson("Levi"); Assert.IsNull(workflow.FindPerson("Levi")); }
public void ShouldSetResultAfterExecuting() { BasicOperation<Colour> doublespace = new DoubleSpace(); var flow = new Workflow<Colour>(); flow.Do(doublespace); flow.Start(new Colour("Red")); Assert.That(doublespace.SuccessResult, Is.True); }
void DrawLayer(MaterialEditor editor, int i, MaterialProperty[] props, string[] keyWords, Workflow workflow, bool hasGloss, bool hasSpec, bool isParallax, bool hasEmis, bool hasDistBlend) { EditorGUIUtility.labelWidth = 0f; var albedoMap = FindProperty ("_Tex" + i, props); var tint = FindProperty("_Tint" + i, props); var normalMap = FindProperty ("_Normal" + i, props); var smoothness = FindProperty("_Glossiness" + i, props); var glossinessMap = FindProperty("_GlossinessTex" + i, props, false); var metallic = FindProperty("_Metallic" + i, props, false); var emissionTex = FindProperty("_Emissive" + i, props); var emissionMult = FindProperty("_EmissiveMult" + i, props); var parallax = FindProperty("_Parallax" + i, props); var texScale = FindProperty("_TexScale" + i, props); var specMap = FindProperty("_SpecGlossMap" + i, props, false); var specColor = FindProperty("_SpecColor" + i, props, false); var distUVScale = FindProperty("_DistUVScale" + i, props, false); editor.TexturePropertySingleLine(new GUIContent("Albedo/Height"), albedoMap); editor.ShaderProperty(tint, "Tint"); editor.TexturePropertySingleLine(new GUIContent("Normal"), normalMap); if (workflow == Workflow.Metallic) { editor.TexturePropertySingleLine(new GUIContent("Metal(R)/Smoothness(A)"), glossinessMap); } else { editor.TexturePropertySingleLine(new GUIContent("Specular(RGB)/Gloss(A)"), specMap); } if (workflow == Workflow.Metallic && !hasGloss) { editor.ShaderProperty(smoothness, "Smoothness"); editor.ShaderProperty(metallic, "Metallic"); } else if (workflow == Workflow.Specular && !hasSpec) { editor.ShaderProperty(smoothness, "Smoothness"); editor.ShaderProperty(specColor, "Specular Color"); } editor.TexturePropertySingleLine(new GUIContent("Emission"), emissionTex); editor.ShaderProperty(emissionMult, "Emissive Multiplier"); editor.ShaderProperty(texScale, "Texture Scale"); if (hasDistBlend) { editor.ShaderProperty(distUVScale, "Distance UV Scale"); } if (isParallax) { editor.ShaderProperty(parallax, "Parallax Height"); } if (i != 1) { editor.ShaderProperty(FindProperty("_Contrast"+i, props), "Interpolation Contrast"); } }
/// <summary> /// Archives a workflow, moving it into the completed store. /// </summary> /// <param name="workflow">The workflow to archive.</param> public override void Archive(Workflow workflow) { var coll = GetCollection(); coll.Remove(_queryById(workflow.Id)); var collCompleted = GetCompletedCollection(); collCompleted.Insert(new CompletedWorkflow(workflow)); }
public void BeforeEachTest() { _red = new Colour("Red"); _pipe = new Workflow<Colour>(); _pipe.Do(new WorkflowMemoryLoader<Colour>(_red)); _doublespace = new DoubleSpace(); _doublespaceOne = new DoubleSpace(); _doubleSpaceTwo = new DoubleSpace(); }
public void GenericPipelineSyntax() { var pipe = new Workflow<Colour>(); pipe.Do(new WorkflowMemoryLoader<Colour>(_red)) .Do(_doublespace); var result = pipe.Start(); Assert.That(result.ToString(), Is.EqualTo("R e d")); }
public void TestSavedPersonShouldBeReturnedWithGetPerson() { var workflow = new Workflow(); workflow.SavePerson(new Person() { Name = "Alibaba", Age = 46 }); var person = workflow.FindPerson("Alibaba"); Assert.IsNotNull(person); Assert.AreEqual("Alibaba", person.Name); Assert.AreEqual(46, person.Age); }
public void Init() { _workStepRepository = new MemoryWorkStepRepository(); _workItemRepository = new MemoryWorkItemRepository(); var repository = new WorkflowRepository(_workItemRepository, _workStepRepository); _workflow = new Workflow(repository); _mover = new WorkItemMover(repository); _mocks = new MockRepository(); }
/// <summary> /// Processes the specified <see cref="Rock.Model.Workflow"/> /// </summary> /// <param name="workflow">The <see cref="Rock.Model.Workflow"/> instance to process.</param> /// <param name="CurrentPersonId">A <see cref="System.String"/> representing the PersonId of the <see cref="Rock.Model.Person"/> who is processing the <see cref="Rock.Model.Workflow"/>.</param> /// <param name="errorMessages">A <see cref="System.Collections.Generic.List{String}"/> that contains any error messages that were returned while processing the <see cref="Rock.Model.Workflow"/>.</param> public void Process( Workflow workflow, int? CurrentPersonId, out List<string> errorMessages ) { workflow.IsProcessing = true; this.Save( workflow, null ); workflow.Process(out errorMessages); workflow.IsProcessing = false; this.Save( workflow, null ); }
public void Given() { _doubleSpace = new DoubleSpace(); _duplicateName = new DuplicateName(); _secondDuplicateName = new DuplicateName(); _colour = new Colour("Red"); _defaultLoader = new WorkflowMemoryLoader<Colour>(_colour); _workflow = new Workflow<Colour>(); _workflow.Do(_defaultLoader); }
public async Task TestActivity() { Func<int, int> pow = x => x*x; var activity = new ActivityBlock(pow); var workflow = new Workflow<int, int>("test", activity); var output = await WorkflowRunner.Run(workflow, 2); Assert.Equal(4, output); }
public void Given() { _duplicateNameTwo = new DuplicateName(); _duplicateNameOne = new DuplicateName(); _duplicateNameTwo = new DuplicateName(); _redOnly = new Colour("Red"); _defaultLoader = new WorkflowMemoryLoader<Colour>(_redOnly); _pipe = new Workflow<Colour>(); _pipe.Do(_defaultLoader); }
public void ShouldDeserializeWorkflowDefaultFilterConfiguration() { var workFlow = new Workflow(); workFlow.Configuration = "{\"default_filter\":{\"queue\":\"WQccc\"},\"filters\":[]}"; var workFlowConfiguration = new WorkflowConfiguration(); workFlowConfiguration.DefaultFilter = new Target() { Queue = "WQccc" }; var config = workFlow.WorkflowConfiguration; Assert.AreEqual(workFlowConfiguration.ToString(), config.ToString()); }
public void DeleteWorkflowMapping(Workflow workflow) { List<WorkflowMapping> workflowMappingList = new List<WorkflowMapping>(); workflowMappingList = GetFilteredDataByWorkflow(workflow); if (workflowMappingList.Any()) { foreach (var workflowMapping in workflowMappingList) { this.workflowMappingRepository.Delete(workflowMapping); } } }
public void DeleteNotificationMapping(Workflow workflow) { List<NotificationMapping> notificationMappingList = new List<NotificationMapping>(); notificationMappingList = GetFilteredDataByWorkflow(workflow); if (notificationMappingList.Any()) { foreach (var notificationMapping in notificationMappingList) { this.notificationMappingRepository.Delete(notificationMapping); } } }
public void DeleteDocumentMapping(Workflow workflow) { List<DocumentMapping> documentMappingList= new List<DocumentMapping>(); documentMappingList= GetFilteredDataByWorkflow(workflow); if (documentMappingList.Any()) { foreach (var documentMapping in documentMappingList) { this.documentMappingRepository.Delete(documentMapping); } } }
public FolderExists(XElement xe, Workflow wf) : base(xe, wf) { Folder = GetSetting("folder"); }
private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { _selectedWorkflow = myDataGrid.SelectedItem as Workflow; Edit_Button.IsEnabled = !(_selectedWorkflow is null); }
public Touch(XElement xe, Workflow wf) : base(xe, wf) { this.TFiles = this.GetSettings("file"); }
public CsvToYaml(XElement xe, Workflow wf) : base(xe, wf) { Separator = GetSetting("separator", ";"); }
private static EnvelopeDefinition MakeEnvelope(string signer1Email, string signer1Name, string signer2Email, string signer2Name, string docPdf, int delay) { // Data for this method // signerEmail // signerName // docPdf // resumeDate // document 1 (pdf) has tag /sn1/ // // Step 2 start // The envelope has a single recipient. // recipient 1 - signer // read file from a local directory // The reads could raise an exception if the file is not available! string docPdfBytes = Convert.ToBase64String(System.IO.File.ReadAllBytes(docPdf)); // create the envelope definition EnvelopeDefinition env = new EnvelopeDefinition(); env.EmailSubject = "Please sign this document set"; // Create document objects, one per document Document doc = new Document { DocumentBase64 = docPdfBytes, Name = "Lorem Ipsum", // can be different from actual file name FileExtension = "pdf", DocumentId = "1" }; // The order in the docs array determines the order in the envelope env.Documents = new List <Document> { doc }; // create a signer recipient to sign the document, identified by name and email // We're setting the parameters via the object creation Signer signer1 = new Signer { Email = signer1Email, Name = signer1Name, RecipientId = "1", RoutingOrder = "1" }; Signer signer2 = new Signer { Email = signer2Email, Name = signer2Name, RecipientId = "2", RoutingOrder = "2" }; // Add the workflow step that sets a delay for the second signer Workflow workflow = new Workflow(); var workflowStep = new WorkflowStep(); workflowStep.Action = "pause_before"; workflowStep.TriggerOnItem = "routing_order"; workflowStep.ItemId = "2"; workflowStep.DelayedRouting = new DocuSign.eSign.Model.DelayedRouting(); var delayRouteRule = new EnvelopeDelayRule(); delayRouteRule.Delay = new TimeSpan(delay, 0, 0).ToString(); workflowStep.DelayedRouting.Rules = new List <EnvelopeDelayRule> { delayRouteRule }; workflow.WorkflowSteps = new List <WorkflowStep> { workflowStep }; env.Workflow = workflow; // routingOrder (lower means earlier) determines the order of deliveries // to the recipients. Parallel routing order is supported by using the // same integer as the order for two or more recipients. // Create signHere fields (also known as tabs) on the document, // We're using anchor (autoPlace) positioning // // The DocuSign platform searches throughout your envelope's // documents for matching anchor strings. So the // signHere2 tab will be used in both document 2 and 3 since they // use the same anchor string for their "signer 1" tabs. SignHere signHere1 = new SignHere { AnchorString = "/sn1/", AnchorUnits = "pixels", AnchorYOffset = "10", AnchorXOffset = "20" }; SignHere signHere2 = new SignHere { AnchorString = "/sn1/", AnchorUnits = "pixels", AnchorYOffset = "10", AnchorXOffset = "120" }; // Tabs are set per recipient / signer Tabs signer1Tabs = new Tabs { SignHereTabs = new List <SignHere> { signHere1 } }; signer1.Tabs = signer1Tabs; Tabs signer2Tabs = new Tabs { SignHereTabs = new List <SignHere> { signHere2 } }; signer2.Tabs = signer2Tabs; // Add the recipients to the envelope object Recipients recipients = new Recipients { Signers = new List <Signer> { signer1, signer2 }, }; env.Recipients = recipients; // Request that the envelope be sent by setting |status| to "sent". // To request that the envelope be created as a draft, set to "created" env.Status = "sent"; // Step 2 end return(env); }
public static void CreateWorkFlow(OrganizationServiceProxy _serProxy, int _langCode) { _serviceProxy = _serProxy; _languageCode = _langCode; Guid _workflowId; { #region Create XAML // Define the workflow XAML. string xamlWF; xamlWF = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""SampleWF"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:SampleWF.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.InputEntities> <this:SampleWF.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Sequence> <Sequence.Variables> <Variable x:TypeArguments=""x:Int32"" Default=""[40]"" Name=""probability_value"" /> <Variable x:TypeArguments=""mxs:Entity"" Default=""[CreatedEntities("primaryEntity#Temp")]"" Name=""CreatedEntity"" /> </Sequence.Variables> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntity]"" Value=""[New Entity("opportunity")]"" /> <Assign x:TypeArguments=""s:Guid"" To=""[CreatedEntity.Id]"" Value=""[InputEntities("primaryEntity").Id]"" /> <mxswa:SetEntityProperty Attribute=""closeprobability"" Entity=""[CreatedEntity]"" EntityName=""opportunity"" TargetType=""[Type.GetType("probability_value")]"" Value=""[probability_value]""> </mxswa:SetEntityProperty> <mxswa:UpdateEntity Entity=""[CreatedEntity]"" EntityName=""opportunity"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[InputEntities("primaryEntity")]"" Value=""[CreatedEntity]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>"; #endregion Create XAML #region Create Workflow //<snippetCreateAWorkflow1> // Create an asynchronous workflow. // The workflow should execute after a new opportunity is created. Workflow workflow = new Workflow() { // These properties map to the New Process form settings in the web application. Name = "Set closeprobability on opportunity create (async)", Type = new OptionSetValue((int)WorkflowType.Definition), Category = new OptionSetValue((int)WorkflowCategory.Workflow), PrimaryEntity = Opportunity.EntityLogicalName, Mode = new OptionSetValue((int)WorkflowMode.Background), // Additional settings from the second New Process form. Description = @"When an opportunity is created, this workflow" + " sets the closeprobability field of the opportunity record to 40%.", OnDemand = false, Subprocess = false, Scope = new OptionSetValue((int)WorkflowScope.User), TriggerOnCreate = true, AsyncAutoDelete = true, Xaml = xamlWF, // Other properties not in the web forms. LanguageCode = 1033, // U.S. English }; _workflowId = _serviceProxy.Create(workflow); //</snippetCreateAWorkflow1> Console.WriteLine("Created Workflow: " + workflow.Name); #endregion Create Workflow #region Activate Workflow // Activate the workflow. var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); Console.WriteLine("Activated Workflow: " + workflow.Name); #endregion Activate Workflow // Deactivate and delete workflow SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue((int)workflow_statuscode.Draft) }; _serviceProxy.Execute(deactivateRequest); _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId); } }
public void GivenTheWorkflowCalledHasAnEtagValueOf(string workflowName, string etag) { Workflow workflow = this.scenarioContext.Get <Workflow>(workflowName); workflow.ETag = etag; }
public ArgumentValidationResult(string argumentName, Workflow workflow) : base(ValidationResultType.Warning) { ArgumentName = argumentName; Workflow = workflow; }
/// <summary> /// Validates the specified workflow from the given resource group. /// </summary> /// <param name="resourceGroupName">Name of the resource group</param> /// <param name="location">The workflow location.</param> /// <param name="workflowName">Workflow name</param> /// <param name="workflow">The Workflow object.</param> public void ValidateWorkflow(string resourceGroupName, string location, string workflowName, Workflow workflow) { this.LogicManagementClient.Workflows.Validate(resourceGroupName, location, workflowName, workflow); }
public ArgumentValidationResult(string argumentName, Workflow workflow, ValidationResultType type) : base(type) { ArgumentName = argumentName; Workflow = workflow; }
public VimeoListUploads(XElement xe, Workflow wf) : base(xe, wf) { Token = GetSetting("token"); }
public async Task <WorkflowExecutionContext> CreateWorkflowExecutionContextAsync(WorkflowType workflowType, Workflow workflow, IDictionary <string, object> input = null) { var state = workflow.State.ToObject <WorkflowState>(); var activityQuery = await Task.WhenAll(workflowType.Activities.Select(async x => { var activityState = state.ActivityStates.ContainsKey(x.ActivityId) ? state.ActivityStates[x.ActivityId] : new JObject(); return(await CreateActivityExecutionContextAsync(x, activityState)); })); var mergedInput = (await DeserializeAsync(state.Input)).Merge(input ?? new Dictionary <string, object>()); var properties = await DeserializeAsync(state.Properties); var output = await DeserializeAsync(state.Output); var lastResult = await DeserializeAsync(state.LastResult); var executedActivities = state.ExecutedActivities; return(new WorkflowExecutionContext(workflowType, workflow, mergedInput, output, properties, executedActivities, lastResult, activityQuery, _workflowContextHandlers.Resolve(), _workflowContextLogger)); }
public LoggedOutState(Workflow workflow) { _workflow = workflow; }
public ImagesConcat(XElement xe, Workflow wf) : base(xe, wf) { }
public FileContentMatch(XElement xe, Workflow wf) : base(xe, wf) { File = GetSetting("file"); Pattern = GetSetting("pattern"); }
public override TaskStatus Run() { Info("Notifying Workiom user..."); bool success = true; try { InfoFormat("Mapping: {0}", Mapping); // Retrieve payload var trigger = new Trigger { Payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(Workflow.RestParams["Payload"]) }; // Retrieve mapping var jArray = JArray.Parse(Mapping); var mapping = new Dictionary <string, MappingValue>(); foreach (var item in jArray) { var field = item.Value <string>("Field"); var val = item.Value <object>("Value"); var type = item.Value <string>("Type"); mapping.Add(field, new MappingValue { Value = val, MappingType = type.ToLower() == "field" ? MappingType.Dynamic : MappingType.Static }); } // Genereate result var result = WorkiomHelper.Map(trigger, mapping); if (result.Count > 0) { var userId = result.Values.First(); var json = "{\"userId\":" + userId + ",\"message\":\"" + Message + "\"}"; InfoFormat("Payload: {0}", json); var auth = Workflow.GetWorkiomAccessToken(); var notifyTask = WorkiomHelper.Post(NotifyUserUrl, auth, json); notifyTask.Wait(); var response = notifyTask.Result; var responseSuccess = (bool)JObject.Parse(response).SelectToken("success"); if (responseSuccess) { InfoFormat("User {0} notified.", userId); } else { ErrorFormat("An error occured while notifying the user {0}: {1}", userId, response); success = false; } } else { Info("The mapping resulted in an empty payload."); } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while notifying Workiom user. Error: {0}", e.Message); success = false; } var status = Status.Success; if (!success) { status = Status.Error; } Info("Task finished."); return(new TaskStatus(status)); }
public MediaInfo(XElement xe, Workflow wf) : base(xe, wf) { }
public async Task CreateWorkflow(WorkflowInput input) { Workflow result = _mapper.Map <Workflow>(input); await _workflowRepository.Create(result); }
void RunWorkflow(Workflow workflow) { var args = new Dictionary <string, object>(); WorkflowRunner.Instance.RunWorkflow(new WorkflowStartEvent(workflow)); }
public TextsEncryptor(XElement xe, Workflow wf) : base(xe, wf) { }
public string Add(AddProjectServiceForm form) { ISqlMapper mapper = Common.GetMapperFromSession(); List <Customer_Project> customers = new List <Customer_Project>(); List <Customer> updateCustomers = new List <Customer>(); WorkflowDao workflowdao = new WorkflowDao(mapper); UserBLL userbll = new UserBLL(); var user = userbll.GetCurrentUser(); string userid = user.User.ID; form.Project.Report = form.Report; var result = bll.Save(form.Project, form.Assets, form.Buyers, form.Sellers, form.ThirdParty, form.Guarantor, form.Project.CreditReceiverInfo, userid); //处理流程 WorkflowDefinitionModel wfdm = WorkflowDefinitionModel.LoadByName("额度申请"); Workflow wf = workflowdao.Query(new WorkflowQueryForm { ProcessID = result }).FirstOrDefault(); WorkflowModel workflow = null; if (wf == null) { workflow = wfdm.StartNew(user.User.ID, result, new WorkflowAuthority()); //如果流程当前处理人等于申请人,就直接审批通过,进入下一个流程 var task = workflow.CurrentActivity.Tasks.Find(t => t.UserID == userid); if (task != null) { workflow.ProcessActivity(new Approval { Creator = user.User.ID, LastUpdator = user.User.ID, Remark = form.Report, Status = (int)ApprovalStatus.Agree, ActivityID = workflow.CurrentActivity.Value.ID, WorkflowID = workflow.Value.ID, }, user.User.ID, new WorkflowAuthority()); } } else { workflow = WorkflowModel.Load(wf.ID); //如果流程当前处理人等于申请人,就直接审批通过,进入下一个流程 var task = workflow.CurrentActivity.Tasks.Find(t => t.UserID == userid); if (task != null) { workflow.ProcessActivity(new Approval { Creator = user.User.ID, LastUpdator = user.User.ID, Status = (int)ApprovalStatus.None, ActivityID = workflow.CurrentActivity.Value.ID, WorkflowID = workflow.Value.ID, }, user.User.ID, new WorkflowAuthority()); task = workflow.CurrentActivity.Tasks.Find(t => t.UserID == userid); if (task != null) { workflow.ProcessActivity(new Approval { Creator = user.User.ID, LastUpdator = user.User.ID, Remark = form.Report, Status = (int)ApprovalStatus.Agree, ActivityID = workflow.CurrentActivity.Value.ID, WorkflowID = workflow.Value.ID, }, user.User.ID, new WorkflowAuthority()); } } } return(result); }
public WorkiomNotifyUser(XElement xe, Workflow wf) : base(xe, wf) { NotifyUserUrl = Workflow.NotifyUserUrl; Mapping = GetSetting("mapping"); Message = GetSetting("message"); }
public async void CloudPortTestWithGoodAndBadData(RequestCloudPortEncodeCreateDTO encodeCreateData, bool blobShouldExist, Type shouldThrowThis, Uri sasUri) { // Arrange var wfj = new WorkflowJob(); Mock.Get(_telestreamCloudClientProvider.CloudPortApi) .Setup(x => x.CreateWorkflowJobAsync(It.IsAny <string>(), It.IsAny <WorkflowJob>())) .ReturnsAsync(wfj); var wf1 = new Workflow(name: "TestWorkflow2") { Input = new WorkflowInput { Sources = new Dictionary <string, VantageNickName>() { { "any value", new VantageNickName() } }, Variables = new Dictionary <string, VantageVariable>(), } }; wf1.Input.Variables.Add("var1", new VantageVariable("0", "0")); var wf2 = new Workflow(); WorkflowsCollection wfc = new WorkflowsCollection() { Workflows = new List <Workflow>() { wf1, wf2 } }; Mock.Get(_telestreamCloudClientProvider.CloudPortApi) .Setup(x => x.ListWorkflowsAsync(null, null, null)) .ReturnsAsync(wfc); Mock.Get(_telestreamCloudClientProvider.CloudPortApi) .Setup(x => x.GetWorkflowAsync(It.IsAny <string>())) .ReturnsAsync(wf1); var sr = new StorageReference(); wf1.Input.StorageReferences = new Dictionary <string, StorageReference>() { { "DavesStorageReference", sr } }; Mock.Get(_storageService) .Setup(x => x.GetBlobExistsAsync(It.IsAny <Uri>(), It.IsAny <StorageClientProviderContext>())) .ReturnsAsync(blobShouldExist); Mock.Get(_storageService) .Setup(x => x.GetSasUrlForBlob(It.IsAny <Uri>(), It.IsAny <TimeSpan>(), It.IsAny <StorageClientProviderContext>())) .Returns(sasUri?.ToString()); Mock.Get(_settingsProvider) .Setup(x => x.GetAppSettingsValue(It.IsAny <string>())) .Returns("telestreamCloudApiKey"); Mock.Get(_telestreamCloudStorageProvider) .Setup(x => x.GetStoreByNameAsync(It.IsAny <Uri>())) .ReturnsAsync(new Store()); // Act var cloudPortService = new CloudPortService(_storageService, _telestreamCloudClientProvider, _telestreamCloudStorageProvider); var ex = await Record.ExceptionAsync(async() => await cloudPortService.EncodeCreateAsync(encodeCreateData).ConfigureAwait(false)).ConfigureAwait(false); // Assert if (shouldThrowThis is null) { // if there are no throws, test is successful. Assert.Null(ex); } else { Assert.NotNull(ex); Assert.IsType(shouldThrowThis, ex); } }
//Properties // //Constructor static Program() { _engine = new Engine(); _workflow = new Workflow(); }
/// <summary> /// Constructor /// </summary> /// <param name="workflow">The workflow that will be adapted</param> public CommunityMembershipRequestAdapter(Workflow workflow, IUserRepository userRepository) { this.workflow = workflow; this.userRepository = userRepository; }
public Sha1(XElement xe, Workflow wf) : base(xe, wf) { }
/// <summary> /// Handles the FileUploaded event of the fsFile control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void fsFile_FileUploaded(object sender, EventArgs e) { var rockContext = new RockContext(); var binaryFileService = new BinaryFileService(rockContext); BinaryFile binaryFile = null; if (fsFile.BinaryFileId.HasValue) { binaryFile = binaryFileService.Get(fsFile.BinaryFileId.Value); } if (binaryFile != null) { if (!string.IsNullOrWhiteSpace(tbName.Text)) { binaryFile.FileName = tbName.Text; } // set binaryFile.Id to original id since the UploadedFile is a temporary binaryFile with a different id binaryFile.Id = hfBinaryFileId.ValueAsInt(); binaryFile.Description = tbDescription.Text; binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt(); if (binaryFile.BinaryFileTypeId.HasValue) { binaryFile.BinaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFile.BinaryFileTypeId.Value); } var tempList = OrphanedBinaryFileIdList; tempList.Add(fsFile.BinaryFileId.Value); OrphanedBinaryFileIdList = tempList; // load attributes, then get the attribute values from the UI binaryFile.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile); // Process uploaded file using an optional workflow (which will probably populate attribute values) Guid workflowTypeGuid = Guid.NewGuid(); if (Guid.TryParse(GetAttributeValue("Workflow"), out workflowTypeGuid)) { try { // temporarily set the binaryFile.Id to the uploaded binaryFile.Id so that workflow can do stuff with it binaryFile.Id = fsFile.BinaryFileId ?? 0; // create a rockContext for the workflow so that it can save it's changes, without var workflowRockContext = new RockContext(); var workflowTypeService = new WorkflowTypeService(workflowRockContext); var workflowType = workflowTypeService.Get(workflowTypeGuid); if (workflowType != null) { var workflow = Workflow.Activate(workflowType, binaryFile.FileName); List <string> workflowErrors; if (workflow.Process(workflowRockContext, binaryFile, out workflowErrors)) { binaryFile = binaryFileService.Get(binaryFile.Id); if (workflow.IsPersisted || workflowType.IsPersisted) { var workflowService = new Rock.Model.WorkflowService(workflowRockContext); workflowService.Add(workflow); workflowRockContext.SaveChanges(); } } } } finally { // set binaryFile.Id to original id again since the UploadedFile is a temporary binaryFile with a different id binaryFile.Id = hfBinaryFileId.ValueAsInt(); } } ShowBinaryFileDetail(binaryFile); } }
protected void btnSave_Click(object sender, EventArgs e) { if (lopAddress.Location == null || string.IsNullOrWhiteSpace(lopAddress.Location.Street1) || string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode)) { nbValidation.Visible = true; ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "setTimeout(function(){window.scroll(0,0);},200)", true); return; } else { nbValidation.Visible = false; } if (_group == null) { ShowMessage("There was an issue with the viewstate. Please reload and try again. If the problem perssits contact an administrator.", "Error", "panel panel-danger"); return; } GroupService groupService = new GroupService(_rockContext); //Add basic information Group group; if (_group.Id == 0) { group = new Group() { GroupTypeId = _groupType.Id }; var destinationGroup = groupService.Get(GetAttributeValue("DestinationGroup").AsGuid()); if (destinationGroup != null) { group.ParentGroupId = destinationGroup.Id; } var parentMapping = GetAttributeValue("CampusGroupMap").ToKeyValuePairList(); foreach (var pair in parentMapping) { if (pair.Key.AsInteger() == cpCampus.SelectedValueAsId()) { group.ParentGroupId = (( string )pair.Value).AsInteger(); } } var zip = "No Zip"; if (lopAddress.Location != null && !string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode)) { zip = lopAddress.Location.PostalCode; } group.Name = string.Format("{0} - {1}", tbName.Text, zip); groupService.Add(group); group.CreatedByPersonAliasId = _person.PrimaryAliasId; group.IsActive = true; } else { group = groupService.Get(_group.Id); group.IsActive = true; } group.CampusId = cpCampus.SelectedValueAsId(); group.Description = tbDescription.Text; //Set location if (lopAddress.Location != null && lopAddress.Location.Id != 0) { if (group.GroupLocations != null && !group.GroupLocations.Select(gl => gl.LocationId).Contains(lopAddress.Location.Id)) { // Disassociate the old address(es) GroupLocationService groupLocationService = new GroupLocationService(_rockContext); var meetingLocationDv = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION); var homeLocationDv = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME); groupLocationService.DeleteRange(group.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == meetingLocationDv.Id || gl.GroupLocationTypeValueId == homeLocationDv.Id || gl.GroupLocationTypeValueId == null)); group.GroupLocations.Add(new GroupLocation() { LocationId = lopAddress.Location.Id, GroupLocationTypeValueId = meetingLocationDv.Id }); } } //Set Schedule if (_groupType.AllowedScheduleTypes != ScheduleType.None) { switch (rblSchedule.SelectedValueAsEnum <ScheduleType>()) { case ScheduleType.None: group.ScheduleId = null; break; case ScheduleType.Weekly: var weeklySchedule = new Schedule() { WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek, WeeklyTimeOfDay = timeWeekly.SelectedTime }; group.Schedule = weeklySchedule; break; case ScheduleType.Custom: var customSchedule = new Schedule() { iCalendarContent = sbSchedule.iCalendarContent }; group.Schedule = customSchedule; break; case ScheduleType.Named: if (spSchedule.SelectedValue.AsInteger() != 0) { group.ScheduleId = spSchedule.SelectedValue.AsInteger(); } break; default: break; } } if (group.Members != null && group.Members.Any()) { foreach (var member in group.Members.Where(gm => gm.PersonId != _person.Id)) { member.GroupMemberStatus = GroupMemberStatus.Inactive; } foreach (int groupMemberId in gMembers.SelectedKeys) { var groupMember = group.Members.Where(m => m.Id == groupMemberId).FirstOrDefault(); if (groupMember != null) { groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } } else { var groupRoleId = new GroupTypeRoleService(_rockContext).Get(GetAttributeValue("GroupRole").AsGuid()).Id; group.Members.Add(new GroupMember() { PersonId = _person.Id, GroupRoleId = groupRoleId }); } //Save attributes _rockContext.SaveChanges(); group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phAttributes, group); var attributeGuid = GetAttributeValue("MultiSelectAttribute"); var multiselectAttribute = new AttributeService(_rockContext).Get(attributeGuid.AsGuid()); if (multiselectAttribute != null) { var attributeValue = group.GetAttributeValue(multiselectAttribute.Key) .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); var newAttributeText = GetAttributeValue("AttributeText"); if (!attributeValue.Contains(newAttributeText)) { attributeValue.Add(newAttributeText); } group.SetAttributeValue(multiselectAttribute.Key, string.Join(",", attributeValue)); } group.SaveAttributeValues(); //Update cache var availableGroupIds = (List <int>)GetCacheItem(GetAttributeValue("DestinationGroup")); if (availableGroupIds != null) { availableGroupIds.Add(group.Id); AddCacheItem(GetAttributeValue("DestinationGroup"), availableGroupIds); } var workflowTypeService = new WorkflowTypeService(_rockContext); WorkflowTypeCache workflowType = null; Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull(); if (workflowTypeGuid.HasValue) { workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value); } GroupMember currentGroupMember = group.Members.Where(gm => gm.PersonId == _person.Id).FirstOrDefault(); if (currentGroupMember != null && workflowType != null && (workflowType.IsActive ?? true)) { try { List <string> workflowErrors; var workflow = Workflow.Activate(workflowType, _person.FullName); if (workflow.AttributeValues.ContainsKey("Group")) { if (group != null) { workflow.AttributeValues["Group"].Value = group.Guid.ToString(); } } if (workflow.AttributeValues.ContainsKey("Person")) { if (_person != null) { workflow.AttributeValues["Person"].Value = _person.PrimaryAlias.Guid.ToString(); } } new WorkflowService(_rockContext).Process(workflow, currentGroupMember, out workflowErrors); } catch (Exception ex) { ExceptionLogService.LogException(ex, this.Context); } } ShowMessage(GetAttributeValue("SuccessText"), "Thank you!", "panel panel-success"); }
public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (this.CheckCancelled(importJob) || this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed || this.CheckPointStageCallback(this)) { return; } var workflowManager = WorkflowManager.Instance; var workflowStateManager = WorkflowStateManager.Instance; var portalId = importJob.PortalId; var importWorkflows = this.Repository.GetAllItems <ExportWorkflow>().ToList(); var existWorkflows = workflowManager.GetWorkflows(portalId).ToList(); var defaultTabWorkflowId = importWorkflows.FirstOrDefault(w => w.IsDefault)?.WorkflowID ?? 1; this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? importWorkflows.Count : this.CheckPoint.TotalItems; foreach (var importWorkflow in importWorkflows) { var workflow = existWorkflows.FirstOrDefault(w => w.WorkflowName == importWorkflow.WorkflowName); if (workflow != null) { if (!importWorkflow.IsSystem && importDto.CollisionResolution == CollisionResolution.Overwrite) { if (workflow.Description != importWorkflow.Description || workflow.WorkflowKey != importWorkflow.WorkflowKey) { workflow.Description = importWorkflow.Description; workflow.WorkflowKey = importWorkflow.WorkflowKey; workflowManager.UpdateWorkflow(workflow); this.Result.AddLogEntry("Updated workflow", workflow.WorkflowName); } } } else { workflow = new Workflow { PortalID = portalId, WorkflowName = importWorkflow.WorkflowName, Description = importWorkflow.Description, WorkflowKey = importWorkflow.WorkflowKey, }; workflowManager.AddWorkflow(workflow); this.Result.AddLogEntry("Added workflow", workflow.WorkflowName); if (importWorkflow.WorkflowID == defaultTabWorkflowId) { TabWorkflowSettings.Instance.SetDefaultTabWorkflowId(portalId, workflow.WorkflowID); } } importWorkflow.LocalId = workflow.WorkflowID; var importStates = this.Repository.GetRelatedItems <ExportWorkflowState>(importWorkflow.Id).ToList(); foreach (var importState in importStates) { var workflowState = workflow.States.FirstOrDefault(s => s.StateName == importState.StateName); if (workflowState != null) { if (!workflowState.IsSystem) { workflowState.Order = importState.Order; workflowState.IsSystem = false; workflowState.SendNotification = importState.SendNotification; workflowState.SendNotificationToAdministrators = importState.SendNotificationToAdministrators; workflowStateManager.UpdateWorkflowState(workflowState); this.Result.AddLogEntry("Updated workflow state", workflowState.StateID.ToString()); } } else { workflowState = new WorkflowState { StateName = importState.StateName, WorkflowID = workflow.WorkflowID, Order = importState.Order, IsSystem = importState.IsSystem, SendNotification = importState.SendNotification, SendNotificationToAdministrators = importState.SendNotificationToAdministrators, }; WorkflowStateManager.Instance.AddWorkflowState(workflowState); this.Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString()); } importState.LocalId = workflowState.StateID; if (!workflowState.IsSystem) { var importPermissions = this.Repository.GetRelatedItems <ExportWorkflowStatePermission>(importState.Id).ToList(); foreach (var importPermission in importPermissions) { var permissionId = DataProvider.Instance().GetPermissionId( importPermission.PermissionCode, importPermission.PermissionKey, importPermission.PermissionName); if (permissionId != null) { var noRole = Convert.ToInt32(Globals.glbRoleNothing); var userId = UserController.GetUserByName(importDto.PortalId, importPermission.Username)?.UserID; var roleId = Util.GetRoleIdByName(importDto.PortalId, importPermission.RoleID ?? noRole, importPermission.RoleName); var permission = new WorkflowStatePermission { PermissionID = permissionId ?? -1, StateID = workflowState.StateID, RoleID = noRole, UserID = -1, AllowAccess = importPermission.AllowAccess, }; if (importPermission.UserID != null && importPermission.UserID > 0 && !string.IsNullOrEmpty(importPermission.Username)) { if (userId == null) { this.Result.AddLogEntry( "Couldn't add tab permission; User is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } permission.UserID = userId.Value; } if (importPermission.RoleID != null && importPermission.RoleID > noRole && !string.IsNullOrEmpty(importPermission.RoleName)) { if (roleId == null) { this.Result.AddLogEntry( "Couldn't add tab permission; Role is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } permission.RoleID = roleId.Value; } try { var existingPermissions = workflowStateManager.GetWorkflowStatePermissionByState(workflowState.StateID); var local = existingPermissions.FirstOrDefault( x => x.PermissionCode == importPermission.PermissionCode && x.PermissionKey == importPermission.PermissionKey && x.PermissionName.Equals(importPermission.PermissionName, StringComparison.InvariantCultureIgnoreCase) && x.RoleID == roleId && x.UserID == userId); if (local == null) { workflowStateManager.AddWorkflowStatePermission(permission, -1); importPermission.LocalId = permission.WorkflowStatePermissionID; this.Result.AddLogEntry( "Added workflow state permission", permission.WorkflowStatePermissionID.ToString()); } else { importPermission.LocalId = local.WorkflowStatePermissionID; } } catch (Exception ex) { this.Result.AddLogEntry("Exception adding workflow state permission", ex.Message, ReportLevel.Error); } } } } } this.Repository.UpdateItems(importStates); this.Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString()); this.CheckPoint.ProcessedItems++; this.CheckPointStageCallback(this); // no need to return; very small amount of data processed } this.Repository.UpdateItems(importWorkflows); this.CheckPoint.Stage++; this.CheckPoint.StageData = null; this.CheckPoint.Progress = 100; this.CheckPoint.TotalItems = importWorkflows.Count; this.CheckPoint.ProcessedItems = importWorkflows.Count; this.CheckPointStageCallback(this); }
public ArgumentValidationResult(string argumentName, Workflow workflow, ValidationResultType type, string message) : base(message, type) { Workflow = workflow; ArgumentName = argumentName; }