예제 #1
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);
            }
        }
        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);
            }
        }
예제 #3
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);
            }

        }
        private void SetConditionExpressionValue(MetadataConditionExpression condition, MetadataConditionOperator conditionOperator, params object[] values)
        {
            condition.ConditionOperator = conditionOperator;
            if (values != null)
            {
                // is the literal a
                foreach (var value in values)
                {
                    if (value is Array)
                    {
                        var vals = new List <object>();

                        foreach (var o in value as Array)
                        {
                            vals.Add(o);
                        }

                        condition.Value = vals;
                    }
                    else
                    {
                        if (condition.Value != null)
                        {
                            throw new NotSupportedException("You cannot use multiple where condition values in a metadata query. " + condition.Value.ToString());
                        }
                        condition.Value = value;
                    }
                }
            }
        }
        public Result GetEntityDetials(MetadataConditionExpression expression)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

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

                EntityMetadata entityMetadata = (EntityMetadata)response.EntityMetadata[0];
                return(new Result(false, string.Empty, entityMetadata, logSystem));
            }
            catch (Exception ex)
            {
                return(new Result(true,
                                  MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                                  null, logSystem));
            }
        }
        public static 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());
        }
예제 #7
0
 public static string SerialiseMetadataConditionExpression(MetadataConditionExpression item)
 {
     return(@"<c:MetadataConditionExpression>
                     <c:ConditionOperator>" + item.ConditionOperator.ToString() + @"</c:ConditionOperator>
                     <c:PropertyName>" + item.PropertyName + @"</c:PropertyName>
                     <c:Value i:type='d:string' xmlns:d='http://www.w3.org/2001/XMLSchema'>" + item.Value + @"</c:Value>
                   </c:MetadataConditionExpression>");
 }
        private MetadataConditionExpression GetCondition(InFilter filter, out Column attColumn)
        {
            var condition = new MetadataConditionExpression();

            var left = filter.LeftHand;

            attColumn = left as Column;

            // defaullt attribute name for the filter condition.
            if (attColumn != null)
            {
                condition.PropertyName = attColumn.Name;
            }
            else
            {
                throw new NotSupportedException("IN operator only works agains a column value.");
            }

            var conditionOperator = MetadataConditionOperator.In;

            if (filter.Not)
            {
                conditionOperator = MetadataConditionOperator.NotIn;
            }
            var values = filter.Values;

            if (values.IsValueList)
            {
                var valuesList = values as ValueList;

                if (valuesList != null)
                {
                    var inValues = new object[valuesList.Values.Count()];
                    int index    = 0;
                    foreach (var item in valuesList.Values)
                    {
                        var literal = item as Literal;
                        if (literal == null)
                        {
                            throw new ArgumentException("The values list must contain literals.");
                        }
                        inValues[index] = GitLiteralValue(literal);
                        index++;
                    }
                    SetConditionExpressionValue(condition, conditionOperator, inValues);
                    return(condition);
                }
                throw new ArgumentException("The values list for the IN expression is null");
            }
            throw new NotSupportedException();
        }
예제 #9
0
        public RetrieveMetadataChangesResponse GetAttributeDetails(IOrganizationService service)
        {
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.In, "cebmain_toinvoicequantity"));

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

            EntityProperties.PropertyNames.AddRange(new string[] { "Attributes" });

            MetadataConditionExpression optionsetAttributeName = new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null);
            MetadataFilterExpression    AttributeFilter        = new MetadataFilterExpression(LogicalOperator.And);

            AttributeFilter.Conditions.Add(optionsetAttributeName);

            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };
            //foreach (string attrProperty in AttributeProperties)
            //{
            //    AttributeProperties.PropertyNames.Add(attrProperty);
            //}

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                Properties     = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = AttributeProperties,
                    Criteria   = AttributeFilter
                }
            };

            RetrieveMetadataChangesRequest req = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,
                //ClientVersionStamp = clientVersionStamp
            };

            return((RetrieveMetadataChangesResponse)service.Execute(req));
        }
예제 #10
0
        public void AddEntities(List<string> entityLogicalNames,List<string> propertiesToReturn)
        {
            Request.Query.Criteria = new MetadataFilterExpression();
            Request.Query.Criteria.FilterOperator = LogicalOperator.Or;
            Request.Query.Criteria.Conditions = new List<MetadataConditionExpression>();

            foreach (string entity in entityLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression();
                condition.ConditionOperator = MetadataConditionOperator.Equals;
                condition.PropertyName = "LogicalName";
                condition.Value = entity;
                Request.Query.Criteria.Conditions.Add(condition);
            }

            Request.Query.Properties = new MetadataPropertiesExpression();
            Request.Query.Properties.PropertyNames = propertiesToReturn;
        }
예제 #11
0
        public bool QueryAllMetaData()
        {
            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest();

            request.Query = new EntityQueryExpression();

            request.Query.Criteria = new MetadataFilterExpression();
            request.Query.Criteria.FilterOperator = LogicalOperator.Or;
            request.Query.Criteria.Conditions     = new List <MetadataConditionExpression>();

            // Which entitiy to return
            MetadataConditionExpression condition = new MetadataConditionExpression();

            condition.ConditionOperator = MetadataConditionOperator.Equals;
            condition.PropertyName      = "LogicalName";
            condition.Value             = "account";
            request.Query.Criteria.Conditions.Add(condition);

            request.Query.Properties = new MetadataPropertiesExpression();
            request.Query.Properties.PropertyNames = new List <string>("Attributes");

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

            attributeQuery.Properties = new MetadataPropertiesExpression();
            attributeQuery.Properties.PropertyNames = new List <string>("OptionSet");
            //attributeQuery.Properties.AllProperties = true;

            request.Query.AttributeQuery = attributeQuery;



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

            attributeQuery.Criteria = critiera;
            critiera.FilterOperator = LogicalOperator.And;
            critiera.Conditions     = new List <MetadataConditionExpression>();


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

            return(true);
        }
예제 #12
0
        public bool QueryAllMetaData()
        {
            

            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest();
            request.Query = new EntityQueryExpression();

            request.Query.Criteria = new MetadataFilterExpression();
            request.Query.Criteria.FilterOperator = LogicalOperator.Or;
            request.Query.Criteria.Conditions = new List<MetadataConditionExpression>();

            // Which entitiy to return
            MetadataConditionExpression condition = new MetadataConditionExpression();
            condition.ConditionOperator = MetadataConditionOperator.Equals;
            condition.PropertyName = "LogicalName";
            condition.Value = "account";
            request.Query.Criteria.Conditions.Add(condition);

            request.Query.Properties = new MetadataPropertiesExpression();
            request.Query.Properties.PropertyNames = new List<string>("Attributes");

            // Attribute Query Properties - Which Properties to return
            AttributeQueryExpression attributeQuery = new AttributeQueryExpression();
            attributeQuery.Properties = new MetadataPropertiesExpression();
            attributeQuery.Properties.PropertyNames = new List<string>("OptionSet");
            //attributeQuery.Properties.AllProperties = true;

            request.Query.AttributeQuery = attributeQuery;

           
            

            // Attribute Query Criteria - Which Attributes to return
            MetadataFilterExpression critiera = new MetadataFilterExpression();
            attributeQuery.Criteria = critiera;
            critiera.FilterOperator = LogicalOperator.And;
            critiera.Conditions = new List<MetadataConditionExpression>();
           

            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(request);
            return true;
        }
예제 #13
0
        public void AddEntities(IList <string> entityLogicalNames, IList <string> propertiesToReturn)
        {
            Request.Query.Criteria = new MetadataFilterExpression()
            {
                FilterOperator = LogicalOperator.Or
            };
            foreach (string entity in entityLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression()
                {
                    ConditionOperator = MetadataConditionOperator.Equals,
                    PropertyName      = "LogicalName",
                    Value             = entity
                };
                Request.Query.Criteria.Conditions.Add(condition);
            }

            if (propertiesToReturn != null)
            {
                Request.Query.Properties = new MetadataPropertiesExpression();
                Request.Query.Properties.PropertyNames.AddRange(propertiesToReturn);
            }
        }
예제 #14
0
        public void AddEntities(List<string> entityLogicalNames, List<string> propertiesToReturn)
        {
            _entityLogicalNames = entityLogicalNames;
            _entityPropertiesToReturn = propertiesToReturn;

            _request.Query.Criteria = new MetadataFilterExpression();
            _request.Query.Criteria.FilterOperator = LogicalOperator.Or;

            foreach (string entity in entityLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression();
                condition.ConditionOperator = MetadataConditionOperator.Equals;
                condition.PropertyName = "LogicalName";
                condition.Value = entity;
                _request.Query.Criteria.Conditions.Add(condition);
            }

            if (propertiesToReturn != null)
            {
                _request.Query.Properties = new MetadataPropertiesExpression();
                _request.Query.Properties.PropertyNames.AddRange(propertiesToReturn);
            }
        }
        public void AddEntities(List <string> entityLogicalNames, List <string> propertiesToReturn)
        {
            _entityLogicalNames       = entityLogicalNames;
            _entityPropertiesToReturn = propertiesToReturn;

            _request.Query.Criteria = new MetadataFilterExpression();
            _request.Query.Criteria.FilterOperator = LogicalOperator.Or;

            foreach (string entity in entityLogicalNames)
            {
                MetadataConditionExpression condition = new MetadataConditionExpression();
                condition.ConditionOperator = MetadataConditionOperator.Equals;
                condition.PropertyName      = "LogicalName";
                condition.Value             = entity;
                _request.Query.Criteria.Conditions.Add(condition);
            }

            if (propertiesToReturn != null)
            {
                _request.Query.Properties = new MetadataPropertiesExpression();
                _request.Query.Properties.PropertyNames.AddRange(propertiesToReturn);
            }
        }
예제 #16
0
        /// <summary>
        /// Gets the entity detials.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>Result.</returns>
        public Result GetEntityDetials(MetadataConditionExpression expression)
        {
            var watch = Stopwatch.StartNew();

            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));
            }
            finally
            {
                watch.Stop();
                logSystem.CreateLog($"{ MethodBase.GetCurrentMethod().ToString() } completed in { watch.ElapsedMilliseconds } ms", System.Diagnostics.EventLogEntryType.Information);
            }
        }
예제 #17
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!");
        }
예제 #18
0
        private static EntityMetadataCollection GetEntityMetadata(IOrganizationService service)
        {
            //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

            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;

            return(entities);
        }
예제 #19
0
        private RetrieveMetadataChangesResponse RetrieveMetadata()
        {
            // Connect to the Organization service.
            // The using statement assures that the service proxy will be properly disposed.
            using (var service = new OrganizationService("Crm"))
            {
                //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);
                var entities = ConfigurationManager.AppSettings["Entities"];
                if (!string.IsNullOrWhiteSpace(entities))
                {
                    string[] includedEntities = entities.ToLowerInvariant().Replace(" ", string.Empty).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    EntityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.In, includedEntities));
                }
                EntityFilter.Conditions.Add(new MetadataConditionExpression("IsValidForAdvancedFind", MetadataConditionOperator.Equals, true));

                //A properties expression to limit the properties to be included with entities
                MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression(
                    "OwnershipType",
                    "DisplayName",
                    "Attributes",
                    "ManyToManyRelationships",
                    "ManyToOneRelationships",
                    "OneToManyRelationships",
                    "PrimaryIdAttribute")
                {
                    AllProperties = false
                };

                //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);

                //A condition expresson to return optionset attributes
                MetadataConditionExpression[] optionsetAttributeTypes = new MetadataConditionExpression[] {
                    new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Uniqueidentifier),
                    new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Customer),
                    new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Lookup),
                    new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Owner)
                };

                //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("DisplayName");

                MetadataPropertiesExpression RelationshipProperties = new MetadataPropertiesExpression(
                    "Entity1LogicalName",
                    "Entity2LogicalName",
                    "RelationshipType",
                    "MetadataId",
                    "ReferencingEntity",
                    "ReferencedEntity",
                    "ReferencingAttribute",
                    "ReferencedAttribute")
                {
                    AllProperties = false
                };

                //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()
                    {
                        Properties = RelationshipProperties
                    },
                    LabelQuery = labelQuery
                };

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

                return((RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest));
            }
        }
예제 #20
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;
            }
        }
예제 #21
0
        public static void NegateOperator(this MetadataConditionExpression conditionOperator)
        {
            var negated = GetNegatedOperator(conditionOperator.ConditionOperator);

            conditionOperator.ConditionOperator = negated;
        }
예제 #22
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

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

                    // 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.
                    var 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));
                    var isVisibileInMobileTrue = new MetadataConditionExpression("IsVisibleInMobile", MetadataConditionOperator.Equals, true);
                    EntityFilter.Conditions.Add(isVisibileInMobileTrue);

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

                    //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
                    var AttributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
                    AttributeFilter.Conditions.AddRange(optionsetAttributeTypes);

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

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

                    //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 initialRequest = getMetadataChanges(service, entityQueryExpression, null, DeletedMetadataFilters.OptionSet);


                    //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(service);
                    //Publishing isn't necessary when adding a custom entity

                    //Add new option labels to the cache and display the results
                    ClientVersionStamp = updateOptionLabelList(service, 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(service);
                    //It is necessary to publish updates to metadata. Create and Delete operations are published automatically.
                    publishUpdatedEntity(service);



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

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

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

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up

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

                    Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp);
                    Console.WriteLine("");
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        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;
            }
        }
        private void AddFilterCondition(MetadataConditionExpression condition, Column attColumn)
        {
            var sourceTable     = (Table)attColumn.Source.Source;
            var sourceTableName = GetTableLogicalEntityName(sourceTable);

            MetadataFilterType filterType = MetadataFilterType.Entity;

            switch (sourceTableName)
            {
            case "entitymetadata":
                filterType = MetadataFilterType.Entity;
                break;

            case "attributemetadata":
                filterType = MetadataFilterType.Attribute;
                break;

            case "onetomanyrelationshipmetadata":
                filterType = MetadataFilterType.Relationship;
                break;

            case "manytomanyrelationshipmetadata":
                filterType = MetadataFilterType.Relationship;
                break;
            }

            //  var sourceEntityName = GetEntityNameOrAliasForSource(attColumn.Source, out isAlias, out link);
            //  condition.EntityName = sourceEntityName;

            // if filter expression present, add it to that.
            if (FilterExpression != null)
            {
                if (FilterExpression.FilterType == filterType)
                {
                    FilterExpression.Filter.Conditions.Add(condition);
                    return;
                }
                else
                {
                    // incompatible filter group type..
                }
            }

            switch (filterType)
            {
            case MetadataFilterType.Entity:
                // this.FilterExpression.Filter.Conditions.Add(condition);
                QueryExpression.Criteria.Conditions.Add(condition);
                break;

            case MetadataFilterType.Attribute:
                // this.AttributeFilterExpression.Filter.Conditions.Add(condition);
                QueryExpression.AttributeQuery.Criteria.Conditions.Add(condition);
                break;

            case MetadataFilterType.Relationship:
                //   this.RelationshipFilterExpression.Filter.Conditions.Add(condition);
                QueryExpression.RelationshipQuery.Criteria.Conditions.Add(condition);
                break;
            }
        }
예제 #25
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!");
        }
예제 #26
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;
   }
  }
        private MetadataConditionExpression GetCondition(OrderFilter filter, out Column attColumn, out bool isLeft)
        {
            var condition = new MetadataConditionExpression();

            attColumn = GetAttributeColumn(filter, out isLeft);
            if (attColumn != null)
            {
                condition.PropertyName = attColumn.Name;
            }

            MetadataConditionOperator con;
            var equalTo = filter as EqualToFilter;

            if (equalTo != null)
            {
                con = MetadataConditionOperator.Equals;
                var filterValue = GetFilterValue <object>(filter, isLeft);
                SetConditionExpressionValue(condition, con, filterValue);
                return(condition);
            }

            // Support Not Equals
            var notEqualTo = filter as NotEqualToFilter;

            if (notEqualTo != null)
            {
                con = MetadataConditionOperator.NotEquals;
                var filterValue = GetFilterValue <object>(filter, isLeft);
                SetConditionExpressionValue(condition, con, filterValue);
                return(condition);
            }

            // Support Greater Than
            var greaterThan = filter as GreaterThanFilter;

            if (greaterThan != null)
            {
                con = MetadataConditionOperator.GreaterThan;
                var filterValue = GetFilterValue <object>(filter, isLeft);
                SetConditionExpressionValue(condition, con, filterValue);
                return(condition);
            }

            // Support Greater Than Equal
            var greaterEqual = filter as GreaterThanEqualToFilter;

            if (greaterEqual != null)
            {
                throw new NotSupportedException("'Greater Than Equals' filter not supported for entity metadata queries.");
            }

            // Support Less Than
            var lessThan = filter as LessThanFilter;

            if (lessThan != null)
            {
                con = MetadataConditionOperator.LessThan;
                var filterValue = GetFilterValue <object>(filter, isLeft);
                SetConditionExpressionValue(condition, con, filterValue);
                return(condition);
            }

            // Support Less Than Equal
            var lessThanEqual = filter as LessThanEqualToFilter;

            if (lessThanEqual != null)
            {
                throw new NotSupportedException("'Less Than Equals' filter not supported for entity metadata queries.");
            }

            // Support Like
            var likeFilter = filter as LikeFilter;

            if (likeFilter != null)
            {
                throw new NotSupportedException("'Like' filter not supported for entity metadata queries.");
            }

            throw new NotSupportedException();
        }