Example #1
0
        public static RetrieveMetadataChangesResponse LoadEntityDetails(IOrganizationService service, string entityName)
        {
            if (service == null)
            {
                return(null);
            }

            var eqe = new EntityQueryExpression
            {
                Properties = new MetadataPropertiesExpression(entityProperties)
            };

            eqe.Properties.PropertyNames.AddRange(entityDetails);
            eqe.Criteria.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));
            var aqe = new AttributeQueryExpression
            {
                Properties = new MetadataPropertiesExpression(attributeProperties)
            };

            aqe.Criteria.Conditions.Add(new MetadataConditionExpression("IsLogical", MetadataConditionOperator.NotEquals, true));
            eqe.AttributeQuery = aqe;
            var req = new RetrieveMetadataChangesRequest
            {
                Query = eqe,
                ClientVersionStamp = null
            };

            return(service.Execute(req) as RetrieveMetadataChangesResponse);
        }
        public static List <EntityMetadata> GetStringFieldsFieldListForEntity(IOrganizationService service, string entityLogicalName)
        {
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));

            MetadataConditionExpression metadataExpression = new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.String);
            MetadataFilterExpression    AttributeFilter    = new
                                                             MetadataFilterExpression(LogicalOperator.And);

            AttributeFilter.Conditions.Add(metadataExpression);

            AttributeQueryExpression Attributefilters = new AttributeQueryExpression()
            {
                Criteria = AttributeFilter
            };

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                AttributeQuery = Attributefilters
            };

            RetrieveMetadataChangesResponse initialRequest = GetMetadataChanges(service, entityQueryExpression, null, DeletedMetadataFilters.All);

            return(initialRequest.EntityMetadata.ToList());
        }
        public bool IsEntityExists(string entityName)
        {
            try
            {
                MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.Equals, entityName));

                var entityQueryExpression = new EntityQueryExpression()
                {
                    Criteria = entityFilter,
                };

                var response = (RetrieveMetadataChangesResponse)_service.Execute(
                    new RetrieveMetadataChangesRequest()
                {
                    ClientVersionStamp = null,
                    Query = entityQueryExpression,
                }
                    );

                return(response.EntityMetadata.SingleOrDefault() != null);
            }
            catch (Exception ex)
            {
                Helpers.DTEHelper.WriteExceptionToOutput(_service.ConnectionData, ex);

                return(false);
            }
        }
        public static List <ComboBoxEntities> GetListEntities(IOrganizationService service)
        {
            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            EntityProperties.PropertyNames.AddRange(new string[] { "IsAuditEnabled", "DisplayName", "LogicalName", "ObjectTypeCode" });


            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Properties = EntityProperties,
            };


            RetrieveMetadataChangesResponse initialRequest = GetMetadataChanges(service, entityQueryExpression, null, DeletedMetadataFilters.OptionSet);

            List <ComboBoxEntities> lsEntities = initialRequest.EntityMetadata.Where(f => f.DisplayName.UserLocalizedLabel != null).Select(x => new ComboBoxEntities()
            {
                DisplayName    = x.DisplayName.UserLocalizedLabel.Label,
                IsAuditEnabled = x.IsAuditEnabled.Value,
                ObjectTypeCode = x.ObjectTypeCode.Value,
                LogicalName    = x.LogicalName
            }).OrderBy(o => o.DisplayName).ToList();

            return(lsEntities);
        }
Example #5
0
        public string GetEntityLogicalName(int entityTypeCode)
        {
            string logicalName = null;

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = new MetadataFilterExpression(LogicalOperator.And)
                {
                    Conditions =
                    {
                        new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, entityTypeCode)
                    }
                },
                Properties = new MetadataPropertiesExpression("DisplayName", "ObjectTypeCode", "PrimaryIdAttribute", "PrimaryNameAttribute")
            };

            var response = (RetrieveMetadataChangesResponse)_organizationService.Execute(new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            });

            if (response.EntityMetadata != null && response.EntityMetadata.Count > 0)
            {
                logicalName = response.EntityMetadata.First().LogicalName;
            }

            return(logicalName);
        }
        private List <EntityMetadata> GetManagedEntities(params Guid[] ids)
        {
            EntityQueryExpression entityQueryExpressionFull = new EntityQueryExpression
            {
                Properties = new MetadataPropertiesExpression
                {
                    AllProperties = false,
                    PropertyNames =
                    {
                        "DisplayName",
                        "LogicalName",
                        "SchemaName",
                    }
                },
                Criteria = new MetadataFilterExpression
                {
                    Conditions =
                    {
                        new MetadataConditionExpression("MetadataId", MetadataConditionOperator.In,     ids),
                        new MetadataConditionExpression("IsManaged",  MetadataConditionOperator.Equals, true)
                    }
                }
            };

            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpressionFull,
                ClientVersionStamp = null
            };

            var fullResponse = (RetrieveMetadataChangesResponse)service.Execute(request);

            return(fullResponse.EntityMetadata.ToList());
        }
        private RetrieveMetadataChangesResponse GetEntityMetadata()
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(
                new MetadataConditionExpression(
                    "LogicalName",
                    MetadataConditionOperator.In,
                    _entityLogicalNames));

            var entityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            entityProperties.PropertyNames.AddRange(new string[] {
                "Attributes",
                "ManyToManyRelationships",
                "OneToManyRelationships",
                "ManyToOneRelationships"
            });

            // A filter expression to apply the optionsetAttributeTypes condition expression
            var attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);

            // A Properties expression to limit the properties to be included with attributes
            var attributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = true
            };

            // A label query expression to limit the labels returned to only those for the output preferred language
            var labelQuery = new LabelQueryExpression();

            labelQuery.FilterLanguages.Add(1033);

            // An entity query expression to combine the filter expressions and property expressions for the query.
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = entityFilter,
                Properties     = entityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria   = attributeFilter,
                    Properties = attributeProperties
                },
                LabelQuery = labelQuery
            };

            // Retrieve the metadata for the query without a ClientVersionStamp
            var request = new RetrieveMetadataChangesRequest()
            {
                ClientVersionStamp = null,
                Query = entityQueryExpression
            };

            var metadataRequest = (RetrieveMetadataChangesResponse)_service.Execute(request);

            return(metadataRequest);
        }
        public Result GetEntityDetials(MetadataConditionExpression expression)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

                MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(expression);
                EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
                {
                    Criteria = entityFilter
                };
                RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };
                RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)xrmService.Execute(retrieveMetadataChangesRequest);

                EntityMetadata entityMetadata = (EntityMetadata)response.EntityMetadata[0];
                return(new Result(false, string.Empty, entityMetadata, logSystem));
            }
            catch (Exception ex)
            {
                return(new Result(true,
                                  MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                                  null, logSystem));
            }
        }
        public static RetrieveMetadataChangesResponse GetEntityAttributes(IOrganizationService service, string entity)
        {
            var entityFilter = new MetadataFilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entity));

            //var entityProps = new MetadataPropertiesExpression("DisplayName", "LogicalName", "SchemaName", "ObjectTypeCode");

            var attributeProps = new MetadataPropertiesExpression("DisplayName", "LogicalName", "SchemaName", "AttributeType", "IsPrimaryId", "IsPrimaryName", "IsValidForRead");

            var query = new EntityQueryExpression()
            {
                Criteria = entityFilter,
                //Properties = entityProps,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = attributeProps
                },
            };

            var request = new RetrieveMetadataChangesRequest()
            {
                Query = query
            };
            var response = (RetrieveMetadataChangesResponse)service.Execute(request);

            return(response);
        }
        public static string geEntityLogicalName(int ObjectTypeCode)
        {
            //http://www.dynamicscrm.blog/object-type-codes-cheat-sheet-for-dynamics-365/
            //https://msdynamicscrmblog.wordpress.com/2013/07/18/entity-type-codes-in-dynamics-crm-2011/

            string entityLogicalName = String.Empty;

            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, ObjectTypeCode));
            MetadataPropertiesExpression mpe = new MetadataPropertiesExpression();

            mpe.AllProperties = false;
            mpe.PropertyNames.Add("ObjectTypeCode");
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = EntityFilter,
                Properties = mpe
            };

            RetrieveMetadataChangesResponse initialRequest = GetMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet);

            if (initialRequest.EntityMetadata.Count == 1)
            {
                entityLogicalName = initialRequest.EntityMetadata[0].LogicalName;
            }

            return(entityLogicalName);
        }
        private AttributeTypeCode?GetAttributeType(string attribute, string entityName)
        {
            log.StartSection(MethodBase.GetCurrentMethod().Name + " " + entityName + "." + attribute);
            AttributeTypeCode?type = null;
            var eqe = new EntityQueryExpression();

            eqe.Properties = new MetadataPropertiesExpression();
            eqe.Properties.PropertyNames.Add("Attributes");
            eqe.Criteria.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));
            var aqe = new AttributeQueryExpression();

            aqe.Properties     = new MetadataPropertiesExpression("LogicalName", "AttributeType");
            eqe.AttributeQuery = aqe;
            var req = new RetrieveMetadataChangesRequest()
            {
                Query = eqe,
                ClientVersionStamp = null
            };
            var resp = (RetrieveMetadataChangesResponse)crmsvc.Execute(req);

            if (resp.EntityMetadata.Count == 1)
            {
                foreach (var attr in resp.EntityMetadata[0].Attributes)
                {
                    if (attr.LogicalName == attribute)
                    {
                        type = attr.AttributeType;
                        break;
                    }
                }
            }
            log.Log("Type: {0}", type);
            log.EndSection();
            return(type);
        }
        /// <summary>
        /// Retrieves all OOB or Custom Entities Metadata depending on isOOB's value (True or False).
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <param name="includedEntities"></param>
        /// <param name="isOOB"></param>
        /// <returns></returns>
        public static EntityMetadata[] RetrieveEntityMetadata(CrmServiceClient serviceClient, string[] includedEntities, bool isOOB)
        {
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            if (includedEntities != null && includedEntities.Length > 0) // If the list of included entities does contain entities
            {
                EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.In, includedEntities));
            }
            else // Otherwise we need to verify the OOB flag to decide which type of entities to return (OOB or Custom)
            {
                if (!isOOB) // Return Custom Entities (Object Type Code >= 10000)
                {
                    EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.GreaterThan, 9999));
                }
            }

            // An entity query expression to combine the filter expressions and property expressions for the query.
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = EntityFilter
            };

            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)serviceClient.Execute(request);

            return(response.EntityMetadata.ToArray());
        }
Example #13
0
 public static string SerialiseEntityQueryExpression(EntityQueryExpression item)
 {
     if (item != null)
     {
         string xml =
             @"<b:value i:type='c:EntityQueryExpression' xmlns:c='http://schemas.microsoft.com/xrm/2011/Metadata/Query'>"
             + MetadataSerialiser.SerialiseMetadataQueryExpression(item);
         if (item.AttributeQuery != null)
         {
             xml += @"<c:AttributeQuery>"
                    + MetadataSerialiser.SerialiseAttributeQueryExpression(item.AttributeQuery)
                    + @"</c:AttributeQuery>";
         }
         xml += @"<c:LabelQuery>"
                + MetadataSerialiser.SerialiseLabelQueryExpression(item.LabelQuery)
                + @"</c:LabelQuery>
         <c:RelationshipQuery i:nil='true' />
         </b:value>";
         return(xml);
     }
     else
     {
         return("<b:value i:nil='true'/>");
     }
 }
        public static IDictionary <string, int> GetEntityCodes(Settings settings,
                                                               IConnectionManager connectionManager, MetadataCache metadataCache)
        {
            if (metadataCache.EntityCodesCache != null)
            {
                return(metadataCache.EntityCodesCache);
            }

            var entityProperties =
                new MetadataPropertiesExpression
            {
                AllProperties = false
            };

            entityProperties.PropertyNames.AddRange("LogicalName", "ObjectTypeCode");

            var entityQueryExpression =
                new EntityQueryExpression
            {
                Properties = entityProperties
            };

            var retrieveMetadataChangesRequest =
                new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };

            return(metadataCache.EntityCodesCache =
                       ((RetrieveMetadataChangesResponse)connectionManager.Get().Execute(retrieveMetadataChangesRequest)).EntityMetadata
                       .ToDictionary(e => e.LogicalName, e => e.ObjectTypeCode.GetValueOrDefault()));
        }
Example #15
0
        public static string GetEntityNameFromETC(int etc, IOrganizationService service)
        {
            EntityQueryExpression metadataQuery = new EntityQueryExpression();

            metadataQuery.Properties = new MetadataPropertiesExpression();
            metadataQuery.Properties.PropertyNames.Add("LogicalName");
            metadataQuery.Criteria.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, etc));

            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = metadataQuery,
                ClientVersionStamp     = null,
                DeletedMetadataFilters = DeletedMetadataFilters.OptionSet
            };

            RetrieveMetadataChangesResponse response = service.Execute(retrieveMetadataChangesRequest) as RetrieveMetadataChangesResponse;

            if (response.EntityMetadata.Count > 0)
            {
                return(response.EntityMetadata[0].LogicalName);
            }
            else
            {
                throw new Exception(string.Format("Entity with Object Type Code '{0}' couldn't be found", etc));
            }
        }
Example #16
0
        public void RetrieveMetadataChangesRequest()
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, 1));
            var propertyExpression = new MetadataPropertiesExpression {
                AllProperties = false
            };

            propertyExpression.PropertyNames.Add("LogicalName");
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = propertyExpression
            };

            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            var response = (RetrieveMetadataChangesResponse)orgAdminService.Execute(retrieveMetadataChangesRequest);

            Assert.Equal("account", response.EntityMetadata[0].LogicalName);
        }
Example #17
0
        public static EntityMetadataCollection LoadAttributes(IOrganizationService service, string entityLogicalName)
        {
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression
            {
                Criteria = new MetadataFilterExpression
                {
                    Conditions =
                    {
                        new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)
                    }
                },
                Properties = new MetadataPropertiesExpression
                {
                    AllProperties = false,
                    PropertyNames = { "Attributes" }
                },
                AttributeQuery = new AttributeQueryExpression
                {
                    Properties = new MetadataPropertiesExpression(AttributeMetadataProperties)
                    {
                        AllProperties = false
                    }
                },
            };

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            return(response.EntityMetadata);
        }
Example #18
0
        public EntityMetadata GetEntityMetadata(int typeCode)
        {
            EntityMetadata entityMetadatas;


            IOrganizationService orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);


            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, 9800));

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression();

            entityQueryExpression.Criteria = EntityFilter;
            //entityQueryExpression.AttributeQuery=new AttributeQueryExpression()

            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,
                //ClientVersionStamp = clientVersionStamp,
                //DeletedMetadataFilters = deletedMetadataFilter
            };

            var response = (RetrieveEntityResponse)orgService.Execute(request);

            entityMetadatas = response.EntityMetadata;


            return(entityMetadatas);
        }
        /// <summary>
        ///  Gets details of changes in metadata that have occurred for a particular entity, since the specified time stamp. Allows a subset of properties to be specified, and filters for information regarding deleted metadata that will be returned.
        /// </summary>
        /// <param name="entityLogicalName"></param>
        /// <param name="clientTimestamp"></param>
        /// <param name="properties"></param>
        /// <param name="deletedFilters"></param>
        /// <returns></returns>
        public RetrieveMetadataChangesResponse GetChanges(string entityLogicalName, string clientTimestamp, IEnumerable <string> properties, DeletedMetadataFilters deletedFilters)
        {
            // retrieve the current timestamp value;
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
            var props = new MetadataPropertiesExpression();

            if (properties == null)
            {
                props.AllProperties = true;
            }
            else
            {
                props.PropertyNames.AddRange(properties);
            }

            //LabelQueryExpression labels = new LabelQueryExpression();
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = entityFilter,
                Properties     = props,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = props
                }
            };

            var response  = GetMetadataChanges(entityQueryExpression, clientTimestamp, deletedFilters);
            var timeStamp = response.ServerVersionStamp;

            Debug.WriteLine("Next Timestamp: " + timeStamp);
            return(response);
        }
Example #20
0
        /// <summary>
        /// Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public string GetEntityLogicalName(IOrganizationService service)
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, this.EntityTypeCode));
            var propertyExpression = new MetadataPropertiesExpression {
                AllProperties = false
            };

            propertyExpression.PropertyNames.Add("LogicalName");
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = propertyExpression
            };

            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };

            var response = service.Execute(retrieveMetadataChangesRequest);

            EntityMetadataCollection metadataCollection = (EntityMetadataCollection)response.Results["EntityMetadata"];

            return(metadataCollection.Count == 1 ? metadataCollection[0].LogicalName : null);
        }
        /// <summary>
        ///  Gets details of changes in metadata that have occurred for a particular entity, since the specified time stamp. Allows a subset of properties to be specified, and filters for information regarding deleted metadata that will be returned.
        /// </summary>
        /// <param name="entityLogicalName"></param>
        /// <param name="clientTimestamp"></param>
        /// <param name="properties"></param>
        /// <param name="deletedFilters"></param>
        /// <returns></returns>
        public RetrieveMetadataChangesResponse GetChanges(string entityLogicalName, string clientTimestamp, IEnumerable<string> properties, DeletedMetadataFilters deletedFilters)
        {
            // retrieve the current timestamp value;
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);
            entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
            var props = new MetadataPropertiesExpression();
            if (properties == null)
            {
                props.AllProperties = true;
            }
            else
            {
                props.PropertyNames.AddRange(properties);
            }

            //LabelQueryExpression labels = new LabelQueryExpression();
            var entityQueryExpression = new EntityQueryExpression()
                {
                    Criteria = entityFilter,
                    Properties = props,
                    AttributeQuery = new AttributeQueryExpression()
                        {
                            Properties = props
                        }
                };

            var response = GetMetadataChanges(entityQueryExpression, clientTimestamp, deletedFilters);
            var timeStamp = response.ServerVersionStamp;
            Debug.WriteLine("Next Timestamp: " + timeStamp);
            return response;
        }
        /// <summary>
        /// Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static string GetEntityLogicalName(IOrganizationService service, int entityTypeCode)
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, entityTypeCode));
            var propertyExpression = new MetadataPropertiesExpression {
                AllProperties = false
            };

            propertyExpression.PropertyNames.Add("LogicalName");
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = propertyExpression
            };

            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            if (response.EntityMetadata.Count == 1)
            {
                return(response.EntityMetadata[0].LogicalName);
            }
            return(null);
        }
        private List <EntityMetadata> FindEntitiesPropertiesOrAll(string entityName, int?entityTypeCode, params string[] properties)
        {
            var entityProperties = new MetadataPropertiesExpression(properties)
            {
                AllProperties = false
            };

            var entityQueryExpression = new EntityQueryExpression()
            {
                Properties = entityProperties,
            };

            if (properties != null && properties.Contains(nameof(EntityMetadata.Attributes), StringComparer.InvariantCultureIgnoreCase))
            {
                entityQueryExpression.AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = new MetadataPropertiesExpression
                                 (
                        nameof(AttributeMetadata.LogicalName)
                        , nameof(AttributeMetadata.AttributeType)
                        , nameof(AttributeMetadata.IsValidForRead)
                                 ),
                };
            }

            if (!string.IsNullOrEmpty(entityName) || entityTypeCode.HasValue)
            {
                var criteria = new MetadataFilterExpression(LogicalOperator.Or);

                if (!string.IsNullOrEmpty(entityName))
                {
                    criteria.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.Equals, entityName));
                }

                if (entityTypeCode.HasValue)
                {
                    criteria.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.ObjectTypeCode), MetadataConditionOperator.Equals, entityTypeCode.Value));
                }

                entityQueryExpression.Criteria = criteria;
            }

            var request = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,
            };

            var response = (RetrieveMetadataChangesResponse)_service.Execute(request);

            if (response.EntityMetadata.Any())
            {
                return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList());
            }
            else if (!string.IsNullOrEmpty(entityName) || entityTypeCode.HasValue)
            {
                return(FindEntitiesPropertiesOrAll(null, null, properties));
            }

            return(new List <EntityMetadata>());
        }
        public static EntityMetadataCollection LoadEntities(IOrganizationService service)
        {
            var entityQueryExpression = new EntityQueryExpression
            {
                Properties     = new MetadataPropertiesExpression("LogicalName", "DisplayName", "Attributes", "IsAuditEnabled", "ObjectTypeCode"),
                AttributeQuery = new AttributeQueryExpression
                {
                    Criteria = new MetadataFilterExpression
                    {
                        Conditions =
                        {
                            new MetadataConditionExpression("LogicalName", MetadataConditionOperator.NotIn, new[] { "traversedpath", "versionnumber" })
                        }
                    },
                    Properties = new MetadataPropertiesExpression("DisplayName", "LogicalName", "AttributeType", "IsAuditEnabled", "AttributeOf", "EntityLogicalName"),
                }
            };
            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            return(((RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest)).EntityMetadata);
        }
Example #25
0
        public bool EntityExists(string logicalName)
        {
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                // Récupération de l'entité spécifiée
                Criteria = new MetadataFilterExpression
                {
                    Conditions =
                    {
                        new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, logicalName)
                    }
                },
                // Sans propriétés d'entité
                Properties = new MetadataPropertiesExpression
                {
                    AllProperties = false,
                },
            };

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            return(response.EntityMetadata.Count != 0);
        }
        public static IEnumerable <EntityNameViewModel> RetrieveEntityNames(IOrganizationService service)
        {
            var entityProperties =
                new MetadataPropertiesExpression
            {
                AllProperties = false
            };

            entityProperties.PropertyNames.AddRange("LogicalName", "DisplayName");

            var entityQueryExpression =
                new EntityQueryExpression
            {
                Properties = entityProperties
            };

            var retrieveMetadataChangesRequest =
                new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            return(((RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest))
                   .EntityMetadata.Select(e =>
                                          new EntityNameViewModel
            {
                LogicalName = e.LogicalName,
                DisplayName = e.DisplayName?.UserLocalizedLabel?.Label
            }));
        }
        private async Task LoadPackEntities(string[] pack)
        {
            if (_cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            EntityQueryExpression entityQueryExpression = GetEntityQueryExpression();

            entityQueryExpression.Criteria.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.In, pack));

            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,
            };

            try
            {
                var service = await GetServiceAsync();

                if (service == null)
                {
                    return;
                }

                RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)service.Execute(request);
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToLog(ex);

                _service = null;
            }
        }
Example #28
0
        protected String updateOptionLabelList(EntityQueryExpression entityQueryExpression, String clientVersionStamp)
        {
            //Retrieve metadata changes and add them to the cache
            RetrieveMetadataChangesResponse updateResponse;

            try
            {
                updateResponse = getMetadataChanges(entityQueryExpression, clientVersionStamp, DeletedMetadataFilters.OptionSet);
                addOptionLabelsToCache(updateResponse.EntityMetadata, true);
                removeOptionLabelsFromCache(updateResponse.DeletedMetadata, true);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // Check for ErrorCodes.ExpiredVersionStamp (0x80044352)
                // Will occur when the timestamp exceeds the Organization.ExpireSubscriptionsInDays value, which is 90 by default.
                if (ex.Detail.ErrorCode == unchecked ((int)0x80044352))
                {
                    //reinitialize cache
                    _optionLabelList.Clear();

                    updateResponse = getMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet);
                    //Add them to the cache and display the changes
                    addOptionLabelsToCache(updateResponse.EntityMetadata, true);
                }
                else
                {
                    throw ex;
                }
            }
            return(updateResponse.ServerVersionStamp);
        }
Example #29
0
        public bool EntityExists(string entityName)
        {
            if (string.IsNullOrWhiteSpace(entityName))
            {
                throw new ArgumentNullException(nameof(entityName), $"The parameter {nameof(entityName)} cannot be null.");
            }

            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = new MetadataFilterExpression(LogicalOperator.And)
                {
                    Conditions =
                    {
                        new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName)
                    }
                },
                Properties = new MetadataPropertiesExpression("ObjectTypeCode")
            };

            var response = (RetrieveMetadataChangesResponse)_organizationService.Execute(new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            });

            return(response.EntityMetadata != null && response.EntityMetadata.Count > 0);
        }
        private void Update_AllEntities()
        {
            try
            {
                // TODO REMOVE THIS var connection = QuickConnection.Connect(settings.CrmSdkUrl, settings.Domain, settings.Username, settings.Password, settings.CrmOrg);
                var connString = CrmConnection.Parse(settings.GetOrganizationCrmConnectionString());
                var connection = new OrganizationService(connString);

                var entityProperties = new MetadataPropertiesExpression
                {
                    AllProperties = false
                };
                entityProperties.PropertyNames.AddRange("LogicalName");
                var entityQueryExpression = new EntityQueryExpression
                {
                    Properties = entityProperties
                };
                var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };

                allEntities =
                    ((RetrieveMetadataChangesResponse)connection.Execute(retrieveMetadataChangesRequest)).EntityMetadata.ToArray();
            }
            catch (Exception ex)
            {
                var error = "[ERROR] " + ex.Message
                            + (ex.InnerException != null ? "\n" + "[ERROR] " + ex.InnerException.Message : "");
                UpdateStatus(error, false);
                UpdateStatus("Unable to refresh entities, check connection information", false);
            }
        }
        internal static List <string> GetEntityFieldNames(string entityName, XrmServiceContext context, bool cached = true)
        {
            if (entityName == "none")
            {
                return(new List <string>());
            }

            if (AttributeList.ContainsKey(entityName) && cached)
            {
                return(AttributeList[entityName]);
            }

            lock (AttributeList)
            {
                var entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(
                    new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));

                var entityProperties = new MetadataPropertiesExpression
                {
                    AllProperties = false
                };
                entityProperties.PropertyNames.AddRange("Attributes");

                var attributesFilter = new MetadataFilterExpression(LogicalOperator.And);
                attributesFilter.Conditions.Add(
                    new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null));

                var attributeProperties = new MetadataPropertiesExpression
                {
                    AllProperties = false
                };
                attributeProperties.PropertyNames.AddRange("LogicalName");

                var entityQueryExpression = new EntityQueryExpression
                {
                    Criteria       = entityFilter,
                    Properties     = entityProperties,
                    AttributeQuery = new AttributeQueryExpression
                    {
                        Criteria   = attributesFilter,
                        Properties = attributeProperties
                    }
                };

                var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };

                var attributeNames = ((RetrieveMetadataChangesResponse)context.Execute(retrieveMetadataChangesRequest))
                                     .EntityMetadata.First().Attributes
                                     .Select(attribute => attribute.LogicalName).OrderBy(name => name).ToList();

                AttributeList[entityName] = attributeNames;
            }

            return(AttributeList[entityName]);
        }
Example #32
0
        public bool EntityExists(string logicalName)
        {
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                // Récupération de l'entité spécifiée
                Criteria = new MetadataFilterExpression
                {
                    Conditions =
                   {
                       new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, logicalName)
                   }
                },
                // Sans propriétés d'entité
                Properties = new MetadataPropertiesExpression
                {
                    AllProperties = false,
                },
            };

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            return response.EntityMetadata.Count != 0;
        }
Example #33
0
 public static RetrieveMetadataChangesResponse LoadEntities(IOrganizationService service)
 {
     if (service == null)
     {
         return null;
     }
     var eqe = new EntityQueryExpression();
     eqe.Properties = new MetadataPropertiesExpression(entityProperties);
     var req = new RetrieveMetadataChangesRequest()
     {
         Query = eqe,
         ClientVersionStamp = null
     };
     return service.Execute(req) as RetrieveMetadataChangesResponse;
 }
Example #34
0
        public static EntityMetadataCollection LoadMetadata(Dictionary<string, List<string>> attributes, IOrganizationService service)
        {
            try
            {
                var allAttributes = new List<string>();
                foreach (var list in attributes.Values)
                {
                    allAttributes.AddRange(list.ToArray());
                }

                var entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName",
                    MetadataConditionOperator.In,
                    attributes.Keys.ToArray()));

                var entityQueryExpression = new EntityQueryExpression()
                {
                    Properties = new MetadataPropertiesExpression("LogicalName", "DisplayName", "Attributes"),
                    Criteria = entityFilter,
                    AttributeQuery = new AttributeQueryExpression()
                    {
                        Properties = new MetadataPropertiesExpression("DisplayName", "LogicalName"),
                        Criteria = new MetadataFilterExpression()
                        {
                            Conditions =
                            {
                                new MetadataConditionExpression("LogicalName", MetadataConditionOperator.In, allAttributes.ToArray())
                            }
                        }
                    }
                };
                var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };

                return
                    ((RetrieveMetadataChangesResponse) service.Execute(retrieveMetadataChangesRequest)).EntityMetadata;
            }
            catch (FaultException<OrganizationServiceFault> error)
            {
                throw new Exception(error.Detail.Message + error.Detail.TraceText);
            }
        }
Example #35
0
 public static RetrieveMetadataChangesResponse LoadEntityDetails(IOrganizationService service, string entityName)
 {
     if (service == null)
     {
         return null;
     }
     var eqe = new EntityQueryExpression();
     eqe.Properties = new MetadataPropertiesExpression(entityProperties);
     eqe.Properties.PropertyNames.AddRange(entityDetails);
     eqe.Criteria.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));
     var aqe = new AttributeQueryExpression();
     aqe.Properties = new MetadataPropertiesExpression(attributeProperties);
     eqe.AttributeQuery = aqe;
     var req = new RetrieveMetadataChangesRequest()
     {
         Query = eqe,
         ClientVersionStamp = null
     };
     return service.Execute(req) as RetrieveMetadataChangesResponse;
 }
Example #36
0
        static void Main(string[] args)
        {
            var _languageCode = 1033;

            CrmServiceClient connection = new CrmServiceClient(ConfigurationManager.ConnectionStrings["crm"].ConnectionString);
            var service = (IOrganizationService)connection.OrganizationWebProxyClient ?? (IOrganizationService)connection.OrganizationServiceProxy;


            //To reduce the number of classes generated to those which are most useful,
            // the following entities will be excluded. If necessary, you can comment out
            // items from this array so that class files will be generated for the entity
            String[] excludedEntities = {
                                  "ApplicationFile",
                                  "AsyncOperation",
                                  "AttributeMap",
                                  "AuthorizationServer",
                                  "BulkDeleteFailure",
                                  "BulkDeleteOperation",
                                  "BulkOperation",
                                  "BulkOperationLog",
                                  "BusinessProcessFlowInstance",
                                  "BusinessUnitMap",
                                  "BusinessUnitNewsArticle",
                                  "ChildIncidentCount",
                                  "ClientUpdate",
                                  "ColumnMapping",
                                  "Commitment",
                                  "ComplexControl",
                                  "ConvertRule",
                                  "ConvertRuleItem",
                                  "Dependency",
                                  "DependencyFeature",
                                  "DependencyNode",
                                  "DisplayString",
                                  "DisplayStringMap",
                                  "DocumentIndex",
                                  "DuplicateRecord",
                                  "DuplicateRule",
                                  "DuplicateRuleCondition",
                                  "EmailHash",
                                  "EmailSearch",
                                  "EmailServerProfile",
                                  "EntityMap",
                                  "ExchangeSyncIdMapping",
                                  "FieldPermission",
                                  "FieldSecurityProfile",
                                  "FilterTemplate",
                                  "FixedMonthlyFiscalCalendar",
                                  "ImageDescriptor",
                                  "Import",
                                  "ImportData",
                                  "ImportEntityMapping",
                                  "ImportFile",
                                  "ImportJob",
                                  "ImportLog",
                                  "ImportMap",
                                  "IntegrationStatus",
                                  "InternalAddress",
                                  "InterProcessLock",
                                  "InvalidDependency",
                                  "IsvConfig",
                                  "License",
                                  "LookUpMapping",
                                  "Mailbox",
                                  "MailboxStatistics",
                                  "MetadataDifference",
                                  "MultiEntitySearch",
                                  "MultiEntitySearchEntities",
                                  "Notification",
                                  "OrganizationStatistic",
                                  "OrganizationUI",
                                  "OwnerMapping",
                                  "PartnerApplication",
                                  "PickListMapping",
                                  "PluginAssembly",
                                  "PluginType",
                                  "PluginTypeStatistic",
                                  "PrincipalObjectAccess",
                                  "PrincipalObjectAccessReadSnapshot",
                                  "PrincipalObjectAttributeAccess",
                                  "Privilege",
                                  "PrivilegeObjectTypeCodes",
                                  "ProcessSession",
                                  "ProcessStage",
                                  "ProcessTrigger",
                                  "Publisher",
                                  "PublisherAddress",
                                  "RecordCountSnapshot",
                                  "RelationshipRole",
                                  "RelationshipRoleMap",
                                  "ReplicationBacklog",
                                  "Report",
                                  "ReportCategory",
                                  "ReportEntity",
                                  "ReportLink",
                                  "ReportVisibility",
                                  "RibbonCommand",
                                  "RibbonContextGroup",
                                  "RibbonCustomization",
                                  "RibbonDiff",
                                  "RibbonRule",
                                  "RibbonTabToCommandMap",
                                  "RoutingRule",
                                  "RoutingRuleItem",
                                  "SalesProcessInstance",
                                  "SdkMessage",
                                  "SdkMessageFilter",
                                  "SdkMessagePair",
                                  "SdkMessageProcessingStep",
                                  "SdkMessageProcessingStepImage",
                                  "SdkMessageProcessingStepSecureConfig",
                                  "SdkMessageRequest",
                                  "SdkMessageRequestField",
                                  "SdkMessageResponse",
                                  "SdkMessageResponseField",
                                  "ServiceEndpoint",
                                  "SiteMap",
                                  "SLA",
                                  "SLAItem",
                                  "Solution",
                                  "SolutionComponent",
                                  "SqlEncryptionAudit",
                                  "StatusMap",
                                  "StringMap",
                                  "Subscription",
                                  "SubscriptionClients",
                                  "SubscriptionSyncInfo",
                                  "SubscriptionTrackingDeletedObject",
                                  "SystemApplicationMetadata",
                                  "SystemForm",
                                  "SystemUserBusinessUnitEntityMap",
                                  "SystemUserPrincipals",
                                  "TraceAssociation",
                                  "TraceLog",
                                  "TraceRegarding",
                                  "TransformationMapping",
                                  "TransformationParameterMapping",
                                  "UnresolvedAddress",
                                  "UserApplicationMetadata",
                                  "UserEntityInstanceData",
                                  "UserEntityUISettings",
                                  "WebWizard",
                                  "WizardAccessPrivilege",
                                  "WizardPage",
                                  "WorkflowWaitSubscription"
                                 };
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
            // No classes for intersect entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
            // Do not retrieve excluded entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities));


            //A properties expression to limit the properties to be included with entities
            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };
            EntityProperties.PropertyNames.AddRange(new string[] {
                        "Attributes",
                        "Description",
                        "DisplayName",
                        "OneToManyRelationships",
                        "SchemaName" });


            MetadataConditionExpression[] attributesToReturn = new MetadataConditionExpression[] { 
                 //No virtual attributes
                 new MetadataConditionExpression("AttributeType", MetadataConditionOperator.NotEquals, AttributeTypeCode.Virtual),
                 // No child attributes
                 new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null)
                 };


            MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.And);
            AttributeFilter.Conditions.AddRange(attributesToReturn);


            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression() { AllProperties = false };
            AttributeProperties.PropertyNames.Add("AttributeTypeName");
            AttributeProperties.PropertyNames.Add("MaxLength");
            AttributeProperties.PropertyNames.Add("OptionSet");
            AttributeProperties.PropertyNames.Add("Description");
            AttributeProperties.PropertyNames.Add("DisplayName");
            AttributeProperties.PropertyNames.Add("RequiredLevel");
            AttributeProperties.PropertyNames.Add("SchemaName");
            AttributeProperties.PropertyNames.Add("Targets");
            AttributeProperties.PropertyNames.Add("IsValidForCreate");
            AttributeProperties.PropertyNames.Add("IsValidForRead");
            AttributeProperties.PropertyNames.Add("IsValidForUpdate");


            MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);

            MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression() { AllProperties = false };
            relationshipProperties.PropertyNames.Add("SchemaName");
            relationshipProperties.PropertyNames.Add("ReferencingEntity");
            relationshipProperties.PropertyNames.Add("ReferencingAttribute");



            //A label query expression to limit the labels returned to only those for the user's preferred language
            LabelQueryExpression labelQuery = new LabelQueryExpression();
            //labelQuery.FilterLanguages.Add(_languageCode);


            //An entity query expression to combine the filter expressions and property expressions for the query.
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {

                Criteria = EntityFilter,
                Properties = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria = AttributeFilter,
                    Properties = AttributeProperties
                },
                RelationshipQuery = new RelationshipQueryExpression()
                {
                    Criteria = relationshipFilter,
                    Properties = relationshipProperties
                },
                LabelQuery = labelQuery

            };

            RetrieveMetadataChangesRequest rmdcr = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };
            RetrieveMetadataChangesResponse resp = (RetrieveMetadataChangesResponse)service.Execute(rmdcr);

            EntityMetadataCollection entities = resp.EntityMetadata;

            foreach (EntityMetadata entity in entities)
            {
                writeEntityTSFile(entity);
            }
            Console.WriteLine("Done!");
        }
Example #37
0
  /// <summary>
  /// Create and configure the organization service proxy.
  /// Retrieve status options for the Incident entity
  /// Use GetValidStatusOptions to get valid status transitions for each status option
  /// </summary>
  /// <param name="serverConfig">Contains server connection information.</param>
  /// <param name="promptForDelete">When True, the user will be prompted to delete all
  /// created entities.</param>
  public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
  {
   try
   {

    // Connect to the Organization service. 
    // The using statement assures that the service proxy will be properly disposed.
    using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
    {
     // This statement is required to enable early-bound type support.
     _serviceProxy.EnableProxyTypes();
     //<snippetStateModelTransitions.run>
     String entityLogicalName = "incident";
     // Retrieve status options for the Incident entity

     //Retrieve just the incident entity and its attributes
     MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
     entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
     MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes" });
     
     //Retrieve just the status attribute and the OptionSet property
     MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
     attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
     MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });
     
     //Instantiate the entity query
     EntityQueryExpression query = new EntityQueryExpression()
     {
      Criteria = entityFilter,
      Properties = entityProperties,
      AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
     };

     //Retrieve the metadata
     RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
     RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);


     StatusAttributeMetadata statusAttribute = (StatusAttributeMetadata)response.EntityMetadata[0].Attributes[0];
     OptionMetadataCollection statusOptions = statusAttribute.OptionSet.Options;
     //Loop through each of the status options
     foreach (StatusOptionMetadata option in statusOptions)
     {
      String StatusOptionLabel = GetOptionSetLabel(statusAttribute, option.Value.Value);
      Console.WriteLine("[{0}] {1} records can transition to:", StatusOptionLabel, entityLogicalName);
      List<StatusOption> validStatusOptions = GetValidStatusOptions(entityLogicalName, option.Value.Value);
      //Loop through each valid transition for the option
      foreach (StatusOption opt in validStatusOptions)
      {
       Console.WriteLine("{0,-3}{1,-10}{2,-5}{3,-10}", opt.StateValue, opt.StateLabel, opt.StatusValue, opt.StatusLabel);
      }
      Console.WriteLine("");
     }
     //</snippetStateModelTransitions.run>
    }
   }

   // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
   catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
   {
    // You can handle an exception here or pass it back to the calling method.
    throw;
   }
  }
        private RetrieveMetadataChangesResponse GetEntityMetadata(IOrganizationService service, Dictionary<string, Dictionary<string, HashSet<string>>> entities, int lcid)
        {
            
            MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.Or);
            MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression{AllProperties = false};
            entityProperties.PropertyNames.Add("Attributes"); // By default query the properties that match the query

            MetadataFilterExpression attributesFilter = new MetadataFilterExpression(LogicalOperator.Or);
            MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression{AllProperties = false};
            LabelQueryExpression labelQuery = new LabelQueryExpression();
            labelQuery.MissingLabelBehavior = 1;
            labelQuery.FilterLanguages.Add(lcid);

           

            HashSet<string> attributePropertyNamesAdded = new HashSet<string>();
            HashSet<string> entityPropertyNamesAdded = new HashSet<string>();

            foreach (var entity in entities.Keys)
            {
                entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entity));
                var attributes = entities[entity];

                foreach (var attribute in attributes.Keys)
                {
                    if (attribute != MetadataExpression.EntityProperties)
                    {
                        // Query attribute properties
                        MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
                        attributesFilter.Filters.Add(attributeFilter);
                        attributeFilter.Conditions.Add(new MetadataConditionExpression("EntityLogicalName", MetadataConditionOperator.Equals, entity));
                        attributeFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, attribute));

                        var properties = attributes[attribute];
                        foreach (var property in properties)
                        {
                            if (!attributePropertyNamesAdded.Contains(property))
                            {
                                attributeProperties.PropertyNames.Add(property);
                                attributePropertyNamesAdded.Add(property);
                            }
                        }
                    }
                    else
                    {
                        // Query entity properties
                        var properties = attributes[attribute];
                        foreach (var property in properties)
                        {
                            if (!entityPropertyNamesAdded.Contains(property))
                            {
                                entityProperties.PropertyNames.Add(property);
                                entityPropertyNamesAdded.Add(property);
                            }
                        }
                    }
                }
            }

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = entityFilter,
                Properties = entityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria = attributesFilter,
                    Properties = attributeProperties
                },
                LabelQuery = labelQuery

            };

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
             
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

           

            return response;

        }
 /// <summary>
 /// Executes the query and returns the results.
 /// </summary>
 /// <param name="entityQueryExpression"></param>
 /// <param name="clientVersionStamp"></param>
 /// <param name="deletedMetadataFilter"></param>
 /// <returns></returns>
 private RetrieveMetadataChangesResponse GetMetadataChanges(EntityQueryExpression entityQueryExpression, String clientVersionStamp, DeletedMetadataFilters deletedMetadataFilter)
 {
     var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
         {
             Query = entityQueryExpression,
             ClientVersionStamp = clientVersionStamp,
             DeletedMetadataFilters = deletedMetadataFilter
         };
     try
     {
         IOrganizationService service = _CrmServiceProvider.GetOrganisationService();
         using (service as IDisposable)
         {
             return (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);
         }
     }
     catch (Exception e)
     {
         throw new Exception("Unable to obtain changes in CRM metadata using client timestamp: " + clientVersionStamp + " as CRM returned a fault. See inner exception for details.", e);
     }
 }
Example #40
0
  //</snippetLabelQueryExpression0>



  #endregion Class Level Members


  /// <summary>
  /// This method connects to the Organization _service. 
  /// </summary>
  /// <param name="serverConfig">Contains server connection information.</param>

  public void Run(ServerConnection.Configuration serverConfig)
  {
   try
   {

    // Connect to the Organization _service. 
    // The using statement assures that the _service proxy will be properly disposed.
       using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
    {
     // This statement is required to enable early-bound type support.
     _serviceProxy.EnableProxyTypes();

     _service = (IOrganizationService)_serviceProxy;
     //<snippetLabelQueryExpression1>
     _userId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
     _languageCode = RetrieveUserUILanguageCode(_userId);
     //</snippetLabelQueryExpression1>



     //<snippetEntityFilter>

     // An array SchemaName values for non-intersect, user-owned entities that should not be returned.
     String[] excludedEntities = {
"WorkflowLog",
"Template",
"CustomerOpportunityRole",
"Import",
"UserQueryVisualization",
"UserEntityInstanceData",
"ImportLog",
"RecurrenceRule",
"QuoteClose",
"UserForm",
"SharePointDocumentLocation",
"Queue",
"DuplicateRule",
"OpportunityClose",
"Workflow",
"RecurringAppointmentMaster",
"CustomerRelationship",
"Annotation",
"SharePointSite",
"ImportData",
"ImportFile",
"OrderClose",
"Contract",
"BulkOperation",
"CampaignResponse",
"Connection",
"Report",
"CampaignActivity",
"UserEntityUISettings",
"IncidentResolution",
"GoalRollupQuery",
"MailMergeTemplate",
"Campaign",
"PostFollow",
"ImportMap",
"Goal",
"AsyncOperation",
"ProcessSession",
"UserQuery",
"ActivityPointer",
"List",
"ServiceAppointment"};

     //A filter expression to limit entities returned to non-intersect, user-owned entities not found in the list of excluded entities.
     MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
     EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
     EntityFilter.Conditions.Add(new MetadataConditionExpression("OwnershipType", MetadataConditionOperator.Equals, OwnershipTypes.UserOwned));
     EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities));
     MetadataConditionExpression isVisibileInMobileTrue = new MetadataConditionExpression("IsVisibleInMobile", MetadataConditionOperator.Equals, true);
     EntityFilter.Conditions.Add(isVisibileInMobileTrue);

     

     //</snippetEntityFilter>
     //<snippetEntityProperties>
     //A properties expression to limit the properties to be included with entities
     MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
     {
      AllProperties = false
     };
     EntityProperties.PropertyNames.AddRange(new string[] { "Attributes" });
     //</snippetEntityProperties>
     
     //<snippetAttributeQueryExpression>
     //A condition expresson to return optionset attributes
     MetadataConditionExpression[] optionsetAttributeTypes = new MetadataConditionExpression[] { 
     new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Picklist),
     new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State),
     new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status),
     new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Boolean)
     };

     //A filter expression to apply the optionsetAttributeTypes condition expression
     MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
     AttributeFilter.Conditions.AddRange(optionsetAttributeTypes);

     //A Properties expression to limit the properties to be included with attributes
     MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression() { AllProperties = false };
     AttributeProperties.PropertyNames.Add("OptionSet");
     AttributeProperties.PropertyNames.Add("AttributeType");

     //</snippetAttributeQueryExpression>

     //<snippetLabelQueryExpression3>

     //A label query expression to limit the labels returned to only those for the user's preferred language
     LabelQueryExpression labelQuery = new LabelQueryExpression();
     labelQuery.FilterLanguages.Add(_languageCode);

     //</snippetLabelQueryExpression3>

     //<snippetInitialRequest>
     //An entity query expression to combine the filter expressions and property expressions for the query.
     EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
     {

      Criteria = EntityFilter,
      Properties = EntityProperties,
      AttributeQuery = new AttributeQueryExpression()
      {
       Criteria = AttributeFilter,
       Properties = AttributeProperties
      },
      LabelQuery = labelQuery

     };
     
     //Retrieve the metadata for the query without a ClientVersionStamp
     RetrieveMetadataChangesResponse initialRequest = getMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet);
     //</snippetInitialRequest>

     //Add option labels to the cache and display the changes
     addOptionLabelsToCache(initialRequest.EntityMetadata, false);
     String ClientVersionStamp = initialRequest.ServerVersionStamp;
     Console.WriteLine("{0} option labels for {1} entities added to the cache.", 
      _optionLabelList.Count, 
      initialRequest.EntityMetadata.Count);
     Console.WriteLine("");
     Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp);
     Console.WriteLine("");


     //Add new custom entity with optionset
     Console.WriteLine("Adding a custom entity named {0} with a custom optionset attribute named : {1}", 
      _customEntitySchemaName, _customAttributeSchemaName);
     Console.WriteLine("");
     addCustomEntityWithOptionSet();
     //Publishing isn't necessary when adding a custom entity

     //Add new option labels to the cache and display the results
     ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp);

     Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp);
     Console.WriteLine("");

     //Add a new option to the custom optionset in the custom entity and publish the custom entity
     Console.WriteLine("Adding an additional option to the {0} attribute options.", 
      _customAttributeSchemaName);
     Console.WriteLine("");
     addOptionToCustomEntityOptionSet();
     //It is necessary to publish updates to metadata. Create and Delete operations are published automatically.
     publishUpdatedEntity();



     //Add the new option label to the cache and display the results
     ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp);

     Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp);
     Console.WriteLine("");

     Console.WriteLine("");
     Console.WriteLine("Current Options: {0}", _optionLabelList.Count.ToString());
     Console.WriteLine("");

     //Delete the custom entity
     Console.WriteLine("");
     Console.WriteLine("Deleting the {0} custom entity", 
      _customEntitySchemaName);
     Console.WriteLine("");
     deleteCustomEntityWithOptionSet();
     //Publishing isn't necessary when deleting a custom entity     


     //Retrieve metadata changes to remove option labels from deleted attributes and display the results
     ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp);

     Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp);
     Console.WriteLine("");

    }

   }

   // Catch any _service fault exceptions that Microsoft Dynamics CRM throws.
   catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
   {
    // You can handle an exception here or pass it back to the calling method.
    throw;
   }
  }
Example #41
0
  //<snippetStateModelTransitions.GetValidStatusOptions>
  /// <summary>
  /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity
  /// </summary>
  /// <param name="entityLogicalName">The logical name of the entity</param>
  /// <param name="currentStatusValue">The current status of the entity instance</param>
  /// <returns>A list of StatusOptions that represent the valid transitions</returns>
  public List<StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue)
  {

   List<StatusOption> validStatusOptions = new List<StatusOption>();

   //Check entity Metadata

   //Retrieve just one entity definition
   MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
   entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
   //Return the attributes and the EnforceStateTransitions property
   MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

   //Retrieve only State or Status attributes
   MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

   //Retrieve only the OptionSet property of the attributes
   MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

   //Set the query
   EntityQueryExpression query = new EntityQueryExpression()
   {
    Criteria = entityFilter,
    Properties = entityProperties,
    AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
   };

   //Retrieve the metadata
   RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
   RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

   //Check the value of EnforceStateTransitions
   Boolean? EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions;

   //Capture the state and status attributes
   StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
   StateAttributeMetadata stateAttribute = new StateAttributeMetadata();

   foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes)
   {
    switch (attributeMetadata.AttributeType)
    {
     case AttributeTypeCode.Status:
      statusAttribute = (StatusAttributeMetadata)attributeMetadata;
      break;
     case AttributeTypeCode.State:
      stateAttribute = (StateAttributeMetadata)attributeMetadata;
      break;
    }
   }


   if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
   {
    //When EnforceStateTransitions is true use the TransitionData to filter the valid options
    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value == currentStatusValue)
     {
      if (option.TransitionData != String.Empty)
      {
       XDocument transitionData = XDocument.Parse(option.TransitionData);

       IEnumerable<XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

       foreach (XElement e in elements)
       {
        int statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
        String statusLabel = GetOptionSetLabel(statusAttribute, statusOptionValue);

        string stateLabel = String.Empty;
        int? stateValue = null;
        foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
        {
         if (statusOption.Value.Value == statusOptionValue)
         {
          stateValue = statusOption.State.Value;
          stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
         }

        }


        validStatusOptions.Add(new StatusOption()
        {
         StateLabel = stateLabel,
         StateValue = stateValue.Value,
         StatusLabel = statusLabel,
         StatusValue = option.Value.Value
        });
       }
      }
     }
    }

   }
   else
   {
    ////When EnforceStateTransitions is false do not filter the available options

    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value != currentStatusValue)
     {

      String statusLabel = "";
      try
      {
       statusLabel = option.Label.UserLocalizedLabel.Label;
      }
      catch (Exception)
      {
       statusLabel = option.Label.LocalizedLabels[0].Label;
      };

      String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

      validStatusOptions.Add(new StatusOption()
      {
       StateLabel = stateLabel,
       StateValue = option.State.Value,
       StatusLabel = statusLabel,
       StatusValue = option.Value.Value

      });
     }
    }
   }
   return validStatusOptions;

  }
        private void LoadEntities()
        {
            working = true;
            entities = null;
            entityShitList = new List<string>();
            WorkAsync("Loading entities...",
                (eventargs) =>
                {
                    EnableControls(false);

                    var eqe = new EntityQueryExpression();
                    eqe.Properties = new MetadataPropertiesExpression(entityProperties);
                    var req = new RetrieveMetadataChangesRequest()
                    {
                        Query = eqe,
                        ClientVersionStamp = null
                    };
                    eventargs.Result = Service.Execute(req);
                },
                (completedargs) =>
                {
                    if (completedargs.Error != null)
                    {
                        MessageBox.Show(completedargs.Error.Message);
                    }
                    else
                    {
                        if (completedargs.Result is RetrieveMetadataChangesResponse)
                        {
                            entities = new Dictionary<string, EntityMetadata>();
                            foreach (var entity in ((RetrieveMetadataChangesResponse)completedargs.Result).EntityMetadata)
                            {
                                entities.Add(entity.LogicalName, entity);
                            }
                        }
                    }
                    working = false;
                    EnableControls(true);
                });
        }
Example #43
0
        public void Experiment_For_Saving_Entity_Metadata_To_File(string entityName)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString },
                                                         new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();
            using (orgService as IDisposable)
            {
                MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));

                EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
                {
                    Criteria = entityFilter,
                    Properties = new MetadataPropertiesExpression() { AllProperties = true }
                };
                RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };
                RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)orgService.Execute(retrieveMetadataChangesRequest);
                var entityMetadata = response.EntityMetadata[0];

                var path = Environment.CurrentDirectory;
                var shortFileName = entityName + "Metadata.xml";

                var fileName = System.IO.Path.Combine(path, shortFileName);
                var serialised = EntityMetadataUtils.SerializeMetaData(entityMetadata, System.Xml.Formatting.Indented);
                using (var writer = new System.IO.StreamWriter(fileName))
                {
                    writer.Write(serialised);
                    writer.Flush();
                    writer.Close();
                }

                if (!File.Exists(fileName))
                {
                    throw new FileNotFoundException("Could not save metadata file for entity " + entityName);
                }
            }
        }
Example #44
0
        public EntityMetadataCollection GetEntitiesMetadata()
        {
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                // Récupération de l'entité spécifiée
                Criteria = new MetadataFilterExpression
                {
                    Conditions =
                   {
                       //new MetadataConditionExpression("IsCustomEntity", MetadataConditionOperator.Equals, true),
                       new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false)
                   }
                },
                // Sans propriétés d'entité
                Properties = new MetadataPropertiesExpression
                {
                    AllProperties = false,
                    PropertyNames = { "Attributes", "DisplayName", "LogicalName", "SchemaName" }
                },
                AttributeQuery = new AttributeQueryExpression
                {
                    // Récupération de l'attribut spécifié
                    Criteria = new MetadataFilterExpression
                    {
                        FilterOperator = LogicalOperator.Or,
                        Conditions =
                       {
                           new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Picklist),
                           new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State),
                           new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status)
                       }
                    },
                    // Avec uniquement les données d'OptionSet
                    Properties = new MetadataPropertiesExpression
                    {
                        AllProperties = false,
                        PropertyNames = { "OptionSet", "DisplayName", "LogicalName", "EntityLogicalName", "SchemaName" }
                    }
                },
                LabelQuery = new LabelQueryExpression()
            };

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression,
                ClientVersionStamp = null
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            return response.EntityMetadata;
        }
Example #45
0
  //<snippetgetMetadataChanges>
  protected RetrieveMetadataChangesResponse getMetadataChanges(
   EntityQueryExpression entityQueryExpression,
   String clientVersionStamp,
   DeletedMetadataFilters deletedMetadataFilter)
  {
   RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
   {
    Query = entityQueryExpression,
    ClientVersionStamp = clientVersionStamp,
    DeletedMetadataFilters = deletedMetadataFilter
   };

   return (RetrieveMetadataChangesResponse)_service.Execute(retrieveMetadataChangesRequest);

  }
  /// <summary>
  /// This method connects to the Organization _service. 
  /// </summary>
  /// <param name="serverConfig">Contains server connection information.</param>

  public void Run(ServerConnection.Configuration serverConfig)
  {
   try
   {

    // Connect to the Organization _service. 
    // The using statement assures that the _service proxy will be properly disposed.
       using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
    {
     // This statement is required to enable early-bound type support.
     _serviceProxy.EnableProxyTypes();

     _service = (IOrganizationService)_serviceProxy;

     _userId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
     _languageCode = RetrieveUserUILanguageCode(_userId);



     //A filter expression to limit entities returned to non-intersect entities
     MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
     EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));


     //A properties expression to limit the properties to be included with entities
     MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
     {
      AllProperties = false
     };
     EntityProperties.PropertyNames.AddRange(new string[] { "OneToManyRelationships", "LogicalName", "DisplayName" });




     //A filter expression to only return system entity relationships
     MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);
     relationshipFilter.Conditions.Add(new MetadataConditionExpression("IsCustomRelationship", MetadataConditionOperator.Equals, false));

     //A Properties expression to limit the properties to be included with relationships
     MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression() { AllProperties = false };
     relationshipProperties.PropertyNames.Add("CascadeConfiguration");
     relationshipProperties.PropertyNames.Add("SchemaName");
     relationshipProperties.PropertyNames.Add("IsCustomizable");


     //A label query expression to limit the labels returned to only those for the user's preferred language
     LabelQueryExpression labelQuery = new LabelQueryExpression();
     labelQuery.FilterLanguages.Add(_languageCode);


     //An entity query expression to combine the filter expressions and property expressions for the query.
     EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
     {

      Criteria = EntityFilter,
      Properties = EntityProperties,
      RelationshipQuery = new RelationshipQueryExpression() { Criteria = relationshipFilter, Properties = relationshipProperties },
      LabelQuery = labelQuery

     };

     //Define the request
     RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression };

     //Retrieve the data
     RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request);


     //Process the data
     foreach (EntityMetadata entity in response.EntityMetadata)
     {
      if (entity.OneToManyRelationships != null)
      {
       foreach (OneToManyRelationshipMetadata relationship in entity.OneToManyRelationships)
       {
        var cascadeConfig = relationship.CascadeConfiguration;
        //When all of the CascadeConfiguration properties use the Cascade behavior the relationship is considered parental
        if (cascadeConfig.Assign == CascadeType.Cascade &&
         cascadeConfig.Delete == CascadeType.Cascade &&
         cascadeConfig.Merge == CascadeType.Cascade &&
         cascadeConfig.Reparent == CascadeType.Cascade &&
         cascadeConfig.Share == CascadeType.Cascade &&
         cascadeConfig.Unshare == CascadeType.Cascade)
        {
         //Only show results for relationships that can be customized
         if (relationship.IsCustomizable.Value)
         {
          //Write the entity name and the name of the relationship.
          Console.WriteLine(entity.DisplayName.UserLocalizedLabel.Label + "," + relationship.SchemaName);
         }
        }
       }
      }
     }
    }
   }

   // Catch any _service fault exceptions that Microsoft Dynamics CRM throws.
   catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
   {
    // You can handle an exception here or pass it back to the calling method.
    throw;
   }
  }
Example #47
0
  //</snippetgetMetadataChanges>

  //<snippetupdateOptionLabelList>
  protected String updateOptionLabelList(EntityQueryExpression entityQueryExpression, String clientVersionStamp)
  {
   //Retrieve metadata changes and add them to the cache
   RetrieveMetadataChangesResponse updateResponse;
   try
   {
    updateResponse = getMetadataChanges(entityQueryExpression, clientVersionStamp, DeletedMetadataFilters.OptionSet);
    addOptionLabelsToCache(updateResponse.EntityMetadata, true);
    removeOptionLabelsFromCache(updateResponse.DeletedMetadata, true);

   }
   catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
   {
    // Check for ErrorCodes.ExpiredVersionStamp (0x80044352)
    // Will occur when the timestamp exceeds the Organization.ExpireSubscriptionsInDays value, which is 90 by default.
    if (ex.Detail.ErrorCode == unchecked((int)0x80044352))
    {
     //reinitialize cache
     _optionLabelList.Clear();

     updateResponse = getMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet);
     //Add them to the cache and display the changes
     addOptionLabelsToCache(updateResponse.EntityMetadata, true);

    }
    else
    {
     throw ex;
    }

   }
   return updateResponse.ServerVersionStamp;
  }
Example #48
0
        public void Experiment_For_Selecting_Entity_Metadata()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString },
                                                         new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();
            using (orgService as IDisposable)
            {
                MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
              //  entityFilter.Conditions.Add(new MetadataConditionExpression("OneToManyRelationships", MetadataConditionOperator.NotEquals, null));

                var relationShipQuery = new RelationshipQueryExpression();
                MetadataFilterExpression relationShipFilter = new MetadataFilterExpression(LogicalOperator.And);
                relationShipFilter.Conditions.Add(new MetadataConditionExpression("RelationshipType", MetadataConditionOperator.Equals, RelationshipType.OneToManyRelationship));
                relationShipQuery.Criteria = relationShipFilter;

                var props = new MetadataPropertiesExpression();
                props.AllProperties = false;
                props.PropertyNames.Add("OneToManyRelationships");

                EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
                {
                    Criteria = entityFilter,
                    Properties = props,
                    RelationshipQuery = relationShipQuery
                };
                RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };
                RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)orgService.Execute(retrieveMetadataChangesRequest);
            }
        }
        /// <summary>
        /// エンティティのフィールドを取得します。
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public AttributeMetadata[] getAttributes(string entityName)
        {
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression();
            EntityFilter.Conditions.Add(new MetadataConditionExpression(
                "LogicalName",
                MetadataConditionOperator.Equals,
                entityName));

            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = true
            };

            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = true
            };

            LabelQueryExpression labelQuery = new LabelQueryExpression();
            labelQuery.FilterLanguages.Add(1041);

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = EntityFilter, // エンティティのフィルター
                Properties = EntityProperties, // エンティティのプロパティ指定
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = AttributeProperties // フィールドのプロパティの指定
                },
                LabelQuery = labelQuery // 表示言語の指定
            };

            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(
                new RetrieveMetadataChangesRequest()
                {
                    Query = entityQueryExpression
                }
            );

            return response.EntityMetadata[0].Attributes;
        }