Thursday, August 21, 2014

Check Entity and Attribute Exist in CRM or not?

   private bool DoesAttributeExist(string entityName,string attributeName, IOrganizationService service)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName = entityName
            };
            RetrieveEntityResponse response
              = (RetrieveEntityResponse)service.Execute(request);

            return response.EntityMetadata.Attributes.FirstOrDefault(element => element.LogicalName == attributeName && element.AttributeType.Value == AttributeTypeCode.DateTime) != null;
        }

        private bool DoesEntityExist(string entityName, IOrganizationService _service)
        {
            RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();
            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            allEntitiesRequest.RetrieveAsIfPublished = false;
            //allEntitiesRequest.MetadataItems = MetadataItems.EntitiesOnly;

            // Execute the request
            RetrieveAllEntitiesResponse allEntitiesResponse = (RetrieveAllEntitiesResponse)_service.Execute(allEntitiesRequest);

            // Iterate through the retrieved entities
            foreach (EntityMetadata entity in allEntitiesResponse.EntityMetadata)
            {
                if (entity.LogicalName == entityName)
                    return true;
            }
            return false;
        }