コード例 #1
0
        public Account GetAccountFromSession(string session)
        {
            // Set up an account to return
            Account account = null;

            // Access the session string here, it's sent in on the request as an HTTP Header
            // Key : Authorization
            // Value : Session XYZ
            // Where XYZ would be the JWT Token you want to authorize
            if (!string.IsNullOrEmpty(session))
            {
                // Here, you would do some logic to access/validate your JWT Token against your service

                // Here, you would use the response from your service to look up an account using our Account ORM
                ORM <Account> accountOrm = new ORM <Account>();

                // Fetch the account using some criteria in WhereConditions
                // For Example, if your service returns an email address for a validated JWT token
                // Use it to fetch the account by email_address
                Account[] accounts = accountOrm.Fetch(new WhereCondition[]
                {
                    new FieldWhereCondition("email_address", QueryMatchType.Equals, "Email Address From Service")
                });

                if (accounts.Length == 1)
                {
                    account = accounts[0];
                }
            }

            return(account);
        }
コード例 #2
0
        public override DataDescription[] ProcessInputDeclaration(Rule flow, DataDescription[] inputData)
        {
            var id = flow.Source?.ComponentRegistrationId?.Split('.').FirstOrDefault();

            if (id != null)
            {
                ORM <OPCEvent> orm = new ORM <OPCEvent>();
                var            e   = orm.Fetch(id);

                if (e != null)
                {
                    List <DataDescription> output = new List <DataDescription>();

                    foreach (var ev in e.EventValues)
                    {
                        Type tagType = TagValueUtils.GetTagValueType(TypeUtilities.FindTypeByFullName(ev.TypeName));
                        output.Add(new DataDescription(tagType, ev.Name));
                        output.Add(new DataDescription(tagType, "Last " + ev.Name));
                    }

                    output.Add(new DataDescription(typeof(DateTime), "LastWorkflowRun"));

                    output.AddRange(base.ProcessInputDeclaration(flow, inputData));

                    return(output.ToArray());
                }
            }

            return(base.ProcessInputDeclaration(flow, inputData));
        }
コード例 #3
0
        public void Initialize()
        {
            ORM <Folder> orm = new ORM <Folder>();

            if (orm.Fetch("OPCBaseFolder") == null)
            {
                Folder f = new Folder();
                f.FolderID           = "OPCBaseFolder";
                f.CanBeRoot          = true;
                f.EntityName         = "OPC Servers";
                f.FolderBehaviorType = typeof(OPCServersFolderBehavior).FullName;
                f.Store();
            }

            ORM <PageData> pageDataOrm = new ORM <PageData>();
            PageData       pageData    = pageDataOrm.Fetch(new WhereCondition[] {
                new FieldWhereCondition("configuration_storage_id", QueryMatchType.Equals, SERVERS_PAGE_ID),
                new FieldWhereCondition("entity_folder_id", QueryMatchType.Equals, "OPCBaseFolder")
            }).FirstOrDefault();

            if (pageData == null)
            {
                pageDataOrm.Store(new PageData
                {
                    EntityFolderID         = "OPCBaseFolder",
                    ConfigurationStorageID = SERVERS_PAGE_ID,
                    EntityName             = "Servers",
                    Order = -1
                });
            }

            LookupListRegistration.Instance.RegisterObjectForType(typeof(OPCDataProvider), new OPCLookupListProvider());
        }
コード例 #4
0
        public override FlowStepToolboxInformation[] GetStepsInformation(string[] nodes, string flowId, string folderId)
        {
            // return step info
            if (nodes == null || nodes.Length != 4 || nodes[0] != "Data" || nodes[1] != PARENT_NODE)
            {
                return(new FlowStepToolboxInformation[0]);
            }

            List <FlowStepToolboxInformation> list = new List <FlowStepToolboxInformation>();
            CRM2011Connection connection           = CRM2011Connection.GetCRMConnectionForName(nodes[2]);

            if (connection == null)
            {
                return(new FlowStepToolboxInformation[0]);
            }

            ORM <CRM2011Entity> orm = new ORM <CRM2011Entity>();

            CRM2011Entity[] crmEntities = orm.Fetch(new WhereCondition[] {
                new FieldWhereCondition("connection_id", QueryMatchType.Equals, connection.connectionId),
                new FieldWhereCondition("crm_entity_display_name", QueryMatchType.Equals, nodes[3])
            });

            foreach (CRM2011Entity entity in crmEntities)
            {
                list.Add(new FlowStepToolboxInformation("Get All Entities", nodes, string.Format(GET_ALL_STEP_INFO + "${0}", entity.entityId)));
                list.Add(new FlowStepToolboxInformation("Get Entity By Id", nodes, string.Format(GET_STEP_INFO + "${0}", entity.entityId)));
                list.Add(new FlowStepToolboxInformation("Add Entity", nodes, string.Format(ADD_STEP_INFO + "${0}", entity.entityId)));
                list.Add(new FlowStepToolboxInformation("Update Entity", nodes, string.Format(UPDATE_STEP_INFO + "${0}", entity.entityId)));
                list.Add(new FlowStepToolboxInformation("Delete Entity", nodes, string.Format(DELETE_STEP_INFO + "${0}", entity.entityId)));
            }
            return(list.ToArray());
        }
コード例 #5
0
        public void Initialize()
        {
            ORM <Folder> orm    = new ORM <Folder>();
            Folder       folder = (Folder)orm.Fetch(typeof(Folder), CRM_LIST_FOLDER_ID);

            if (folder == null)
            {
                Log log = new Log("MSCRM 2011 Folder Behavior");
                log.Debug("Creating System Folder '" + CRM_LIST_FOLDER_ID + "'");
                folder = new Folder(CRM_LIST_FOLDER_ID, "MSCRM 2011", Constants.INTEGRATIONS_FOLDER_ID);
                folder.FolderBehaviorType = typeof(CRM2011FolderBehavior).FullName;

                orm.Store(folder);
            }

            ORM <PageData> pageDataOrm = new ORM <PageData>();
            PageData       pageData    = pageDataOrm.Fetch(new WhereCondition[] {
                new FieldWhereCondition("configuration_storage_id", QueryMatchType.Equals, CRM_PAGE_ID),
                new FieldWhereCondition("entity_folder_id", QueryMatchType.Equals, CRM_LIST_FOLDER_ID)
            }).FirstOrDefault();

            if (pageData == null)
            {
                pageData = new PageData {
                    EntityFolderID         = CRM_LIST_FOLDER_ID,
                    ConfigurationStorageID = CRM_PAGE_ID,
                    EntityName             = "MSCRM 2011 Entities",
                    Order = -1
                };
                pageDataOrm.Store(pageData);
            }

            // This generated types folder will be shared with the 2016 module:
            Folder typesFolder = orm.Fetch(CRM2011Entity.CRM_GENERATED_TYPES_FOLDER_ID);

            if (typesFolder == null)
            {
                Log log = new Log("MSCRM 2011 Folder Behavior");
                log.Debug("Creating System Folder '" + CRM2011Entity.CRM_GENERATED_TYPES_FOLDER_ID + "'");
                typesFolder = new Folder(CRM2011Entity.CRM_GENERATED_TYPES_FOLDER_ID, "MSCRM", Constants.DATA_STRUCTURES_FOLDER_ID);
                orm.Store(typesFolder);
            }

            FlowEditService.RegisterModuleBasedFlowStepFactory(new CRM2011StepsFactory());
        }
コード例 #6
0
        public string GetStatus(AbstractUserContext userContext, string externalEntityInvocationId)
        {
            ORM <ExternalInvocationEntity> externalInvocationEntityOrm = new ORM <ExternalInvocationEntity>();
            ExternalInvocationEntity       externalInvocationEntity    = externalInvocationEntityOrm.Fetch(externalEntityInvocationId);

            Log.Warn("Get Status Operation Successfully Invoked");

            return(externalInvocationEntity.Status);
        }
コード例 #7
0
        private string FindAccessToken(string id)
        {
            ORM <OAuthToken> orm = new ORM <OAuthToken>();
            var token            = orm.Fetch(id);

            if (token != null)
            {
                return(token.TokenData);
            }
            throw new EntityNotFoundException($"Can not find token with TokenId=\"{id}\"");
        }
コード例 #8
0
        public IORMEntity[] AccountsContainingSpecificName()
        {
            ORM <Account> aORM = new ORM <Account>();

            FieldWhereCondition fieldWhereCondition = new FieldWhereCondition("user_identifier", QueryMatchType.Equals, "*****@*****.**");

            WhereCondition[] whereConditions = new WhereCondition[]
            {
                fieldWhereCondition
            };

            IORMEntity[] results = aORM.Fetch(whereConditions);

            return(results);
        }
コード例 #9
0
        internal void EnsureCrmConnectionFolderExists()
        {
            if (connectionId == null)
            {
                throw new InvalidOperationException("Cannot create a folder for an incomplete connection.");
            }
            ORM <Folder> folderORM             = new ORM <Folder>();
            string       crmConnectionFolderId = GetCrmConnectionFolderId();
            Folder       crmEntityFolder       = folderORM.Fetch(crmConnectionFolderId);

            if (crmEntityFolder == null)
            {
                crmEntityFolder = new Folder(crmConnectionFolderId, connectionName, CRM2011Entity.CRM_GENERATED_TYPES_FOLDER_ID);
                folderORM.Store(crmEntityFolder);
            }
        }
コード例 #10
0
        public void Complete(AbstractUserContext userContext, string externalEntityInvocationId)
        {
            ORM <ExternalInvocationEntity> externalInvocationEntityOrm = new ORM <ExternalInvocationEntity>();
            ExternalInvocationEntity       externalInvocationEntity    = externalInvocationEntityOrm.Fetch(externalEntityInvocationId);

            // Get the flow engine for the flow we'd like to complete
            FlowEngine engine = FlowEngine.GetEngine(externalInvocationEntity.FlowTrackingId);

            // Call Done to tell the Engine the Step is complete
            engine.Done(externalInvocationEntity.FlowTrackingId, externalInvocationEntity.StepTrackingId, new ResultData("Done"));

            // Mark the Entity Invocation Completed
            externalInvocationEntity.Status = "Completed";

            // Store the entity
            externalInvocationEntityOrm.Store(externalInvocationEntity);

            Log.Warn("Complete Operation Successfully Invoked");
        }
コード例 #11
0
        private void RebuildTagCache(Folder f)
        {
            ORM <Folder> orm = new ORM <Folder>();

            if (orm.Fetch(f.FolderID + ".tagdata") == null)
            {
                Folder tagf = new Folder();
                tagf.EntityFolderID     = f.FolderID;
                tagf.EntityName         = "Tag Data";
                tagf.FolderBehaviorType = typeof(DefaultFolderBehavior).FullName;
                tagf.FolderID           = f.FolderID + ".tagdata";
                tagf.Store();
            }

            OPCServerFolderBehaviorData folderExt = f.GetExtensionData <OPCServerFolderBehaviorData>();
            var url = folderExt.Url;

            OPCEngine.GetInitialData(url, folderExt.AgentId, false);
        }
コード例 #12
0
        private void EnsureCrmEntityFolderExists()
        {
            if (Connection == null)
            {
                throw new InvalidOperationException("Could not find connection.");
            }

            Connection.EnsureCrmConnectionFolderExists();

            string connectionFolderId = Connection.GetCrmConnectionFolderId();

            ORM <Folder> folderORM         = new ORM <Folder>();
            string       crmEntityFolderId = GetCrmEntityFolderId();
            Folder       crmEntityFolder   = folderORM.Fetch(crmEntityFolderId);

            if (crmEntityFolder == null)
            {
                crmEntityFolder = new Folder(crmEntityFolderId, CRMEntityDisplayName, connectionFolderId);
                folderORM.Store(crmEntityFolder);
            }
        }
コード例 #13
0
        private void AddOrUpdateCRMEntity()
        {
            IOrganizationService serviceProxy = GetCRMClientServiceProxy();

            if (serviceProxy == null)
            {
                throw new Exception("Unable to found CRM client service proxy");
            }
            try
            {
                ORM <SimpleFlowStructure> orm = new ORM <SimpleFlowStructure>();
                //Check current type of entity present in data base or not
                SimpleFlowStructure simpleFlowStructure = orm.Fetch(new WhereCondition[]
                {
                    new FieldWhereCondition("data_type_name", QueryMatchType.Equals, CRMEntityName),
                    new FieldWhereCondition("data_type_name_space", QueryMatchType.Equals, GetCrmEntityNamespace())
                }).FirstOrDefault();

                if (simpleFlowStructure == null)
                {
                    EnsureCrmEntityFolderExists();
                    simpleFlowStructure = new SimpleFlowStructure();
                    simpleFlowStructure.DataTypeNameSpace = GetCrmEntityNamespace();
                    simpleFlowStructure.EntityFolderID    = GetCrmEntityFolderId();
                    simpleFlowStructure.StorageOption     = StorageOption.NotDatabaseStored;
                    simpleFlowStructure.SuperClass        = null;
                    simpleFlowStructure.TemplateForType   = @"DecisionsFramework.Utilities.CodeGeneration.Templates.StringMappedDataStructure.vm";
                }
                simpleFlowStructure.DataTypeName = CRMEntityName;

                AddOrUpdateCRMEntityWithDataStructure(serviceProxy, CRMEntityName, simpleFlowStructure);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
コード例 #14
0
        private void RegenerateDataStructureOfSelectedEntity(AbstractUserContext userContext, string entityId)
        {
            try
            {
                ORM <CRM2011Entity> crmEntityORM = new ORM <CRM2011Entity>();
                CRM2011Entity       crmEntity    = crmEntityORM.Fetch(entityId);
                if (crmEntity != null)
                {
                    log.Info(string.Format("started regenerating data structure of {0} entity", crmEntity.CRMEntityName));
                    ORM <SimpleFlowStructure> simpleFlowStructureORM = new ORM <SimpleFlowStructure>();
                    SimpleFlowStructure       simpleFlowStructure    = simpleFlowStructureORM.Fetch(new WhereCondition[]
                    {
                        new FieldWhereCondition("data_type_name", QueryMatchType.Equals, crmEntity.CRMEntityName),
                        new FieldWhereCondition("data_type_name_space", QueryMatchType.Equals, crmEntity.GetCrmEntityNamespace())
                    }).FirstOrDefault();
                    if (simpleFlowStructure != null)
                    {
                        IOrganizationService serviceProxy = GetCRMClientServiceProxy();
                        if (serviceProxy == null)
                        {
                            throw new BusinessRuleException("Unable to found CRM service client proxy");
                        }

                        simpleFlowStructure.Children = null;
                        AddOrUpdateCRMEntityWithDataStructure(serviceProxy, crmEntity.CRMEntityName, simpleFlowStructure);
                        // Make sure the updated CRMEntityFields are stored:
                        crmEntityORM.Store(this, true, false);
                    }
                    log.Info(string.Format("completed regenerating data structure of {0} entity", crmEntity.CRMEntityName));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
コード例 #15
0
 public override string[] GetSubCategories(string[] nodes, string flowId, string folderId)
 {
     if (nodes == null || nodes.Length == 0)
     {
         return(new string[0]);
     }
     if (nodes[0] == "Data")
     {
         if (nodes.Length == 1)
         {
             return new string[] { PARENT_NODE }
         }
         ;
         if (nodes[1] == PARENT_NODE)
         {
             if (nodes.Length == 2)
             {
                 return(ModuleSettingsAccessor <CRM2011Settings> .Instance.Connections.Select(x => x.ConnectionName).ToArray());
             }
             else if (nodes.Length == 3)
             {
                 CRM2011Connection connection = CRM2011Connection.GetCRMConnectionForName(nodes[2]);
                 if (connection == null)
                 {
                     return(new string[0]);
                 }
                 ORM <CRM2011Entity> orm         = new ORM <CRM2011Entity>();
                 CRM2011Entity[]     crmEntities = orm.Fetch(new WhereCondition[]
                 {
                     new FieldWhereCondition("connection_id", QueryMatchType.Equals, connection.connectionId)
                 });
                 return(crmEntities.Select(t => t.CRMEntityDisplayName).ToArray());
             }
         }
     }
     return(new string[0]);
 }
コード例 #16
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);
                    }
                }
            }
        }
コード例 #17
0
        public override void BeforeSave()
        {
            CRM2011Connection specifiedConnection = connection;

            if (specifiedConnection == null)
            {
                // If 'connection' is null, this might be an import.
                log.Debug("sConnection is null, fetching by ID");
                specifiedConnection = CRM2011Connection.GetCRMConnectionById(connectionId);
                if (specifiedConnection != null)
                {
                    Connection = specifiedConnection;
                }
            }
            // If a connection exists at this point, make sure this entity name doesn't already exist for this connection:
            if (specifiedConnection != null)
            {
                SetNamesFromSelectedName();
                log.Debug($"Checking whether entity already exists with connection_id '{specifiedConnection.connectionId}' and crm_entity_name '{CRMEntityName}'.");
                ORM <CRM2011Entity> orm = new ORM <CRM2011Entity>();
                var conditions          = new List <WhereCondition>
                {
                    new FieldWhereCondition("connection_id", QueryMatchType.Equals, specifiedConnection.connectionId),
                    new FieldWhereCondition("crm_entity_name", QueryMatchType.Equals, this.CRMEntityName)
                };
                if (!string.IsNullOrWhiteSpace(this.entityId))
                {
                    // (if ID is the same, this is an edit)
                    conditions.Add(new FieldWhereCondition("entity_id", QueryMatchType.DoesNotEqual, this.entityId));
                }
                CRM2011Entity otherEntity = orm.Fetch(conditions.ToArray()).FirstOrDefault();
                log.Debug($"entity: {otherEntity?.CRMEntityDisplayName ?? "(null)"}");
                if (otherEntity != null)
                {
                    throw new InvalidOperationException("This entity already exists for this connection.");
                }
            }

            if (specifiedConnection == null)
            {
                // If the ID is missing, this might be an import. Check for a matching name:
                log.Debug("sConnection is null, fetching by name");
                specifiedConnection = CRM2011Connection.GetCRMConnectionForName(connectionName);
            }
            if (specifiedConnection == null)
            {
                // If no connection was found by ID or by name, create one:
                log.Debug("sConnection is null, creating");
                specifiedConnection = new CRM2011Connection()
                {
                    ConnectionName  = connectionName,
                    OrganisationUrl = organisationUrl,
                    Domain          = domain,
                    UserName        = userName,
                    Password        = password
                };
                // Add new connection to settings:
                CRM2011Connection[] oldConnections = ModuleSettingsAccessor <CRM2011Settings> .Instance.Connections;
                ModuleSettingsAccessor <CRM2011Settings> .Instance.Connections = oldConnections.Concat(new[] { specifiedConnection }).ToArray();
                log.Debug($"about to save new connections...");
                ModuleSettingsAccessor <CRM2011Settings> .SaveSettings();

                specifiedConnection = CRM2011Connection.GetCRMConnectionForName(connectionName);
                if (specifiedConnection == null)
                {
                    throw new EntityNotFoundException("CRMConnection was not created successfully.");
                }
                log.Debug("new connections saved.");
            }
            if (specifiedConnection != null)
            {
                // Update our data to match the connection's data:
                log.Debug("sConnection exists, updating data to match it...");
                Connection      = specifiedConnection;
                connectionId    = specifiedConnection.connectionId;
                connectionName  = specifiedConnection.ConnectionName;
                organisationUrl = specifiedConnection.OrganisationUrl;
                domain          = specifiedConnection.Domain;
                userName        = specifiedConnection.UserName;
                password        = specifiedConnection.Password;
            }

            SetNamesFromSelectedName();

            base.BeforeSave();

            AddOrUpdateCRMEntity();
        }
コード例 #18
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");
                    }
                }
            }
        }
コード例 #19
0
        public DataDescription[] GetSubItems()
        {
            Log.Debug($"GetSubItems called on path {Path}");

            if (Path == null || Path == OPCEventFlowBehavior.SNAPSHOT_DATA) // If we're at the top, just return all server names:
            {
                return(opcServerOrm.Fetch()
                       .Select(x => new DataDescription(typeof(OPCDataProvider), x.GetEntity().EntityName, false)
                {
                    NestedVariableName = x.GetEntity().EntityName
                }).ToArray());
            }

            string[] pathSplit = Path.Split(new char[] { '.' }, 2); // {Server Name}.{remaining.tag.path}

            DynamicORM orm = new DynamicORM();

            HashSet <string>       nextPaths = new HashSet <string>();
            List <DataDescription> dds       = new List <DataDescription>();

            foreach (string key in OPCEngine.mostRecentValues.Keys) // keys are like "<guid>|Channel1.Device1.Tag1"
            {
                string[] keySplit   = key.Split('|');
                string   eventId    = keySplit[0];
                string   keyTagPath = keySplit[1];
                OPCEvent ev         = orm.Fetch(typeof(OPCEvent), eventId) as OPCEvent;
                if (ev == null)
                {
                    throw new Exception("OPCEvent not found with id " + eventId);
                }
                string serverName = (orm.Fetch(typeof(Folder), ev.EntityFolderID) as Folder)?.EntityName;
                if (string.IsNullOrEmpty(serverName))
                {
                    throw new Exception("Server name not found");
                }

                if (serverName != pathSplit[0])
                {
                    continue;
                }

                if (pathSplit.Length == 1) // This is the node for the server, so include everything under it:
                {
                    nextPaths.Add(keyTagPath.Split('.')[0]);
                }
                else
                {
                    // If "Channel1.Device1.Tag1" starts with "Channel1.Device1", for example:
                    if (keyTagPath.StartsWith(pathSplit[1]))
                    {
                        string   remainingPath  = keyTagPath.Substring(pathSplit[1].Length + 1); // "Tag1"
                        string[] splitRemaining = remainingPath.Split('.');
                        if (splitRemaining.Length == 1)                                          // This is a tag, so find its type
                        {
                            BaseTagValue tagValue;
                            if (!OPCEngine.mostRecentValues.TryGetValue(key, out tagValue))
                            {
                                throw new Exception("Could not find type for tag " + key);
                            }

                            if (dds.Any(d => d.Name == splitRemaining[0])) // Don't create duplicates - most recent value will be used.
                            {
                                continue;
                            }

                            DataDescription dd = TagValueUtils.GetDataDescriptionFromTagType(tagValue.GetType(), splitRemaining[0]);
                            dd.NestedVariableName = $"{this.Path}.{splitRemaining[0]}";
                            dds.Add(dd);
                        }
                        else
                        {
                            nextPaths.Add(splitRemaining[0]);
                        }
                    }
                }
            }

            foreach (string nextPath in nextPaths)
            {
                dds.Add(new DataDescription(typeof(OPCDataProvider), nextPath, false)
                {
                    NestedVariableName = $"{this.Path}.{nextPath}"
                });
            }

            return(dds.ToArray());
        }