示例#1
0
        //Method to execute the specified flow a specified number of times.
        public void StartFlowExecution()
        {
            //Register the user
            using (UserContextHolder.Register(_userContext))
            {
                //Create a stopwatch and kick it off, logging a guid to identify the batch of flow runs
                string    threadExecutionId = System.Guid.NewGuid().ToString();
                Stopwatch outerStopWatch    = new Stopwatch();
                Log.Error("Starting Thread: " + threadExecutionId + ", number of executions: " + _executions + ",flow: " + _flowId);
                outerStopWatch.Start();

                //Kick off the specified flow executions with the Flow Engine
                for (int i = 0; i < _executions; i++)
                {
                    //Create a stopwatch and kick it off, logging a guid to identify the individual flow run
                    string    flowExecutionId = System.Guid.NewGuid().ToString();
                    Stopwatch innerStopWatch  = new Stopwatch();
                    Log.Error("Starting Flow Run: " + flowExecutionId);
                    innerStopWatch.Start();

                    //Execute the flow with canned data
                    FlowEngine.StartSyncFlow(FlowEngine.GetFlow(_flowId),
                                             GetFlowStateData());

                    //Stop the stopwatch and log how much time it took for the individual flow run
                    innerStopWatch.Stop();
                    Log.Error("Flow Run " + flowExecutionId + " took: " + innerStopWatch.Elapsed.TotalMilliseconds +
                              " milliseconds.");
                }

                //Stop the stopwatch and log how much time it took for the batch of flow runs
                outerStopWatch.Stop();
                Log.Error("Thread: " + threadExecutionId + ", number of executions: " + _executions + ",flow: " + _flowId + ", took " + outerStopWatch.Elapsed.TotalSeconds + " seconds.");
            }
        }
示例#2
0
        private void AddOrUpdateCRMEntityWithDataStructure(IOrganizationService serviceProxy, string crmEntityName, SimpleFlowStructure simpleFlowStructure)
        {
            RetrieveEntityResponse crmEntity = GetEntityInformationFromCRMClient(serviceProxy, crmEntityName);

            if (crmEntity != null)
            {
                log.Info("CRM entity fetched successfully from server");
                List <AttributeMetadata>         entityAttributes = crmEntity.EntityMetadata.Attributes.Where(t => t.IsValidForCreate == true).ToList();
                List <CRMEntityField>            entityFields;
                List <DefinedDataTypeDataMember> memberList;

                GetEntityFieldsFromCRMEntityAttributes(entityAttributes, crmEntityName, out entityFields, out memberList);

                simpleFlowStructure.Children = memberList.ToArray();
                CRMEntityFields = entityFields.ToArray();
                string displayName;
                if (crmEntity.EntityMetadata.DisplayName.LocalizedLabels != null && crmEntity.EntityMetadata.DisplayName.LocalizedLabels.Count > 0)
                {
                    displayName = crmEntity.EntityMetadata.DisplayName.LocalizedLabels[0].Label;
                }
                else
                {
                    displayName = crmEntity.EntityMetadata.LogicalName;
                }
                CRMEntityDisplayName = displayName;
                DataStructureService.Instance.AddDataStructure(UserContextHolder.GetRootUserContext(), simpleFlowStructure);
                log.Info(string.Format("Entity with name {0} added successfully to the database", crmEntityName));
            }
        }
示例#3
0
        public DecisionsFramework.Design.Flow.FlowStep ConvertStep(ConversionData allConvertData, ConvertedStep stepToConvert)
        {
            SystemUserContext suc = new SystemUserContext();

            using (UserContextHolder.Register(suc))
            {
                LinkedFlowStep lfs = new LinkedFlowStep();

                // Get name of flow to run / id of flow to run.
                StepInput flowId = stepToConvert.StepProperties.FirstOrDefault(x => x.Name == "EmbeddedFlowId");

                //string flowId = flowName.ConstantValue;
                //foreach (Flow cf in allConvertData.ConvertedFlows)
                //{
                //    if (cf.Name == flowName.ConstantValue)
                //    {
                //        flowId = cf.Id;
                //    }
                //}


                lfs.RegistrationId = flowId.ConstantValue;

                return(new FlowStep(lfs));
            }
        }
示例#4
0
        //This method is called when the module is initialized
        public void Initialize()
        {
            //Create the Base Flow Folder which will take on the implemented behavior if it doesn't already exist
            //This folder will be added for everyone
            SystemUserContext suc = new SystemUserContext();

            if (FolderService.Instance.Exists(suc, RESTRICTED_STEPS_FOLDER_EXAMPLE) == false)
            {
                //Create the folder at the root
                FolderService.Instance.CreateRootFolder(suc, RESTRICTED_STEPS_FOLDER_EXAMPLE, "Restricted Flow Steps", typeof(RestrictedStepsFolderBehavior).FullName);

                //Add all Permissions besides ADMIN for the DESIGNERS group so DESIGNERS can create flows in this folder.
                //IF we want to always ensure this permission we would move it OUT of this if block.
                FolderService.Instance.AddGroupPermission(UserContextHolder.GetCurrent(), RESTRICTED_STEPS_FOLDER_EXAMPLE, Constants.DESIGNERS_GROUP_ID, FolderPermission.AllButAdmin);
            }

            //Example Call to REMOVE the created folder
            //FolderService.Instance.DeleteFolder(suc, RESTRICTED_STEPS_FOLDER_EXAMPLE, false);
        }
        public void ListFlowToolboxSteps(string csvOutputPath, string csvFileName)
        {
            AbstractUserContext userContext   = UserContextHolder.GetCurrent();
            FlowEngine          currentEngine = FlowEngine.CurrentEngine;
            string flowId = currentEngine.CurrentTrackingData.FlowId;

            FlowEditSession flowEditSession = FlowEditService.Instance.OpenFlowForEditing(userContext, flowId);

            string[] toolboxCategories =
                FlowEditService.Instance.GetToolboxCategories(userContext, flowEditSession.FlowSessionId, new string[] {});

            List <string> stepInfos = new List <string>();

            foreach (string category in toolboxCategories)
            {
                stepInfos.AddRange(GetStepsInSubCategory(userContext, flowEditSession.FlowSessionId, new [] { category }));
            }

            string filePath = Path.Combine(csvOutputPath, csvFileName);

            File.WriteAllLines(filePath, stepInfos);
        }
        //Method to create a flow with the implemented behavior using Element Registration Helper
        //entityId is the ID of the folder being acted on
        //answer is the text provided by the user who triggered the GetStringAction and will become the name of the rule
        private void CreateRestrictedFlow(AbstractUserContext userContext, string entityID, string answer)
        {
            //Create the flow with the implemented flow behavior
            ElementContextInfo info = new ElementContextInfo(entityID, ElementType.Flow, null,
                                                             typeof(RestrictedStepsFlowBehavior).FullName, null, answer);

            string createdElementRegistrationId = null;

            if (info.ShowIntent)
            {
                FlowInputDataDescription[] inputs = (info.ShowData) ? info.FlowInputs : null;
                string flowExecutionsInFolderId   = (info.ShowTracking && info.SetupReportingOnFlowExecution) ? info.StoreFlowExecutionsInFolderId : null;
                string flowRunIdPrefix            = (info.ShowTracking && info.SetupReportingOnFlowExecution) ? info.Prefix : null;

                // we are going to create based on intent
                createdElementRegistrationId =
                    ConfigurationStorageService.Instance.CreateFlowWithExtraSettings(UserContextHolder.GetCurrent(),
                                                                                     info.FolderId, info.Name, inputs, flowExecutionsInFolderId, flowRunIdPrefix);
            }
            else
            if (info.BasedOn == CreateElementBasedOn.Template && !string.IsNullOrEmpty(info.TemplateId))
            {
                createdElementRegistrationId =
                    ConfigurationStorageService.Instance.CreateFlowFromTemplate(UserContextHolder.GetCurrent(), info.FolderId, info.Name, info.TemplateId);
            }
            else
            if (info.BasedOn == CreateElementBasedOn.Behavior && !string.IsNullOrWhiteSpace(info.BehaviorType))
            {
                createdElementRegistrationId =
                    ConfigurationStorageService.Instance.CreateFlowFromTemplateAndBehaviorType(UserContextHolder.GetCurrent(), info.FolderId, info.Name, null, info.BehaviorType);
            }

            if (string.IsNullOrEmpty(createdElementRegistrationId))
            {
                ConfigurationStorageService.Instance.CreateFlow(UserContextHolder.GetCurrent(), info.FolderId, info.Name);
            }
        }
示例#7
0
        private void GetEntityFieldsFromCRMEntityAttributes(List <AttributeMetadata> entityAttributes, string crmEntityName, out List <CRMEntityField> entityFields, out List <DefinedDataTypeDataMember> memberList)
        {
            entityFields = new List <CRMEntityField>();
            memberList   = new List <DefinedDataTypeDataMember>();
            if (entityAttributes.Count() > 0)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug(string.Join(", ", entityAttributes.Select(x => $"{x.LogicalName}({x.DisplayName})[{x.AttributeType}, ")));
                }

                foreach (AttributeMetadata attribute in entityAttributes)
                {
                    Type type = GetTypeFromAttributeType(attribute.AttributeType);
                    if (type != null)
                    {
                        string displayName;
                        if (attribute.DisplayName.LocalizedLabels != null && attribute.DisplayName.LocalizedLabels.Count > 0)
                        {
                            displayName = attribute.DisplayName.LocalizedLabels[0].Label;
                        }
                        else
                        {
                            displayName = attribute.LogicalName;
                        }
                        bool?validForUpdate = attribute.IsValidForUpdate;
                        DefinedDataTypeDataMember member = new DefinedDataTypeDataMember();
                        member.RelationshipName             = attribute.LogicalName;
                        member.DisplayLabelName             = CleanDisplayName(displayName);
                        member.IsOverrideDisplayInformation = true;
                        member.RelatedToDataType            = type.FullName;
                        member.AllowNull = true;

                        if (attribute.AttributeType == AttributeTypeCode.Uniqueidentifier || attribute.IsPrimaryId == true)
                        {
                            member.CustomAttributes = new CustomAttributeDefinition[] { new CustomAttributeDefinition("PropertyHidden", new string[0]) };
                            validForUpdate          = false;
                        }
                        CRMEntityField entityField = new CRMEntityField()
                        {
                            DisplayName      = CleanDisplayName(displayName),
                            FieldName        = attribute.LogicalName,
                            FieldType        = new DecisionsNativeType(type),
                            IsValidForUpdate = validForUpdate,
                            AttributeType    = attribute.AttributeType.ToString()
                        };

                        if (attribute.AttributeType == AttributeTypeCode.Picklist)
                        {
                            ORM <EnumDataType> orm = new ORM <EnumDataType>();

                            //Check this type of enum data is present in database or not
                            // and either create it or update it
                            string currentOptionSetDataTypeName = string.Format("{0}_{1}", crmEntityName, attribute.LogicalName);

                            EnumDataType optionsSet = orm.Fetch(new WhereCondition[]
                            {
                                new FieldWhereCondition("data_type_name", QueryMatchType.Equals, currentOptionSetDataTypeName),
                                new FieldWhereCondition("data_type_name_space", QueryMatchType.Equals, GetCrmEntityNamespace())
                            }).FirstOrDefault();

                            if (optionsSet == null)
                            {
                                log.Debug($"No enum type with name '{currentOptionSetDataTypeName}' and namespace '{GetCrmEntityNamespace()}' found, trying to create one:");
                                EnsureCrmEntityFolderExists();
                                optionsSet = new EnumDataType();
                                optionsSet.DataTypeName      = currentOptionSetDataTypeName;
                                optionsSet.DataTypeNameSpace = GetCrmEntityNamespace();
                                optionsSet.EntityFolderID    = GetCrmEntityFolderId();
                                optionsSet.EnumValues        = CleanEnumValues(((PicklistAttributeMetadata)attribute).OptionSet.Options.Select(t => t.Label.LocalizedLabels[0].Label).ToArray());
                                orm.Store(optionsSet);
                                log.Debug($"new enum type created for '{currentOptionSetDataTypeName}'");
                            }
                            else
                            {
                                log.Debug($"Enum type '{GetCrmEntityNamespace()}.{currentOptionSetDataTypeName}' already exists; updating its enum value list.");

                                string[] enumValues = CleanEnumValues(((PicklistAttributeMetadata)attribute).OptionSet.Options.Select(t => t.Label.LocalizedLabels[0].Label).ToArray());

                                if (log.IsDebugEnabled)
                                {
                                    log.Debug(string.Join(", ", ((PicklistAttributeMetadata)attribute).OptionSet.Options.Select(t => $"'{t.Label.LocalizedLabels[0].Label}':'{t.Value}'")));
                                }

                                DataStructureService.Instance.ChangeEnumValues(UserContextHolder.GetRootUserContext(), GetCrmEntityNamespace(), currentOptionSetDataTypeName, enumValues);

                                log.Debug("Enum value list updated.");
                            }

                            string generatedEnumFullTypeName = string.Format("{0}.{1}", GetCrmEntityNamespace(), currentOptionSetDataTypeName);

                            member.RelatedToDataType = generatedEnumFullTypeName;
                            List <CRMOptionsSet> options = new List <CRMOptionsSet>();
                            foreach (var option in ((PicklistAttributeMetadata)attribute).OptionSet.Options)
                            {
                                options.Add(new CRMOptionsSet()
                                {
                                    OptionName = option.Label.LocalizedLabels[0].Label.Replace(" ", ""), OptionValue = option.Value
                                });
                            }
                            entityField.CRMOptionSet = options.ToArray();
                        }

                        if (attribute.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired || attribute.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired)
                        {
                            entityField.IsRequired = true;
                            member.Required        = true;
                        }

                        entityFields.Add(entityField);
                        memberList.Add(member);
                    }
                }
            }
        }
示例#8
0
 public override bool IsVisible(Folder f)
 {
     return(UserContextHolder.GetCurrent().StudioPortal);
 }
示例#9
0
        private void SetValues(string opcServerUrl, string eventId, BaseTagValueWrapper valuesWrapper)
        {
            BaseTagValue[] values = valuesWrapper.Values;
            using (UserContextHolder.Register(new SystemUserContext()))
            {
                Folder configFolder = EntityCache <OPCServerFolderBehaviorData> .GetCache().AllEntities.FirstOrDefault(s => s.Url == opcServerUrl)?.GetEntity() as Folder;

                if (configFolder == null)
                {
                    return;
                }

                Array.ForEach(values, tagValue => { LOG.Debug($"Value Change: {tagValue.Path} - {TagValueUtils.GetObjectValueFromTag(tagValue)}"); });

                // put values in last cache
                foreach (var v in values)
                {
                    string       key = eventId + "|" + v.Path;
                    BaseTagValue priorValue;
                    OPCEngine.mostRecentValues.TryGetValue(key, out priorValue);

                    OPCEngine.mostRecentValues[key] = v;

                    if (priorValue == null)
                    {
                        OPCEngine.priorValues[key] = v;
                    }
                    else
                    {
                        OPCEngine.priorValues[key] = priorValue;
                    }
                }

                OPCEvent opcEvent = opcEventOrm.Fetch(eventId);
                if (opcEvent == null || opcEvent.Disabled)
                {
                    return;
                }

                bool runIt = false;
                // see if this event is interested in this change
                foreach (var v in opcEvent.EventValues)
                {
                    if (values.FirstOrDefault(changedValue => changedValue.Path == v.PathToValue) != null)
                    {
                        runIt = true;
                        break;
                    }
                }

                if (runIt)
                {
                    try
                    {
                        List <DataPair> inputs = new List <DataPair>();

                        foreach (var v in opcEvent.EventValues)
                        {
                            string       key   = eventId + "|" + v.PathToValue;
                            BaseTagValue value = null;

                            OPCEngine.mostRecentValues.TryGetValue(key, out value);

                            inputs.Add(new DataPair(v.Name, value));

                            BaseTagValue priorvalue = null;

                            OPCEngine.priorValues.TryGetValue(key, out priorvalue);

                            inputs.Add(new DataPair("Last " + v.Name, priorvalue));
                        }

                        inputs.Add(new DataPair("LastWorkflowRun", opcEvent.LastRun));

                        // check rule to see if it matches
                        var ruleResult = RuleEngine.RunRule(opcEvent.Rule, inputs.ToArray());

                        if (ruleResult != null && ruleResult is bool)
                        {
                            if (((bool)ruleResult) == true)
                            {
                                new Log("OPC").Error("Value Changed And Rule Returned True - running flow");
                                FlowEngine.Start(FlowEngine.LoadFlowByID(opcEvent.Flow, false, true),
                                                 new FlowStateData(inputs.ToArray()));
                            }
                            else
                            {
                                new Log("OPC").Error("Value Changed But Rule Returned False");
                            }
                        }
                        else
                        {
                            new Log("OPC").Error("Value Changed But Rule Returned False");
                        }
                    }
                    catch (Exception except)
                    {
                        new Log("OPC").Error(except, "Error running flow from event");
                    }
                }
            }
        }