Exemplo n.º 1
0
        internal void Associate_Disassociate()
        {
            //建立等等要關聯用的客戶資料
            var account1 = new Account()
            {
                Name = "TestAccount"
            };
            var acc1Id = _orgService.Create(account1);

            var account2 = new Account()
            {
                Name = "TestAccount2"
            };
            var acc2Id = _orgService.Create(account2);
            //建立等等要關聯用的聯絡人資料
            var contact1 = new Contact()
            {
                FirstName = "Lin", LastName = "Jeremy"
            };
            var contact1Id = _orgService.Create(contact1);

            //建立客戶主要聯絡人的實體關聯物件
            Relationship rel = new Relationship("account_primary_contact");

            //把要被設定主要聯絡人的客戶加入到集合中
            var accounts = new EntityReferenceCollection();

            accounts.Add(new EntityReference(Account.EntityLogicalName, acc1Id));
            accounts.Add(new EntityReference(Account.EntityLogicalName, acc2Id));

            //從連絡人執行關聯到客戶
            _orgService.Associate(Contact.EntityLogicalName, contact1Id, rel, accounts);

            onLog(string.Format("Associate Product Success"));

            //從聯絡人解除跟客戶的關聯
            _orgService.Disassociate(Contact.EntityLogicalName, contact1Id, rel, accounts);

            onLog(string.Format("Disassociate Product Success"));

            //把要設定主要聯絡人的聯絡人加入到集合中
            var contacts = new EntityReferenceCollection();

            contacts.Add(new EntityReference(Contact.EntityLogicalName, contact1Id));

            //從客戶執行關聯到聯絡人
            _orgService.Associate(Account.EntityLogicalName, acc1Id, rel, contacts);
            _orgService.Associate(Account.EntityLogicalName, acc2Id, rel, contacts);

            onLog(string.Format("Other Way Associate Product Success"));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Disassociate two or more entitity records.
 /// </summary>
 /// <param name="entityName">The name of the entity that contains the record.</param>
 /// <param name="entityId">The id of the record being disassociated.</param>
 /// <param name="relationship">The relatiomship being use for the current association.</param>
 /// <param name="relatedEntities">The collection of entities to disassociate the record from.</param>
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     try
     {
         using (OrganizationServiceProxy organizationServiceProxy = this.OrganizationServiceProxy)
         {
             organizationServiceProxy.Disassociate(entityName, entityId, relationship, relatedEntities);
         }
     }
     catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
     {
         throw;
     }
 }
Exemplo n.º 3
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;
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Deletes/reverts any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete/revert the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

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

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

            if (deleteRecords)
            {
                _serviceProxy.Disassociate("systemuser",
                                           _userId,
                                           new Relationship("systemuserroles_association"),
                                           new EntityReferenceCollection()
                {
                    new EntityReference("role", _roleId)
                });
                Console.WriteLine("Entity records have been deleted/reverted.");
            }
        }
Exemplo n.º 5
0
 public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     RunSafe(() => _serviceProxy.Disassociate(entityName, entityId, relationship, relatedEntities));
 }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, it
        /// creates/retrieves a system user, and
        /// updates the system user to associate with the salesperson role.
        /// Note: Creating a user is only supported
        /// in an on-premises/active directory environment.
        /// </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 is properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Retrieve a user.
                    SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName,
                                                             _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>();

                    if (user != null)
                    {
                        Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName);
                        // Find the role.
                        QueryExpression query = new QueryExpression
                        {
                            EntityName = "role",
                            ColumnSet  = new ColumnSet("roleid"),
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "name",
                                        Operator      = ConditionOperator.Equal,
                                        Values        = { _givenRole }
                                    }
                                }
                            }
                        };

                        // Get the role.
                        EntityCollection roles = _serviceProxy.RetrieveMultiple(query);

                        // Disassociate the role.
                        if (roles.Entities.Count > 0)
                        {
                            Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>();

                            Console.WriteLine("Role {0} is retrieved.", _givenRole);

                            _serviceProxy.Disassociate(
                                "systemuser",
                                user.Id,
                                new Relationship("systemuserroles_association"),
                                new EntityReferenceCollection()
                            {
                                new EntityReference("role", salesRole.Id)
                            });
                            Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName);
                        }
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 7
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;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, it
        /// creates/retrieves a system user, and
        /// updates the system user to associate with the salesperson role. 
        /// Note: Creating a user is only supported
        /// in an on-premises/active directory environment.
        /// </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
            {
                //<snippetRemoveRoleFromUser1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy is properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Retrieve a user.
                    SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName,
                        _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity<SystemUser>();

                    if (user != null)
                    {
                        Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName);
                        // Find the role.
                        QueryExpression query = new QueryExpression
                        {
                            EntityName = "role",
                            ColumnSet = new ColumnSet("roleid"),
                            Criteria = new FilterExpression
                            {
                                Conditions =
                                {
    
                                    new ConditionExpression
                                    {
                                        AttributeName = "name",
                                        Operator = ConditionOperator.Equal,
                                        Values = {_givenRole}
                                    }
                                }
                            }
                        };

                        // Get the role.
                        EntityCollection roles = _serviceProxy.RetrieveMultiple(query);

                        // Disassociate the role.
                        if (roles.Entities.Count > 0)
                        {
                            Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity<Role>();

                            Console.WriteLine("Role {0} is retrieved.", _givenRole);

                            _serviceProxy.Disassociate(
                                        "systemuser",
                                        user.Id,
                                        new Relationship("systemuserroles_association"),
                                        new EntityReferenceCollection() { new EntityReference("role", salesRole.Id) });
                            Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName);
                        }
                    }

                }
                //</snippetRemoveRoleFromUser1>
            }
            // 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;
            }
        }