/// <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;
   }
  }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        public async Task Test_UpdateEntityRequest_Handler()
        {
            // resolving Meditor service implementation using ServiceProvider
            var mediatr = IoC.ServiceProvider.GetRequiredService <IMediator>();


            var createResult = await mediatr.Send(
                new CreateEntityRequest <TestModel>(new TestModel()
            {
                Name = "test name 1",
                Description = "test description 1"
            })
                );

            // updating fields
            // preparing the entity to use
            var entity = new TestModel()
            {
                Id          = createResult.Id,
                Name        = "test name update",
                Description = "test description update"
            };


            var updateEntityRequest = new UpdateEntityRequest <int, TestModel>(entity.Id, entity);

            var persistedValue = await mediatr.Send(updateEntityRequest);

            // testing results
            //Assert.AreNotEqual(createResult, persistedValue);
            Assert.AreEqual(persistedValue, createResult);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            UpdateEntityRequest request;

            try
            {
                request = new UpdateEntityRequest
                {
                    CatalogId           = CatalogId,
                    DataAssetKey        = DataAssetKey,
                    EntityKey           = EntityKey,
                    UpdateEntityDetails = UpdateEntityDetails,
                    IfMatch             = IfMatch,
                    OpcRequestId        = OpcRequestId
                };

                response = client.UpdateEntity(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Entity);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
Exemplo n.º 5
0
        public static void ApplyImagesToEntities(List <EntityImageMap> mappings, IOrganizationService service)
        {
            foreach (var mapping in mappings)
            {
                if (mapping.ImageSize == 16)
                {
                    mapping.Entity.IconSmallName = mapping.WebResourceName;
                }
                else
                {
                    mapping.Entity.IconMediumName = mapping.WebResourceName;
                }

                var request = new UpdateEntityRequest {
                    Entity = mapping.Entity
                };
                service.Execute(request);
            }

            string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>"));

            string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>",
                                                parameter);

            var publishRequest = new PublishXmlRequest {
                ParameterXml = parameterXml
            };

            service.Execute(publishRequest);
        }
        private void UpdateEntityDisplayName()
        {
            var i = 1;

            foreach (var entity in Entities)
            {
                try
                {
                    var retrieveRequest = new RetrieveEntityRequest {
                        LogicalName = entity, EntityFilters = EntityFilters.Entity
                    };
                    var retrieveResponse = (RetrieveEntityResponse)service.Execute(retrieveRequest);
                    var update           = retrieveResponse.EntityMetadata;
                    if (update.DisplayName.UserLocalizedLabel.Label.StartsWith(NOT_USE))
                    {
                        continue;
                    }
                    update.DisplayName = new Microsoft.Xrm.Sdk.Label($"{NOT_USE}{update.DisplayName.UserLocalizedLabel.Label}", 1033);
                    var updateRequest = new UpdateEntityRequest
                    {
                        Entity = update,
                    };
                    service.Execute(updateRequest);
                    CliLog.WriteLine(CliLog.ColorWhite, i, " UpdateEntityDisplayName - ", entity);
                }
                catch
                {
                    CliLog.WriteLine(CliLog.ColorRed, i, " UpdateEntityDisplayName - ", entity);
                }
                i++;
            }
        }
Exemplo n.º 7
0
        public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service)
        {
            foreach (var mapping in mappings)
            {
                if (mapping.ImageSize == 16)
                {
                    mapping.Entity.IconSmallName = mapping.WebResourceName;
                }
                else
                {
                    mapping.Entity.IconMediumName = mapping.WebResourceName;
                }

                var request = new UpdateEntityRequest { Entity = mapping.Entity };
                service.Execute(request);
            }

            string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>"));

            string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>",
                                                parameter);

            var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml };
            service.Execute(publishRequest);
        }
Exemplo n.º 8
0
        private void UpdateEntityMetadata(EntityMetadata entityMetadata)
        {
            var request = new UpdateEntityRequest()
            {
                Entity = entityMetadata,
            };

            var response = (UpdateEntityResponse)_service.Execute(request);
        }
Exemplo n.º 9
0
        public Task <TEntity> Handle(UpdateEntityRequest <TKey, TEntity> request, CancellationToken cancellationToken)
        {
            var keyProperty = typeof(TEntity).GetProperties().FirstOrDefault(p => p.GetCustomAttribute <KeyAttribute>() != null);

            return(Task.Run(() =>
            {
                var item = _entities.FirstOrDefault(e => ((TKey)keyProperty.GetValue(e)).Equals(request.Key));
                item = request.Entity;
                return item;
            }));
        }
        public virtual async Task <IActionResult> Put(TKey id, [FromBody] TEntity entity)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new { entity, ModelState.ValidationState }));
            }
            var request = new UpdateEntityRequest <TEntity, TKey>(new KeyValuePair <TKey, TEntity>(id, entity));
            var result  = await _mediator.Send(request);

            return(new OkObjectResult(result));
        }
Exemplo n.º 11
0
        public static void ResetIcons(EntityMetadata emd, IOrganizationService service)
        {
            emd.IconSmallName = "";
            emd.IconMediumName = "";
            emd.IconLargeName = "";
            var request = new UpdateEntityRequest { Entity = emd };
            service.Execute(request);

            string parameterXml = string.Format("<importexportxml ><entities><entity>{0}</entity></entities></importexportxml>",
                                                emd.LogicalName);

            var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml };
            service.Execute(publishRequest);
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Put(TKey id, [FromBody] TEntity value)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new { Errors = ModelState.Values, Payload = value }));
            }
            var request = new UpdateEntityRequest <TKey, TEntity>(id, value);
            var result  = await _mediator.Send(request);

            return(new OkObjectResult(result)
            {
                StatusCode = 200
            });
        }
Exemplo n.º 13
0
        public override Result Execute()
        {
            var doExecute = false;

            // Retrieve the entity metadata
            var retrieveEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = this.EntityLogicalName,
            };

            var retrieveEntityResponse = this.CrmOrganization.Execute <RetrieveEntityResponse>(retrieveEntityRequest);

            EntityMetadata entityMetadata = retrieveEntityResponse.EntityMetadata;

            // Update 'ChangeTrackingEnabled' property
            if (entityMetadata.CanChangeTrackingBeEnabled.CanBeChanged)
            {
                if (entityMetadata.ChangeTrackingEnabled == null || entityMetadata.ChangeTrackingEnabled != this.EnableChangeTracking)
                {
                    entityMetadata.ChangeTrackingEnabled = this.EnableChangeTracking;
                    doExecute = true;
                }
            }

            // Fire & execute
            if (doExecute)
            {
                // Prepare the UpdateEntityRequest
                var updateEntityRequest = new UpdateEntityRequest
                {
                    Entity = entityMetadata,
                };

                Logger.Log($"Entity Change Tracking has been set to {this.EnableChangeTracking} for {this.EntityLogicalName}", LogLevel.Info);

                this.CrmOrganization.Execute(updateEntityRequest);
            }
            else
            {
                Logger.Log($"Entity Change Tracking was already set to {this.EnableChangeTracking} for {this.EntityLogicalName}", LogLevel.Info);
            }

            return(new Result()
            {
                Success = true
            });
        }
        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.");
            }

            // Check if change tracking enabled
            if (!(bool)checkResponse.EntityMetadata.ChangeTrackingEnabled)
            {
                // Check if change tracking can be enabled
                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.");
                }
                else
                {
                    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.");
                    }
                }
            }
        }
Exemplo n.º 15
0
        public static void ResetIcons(EntityMetadata emd, IOrganizationService service)
        {
            emd.IconSmallName  = "";
            emd.IconMediumName = "";
            emd.IconLargeName  = "";
            var request = new UpdateEntityRequest {
                Entity = emd
            };

            service.Execute(request);

            string parameterXml = string.Format("<importexportxml ><entities><entity>{0}</entity></entities></importexportxml>",
                                                emd.LogicalName);

            var publishRequest = new PublishXmlRequest {
                ParameterXml = parameterXml
            };

            service.Execute(publishRequest);
        }
        /// <summary>
        /// Reverts any changes that were done by this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to revert the changes done by this sample.</param>
        /// </summary>
        public void RevertChanges(bool prompt)
        {
            bool revertChanges = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these changes reverted? (y/n) [y]: ");
                String answer = Console.ReadLine();

                revertChanges = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
            }

            if (revertChanges)
            {
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                {
                    EntityFilters         = EntityFilters.All,
                    LogicalName           = Contact.EntityLogicalName,
                    RetrieveAsIfPublished = false
                };
                RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);

                EntityMetadata contactEntity = entityResponse.EntityMetadata;

                // Disable document management for the retrieved entity.
                contactEntity.IsDocumentManagementEnabled = false;

                UpdateEntityRequest updateRequest = new UpdateEntityRequest
                {
                    Entity = contactEntity
                };
                _serviceProxy.Execute(updateRequest);

                // Publish the customizations to the entity.
                PublishAllXmlRequest disableRequest = new PublishAllXmlRequest();
                _serviceProxy.Execute(disableRequest);

                Console.WriteLine("Changes have been reverted.");
            }
        }
Exemplo n.º 17
0
        public async Task <TEntity> Handle(UpdateEntityRequest <TKey, TEntity> request, CancellationToken cancellationToken)
        {
            var resultToReturn = await innerDataContext.Set <TEntity>().FindAsync(request.Key);

            var entityType = innerDataContext.Model.FindRuntimeEntityType(typeof(TEntity));//.FirstOrDefault(e => e.Name == );
            //.FindEntityType(typeof(TEntity).Name);

            var keyProperties = entityType
                                .FindPrimaryKey()?.Properties.Select(p => p.PropertyInfo) ?? new PropertyInfo[] { };

            foreach (var property in typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var value = property.GetValue(request.Entity);
                if (!(value is null) && keyProperties.Contains(property))
                {
                    property.SetValue(resultToReturn, value);
                }
            }
            await innerDataContext.SaveChangesAsync(cancellationToken);

            return(resultToReturn);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Checks if knowledge management is enabled for the Incident entity.
        /// </summary>
        private void CheckKnowledgeManagementStatus()
        {
            RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName   = Incident.EntityLogicalName,

                // Retrieve only the currently published changes, ignoring the changes
                // that have not been published.
                RetrieveAsIfPublished = false
            };
            RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);

            if (entityResponse.EntityMetadata.IsKnowledgeManagementEnabled == true)
            {
                Console.WriteLine("Verified that knowledge management is enabled for Incident entity.\n");
                return;
            }
            else
            {
                // Enable knolwledge management for the Incident entity.
                Console.WriteLine("Knowledge management is not enabled for the Incident entity.");
                entityResponse.EntityMetadata.IsKnowledgeManagementEnabled = true;

                // Create an update request.
                UpdateEntityRequest updateRequest = new UpdateEntityRequest
                {
                    Entity = entityResponse.EntityMetadata
                };
                _serviceProxy.Execute(updateRequest);

                // Publish the entity.
                // All customizations must be published before they can be used.
                PublishAllXmlRequest enableRequest = new PublishAllXmlRequest();
                _serviceProxy.Execute(enableRequest);
                Console.WriteLine("Enabled Knowledge management for the Incident entity.");
            }
        }
Exemplo n.º 19
0
        public bool CheckAndUpdateEntity(string entity, OrganizationWebProxyClient proxy, Logger logger)
        {
            var checkRequest = new RetrieveEntityRequest()
            {
                LogicalName   = entity,
                EntityFilters = EntityFilters.Entity
            };

            var checkResponse = new RetrieveEntityResponse();

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

            if (checkResponse.EntityMetadata.ChangeTrackingEnabled != null &&
                !(bool)checkResponse.EntityMetadata.ChangeTrackingEnabled &&
                checkResponse.EntityMetadata.CanChangeTrackingBeEnabled.Value)
            {
                var updateRequest = new UpdateEntityRequest()
                {
                    Entity = checkResponse.EntityMetadata
                };

                updateRequest.Entity.ChangeTrackingEnabled = true;
                var updateResponse = new UpdateEntityResponse();
                updateResponse = (UpdateEntityResponse)proxy.Execute(updateRequest);

                return(true);
            }

            if (checkResponse.EntityMetadata.ChangeTrackingEnabled != null &&
                (bool)checkResponse.EntityMetadata.ChangeTrackingEnabled)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 20
0
        private void TsbApplyChangesClick(object sender, EventArgs e)
        {
            if (entityInfos.All(ei => ei.Action == ActionState.None) &&
                attributeInfos.All(ai => ai.Action == ActionState.None))
            {
                return;
            }

            gbEntities.Enabled    = false;
            gbAttributes.Enabled  = false;
            toolStripMenu.Enabled = false;

            WorkAsync("Updating entities...",
                      (bw, evt) =>
            {
                foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                {
                    if (ei.Action == ActionState.Added)
                    {
                        bw.ReportProgress(0, string.Format("Enabling entity '{0}' for audit...", ei.Emd.LogicalName));

                        ei.Emd.IsAuditEnabled.Value = true;
                    }
                    else if (ei.Action == ActionState.Removed)
                    {
                        bw.ReportProgress(0, string.Format("Disabling entity '{0}' for audit...", ei.Emd.LogicalName));

                        ei.Emd.IsAuditEnabled.Value = false;
                    }
                    else
                    {
                        continue;
                    }

                    var request = new UpdateEntityRequest {
                        Entity = ei.Emd
                    };
                    Service.Execute(request);

                    ei.Action = ActionState.None;
                }

                bw.ReportProgress(0, "Updating attributes...");

                foreach (AttributeInfo ai in attributeInfos.OrderBy(a => a.Amd.EntityLogicalName).ThenBy(a => a.Amd.LogicalName))
                {
                    if (ai.Action == ActionState.Added)
                    {
                        bw.ReportProgress(0, string.Format("Enabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                        ai.Amd.IsAuditEnabled.Value = true;
                    }
                    else if (ai.Action == ActionState.Removed)
                    {
                        bw.ReportProgress(0, string.Format("Disabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                        ai.Amd.IsAuditEnabled.Value = false;
                    }
                    else
                    {
                        continue;
                    }

                    var request = new UpdateAttributeRequest {
                        Attribute = ai.Amd, EntityName = ai.Amd.EntityLogicalName
                    };
                    Service.Execute(request);

                    ai.Action = ActionState.None;
                }

                bw.ReportProgress(0, "Publishing changes...");

                var publishRequest = new PublishXmlRequest {
                    ParameterXml = "<importexportxml><entities>"
                };

                foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                {
                    publishRequest.ParameterXml += string.Format("<entity>{0}</entity>", ei.Emd.LogicalName);
                }

                publishRequest.ParameterXml +=
                    "</entities><securityroles/><settings/><workflows/></importexportxml>";

                Service.Execute(publishRequest);
            },
                      evt =>
            {
                if (evt.Error != null)
                {
                    MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }

                gbEntities.Enabled    = true;
                gbAttributes.Enabled  = true;
                toolStripMenu.Enabled = true;

                tsbApplyChanges.Enabled = !((entityInfos.All(ei => ei.Action == ActionState.None) &&
                                             attributeInfos.All(ai => ai.Action == ActionState.None)));
            },
                      evt => SetWorkingMessage(evt.UserState.ToString()));
        }
Exemplo n.º 21
0
        private void TsbApplyChangesClick(object sender, EventArgs e)
        {
            if (entityInfos.All(ei => ei.Action == ActionState.None) &&
                attributeInfos.All(ai => ai.Action == ActionState.None))
                return;

            gbEntities.Enabled = false;
            gbAttributes.Enabled = false;
            toolStripMenu.Enabled = false;

            WorkAsync("Updating entities...",
                (bw, evt) =>
                {
                    foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                    {
                        if (ei.Action == ActionState.Added)
                        {
                            bw.ReportProgress(0,string.Format("Enabling entity '{0}' for audit...", ei.Emd.LogicalName));

                            ei.Emd.IsAuditEnabled.Value = true;
                        }
                        else if (ei.Action == ActionState.Removed)
                        {
                            bw.ReportProgress(0, string.Format("Disabling entity '{0}' for audit...", ei.Emd.LogicalName));

                            ei.Emd.IsAuditEnabled.Value = false;
                        }
                        else
                        {
                            continue;
                        }

                        var request = new UpdateEntityRequest { Entity = ei.Emd };
                        Service.Execute(request);

                        ei.Action = ActionState.None;
                    }

                    bw.ReportProgress(0, "Updating attributes...");

                    foreach (AttributeInfo ai in attributeInfos.OrderBy(a => a.Amd.EntityLogicalName).ThenBy(a => a.Amd.LogicalName))
                    {
                        if (ai.Action == ActionState.Added)
                        {
                            bw.ReportProgress(0, string.Format("Enabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                            ai.Amd.IsAuditEnabled.Value = true;
                        }
                        else if (ai.Action == ActionState.Removed)
                        {
                            bw.ReportProgress(0, string.Format("Disabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                            ai.Amd.IsAuditEnabled.Value = false;
                        }
                        else
                        {
                            continue;
                        }

                        var request = new UpdateAttributeRequest { Attribute = ai.Amd, EntityName = ai.Amd.EntityLogicalName };
                        Service.Execute(request);

                        ai.Action = ActionState.None;
                    }

                    bw.ReportProgress(0, "Publishing changes...");

                    var publishRequest = new PublishXmlRequest { ParameterXml = "<importexportxml><entities>" };

                    foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                    {
                        publishRequest.ParameterXml += string.Format("<entity>{0}</entity>", ei.Emd.LogicalName);
                    }

                    publishRequest.ParameterXml +=
                        "</entities><securityroles/><settings/><workflows/></importexportxml>";

                    Service.Execute(publishRequest);
                },
                evt =>
                {
                    if (evt.Error != null)
                    {
                        MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }

                    gbEntities.Enabled = true;
                    gbAttributes.Enabled = true;
                    toolStripMenu.Enabled = true;

                    tsbApplyChanges.Enabled = !((entityInfos.All(ei => ei.Action == ActionState.None) &&
                                          attributeInfos.All(ai => ai.Action == ActionState.None)));
                },
                evt => SetWorkingMessage(evt.UserState.ToString()));
        }
Exemplo n.º 22
0
        /// <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;
            }
        }
Exemplo n.º 23
0
        public void UpdateEntityData(BackgroundWorker w, bool bCountMode)
        {
            iEntityCount           = 0;
            iEntityUpdatedCount    = 0;
            iAttributeCount        = 0;
            iAttributeUpdatedCount = 0;

            if (bCountMode) //if this is count mode then initialise counter
            {
                iEntitiesOrAttributesToUpdate = 0;
            }

            LogInfo("Apply updates to CRM (if any)");

            foreach (string sKey in FileEntitySet.entities.Keys) //loop over entities read from file
            {
                iEntityCount++;
                if (CRMEntitySet.entities.ContainsKey(sKey)) //only do this if there is a corresponding entity in CRM - should almost always be so
                {
                    if (RemoveNulls(FileEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)) != RemoveNulls(CRMEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)))
                    {
                        //Entity description has changed so update it unless not updateable
                        if (!CRMEntitySet.entities[sKey].NotUpdateAble)
                        {
                            if (bCountMode)
                            {
                                iEntitiesOrAttributesToUpdate++;
                            }
                            else
                            {
                                string sDescription = FileEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString);
                                LogInfo2(string.Format("About to update entity {0} with description {1}", sKey, sDescription));
                                EntityMetadata entityMeta = new EntityMetadata()
                                {
                                    LogicalName = sKey,
                                    Description = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].LanguageCode)
                                };

                                UpdateEntityRequest UpdateRequest = new UpdateEntityRequest()
                                {
                                    Entity = entityMeta
                                };

                                UpdateEntityResponse updateResp = (UpdateEntityResponse)Service.Execute(UpdateRequest);
                                iEntityUpdatedCount++;
                                w.ReportProgress(-1, "Entity/attribute updated. Completed: " + ((iAttributeUpdatedCount + iEntityUpdatedCount) * 100 / iEntitiesOrAttributesToUpdate).ToString() + "%");
                            }
                        }
                        else
                        {
                            LogWarning("Entity description for " + sKey + " could not be updated as this is not permitted by CRM");
                        }
                    }
                    foreach (string sKey2 in FileEntitySet.entities[sKey].attributes.Keys)
                    {
                        iAttributeCount++;
                        if (CRMEntitySet.entities[sKey].attributes.ContainsKey(sKey2))        //only do this if attribute present
                        {
                            if (!CRMEntitySet.entities[sKey].attributes[sKey2].NotUpdateAble) //skip if not updateable
                            {
                                if (RemoveNulls(FileEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)) != RemoveNulls(CRMEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)))
                                {
                                    if (bCountMode)
                                    {
                                        iEntitiesOrAttributesToUpdate++;
                                    }
                                    else
                                    {
                                        string sDescription = FileEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString);
                                        LogInfo2(string.Format("About to update attribute {0} in entity {1} with description {2}", sKey2, sKey, sDescription));

                                        //Construct metadata. Note special for picklist
                                        if ((CRMEntitySet.entities[sKey].attributes[sKey2].attributeTypeDescription == "Picklist") &&
                                            CRMEntitySet.entities[sKey].attributes[sKey2].DefaultOptionSetValue != null)    //this shows that it is a picklist with non-default default
                                        {
                                            PicklistAttributeMetadata atttributeMeta = new PicklistAttributeMetadata()
                                            {
                                                LogicalName      = sKey2,
                                                Description      = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].attributes[sKey2].LanguageCode),
                                                DefaultFormValue = CRMEntitySet.entities[sKey].attributes[sKey2].DefaultOptionSetValue
                                            };
                                            UpdateAttributeRequest UpdateRequest = new UpdateAttributeRequest()
                                            {
                                                Attribute  = atttributeMeta,
                                                EntityName = sKey
                                            };
                                            iAttributeUpdatedCount++;
                                            UpdateAttributeResponse updateResp = (UpdateAttributeResponse)Service.Execute(UpdateRequest);
                                        }
                                        else
                                        {
                                            AttributeMetadata atttributeMeta = new AttributeMetadata()
                                            {
                                                LogicalName = sKey2,
                                                Description = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].attributes[sKey2].LanguageCode)
                                            };
                                            UpdateAttributeRequest UpdateRequest = new UpdateAttributeRequest()
                                            {
                                                Attribute  = atttributeMeta,
                                                EntityName = sKey
                                            };
                                            iAttributeUpdatedCount++;
                                            UpdateAttributeResponse updateResp = (UpdateAttributeResponse)Service.Execute(UpdateRequest);
                                        }
                                        w.ReportProgress(-1, "Entity/attribute updated. Completed: " + ((iAttributeUpdatedCount + iEntityUpdatedCount) * 100 / iEntitiesOrAttributesToUpdate).ToString() + "%");
                                    }
                                }
                            }
                            else
                            {
                                LogWarning("Skipping field " + sKey2 + " as not updateable");
                            }
                        }
                        else
                        {
                            LogWarning("Atttibute " + sKey2 + " in entity " + sKey + " from input file not found in CRM. This record will be ignored");
                        }
                    }
                }
                else
                {
                    LogWarning("Entity " + sKey + " from input file not found in CRM. This record will be ignored");
                }
            }
        }
Exemplo n.º 24
0
        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);
            }
        }
Exemplo n.º 25
0
        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);
            }
        }
Exemplo n.º 26
0
 private void SendEntityUpdateToSystem(UpdateEntityRequest message)
 {
     _queue.Enqueue(message);
 }
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var bw = (BackgroundWorker)sender;

            bw.ReportProgress(0, _retrievingMetadataStatus);

            //1. retrieve teamtemplate entity metadata
            //set attributes to exclude from the query
            List <string> IgnoredAttributes = new List <string> {
                "issystem"
            };

            //execute the teamtemplate entitymetadata request
            RetrieveEntityRequest entityreq = new RetrieveEntityRequest
            {
                LogicalName   = "teamtemplate",
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
            };
            RetrieveEntityResponse entityres = (RetrieveEntityResponse)_service.Execute(entityreq);

            //2. build and execute fetchxml to retrieve teamtemplate records
            string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";

            fetchXml += "<entity name='teamtemplate'>";

            foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
            {
                //only include attributes not in the ignore list
                if (!IgnoredAttributes.Contains(amd.LogicalName))
                {
                    fetchXml += "<attribute name='" + amd.LogicalName + "' />";
                }
            }
            fetchXml += "</entity></fetch>";

            bw.ReportProgress(0, _exportingStatus);
            EntityCollection exported = _service.RetrieveMultiple(new FetchExpression(fetchXml));


            //if we have any results
            if (exported.Entities.Count > 0)
            {
                bw.ReportProgress(0, _enablingAccessTeamStatus);

                //3. get list of unique objecttypecodes with access teams from source org
                List <int> objecttypeList = new List <int>();
                foreach (Entity entity in exported.Entities)
                {
                    if (!objecttypeList.Contains((int)entity["objecttypecode"]))
                    {
                        objecttypeList.Add((int)entity["objecttypecode"]);
                    }
                }

                //4. retrieve all entity metadata from target org so we can check whether to enable access teams
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters         = EntityFilters.Entity,
                    RetrieveAsIfPublished = false
                };
                RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_targetService.Execute(request);

                //5. loop through target entitymetadata results
                //create a list to store entities that are enabled for access teams
                List <int> enabledEntities = new List <int>();
                foreach (EntityMetadata emd in response.EntityMetadata)
                {
                    //if objecttypecode is in list from source org AND AutoCreateAccessTeams == false, set AutoCreateAccessTeams = true
                    //AutoCreateAccessTeams is nullable, so need to set separate enabled flag
                    bool enabled = false;
                    if (emd.AutoCreateAccessTeams.HasValue)
                    {
                        if ((bool)emd.AutoCreateAccessTeams)
                        {
                            //set the flag so we don't try to update it later
                            enabled = true;

                            //add it to the list of entities that are enabled for access teams
                            enabledEntities.Add((int)emd.ObjectTypeCode);
                        }
                    }

                    //6. update target entities to enable access teams if requested
                    if (objecttypeList.Contains((int)emd.ObjectTypeCode) && !enabled && enableTargetAccessTeamsCheckBox.Checked)
                    {
                        //6a. set the entity metadata AutoCreateAccessTeams value
                        emd.AutoCreateAccessTeams = true;
                        UpdateEntityRequest updateReq = new UpdateEntityRequest
                        {
                            Entity = emd,
                        };

                        //update the entity metadata
                        _targetService.Execute(updateReq);

                        //add it to the list of entities that are enabled for access teams
                        enabledEntities.Add((int)emd.ObjectTypeCode);
                    }
                }

                bw.ReportProgress(0, _importingStatus);

                //7. do the access team migration
                foreach (Entity entity in exported.Entities)
                {
                    //only copy team templates for entities that are enabled for access teams
                    if (enabledEntities.Contains((int)entity["objecttypecode"]))
                    {
                        try
                        {
                            //7a. try to update first
                            try
                            {
                                _targetService.Update(entity);
                            }
                            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                            {
                                //7b. if update fails, then create
                                _targetService.Create(entity);
                            }

                            //8. update our success counter
                            Interlocked.Increment(ref _counter);
                        }
                        catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //7c. if everything fails, return error
                            throw new Exception(string.Format(_rowErrorMessage, ex.Message, entity["teamtemplatename"]));
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        public async Task <IActionResult> PatchFile(Guid id, [FromBody] JsonPatchDocument <UpdateEntityRequest> request, int version)
        {
            BsonDocument filter = new OrganizeFilter(UserId.Value).ById(id);

            var permissions = await Database.GetCollection <dynamic>("Files").Aggregate().Match(filter)
                              .Lookup <BsonDocument, BsonDocument>(nameof(AccessPermissions), "_id", "_id", nameof(AccessPermissions))
                              .Unwind(nameof(AccessPermissions), new AggregateUnwindOptions <BsonDocument> {
                PreserveNullAndEmptyArrays = true
            })
                              .Project("{AccessPermissions:1}")
                              .FirstOrDefaultAsync();

            if (permissions is null)
            {
                return(NotFound());
            }

            var file = new UpdateEntityRequest()
            {
                Id = id
            };

            if (permissions.Contains(nameof(AccessPermissions)))
            {
                file.Permissions = BsonSerializer.Deserialize <AccessPermissions>(permissions[nameof(AccessPermissions)].AsBsonDocument);
            }

            request.ApplyTo(file);

            if (!string.IsNullOrEmpty(file.Name))
            {
                if (_invalidName.IsMatch(file.Name?.Trim() ?? string.Empty))
                {
                    Log.Error($"Invalid file name {file.Name}");
                    return(BadRequest());
                }

                Log.Information($"Renaming file {id} to { file.Name}");
                await _bus.Publish <RenameFile>(new
                {
                    Id              = id,
                    UserId          = UserId.Value,
                    NewName         = file.Name.Trim(),
                    ExpectedVersion = version
                });
            }

            if (file.Metadata.Any())
            {
                Log.Information($"Update metadata for file {id}");
                await _bus.Publish <UpdateMetadata>(new
                {
                    file.Metadata,
                    Id              = id,
                    UserId          = UserId.Value,
                    ExpectedVersion = version
                });
            }

            if (file.ParentId != Guid.Empty)
            {
                Log.Information($"Move file {id} to {file.ParentId}");
                await _bus.Publish <MoveFile>(new
                {
                    Id              = id,
                    UserId          = UserId.Value,
                    NewParentId     = file.ParentId,
                    ExpectedVersion = version
                });
            }

            if (request.Operations.Any(o => o.path.Contains("/Permissions")))
            {
                Log.Information($"Grant access to file {id}");
                await _bus.Publish <Generic.Domain.Commands.Files.GrantAccess>(new
                {
                    Id     = id,
                    UserId = UserId.Value,
                    file.Permissions
                });
            }

            return(Accepted());
        }
Exemplo n.º 29
0
 private void EntityUpdated(UpdateEntityRequest obj)
 {
     LastMessage = $"{DateTime.Now.ToString()}: Saved";
 }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// retrieves the Contact entity record, and then enables the document management
        /// for the entity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforRevert">When True, the user will be prompted to revert all
        /// the changes done in this sample.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforRevert)
        {
            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();

                    CreateRequiredRecords();

                    // Retrieve an entity for which you want to enable document management.
                    // In this sample, we will retrieve and enable document management
                    // for the Contact entity because by default, document management is
                    // not enabled for this entity.

                    RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.All,
                        LogicalName   = Contact.EntityLogicalName,

                        // Retrieve only the currently published changes, ignoring the changes
                        // that have not been published.
                        RetrieveAsIfPublished = false
                    };
                    RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    Console.WriteLine("Retrieved the contact entity.");

                    // Get the entity from the response.
                    EntityMetadata contactEntity = entityResponse.EntityMetadata;

                    // Enable document management for the retrieved entity.
                    contactEntity.IsDocumentManagementEnabled = true;

                    // Create an update request.
                    UpdateEntityRequest updateRequest = new UpdateEntityRequest
                    {
                        Entity = contactEntity
                    };
                    _serviceProxy.Execute(updateRequest);

                    // Publish the entity.
                    // All customizations must be published before they can be used.
                    PublishAllXmlRequest enableRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(enableRequest);

                    // Retrieve the contact entity, and verify that document management is enabled.
                    entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    contactEntity  = entityResponse.EntityMetadata;
                    if (contactEntity.IsDocumentManagementEnabled.Value == true)
                    {
                        Console.WriteLine("Enabled document management for the contact entity.");
                    }

                    RevertChanges(promptforRevert);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        private void UpdateCrm(string solutionName)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Updating CRM",
                Work    = (worker, args) =>
                {
                    bool publishRequired = false;
                    foreach (DataGridViewRow row in this.entityDataGrid.Rows)
                    {
                        SlimEntityMetadata metaData = row.DataBoundItem as SlimEntityMetadata;

                        if (metaData.ChangeTrackingEnabled)
                        {
                            bool selectedForChangeTrackingUpdate = false;
                            foreach (DataGridViewCell cell in row.Cells)
                            {
                                if (cell is DataGridViewCheckBoxCell && !(cell as DataGridViewCheckBoxCell).ReadOnly)
                                {
                                    selectedForChangeTrackingUpdate = true;
                                }
                            }

                            if (selectedForChangeTrackingUpdate)
                            {
                                publishRequired = true;
                                UpdateEntityRequest entrequest = new UpdateEntityRequest()
                                {
                                    Entity = new Microsoft.Xrm.Sdk.Metadata.EntityMetadata()
                                    {
                                        ChangeTrackingEnabled = true,
                                        LogicalName           = metaData.LogicalName,
                                    },
                                    SolutionUniqueName = solutionName
                                };

                                Service.Execute(entrequest);
                            }
                        }
                    }

                    if (publishRequired)
                    {
                        PublishAllXmlRequest pubCustomizationRequest = new PublishAllXmlRequest();
                        Service.Execute(pubCustomizationRequest);
                    }

                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
                    request.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity;
                    var response          = Service.Execute(request) as RetrieveAllEntitiesResponse;

                    List <SlimEntityMetadata> metadata = new List <SlimEntityMetadata>();
                    foreach (var ent in response.EntityMetadata
                             .Where(x => x.DisplayName != null && x.DisplayName.UserLocalizedLabel != null
                                    //&& x.IsValidForAdvancedFind != null && x.IsValidForAdvancedFind.Value
                                    && x.CanChangeTrackingBeEnabled != null && x.CanChangeTrackingBeEnabled.Value)
                             .OrderBy(x => x.DisplayName.UserLocalizedLabel.Label))
                    {
                        metadata.Add(new SlimEntityMetadata()
                        {
                            EntityName            = ent.DisplayName.UserLocalizedLabel.Label,
                            ChangeTrackingEnabled = ent.ChangeTrackingEnabled.HasValue && ent.ChangeTrackingEnabled.Value,
                            SchemaName            = ent.SchemaName,
                            LogicalName           = ent.LogicalName
                        });
                    }

                    args.Result = metadata;
                },
                // Work is completed, results can be shown to user
                PostWorkCallBack = (args) =>
                {
                    if (args.Error != null)
                    {
                        MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        // Binding result data to ListBox Control
                        entityDataGrid.Visible    = true;
                        entityDataGrid.DataSource = null;
                        this.unmanagedSolutionsList.DataSource = this.Solutions;

                        var lstResults            = (args.Result as List <SlimEntityMetadata>);
                        entityDataGrid.DataSource = lstResults;

                        for (int index = 0; index < lstResults.Count; index++)
                        {
                            var item = lstResults[index];
                            if (item.ChangeTrackingEnabled)
                            {
                                entityDataGrid.Rows[index].ReadOnly = true;

                                foreach (var cell in entityDataGrid.Rows[index].Cells)
                                {
                                    (cell as DataGridViewCell).Style.BackColor = Color.LightGray;
                                }
                            }
                        }
                    }

                    submitUpdateBtn.Visible        = true;
                    unmanagedSolutionsList.Visible = true;
                    unmanagedSolutionLabel.Visible = true;
                    loadMetadataButton.Visible     = false;
                },
                IsCancelable = false
            });
        }
Exemplo n.º 32
0
        /// <summary>
        /// Reverts any changes that were done by this sample.
        /// <param name="prompt">Indicates whether to prompt the user 
        /// to revert the changes done by this sample.</param>
        /// </summary>
        public void RevertChanges(bool prompt)
        {
            bool revertChanges = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these changes reverted? (y/n) [y]: ");
                String answer = Console.ReadLine();

                revertChanges = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
            }

            if (revertChanges)
            {
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName = Contact.EntityLogicalName,                    
                    RetrieveAsIfPublished = false
                };
                RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                
                EntityMetadata contactEntity = entityResponse.EntityMetadata;

                // Disable document management for the retrieved entity.
                contactEntity.IsDocumentManagementEnabled = false;

                UpdateEntityRequest updateRequest = new UpdateEntityRequest
                {
                    Entity = contactEntity
                };
                _serviceProxy.Execute(updateRequest);

                // Publish the customizations to the entity.                
                PublishAllXmlRequest disableRequest = new PublishAllXmlRequest();
                _serviceProxy.Execute(disableRequest);
                
                Console.WriteLine("Changes have been reverted.");
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// retrieves the Contact entity record, and then enables the document management 
        /// for the entity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforRevert">When True, the user will be prompted to revert all
        /// the changes done in this sample.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforRevert)
        {
            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();

                    CreateRequiredRecords();

                    //<snippetEnableDocumentManagement1>
                    // Retrieve an entity for which you want to enable document management.
                    // In this sample, we will retrieve and enable document management
                    // for the Contact entity because by default, document management is
                    // not enabled for this entity.                    
                    
                    RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.All,
                        LogicalName = Contact.EntityLogicalName,

                        // Retrieve only the currently published changes, ignoring the changes 
                        // that have not been published.
                        RetrieveAsIfPublished = false
                    };
                    RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    Console.WriteLine("Retrieved the contact entity.");

                    // Get the entity from the response.
                    EntityMetadata contactEntity = entityResponse.EntityMetadata;

                    // Enable document management for the retrieved entity.
                    contactEntity.IsDocumentManagementEnabled = true;

                    // Create an update request.                    
                    UpdateEntityRequest updateRequest = new UpdateEntityRequest
                    {
                        Entity = contactEntity                        
                    };
                    _serviceProxy.Execute(updateRequest);

                    // Publish the entity.
                    // All customizations must be published before they can be used.
                    PublishAllXmlRequest enableRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(enableRequest);                    

                    // Retrieve the contact entity, and verify that document management is enabled.
                    entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    contactEntity = entityResponse.EntityMetadata;
                    if (contactEntity.IsDocumentManagementEnabled.Value == true)
                    {
                        Console.WriteLine("Enabled document management for the contact entity.");
                    }                    

                    RevertChanges(promptforRevert);
                   //</snippetEnableDocumentManagement1>
                }

            }

            // 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, BackgroundWorker worker)
        {
            var rowsCount  = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;

            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 | EntityFilters.Relationships
                    };

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

                            emd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

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

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

                            emd.DisplayCollectionName.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

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

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

                            emd.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

                        columnIndex++;
                    }
                }
            }

            var entities = emds.Where(e => e.IsRenameable.Value).ToList();
            int i        = 0;

            foreach (var emd in entities)
            {
                var entityUpdate = new EntityMetadata();
                entityUpdate.LogicalName           = emd.LogicalName;
                entityUpdate.DisplayName           = emd.DisplayName;
                entityUpdate.Description           = emd.Description;
                entityUpdate.DisplayCollectionName = emd.DisplayCollectionName;

                try
                {
                    var request = new UpdateEntityRequest {
                        Entity = entityUpdate
                    };

                    service.Execute(request);

                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = true,
                        SheetName = sheet.Name
                    });
                }
                catch (Exception error)
                {
                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = false,
                        SheetName = sheet.Name,
                        Message   = $"{emd.LogicalName}: {error.Message}"
                    });
                }

                i++;
                worker.ReportProgressIfPossible(0, new ProgressInfo
                {
                    Item = i * 100 / entities.Count
                });
            }
        }
Exemplo n.º 35
0
        public async Task <IActionResult> PatchModel(Guid id, [FromBody] JsonPatchDocument <UpdateEntityRequest> request, int version)
        {
            Log.Information($"Updating model {id}");

            BsonDocument filter = new OrganizeFilter(UserId.Value).ById(id);

            var modelToUpdate = await Database.GetCollection <dynamic>("Models").Aggregate().Match(filter)
                                .Lookup <BsonDocument, BsonDocument>(nameof(AccessPermissions), "_id", "_id", nameof(AccessPermissions))
                                .Unwind(nameof(AccessPermissions), new AggregateUnwindOptions <BsonDocument> {
                PreserveNullAndEmptyArrays = true
            })
                                .Project("{AccessPermissions:1}")
                                .FirstOrDefaultAsync();

            if (modelToUpdate is null)
            {
                return(NotFound());
            }

            var model = new UpdateEntityRequest()
            {
                Id = id
            };

            if (modelToUpdate.Contains(nameof(AccessPermissions)))
            {
                model.Permissions = BsonSerializer.Deserialize <AccessPermissions>(modelToUpdate[nameof(AccessPermissions)].AsBsonDocument);
            }

            request.ApplyTo(model);

            if (!string.IsNullOrEmpty(model.Name))
            {
                if (_invalidName.IsMatch(model.Name?.Trim() ?? string.Empty))
                {
                    Log.Error($"Invalid model name {model.Name}");
                    return(BadRequest());
                }

                Log.Information($"Rename model {id} to { model.Name}");

                await _bus.Publish <UpdateModelName>(new
                {
                    Id              = id,
                    UserId          = UserId,
                    ModelName       = model.Name.Trim(),
                    ExpectedVersion = version
                });
            }

            if (model.ParentId != Guid.Empty)
            {
                Log.Information($"Move model {id} to {model.ParentId}");

                await _bus.Publish <MoveModel>(new
                {
                    Id              = id,
                    UserId          = UserId,
                    NewParentId     = model.ParentId,
                    ExpectedVersion = version
                });
            }

            if (request.Operations.Any(o => o.path.Contains("/Permissions")))
            {
                Log.Information($"Grant access to model {id}");
                await _bus.Publish <MachineLearning.Domain.Commands.GrantAccess>(new
                {
                    Id = id,
                    UserId,
                    model.Permissions
                });
            }

            return(Accepted());
        }
Exemplo n.º 36
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;
        }
Exemplo n.º 37
0
        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);
            }
        }
Exemplo n.º 38
0
        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);
            }
        }
 public async Task <TEntity> Handle(UpdateEntityRequest <TEntity, TKey> request, CancellationToken cancellationToken)
 {
     return(await _innerHandler.Handle(request, cancellationToken));
 }
Exemplo n.º 40
0
        /// <summary>
        ///     DOESN'T UPDATE PRIMARY FIELD - CALL THE CREATEORUPDATESTRING METHOD
        /// </summary>
        public void CreateOrUpdateEntity(string schemaName, string displayName, string displayCollectionName,
            string description, bool audit, string primaryFieldSchemaName,
            string primaryFieldDisplayName, string primaryFieldDescription,
            int primaryFieldMaxLength, bool primaryFieldIsMandatory, bool primaryFieldAudit, bool isActivityType,
            bool notes, bool activities, bool connections, bool mailMerge, bool queues)
        {
            lock (LockObject)
            {
                var metadata = new EntityMetadata();

                var exists = EntityExists(schemaName);
                if (exists)
                    metadata = GetEntityMetadata(schemaName);

                metadata.SchemaName = schemaName;
                metadata.LogicalName = schemaName;
                metadata.DisplayName = new Label(displayName, 1033);
                metadata.DisplayCollectionName = new Label(displayCollectionName, 1033);
                metadata.IsAuditEnabled = new BooleanManagedProperty(audit);
                metadata.IsActivity = isActivityType;
                metadata.IsValidForQueue = new BooleanManagedProperty(queues);
                metadata.IsMailMergeEnabled = new BooleanManagedProperty(mailMerge);
                metadata.IsConnectionsEnabled = new BooleanManagedProperty(connections);
                metadata.IsActivity = isActivityType;
                if (!String.IsNullOrWhiteSpace(description))
                    metadata.Description = new Label(description, 1033);

                if (exists)
                {
                    var request = new UpdateEntityRequest
                    {
                        Entity = metadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                }
                else
                {
                    metadata.OwnershipType = OwnershipTypes.UserOwned;

                    var primaryFieldMetadata = new StringAttributeMetadata();
                    SetCommon(primaryFieldMetadata, primaryFieldSchemaName, primaryFieldDisplayName,
                        primaryFieldDescription,
                        primaryFieldIsMandatory, primaryFieldAudit, true);
                    primaryFieldMetadata.MaxLength = primaryFieldMaxLength;

                    var request = new CreateEntityRequest
                    {
                        Entity = metadata,
                        PrimaryAttribute = primaryFieldMetadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                    RefreshFieldMetadata(primaryFieldSchemaName, schemaName);
                }
                RefreshEntityMetadata(schemaName);
            }
        }
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var bw = (BackgroundWorker)sender;

            bw.ReportProgress(0, _retrievingMetadataStatus);

            //1. retrieve teamtemplate entity metadata
            //set attributes to exclude from the query
            List<string> IgnoredAttributes = new List<string> { "issystem" };

            //execute the teamtemplate entitymetadata request
            RetrieveEntityRequest entityreq = new RetrieveEntityRequest
            {
                LogicalName = "teamtemplate",
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
            };
            RetrieveEntityResponse entityres = (RetrieveEntityResponse)_service.Execute(entityreq);

            //2. build and execute fetchxml to retrieve teamtemplate records
            string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
            fetchXml += "<entity name='teamtemplate'>";

            foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
            {
                //only include attributes not in the ignore list
                if (!IgnoredAttributes.Contains(amd.LogicalName))
                {
                    fetchXml += "<attribute name='" + amd.LogicalName + "' />";
                }
            }
            fetchXml += "</entity></fetch>";

            bw.ReportProgress(0, _exportingStatus);
            EntityCollection exported = _service.RetrieveMultiple(new FetchExpression(fetchXml));


            //if we have any results
            if (exported.Entities.Count > 0)
            {
                bw.ReportProgress(0, _enablingAccessTeamStatus);

                //3. get list of unique objecttypecodes with access teams from source org
                List<int> objecttypeList = new List<int>();
                foreach (Entity entity in exported.Entities)
                {
                    if (!objecttypeList.Contains((int)entity["objecttypecode"]))
                    {
                        objecttypeList.Add((int)entity["objecttypecode"]);
                    }
                }

                //4. retrieve all entity metadata from target org so we can check whether to enable access teams
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters = EntityFilters.Entity,
                    RetrieveAsIfPublished = false
                };
                RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_targetService.Execute(request);

                //5. loop through target entitymetadata results
                //create a list to store entities that are enabled for access teams
                List<int> enabledEntities = new List<int>();
                foreach (EntityMetadata emd in response.EntityMetadata)
                {
                    //if objecttypecode is in list from source org AND AutoCreateAccessTeams == false, set AutoCreateAccessTeams = true
                    //AutoCreateAccessTeams is nullable, so need to set separate enabled flag
                    bool enabled = false;
                    if (emd.AutoCreateAccessTeams.HasValue)
                    {
                        if ((bool)emd.AutoCreateAccessTeams)
                        {
                            //set the flag so we don't try to update it later
                            enabled = true;

                            //add it to the list of entities that are enabled for access teams
                            enabledEntities.Add((int)emd.ObjectTypeCode);
                        }
                    }

                    //6. update target entities to enable access teams if requested
                    if (objecttypeList.Contains((int)emd.ObjectTypeCode) && !enabled && enableTargetAccessTeamsCheckBox.Checked)
                    {
                        //6a. set the entity metadata AutoCreateAccessTeams value
                        emd.AutoCreateAccessTeams = true;
                        UpdateEntityRequest updateReq = new UpdateEntityRequest
                        {
                            Entity = emd,
                        };

                        //update the entity metadata
                        _targetService.Execute(updateReq);

                        //add it to the list of entities that are enabled for access teams
                        enabledEntities.Add((int)emd.ObjectTypeCode);
                    }
                }

                bw.ReportProgress(0, _importingStatus);

                //7. do the access team migration
                foreach (Entity entity in exported.Entities)
                {
                    //only copy team templates for entities that are enabled for access teams
                    if (enabledEntities.Contains((int)entity["objecttypecode"]))
                    { 
                        try
                        {
                            //7a. try to update first
                            try
                            {
                                _targetService.Update(entity);
                            }
                            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
                            {
                                //7b. if update fails, then create
                                _targetService.Create(entity);
                            }

                            //8. update our success counter
                            Interlocked.Increment(ref _counter);
                        }
                        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //7c. if everything fails, return error
                            throw new Exception(string.Format(_rowErrorMessage, ex.Message, entity["teamtemplatename"]));
                        }
                    }
                }
            }
        }