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); }
private ParameterCollection GetEntityUsingMetadataQuery() { LabelQueryExpression labelFilter = new LabelQueryExpression(); labelFilter.FilterLanguages.Add(CrmContext.Language); EntityQueryExpression query = new EntityQueryExpression() { Properties = new MetadataPropertiesExpression() { AllProperties = true }, LabelQuery = labelFilter }; OrganizationRequest request = new OrganizationRequest("RetrieveMetadataChanges") { Parameters = new ParameterCollection { { "Query", query }, { "ClientVersionStamp", _timestamp } } }; OrganizationResponse response = CrmContext.OrganizationProxy.Execute(request); return(response.Results); }
public static string SerialiseLabelQueryExpression(LabelQueryExpression item) { if (item != null) { string xml = @"<c:FilterLanguages xmlns:d='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>"; foreach (int lcid in item.FilterLanguages) { xml = xml + @"<d:int>" + lcid.ToString() + @"</d:int>"; } xml = xml + @"</c:FilterLanguages>"; return(xml); } else { return(""); } }
/// <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); }
/// <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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // 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; } }
//</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; } }
[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(); } }
/// <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; } }
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!"); }
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); }
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)); } }
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; }
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); }
//</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; } }
/// <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; }