Monday, 15 August 2016

Retrieve data from configuration record using C# in Dynamics CRM

Hi guys,

In continuation of my previous blog here: http://musingsofasoftwareenthusiast.blogspot.in/2016/08/retrieve-data-from-configuration.html, here I will discuss (and give the code) to retrieve data from configuration record using C#. In particular, I would keep this code in a Common.cs file, so that the methods in this file can be accessed by all plugins/workflow assemblies.

/// <summary>
        /// Get the value of the configuration record corresponding to the key
        /// </summary>
        /// <param name="configurationKeyName">configuration Key Name</param>
        /// <param name="service">IOrganization service</param>
        /// <returns>The value of the configuration record for the supplied key</returns>
        public static string RetrieveConfigurationData(string configurationKeyName, IOrganizationService service)
        {
            Entity configurationEntity = null;
            EntityCollection configurationEntityCollection = null;          
                QueryExpression qE = new QueryExpression("contoso_configuration");
                qE.ColumnSet = new ColumnSet("contoso_value");
                qE.Criteria.AddCondition(new ConditionExpression("contoso_name", ConditionOperator.Equal, configurationKeyName));
                if (service != null)
                {
                    configurationEntityCollection = service.RetrieveMultiple(qE);
                }

                if (configurationEntityCollection != null && configurationEntityCollection.Entities != null && configurationEntityCollection.Entities.Count > 0)
                {
                    configurationEntity = configurationEntityCollection.Entities[0];
                }
                else
                {
                    throw new InvalidPluginExecutionException("There is no configuration record with the name: " + configurationKeyName);
                }
           
            string configurationEntityValue = string.Empty;
            if (configurationEntity != null)
            {
                configurationEntityValue = configurationEntity.GetAttributeValue<string>("contoso_value");
            }

            return configurationEntityValue;
        }

I have used late binding here, so that names of the entity and fields will be as per your organization.

Also, note that unlike the Javascript example in my earlier post here we are using the all small case schema name to refer to the names of the entity and the fields.

Let me know if this helps by giving your feedback!
Happy Dynamics CRMing!

No comments:

Post a Comment