/// <summary>
  /// Create a custom entity.
  /// Update the custom entity.
  /// Optionally delete the custom entity.
  /// </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();


     // Create the custom entity.
     //<snippetCreateUpdateEntityMetadata1>
     CreateEntityRequest createrequest = new CreateEntityRequest
     {

      //Define the entity
      Entity = new EntityMetadata
      {
       SchemaName = _customEntityName,
       DisplayName = new Label("Bank Account", 1033),
       DisplayCollectionName = new Label("Bank Accounts", 1033),
       Description = new Label("An entity to store information about customer bank accounts", 1033),
       OwnershipType = OwnershipTypes.UserOwned,
       IsActivity = false,

      },

      // Define the primary attribute for the entity
      PrimaryAttribute = new StringAttributeMetadata
      {
       SchemaName = "new_accountname",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       MaxLength = 100,
       FormatName = StringFormatName.Text,
       DisplayName = new Label("Account Name", 1033),
       Description = new Label("The primary attribute for the Bank Account entity.", 1033)
      }

     };
     _serviceProxy.Execute(createrequest);
     Console.WriteLine("The bank account entity has been created.");
     //</snippetCreateUpdateEntityMetadata1>


     // Add some attributes to the Bank Account entity
     //<snippetCreateUpdateEntityMetadata2>
     CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new StringAttributeMetadata
      {
       SchemaName = "new_bankname",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       MaxLength = 100,
       FormatName = StringFormatName.Text,
       DisplayName = new Label("Bank Name", 1033),
       Description = new Label("The name of the bank.", 1033)
      }
     };

     _serviceProxy.Execute(createBankNameAttributeRequest);
     //</snippetCreateUpdateEntityMetadata2>
     Console.WriteLine("An bank name attribute has been added to the bank account entity.");

     //<snippetCreateUpdateEntityMetadata3>
     CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new MoneyAttributeMetadata
      {
       SchemaName = "new_balance",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       PrecisionSource = 2,
       DisplayName = new Label("Balance", 1033),
       Description = new Label("Account Balance at the last known date", 1033),

      }
     };

     _serviceProxy.Execute(createBalanceAttributeRequest);
     //</snippetCreateUpdateEntityMetadata3>
     Console.WriteLine("An account balance attribute has been added to the bank account entity.");

     //<snippetCreateUpdateEntityMetadata4>
     CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new DateTimeAttributeMetadata
      {
       SchemaName = "new_checkeddate",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       Format = DateTimeFormat.DateOnly,
       DisplayName = new Label("Date", 1033),
       Description = new Label("The date the account balance was last confirmed", 1033)

      }
     };

     _serviceProxy.Execute(createCheckedDateRequest);
     Console.WriteLine("An date attribute has been added to the bank account entity.");
     //</snippetCreateUpdateEntityMetadata4>
     //Create a lookup attribute to link the bank account with a contact record.

     //<snippetCreateUpdateEntityMetadata5>
     CreateOneToManyRequest req = new CreateOneToManyRequest()
     {
      Lookup = new LookupAttributeMetadata()
      {
       Description = new Label("The owner of the bank account", 1033),
       DisplayName = new Label("Account Owner", 1033),
       LogicalName = "new_parent_contactid",
       SchemaName = "New_Parent_ContactId",
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired)
      },
      OneToManyRelationship = new OneToManyRelationshipMetadata()
      {
       AssociatedMenuConfiguration = new AssociatedMenuConfiguration()
       {
        Behavior = AssociatedMenuBehavior.UseCollectionName,
        Group = AssociatedMenuGroup.Details,
        Label = new Label("Bank Accounts", 1033),
        Order = 10000
       },
       CascadeConfiguration = new CascadeConfiguration()
       {
        Assign = CascadeType.Cascade,
        Delete = CascadeType.Cascade,
        Merge = CascadeType.Cascade,
        Reparent = CascadeType.Cascade,
        Share = CascadeType.Cascade,
        Unshare = CascadeType.Cascade
       },
       ReferencedEntity = Contact.EntityLogicalName,
       ReferencedAttribute = "contactid",
       ReferencingEntity = _customEntityName,
       SchemaName = "new_contact_new_bankaccount"
      }
     };
     _serviceProxy.Execute(req);
     //</snippetCreateUpdateEntityMetadata5>
     Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity.");

     //<snippetCreateUpdateEntityMetadata11>
     //Create an Image attribute for the custom entity
     // Only one Image attribute can be added to an entity that doesn't already have one.
     CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
     {
      EntityName = _customEntityName,
      Attribute = new ImageAttributeMetadata
      {
       SchemaName = "EntityImage", //The name is always EntityImage
       RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
       DisplayName = new Label("Image", 1033),
       Description = new Label("An image to represent the bank account.", 1033)

      }
     };

     _serviceProxy.Execute(createEntityImageRequest);
     Console.WriteLine("An image attribute has been added to the bank account entity.");
     //</snippetCreateUpdateEntityMetadata11>

     //<snippetCreateUpdateEntityMetadata9>

     //<snippetCreateUpdateEntityMetadata.RetrieveEntity>
     RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
     {
      EntityFilters = EntityFilters.Entity,
      LogicalName = _customEntityName
     };
     RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest);
     //</snippetCreateUpdateEntityMetadata.RetrieveEntity>
     //<snippetCreateUpdateEntityMetadata8>
     EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata;

     // Disable Mail merge
     BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false);
     // Enable Notes
     UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest
     {
      Entity = BankAccountEntity,
      HasNotes = true
     };



     _serviceProxy.Execute(updateBankAccountRequest);
     //</snippetCreateUpdateEntityMetadata8>
     //</snippetCreateUpdateEntityMetadata9>

     Console.WriteLine("The bank account entity has been updated");


     //Update the entity form so the new fields are visible
     UpdateEntityForm(_customEntityName);

     // Customizations must be published after an entity is updated.
     //<snippetCreateUpdateEntityMetadata6>
     PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
     _serviceProxy.Execute(publishRequest);
     //</snippetCreateUpdateEntityMetadata6>
     Console.WriteLine("Customizations were published.");

     //Provides option to view the entity in the default solution
     ShowEntityInBrowser(promptForDelete, BankAccountEntity);
     //Provides option to view the entity form with the fields added
     ShowEntityFormInBrowser(promptForDelete, BankAccountEntity);

     DeleteRequiredRecords(promptForDelete);
    }
   }

   // 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;
   }
  }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var rmds = new List<OneToManyRelationshipMetadata>();

            foreach (var row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var rmd = rmds.FirstOrDefault(r => r.MetadataId == new Guid(row.Cells[1].Value.ToString()));
                if (rmd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == row.Cells[0].Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = row.Cells[0].Value.ToString(),
                            EntityFilters = EntityFilters.Relationships
                        };

                        var response = ((RetrieveEntityResponse) service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    rmd =
                        currentEntity.OneToManyRelationships.FirstOrDefault(
                            r => r.SchemaName == row.Cells[2].Value.ToString());
                    if (rmd == null)
                    {
                        rmd =
                            currentEntity.ManyToOneRelationships.FirstOrDefault(
                                r => r.SchemaName == row.Cells[2].Value.ToString());
                    }

                    rmds.Add(rmd);
                }

                int columnIndex = 4;

                rmd.AssociatedMenuConfiguration.Label = new Label();

                while (row.Cells[columnIndex].Value != null)
                {
                    rmd.AssociatedMenuConfiguration.Label.LocalizedLabels.Add(
                        new LocalizedLabel(row.Cells[columnIndex].Value.ToString(),
                            int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                    columnIndex++;
                }
            }

            foreach (var rmd in rmds)
            {
                var request = new UpdateRelationshipRequest
                {
                    Relationship = rmd,
                };
                service.Execute(request);
            }
        }
Beispiel #3
0
        public Guid GetEntityId(IPluginExecutionContext context, IMetadataService metaData)
        {
            // Get the metadata about the current entity.
            var req = new RetrieveEntityRequest { LogicalName = context.PrimaryEntityName };
            var res = (RetrieveEntityResponse)metaData.Execute(req);

            return this.GetKeyValue(context, res.EntityMetadata.PrimaryKey);
        }
        public XrmEntityDefinition EntityDefinitionGet(string entityName)
        {
            var request = new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Attributes };

            var response = (RetrieveEntityResponse)_organizationService.Execute(request);

            var metaData = response.EntityMetadata;

            var entityDefinition = new XrmEntityDefinition(metaData);

            return entityDefinition;
        }
Beispiel #5
0
        private void LoadData(string entity)
        {
            var logicalName = entity.ToLower();

            Lists = new List <CrmAttribute>();
            var request = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Attributes,
                LogicalName   = logicalName
            };
            var response = (RetrieveEntityResponse)_crmService.Execute(request);

            ObjectTypeCode = response.EntityMetadata.ObjectTypeCode.Value;
            HasImage       = !string.IsNullOrEmpty(response.EntityMetadata.PrimaryImageAttribute);
            var requestRelationships = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Relationships,
                LogicalName   = logicalName
            };
            var responseRelationships = (RetrieveEntityResponse)_crmService.Execute(requestRelationships);

            var lists = new List <CrmAttribute>();

            foreach (var attribute in response.EntityMetadata.Attributes)
            {
                var crmAttribute = new CrmAttribute(attribute, logicalName);
                if (crmAttribute.FieldType == AttributeTypeCode.Lookup ||
                    crmAttribute.FieldType == AttributeTypeCode.Customer ||
                    crmAttribute.FieldType == AttributeTypeCode.Owner)
                {
                    crmAttribute.LogicalCollectionName  = GetLogicalCollectionName(crmAttribute);
                    crmAttribute.NavigationPropertyName =
                        GetNavigationPropertyName(crmAttribute, responseRelationships);
                }
                else
                {
                    crmAttribute.LogicalCollectionName = string.Empty;
                }

                lists.Add(crmAttribute);
            }

            lists = lists.OrderBy(row => row.Name).ToList();
            Lists = lists;
        }
        protected EntityMetadata GetEntityMetadata(OrganizationServiceContext serviceContext)
        {
            var entityRequest = new RetrieveEntityRequest
            {
                RetrieveAsIfPublished = false,
                LogicalName           = Metadata.ViewTargetEntityType,
                EntityFilters         = EntityFilters.All
            };

            var entityResponse = serviceContext.Execute(entityRequest) as RetrieveEntityResponse;

            if (entityResponse == null)
            {
                throw new ApplicationException(string.Format("RetrieveEntityRequest failed for view target entity type {0}", Metadata.ViewTargetEntityType));
            }

            return(entityResponse.EntityMetadata);
        }
Beispiel #7
0
        public IEnumerable <AttributeDisplayName> GetAttributeDisplayName(string entitySchemaName)
        {
            var service = organizationServiceProxy;
            var req     = new RetrieveEntityRequest
            {
                RetrieveAsIfPublished = true,
                LogicalName           = entitySchemaName,
                EntityFilters         = EntityFilters.Attributes
            };

            var resp = (RetrieveEntityResponse)service.Execute(req);

            return(resp.EntityMetadata.Attributes.Select(a => new AttributeDisplayName
            {
                DisplayName = a.DisplayName.LocalizedLabels.Count > 0 ? a.DisplayName.LocalizedLabels[0].Label : a.LogicalName,
                LogicalName = a.LogicalName
            }));
        }
Beispiel #8
0
        internal static string GetPrimaryAttribute(this IOrganizationService service, string entityName)
        {
            var info = Info(entityName);

            if (!String.IsNullOrWhiteSpace(info?.PrimaryNameAttribute))
            {
                return(info.PrimaryNameAttribute);
            }

            var request = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = entityName
            };
            var response = service.Execute <RetrieveEntityResponse>(request);

            return(response.EntityMetadata.PrimaryNameAttribute.ToLowerInvariant());
        }
Beispiel #9
0
        public static bool CheckEntityExists(IOrganizationService service, string logicalName)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = logicalName
            };

            try
            {
                RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 public Sobiens.Connectors.Entities.FieldCollection GetFields(ISiteSetting siteSetting, string entityName)
 {
     try
     {
         IOrganizationService  organizationService = GetClientContext(siteSetting);
         RetrieveEntityRequest request             = new RetrieveEntityRequest {
             EntityFilters = EntityFilters.Attributes, LogicalName = entityName
         };
         RetrieveEntityResponse response = (RetrieveEntityResponse)organizationService.Execute(request);
         return(ParseFields(response.EntityMetadata.Attributes));
     }
     catch (Exception ex)
     {
         string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
         //LogManager.LogAndShowException(methodName, ex);
         throw ex;
     }
 }
        private string GetLogicalCollectionName(CrmAttribute crmAttribute)
        {
            var value    = string.Empty;
            var entities = crmAttribute.EntityReferenceLogicalName.Split(";".ToCharArray());

            foreach (var entity in entities)
            {
                var request = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.Attributes,
                    LogicalName   = entity
                };
                var response = (RetrieveEntityResponse)CrmService.Execute(request);
                value += response.EntityMetadata.LogicalCollectionName + ";";
            }

            return(value.TrimEnd(";".ToCharArray()));
        }
Beispiel #12
0
        public void CheckAndUpdateEntity(string entity, OrganizationWebProxyClient proxy, Logger logger)
        {
            var checkRequest = new RetrieveEntityRequest()
            {
                LogicalName   = entity,
                EntityFilters = EntityFilters.Entity
            };


            RetrieveEntityResponse checkResponse = (RetrieveEntityResponse)proxy.Execute(checkRequest);

            // Check if entity exists
            if (checkResponse == null || checkResponse.EntityMetadata == null)
            {
                logger.LogCustomProperty("PSAEntity", $"The {entity} entity cannot be retrieved from the PSA instance.");
                throw new Exception($"The {entity} entity cannot be retrieved from the PSA instance.");
            }

            // Raise and error if we can't enable it, but we need to
            if (!checkResponse.EntityMetadata.CanChangeTrackingBeEnabled.Value)
            {
                logger.LogCustomProperty("PSAEntity", $"The {entity} entity cannot be enabled for change tracking.");
                throw new Exception($"The {entity} entity cannot be enabled for change tracking.");
            }

            // Nothing to do further, try changing
            if (!(bool)checkResponse.EntityMetadata.ChangeTrackingEnabled)
            {
                UpdateEntityRequest updateRequest = new UpdateEntityRequest()
                {
                    Entity = checkResponse.EntityMetadata
                };
                updateRequest.Entity.ChangeTrackingEnabled = true;

                UpdateEntityResponse updateResponse = (UpdateEntityResponse)proxy.Execute(updateRequest);

                // Check the entity has actually been change tracking enabled
                RetrieveEntityResponse verifyChange = (RetrieveEntityResponse)proxy.Execute(checkRequest);
                if (!(bool)verifyChange.EntityMetadata.ChangeTrackingEnabled)
                {
                    logger.LogCustomProperty("PSAEntity", $"Warning: Change tracking for {entity} has been enabled, but is not yet active.");
                }
            }
        }
        /// <summary>
        /// 验证创建Entity的LogicalName和Primary Field的LogicalName
        /// </summary>
        /// <param name="entityName">Entity的LogicalName</param>
        /// <param name="primaryAttrName">Primary Field的LogicalName</param>
        private bool CheckCreateEntity(string entityName, string primaryAttrName)
        {
            // 验证Entity的LogicalName是否以new_开头
            if (!entityName.StartsWith("new_"))
            {
                throw new ArgumentException("The customize entity name should start with \"new_\".");
            }
            // 验证Entity的LogicalName是否都是小写字符
            if (entityName.ToLower() != entityName)
            {
                throw new ArgumentException("The customize entity name should be lower characters.");
            }
            // 验证Entity的LogicalName是否已存在
            try
            {
                var request = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.Entity,
                    LogicalName   = entityName
                };
                Service.Execute(request);
                throw new ArgumentException(string.Format("The entity {0} is already exists.", entityName));
            }
            catch // 出现异常时表示该Entity的LogicaName是不存在的,可以创建
            {
            }

            // 验证Primary Field的LogicalName是否以new_开头
            if (!primaryAttrName.StartsWith("new_"))
            {
                throw new ArgumentException("The primary field name should start with \"new_\".");
            }
            // 验证Primary Field的LogicalName是否和Primary Key的LogicalName重复
            if (string.Concat(entityName, "id") == primaryAttrName)
            {
                throw new ArgumentException("The entity primary field name should not equal with primary key name.");
            }
            // 验证Primary Field的LogicalName是否都是小写字符
            if (primaryAttrName.ToLower() != primaryAttrName)
            {
                throw new ArgumentException("The primary field name should be lower characters.");
            }
            return(true);
        }
        private static string CreateEntityName(IOrganizationService svc, string entityName, string fieldName)
        {
            ThrowIf.Argument.IsNull(svc, "svc");
            ThrowIf.Argument.IsNullOrEmpty(entityName, "entityName");
            ThrowIf.Argument.IsNullOrEmpty(fieldName, "fieldName");

            var entityReq = new RetrieveEntityRequest()
            {
                EntityFilters = EntityFilters.Entity | EntityFilters.Attributes,
                LogicalName   = entityName
            };

            RetrieveEntityResponse entityResp = null;

            try
            {
                entityResp = svc.Execute(entityReq) as RetrieveEntityResponse;
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("Entity '{0}' not found - it either doesn't exist or you do not have permissions to view it.".FormatWith(entityName), ex);
            }

            var entityDisplayName = entityResp.EntityMetadata.DisplayName.UserLocalizedLabel.Label;

            var fieldMeta = entityResp.EntityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == fieldName);

            if (fieldMeta == null)
            {
                var comparer   = new SimilarityComparer(fieldName);
                var topSimilar = entityResp.EntityMetadata.Attributes
                                 .Where(a => a.AttributeOf == null && comparer.Distance(a.LogicalName) <= 3)
                                 .OrderByDescending(a => a.LogicalName, comparer)
                                 .Take(5);

                var suggestions = string.Join(", ", topSimilar.Select(a => a.LogicalName));
                throw new InvalidPluginExecutionException("Entity '{0}' does not contain field '{1}'. Did you mean one of these? {2}".FormatWith(entityName, fieldName, suggestions));
            }

            var fieldDisplayName = fieldMeta.DisplayName.UserLocalizedLabel.Label;

            return("{0} - {1}".FormatWith(entityDisplayName, fieldDisplayName));
        }
Beispiel #15
0
        public void When_calling_retrieve_entity_without_a_fake_entity_metadata_exception_is_thrown()
        {
            var ctx = new XrmFakedContext()
            {
                ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account))
            };

            var service  = ctx.GetOrganizationService();
            var executor = new RetrieveEntityRequestExecutor();

            ctx.AddFakeMessageExecutor <RetrieveEntityRequest>(executor);

            var request = new RetrieveEntityRequest()
            {
                LogicalName = Account.EntityLogicalName
            };

            Assert.Throws <Exception>(() => service.Execute(request));
        }
Beispiel #16
0
        public static EntityMetadata RetrieveEntityMetadata(MetadataService metadataService, string entityName)
        {
            string key = GetEntityKey(
                metadataService.Url,
                metadataService.CrmAuthenticationTokenValue.OrganizationName,
                entityName);

            EntityMetadata entityMetadata = null;

            lock (_entityCacheLock)
            {
                if (!_entityCache.TryGetValue(key, out entityMetadata))
                {
                    RetrieveEntityRequest entityRequest = new RetrieveEntityRequest()
                    {
                        LogicalName           = entityName,
                        EntityItems           = EntityItems.IncludeAttributes,
                        RetrieveAsIfPublished = false
                    };

                    try
                    {
                        RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)metadataService.Execute(entityRequest);
                        entityMetadata = entityResponse.EntityMetadata;
                    }
                    catch (SoapException ex)
                    {
                        // rethrow all exceptions except for a missing entity
                        XmlNode node;
                        if (ex.Detail == null ||
                            (node = ex.Detail.SelectSingleNode("//code")) == null ||
                            node.InnerText != "0x80040217")
                        {
                            throw;
                        }
                    }

                    _entityCache.Add(key, entityMetadata);
                }
            }

            return(entityMetadata);
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracing = (ITracingService) serviceProvider.GetService(typeof (ITracingService));
            var context = (IPluginExecutionContext) serviceProvider.GetService(typeof (IPluginExecutionContext));
            var factory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);

            var request = new RetrieveEntityRequest
            {
                LogicalName = "Contact",
                EntityFilters = EntityFilters.All,
                RetrieveAsIfPublished = false
            };

            var response = (RetrieveEntityResponse)service.Execute(request);

            var target = ((Entity) context.InputParameters["Target"]);
            target["response"] = response.ResponseName;
        }
Beispiel #18
0
        public static string[] GetEmails(IOrganizationService service, string entityName)
        {
            List <string> temp;

            if (_attEmails.TryGetValue(entityName, out temp))
            {
                if (temp != null)
                {
                    return(temp.ToArray());
                }
            }
            else
            {
                lock (_syncRoot)
                {
                    temp = new List <string>();
                    RetrieveEntityRequest  metaDataRequest  = new RetrieveEntityRequest();
                    RetrieveEntityResponse metaDataResponse = new RetrieveEntityResponse();
                    metaDataRequest.EntityFilters = EntityFilters.Attributes;
                    metaDataRequest.LogicalName   = entityName;
                    metaDataResponse = (RetrieveEntityResponse)service.Execute(metaDataRequest);
                    var entityData = metaDataResponse.EntityMetadata;
                    // entityData.Attributes.Where(aa=>aa.is)
                    foreach (var attr in entityData.Attributes)
                    {
                        if (attr is StringAttributeMetadata)
                        {
                            StringAttributeMetadata isemail = (StringAttributeMetadata)attr;
                            if (isemail.Format == StringFormat.Email)
                            {
                                temp.Add(isemail.SchemaName.ToLower());
                            }
                        }
                    }
                    _attEmails.TryAdd(entityName, temp);
                }
            }
            if (temp == null | !temp.Any())
            {
                return(null);
            }
            return(temp.ToArray());
        }
Beispiel #19
0
        public IEnumerable <AttributeMetadata> GetDynamicsEntityProperties(string entityName)
        {
            try
            {
                RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.Attributes,
                    LogicalName   = entityName
                };

                RetrieveEntityResponse entityMetadata = (RetrieveEntityResponse)organizationProxy.Execute(retrieveEntityRequest);
                return(entityMetadata.EntityMetadata.Attributes);
            }
            catch (Exception exception)
            {
                Logger.LogError("GetDynamicsEntityProperties: " + exception.Message + exception.InnerException ?? "; Inner " + exception.InnerException.Message);
                return(null);
            }
        }
Beispiel #20
0
        public List <Privilege> RetrievePrivs(string entityName)
        {
            var request = new RetrieveEntityRequest {
                LogicalName = entityName, EntityFilters = EntityFilters.Privileges
            };
            var response = (RetrieveEntityResponse)service.Execute(request);

            var privList = Helper.NewPrivList();

            foreach (SecurityPrivilegeMetadata spmd in response.EntityMetadata.Privileges)
            {
                var privilege = privList.FirstOrDefault(priv => (priv.PrivilegeType + entityName).ToLower() == spmd.Name.ToLower());
                if (privilege != null)
                {
                    privilege.PrivilegeId = spmd.PrivilegeId;
                }
            }
            return(privList);
        }
Beispiel #21
0
        public EntityMetadata GetEntityMetadata(string entityName)
        {
            EntityMetadata entityMetadatas;

            IOrganizationService orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);

            RetrieveEntityRequest request = new RetrieveEntityRequest();

            request.EntityFilters         = EntityFilters.Entity;
            request.LogicalName           = entityName;
            request.RetrieveAsIfPublished = true;
            var response = (RetrieveEntityResponse)orgService.Execute(request);


            entityMetadatas = response.EntityMetadata;


            return(entityMetadatas);
        }
Beispiel #22
0
        /// <summary>
        /// Get Label for Optionset Value
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="attributeName"></param>
        /// <param name="optionSetValue"></param>
        /// <returns></returns>
        public string GetOptionsetText(string entityName, string attributeName, int optionSetValue)
        {
            var optionsetLabel = string.Empty;

            var retrieveDetails = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName   = entityName
            };

            var retrieveEntityResponseObj = (RetrieveEntityResponse)Svc.Execute(retrieveDetails);

            if (retrieveEntityResponseObj.EntityMetadata == null)
            {
                return(optionsetLabel);
            }

            var metadata = retrieveEntityResponseObj.EntityMetadata;

            if (metadata.Attributes == null)
            {
                return(optionsetLabel);
            }

            var picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;

            if (picklistMetadata?.OptionSet == null)
            {
                return(optionsetLabel);
            }

            var options = picklistMetadata.OptionSet;
            IList <OptionMetadata> optionsList = (from o in options.Options where o.Value != null && o.Value.Value == optionSetValue select o).ToList();

            var label = (optionsList.First()).Label;

            if (label?.UserLocalizedLabel != null)
            {
                optionsetLabel = label.UserLocalizedLabel.Label;
            }

            return(optionsetLabel);
        }
Beispiel #23
0
 public virtual EntityMetadata GetEntityMetadata(string entity)
 {
     lock (LockObject)
     {
         if (!EntityMetadata.Any(em => em.LogicalName == entity))
         {
             _controller.LogLiteral("Retrieving " + entity + " entity metadata");
             var request = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.Default,
                 LogicalName   = entity
             };
             var response = (RetrieveEntityResponse)Execute(request);
             _controller.LogLiteral("Retrieved " + entity + " entity metadata");
             EntityMetadata.Add(response.EntityMetadata);
         }
     }
     return(EntityMetadata.First(em => em.LogicalName == entity));
 }
        private RetrieveEntityResponse ExecuteInternal(RetrieveEntityRequest request)
        {
            var name = new LocalizedLabel(request.LogicalName, Info.LanguageCode);

            return(new RetrieveEntityResponse
            {
                Results =
                {
                    ["EntityMetadata"] = new EntityMetadata
                        {
                        DisplayCollectionName = new Label(name,
                                                          new[]
                        {
                        name
                        }),
                        }
                }
            });
        }
Beispiel #25
0
 private RetrieveEntityResponse GetEntityInformationFromCRMClient(IOrganizationService serviceProxy, string crmEntityName)
 {
     try
     {
         log.Info("Fetching CRM entity from server");
         RetrieveEntityRequest entitiesRequest = new RetrieveEntityRequest()
         {
             EntityFilters = EntityFilters.Attributes,
             LogicalName   = crmEntityName,
         };
         RetrieveEntityResponse entity = (RetrieveEntityResponse)serviceProxy.Execute(entitiesRequest);
         return(entity);
     }
     catch (Exception ex)
     {
         log.Error(ex, string.Format("Error occur while fetch CRM entity of name {0} from server", crmEntityName));
         throw ex;
     }
 }
Beispiel #26
0
        //public static string GetConfigurationValue(IOrganizationService adminService, string name)
        //{
        //    string query = string.Format(@"<fetch>
        //                         <entity name='defra_configuration'>
        //                             <attribute name='defra_value' />
        //                             <filter>
        //                                <condition attribute='defra_name' operator= 'eq' value='{0}' />
        //                            </filter>
        //                         </entity>
        //                    </fetch>", name);

        //    Entity configRecord = Query.QueryCRMForSingleEntity(adminService, query);

        //    if (configRecord == null || !configRecord.Attributes.Contains("defra_value"))
        //    {
        //        throw new InvalidPluginExecutionException(string.Format("Configuration value {0} not found or has not been set", name));
        //    }
        //    else
        //    {
        //        return (string)configRecord["defra_value"];
        //    }
        //}

        //public static Entity GetConfigurationEntity(IOrganizationService adminService, string name)
        //{
        //    string query = string.Format(@"<fetch>
        //                         <entity name='defra_configuration'>
        //                             <attribute name='defra_addressbasefacadeurl' />
        //                             <attribute name='defra_sharepointlogicappurl' />
        //                             <attribute name='defra_sharepointpermitlist' />
        //                             <attribute name='defra_sharepointfoldercontenttype' />
        //                             <filter>
        //                                <condition attribute='defra_name' operator= 'eq' value='{0}' />
        //                            </filter>
        //                         </entity>
        //                    </fetch>", name);

        //    Entity configRecord = Query.QueryCRMForSingleEntity(adminService, query);

        //    if (configRecord == null || configRecord.Attributes.Count == 0)
        //    {
        //        throw new InvalidPluginExecutionException(string.Format("Configuration record {0} not found or has not been set", name));
        //    }
        //    else
        //    {
        //        return configRecord;
        //    }
        //}

        public static string GetCRMOptionsetText(IOrganizationService service, string entityName, string attributeName, int optionSetValue)
        {
            var retrieveDetails = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName   = entityName
            };

            var retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
            var metadata         = retrieveEntityResponseObj.EntityMetadata;
            var picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => string.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;
            var options          = picklistMetadata.OptionSet;

            var optionsetLabel = (from o in options.Options
                                  where o.Value.Value == optionSetValue
                                  select o).First().Label.UserLocalizedLabel.Label;

            return(optionsetLabel);
        }
        public static EntityMetadata GetEntityMetadata(IOrganizationService service, string entityName)
        {
            var retrieveEntityRequest = new RetrieveEntityRequest()
            {
                EntityFilters         = EntityFilters.All,
                LogicalName           = entityName,
                RetrieveAsIfPublished = false
            };

            try
            {
                var retrieveEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
                return(retrieveEntityResponse.EntityMetadata);
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new Exception("Error on loading metadata: " + ex.Detail.Message);
            }
        }
Beispiel #28
0
        private void GetEntityMetadataFromServer(string entityName, List <EntityMetadata> meta, IOrganizationService service)
        {
            if (meta.Any(metadata => string.Equals(metadata.LogicalName, entityName)))
            {
                PopulateAttributeList();
                return;
            }

            WorkAsync(new WorkAsyncInfo
            {
                Message = $"Retrieving {entityName} metadata ...",
                Work    = (w, e) =>
                {
                    var retrieveEntityRequest = new RetrieveEntityRequest
                    {
                        LogicalName           = entityName,
                        EntityFilters         = EntityFilters.All,
                        RetrieveAsIfPublished = false
                    };

                    if (service == null)
                    {
                        throw new Exception("No Service set!");
                    }

                    var response = service.Execute(retrieveEntityRequest) as RetrieveEntityResponse;

                    if (response == null)
                    {
                        throw new Exception("Failed to retrieve entity!");
                    }
                    meta.Add(response.EntityMetadata);
                },
                PostWorkCallBack = e =>
                {
                    PopulateAttributeList();
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
        private static EntityMetadata LoadEntityMetadata(string entityLogicalName)
        {
            string         cacheKey = entityLogicalName;
            EntityMetadata metaData = (EntityMetadata)_entityMetaData[cacheKey];

            if (metaData == null)
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.EntityFilters         = EntityFilters.Entity;
                request.LogicalName           = entityLogicalName;
                request.RetrieveAsIfPublished = true;
                request.MetadataId            = new Guid("00000000-0000-0000-0000-000000000000");

                RetrieveEntityResponse response = (RetrieveEntityResponse)OrganizationServiceProxy.Execute(request);
                metaData = response.EntityMetadata;
                _entityMetaData[cacheKey] = metaData;
            }
            return(metaData);
        }
Beispiel #30
0
        /// <summary>
        /// retrieves the entity type code for the specified entity name
        /// </summary>
        /// <param name="entityName">name of the entity</param>
        /// <param name="service">target organization service</param>
        /// <returns>entity type code</returns>
        private static int GetTypeCode(string entityName, IOrganizationService service)
        {
            // save as static collection to avoid round trips
            if (_objectTypeCodes == null)
            {
                _objectTypeCodes = new Dictionary <string, int>();
            }

            if (!_objectTypeCodes.ContainsKey(entityName))
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.LogicalName = entityName;

                // Retrieve the MetaData, OTC for the entity name
                RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
                _objectTypeCodes.Add(entityName, response.EntityMetadata.ObjectTypeCode.Value);
            }
            return(_objectTypeCodes[entityName]);
        }
        protected override EntityMetadata CreateCachedItem(string cacheKey)
        {
            if (cacheKey == null)
            {
                throw new ArgumentNullException(nameof(cacheKey));
            }

            string entityName = cacheKey.Substring(cacheId.Length);

            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName   = entityName
            };

            RetrieveEntityResponse response = (RetrieveEntityResponse)orgService.Execute(request);

            return(response.EntityMetadata);
        }
Beispiel #32
0
        public void When_calling_retrieve_entity_with_a_fake_attribute_definition_it_is_returned()
        {
            var ctx = new XrmFakedContext()
            {
                ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account))
            };

            var service = ctx.GetOrganizationService();

            var executor = new RetrieveEntityRequestExecutor();

            executor.AddFakeEntityMetadata(Account.EntityLogicalName, new EntityMetadata()
            {
                IsCustomizable = new BooleanManagedProperty(true)
            });

            var stringMetadata = new StringAttributeMetadata()
            {
                MaxLength = 200
            };

            stringMetadata.GetType().GetProperty("IsValidForCreate").SetValue(stringMetadata, new Nullable <bool>(true), null);
            executor.AddFakeAttributeMetadata(Account.EntityLogicalName, "name", stringMetadata);

            ctx.AddFakeMessageExecutor <RetrieveEntityRequest>(executor);

            var request = new RetrieveEntityRequest()
            {
                EntityFilters = EntityFilters.Attributes,
                LogicalName   = Account.EntityLogicalName
            };

            var response = service.Execute(request);

            Assert.IsType <RetrieveEntityResponse>(response);

            var nameAttribute = (response as RetrieveEntityResponse).EntityMetadata.Attributes
                                .Where(a => a.SchemaName.Equals("name"))
                                .FirstOrDefault();

            Assert.True(nameAttribute.IsValidForCreate.Value);
        }
Beispiel #33
0
 public List <AttributeMetadata> GetEntityFieldMetadata(string entity)
 {
     lock (LockObject)
     {
         if (!EntityFieldMetadata.ContainsKey(entity))
         {
             _controller.LogLiteral("Retrieving " + entity + " field metadata");
             // Create the request
             var request = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.Attributes,
                 LogicalName   = entity
             };
             var response = (RetrieveEntityResponse)Execute(request);
             _controller.LogLiteral("Retrieved " + entity + " field metadata");
             EntityFieldMetadata.Add(entity, new List <AttributeMetadata>(response.EntityMetadata.Attributes));
         }
     }
     return(EntityFieldMetadata[entity]);
 }
        /// <summary>
        /// Gets specified entity metadata (include attributes)
        /// </summary>
        /// <param name="service">CRM organization service</param>
        /// <param name="logicalName">Logical name of the entity</param>
        /// <returns>Entity metadata</returns>
        public static EntityMetadata RetrieveEntityMetadata(IOrganizationService service, string logicalName)
        {
            try
            {
                var request = new RetrieveEntityRequest
                {
                    LogicalName           = logicalName,
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = true
                };

                var response = (RetrieveEntityResponse)service.Execute(request);

                return(response.EntityMetadata);
            }
            catch (Exception error)
            {
                throw new Exception("RetrieveAuditHistory Error while retrieving entity metadata: " + error.StackTrace);
            }
        }
Beispiel #35
0
        public static EntityMetadata RetrieveEntity(string logicalName, IOrganizationService oService)
        {
            try
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest
                {
                    LogicalName   = logicalName,
                    EntityFilters = EntityFilters.Attributes | EntityFilters.Relationships
                };

                RetrieveEntityResponse response = (RetrieveEntityResponse)oService.Execute(request);

                return(response.EntityMetadata);
            }
            catch (Exception error)
            {
                string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false);
                throw new Exception("Error while retrieving entity: " + errorMessage);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Gets specified entity metadata (include attributes)
        /// </summary>
        /// <param name="logicalName">Logical name of the entity</param>
        /// <param name="oService">Crm organization service</param>
        /// <returns>Entity metadata</returns>
        public static EntityMetadata RetrieveEntity(string logicalName, IOrganizationService oService)
        {
            try
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest
                                                    {
                                                        LogicalName = logicalName,
                                                        EntityFilters = EntityFilters.Attributes,
                                                        RetrieveAsIfPublished = true
                                                    };

                RetrieveEntityResponse response = (RetrieveEntityResponse)oService.Execute(request);

                return response.EntityMetadata;
            }
            catch (Exception error)
            {
                string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false);
                throw new Exception("Error while retrieving entity: " + errorMessage);
            }
        }
        /// <summary>
        /// Gets the option set text.
        /// </summary>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <param name="optionSetValue">The option set value.</param>
        /// <returns>Result.</returns>
        public Result GetOptionSetText(string entityName, string attributeName, int? optionSetValue)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

                string AttributeName = attributeName;
                string EntityLogicalName = entityName;
                RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName = EntityLogicalName
                };
                RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)xrmService.Execute(retrieveDetails);
                Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
                Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
            (attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
                Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
                IList<OptionMetadata> OptionsList = (from o in options.Options
                                                     where o.Value.Value == optionSetValue
                                                     select o).ToList();
                string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
                return new Result(false, string.Empty, optionsetLabel, logSystem);
            }
            catch (Exception ex)
            {
                return new Result(true,
                    MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                    null, logSystem);
            }
        }
        /// <summary>
        /// Gets the option sets.
        /// </summary>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <returns>Result.</returns>
        public Result GetOptionSets(string entityName, string attributeName)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

                string AttributeName = attributeName;
                string EntityLogicalName = entityName;
                RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName = EntityLogicalName
                };
                RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)xrmService.Execute(retrieveDetails);
                Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
                Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
            (attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;

                foreach (OptionMetadata item in picklistMetadata.OptionSet.Options)
                {
                    ObjectCarrier.SetValue(item.Value.ToString(), item.Label.UserLocalizedLabel.Label);
                }

                return new Result(false, string.Empty, ObjectCarrier.GetAllValues(), logSystem);
            }
            catch (Exception ex)
            {
                return new Result(true,
                    MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                    null, logSystem);
            }
        }
        void attrWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var request = new RetrieveEntityRequest {EntityFilters = EntityFilters.Attributes, LogicalName = ((EntityInfo)e.Argument).Metadata.LogicalName};
            var response = (RetrieveEntityResponse) service.Execute(request);

            e.Result = response.EntityMetadata;
        }
Beispiel #40
0
        private void LoadEntity()
        {
            if (entityListView.SelectedItems.Count == 0)
                return;

            var emd = new EntityMetadataInfo((EntityMetadata)entityListView.SelectedItems[0].Tag);

            WorkAsync("Loading Entity...",
                dwe =>
                {
                    var request = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.All,
                        LogicalName = ((EntityMetadataInfo)dwe.Argument).LogicalName
                    };
                    var response = (RetrieveEntityResponse)Service.Execute(request);
                    dwe.Result = response.EntityMetadata;
                },
                wce =>
                {
                    var emdFull = (EntityMetadata)wce.Result;

                    TabPage tab;
                    if (mainTabControl.TabPages.ContainsKey(emd.SchemaName))
                    {
                        tab = mainTabControl.TabPages[emd.SchemaName];
                        ((EntityPropertiesControl)tab.Controls[0]).RefreshContent(emdFull);
                    }
                    else
                    {
                        mainTabControl.TabPages.Add(emd.SchemaName, emd.SchemaName);
                        tab = mainTabControl.TabPages[emd.SchemaName];

                        var epc = new EntityPropertiesControl(emdFull, lvcSettings)
                        {
                            Dock = DockStyle.Fill,
                            Name = emdFull.SchemaName
                        };
                        epc.OnColumnSettingsUpdated += epc_OnColumnSettingsUpdated;
                        tab.Controls.Add(epc);
                        mainTabControl.SelectTab(tab);
                    }
                },
                emd);
        }
Beispiel #41
0
        //</snippetAuditing2>

        /// <summary>
        /// Enable auditing on an entity.
        /// </summary>
        /// <param name="entityLogicalName">The logical name of the entity.</param>
        /// <param name="flag">True to enable auditing, otherwise false.</param>
        /// <returns>The previous value of the IsAuditEnabled attribute.</returns>
        //<snippetAuditing3>
        private bool EnableEntityAuditing(string entityLogicalName, bool flag)
        {
            // Retrieve the entity metadata.
            RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
            {
                LogicalName = entityLogicalName,
                EntityFilters = EntityFilters.Attributes
            };

            RetrieveEntityResponse entityResponse =
                (RetrieveEntityResponse)_service.Execute(entityRequest);

            // Enable auditing on the entity. By default, this also enables auditing
            // on all the entity's attributes.
            EntityMetadata entityMetadata = entityResponse.EntityMetadata;

            bool oldValue = entityMetadata.IsAuditEnabled.Value;
            entityMetadata.IsAuditEnabled = new BooleanManagedProperty(flag);

            UpdateEntityRequest updateEntityRequest = new UpdateEntityRequest { Entity = entityMetadata };

            UpdateEntityResponse updateEntityResponse =
                (UpdateEntityResponse)_service.Execute(updateEntityRequest);

            return oldValue;
        }
Beispiel #42
0
 public List<AttributeMetadata> GetEntityFieldMetadata(string entity)
 {
     lock (LockObject)
     {
         if (!EntityFieldMetadata.ContainsKey(entity))
         {
             Controller.LogLiteral("Retrieving " + entity + " field metadata");
             // Create the request
             var request = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.Attributes,
                 LogicalName = entity
             };
             var response = (RetrieveEntityResponse) Execute(request);
             Controller.LogLiteral("Retrieved " + entity + " field metadata");
             EntityFieldMetadata.Add(entity, new List<AttributeMetadata>(response.EntityMetadata.Attributes));
         }
     }
     return EntityFieldMetadata[entity];
 }
        private void LvEntitiesSelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvEntities.SelectedItems.Count == 0)
            {
                return;
            }

            var currentEntity = settings.EntitiesToProceed.FirstOrDefault(x => x.Name == lvEntities.SelectedItems[0].Tag.ToString());
            if (currentEntity == null)
            {
                lvEntities.SelectedItems[0].Checked = true;
            }

            if (cbbSelectionType.SelectedIndex == (int)AttributeSelectionOption.AttributeManualySelected)
            {
                lvAttributes.Items.Clear();

                var entityName = lvEntities.SelectedItems[0].Tag.ToString();
                SetWorkingState(true);

                WorkAsync("Retrieving attributes...",
                    evt =>
                    {
                        var entityLogicalName = evt.Argument.ToString();

                        var request = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = entityLogicalName };
                        var response = (RetrieveEntityResponse)Service.Execute(request);

                        evt.Result = response.EntityMetadata;
                    },
                    evt =>
                    {
                        var currentEntityMd = settings.EntitiesToProceed.FirstOrDefault(x => x.Name == lvEntities.SelectedItems[0].Tag.ToString());

                        foreach (var amd in ((EntityMetadata)evt.Result).Attributes)
                        {
                            var displayName = amd.DisplayName != null && amd.DisplayName.UserLocalizedLabel != null
                                                  ? amd.DisplayName.UserLocalizedLabel.Label
                                                  : "N/A";

                            var item = new ListViewItem(displayName);
                            item.SubItems.Add(amd.LogicalName);
                            item.Tag = amd.LogicalName;

                            if (currentEntityMd != null && currentEntityMd.Attributes.Contains(amd.LogicalName))
                            {
                                item.Checked = true;
                            }

                            lvAttributes.Items.Add(item);
                        }

                        SetWorkingState(false);
                    },
                    entityName);
            }
            else if (cbbSelectionType.SelectedIndex == (int)AttributeSelectionOption.AttributesOnForm
                || cbbSelectionType.SelectedIndex == (int)AttributeSelectionOption.AttributesNotOnForm)
            {
                lvForms.Items.Clear();

                var entityName = lvEntities.SelectedItems[0].Tag.ToString();
                SetWorkingState(true);

                var theEntity = settings.EntitiesToProceed.First(x => x.Name == lvEntities.SelectedItems[0].Tag.ToString());
                theEntity.FormsDefinitions.Clear();

                WorkAsync("Retrieving forms...",
                    evt =>
                    {
                        var qba = new QueryByAttribute("systemform");
                        qba.Attributes.AddRange("objecttypecode", "type");
                        qba.Values.AddRange(evt.Argument.ToString(), 2);
                        qba.ColumnSet = new ColumnSet(true);

                        evt.Result = Service.RetrieveMultiple(qba).Entities;
                    },
                    evt =>
                    {
                        var currentEntityMd = settings.EntitiesToProceed.FirstOrDefault(x => x.Name == lvEntities.SelectedItems[0].Tag.ToString());

                        foreach (var form in (DataCollection<Entity>)evt.Result)
                        {
                            currentEntityMd.FormsDefinitions.Add(form);

                            var item = new ListViewItem(form.GetAttributeValue<string>("name")) { Tag = form };

                            if (currentEntityMd != null && currentEntityMd.Forms.Contains(form.Id))
                            {
                                item.Checked = true;
                            }

                            lvForms.Items.Add(item);
                        }

                        SetWorkingState(false);
                    },
                    entityName);
            }
        }
        private void UpdateSettings()
        {
            if (string.IsNullOrWhiteSpace(this.OrganizationUrl) || !Uri.IsWellFormedUriString(this.OrganizationUrl, UriKind.Absolute))
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Organization Url is not valid. {0}", this.OrganizationUrl));
                return;
            }

            if (this.Settings == null)
            {
                Log.LogError("Required parameter missing: Settings");
                return;
            }

            Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to Organization {0}.", this.OrganizationUrl));
            string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout);
            var connection = CrmConnection.Parse(connectionString);
            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var request = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.Attributes,
                        LogicalName = "organization"
                    };

                    var response = serviceContext.Execute(request) as RetrieveEntityResponse;
                    if (response == null)
                    {
                        Log.LogError(string.Format(
                                        CultureInfo.CurrentCulture,
                                        "No response was received while retrieving settings for Organization with Url {0}",
                                        this.OrganizationUrl));
                        return;
                    }

                    var columnSet = new ColumnSet();
                    foreach (var settingItem in this.Settings)
                    {
                        string settingName = settingItem.ItemSpec;
                        columnSet.AddColumn(settingName);
                        var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName);
                        if (setting == null || setting.AttributeType == null)
                        {
                            Log.LogError(string.Format(
                                            CultureInfo.CurrentCulture,
                                            "No meta data for setting {0} was found.",
                                            settingName));
                            return;
                        }
                    }

                    var entityCollection = serviceContext.RetrieveMultiple(
                        new QueryExpression("organization")
                        {
                            ColumnSet = columnSet
                        });

                    if (entityCollection == null || entityCollection.Entities.Count == 0)
                    {
                        Log.LogError(string.Format(
                                        CultureInfo.CurrentCulture,
                                        "No setting was found for one of the settings"));
                        return;
                    }

                    var entity = entityCollection.Entities.First();
                    foreach (var settingItem in this.Settings)
                    {
                        string settingName = settingItem.ItemSpec;
                        string settingValue = settingItem.GetMetadata("value");
                        var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName);
                        if (setting == null || setting.AttributeType == null)
                        {
                            Log.LogError(string.Format(
                                            CultureInfo.CurrentCulture,
                                            "No meta data was found for setting with Name {0} was found.", 
                                            settingName));
                            return;
                        }

                        entity.Attributes[settingName] = ConvertCrmTypeToDotNetType(setting.AttributeType.Value, settingValue);
                    }

                    serviceContext.Update(entity);
                    Log.LogMessage(MessageImportance.High, "The organization settings were updated successfully.");   
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred while update settings for Organization with Url {0}. [{1}]", this.OrganizationUrl, exception.Message));   
                }
            }
        }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                {
                    var emd = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (emd == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        emd = response.EntityMetadata;

                        emds.Add(emd);
                    }

                    if (ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString() == "DisplayName")
                    {
                        emd.DisplayName = new Label();
                        int columnIndex = 3;

                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            emd.DisplayName.LocalizedLabels.Add(
                                new LocalizedLabel(ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString(),
                                    int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString() == "DisplayCollectionName")
                    {
                        emd.DisplayCollectionName = new Label();
                        int columnIndex = 3;

                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            emd.DisplayCollectionName.LocalizedLabels.Add(
                                new LocalizedLabel(ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString(),
                                    int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString() == "Description")
                    {
                        emd.Description = new Label();
                        int columnIndex = 3;

                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            emd.Description.LocalizedLabels.Add(
                                new LocalizedLabel(ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString(),
                                    int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var emd in emds.Where(e => e.IsRenameable.Value))
            {
                var entityUpdate = new EntityMetadata();
                entityUpdate.LogicalName = emd.LogicalName;
                entityUpdate.DisplayName = emd.DisplayName;
                entityUpdate.Description = emd.Description;
                entityUpdate.DisplayCollectionName = emd.DisplayCollectionName;

                var request = new UpdateEntityRequest { Entity = entityUpdate };

                service.Execute(request);
            }
        }
Beispiel #46
0
        private void LookupSingleLoad(object sender, EventArgs e)
        {
            var request = new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Attributes };
            metadata = ((RetrieveEntityResponse)service.Execute(request)).EntityMetadata;

            var qe = new QueryExpression("savedquery");
            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria.AddCondition("returnedtypecode", ConditionOperator.Equal, entityName);
            qe.Criteria.AddCondition("querytype", ConditionOperator.Equal, 4);
            var records = service.RetrieveMultiple(qe);

            int index = 0;
            int defaultViewIndex = 0;

            foreach (var record in records.Entities)
            {
                if ((bool)record["isdefault"])
                    defaultViewIndex = index;

                var view = new ViewInfo();
                view.Entity = record;

                cbbViews.Items.Add(view);

                index++;
            }

            cbbViews.SelectedIndex = defaultViewIndex;
        }
        object DoRetrieveAttributes(object item)
        {
            var i = item as EntityDefinition;

            SendStepChange(string.Format("Retrieving '{0}' attributes...", i.LogicalName));

            var request = new RetrieveEntityRequest
            {
                LogicalName = i.LogicalName,
                EntityFilters = EntityFilters.Attributes,
                RetrieveAsIfPublished = true
            };

            var response = _service.Execute<RetrieveEntityResponse>(request);

            var list = new List<AttributeDefinition>();

            foreach (AttributeMetadata attributeMetadata in response.EntityMetadata.Attributes.OrderBy(a => a.LogicalName))
            {
                if (!attributeMetadata.IsValidForCreate.Value && !attributeMetadata.IsValidForRead.Value && !attributeMetadata.IsValidForUpdate.Value)
                {
                    continue;
                }
                if (attributeMetadata.IsLogical.Value || attributeMetadata.AttributeType.Value == AttributeTypeCode.EntityName || !string.IsNullOrEmpty(attributeMetadata.AttributeOf))
                {
                    continue;
                }

                EnumDefinition enumDefinition = null;

                if (attributeMetadata.AttributeType.Value == AttributeTypeCode.Picklist || attributeMetadata.AttributeType.Value == AttributeTypeCode.State || attributeMetadata.AttributeType.Value == AttributeTypeCode.Status)
                {
                    var meta = ((EnumAttributeMetadata)attributeMetadata).OptionSet;

                    var tempEnumDefinition = new EnumDefinition
                    {
                        LogicalName = meta.Name,
                        IsGlobal = meta.IsGlobal.Value
                    };

                    if (attributeMetadata.AttributeType.Value == AttributeTypeCode.State)
                    {
                        tempEnumDefinition.Name = i.Name.Replace("Definition", "") + "State";
                    }
                    else if (attributeMetadata.AttributeType.Value == AttributeTypeCode.Status)
                    {
                        tempEnumDefinition.Name = i.Name.Replace("Definition", "") + "Status";
                    }
                    else
                    {
                        tempEnumDefinition.Name = meta.DisplayName.UserLocalizedLabel.Label.FormatText();
                    }

                    foreach (var option in meta.Options)
                    {
                        tempEnumDefinition.Values.Add(new EnumValueDefinition
                        {
                            Name = option.Label.UserLocalizedLabel.Label.FormatText(),
                            LogicalName = option.Value.Value.ToString(),
                            DisplayName = option.Label.UserLocalizedLabel.Label,
                            Value = option.Value.Value.ToString()
                        });
                    }

                    if (!EnumDefinitionCollection.Instance.Definitions.Any(d => d.LogicalName == meta.Name))
                    {
                        enumDefinition = tempEnumDefinition;
                        EnumDefinitionCollection.Instance.Add(enumDefinition);
                    }
                    else
                    {
                        enumDefinition = EnumDefinitionCollection.Instance.Definitions.First(d => d.LogicalName == meta.Name);
                        enumDefinition.Merge(tempEnumDefinition);
                    }
                }

                list.Add(new AttributeDefinition
                {
                    LogicalName = attributeMetadata.LogicalName,
                    Name = RemovePrefix(attributeMetadata.SchemaName),
                    DisplayName = attributeMetadata.DisplayName.UserLocalizedLabel == null ? attributeMetadata.SchemaName : attributeMetadata.DisplayName.UserLocalizedLabel.Label,
                    IsValidForAdvancedFind = attributeMetadata.IsValidForAdvancedFind.Value,
                    IsValidForCreate = attributeMetadata.IsValidForCreate.Value,
                    IsValidForRead = attributeMetadata.IsValidForRead.Value,
                    IsValidForUpdate = attributeMetadata.IsValidForUpdate.Value,
                    Type = attributeMetadata.AttributeType.Value.ToString(),
                    Enum = enumDefinition
                });
            }

            SendStepChange(string.Empty);
            return list;
        }
Beispiel #48
0
 public virtual EntityMetadata GetEntityMetadata(string entity)
 {
     lock (LockObject)
     {
         if (!EntityMetadata.Any(em => em.LogicalName == entity))
         {
             Controller.LogLiteral("Retrieving " + entity + " entity metadata");
             var request = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.Default,
                 LogicalName = entity
             };
             var response = (RetrieveEntityResponse) Execute(request);
             Controller.LogLiteral("Retrieved " + entity + " entity metadata");
             EntityMetadata.Add(response.EntityMetadata);
         }
     }
     return EntityMetadata.First(em => em.LogicalName == entity);
 }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            foreach (ExcelRow row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var emd = emds.FirstOrDefault(e => e.LogicalName == row.Cells[1].Value.ToString());
                if (emd == null)
                {
                    var request = new RetrieveEntityRequest
                                  {
                                      LogicalName = row.Cells[1].Value.ToString(),
                                      EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships
                                  };

                    var response = ((RetrieveEntityResponse) service.Execute(request));
                    emd = response.EntityMetadata;

                    emds.Add(emd);
                }

                if (row.Cells[2].Value.ToString() == "DisplayName")
                {
                    emd.DisplayName = new Label();
                    int columnIndex = 3;

                    while (row.Cells[columnIndex].Value != null)
                    {
                        emd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (row.Cells[2].Value.ToString() == "DisplayCollectionName")
                {
                    emd.DisplayCollectionName = new Label();
                    int columnIndex = 3;

                    while (row.Cells[columnIndex].Value != null)
                    {
                        emd.DisplayCollectionName.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (row.Cells[2].Value.ToString() == "Description")
                {
                    emd.Description = new Label();
                    int columnIndex = 3;

                    while (row.Cells[columnIndex].Value != null)
                    {
                        emd.Description.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
            }

            foreach (var emd in emds.Where(e=>e.IsRenameable.Value))
            {
                var request = new UpdateEntityRequest {Entity = emd};
                service.Execute(request);
            }
        }
Beispiel #50
0
        public static void retrieveAttributeList(string entityName)
        {
            using (OrganizationService orgService = new OrganizationService(getCrmConnection())){
                RetrieveEntityRequest lclAEntityMetaDataRequest = new RetrieveEntityRequest();
                RetrieveEntityResponse lclEntityMetaDataResponse = null;
                lclAEntityMetaDataRequest.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes;
                lclAEntityMetaDataRequest.LogicalName = entityName;
                lclEntityMetaDataResponse = (RetrieveEntityResponse)orgService.Execute(lclAEntityMetaDataRequest);

            }
        }
 /// <summary>
 /// Gets a subset of metadata for the specified entity, as dictated by the filters specified.
 /// </summary>
 /// <param name="entityLogicalName"></param>
 /// <param name="filters"></param>
 /// <returns></returns>
 public EntityMetadata GetEntityMetadata(string entityLogicalName, EntityFilters filters)
 {
     var metaRequest = new RetrieveEntityRequest()
         {
             EntityFilters = EntityFilters.All,
             LogicalName = entityLogicalName
         };
     try
     {
         IOrganizationService service = _CrmServiceProvider.GetOrganisationService();
         using (service as IDisposable)
         {
             var metaResponse = (RetrieveEntityResponse)service.Execute(metaRequest);
             return metaResponse.EntityMetadata;
         }
     }
     catch (Exception e)
     {
         throw new Exception("Unable to obtain CRM metadata for entity: " + entityLogicalName + " as CRM returned a fault. See inner exception for details.", e);
     }
 }
 private void LoadEntityDetails(string entityName, Action detailsLoaded)
 {
     if (working)
     {
         return;
     }
     working = true;
     WorkAsync("Loading " + GetEntityDisplayName(entityName) + " metadata...",
         (eventargs) =>
         {
             var req = new RetrieveEntityRequest()
             {
                 LogicalName = entityName,
                 EntityFilters = EntityFilters.Attributes | EntityFilters.Relationships,
                 RetrieveAsIfPublished = true
             };
             eventargs.Result = Service.Execute(req);
         },
         (completedargs) =>
         {
             working = false;
             if (completedargs.Error != null)
             {
                 entityShitList.Add(entityName);
                 MessageBox.Show(completedargs.Error.Message, "Load attribute metadata", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             else
             {
                 if (completedargs.Result is RetrieveEntityResponse)
                 {
                     var resp = (RetrieveEntityResponse)completedargs.Result;
                     if (entities == null)
                     {
                         entities = new Dictionary<string, EntityMetadata>();
                     }
                     if (entities.ContainsKey(entityName))
                     {
                         entities[entityName] = resp.EntityMetadata;
                     }
                     else
                     {
                         entities.Add(entityName, resp.EntityMetadata);
                     }
                 }
                 detailsLoaded();
             }
             working = false;
         });
 }
Beispiel #53
0
 private void RefreshEntityMetadata(string schemaName)
 {
     lock (LockObject)
     {
         var request = new RetrieveEntityRequest
         {
             EntityFilters = EntityFilters.Attributes,
             LogicalName = schemaName
         };
         var response = (RetrieveEntityResponse) Execute(request);
         if (EntityExists(schemaName))
             GetAllEntityMetadata().Remove(GetAllEntityMetadata().First(m => m.SchemaName == schemaName));
         GetAllEntityMetadata().Add(response.EntityMetadata);
     }
 }
Beispiel #54
0
 public IEnumerable<RelationshipMetadataBase> GetEntityRelationships(string entity)
 {
     lock (LockObject)
     {
         if (!EntityRelationships.ContainsKey(entity))
         {
             Controller.LogLiteral("Retrieving " + entity + " relationship metadata");
             var request = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.Relationships,
                 LogicalName = entity
             };
             var response = (RetrieveEntityResponse) Execute(request);
             Controller.LogLiteral("Retrieved " + entity + " relationship metadata");
             EntityRelationships.Add(entity,
                 response.EntityMetadata.OneToManyRelationships
                     .Cast<RelationshipMetadataBase>()
                     .Union(response.EntityMetadata.ManyToManyRelationships).ToArray());
         }
     }
     return EntityRelationships[entity];
 }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List<MasterAttribute>();

            var rowsCount = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;
            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(ZeroBasedSheet.Cell(sheet, rowI, 0).Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new Label();

                    while (columnIndex < cellsCount)
                    {
                        if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var lcid = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                            var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                            amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }
                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                {
                    amd.Amd.Description = new Label();

                    while (columnIndex < cellsCount)
                    {
                        if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var lcid = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                            var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                            amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

                        columnIndex++;
                    }
                }
            }

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label))
                    || amd.Amd.IsRenameable.Value == false)
                    continue;

                var request = new UpdateAttributeRequest { Attribute = amd.Amd, EntityName = amd.Amd.EntityLogicalName };
                service.Execute(request);
            }
        }
Beispiel #56
0
        /// <summary>
        ///     WARNING!! DELETES THE CUSTOM ENTITY
        /// </summary>
        /// <param name="schemaName"></param>
        public void DeleteEntity(string schemaName)
        {
            lock (LockObject)
            {
                var tempRequest1 = new RetrieveEntityRequest
                {
                    LogicalName = schemaName,
                    EntityFilters = EntityFilters.Relationships
                };
                var response = (RetrieveEntityResponse) Execute(tempRequest1);
                foreach (var r in response.EntityMetadata.OneToManyRelationships)
                {
                    if (r.IsCustomRelationship.HasValue && r.IsCustomRelationship.Value)
                    {
                        var tempRequest2 = new DeleteRelationshipRequest
                        {
                            Name = r.SchemaName
                        };
                        Execute(tempRequest2);
                    }
                }

                var request = new DeleteEntityRequest();
                request.LogicalName = schemaName;
                Execute(request);
                if (GetAllEntityMetadata().Any(m => m.SchemaName == schemaName))
                    GetAllEntityMetadata().Remove(GetAllEntityMetadata().Single(m => m.SchemaName == schemaName));
                if (_entityFieldMetadata.ContainsKey(schemaName))
                    _entityFieldMetadata.Remove(schemaName);
            }
        }
Beispiel #57
0
        /// <summary>
        /// Retrieve all privileges definition for the specified entity
        /// </summary>
        /// <param name="entityName">Entity logical name</param>
        /// <returns>List of privileges</returns>
        public Dictionary<string, Guid> RetrievePrivileges(string entityName)
        {
            var request = new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Privileges };
            var response = (RetrieveEntityResponse)service.Execute(request);

            var privileges = new Dictionary<string, Guid>();

            foreach (SecurityPrivilegeMetadata spmd in response.EntityMetadata.Privileges)
            {
                privileges.Add(spmd.Name.ToLower(), spmd.PrivilegeId);
            }

            return privileges;
        }
Beispiel #58
0
        public void Export(ExportSettings settings, IOrganizationService service, BackgroundWorker worker = null)
        {
            // Loading available languages
            if (worker != null && worker.WorkerReportsProgress)
            {
                worker.ReportProgress(0, "Loading provisioned languages...");
            }
            var lcidRequest = new RetrieveProvisionedLanguagesRequest();
            var lcidResponse = (RetrieveProvisionedLanguagesResponse)service.Execute(lcidRequest);
            var lcids = lcidResponse.RetrieveProvisionedLanguages.Select(lcid => lcid).ToList();

            // Loading entities
            var emds = new List<EntityMetadata>();

            if (worker != null && worker.WorkerReportsProgress)
            {
                worker.ReportProgress(0, "Loading selected entities...");
            }
            foreach (string entityLogicalName in settings.Entities)
            {
                var filters = EntityFilters.Default;
                if (settings.ExportEntities)
                {
                    filters = filters | EntityFilters.Entity;
                }
                if (settings.ExportCustomizedRelationships)
                {
                    filters = filters | EntityFilters.Relationships;
                }
                if (settings.ExportAttributes)
                {
                    filters = filters | EntityFilters.Attributes;
                }

                var request = new RetrieveEntityRequest { LogicalName = entityLogicalName, EntityFilters = filters };
                var response = (RetrieveEntityResponse)service.Execute(request);
                emds.Add(response.EntityMetadata);
            }

            var file = new ExcelPackage();
            file.File = new FileInfo(settings.FilePath);

            if (settings.ExportEntities && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting entities translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Entities");
                var et = new EntityTranslation();
                et.Export(emds, lcids, sheet);
                StyleMutator.FontDefaults(sheet);
            }

            if (settings.ExportAttributes && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting attributes translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Attributes");
                var at = new AttributeTranslation();
                at.Export(emds, lcids, sheet);
                StyleMutator.FontDefaults(sheet);
            }

            if (settings.ExportCustomizedRelationships && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting relationships with custom labels translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Relationships");
                var rt = new RelationshipTranslation();
                rt.Export(emds, lcids, sheet);
                StyleMutator.FontDefaults(sheet);

                var sheetNn = file.Workbook.Worksheets.Add("RelationshipsNN");
                var rtNn = new RelationshipNnTranslation();
                rtNn.Export(emds, lcids, sheetNn);
                StyleMutator.FontDefaults(sheetNn);
            }

            if (settings.ExportGlobalOptionSet)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting global optionsets translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Global OptionSets");
                var ot = new GlobalOptionSetTranslation();
                ot.Export(lcids, sheet, service);
                StyleMutator.FontDefaults(sheet);
            }

            if (settings.ExportOptionSet && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting optionset translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("OptionSets");
                var ot = new OptionSetTranslation();
                ot.Export(emds, lcids, sheet);
                StyleMutator.FontDefaults(sheet);
            }

            if (settings.ExportBooleans && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting booleans translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Booleans");

                var bt = new BooleanTranslation();
                bt.Export(emds, lcids, sheet);
                StyleMutator.FontDefaults(sheet);
            }

            if (settings.ExportViews && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting views translations...");
                }

                var sheet = file.Workbook.Worksheets.Add("Views");
                var vt = new ViewTranslation();
                vt.Export(emds, lcids, sheet, service);
                StyleMutator.FontDefaults(sheet);
            }

            if ((settings.ExportForms || settings.ExportFormTabs || settings.ExportFormSections || settings.ExportFormFields) && emds.Count > 0)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting forms translations...");
                }

                var ft = new FormTranslation();

                ft.Export(emds, lcids, file.Workbook, service,
                    new FormExportOption
                    {
                        ExportForms = settings.ExportForms,
                        ExportFormTabs = settings.ExportFormTabs,
                        ExportFormSections = settings.ExportFormSections,
                        ExportFormFields = settings.ExportFormFields
                    });
            }

            if (settings.ExportSiteMap)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting SiteMap custom labels translations...");
                }

                var st = new SiteMapTranslation();

                st.Export(lcids, file.Workbook, service);
            }

            if (settings.ExportDashboards)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Exporting Dashboards custom labels translations...");
                }

                var st = new DashboardTranslation();

                st.Export(lcids, file.Workbook, service);
            }

            file.Save();

            if (DialogResult.Yes == MessageBox.Show("Do you want to open generated document?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                Process.Start(settings.FilePath);
            }
        }
Beispiel #59
0
        public void Generate(IOrganizationService service)
        {
            int totalEntities = _settings.EntitiesToProceed.Count;
            int processed = 0;

            foreach (var entity in _settings.EntitiesToProceed)
            {
                ReportProgress(processed * 100 / totalEntities, string.Format("Processing entity '{0}'...", entity.Name));

                var emd = emdCache.FirstOrDefault(x => x.LogicalName == entity.Name);
                if (emd == null)
                {
                    var reRequest = new RetrieveEntityRequest
                                        {
                                            LogicalName = entity.Name,
                                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                                        };
                    var reResponse = (RetrieveEntityResponse)service.Execute(reRequest);

                    emdCache.Add(reResponse.EntityMetadata);
                    emd = reResponse.EntityMetadata;
                }

                AddEntityMetadata(emd);

                List<AttributeMetadata> amds = new List<AttributeMetadata>();

                if (_settings.AddFormLocation)
                {
                    currentEntityForms = MetadataHelper.RetrieveEntityFormList(emd.LogicalName, service);
                }

                switch (_settings.AttributesSelection)
                {
                    case AttributeSelectionOption.AllAttributes:
                        amds = emd.Attributes.ToList();
                        break;

                    case AttributeSelectionOption.AttributesOptionSet:
                        amds =
                            emd.Attributes.Where(
                                x => x.AttributeType != null && (x.AttributeType.Value == AttributeTypeCode.Boolean
                                                                 || x.AttributeType.Value == AttributeTypeCode.Picklist
                                                                 || x.AttributeType.Value == AttributeTypeCode.State
                                                                 || x.AttributeType.Value == AttributeTypeCode.Status)).ToList();
                        break;

                    case AttributeSelectionOption.AttributeManualySelected:
                        amds =
                            emd.Attributes.Where(
                                x =>
                                _settings.EntitiesToProceed.First(y => y.Name == emd.LogicalName).Attributes.Contains(
                                    x.LogicalName)).ToList();
                        break;

                    case AttributeSelectionOption.AttributesOnForm:

                        // If no forms selected, we search attributes in all forms
                        if (entity.Forms.Count == 0)
                        {
                            foreach (var form in entity.FormsDefinitions)
                            {
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") !=
                                    null));
                            }
                        }
                        else
                        {
                            // else we parse selected forms
                            foreach (var formId in entity.Forms)
                            {
                                var form = entity.FormsDefinitions.First(f => f.Id == formId);
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") !=
                                    null));
                            }
                        }

                        break;

                    case AttributeSelectionOption.AttributesNotOnForm:
                        // If no forms selected, we search attributes in all forms
                        if (entity.Forms.Count == 0)
                        {
                            foreach (var form in entity.FormsDefinitions)
                            {
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") ==
                                    null));
                            }
                        }
                        else
                        {
                            // else we parse selected forms
                            foreach (var formId in entity.Forms)
                            {
                                var form = entity.FormsDefinitions.First(f => f.Id == formId);
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") ==
                                    null));
                            }
                        }

                        break;
                }

                if (Settings.Prefixes != null && Settings.Prefixes.Count > 0)
                {
                    var filteredAmds = new List<AttributeMetadata>();

                    foreach (var prefix in Settings.Prefixes)
                    {
                        filteredAmds.AddRange(amds.Where(a => a.LogicalName.StartsWith(prefix) /*|| a.IsCustomAttribute.Value == false*/));
                    }

                    amds = filteredAmds;
                }

                AddAttribute(amds);
                processed++;
            }
            SaveDocument(_settings.FilePath);
        }
Beispiel #60
0
        public void Generate(IOrganizationService service)
        {
            ExcelWorksheet summarySheet = null;
            if (settings.AddEntitiesSummary)
            {
                summaryLineNumber = 1;
                summarySheet = AddWorkSheet("Entities list");
            }
            int totalEntities = settings.EntitiesToProceed.Count;
            int processed = 0;

            foreach (var entity in settings.EntitiesToProceed.OrderBy(e => e.Name))
            {
                ReportProgress(processed * 100 / totalEntities, string.Format("Processing entity '{0}'...", entity.Name));

                var emd = emdCache.FirstOrDefault(x => x.LogicalName == entity.Name);
                if (emd == null)
                {
                    var reRequest = new RetrieveEntityRequest
                    {
                        LogicalName = entity.Name,
                        EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                    };
                    var reResponse = (RetrieveEntityResponse)service.Execute(reRequest);

                    emdCache.Add(reResponse.EntityMetadata);
                    emd = reResponse.EntityMetadata;
                }

                if (settings.AddEntitiesSummary)
                {
                    AddEntityMetadataInLine(emd, summarySheet);
                }

                lineNumber = 1;

                var emdDisplayNameLabel = emd.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);

                var sheet = AddWorkSheet(emdDisplayNameLabel == null ? "N/A" : emdDisplayNameLabel.Label, emd.SchemaName);

                if (!settings.AddEntitiesSummary)
                {
                    AddEntityMetadata(emd, sheet);
                }

                if (settings.AddFormLocation)
                {
                    currentEntityForms = MetadataHelper.RetrieveEntityFormList(emd.LogicalName, service);
                }

                List<AttributeMetadata> amds = new List<AttributeMetadata>();

                switch (settings.AttributesSelection)
                {
                    case AttributeSelectionOption.AllAttributes:
                        amds = emd.Attributes.ToList();
                        break;

                    case AttributeSelectionOption.AttributesOptionSet:
                        amds =
                            emd.Attributes.Where(
                                x => x.AttributeType != null && (x.AttributeType.Value == AttributeTypeCode.Boolean
                                                                 || x.AttributeType.Value == AttributeTypeCode.Picklist
                                                                 || x.AttributeType.Value == AttributeTypeCode.State
                                                                 || x.AttributeType.Value == AttributeTypeCode.Status)).ToList();
                        break;

                    case AttributeSelectionOption.AttributeManualySelected:

                        amds =
                            emd.Attributes.Where(
                                x =>
                                settings.EntitiesToProceed.FirstOrDefault(y => y.Name == emd.LogicalName).Attributes.Contains(
                                    x.LogicalName)).ToList();
                        break;

                    case AttributeSelectionOption.AttributesOnForm:

                        // If no forms selected, we search attributes in all forms
                        if (entity.Forms.Count == 0)
                        {
                            foreach (var form in entity.FormsDefinitions)
                            {
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") !=
                                    null));
                            }
                        }
                        else
                        {
                            // else we parse selected forms
                            foreach (var formId in entity.Forms)
                            {
                                var form = entity.FormsDefinitions.FirstOrDefault(f => f.Id == formId);
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") !=
                                    null));
                            }
                        }

                        break;

                    case AttributeSelectionOption.AttributesNotOnForm:
                        // If no forms selected, we search attributes in all forms
                        if (entity.Forms.Count == 0)
                        {
                            foreach (var form in entity.FormsDefinitions)
                            {
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") ==
                                    null));
                            }
                        }
                        else
                        {
                            // else we parse selected forms
                            foreach (var formId in entity.Forms)
                            {
                                var form = entity.FormsDefinitions.FirstOrDefault(f => f.Id == formId);
                                var tempStringDoc = form.GetAttributeValue<string>("formxml");
                                var tempDoc = new XmlDocument();
                                tempDoc.LoadXml(tempStringDoc);

                                amds.AddRange(emd.Attributes.Where(x =>
                                    tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") ==
                                    null));
                            }
                        }

                        break;
                }

                if (settings.Prefixes != null && settings.Prefixes.Count > 0)
                {
                    var filteredAmds = new List<AttributeMetadata>();

                    foreach (var prefix in settings.Prefixes)
                    {
                        filteredAmds.AddRange(amds.Where(a => a.LogicalName.StartsWith(prefix) /*|| a.IsCustomAttribute.Value == false*/));
                    }

                    amds = filteredAmds;
                }

                if (amds.Any())
                {
                    foreach (var amd in amds.Distinct(new AttributeMetadataComparer()).OrderBy(a => a.LogicalName))
                    {
                        AddAttribute(emd.Attributes.FirstOrDefault(x => x.LogicalName == amd.LogicalName), sheet);
                    }
                }
                else
                {
                    Write("no attributes to display", sheet, 1, !settings.AddEntitiesSummary ? 10 : 1);
                }

                sheet.Cells[sheet.Dimension.Address].AutoFitColumns();

                processed++;
            }

            if (settings.AddEntitiesSummary)
            {
                summarySheet.Cells[summarySheet.Dimension.Address].AutoFitColumns();
            }

            SaveDocument(settings.FilePath);
        }