/// <summary>
        /// Reactivate an Entity Key 
        /// </summary>
        /// <param name="service"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<string> ReactivateEntityKey(IOrganizationService service, EntityKeyMetadata key) {

            try {
                // call the Activate action for the selected key 
                var req = new ReactivateEntityKeyRequest() {
                    EntityKeyLogicalName = key.SchemaName,
                    EntityLogicalName = key.EntityLogicalName
                };

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

                return null;
            }
            catch(Exception ex)
            {
                return new List<string>() {$"Error reactivating key {key.SchemaName}: \n{ex.Message}" };
            }
        }
Exemple #2
0
        /// <summary>
        /// Alternate keys may not be active immediately after a solution defining them is installed.
        /// This method polls the metadata for a specific entity
        /// to delay execution of the rest of the sample until the alternate keys are ready.
        /// </summary>
        /// <param name="service">Specifies the service to connect to.</param>
        /// <param name="asyncJob">The system job that creates the index to support the alternate key</param>
        /// <param name="iteration">The number of times this method has been called.</param>
        ///
        private static bool VerifyBookCodeKeyIsActive(IOrganizationService service, EntityReference asyncJob = null, int iteration = 0)
        {
            if (iteration > 5)
            {
                //Give up
                return(false);
            }


            if (iteration == 0) //only the first time
            {
                //Get whether the Entity Key index is active from the metadata
                EntityQueryExpression entityQuery = new EntityQueryExpression();
                entityQuery.Criteria = new MetadataFilterExpression(LogicalOperator.And)
                {
                    Conditions = { { new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, "sample_book") } }
                };

                entityQuery.Properties = new MetadataPropertiesExpression("Keys");

                RetrieveMetadataChangesRequest metadataRequest = new RetrieveMetadataChangesRequest()
                {
                    Query = entityQuery
                };
                RetrieveMetadataChangesResponse metadataResponse = (RetrieveMetadataChangesResponse)service.Execute(metadataRequest);
                EntityKeyMetadata bookcodekey = metadataResponse.EntityMetadata.FirstOrDefault().Keys.FirstOrDefault();

                if (bookcodekey.EntityKeyIndexStatus == EntityKeyIndexStatus.Active)
                {
                    return(true);
                }
                else
                {
                    iteration++;
                    return(VerifyBookCodeKeyIsActive(service, bookcodekey.AsyncJob, iteration));
                }
            }
            else
            {
                //Check the status of the system job that is should indicate that the alternate key index is active.
                AsyncOperation systemJob = (AsyncOperation)service.Retrieve(asyncJob.LogicalName, asyncJob.Id, new ColumnSet("statecode", "statuscode"));

                if (systemJob.StateCode == AsyncOperationState.Completed) //Completed
                {
                    if (!systemJob.StatusCode.Value.Equals(30))           //Not Succeeded
                    {
                        //Delete the system job and try to reactivate
                        service.Delete(asyncJob.LogicalName, asyncJob.Id);

                        ReactivateEntityKeyRequest reactivateRequest = new ReactivateEntityKeyRequest()
                        {
                            EntityLogicalName    = "sample_book",
                            EntityKeyLogicalName = "sample_bookcode"
                        };
                        ReactivateEntityKeyResponse reactivateResponse = (ReactivateEntityKeyResponse)service.Execute(reactivateRequest);

                        //Get the system job created by the reactivate request
                        QueryByAttribute systemJobQuery = new QueryByAttribute("asyncoperation");
                        systemJobQuery.AddAttributeValue("primaryentitytype", "sample_book");
                        systemJobQuery.AddOrder("createdon", OrderType.Descending);
                        systemJobQuery.TopCount  = 1;
                        systemJobQuery.ColumnSet = new ColumnSet("asyncoperationid", "name");

                        EntityCollection systemJobs = service.RetrieveMultiple(systemJobQuery);
                        asyncJob = systemJobs.Entities.FirstOrDefault().ToEntityReference();

                        iteration++;
                        return(VerifyBookCodeKeyIsActive(service, asyncJob, iteration));
                    }
                    else
                    {
                        //It succeeded
                        return(true);
                    }
                }
                else
                {
                    //Give it more time to complete
                    Thread.Sleep(TimeSpan.FromSeconds(30));
                    iteration++;
                    return(VerifyBookCodeKeyIsActive(service, asyncJob, iteration));
                }
            }
        }