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]);
        }
        private static string GetPrimaryIdAttributeLogicalName(OrganizationServiceContext serviceContext, string entityLogicalName)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

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

            var response = (RetrieveMetadataChangesResponse)serviceContext.Execute(new RetrieveMetadataChangesRequest
            {
                Query = new EntityQueryExpression
                {
                    Criteria   = entityFilter,
                    Properties = new MetadataPropertiesExpression("LogicalName", "PrimaryIdAttribute")
                }
            });

            var entity = response.EntityMetadata.FirstOrDefault(e => e.LogicalName == entityLogicalName);

            if (entity == null)
            {
                throw new InvalidOperationException(ResourceManager.GetString("PrimaryIdAttribute_For_Entity_Retrieve_Exception".FormatWith(entityLogicalName)));
            }

            return(entity.PrimaryIdAttribute);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        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);
            }
        }
Exemplo n.º 5
0
        public void AddAttributes(List<string> attributeLogicalNames, List<string> propertiesToReturn)
        {
            this._attributeLogicalNames = attributeLogicalNames;
            this._attributePropertiesToReturn = propertiesToReturn;

            // Attribute Query Properties - Which Properties to return
            AttributeQueryExpression attributeQuery = new AttributeQueryExpression();
            attributeQuery.Properties = new MetadataPropertiesExpression();
            attributeQuery.Properties.PropertyNames.AddRange(propertiesToReturn);

            _request.Query.AttributeQuery = attributeQuery;

            // Attribute Query Criteria - Which Attributes to return
            MetadataFilterExpression critiera = new MetadataFilterExpression();
            attributeQuery.Criteria = critiera;
            critiera.FilterOperator = LogicalOperator.Or;


            foreach (string attribute in attributeLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression();
                condition.PropertyName = "LogicalName";
                condition.ConditionOperator = MetadataConditionOperator.Equals;
                condition.Value = attribute;
                critiera.Conditions.Add(condition);
            }

        }
        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());
        }
        /// <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>
        /// <param name="entityTypeCode"></param>
        /// <returns></returns>
        public static string GetEntityLogicalName(this 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);

            return(response.EntityMetadata.Count == 1 ? response.EntityMetadata[0].LogicalName : null);
        }
        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));
            }
        }
        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 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);
        }
Exemplo n.º 11
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);
        }
        /// <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());
        }
        public void AddAttributes(List <string> attributeLogicalNames, List <string> propertiesToReturn)
        {
            this._attributeLogicalNames       = attributeLogicalNames;
            this._attributePropertiesToReturn = propertiesToReturn;

            // Attribute Query Properties - Which Properties to return
            AttributeQueryExpression attributeQuery = new AttributeQueryExpression();

            attributeQuery.Properties = new MetadataPropertiesExpression();
            attributeQuery.Properties.PropertyNames.AddRange(propertiesToReturn);

            _request.Query.AttributeQuery = attributeQuery;

            // Attribute Query Criteria - Which Attributes to return
            MetadataFilterExpression critiera = new MetadataFilterExpression();

            attributeQuery.Criteria = critiera;
            critiera.FilterOperator = LogicalOperator.Or;


            foreach (string attribute in attributeLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression();
                condition.PropertyName      = "LogicalName";
                condition.ConditionOperator = MetadataConditionOperator.Equals;
                condition.Value             = attribute;
                critiera.Conditions.Add(condition);
            }
        }
        private static bool RemoveWrongEntityMetadataAttributes(IOrganizationServiceExtented service, List <string> list)
        {
            bool executeAgain = true;

            while (executeAgain)
            {
                executeAgain = false;

                try
                {
                    MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                    entityFilter.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.Equals, SystemUser.EntityLogicalName));

                    var entityQueryExpression = new EntityQueryExpression()
                    {
                        Properties = new MetadataPropertiesExpression(nameof(EntityMetadata.LogicalName)),

                        Criteria = entityFilter,
                    };

                    entityQueryExpression.Properties.PropertyNames.AddRange(list);

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

                    return(true);
                }
                catch (FaultException <OrganizationServiceFault> fex)
                {
                    if (fex.Detail != null &&
                        fex.Detail.ErrorCode == -2147204733 &&
                        fex.Detail.InnerFault != null &&
                        fex.Detail.InnerFault.InnerFault != null &&
                        fex.Detail.InnerFault.InnerFault.Message.StartsWith("The type EntityMetadata does not have a property named ", StringComparison.InvariantCultureIgnoreCase)
                        )
                    {
                        var propertyName = fex.Detail.InnerFault.InnerFault.Message.Replace("The type EntityMetadata does not have a property named ", string.Empty);

                        list.Remove(propertyName);

                        executeAgain = true;
                    }
                    else
                    {
                        DTEHelper.WriteExceptionToLog(fex);
                    }
                }
                catch (Exception ex)
                {
                    DTEHelper.WriteExceptionToLog(ex);
                }
            }

            return(false);
        }
Exemplo n.º 15
0
        /// <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);
        }
Exemplo n.º 16
0
        public EntityReference GetEntityReference(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 = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            if (response.EntityMetadata.Count == 1)
            {
                string logicalName = response.EntityMetadata[0].LogicalName;
                return(new EntityReference(logicalName, Id));
            }
            return(null);
        }
Exemplo n.º 17
0
        public void AddAttributes(IList <string> attributeLogicalNames, IList <string> propertiesToReturn)
        {
            // Attribute Query Properties - Which Properties to return
            AttributeQueryExpression attributeQuery = new AttributeQueryExpression()
            {
                Properties = new MetadataPropertiesExpression()
            };

            attributeQuery.Properties.PropertyNames.AddRange(propertiesToReturn);

            Request.Query.AttributeQuery = attributeQuery;

            // Attribute Query Criteria - Which Attributes to return
            MetadataFilterExpression critiera = new MetadataFilterExpression()
            {
                FilterOperator = LogicalOperator.Or
            };

            attributeQuery.Criteria = critiera;


            foreach (string attribute in attributeLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression()
                {
                    PropertyName      = "LogicalName",
                    ConditionOperator = MetadataConditionOperator.Equals,
                    Value             = attribute
                };
                critiera.Conditions.Add(condition);
            }
        }
        private void SetRelationshipFilter(MetadataFilterExpression metadataFilterExpression, MetadataConditionExpression relationshipTypeCondition, bool includeOneToMany, bool includeManyToMany)
        {
            if (includeManyToMany && includeOneToMany)
            {
                metadataFilterExpression.Conditions.Remove(relationshipTypeCondition);
            }
            else
            {
                if (includeManyToMany)
                {
                    relationshipTypeCondition.Value = RelationshipType.ManyToManyRelationship;
                }
                else if (includeOneToMany)
                {
                    relationshipTypeCondition.Value = RelationshipType.OneToManyRelationship;
                }
            }

            if (!_hasRelationships)
            {
                SetExcludeFilter(metadataFilterExpression, false);
                metadataFilterExpression.Conditions.Add(relationshipTypeCondition);
                _hasRelationships = true;
            }
        }
        /// <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;
        }
        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>());
        }
        /// <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"];

            if (metadataCollection.Count == 1)
            {
                return(metadataCollection[0].LogicalName);
            }
            return(null);
        }
Exemplo n.º 22
0
        public static RetrieveMetadataChangesResponse GetEntitiesMetadata(IOrganizationService service, bool BPFEntitySupported)
        {
            var entityFilter = new MetadataFilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
            if (BPFEntitySupported)
            {
                entityFilter.Conditions.Add(new MetadataConditionExpression("IsBPFEntity", MetadataConditionOperator.Equals, false));
            }
            entityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities));

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

            var query = new EntityQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = entityProps
            };

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

            return(response);
        }
Exemplo n.º 23
0
        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);
        }
Exemplo n.º 25
0
        public static List <string> GetAllDataSource(CrmServiceClient crmServiceClient)
        {
            var list             = new List <string>();
            var filterExpression = new MetadataFilterExpression();

            filterExpression.Conditions.Add(new MetadataConditionExpression("DataProviderId", MetadataConditionOperator.Equals, Guid.Parse("B2112A7E-B26C-42F7-9B63-9A809A9D716F")));
            var propertiesExpression = new MetadataPropertiesExpression(new string[7]
            {
                "DataProviderId",
                "LogicalName",
                "SchemaName",
                "MetadataId",
                "DisplayName",
                "ExternalName",
                "DisplayCollectionName"
            });
            var entityQueryExpression = new EntityQueryExpression
            {
                Criteria = new MetadataFilterExpression()
            };

            entityQueryExpression.Criteria   = filterExpression;
            entityQueryExpression.Properties = propertiesExpression;
            var request = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };
            var response = (RetrieveMetadataChangesResponse)crmServiceClient.Execute(request);

            foreach (EntityMetadata entityMetadata in response.EntityMetadata)
            {
                list.Add(entityMetadata.LogicalName);
            }
            return(list);
        }
Exemplo n.º 26
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);
                }
            }
        }
Exemplo n.º 27
0
        public static void QueryAllEntities()
        {
            string _timestamp        = "";
            int    DaysSinceModified = 0;

            var spinner = new Spinner(5, 0);

            Console.ForegroundColor = ConsoleColor.Green;
            spinner.Start();


            EntityMetadata md;

            if (_ClientVersionStamp != null)
            {
                _timestamp = _ClientVersionStamp;
            }
            else
            {
                try
                {
                    _timestamp          = GetStoredTimestamp();
                    _ClientVersionStamp = _timestamp;
                    Console.WriteLine("Stored timestamp found: " + _timestamp);
                }catch (Exception e)
                {
                    Console.WriteLine("Error getting stored timestamp: " + e.Message);
                }
            }

            var EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
            //EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.Equals, "ServiceAppointment"));
            var entityQueryExpression = new EntityQueryExpression()
            {
                Criteria = EntityFilter
            };
            RetrieveMetadataChangesRequest req = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,
                ClientVersionStamp = _timestamp
            };
            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)service.Execute(req);


            spinner.Stop();
            Console.WriteLine("\n Query Completed, presenting findings... \n");
            Console.ForegroundColor = ConsoleColor.White;
            StoreChangedMetaData(response.DeletedMetadata, response.EntityMetadata);



            Console.WriteLine("\n===END===");
            Console.ForegroundColor = ConsoleColor.White;
        }
 private void SetExcludeFilter(MetadataFilterExpression filterExpression, bool filterOutAll)
 {
     if (filterOutAll)
     {
         filterExpression.Conditions.Add(_DefaultExcludeFilter);
     }
     else
     {
         filterExpression.Conditions.Remove(_DefaultExcludeFilter);
     }
 }
        private RetrieveMetadataChangesResponse GetEntityMetadata()
        {
            var entityFilter = new MetadataFilterExpression(LogicalOperator.And);

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

            var entityProperties = new MetadataPropertiesExpression
            {
                AllProperties = false
            };

            entityProperties.PropertyNames.AddRange("DisplayName", "Attributes", "OneToManyRelationships"
                                                    , "ManyToOneRelationships", "ManyToManyRelationships");

            var attributeProperties = new MetadataPropertiesExpression
            {
                AllProperties = false
            };

            attributeProperties.PropertyNames
            .AddRange("IsPrimaryId", "LogicalName", "SchemaName", "DisplayName", "AttributeOf", "IsValidForCreate", "IsValidForUpdate");

            var relationshipProperties = new MetadataPropertiesExpression
            {
                AllProperties = false
            };

            relationshipProperties.PropertyNames.AddRange("ReferencedAttribute", "ReferencedEntity",
                                                          "ReferencingEntity", "ReferencingAttribute", "SchemaName",
                                                          "Entity1LogicalName", "Entity2LogicalName", "IntersectEntityName");

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

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

            return((RetrieveMetadataChangesResponse)Service.Execute(retrieveMetadataChangesRequest));
        }
Exemplo n.º 30
0
        internal override void AddCriteria(RetrieveMetadataChangesRequest metadataQry)
        {
            var filter = new MetadataFilterExpression
            {
                Conditions =
                {
                    new MetadataConditionExpression(nameof(AttributeMetadata.LogicalName), MetadataConditionOperator.Equals, AttributeName)
                }
            };

            AddFilter(metadataQry, filter);
        }
        public static void Run(CDSWebApiService svc)
        {
            var entityFilter = new MetadataFilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions     = new List <MetadataConditionExpression>
                {
                    new MetadataConditionExpression()
                    {
                        ConditionOperator = MetadataConditionOperator.Equals,
                        PropertyName      = "SchemaName",
                        Value             = new Microsoft.Cds.Metadata.Query.Object()
                        {
                            Type = "string", Value = "Account"
                        }
                    }
                }
            };

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

            var query = new EntityKeyQueryExpression()
            {
                Criteria   = entityFilter,
                Properties = entityProperties
            };
            var jsonQuery = JsonConvert.SerializeObject(query);
            var jsonDeletedMetadataFilters = JsonConvert.SerializeObject(DeletedMetadataFilters.Default);

            //BUG: 1563435 This returns an HTML Bad Request error
            //svc.Get($"RetrieveMetadataChanges(Query={jsonQuery},DeletedMetadataFilters={jsonDeletedMetadataFilters})");

            //This returns all metadata without any filter
            var response = svc.Get("RetrieveMetadataChanges");

            var results = (RetrieveMetadataChangesResponse)JsonConvert.DeserializeObject(response.ToString(), typeof(RetrieveMetadataChangesResponse));

            Console.WriteLine($"ServerVersionStamp: {results.ServerVersionStamp}\n");
            Console.WriteLine($"Entities returned: {results.EntityMetadata.Count}\n");

            var accountMetadata = results.EntityMetadata.Find(x => x.SchemaName.Equals("Account"));

            accountMetadata.Attributes.Sort((x, y) => x.SchemaName.CompareTo(y.SchemaName));

            accountMetadata.Attributes.ForEach(x => {
                Console.WriteLine($"{x.SchemaName} {x.AttributeTypeName.Value}");
            });
            Console.WriteLine();
        }
Exemplo n.º 32
0
        public void getEntityMetaData()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            RetrieveVersionRequest  versionReq = new RetrieveVersionRequest();
            RetrieveVersionResponse resp       = (RetrieveVersionResponse)service.Execute(versionReq);
            //assigns the version to a string
            string VersionNumber = resp.Version;

            bool isKeyCompatibleVersion = isCompatibleVersion(VersionNumber);

            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

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

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

            EntityProperties.PropertyNames.AddRange(new string[] { "Attributes", "OneToManyRelationships", "LogicalName", "DisplayName", "PrimaryIdAttribute", "PrimaryNameAttribute" });
            if (isKeyCompatibleVersion)
            {
                EntityProperties.PropertyNames.Add("Keys");
            }


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

            AttributeProperties.PropertyNames.AddRange("AttributeType", "LogicalName", "DisplayName", "SchemaName", "AttributeType", "IsPrimaryName", "IsValidForUpdate", "OptionSet");

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                Properties     = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = AttributeProperties
                }//,
                 //RelationshipQuery = new RelationshipQueryExpression() { Properties = new MetadataPropertiesExpression() {  AllProperties = true} }
            };

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

            var response = (RetrieveMetadataChangesResponse)service.Execute(req);
        }
Exemplo n.º 33
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);
            }
        }
Exemplo n.º 34
0
        /// <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;
        }
Exemplo n.º 35
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;

  }
Exemplo n.º 36
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);
            }
        }
Exemplo n.º 37
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);
                }
            }
        }
Exemplo n.º 38
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;
   }
  }
Exemplo n.º 39
0
        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>
  /// 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;
   }
  }
Exemplo n.º 41
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;
   }
  }
Exemplo n.º 42
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!");
        }