internal static List <string> GetEntityFieldNames(string entityName, XrmServiceContext context, bool cached = true) { if (entityName == "none") { return(new List <string>()); } if (AttributeList.ContainsKey(entityName) && cached) { return(AttributeList[entityName]); } lock (AttributeList) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add( new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName)); var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("Attributes"); var attributesFilter = new MetadataFilterExpression(LogicalOperator.And); attributesFilter.Conditions.Add( new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null)); var attributeProperties = new MetadataPropertiesExpression { AllProperties = false }; attributeProperties.PropertyNames.AddRange("LogicalName"); var entityQueryExpression = new EntityQueryExpression { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression { Criteria = attributesFilter, Properties = attributeProperties } }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression, ClientVersionStamp = null }; var attributeNames = ((RetrieveMetadataChangesResponse)context.Execute(retrieveMetadataChangesRequest)) .EntityMetadata.First().Attributes .Select(attribute => attribute.LogicalName).OrderBy(name => name).ToList(); AttributeList[entityName] = attributeNames; } return(AttributeList[entityName]); }
public void RetrieveMetadataChangesRequest() { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, 1)); var propertyExpression = new MetadataPropertiesExpression { AllProperties = false }; propertyExpression.PropertyNames.Add("LogicalName"); var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = propertyExpression }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)orgAdminService.Execute(retrieveMetadataChangesRequest); Assert.Equal("account", response.EntityMetadata[0].LogicalName); }
public EntityReference GetEntityReference(IOrganizationService service) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, this.EntityTypeCode)); var propertyExpression = new MetadataPropertiesExpression { AllProperties = false }; propertyExpression.PropertyNames.Add("LogicalName"); var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = propertyExpression }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest); if (response.EntityMetadata.Count == 1) { string logicalName = response.EntityMetadata[0].LogicalName; return(new EntityReference(logicalName, Id)); } return(null); }
/// <summary> /// Gets details of changes in metadata that have occurred for a particular entity, since the specified time stamp. Allows a subset of properties to be specified, and filters for information regarding deleted metadata that will be returned. /// </summary> /// <param name="entityLogicalName"></param> /// <param name="clientTimestamp"></param> /// <param name="properties"></param> /// <param name="deletedFilters"></param> /// <returns></returns> public RetrieveMetadataChangesResponse GetChanges(string entityLogicalName, string clientTimestamp, IEnumerable <string> properties, DeletedMetadataFilters deletedFilters) { // retrieve the current timestamp value; var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); var props = new MetadataPropertiesExpression(); if (properties == null) { props.AllProperties = true; } else { props.PropertyNames.AddRange(properties); } //LabelQueryExpression labels = new LabelQueryExpression(); var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = props, AttributeQuery = new AttributeQueryExpression() { Properties = props } }; var response = GetMetadataChanges(entityQueryExpression, clientTimestamp, deletedFilters); var timeStamp = response.ServerVersionStamp; Debug.WriteLine("Next Timestamp: " + timeStamp); return(response); }
/// <summary> /// Gets details of changes in metadata that have occurred for a particular entity, since the specified time stamp. Allows a subset of properties to be specified, and filters for information regarding deleted metadata that will be returned. /// </summary> /// <param name="entityLogicalName"></param> /// <param name="clientTimestamp"></param> /// <param name="properties"></param> /// <param name="deletedFilters"></param> /// <returns></returns> public RetrieveMetadataChangesResponse GetChanges(string entityLogicalName, string clientTimestamp, IEnumerable<string> properties, DeletedMetadataFilters deletedFilters) { // retrieve the current timestamp value; var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); var props = new MetadataPropertiesExpression(); if (properties == null) { props.AllProperties = true; } else { props.PropertyNames.AddRange(properties); } //LabelQueryExpression labels = new LabelQueryExpression(); var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = props, AttributeQuery = new AttributeQueryExpression() { Properties = props } }; var response = GetMetadataChanges(entityQueryExpression, clientTimestamp, deletedFilters); var timeStamp = response.ServerVersionStamp; Debug.WriteLine("Next Timestamp: " + timeStamp); return response; }
private RetrieveMetadataChangesResponse GetEntityMetadata() { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add( new MetadataConditionExpression( "LogicalName", MetadataConditionOperator.In, _entityLogicalNames)); var entityProperties = new MetadataPropertiesExpression() { AllProperties = false }; entityProperties.PropertyNames.AddRange(new string[] { "Attributes", "ManyToManyRelationships", "OneToManyRelationships", "ManyToOneRelationships" }); // A filter expression to apply the optionsetAttributeTypes condition expression var attributeFilter = new MetadataFilterExpression(LogicalOperator.Or); // A Properties expression to limit the properties to be included with attributes var attributeProperties = new MetadataPropertiesExpression() { AllProperties = true }; // A label query expression to limit the labels returned to only those for the output preferred language var labelQuery = new LabelQueryExpression(); labelQuery.FilterLanguages.Add(1033); // An entity query expression to combine the filter expressions and property expressions for the query. var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }, LabelQuery = labelQuery }; // Retrieve the metadata for the query without a ClientVersionStamp var request = new RetrieveMetadataChangesRequest() { ClientVersionStamp = null, Query = entityQueryExpression }; var metadataRequest = (RetrieveMetadataChangesResponse)_service.Execute(request); return(metadataRequest); }
public static RetrieveMetadataChangesResponse GetEntitiesMetadata(IOrganizationService service, bool BPFEntitySupported) { var entityFilter = new MetadataFilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false)); if (BPFEntitySupported) { entityFilter.Conditions.Add(new MetadataConditionExpression("IsBPFEntity", MetadataConditionOperator.Equals, false)); } entityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities)); var entityProps = new MetadataPropertiesExpression("DisplayName", "LogicalName", "SchemaName", "ObjectTypeCode"); var query = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProps }; var request = new RetrieveMetadataChangesRequest() { Query = query }; var response = (RetrieveMetadataChangesResponse)service.Execute(request); return(response); }
private void Update_AllEntities() { try { // TODO REMOVE THIS var connection = QuickConnection.Connect(settings.CrmSdkUrl, settings.Domain, settings.Username, settings.Password, settings.CrmOrg); var connString = CrmConnection.Parse(settings.GetOrganizationCrmConnectionString()); var connection = new OrganizationService(connString); var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("LogicalName"); var entityQueryExpression = new EntityQueryExpression { Properties = entityProperties }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression, ClientVersionStamp = null }; allEntities = ((RetrieveMetadataChangesResponse)connection.Execute(retrieveMetadataChangesRequest)).EntityMetadata.ToArray(); } catch (Exception ex) { var error = "[ERROR] " + ex.Message + (ex.InnerException != null ? "\n" + "[ERROR] " + ex.InnerException.Message : ""); UpdateStatus(error, false); UpdateStatus("Unable to refresh entities, check connection information", false); } }
private List <EntityMetadata> GetEntitiesDisplayNameWithPrivileges() { MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression ( nameof(EntityMetadata.LogicalName) , nameof(EntityMetadata.DisplayName) , nameof(EntityMetadata.SchemaName) , nameof(EntityMetadata.Description) , nameof(EntityMetadata.ObjectTypeCode) , nameof(EntityMetadata.Privileges) ) { AllProperties = false }; EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, }; RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request); return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList()); }
public static RetrieveMetadataChangesResponse GetEntityAttributes(IOrganizationService service, string entity) { var entityFilter = new MetadataFilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entity)); //var entityProps = new MetadataPropertiesExpression("DisplayName", "LogicalName", "SchemaName", "ObjectTypeCode"); var attributeProps = new MetadataPropertiesExpression("DisplayName", "LogicalName", "SchemaName", "AttributeType", "IsPrimaryId", "IsPrimaryName", "IsValidForRead"); var query = new EntityQueryExpression() { Criteria = entityFilter, //Properties = entityProps, AttributeQuery = new AttributeQueryExpression() { Properties = attributeProps }, }; var request = new RetrieveMetadataChangesRequest() { Query = query }; var response = (RetrieveMetadataChangesResponse)service.Execute(request); return(response); }
/// <summary> /// Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata /// </summary> /// <param name="service"></param> /// <param name="entityTypeCode"></param> /// <returns></returns> public static string GetEntityLogicalName(this IOrganizationService service, int entityTypeCode) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, entityTypeCode)); var propertyExpression = new MetadataPropertiesExpression { AllProperties = false }; propertyExpression.PropertyNames.Add("LogicalName"); var entityQueryExpression = new EntityQueryExpression { Criteria = entityFilter, Properties = propertyExpression }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest); return(response.EntityMetadata.Count == 1 ? response.EntityMetadata[0].LogicalName : null); }
private List <EntityMetadata> FindEntitiesPropertiesOrAll(string entityName, int?entityTypeCode, params string[] properties) { var entityProperties = new MetadataPropertiesExpression(properties) { AllProperties = false }; var entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, }; if (properties != null && properties.Contains(nameof(EntityMetadata.Attributes), StringComparer.InvariantCultureIgnoreCase)) { entityQueryExpression.AttributeQuery = new AttributeQueryExpression() { Properties = new MetadataPropertiesExpression ( nameof(AttributeMetadata.LogicalName) , nameof(AttributeMetadata.AttributeType) , nameof(AttributeMetadata.IsValidForRead) ), }; } if (!string.IsNullOrEmpty(entityName) || entityTypeCode.HasValue) { var criteria = new MetadataFilterExpression(LogicalOperator.Or); if (!string.IsNullOrEmpty(entityName)) { criteria.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.Equals, entityName)); } if (entityTypeCode.HasValue) { criteria.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.ObjectTypeCode), MetadataConditionOperator.Equals, entityTypeCode.Value)); } entityQueryExpression.Criteria = criteria; } var request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; var response = (RetrieveMetadataChangesResponse)_service.Execute(request); if (response.EntityMetadata.Any()) { return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList()); } else if (!string.IsNullOrEmpty(entityName) || entityTypeCode.HasValue) { return(FindEntitiesPropertiesOrAll(null, null, properties)); } return(new List <EntityMetadata>()); }
public static IEnumerable <EntityNameViewModel> RetrieveEntityNames(IOrganizationService service) { var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("LogicalName", "DisplayName"); var entityQueryExpression = new EntityQueryExpression { Properties = entityProperties }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression, ClientVersionStamp = null }; return(((RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest)) .EntityMetadata.Select(e => new EntityNameViewModel { LogicalName = e.LogicalName, DisplayName = e.DisplayName?.UserLocalizedLabel?.Label })); }
public static IDictionary <string, int> GetEntityCodes(Settings settings, IConnectionManager connectionManager, MetadataCache metadataCache) { if (metadataCache.EntityCodesCache != null) { return(metadataCache.EntityCodesCache); } var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("LogicalName", "ObjectTypeCode"); var entityQueryExpression = new EntityQueryExpression { Properties = entityProperties }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression }; return(metadataCache.EntityCodesCache = ((RetrieveMetadataChangesResponse)connectionManager.Get().Execute(retrieveMetadataChangesRequest)).EntityMetadata .ToDictionary(e => e.LogicalName, e => e.ObjectTypeCode.GetValueOrDefault())); }
public void Should_Support_Selecting_Entity_Metadata() { StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendLine("SELECT e.MetadataId, e.HasChanged, e.ActivityTypeMask, e.Attributes, e.AutoRouteToOwnerQueue, e.CanBeInManyToMany, e.CanBePrimaryEntityInRelationship, "); sqlBuilder.AppendLine("e.CanBeRelatedEntityInRelationship, e.CanCreateAttributes, e.CanCreateCharts, e.CanCreateForms, e.CanCreateViews, e.CanModifyAdditionalSettings, e.CanTriggerWorkflow, "); sqlBuilder.AppendLine("e.Description, e.DisplayCollectionName, e.DisplayName, e.IconLargeName, e.IconMediumName, e.IconSmallName, e.IsActivity, e.IsActivityParty, e.IsAuditEnabled, "); sqlBuilder.AppendLine("e.IsAvailableOffline, e.IsChildEntity, e.IsConnectionsEnabled, e.IsCustomEntity, e.IsCustomizable, e.IsDocumentManagementEnabled, e.IsDuplicateDetectionEnabled, "); sqlBuilder.AppendLine("e.IsEnabledForCharts, e.IsImportable, e.IsIntersect, e.IsMailMergeEnabled, e.IsMailMergeEnabled, e.IsManaged, e.IsMappable, e.IsReadingPaneEnabled, e.IsRenameable, "); sqlBuilder.AppendLine("e.IsValidForAdvancedFind, e.IsValidForQueue, e.IsVisibleInMobile, e.LogicalName, e.IsCustomEntity, e.ManyToManyRelationships, e.ManyToOneRelationships, "); sqlBuilder.AppendLine("e.ObjectTypeCode, e.OneToManyRelationships, e.OwnershipType, e.PrimaryIdAttribute, e.PrimaryNameAttribute, e.Privileges, e.RecurrenceBaseEntityLogicalName, "); sqlBuilder.AppendLine("e.ReportViewName, e.SchemaName, e.RecurrenceBaseEntityLogicalName "); sqlBuilder.AppendLine("FROM EntityMetadata AS e"); // Arrange var sql = sqlBuilder.ToString(); Console.Write(sql); // Act using (var sandbox = RequestProviderTestsSandbox.Create()) { var queryExpression = GetOrganizationRequest <RetrieveMetadataChangesRequest>(sandbox.FakeCrmDbConnection, sql); // Assert Assert.That(queryExpression, Is.Not.Null); Assert.That(queryExpression.Query, Is.Not.Null); EntityQueryExpression query = queryExpression.Query; Assert.That(query.Properties, Is.Not.Null); MetadataPropertiesExpression props = query.Properties; Assert.That(props.PropertyNames.Count, Is.GreaterThan(1)); } }
public static string geEntityLogicalName(int ObjectTypeCode) { //http://www.dynamicscrm.blog/object-type-codes-cheat-sheet-for-dynamics-365/ //https://msdynamicscrmblog.wordpress.com/2013/07/18/entity-type-codes-in-dynamics-crm-2011/ string entityLogicalName = String.Empty; MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And); EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, ObjectTypeCode)); MetadataPropertiesExpression mpe = new MetadataPropertiesExpression(); mpe.AllProperties = false; mpe.PropertyNames.Add("ObjectTypeCode"); EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Criteria = EntityFilter, Properties = mpe }; RetrieveMetadataChangesResponse initialRequest = GetMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet); if (initialRequest.EntityMetadata.Count == 1) { entityLogicalName = initialRequest.EntityMetadata[0].LogicalName; } return(entityLogicalName); }
public static List <string> GetAllDataSource(CrmServiceClient crmServiceClient) { var list = new List <string>(); var filterExpression = new MetadataFilterExpression(); filterExpression.Conditions.Add(new MetadataConditionExpression("DataProviderId", MetadataConditionOperator.Equals, Guid.Parse("B2112A7E-B26C-42F7-9B63-9A809A9D716F"))); var propertiesExpression = new MetadataPropertiesExpression(new string[7] { "DataProviderId", "LogicalName", "SchemaName", "MetadataId", "DisplayName", "ExternalName", "DisplayCollectionName" }); var entityQueryExpression = new EntityQueryExpression { Criteria = new MetadataFilterExpression() }; entityQueryExpression.Criteria = filterExpression; entityQueryExpression.Properties = propertiesExpression; var request = new RetrieveMetadataChangesRequest { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)crmServiceClient.Execute(request); foreach (EntityMetadata entityMetadata in response.EntityMetadata) { list.Add(entityMetadata.LogicalName); } return(list); }
/// <summary> /// Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata /// </summary> /// <param name="service"></param> /// <returns></returns> public string GetEntityLogicalName(IOrganizationService service) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, this.EntityTypeCode)); var propertyExpression = new MetadataPropertiesExpression { AllProperties = false }; propertyExpression.PropertyNames.Add("LogicalName"); var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = propertyExpression }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var response = service.Execute(retrieveMetadataChangesRequest); EntityMetadataCollection metadataCollection = (EntityMetadataCollection)response.Results["EntityMetadata"]; if (metadataCollection.Count == 1) { return(metadataCollection[0].LogicalName); } return(null); }
public static List <ComboBoxEntities> GetListEntities(IOrganizationService service) { MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression() { AllProperties = false }; EntityProperties.PropertyNames.AddRange(new string[] { "IsAuditEnabled", "DisplayName", "LogicalName", "ObjectTypeCode" }); MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And); EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false)); EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = EntityProperties, }; RetrieveMetadataChangesResponse initialRequest = GetMetadataChanges(service, entityQueryExpression, null, DeletedMetadataFilters.OptionSet); List <ComboBoxEntities> lsEntities = initialRequest.EntityMetadata.Where(f => f.DisplayName.UserLocalizedLabel != null).Select(x => new ComboBoxEntities() { DisplayName = x.DisplayName.UserLocalizedLabel.Label, IsAuditEnabled = x.IsAuditEnabled.Value, ObjectTypeCode = x.ObjectTypeCode.Value, LogicalName = x.LogicalName }).OrderBy(o => o.DisplayName).ToList(); return(lsEntities); }
private List <EntityMetadata> GetEntitiesWithAttributes() { MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression ( nameof(EntityMetadata.LogicalName) , nameof(EntityMetadata.DisplayName) , nameof(EntityMetadata.SchemaName) , nameof(EntityMetadata.Description) , nameof(EntityMetadata.DisplayCollectionName) , nameof(EntityMetadata.ObjectTypeCode) , nameof(EntityMetadata.IsIntersect) , nameof(EntityMetadata.IsCustomEntity) , nameof(EntityMetadata.Attributes) , nameof(EntityMetadata.OwnershipType) ) { AllProperties = false, }; FillAdditionalEntityProperties(_service, entityProperties); MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression ( nameof(AttributeMetadata.LogicalName) , nameof(AttributeMetadata.AttributeOf) , nameof(AttributeMetadata.EntityLogicalName) , nameof(AttributeMetadata.SchemaName) , nameof(AttributeMetadata.DisplayName) , nameof(EnumAttributeMetadata.OptionSet) ) { AllProperties = false }; EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Properties = attributeProperties }, }; RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request); return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList()); }
private RetrieveMetadataChangesResponse GetEntityMetadata() { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add( new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, LogicalName)); var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("DisplayName", "Attributes", "OneToManyRelationships" , "ManyToOneRelationships", "ManyToManyRelationships"); var attributeProperties = new MetadataPropertiesExpression { AllProperties = false }; attributeProperties.PropertyNames .AddRange("IsPrimaryId", "LogicalName", "SchemaName", "DisplayName", "AttributeOf", "IsValidForCreate", "IsValidForUpdate"); var relationshipProperties = new MetadataPropertiesExpression { AllProperties = false }; relationshipProperties.PropertyNames.AddRange("ReferencedAttribute", "ReferencedEntity", "ReferencingEntity", "ReferencingAttribute", "SchemaName", "Entity1LogicalName", "Entity2LogicalName", "IntersectEntityName"); var entityQueryExpression = new EntityQueryExpression { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression { Properties = attributeProperties }, RelationshipQuery = new RelationshipQueryExpression { Properties = relationshipProperties } }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest { Query = entityQueryExpression, }; return((RetrieveMetadataChangesResponse)Service.Execute(retrieveMetadataChangesRequest)); }
private EntityDynamicPluginStepsConfig RefineEntityDynamicPluginStepsConfig(EntityDynamicPluginStepsConfig config) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add( new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, config.EntityName)); var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("LogicalName", "Attributes"); var attributeFilter = new MetadataFilterExpression(LogicalOperator.And); attributeFilter.Conditions.Add( new MetadataConditionExpression("LogicalName", MetadataConditionOperator.In, config.Attributes)); var attributeProperties = new MetadataPropertiesExpression() { AllProperties = false }; attributeProperties.PropertyNames.AddRange("LogicalName"); var attributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }; var query = new EntityQueryExpression { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = attributeQuery, }; var request = new RetrieveMetadataChangesRequest { Query = query }; var pluginContext = this.PluginContext; var respones = (RetrieveMetadataChangesResponse)pluginContext.OrgCtx.Execute(request); var entityMetadata = respones.EntityMetadata.FirstOrDefault(); if (entityMetadata == null || !entityMetadata.Attributes.Any()) { return(null); } return(new EntityDynamicPluginStepsConfig() { EntityName = config.EntityName, Attributes = entityMetadata.Attributes.Select(r => r.LogicalName).ToArray() }); }
public void getEntityMetaData() { IOrganizationService service = CRMHelper.ConnectToMSCRM(); RetrieveVersionRequest versionReq = new RetrieveVersionRequest(); RetrieveVersionResponse resp = (RetrieveVersionResponse)service.Execute(versionReq); //assigns the version to a string string VersionNumber = resp.Version; bool isKeyCompatibleVersion = isCompatibleVersion(VersionNumber); MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And); EntityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, "contact")); MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression() { AllProperties = false }; EntityProperties.PropertyNames.AddRange(new string[] { "Attributes", "OneToManyRelationships", "LogicalName", "DisplayName", "PrimaryIdAttribute", "PrimaryNameAttribute" }); if (isKeyCompatibleVersion) { EntityProperties.PropertyNames.Add("Keys"); } MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression() { AllProperties = false }; AttributeProperties.PropertyNames.AddRange("AttributeType", "LogicalName", "DisplayName", "SchemaName", "AttributeType", "IsPrimaryName", "IsValidForUpdate", "OptionSet"); EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Criteria = EntityFilter, Properties = EntityProperties, AttributeQuery = new AttributeQueryExpression() { Properties = AttributeProperties }//, //RelationshipQuery = new RelationshipQueryExpression() { Properties = new MetadataPropertiesExpression() { AllProperties = true} } }; RetrieveMetadataChangesRequest req = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)service.Execute(req); }
public static void Run(CDSWebApiService svc) { var entityFilter = new MetadataFilterExpression { FilterOperator = LogicalOperator.And, Conditions = new List <MetadataConditionExpression> { new MetadataConditionExpression() { ConditionOperator = MetadataConditionOperator.Equals, PropertyName = "SchemaName", Value = new Microsoft.Cds.Metadata.Query.Object() { Type = "string", Value = "Account" } } } }; var entityProperties = new MetadataPropertiesExpression() { AllProperties = true }; var query = new EntityKeyQueryExpression() { Criteria = entityFilter, Properties = entityProperties }; var jsonQuery = JsonConvert.SerializeObject(query); var jsonDeletedMetadataFilters = JsonConvert.SerializeObject(DeletedMetadataFilters.Default); //BUG: 1563435 This returns an HTML Bad Request error //svc.Get($"RetrieveMetadataChanges(Query={jsonQuery},DeletedMetadataFilters={jsonDeletedMetadataFilters})"); //This returns all metadata without any filter var response = svc.Get("RetrieveMetadataChanges"); var results = (RetrieveMetadataChangesResponse)JsonConvert.DeserializeObject(response.ToString(), typeof(RetrieveMetadataChangesResponse)); Console.WriteLine($"ServerVersionStamp: {results.ServerVersionStamp}\n"); Console.WriteLine($"Entities returned: {results.EntityMetadata.Count}\n"); var accountMetadata = results.EntityMetadata.Find(x => x.SchemaName.Equals("Account")); accountMetadata.Attributes.Sort((x, y) => x.SchemaName.CompareTo(y.SchemaName)); accountMetadata.Attributes.ForEach(x => { Console.WriteLine($"{x.SchemaName} {x.AttributeTypeName.Value}"); }); Console.WriteLine(); }
private List <EntityMetadata> GetEntitiesWithAttributesFull(IEnumerable <string> entityList) { MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression ( nameof(EntityMetadata.LogicalName) , nameof(EntityMetadata.DisplayName) , nameof(EntityMetadata.SchemaName) , nameof(EntityMetadata.Description) , nameof(EntityMetadata.DisplayCollectionName) , nameof(EntityMetadata.OwnershipType) , nameof(EntityMetadata.ObjectTypeCode) , nameof(EntityMetadata.IsIntersect) , nameof(EntityMetadata.IsCustomEntity) , nameof(EntityMetadata.Attributes) ) { AllProperties = false, }; FillAdditionalEntityProperties(_service, entityProperties); EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Properties = new MetadataPropertiesExpression() { AllProperties = true, }, }, Criteria = new MetadataFilterExpression(LogicalOperator.And) { Conditions = { new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.In, entityList.ToArray()), }, }, }; RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request); return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList()); }
private EntityMetadata GetEntityMetadataWithAttributes(string entityName) { MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression(nameof(EntityMetadata.LogicalName), MetadataConditionOperator.Equals, entityName)); MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression ( nameof(EntityMetadata.LogicalName) , nameof(EntityMetadata.DisplayName) , nameof(EntityMetadata.SchemaName) , nameof(EntityMetadata.Description) , nameof(EntityMetadata.PrimaryIdAttribute) , nameof(EntityMetadata.PrimaryNameAttribute) , nameof(EntityMetadata.ObjectTypeCode) , nameof(EntityMetadata.IsIntersect) , nameof(EntityMetadata.IsCustomEntity) , nameof(EntityMetadata.Attributes) ) { AllProperties = false, }; FillAdditionalEntityProperties(_service, entityProperties); MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression() { AllProperties = true, }; EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Properties = attributeProperties }, Criteria = entityFilter, }; RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request); return(response.EntityMetadata.SingleOrDefault()); }
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)); }
private void ProcessHandleSecurityPrivileges(pavelkh_advancedmultiselectitemsetconfiguration itemSetConfig) { var handleSecurityPrivileges = itemSetConfig.pavelkh_HandleSecurityPrivileges ?? false; var pluginContext = this.PluginContext; var target = pluginContext.InputTarget; if (!handleSecurityPrivileges) { target.pavelkh_EntityHasOrganizationOwnership = null; target.pavelkh_ItemSetEntityHasOrganizationOwnership = null; return; } var props = new MetadataPropertiesExpression { AllProperties = false }; props.PropertyNames.AddRange("LogicalName", "OwnershipType"); var filter = new MetadataFilterExpression(); filter.Conditions.Add(new MetadataConditionExpression( "LogicalName", MetadataConditionOperator.In, new [] { itemSetConfig.pavelkh_EntityName, itemSetConfig.pavelkh_ItemSetEntityName })); var query = new EntityQueryExpression { Properties = props, Criteria = filter }; var request = new RetrieveMetadataChangesRequest { Query = query }; var service = pluginContext.ServiceAsSystemUser; var response = (RetrieveMetadataChangesResponse)service.Execute(request); var entityMetadata = response.EntityMetadata; target.pavelkh_EntityHasOrganizationOwnership = // ReSharper disable once PossibleNullReferenceException entityMetadata.FirstOrDefault( r => r.LogicalName.Equals(itemSetConfig.pavelkh_EntityName)).OwnershipType == OwnershipTypes.OrganizationOwned; target.pavelkh_ItemSetEntityHasOrganizationOwnership = // ReSharper disable once PossibleNullReferenceException entityMetadata.FirstOrDefault( r => r.LogicalName.Equals(itemSetConfig.pavelkh_ItemSetEntityName)).OwnershipType == OwnershipTypes.OrganizationOwned; }
private bool entityExists(string logicalName, string fieldName = null) { var entityName = logicalName; var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName)); var mpe = new MetadataPropertiesExpression() { AllProperties = true/*, * PropertyNames = { "DisplayName", "ObjectTypeCode", "PrimaryIdAttribute", "PrimaryNameAttribute" }*/ }; var entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = mpe }; var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var metadataResponse = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest); if (metadataResponse.EntityMetadata.Count == 1) { if (fieldName == null) { return(true); } foreach (object am in metadataResponse.EntityMetadata[0].Attributes) { AttributeMetadata a = (AttributeMetadata)am; if (a.LogicalName == fieldName) { return(true); } } } return(false); }
private List <EntityMetadata> GetEntitiesWithAttributesForAudit() { MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression ( nameof(EntityMetadata.LogicalName) , nameof(EntityMetadata.IsAuditEnabled) , nameof(EntityMetadata.Attributes) ) { AllProperties = false, }; FillAdditionalEntityProperties(_service, entityProperties); MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression ( nameof(AttributeMetadata.LogicalName) , nameof(AttributeMetadata.EntityLogicalName) , nameof(AttributeMetadata.IsAuditEnabled) , nameof(AttributeMetadata.AttributeOf) ) { AllProperties = false }; EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Properties = attributeProperties }, }; RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request); return(response.EntityMetadata.OrderBy(ent => ent.LogicalName).ToList()); }
public static AttributeMetadata GetAttributeMetadata( IOrganizationService service, string entityName, string attributeName, string[] attrPropNames) { var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName)); var entityProperties = new MetadataPropertiesExpression { AllProperties = false }; entityProperties.PropertyNames.AddRange("LogicalName", "Attributes"); var attributeFilter = new MetadataFilterExpression(LogicalOperator.And); attributeFilter.Conditions.Add( new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, attributeName)); var attributeProperties = new MetadataPropertiesExpression() { AllProperties = false }; attributeProperties.PropertyNames.AddRange(attrPropNames); var attributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }; var query = new EntityQueryExpression { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = attributeQuery, }; var request = new RetrieveMetadataChangesRequest { Query = query }; var response = (RetrieveMetadataChangesResponse)service.Execute(request); return(response.EntityMetadata.FirstOrDefault()?.Attributes.FirstOrDefault()); }
/// <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; }
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; }
public void Experiment_For_Selecting_Entity_Metadata() { var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"]; var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString }, new CrmClientCredentialsProvider()); var orgService = serviceProvider.GetOrganisationService(); using (orgService as IDisposable) { MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And); // entityFilter.Conditions.Add(new MetadataConditionExpression("OneToManyRelationships", MetadataConditionOperator.NotEquals, null)); var relationShipQuery = new RelationshipQueryExpression(); MetadataFilterExpression relationShipFilter = new MetadataFilterExpression(LogicalOperator.And); relationShipFilter.Conditions.Add(new MetadataConditionExpression("RelationshipType", MetadataConditionOperator.Equals, RelationshipType.OneToManyRelationship)); relationShipQuery.Criteria = relationShipFilter; var props = new MetadataPropertiesExpression(); props.AllProperties = false; props.PropertyNames.Add("OneToManyRelationships"); EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = props, RelationshipQuery = relationShipQuery }; RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression, ClientVersionStamp = null }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)orgService.Execute(retrieveMetadataChangesRequest); } }
//</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> /// 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!"); }
//<snippetStateModelTransitions.GetValidStatusOptions> /// <summary> /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity /// </summary> /// <param name="entityLogicalName">The logical name of the entity</param> /// <param name="currentStatusValue">The current status of the entity instance</param> /// <returns>A list of StatusOptions that represent the valid transitions</returns> public List<StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue) { List<StatusOption> validStatusOptions = new List<StatusOption>(); //Check entity Metadata //Retrieve just one entity definition MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); //Return the attributes and the EnforceStateTransitions property MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" }); //Retrieve only State or Status attributes MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or); attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status)); attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State)); //Retrieve only the OptionSet property of the attributes MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" }); //Set the query EntityQueryExpression query = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties } }; //Retrieve the metadata RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request); //Check the value of EnforceStateTransitions Boolean? EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions; //Capture the state and status attributes StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata(); StateAttributeMetadata stateAttribute = new StateAttributeMetadata(); foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes) { switch (attributeMetadata.AttributeType) { case AttributeTypeCode.Status: statusAttribute = (StatusAttributeMetadata)attributeMetadata; break; case AttributeTypeCode.State: stateAttribute = (StateAttributeMetadata)attributeMetadata; break; } } if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true) { //When EnforceStateTransitions is true use the TransitionData to filter the valid options foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options) { if (option.Value == currentStatusValue) { if (option.TransitionData != String.Empty) { XDocument transitionData = XDocument.Parse(option.TransitionData); IEnumerable<XElement> elements = (((XElement)transitionData.FirstNode)).Descendants(); foreach (XElement e in elements) { int statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value); String statusLabel = GetOptionSetLabel(statusAttribute, statusOptionValue); string stateLabel = String.Empty; int? stateValue = null; foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options) { if (statusOption.Value.Value == statusOptionValue) { stateValue = statusOption.State.Value; stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value); } } validStatusOptions.Add(new StatusOption() { StateLabel = stateLabel, StateValue = stateValue.Value, StatusLabel = statusLabel, StatusValue = option.Value.Value }); } } } } } else { ////When EnforceStateTransitions is false do not filter the available options foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options) { if (option.Value != currentStatusValue) { String statusLabel = ""; try { statusLabel = option.Label.UserLocalizedLabel.Label; } catch (Exception) { statusLabel = option.Label.LocalizedLabels[0].Label; }; String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value); validStatusOptions.Add(new StatusOption() { StateLabel = stateLabel, StateValue = option.State.Value, StatusLabel = statusLabel, StatusValue = option.Value.Value }); } } } return validStatusOptions; }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve status options for the Incident entity /// Use GetValidStatusOptions to get valid status transitions for each status option /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetStateModelTransitions.run> String entityLogicalName = "incident"; // Retrieve status options for the Incident entity //Retrieve just the incident entity and its attributes MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes" }); //Retrieve just the status attribute and the OptionSet property MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And); attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status)); MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" }); //Instantiate the entity query EntityQueryExpression query = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties } }; //Retrieve the metadata RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query }; RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request); StatusAttributeMetadata statusAttribute = (StatusAttributeMetadata)response.EntityMetadata[0].Attributes[0]; OptionMetadataCollection statusOptions = statusAttribute.OptionSet.Options; //Loop through each of the status options foreach (StatusOptionMetadata option in statusOptions) { String StatusOptionLabel = GetOptionSetLabel(statusAttribute, option.Value.Value); Console.WriteLine("[{0}] {1} records can transition to:", StatusOptionLabel, entityLogicalName); List<StatusOption> validStatusOptions = GetValidStatusOptions(entityLogicalName, option.Value.Value); //Loop through each valid transition for the option foreach (StatusOption opt in validStatusOptions) { Console.WriteLine("{0,-3}{1,-10}{2,-5}{3,-10}", opt.StateValue, opt.StateLabel, opt.StatusValue, opt.StatusLabel); } Console.WriteLine(""); } //</snippetStateModelTransitions.run> } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }