private void AssignAdminRole(IOrganizationService service, Guid id)
        {
            string adminRoleName = "System Administrator";
            try
            {
                QueryExpression query = new QueryExpression
                {
                    EntityName = "role",
                    ColumnSet = new ColumnSet("name"),
                    Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                                AttributeName = "name",
                                Operator = ConditionOperator.Equal,
                                Values = {adminRoleName}
                        }
                    }
                }
                };
                EntityCollection roles = service.RetrieveMultiple(query);
                EntityReferenceCollection entityRefCln = new EntityReferenceCollection();
                foreach (Entity entity in roles.Entities)
                {
                        entityRefCln.Add(entity.ToEntityReference());
                }
                service.Associate("team", id, new Relationship("teamroles_association"), entityRefCln);
            }
            catch (Exception ex)
            {

            }
        }
Exemple #2
0
 /// <summary>
 /// </summary>
 /// <param name="entityName"></param>
 /// <param name="entityId"></param>
 /// <param name="relationship"></param>
 /// <param name="relatedEntities"></param>
 /// <exception cref="NotImplementedException"></exception>
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     if (this.Original != null)
     {
         this.Original.Associate(entityName, entityId, relationship, relatedEntities);
     }
 }
 public virtual void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     CapturedInput.EntityId = entityId;
     CapturedInput.EntityName = entityName;
     CapturedInput.Relationship = relationship;
     CapturedInput.RelatedEntities = relatedEntities;
 }
Exemple #4
0
        public void ApplyRulesToUser(EntityReferenceCollection ec, Guid userId)
        {
            var request = new InstantiateFiltersRequest
            {
                UserId = userId,
                TemplateCollection = ec
            };

            service.Execute(request);
        }
        /// <summary>
        /// Binds the references to those already in the data store (or skips those which are new).
        /// </summary>
        /// <param name="references">The collection of references to be bound.</param>
        public virtual void BindReferences(EntityReferenceCollection references)
        {
            // TODO: Comment out logging
            // Logging commented out to boost performance
            using (LogGroup logGroup = LogGroup.Start("Binding the provided references with those in the data store.", LogLevel.Debug))
            {
                if (references == null)
                    throw new ArgumentNullException("references");

                LogWriter.Debug("Total #: " + references.Count.ToString());

                for (int i = 0; i < references.Count; i++)
                {
                    EntityReference reference = references[i];

                    bool isBound = DataAccess.Data.IsBound(reference);
                    bool exists = DataAccess.Data.IsStored(reference);

                    if (exists && !isBound)
                    {
                        LogWriter.Debug("Already exists: " + exists.ToString());

                        Type type1 = EntityState.GetType(reference.Type1Name);
                        Type type2 = EntityState.GetType(reference.Type2Name);

                        EntityReference foundReference = DataAccess.Data.Referencer
                            .GetReference(type1,
                                          reference.Entity1ID,
                                          reference.Property1Name,
                                          type2,
                                          reference.Entity2ID,
                                          reference.Property2Name,
                                          false);

                        if (foundReference != null)
                        {
                            // Copy the unbound info to the bound object
                            references[i].CopyTo(foundReference);

                            // Put the bound object back into the list in place of the unbound object
                            references[i] = foundReference;

                            LogWriter.Debug("Found corresponding reference. Binding.");
                        }
                        else
                            throw new Exception("Reference matched IsStored check but failed to load.");
                    }
                    else
                        LogWriter.Debug("Doesn't exist. Skipping.");
                }
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create a team, a queue and a role.
        /// Add read queue privileges to the role.
        /// Assign the role to the team so that they can read the queue.
        /// Assign the queue to the team.
        /// Optionally delete any entity records that were created for this sample.
         /// </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))
                {
                    _service = (IOrganizationService)_serviceProxy;

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetAssociateDisassociateDE1>
                    // The account ID would typically be passed in as an argument or determined by a query.
                    // The contact ID would typically be passed in as an argument or determined by a query.
                    // Associate the accounts to the contact record.

                    //Create a collection of the entity ids that will be associated to the contact.
                    EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                    relatedEntities.Add(new EntityReference("account", _account1Id));
                    relatedEntities.Add(new EntityReference("account", _account2Id));
                    relatedEntities.Add(new EntityReference("account", _account3Id));

                    // Create an object that defines the relationship between the contact and account.
                    Relationship relationship = new Relationship("account_primary_contact");

                    //Associate the contact with the 3 accounts.
                    _service.Associate("contact", _contactId, relationship, relatedEntities);

                    Console.WriteLine("The entities have been associated.");

                    //Disassociate the records.
                    _service.Disassociate("contact", _contactId, relationship, relatedEntities);

                    //</snippetAssociateDisassociateDE1>

                    Console.WriteLine("The entities have been disassociated.");

                    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;
            }
        }
        /// <summary>
        /// Deletes the provided obsolete references.
        /// </summary>
        /// <param name="references">The array of references to delete.</param>
        public virtual void DeleteObsoleteReferences(EntityReferenceCollection references)
        {
            using (LogGroup logGroup2 = LogGroup.Start("Deleting provided obsolete references.", LogLevel.Debug))
            {
                LogWriter.Debug("References: " + references.Count);

                foreach (EntityReference reference in references)
                {
                    if (DataAccess.Data.IsStored(reference))
                    {
                        LogWriter.Debug("Deleting reference.");
                        DataAccess.Data.Stores[reference].Deleter.Delete((IEntity)reference);
                    }
                    else
                        LogWriter.Debug("Reference not stored. Skipping.");
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Create an email record using the given dictionary to replace dynamic fields
        /// </summary>
        /// <param name="templateName">Name of existing Email template</param>
        /// <param name="userId">User GUID that will be used to Instantiate Template. See CRM SDK InstantiateTemplateRequest</param>
        /// <param name="dictionary">[Optional] Collection of dynamic fields within the template to be replaced</param>
        /// <param name="context">[Optional] Exisiting CRM record that sets the root context where dynamics
        /// fields values within the template will be taken from</param>
        /// <param name="regarding">[Optional] Email regarding record</param>
        /// <param name="from">Email sender (activityparty record type)</param>
        /// <param name="toRecipient">List of recipients (activityparty record type)</param>
        /// <param name="attachments">List of attachment names (e.g. "DXTools - Payments.pdf")</param>
        /// <param name="allowDuplicateAttachments">
        /// If allowDuplicateAttachments = True, two or more attachments are allowed with the same filename
        /// </param>
        /// <param name="onlyAttachmentsInTemplate">
        /// If onlyUseAttachmentsInTemplate = True, the attachments to be considered will be only the ones
        /// in the given template. Otherwise, it will search across any attachment
        /// </param>
        /// <returns>New Email record</returns>
        public Entity CreateEmail(string templateName, Guid userId, Dictionary <string, string> dictionary, EntityReference context, EntityReference regarding, EntityReference from, EntityReferenceCollection toRecipient, string[] attachments, bool allowDuplicateAttachments, bool onlyUseAttachmentsInTemplate)
        {
            Entity template = RetrieveEmailTemplate(templateName);

            Entity email = GetEmailInstantiateFromTemplate(template, userId);

            ProcessEmailText(email, dictionary, context);

            CreateEmail(email, regarding, from, toRecipient);

            CreateActivityMimeAttachments(template, email, attachments, allowDuplicateAttachments, onlyUseAttachmentsInTemplate);

            return(email);
        }
Exemple #9
0
 /// <summary>
 /// Create an email record using the given dictionary to replace dynamic fields
 /// </summary>
 /// <param name="templateName">Name of existing Email template</param>
 /// <param name="userId">User GUID that will be used to Instantiate Template. See CRM SDK InstantiateTemplateRequest</param>
 /// <param name="context">Exisiting CRM record that sets the root context where dynamics
 /// fields values within the template will be taken from</param>
 /// <param name="regarding">[Optional] Email regarding record</param>
 /// <param name="from">Email sender (activityparty record type)</param>
 /// <param name="toRecipient">List of recipients (activityparty record type)</param>
 /// <param name="attachments">List of attachment names (e.g. "DXTools - Payments.pdf")</param>
 /// <param name="allowDuplicateAttachments">
 /// If allowDuplicateAttachments = True, two or more attachments are allowed with the same filename
 /// </param>
 /// <param name="onlyUseAttachmentsInTemplate">
 /// If onlyAttachmentsInTemplate = True, the attachments to be considered will be only the ones
 /// in the given template. Otherwise, it will search across any attachment
 /// </param>
 /// <returns>New Email record</returns>
 public Entity CreateEmail(string templateName, Guid userId, EntityReference context, EntityReference regarding, EntityReference from, EntityReferenceCollection toRecipient, string[] attachments, bool allowDuplicateAttachments, bool onlyUseAttachmentsInTemplate)
 {
     return(CreateEmail(templateName, userId, null, context, regarding, from, toRecipient, attachments, allowDuplicateAttachments, onlyUseAttachmentsInTemplate));
 }
Exemple #10
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Verify if knowledge management is enabled for the
        /// Incident entity.
        /// Create sample records (account and incident).
        /// Create a knowledge base record.
        /// Associate the knowledge base record to entity record.
        /// Dissociate the knowledge base record from entity record.
        /// Optionally delete/revert any records
        /// that were created/changed for this sample.
        /// </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();

                    if (CheckCRMVersion() == true)
                    {
                        // Check if knowledge management is enabled
                        // for the Incident entity.
                        CheckKnowledgeManagementStatus();

                        // Create required records for the sample.
                        CreateRequiredRecords();

                        // Create a knowledge base record instance
                        KnowledgeBaseRecord kbRecord = new KnowledgeBaseRecord
                        {
                            // These are sample values. Replace them with
                            // appropriate values as per your integrated
                            // Parature  instance.
                            PrivateUrl = "https://www.demo.parature.com/internal",
                            PublicUrl  = "https://www.demo.parature.com",
                            Title      = "How to track shipping?",
                            UniqueId   = "8000/8467/Article/23782"
                        };
                        _kbRecordId = _serviceProxy.Create(kbRecord);
                        Console.WriteLine("Created knowledge base record with ID: '{0}'.\n", _kbRecordId.ToString());

                        // Associate the knowledge base record with an incident record

                        // Step 1: Create a collection of knowledge base record that will be
                        // associated to the incident. In this case, we have only a single
                        // knowledge base record to be associated.
                        EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                        relatedEntities.Add(new EntityReference(KnowledgeBaseRecord.EntityLogicalName, _kbRecordId));

                        // Step 2: Create an object that defines the relationship between knowledge base record and incident.
                        // Use the many-to-many relationship name (KnowledgeBaseRecord_Incident) between knowledge base
                        // record and incident.
                        Relationship relationship = new Relationship("KnowledgeBaseRecord_Incident");

                        // Step 3: Associate the knowledge base record with the incident record.
                        _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId, relationship,
                                                relatedEntities);

                        // Check to see if the association record is created in the
                        // IncidentKnowledgeBaseRecord intersect entity
                        QueryExpression associationQuery = new QueryExpression
                        {
                            EntityName = IncidentKnowledgeBaseRecord.EntityLogicalName,
                            ColumnSet  = new ColumnSet("incidentid", "knowledgebaserecordid"),
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "incidentid",
                                        Operator      = ConditionOperator.Equal,
                                        Values        = { _incidentId }
                                    },
                                    new ConditionExpression
                                    {
                                        AttributeName = "knowledgebaserecordid",
                                        Operator      = ConditionOperator.Equal,
                                        Values        = { _kbRecordId }
                                    }
                                }
                            },
                            PageInfo = new PagingInfo
                            {
                                PageNumber = 1,
                                Count      = 1
                            }
                        };

                        DataCollection <Entity> entityCollection = _serviceProxy.RetrieveMultiple(associationQuery).Entities;
                        if (entityCollection.Count() > 0)
                        {
                            Console.WriteLine("Associated knowledge base record with the incident record.");

                            // Disassociate the records.
                            _serviceProxy.Disassociate(Incident.EntityLogicalName, _incidentId, relationship,
                                                       relatedEntities);
                            Console.WriteLine("Disasociated knowledge base record from the incident record.\n");
                        }
                        else
                        {
                            Console.WriteLine("Could not associate knowledge base record with the incident record.\n");
                        }

                        // Prompt the user to delete the records and attribute created by the sample.
                        DeleteRequiredRecords(promptForDelete);
                    }
                    else
                    {
                        Console.WriteLine("Aborting the sample.");
                    }
                }
            }

            // 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 abstract IEntity[] GetEntitiesWithReference(IEntity entity, string propertyName, EntityReferenceCollection references);
Exemple #12
0
        /// <summary>internal</summary>
        protected internal virtual void AssociateCore(
            string entityName,
            Guid entityId,
            Relationship relationship,
            EntityReferenceCollection relatedEntities)
        {
            bool?retry = new bool?();

            do
            {
                bool forceClose = false;
                try
                {
                    using (new OrganizationServiceContextInitializer(this))
                    {
                        this.ServiceChannel.Channel.Associate(entityName, entityId, relationship, relatedEntities);
                        break;
                    }
                }
                catch (MessageSecurityException ex)
                {
                    forceClose = true;
                    retry      = this.ShouldRetry(ex, retry);
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                }
                catch (EndpointNotFoundException ex)
                {
                    forceClose = true;
                    retry      = new bool?(this.HandleFailover(retry));
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                }
                catch (TimeoutException ex)
                {
                    forceClose = true;
                    retry      = new bool?(this.HandleFailover(retry));
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    forceClose = true;
                    retry      = this.HandleFailover((BaseServiceFault)ex.Detail, retry);
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                }
                catch
                {
                    forceClose = true;
                    throw;
                }
                finally
                {
                    this.CloseChannel(forceClose);
                }
            }while (retry.HasValue && retry.Value);
        }
Exemple #13
0
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     throw new NotImplementedException();
 }
        protected internal Guid CreateEntity(Entity e)
        {
            if (e == null)
            {
                throw new InvalidOperationException("The entity must not be null");
            }

            var clone = e.Clone(e.GetType());

            if (clone.Id == Guid.Empty)
            {
                clone.Id = Guid.NewGuid(); // Add default guid if none present
            }

            // Hack for Dynamic Entities where the Id property doesn't populate the "entitynameid" primary key
            var primaryKeyAttribute = $"{e.LogicalName}id";

            if (!clone.Attributes.ContainsKey(primaryKeyAttribute))
            {
                clone[primaryKeyAttribute] = clone.Id;
            }

            ValidateEntity(clone);

            // Create specific validations
            if (clone.Id != Guid.Empty && Data.ContainsKey(clone.LogicalName) &&
                Data[clone.LogicalName].ContainsKey(clone.Id))
            {
                throw new InvalidOperationException($"There is already a record of entity {clone.LogicalName} with id {clone.Id}, can't create with this Id.");
            }

            // Create specific validations
            if (clone.Attributes.ContainsKey("statecode"))
            {
                throw new InvalidOperationException($"When creating an entity with logical name '{clone.LogicalName}', or any other entity, it is not possible to create records with the statecode property. Statecode must be set after creation.");
            }

            AddEntityWithDefaults(clone, false, this.UsePipelineSimulation);

            if (e.RelatedEntities.Count > 0)
            {
                foreach (var relationshipSet in e.RelatedEntities)
                {
                    var relationship = relationshipSet.Key;

                    var entityReferenceCollection = new EntityReferenceCollection();

                    foreach (var relatedEntity in relationshipSet.Value.Entities)
                    {
                        var relatedId = CreateEntity(relatedEntity);
                        entityReferenceCollection.Add(new EntityReference(relatedEntity.LogicalName, relatedId));
                    }

                    if (FakeMessageExecutors.ContainsKey(typeof(AssociateRequest)))
                    {
                        var request = new AssociateRequest
                        {
                            Target          = clone.ToEntityReference(),
                            Relationship    = relationship,
                            RelatedEntities = entityReferenceCollection
                        };
                        FakeMessageExecutors[typeof(AssociateRequest)].Execute(request, this);
                    }
                    else
                    {
                        throw PullRequestException.NotImplementedOrganizationRequest(typeof(AssociateRequest));
                    }
                }
            }

            return(clone.Id);
        }
 public virtual void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     Service.Disassociate(entityName, entityId, relationship, relatedEntities);
 }
        private void Disassociate(CrmDbContext context, ContentMap map, EntityReference target, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            target.ThrowOnNull("target");
            relationship.ThrowOnNull("relationship");
            relatedEntities.ThrowOnNull("relatedEntities");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Target: LogicalName={0}, Id={1}", EntityNamePrivacy.GetEntityName(target.LogicalName), target.Id));
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Relationship: SchemaName={0}, PrimaryEntityRole={1}", relationship.SchemaName, relationship.PrimaryEntityRole));

            foreach (var entity in relatedEntities)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Related: LogicalName={0}, Id={1}", EntityNamePrivacy.GetEntityName(entity.LogicalName), entity.Id));
            }

            var entities = new List <EntityReference>();

            if (this.EventHubJobSettings.IsEnabled)
            {
                //logic to ignore to get Intersect entity which we already have in eventhub model.
                EntityReference intersectEntity = new EntityReference();
                intersectEntity.LogicalName = target.LogicalName;
                intersectEntity.Id          = target.Id;
                entities.Add(intersectEntity);
            }
            else
            {
                // validate that the relationships do in fact not exist by querying for the intersects
                entities = map.Using(ContentMapLockType.Read, () => RetrieveDisassociatedIntersectEntities(context, map, target, relationship, relatedEntities).ToList());
            }

            if (entities != null)
            {
                // add intersect entities to the content map

                map.Using(ContentMapLockType.Write, () => map.RemoveRange(entities));
            }
        }
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     this.ExecuteSoapRequest <DisassociateRequest, DisassociateResponse>(
         new DisassociateRequest(entityName, entityId, relationship, relatedEntities));
 }
 public virtual void Disassociate(ContentMap map, EntityReference target, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     using (var context = this.CreateContext())
     {
         this.Disassociate(context, map, target, relationship, relatedEntities);
     }
 }
        private static void Associate(CrmDbContext context, ContentMap map, EntityReference target, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            target.ThrowOnNull("target");
            relationship.ThrowOnNull("relationship");
            relatedEntities.ThrowOnNull("relatedEntities");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Target: LogicalName={0}, Id={1}", EntityNamePrivacy.GetEntityName(target.LogicalName), target.Id));
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Relationship: SchemaName={0}, PrimaryEntityRole={1}", relationship.SchemaName, relationship.PrimaryEntityRole));

            foreach (var entity in relatedEntities)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Related: LogicalName={0}, Id={1}", EntityNamePrivacy.GetEntityName(entity.LogicalName), entity.Id));
            }

            // validate that the relationships do in fact exist by querying for the intersects

            var entities = map.Using(ContentMapLockType.Read, () => RetrieveIntersectEntities(context, map, target, relationship, relatedEntities));

            if (entities != null)
            {
                // add intersect entities to the content map

                map.Using(ContentMapLockType.Write, () => map.AddRange(entities));

                foreach (var added in entities)
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Added: LogicalName={0}, Id={1}", EntityNamePrivacy.GetEntityName(added.LogicalName), added.Id));
                }
            }
        }
        /// <summary>
        /// Creates the Association
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="entityName">Type: String. The logical name of the entity that is specified in the <paramref name="entityId" /> parameter.</param>
        /// <param name="entityId">Type: Guid. The Id of the record to which the related records are associated.</param>
        /// <param name="relationship">Type: <see cref="T:Microsoft.Xrm.Sdk.Relationship" />. The name of the relationship to be used to create the link.</param>
        /// <param name="relatedEntities">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityReferenceCollection" />. A collection of entity references (references to records) to be associated.</param>
        public Guid[] CreateAssociation(IOrganizationService service, string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            if (!DefinitionsByRelationshipName.TryGetValue(relationship.SchemaName, out var definition))
            {
                throw new KeyNotFoundException($"Schema name {relationship.SchemaName} was not found in the DefinitionsByRelationshipName dictionary.");
            }

            var primaryAttributeName = entityName == definition.PrimaryEntityType
                ? definition.PrimaryEntityIdName
                : definition.AssociatedEntityIdName;
            var associatedAttributeName = entityName == definition.PrimaryEntityType
                ? definition.AssociatedEntityIdName
                : definition.PrimaryEntityIdName;
            var ids = new List <Guid>();

            foreach (var relation in relatedEntities.Select(relatedEntity => new Entity(definition.AssociationLogicalName)
            {
                [primaryAttributeName] = entityId,
                [associatedAttributeName] = relatedEntity.Id
            }))
            {
                ids.Add(service.Create(relation));
            }

            return(ids.ToArray());
        }
 internal IAsyncResult BeginAssociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, AsyncCallback callback, object asyncState, CancellationToken cancellationToken)
 => AsyncCallOperation <int> .Begin("Associate", callback, asyncState, cancellationToken,
                                    createContext : () => new OrganizationServiceContextInitializer(this),
                                    tryBegin : TryRun,
                                    tryEnd : TryRun,
                                    beginOperation : (_callback, _state) => base.ServiceChannel.Channel.BeginAssociate(entityName, entityId, relationship, relatedEntities, _callback, _state),
                                    endOperation : (_asynResult) => { base.ServiceChannel.Channel.EndAssociate(_asynResult); return(0); },
                                    cancelOperation : (_asyncResult) => base.ServiceChannel.Abort());
        /// <inheritdoc />
        public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            var message = Settings.LogDetailedRequests
                ? $"Disassociate Request for {entityName}, with Id {entityId}, Relationship {relationship.SchemaName}, and Related Entities {relatedEntities.Select(e => e.ToStringDebug()).ToCsv()}."
                : "Disassociate Request";

            if (Settings.TimeRequests)
            {
                var timer = new Stopwatch();
                try
                {
                    TraceStart(message);
                    timer.Start();
                    Service.Disassociate(entityName, entityId, relationship, relatedEntities);
                    return;
                }
                finally
                {
                    TraceEnd(timer);
                }
            }

            TraceExecute(message);
            Service.Disassociate(entityName, entityId, relationship, relatedEntities);
        }
        /// <summary>
        /// Imports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        private void Import(NtoNAssociationsTransportProfile profile, string transportReportFileName)
        {
            int totalTreatedRecords = 0;
            int totalImportFailures = 0;
            int totalImportSuccess = 0;
            int ReconnectionRetryCount = 5;

            try
            {
                NtoNTransportReport report = new NtoNTransportReport(transportReportFileName);
                //Get Transport Report
                if (File.Exists(transportReportFileName))
                {
                    report = ReadTransportReport(transportReportFileName);
                }

                MSCRMConnection connection = profile.getTargetConneciton(); ;
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                LogManager.WriteLog("Start importing data in " + connection.ConnectionName);

                //Mesure import time
                DateTime importStartDT = DateTime.Now;

                //es = ReadEnvStructure(profile.SourceConnectionName);

                foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships)
                {
                    //Check if there are any records to import
                    if (ee.ExportedRecords == 0)
                    {
                        continue;
                    }

                    //Mesure import time
                    DateTime entityImportStartDT = DateTime.Now;

                    string entityFolderPath = Folder + "\\" + profile.ProfileName + "\\Data\\" + ee.RelationshipSchemaName;
                    string[] filePaths = Directory.GetFiles(entityFolderPath, "*.xml");

                    LogManager.WriteLog("Importing " + ee.RelationshipSchemaName + " records.");
                    int treatedRecordsForEntity = 0;
                    int importedRecordsForEntity = 0;
                    int importFailuresForEntity = 0;

                    foreach (string filePath in filePaths)
                    {
                        List<Type> knownTypes = new List<Type>();
                        knownTypes.Add(typeof(Entity));

                        XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas();
                        XRQ.MaxStringContentLength = int.MaxValue;

                        using(FileStream fs = new FileStream(filePath, FileMode.Open))
                        using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ))
                        {
                            DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes);
                            EntityCollection fromDisk = (EntityCollection)ser.ReadObject(reader, true);

                            foreach (Entity en in fromDisk.Entities)
                            {
                                EntityReference relatedEntity1 = new EntityReference();
                                EntityReference relatedEntity2 = new EntityReference();

                                try
                                {
                                    Guid relatedEntity1Id = getRelatedEntityGuid(en[ee.Entity1IntersectAttribute]);
                                    Guid relatedEntity2Id = getRelatedEntityGuid(en[ee.Entity2IntersectAttribute]);

                                    relatedEntity1 = new EntityReference { LogicalName = ee.Entity1LogicalName, Id = relatedEntity1Id };
                                    relatedEntity2 = new EntityReference { LogicalName = ee.Entity2LogicalName, Id = relatedEntity2Id };

                                    if (!AlreadyAssociated(_serviceProxy, ee, relatedEntity1Id, relatedEntity2Id))
                                    {
                                        if (ee.IntersectEntityName == "listmember")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;

                                            if (ee.Entity1LogicalName == "list")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                            }

                                            AddMemberListRequest request = new AddMemberListRequest();
                                            request.EntityId = entity_id;
                                            request.ListId = list_id;
                                            AddMemberListResponse response = (AddMemberListResponse)service.Execute(request);
                                        }
                                        else if (ee.IntersectEntityName == "campaignitem")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;
                                            string EntityName = "";

                                            if (ee.Entity1LogicalName == "campaign")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                                EntityName = (string)en["entitytype"];
                                                relatedEntity2.LogicalName = EntityName;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                                EntityName = (string)en["entitytype"];
                                                relatedEntity1.LogicalName = EntityName;
                                            }

                                            AddItemCampaignRequest req = new AddItemCampaignRequest();
                                            req.CampaignId = relatedEntity1Id;
                                            req.EntityName = EntityName;
                                            req.EntityId = entity_id;
                                            AddItemCampaignResponse resp = (AddItemCampaignResponse)service.Execute(req);
                                        }
                                        else if (ee.IntersectEntityName == "campaignactivityitem")
                                        {
                                            Guid entity_id = Guid.Empty;
                                            Guid list_id = Guid.Empty;
                                            string EntityName = "";

                                            if (ee.Entity1LogicalName == "campaignactivity")
                                            {
                                                entity_id = relatedEntity2Id;
                                                list_id = relatedEntity1Id;
                                                EntityName = (string)en["itemobjecttypecode"];
                                                relatedEntity2.LogicalName = EntityName;
                                            }
                                            else
                                            {
                                                entity_id = relatedEntity1Id;
                                                list_id = relatedEntity2Id;
                                                EntityName = (string)en["itemobjecttypecode"];
                                                relatedEntity1.LogicalName = EntityName;
                                            }

                                            AddItemCampaignActivityRequest req = new AddItemCampaignActivityRequest();
                                            req.CampaignActivityId = relatedEntity1Id;
                                            req.EntityName = EntityName;
                                            req.ItemId = entity_id;
                                            AddItemCampaignActivityResponse resp = (AddItemCampaignActivityResponse)service.Execute(req);
                                        }
                                        else
                                        {
                                            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                                            relatedEntities.Add(relatedEntity2);
                                            Relationship relationship = new Relationship(ee.RelationshipSchemaName);
                                            relationship.PrimaryEntityRole = EntityRole.Referencing;
                                            service.Associate(relatedEntity1.LogicalName, relatedEntity1.Id, relationship, relatedEntities);
                                        }
                                    }

                                    importedRecordsForEntity++;
                                    totalImportSuccess++;
                                }
                                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                                {
                                    totalImportFailures++;
                                    importFailuresForEntity++;
                                    NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure
                                    {
                                        CreatedOn = DateTime.Now.ToString(),
                                        NtoNRelationshipName = ee.RelationshipSchemaName,
                                        Reason = ex.Detail.Message,
                                        UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(),
                                        UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString()
                                    };
                                    report.TotalImportFailures += 1;
                                    //Insert the Failure line in the Failures Report
                                    WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                }
                                catch (Exception ex)
                                {
                                    //Check if the authentification session is expired
                                    if (ex.InnerException != null && ex.InnerException.Message.StartsWith("ID3242"))
                                    {
                                        LogManager.WriteLog("Error:The CRM authentication session expired. Reconnection attempt n° " + ReconnectionRetryCount);
                                        ReconnectionRetryCount--;
                                        //On 5 failed reconnections exit
                                        if (ReconnectionRetryCount == 0)
                                            throw;

                                        _serviceProxy = cm.connect(connection);
                                        service = (IOrganizationService)_serviceProxy;
                                        LogManager.WriteLog("Error:The CRM authentication session expired.");
                                        totalImportFailures++;
                                        importFailuresForEntity++;
                                        NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure
                                        {
                                            CreatedOn = DateTime.Now.ToString(),
                                            NtoNRelationshipName = ee.RelationshipSchemaName,
                                            Reason = ex.InnerException.Message,
                                            UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(),
                                            UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString()
                                        };
                                        report.TotalImportFailures += 1;
                                        //Insert the Failure line in the Failures Report
                                        WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                                totalTreatedRecords++;
                                treatedRecordsForEntity++;
                                updateTransportReport(report, ee, importedRecordsForEntity, importFailuresForEntity, entityImportStartDT);
                            }
                        }
                    }
                    LogManager.WriteLog("Treated " + treatedRecordsForEntity + " " + ee.RelationshipSchemaName + " records with " + importedRecordsForEntity + " successfully imported records and " + importFailuresForEntity + " failures.");
                }

                TimeSpan importTimeSpan = DateTime.Now - importStartDT;
                LogManager.WriteLog("Import finished for " + connection.ConnectionName + ". Treated " + totalTreatedRecords + " records in " + importTimeSpan.ToString().Substring(0, 10) + ". Successfuly imported " + totalImportSuccess + " records and " + totalImportFailures + " failures.");
                WriteTransportReport(report, transportReportFileName);
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
            }
        }
Exemple #24
0
        public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            ThrowExceptionIfDisposed();

            try
            {
                _serviceProxy.Disassociate(entityName, entityId, relationship, relatedEntities);
            }
            catch (Exception ex)
            {
                Helpers.DTEHelper.WriteExceptionToLog(ex);
                throw;
            }
        }
Exemple #25
0
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     OrganizationService.Disassociate(entityName, entityId, relationship, relatedEntities);
 }
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     service.Associate(entityName, entityId, relationship, relatedEntities);
 }
        /// <summary>
        /// This method first connects to the Outlook service. Afterwards,
        /// client information is retrieved and the client state is changed.
        /// </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();

                    //<snippetRetrieveDataFilters1>

                    // Create and Retrieve Offline Filter
                    // In your Outlook client, this will appear in the System Filters tab
                    // under File | CRM | Synchronize | Outlook Filters.
                    Console.Write("Creating offline filter");
                    String contactName = String.Format("offlineFilteredContact {0}",
                        DateTime.Now.ToLongTimeString());
                    String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" +
                        "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" +
                        "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName);
                    SavedQuery filter = new SavedQuery();
                    filter.FetchXml = fetchXml;
                    filter.IsQuickFindQuery = false;
                    filter.QueryType = SavedQueryQueryType.OfflineFilters;
                    filter.ReturnedTypeCode = Contact.EntityLogicalName;
                    filter.Name = "ReadOnlyFilter_" + contactName;
                    filter.Description = "Sample offline filter for Contact entity";
                    _offlineFilter = _serviceProxy.Create(filter);

                    Console.WriteLine(" and retrieving offline filter");
                    SavedQuery result = (SavedQuery)_serviceProxy.Retrieve(
                        SavedQuery.EntityLogicalName,
                        _offlineFilter,
                        new ColumnSet("name", "description"));
                    Console.WriteLine("Name: {0}", result.Name);
                    Console.WriteLine("Description: {0}", result.Description);
                    Console.WriteLine();

                    // Create and Retrieve Offline Template
                    // In your Outlook client, this will appear in the User Filters tab
                    // under File | CRM | Synchronize | Outlook Filters.
                    Console.Write("Creating offline template");
                    String accountName = String.Format("offlineFilteredAccount {0}",
                        DateTime.Now.ToLongTimeString());
                    fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" +
                        "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" +
                        "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName);
                    SavedQuery template = new SavedQuery();
                    template.FetchXml = fetchXml;
                    template.IsQuickFindQuery = false;
                    template.QueryType = SavedQueryQueryType.OfflineTemplate;
                    template.ReturnedTypeCode = Account.EntityLogicalName;
                    template.Name = "ReadOnlyFilter_" + accountName;
                    template.Description = "Sample offline template for Account entity";
                    _offlineTemplate = _serviceProxy.Create(template);

                    Console.WriteLine(" and retrieving offline template");
                    result = (SavedQuery)_serviceProxy.Retrieve(
                        SavedQuery.EntityLogicalName,
                        _offlineTemplate,
                        new ColumnSet("name", "description"));
                    Console.WriteLine("Name: {0}", result.Name);
                    Console.WriteLine("Description: {0}", result.Description);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters1>

                    //<snippetRetrieveDataFilters2>

                    // Call InstantiateFiltersRequest
                    Console.WriteLine("Retrieving user's ID and creating the template collection");
                    WhoAmIRequest whoAmI = new WhoAmIRequest();
                    Guid id = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
                    EntityReferenceCollection templates = new EntityReferenceCollection();
                    templates.Add(new EntityReference(
                        SavedQuery.EntityLogicalName,
                        _offlineTemplate));

                    Console.WriteLine("Activating the selected offline templates for this user");
                    InstantiateFiltersRequest request = new InstantiateFiltersRequest
                    {
                        UserId = id,
                        TemplateCollection = templates                            
                    };
                    InstantiateFiltersResponse response =
                        (InstantiateFiltersResponse)_serviceProxy.Execute(request);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters2>

                    //<snippetRetrieveDataFilters3>
                    // Call ResetUserFiltersRequest
                    Console.WriteLine("Resetting the user's offline templates to the defaults");
                    ResetUserFiltersRequest resetRequest = new ResetUserFiltersRequest
                    {
                        QueryType = SavedQueryQueryType.OfflineFilters
                    };
                    ResetUserFiltersResponse resetResponse =
                        (ResetUserFiltersResponse)_serviceProxy.Execute(resetRequest);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters3>

                    DeleteRequiredRecords(promptforDelete);
                }


            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
 public DisassociateRequest(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     this.EntityName      = entityName;
     this.EntityId        = entityId;
     this.Relationship    = relationship;
     this.RelatedEntities = relatedEntities;
 }
Exemple #29
0
        /// <summary>
        /// Delete all remaining entity records that were created by this sample.
        /// <param name="prompt">When true, the user is prompted whether 
        /// the records created in this sample should be deleted; otherwise, false.</param>
        /// </summary>
        public void DeleteEntityRecords(OrganizationServiceProxy service,
                                        EntityReferenceCollection records, bool prompt)
        {
            bool deleteRecords = true;

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

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

            if (deleteRecords)
            {
                while (records.Count > 0)
                {
                    EntityReference entityRef = records[records.Count - 1];
                    Console.WriteLine("Deleting {0} '{1}' ...", entityRef.LogicalName, entityRef.Name);
                    service.Delete(entityRef.LogicalName, entityRef.Id);
                    records.Remove(entityRef);
                }

                Console.WriteLine("Entity records have been deleted.");
            }
        }
        /// <summary>
        /// Persists the provided references into the data store. Checks each of the provided references and saves those that are missing.
        /// </summary>
        /// <param name="references">The collection of entity references to persist.</param>
        public virtual void PersistReferences(EntityReferenceCollection references)
        {
            using (LogGroup logGroup = LogGroup.Start("Persisting the provided references.", LogLevel.Debug))
            {
                if (references != null)
                {

                    LogWriter.Debug("Reference count: " + references.Count.ToString());

                    // TODO: Check if binding is needed. Shouldn't be because
                    // existing references are skipped and only new references get saved
                    //BindReferences(references);

                    foreach (EntityReference reference in references)
                    {
                        // If the reference is new then save it
                        if (!Provider.IsStored(reference))
                        {
                            LogWriter.Debug("Reference is new. Saving.");

                            Provider.Saver.Save(reference);
                        }
                        // Otherwise just leave the existing reference as-is
                        // Existing references shouldn't need to change
                    }
                }
            }
        }
Exemple #31
0
 /// <summary>
 /// Deletes a link between records.
 /// </summary>
 /// <param name="entityName">The logical name of the entity specified in the entityId parameter.</param>
 /// <param name="entityId">The ID of the record from which the related records will be disassociated.</param>
 /// <param name="relationship">The name of the relationship to be used to remove the link.</param>
 /// <param name="relatedEntities">A collection of entity references (references to records) to be disassociated.</param>
 public virtual void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
 }
        /// <summary>
        /// Retrieves the active references from the provided property. This only includes those references currently active and not those in the data store.
        /// </summary>
        /// <param name="entity">The entity containing the property that the references are assigned to.</param>
        /// <param name="property">The property that the references are assigned to.</param>
        /// <param name="mirrorPropertyName">The name of the mirror property.</param>
        /// <returns>The active entity reference if it exists.</returns>
        protected virtual EntityReference GetActiveReferenceFromSingleReferenceProperty(IEntity entity, PropertyInfo property, string mirrorPropertyName)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection();

            using (LogGroup logGroup = LogGroup.Start("Retrieving the reference from a single reference property.", LogLevel.Debug))
            {
                LogWriter.Debug("Single reference property.");

                IEntity[] referencedEntities = EntitiesUtilities.GetReferencedEntities(entity, property);

                if (referencedEntities != null && referencedEntities.Length > 0)
                {
                    IEntity referencedEntity = referencedEntities[0];

                    // TODO: Check if this can be simplified by skipping the collection part.
                    // It's only a single reference so the collection is unnecessary
                    collection = new EntityReferenceCollection(entity, property.Name, new IEntity[] {referencedEntity}, mirrorPropertyName);

                    //foreach (EntityReference r in references)
                    //{
                    //LogWriter.Debug("Adding reference with ID: " + r.ID.ToString());

                    //LogWriter.Debug("Source entity ID: " + r.Entity1ID.ToString());
                    //LogWriter.Debug("Referenced entity ID: " + r.Entity2ID.ToString());

                    //LogWriter.Debug("Source entity name: " + r.Type1Name);
                    //LogWriter.Debug("Referenced entity name: " + r.Type2Name);

                    //}
                }
                else
                    LogWriter.Debug("referencedEntities == null || referencedEntities.Length = 0");
            }

            if (collection.Count > 0)
                return (EntityReference)collection[0];
            else
                return null;
        }
        /// <summary>
        /// Retrieves all the references to the specified entity. The specified entity can be either the source or reference entity as references work both ways.
        /// </summary>
        /// <param name="entityType">The type of the entity to retrieve the corresponding references for.</param>
        /// <param name="entityID">The ID of the entity to retrieve the corresponding references for.</param>
        /// <param name="referenceType">The type of entity at the other side of the reference to the one specified.</param>
        /// <param name="activateAll">A value indicating whether to activate the references by loading the corresponding entities and setting them to the SourceEntity and ReferenceEntity properties.</param>
        /// <returns>A collection of references that match the provided parameters.</returns>
        public override EntityReferenceCollection GetReferences(Type entityType, Guid entityID, Type referenceType, bool activateAll)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection();

            using (LogGroup logGroup = LogGroup.StartDebug("Retrieving references."))
            {

                if (entityType == null)
                    throw new ArgumentNullException("entityType");

                if (referenceType == null)
                    throw new ArgumentNullException("referenceType");

                LogWriter.Debug("Entity type: " + entityType.ToString());
                LogWriter.Debug("Reference type: " + referenceType.ToString());

                Db4oDataStore dataStore = (Db4oDataStore)GetDataStore(entityType.Name, referenceType.Name);

                if(dataStore.DoesExist)
                {
                    EntityReferenceCollection list = new EntityReferenceCollection();

                    IQuery query1 = dataStore.ObjectContainer.Query();
                    query1.Constrain(typeof(EntityReference));

                    IConstraint constraint1 = query1.Descend("type1Name").Constrain(EntitiesUtilities.GetShortType(entityType.Name)).Equal().And(
                        query1.Descend("type2Name").Constrain(EntitiesUtilities.GetShortType(referenceType.Name)).Equal());

                    if (entityID != Guid.Empty)
                        constraint1.And(query1.Descend("entity1ID").Constrain(entityID).Equal());

                    IQuery query2 = dataStore.ObjectContainer.Query();
                    query2.Constrain(typeof(EntityReference));

                    IConstraint constraint2 = query2.Descend("type2Name").Constrain(EntitiesUtilities.GetShortType(entityType.Name)).Equal().And(
                        query2.Descend("type1Name").Constrain(EntitiesUtilities.GetShortType(referenceType.Name)).Equal());

                    if (entityID != Guid.Empty)
                        constraint2.And(query2.Descend("entity2ID").Constrain(entityID).Equal());

                    IObjectSet os1 = query1.Execute();

                    while (os1.HasNext())
                    {
                        EntityReference reference = (EntityReference)os1.Next();

                        list.Add(reference);
                    }

                    IObjectSet os2 = query2.Execute();

                    while (os2.HasNext())
                    {
                        EntityReference reference = (EntityReference)os2.Next();

                        list.Add(reference);
                    }

                    if (list.Count == 0)
                    {
                        LogWriter.Debug("No references loaded from the data store.");
                    }
                    else
                    {
                        LogWriter.Debug("Count: " + list.Count);

                        foreach (EntityReference r in list)
                        {
                            using (LogGroup logGroup2 = LogGroup.StartDebug("Processing reference."))
                            {

                                EntityReference reference = (EntityReference)r.SwitchFor(entityType, entityID);

                                LogWriter.Debug("Loaded reference - Entity ID 1: " + reference.Entity1ID);
                                LogWriter.Debug("Loaded reference - Entity ID 2: " + reference.Entity2ID);

                                LogWriter.Debug("Loaded reference - Property 1 name: " + reference.Property1Name);
                                LogWriter.Debug("Loaded reference - Property 2 name: " + reference.Property2Name);

                                LogWriter.Debug("Loaded reference - Type name 1: " + reference.Type1Name);
                                LogWriter.Debug("Loaded reference - Type name 2: " + reference.Type2Name);

                                if (reference.Entity1ID != Guid.Empty
                                    && reference.Entity2ID != Guid.Empty)
                                {
                                    //	LogWriter.Debug("Adding to the collection.");
                                    collection.Add(reference);
                                }
                                else
                                {
                                    LogWriter.Error("Reference not added to the collection. IDs are empty. This shouldn't happen but the system can ignore it and continue. Invalid references like these should probably be deleted.");
                                }
                            }
                        }
                    }
                }

                LogWriter.Debug("References #: " + collection.Count.ToString());

                if (activateAll)
                {
                    LogWriter.Debug("Activating references.");

                    foreach (EntityReference reference in collection)
                    {
                        Provider.Activator.ActivateReference(reference);
                    }
                }

                LogWriter.Debug("References #: " + collection.Count.ToString());
            }

            return collection;
        }
        /// <summary>
        /// Retrieves the active references from the provided entity property. This only includes those references currently active and not those in the data store.
        /// </summary>
        /// <param name="entity">The entity containing the property that the references are assigned to.</param>
        /// <param name="property">The property that the references are assigned to.</param>
        /// <param name="mirrorPropertyName">The name of the mirror property.</param>
        /// <returns>An array of the entity references.</returns>
        protected virtual EntityReference[] GetActiveReferencesFromMultipleReferenceProperty(IEntity entity, PropertyInfo property, string mirrorPropertyName)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection(entity);

            using (LogGroup logGroup = LogGroup.Start("Retrieving the references from a multiple reference property.", LogLevel.Debug))
            {
                LogWriter.Debug("Multiple reference property.");

                object propertyValue = property.GetValue(entity, null);

                LogWriter.Debug("Property value: " + (propertyValue == null ? "[null]" : propertyValue.ToString()));

                Collection<IEntity> referencedEntities = new Collection<IEntity>();

                referencedEntities.AddRange(EntitiesUtilities.GetReferencedEntities(entity, property));

                LogWriter.Debug("# of referenced entities found: " + referencedEntities.Count);

                EntityReferenceCollection references = new EntityReferenceCollection(entity, property.Name, referencedEntities.ToArray(), mirrorPropertyName);

                LogWriter.Debug("Reference objects created.");

                foreach (EntityReference reference in references)
                {
                    LogWriter.Debug("Adding reference with ID: " + reference.ID.ToString());

                    LogWriter.Debug("Source entity ID: " + reference.Entity1ID.ToString());
                    LogWriter.Debug("Referenced entity ID: " + reference.Entity2ID.ToString());

                    LogWriter.Debug("Source entity name: " + reference.Type1Name);
                    LogWriter.Debug("Referenced entity name: " + reference.Type2Name);

                    LogWriter.Debug("Source property name: " + reference.Property1Name);
                    LogWriter.Debug("Mirror property name: " + reference.Property2Name);

                    collection.Add((EntityReference)reference);
                }

            }

            return collection.ToArray();
        }
Exemple #35
0
        private void CreateEmail(Entity email, EntityReference regarding, EntityReference from, EntityReferenceCollection toRecipient)
        {
            if (from != null)
            {
                Entity fromActivityParty = new Entity("activityparty");
                fromActivityParty["partyid"] = from;

                email["from"] = new Entity[] { fromActivityParty };
            }

            if (toRecipient != null)
            {
                Entity[] toActivityParties = new Entity[toRecipient.Count];
                for (int x = 0; x < toRecipient.Count; x++)
                {
                    toActivityParties[x]            = new Entity("activityparty");
                    toActivityParties[x]["partyid"] = toRecipient[x];
                }
                email["to"] = toActivityParties;
            }

            if (regarding != null)
            {
                email["regardingobjectid"] = regarding;
            }

            TraceService.Trace("Email is going to be created");

            email.Id = this.OrganizationService.Create(email);

            TraceService.Trace("Email has been created correctly. ID:{0}", email.Id);
        }
Exemple #36
0
    public object Disassociate(dynamic options)
    {
        string entityName = options.entityName;
        Guid entityId = new Guid(options.entityId);
        Relationship relationship = new Relationship(options.relationship);
        var relatedEntitiesList = new List<EntityReference>();
        foreach (var rel in options.relatedEntities)
        {
            relatedEntitiesList.Add(new EntityReference(rel.entityName, new Guid(rel.entityId)));
        }
        EntityReferenceCollection relatedEntities = new EntityReferenceCollection(relatedEntitiesList);
        _service.Disassociate(entityName, entityId, relationship, relatedEntities);

        return null;
    }
 /// <summary>Creates a link between records.</summary>
 /// <param name="relatedEntities">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityReferenceCollection"></see>. property_relatedentities to be associated.</param>
 /// <param name="relationship">Type: <see cref="T:Microsoft.Xrm.Sdk.Relationship"></see>. The name of the relationship to be used to create the link. </param>
 /// <param name="entityName">Type: Returns_String. The logical name of the entity that is specified in the entityId parameter.</param>
 /// <param name="entityId">Type: Returns_Guid. property_entityid to which the related records are associated.</param>
 /// <param name="callback"></param>
 /// <param name="asyncState"></param>
 public IAsyncResult BeginAssociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, AsyncCallback callback, object asyncState)
 => BeginAssociate(entityName, entityId, relationship, relatedEntities, callback, asyncState, CancellationToken.None);
        public void Test_GetReference_Sync_Exclude()
        {
            using (LogGroup logGroup = LogGroup.Start("Testing the GetReference function with a synchronous reference to ensure it retrieves the correct reference.", NLog.LogLevel.Debug))
            {
                TestUtilities.CreateDummyReferences(100);

                TestUser user = new TestUser();
                user.ID = Guid.NewGuid();
                user.FirstName = "Test";
                user.LastName = "User";

                TestUser user2 = new TestUser();
                user2.ID = Guid.NewGuid();
                user2.FirstName = "Test";
                user2.LastName = "User 2";

                TestRole role = new TestRole();
                role.ID = Guid.NewGuid();
                role.Name = "Test Role";

                TestRole role2 = new TestRole();
                role2.ID = Guid.NewGuid();
                role2.Name = "Test Role 2";

                user.Roles = new TestRole[] {role};
                user2.Roles = new TestRole[] { role2 };
                //role2.Users = new TestUser[] {user, user2};

                LogWriter.Debug("User 1 ID: " + user.ID.ToString());
                LogWriter.Debug("User 2 ID: " + user2.ID.ToString());
                LogWriter.Debug("Role 1 ID: " + role.ID.ToString());
                LogWriter.Debug("Role 2 ID: " + role2.ID.ToString());

                EntityReferenceCollection userReferences = DataAccess.Data.Referencer.GetActiveReferences(user);
                EntityReferenceCollection user2References = DataAccess.Data.Referencer.GetActiveReferences(user2);

                Assert.AreEqual(1, userReferences.Count, "userReferences.Length is incorrect");
                Assert.AreEqual(1, user2References.Count, "user2References.Length is incorrect");

                EntityReference originalReference1 = userReferences[0];
                EntityReference originalReference2 = user2References[0];

                LogWriter.Debug("Original reference - Entity 1 ID: " + originalReference1.Entity1ID.ToString());
                LogWriter.Debug("Original reference - Entity 2 ID: " + originalReference1.Entity2ID.ToString());
                LogWriter.Debug("Original reference - Property 1 name: " + originalReference1.Property1Name);
                LogWriter.Debug("Original reference - Property 2 name: " + originalReference1.Property2Name);
                LogWriter.Debug("Original reference - Type 1 name: " + originalReference1.Type1Name);
                LogWriter.Debug("Original reference - Type 2 name: " + originalReference1.Type2Name);

                DataAccess.Data.Saver.Save(role2);
                DataAccess.Data.Saver.Save(role);
                DataAccess.Data.Saver.Save(user);
                DataAccess.Data.Saver.Save(user2);

                string referenceStoreName = DataUtilities.GetDataStoreName("TestUser", "TestRole");

                EntityReferenceCollection referenceEntities = DataAccess.Data.Referencer.GetReferences(user.GetType().Name, role.GetType().Name);

                Assert.AreEqual(2, referenceEntities.Count, "Incorrect number of references found in the store after saving entities.");

                // Switch the references around if necessary
                if (referenceEntities[0].Entity1ID == originalReference2.Entity1ID)
                {
                    EntityReference r1 = referenceEntities[1];
                    EntityReference r2 = referenceEntities[0];

                    referenceEntities = new EntityReferenceCollection();
                    referenceEntities.Add(r1);
                    referenceEntities.Add(r2);
                }

                bool firstReferenceMatches = (((referenceEntities[0].Includes(originalReference1.Entity1ID, originalReference1.Property1Name)
                                                && referenceEntities[0].Includes(originalReference1.Entity2ID, originalReference1.Property2Name))
                                               ||
                                               ((referenceEntities[0].Includes(originalReference2.Entity1ID, originalReference2.Property1Name)
                                                 && referenceEntities[0].Includes(originalReference2.Entity2ID, originalReference2.Property2Name)))));

                bool secondReferenceMatches = (((referenceEntities[1].Includes(originalReference1.Entity1ID, originalReference1.Property1Name)
                                                 && referenceEntities[1].Includes(originalReference1.Entity2ID, originalReference1.Property2Name))
                                                ||
                                                ((referenceEntities[1].Includes(originalReference2.Entity1ID, originalReference2.Property1Name)
                                                  && referenceEntities[1].Includes(originalReference2.Entity2ID, originalReference2.Property2Name)))));

                Assert.IsTrue(firstReferenceMatches,
                              "First reference doesn't match original references.");

                Assert.IsTrue(secondReferenceMatches,
                              "Second reference doesn't match original references.");

                EntityReference reference = DataAccess.Data.Referencer.GetReference(user.GetType(),
                                                                                    user.ID,
                                                                                    "Roles",
                                                                                    role.GetType(),
                                                                                    role2.ID,
                                                                                    "Users",
                                                                                    false);

                Assert.IsNull(reference, "The return value should be null.");
            }
        }
Exemple #39
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as QualifyLeadRequest;

            var orgService = ctx.GetOrganizationService();

            if (req.LeadId == null)
            {
                throw new Exception("Lead Id must be set in request.");
            }

            var leads = (from l in ctx.CreateQuery("lead")
                         where l.Id == req.LeadId.Id
                         select l);

            var leadsCount = leads.Count();

            if (leadsCount != 1)
            {
                throw new Exception(string.Format("Number of Leads by given LeadId should be 1. Instead it is {0}.", leadsCount));
            }

            // Made here to get access to CreatedEntities collection
            var response = new QualifyLeadResponse();

            response["CreatedEntities"] = new EntityReferenceCollection();

            // Create Account
            if (req.CreateAccount) // ParentAccount
            {
                var account = new Entity("account")
                {
                    Id = Guid.NewGuid()
                };
                account.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(account);
                response.CreatedEntities.Add(account.ToEntityReference());
            }

            // Create Contact
            if (req.CreateContact)
            {
                var contact = new Entity("contact")
                {
                    Id = Guid.NewGuid()
                };
                contact.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(contact);
                response.CreatedEntities.Add(contact.ToEntityReference());
            }

            // Create Opportunity
            if (req.CreateOpportunity)
            {
                var opportunity = new Entity("opportunity")
                {
                    Id = Guid.NewGuid()
                };

                // Set OpportunityCurrencyId if given
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycurrencyid.aspx
                if (req.OpportunityCurrencyId != null)
                {
                    opportunity.Attributes["transactioncurrencyid"] = req.OpportunityCurrencyId;
                }

                // Associate Account or Contact with Opportunity
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycustomerid.aspx
                if (req.OpportunityCustomerId != null)
                {
                    var logicalName = req.OpportunityCustomerId.LogicalName;

                    // Associate Account or Contact
                    if (logicalName.Equals("account") || logicalName.Equals("contact"))
                    {
                        opportunity.Attributes["customerid"] = req.OpportunityCustomerId;
                    }
                    // Wrong Entity was given as parameter
                    else
                    {
                        throw new Exception(string.Format("Opportunity Customer Id should be connected with Account or Contact. Instead OpportunityCustomerId was given with Entity.LogicalName = {0}", logicalName));
                    }
                }

                opportunity.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(opportunity);
                response.CreatedEntities.Add(opportunity.ToEntityReference());
            }

            // Actual Lead
            var lead = leads.First();

            lead.Attributes["statuscode"] = req.Status.Value;
            orgService.Update(lead);

            return(response);
        }
        internal void ApplySelectedFiltersToUsers(bool applyToActiveUsers = false)
        {
            if (lvViews.SelectedItems.Count == 0)
            {
                return;
            }

            var templates = new EntityReferenceCollection();
            foreach (ListViewItem item in lvViews.SelectedItems)
            {
                templates.Add(new EntityReference(entityName, ((Entity)item.Tag).Id));
            }

            List<Entity> users = null;

            if (!applyToActiveUsers)
            {
                var usDialog = new UserSelectionDialog(service);
                if (usDialog.ShowDialog(this) == DialogResult.OK)
                {
                    users = usDialog.SelectedUsers;
                }
                else
                {
                    return;
                }

            }

            if (users == null || users.Count > 0)
            {
                loadingPanel = InformationPanel.GetInformationPanel(this, "Processing...", 340, 120);

                var bwApplyFiltersToUsers = new BackgroundWorker {WorkerReportsProgress = true};
                bwApplyFiltersToUsers.DoWork += bwApplyFiltersToUsers_DoWork;
                bwApplyFiltersToUsers.ProgressChanged += bwApplyFiltersToUsers_ProgressChanged;
                bwApplyFiltersToUsers.RunWorkerCompleted += bwApplyFiltersToUsers_RunWorkerCompleted;
                bwApplyFiltersToUsers.RunWorkerAsync(new object[] {templates, users});
            }
        }
        public void Activate(IEntity entity, string propertyName, Type propertyType, int depth, EntityReferenceCollection references)
        {
            using (LogGroup logGroup = LogGroup.StartDebug("Activating the '" + propertyName + "' property on the '" + entity.ShortTypeName + "' type."))
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                if (propertyName == null || propertyName == String.Empty)
                    throw new ArgumentException("propertyName", "Cannot be null or String.Empty.");

                PropertyInfo property = EntitiesUtilities.GetProperty(entity.GetType(), propertyName, propertyType);

                if (property == null)
                    throw new Exception("Cannot find property with name '" + propertyName + "' and type '" + (propertyType == null ? "[null]" : propertyType.ToString()) + "' on the type '" + entity.ShortTypeName + "'.");

                Type referenceType = DataUtilities.GetEntityType(entity, property);

                // If the reference type is not null then activate the property
                // otherwise skip it because it means it's a dynamic reference property which hasn't been set
                if (referenceType != null)
                {
                    LogWriter.Debug("Reference entity type: " + referenceType.ToString());

                    IEntity[] referencedEntities = Provider.Indexer.GetEntitiesWithReference(entity, property.Name, references);

                    if (referencedEntities == null)
                        LogWriter.Debug("# of entities found: [null]");
                    else
                        LogWriter.Debug("# of entities found:" + referencedEntities.Length);

                    // Multiple references.
                    if (EntitiesUtilities.IsMultipleReference(entity.GetType(), property))
                    {
                        LogWriter.Debug("Multiple reference property");

                        ActivateMultipleReferenceProperty(entity, property, referencedEntities);

                    }
                    // Single reference.
                    else
                    {
                        LogWriter.Debug("Single reference property");

                        ActivateSingleReferenceProperty(entity, property, referencedEntities);
                    }
                }
            }
        }
Exemple #42
0
 public void Disassociate(string entityName, Guid entityId, Relationship relationship,
     EntityReferenceCollection relatedEntities)
 {
     if (relatedEntities.Count > 0)
     {
         var request = new DisassociateRequest
         {
             Target = CreateLookup(entityName, entityId),
             Relationship = relationship,
             RelatedEntities = relatedEntities
         };
         Execute(request);
     }
 }
Exemple #43
0
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     _connection.Associate(entityName, entityId, relationship, relatedEntities);
 }
Exemple #44
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create an account record
        /// Retrieve the account record
        /// Update the account record
        /// Optionally delete any entity records that were created for this sample.
        /// </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)
        {
            while (true)
            {
                Console.Write("Find Account Name: ");
                accountName = Console.ReadLine();
                if (accountName != string.Empty)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("Account Name can't be empty!");
                }
            }

            while (true)
            {
                Console.Write("Contacts First Name: ");
                fName = Console.ReadLine();
                if (fName != string.Empty)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("Contact Name can't be empty!");
                }
            }

            while (true)
            {
                Console.Write("Contacts Last Name: ");
                lName = Console.ReadLine();
                if (lName != string.Empty)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("Contact Name can't be empty!");
                }
            }


            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))
                {
                    _service    = (IOrganizationService)_serviceProxy;
                    _orgContext = new OrganizationServiceContext(_service);

                    var account = FindAccount(accountName);
                    _accountId = account.Id;
                    if (_accountId == null)
                    {
                        Console.WriteLine("Account was not found!");;
                    }
                    else
                    {
                        EntityReferenceCollection myEntityReferenceCollection = CreateAContact(_accountId, account);

                        //EntityReferenceCollection myEntityReferenceCollection = CreateContact(_accountId);

                        //AssociateConctactWithAccount(myEntityReferenceCollection);
                    }
                }
            }

            // 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;
            }
        }
Exemple #45
0
  /// <summary>
  /// Creates any entity records that this sample requires.
  /// </summary>
  public void CreateRequiredRecords()
  {
   Contact contact1 = new Contact
   {
    FirstName = "Colin",
    LastName = "Wilcox",
    Address1_City = "Redmond",
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98052",
    Anniversary = new DateTime(2010, 3, 5),
    CreditLimit = new Money(300),
    Description = "Alpine Ski House",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(1),
    NumberOfChildren = 1,
    Address1_Latitude = 47.6741667,
    Address1_Longitude = -122.1202778,
    CreditOnHold = false
   };
   _contactId1 = _serviceProxy.Create(contact1);

   Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName);

   Contact contact2 = new Contact
   {
    FirstName = "Brian",
    LastName = "Smith",
    Address1_City = "Bellevue",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98008",
    Anniversary = new DateTime(2010, 4, 5),
    CreditLimit = new Money(30000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = false
   };
   _contactId2 = _serviceProxy.Create(contact2);

   Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName);

   Contact contact3 = new Contact
   {
    FirstName = "Darren",
    LastName = "Parker",
    Address1_City = "Kirkland",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98033",
    Anniversary = new DateTime(2010, 10, 5),
    CreditLimit = new Money(10000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = false
   };
   _contactId3 = _serviceProxy.Create(contact3);

   Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName);

   Contact contact4 = new Contact
   {
    FirstName = "Ben",
    LastName = "Smith",
    Address1_City = "Kirkland",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98033",
    Anniversary = new DateTime(2010, 7, 5),
    CreditLimit = new Money(12000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = true
   };
   _contactId4 = _serviceProxy.Create(contact4);

   Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName);

   Incident incident1 = new Incident
   {
    Title = "Test Case 1",
    PriorityCode = new OptionSetValue(1), // 1 = High
    CaseOriginCode = new OptionSetValue(1), // 1 = Phone
    CaseTypeCode = new OptionSetValue(2), // 2 = Problem
    Description = "Description for Test Case 1.",
    FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
    CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId2)
   };

   _incidentId1 = _serviceProxy.Create(incident1);

   Console.Write("Created a sample incident 1: {0}, ", incident1.Title);

   Relationship relationship1 = new Relationship("incident_customer_contacts");
   EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection();
   relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1));
   _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1);

   Console.Write("Added relationship between incident 1 and contact 1, ");


   Account account1 = new Account
   {
    Name = "Coho Winery",
    Address1_Name = "Coho Vineyard & Winery",
    Address1_City = "Redmond"
   };
   _accountId1 = _serviceProxy.Create(account1);

   Console.Write("Created a sample account 1: {0}, ", account1.Name);

   Incident incident2 = new Incident
   {
    Title = "Test Case 2",
    PriorityCode = new OptionSetValue(1), // 1 = High
    CaseOriginCode = new OptionSetValue(1), // 1 = Phone
    CaseTypeCode = new OptionSetValue(2), // 2 = Problem
    Description = "Description for Sample Case 2.",
    FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
    CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId1)
   };

   _incidentId2 = _serviceProxy.Create(incident2);

   Console.Write("Created a sample incident 2: {0}, ", incident2.Title);

   Relationship relationship2 = new Relationship("incident_customer_accounts");
   EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection();
   relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1));
   _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2);

   Console.Write("Added relationship between incident 2 and account 1, ");

   Lead lead = new Lead()
   {
    FirstName = "Diogo",
    LastName = "Andrade"
   };
   _leadId = _serviceProxy.Create(lead);
   Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName);

   Account account2 = new Account
   {
    Name = "Contoso Ltd",
    ParentAccountId = new EntityReference(Account.EntityLogicalName, _accountId1),
    Address1_Name = "Contoso Pharmaceuticals",
    Address1_City = "Redmond",
    OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId)
   };
   _accountId2 = _serviceProxy.Create(account2);

   Console.Write("Created a sample account 2: {0}, ", account2.Name);

   Relationship relationship3 = new Relationship("account_primary_contact");
   EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection();
   relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2));
   _serviceProxy.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3);

   Console.WriteLine("Added relationship between account 2 and contact 2.");
  }
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid       userid     = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                                                                 new ColumnSet(new string[] { "firstname", "lastname" }));

            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);

            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account {
                Name = "SiroccoTest"
            };

            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode    = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Sirocco.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            var eref = new EntityReference(Account.EntityLogicalName, accountId);

            eref.Name = account.Name;
            records.Add(eref);

            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);

            Console.Write("retrieved, ");

            // The phone number.
            retrievedAccount.Telephone1 = "99999999";

            // The fax number.
            retrievedAccount.Fax = "23442342";

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            retrievedAccount.Address2_PostalCode = null;

            // Shows use of a Money value.
            retrievedAccount.Revenue = new Money(5000000);

            // New contact?????????
            //retrievedAccount.Firstname = new Contact("Peter");

            // Shows use of a Boolean value.
            retrievedAccount.CreditOnHold = false;

            // Update the account record.
            service.Update(retrievedAccount);
            Console.WriteLine("and updated.");
        }
Exemple #47
0
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
 }
        public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            if (!relatedEntities.Any())
            {
                throw new ArgumentException("Must contain at least one related entity!", nameof(relatedEntities));
            }
            if (relatedEntities.Any(e => e.LogicalName != relatedEntities.First().LogicalName))
            {
                throw new NotImplementedException("Don't currently Support different Entity Types for related Entities!");
            }

            if (relationship.PrimaryEntityRole.GetValueOrDefault(EntityRole.Referenced) == EntityRole.Referencing)
            {
                throw new NotImplementedException("Referencing Not Currently Implemented");
            }

            var referencedIdName  = EntityHelper.GetIdAttributeName(entityName);
            var referencingIdName = EntityHelper.GetIdAttributeName(relatedEntities.First().LogicalName);

            if (referencedIdName == referencingIdName)
            {
                referencedIdName  += "one";
                referencingIdName += "two";
            }

            //if (EntityHelper.IsTypeDefined(Info.EarlyBoundEntityAssembly, Info.EarlyBoundNamespace,
            //    relationship.SchemaName))
            //{
            Disassociate1ToN(entityId, relationship, relatedEntities, referencedIdName, referencingIdName);
            //}
            //else
            //{
            //    foreach (var entity in relatedEntities)
            //    {
            //        DisassociateN2N(new EntityReference(entityName, entityId), entity, relationship);
            //    }
            //}
        }
        private void ApplyTemplateToUsers(List<Guid> rulesIds, string question, RuleManager rm, BackgroundWorker worker)
        {
            worker.ReportProgress(0, "Waiting for input...");

            if (
               MessageBox.Show(this, question, "Question",
                   MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var usDialog = new UserSelectionDialog(service);
                if (usDialog.ShowDialog() == DialogResult.OK)
                {
                    foreach (var user in usDialog.SelectedUsers)
                    {
                        worker.ReportProgress(0, string.Format("Applying rule(s) to user(s) '{0}'", user.GetAttributeValue<string>("fullname")));

                        var erc = new EntityReferenceCollection();
                        foreach (var ruleId in rulesIds)
                        {
                            erc.Add(new EntityReference("savedquery", ruleId));
                        }

                        rm.ApplyRulesToUser(erc, user.Id);
                    }
                }
            }
        }
Exemple #50
0
 public void Disassociate( string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities )
 {
     throw new NotImplementedException();
 }
Exemple #51
0
        /// <summary>
        ///     !! Doesn;t work same entity type!!
        /// </summary>
        public void Disassociate(string relationshipName, string keyAttributeFrom, Guid entityFrom,
            string keyAttributeTo, IEnumerable<Guid> relatedEntities)
        {
            var metadata = GetRelationshipMetadata(relationshipName);
            var isReferencing = metadata.Entity1IntersectAttribute == keyAttributeFrom;
            var relatedType = isReferencing ? metadata.Entity2LogicalName : metadata.Entity1LogicalName;
            var targetType = isReferencing ? metadata.Entity1LogicalName : metadata.Entity2LogicalName;

            var relationship = new Relationship(relationshipName)
            {
                PrimaryEntityRole =
                    isReferencing ? EntityRole.Referencing : EntityRole.Referenced
            };

            var entityReferenceCollection = new EntityReferenceCollection();
            foreach (var id in relatedEntities)
                entityReferenceCollection.Add(CreateLookup(relatedType, id));

            Disassociate(targetType, entityFrom, relationship, entityReferenceCollection);
        }
        /// <summary>Deletes a link between records.</summary>
        /// <param name="relatedEntities">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityReferenceCollection"></see>. A collection of entity references (references to records) to be disassociated.</param>
        /// <param name="relationship">Type: <see cref="T:Microsoft.Xrm.Sdk.Relationship"></see>. The name of the relationship to be used to remove the link.</param>
        /// <param name="entityName">Type: Returns_String. The logical name of the entity that is specified in the entityId parameter.</param>
        /// <param name="entityId">Type: Returns_Guid. The ID of the record from which the related records are disassociated.</param>
        protected internal virtual void DisassociateCore(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            bool?retry = null;

            do
            {
                bool forceClose = false;
                try {
                    using (new OrganizationServiceContextInitializer(this)) {
                        base.ServiceChannel.Channel.Disassociate(entityName, entityId, relationship, relatedEntities);
                    }
                    break;
                } catch (System.ServiceModel.Security.MessageSecurityException messageSecurityException) {
                    forceClose = true;
                    retry      = base.ShouldRetry(messageSecurityException, retry);
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                } catch (System.ServiceModel.EndpointNotFoundException) {
                    forceClose = true;
                    retry      = new bool?(base.HandleFailover(retry));
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                } catch (TimeoutException) {
                    forceClose = true;
                    retry      = new bool?(base.HandleFailover(retry));
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                } catch (System.ServiceModel.FaultException <OrganizationServiceFault> faultException) {
                    forceClose = true;
                    retry      = base.HandleFailover(faultException.Detail, retry);
                    if (!retry.GetValueOrDefault())
                    {
                        throw;
                    }
                } catch {
                    forceClose = true;
                    throw;
                } finally {
                    this.CloseChannel(forceClose);
                }
            }while (retry.HasValue && retry.Value);
        }
 public override void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     if (DisassociateAction != null)
     {
         DisassociateAction(Service, entityName, entityId, relationship, relatedEntities);
     }
     else if (DisassociateActions != null)
     {
         if (DisassociateCache == null)
         {
             DisassociateCache = Service;
             foreach (var disassociate in DisassociateActions)
             {
                 DisassociateCache = new FakeIOrganizationService(DisassociateCache) {DisassociateAction = disassociate};
             }
         }
         DisassociateCache.Disassociate(entityName, entityId, relationship, relatedEntities);
     }
     else
     {
         if (ExecutionTracingEnabled)
         {
             Timer.Time(DisassociateInternal, new Tuple<string, Guid, Relationship, EntityReferenceCollection>(entityName, entityId, relationship, relatedEntities),
                 "Disassociate {0}:{1} using relationship {2} to releated Entities {3}: {4}",
                 entityName, entityId, relationship, String.Join(", ", relatedEntities.Select(e => e.GetNameId())));
         }
         else
         {
             Service.Disassociate(entityName, entityId, relationship, relatedEntities);
         }
     }
 }
 /// <summary>Deletes a link between records.</summary>
 /// <param name="relatedEntities">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityReferenceCollection"></see>. A collection of entity references (references to records) to be disassociated.</param>
 /// <param name="relationship">Type: <see cref="T:Microsoft.Xrm.Sdk.Relationship"></see>. The name of the relationship to be used to remove the link.</param>
 /// <param name="entityName">Type: Returns_String. The logical name of the entity that is specified in the entityId parameter.</param>
 /// <param name="entityId">Type: Returns_Guid. The ID of the record from which the related records are disassociated.</param>
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     this.DisassociateCore(entityName, entityId, relationship, relatedEntities);
 }
        /// <summary>
        /// Prepares the provided entity for deletion by removing dependent referenced, etc.
        /// </summary>
        /// <param name="entity">The entity to prepare for deletion.</param>
        public override void PreDelete(IEntity entity)
        {
            using (LogGroup logGroup = LogGroup.Start("Preparing to delete the provided entity.", NLog.LogLevel.Debug))
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                Db4oDataStore store = (Db4oDataStore)GetDataStore(entity);

                //if (entity.ID == Guid.Empty)
                //	throw new ArgumentException("entity.ID must be set.");

                EntityReferenceCollection toDelete = new EntityReferenceCollection();

                if (entity != null && entity.ID != Guid.Empty)
                {
                    //Provider.Activator.Activate(entity);

                    EntityReferenceCollection latestReferences = Provider.Referencer.GetReferences(entity);

                    // Delete all references
                    foreach (PropertyInfo property in entity.GetType().GetProperties())
                    {
                        bool isReference = EntitiesUtilities.IsReference(entity.GetType(), property.Name, property.PropertyType);

                        if (isReference)
                        {
                            using (LogGroup logGroup2 = LogGroup.StartDebug("Checking reference property '" + property.Name + "' for obsolete references."))
                            {
                                Type referenceType = EntitiesUtilities.GetReferenceType(entity, property.Name);

                                // If the reference type is not null then continue
                                if (referenceType != null)
                                {
                                    EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(entity.GetType(),
                                                                                                                    entity.ID,
                                                                                                                    property.Name,
                                                                                                                    referenceType,
                                                                                                                    false);
                                    if (references.Count > 0)
                                    {
                                        LogWriter.Debug("Found references: " + references.Count.ToString());

                                        foreach (EntityReference reference in references)
                                        {
                                            LogWriter.Debug("Found reference between '" + reference.Type1Name + "' and '" + reference.Type2Name + "'.");

                                            toDelete.Add(reference);
                                        }
                                    }
                                    else
                                        LogWriter.Debug("No references found associated with this property.");
                                }
                                // Otherwise skip it because the reference property hasn't been set
                            }
                        }
                    }
                }

                LogWriter.Debug("References to delete: " + toDelete.Count);

                //entitiesToUpdate = toUpdate.ToArray();
                Provider.Referencer.DeleteObsoleteReferences(toDelete);

            }
        }
Exemple #56
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // Associate the accounts to the contact record.

                    // Create a collection of the entities that will be
                    // associated to the contact.
                    var relatedEntities = new EntityReferenceCollection();
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id));
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id));
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id));

                    // Create an object that defines the relationship between the contact and account.
                    var relationship = new Relationship("account_primary_contact");


                    //Associate the contact with the 3 accounts.
                    service.Associate(Contact.EntityLogicalName, _contactId, relationship,
                                      relatedEntities);

                    Console.WriteLine("The entities have been associated.");

                    //Disassociate the records.
                    service.Disassociate(Contact.EntityLogicalName, _contactId, relationship,
                                         relatedEntities);

                    Console.WriteLine("The entities have been disassociated.");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemple #57
0
        public void ApplyRuleToActiveUsers(EntityReferenceCollection ec)
        {
            var qba = new QueryByAttribute("systemuser");
            qba.AddAttributeValue("isdisabled", false);
            foreach (var user in service.RetrieveMultiple(qba).Entities)
            {
                var request = new InstantiateFiltersRequest
                {
                    UserId = user.Id,
                    TemplateCollection = ec
                };

                service.Execute(request);
            }
        }
Exemple #58
0
 public override void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     if (DisassociateAction != null)
     {
         DisassociateAction(Service, entityName, entityId, relationship, relatedEntities);
     }
     else if (DisassociateActions != null)
     {
         if (DisassociateCache == null)
         {
             DisassociateCache = Service;
             foreach (var disassociate in DisassociateActions)
             {
                 DisassociateCache = new FakeIOrganizationService(DisassociateCache)
                 {
                     DisassociateAction = disassociate
                 };
             }
         }
         DisassociateCache.Disassociate(entityName, entityId, relationship, relatedEntities);
     }
     else
     {
         if (ExecutionTracingEnabled)
         {
             Timer.Time(DisassociateInternal, new Tuple <string, Guid, Relationship, EntityReferenceCollection>(entityName, entityId, relationship, relatedEntities),
                        "Disassociate {0}:{1} using relationship {2} to releated Entities {3}: {4}",
                        entityName, entityId, relationship, String.Join(", ", relatedEntities.Select(e => e.GetNameId())));
         }
         else
         {
             Service.Disassociate(entityName, entityId, relationship, relatedEntities);
         }
     }
 }
Exemple #59
0
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                new ColumnSet(new string[] { "firstname", "lastname" }));
            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);
            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account { Name = "Fourth Coffee" };
            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Fourth Coffee.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            var eref = new EntityReference(Account.EntityLogicalName, accountId);
            eref.Name = account.Name;
            records.Add(eref);

            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);
            Console.Write("retrieved, ");

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            retrievedAccount.Address2_PostalCode = null;

            // Shows use of a Money value.
            retrievedAccount.Revenue = new Money(5000000);

            // Shows use of a Boolean value.
            retrievedAccount.CreditOnHold = false;

            // Update the account record.
            service.Update(retrievedAccount);
            Console.WriteLine("and updated.");
        }
Exemple #60
0
        public async static Task DisassociateAsync(this IOrganizationService sdk, string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            var t = Task.Factory.StartNew(() =>
            {
                sdk.Disassociate(entityName, entityId, relationship, relatedEntities);
            });

            await t;
        }