Tuesday, 1 May 2012

Creating,Updating, Retrieving and Associating Connection Role and Connections in CRM 2011


In this article , I am going to explain how to create , update , retrieve Connection and Connection Role

Namespace need to include 

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;


Defining Connection Property

var Categories = new
{
   Business = 1,
   Family = 2,
   Social = 3,
   Sales = 4,
   Other = 5
};


Code to create Connection Role for account and contact entity

// Create the Connection Role 1
  ConnectionRole newConnectionRole1 = new ConnectionRole
  {
    Name = "Example Connection Role 1",
    Category = new OptionSetValue(Categories.Business),
  };
  Guid _connectionRole1Id = _serviceProxy.Create(newConnectionRole1);

  // Create a related Connection Role Object Type Code record for Account
  ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode
           = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                  ConnectionRole.EntityLogicalName, _connectionRole1Id),
     AssociatedObjectTypeCode = Account.EntityLogicalName
  };

  _serviceProxy.Create(newAccountConnectionRole1TypeCode);

  // Create a related Connection Role Object Type Code record for Contact
  ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode
            = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                ConnectionRole.EntityLogicalName, _connectionRole1Id),
     AssociatedObjectTypeCode = Contact.EntityLogicalName
  };

  _serviceProxy.Create(newContactConnectionRole1TypeCode);



  // Create the Connection Role 2
  ConnectionRole newConnectionRole2 = new ConnectionRole
  {
     Name = "Example Connection Role 2",
     Category = new OptionSetValue(Categories.Business),
  };
  Guid _connectionRole2Id = _serviceProxy.Create(newConnectionRole2);

  // Create a related Connection Role 2 Object Type Code record for Account
  ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode
       = new ConnectionRoleObjectTypeCode
  {
      ConnectionRoleId = new EntityReference(
                  ConnectionRole.EntityLogicalName, _connectionRole2Id),
      AssociatedObjectTypeCode = Account.EntityLogicalName
  };
  _serviceProxy.Create(newAccountConnectionRole2TypeCode);

  // Create a related Connection Role 2 Object Type Code record for Contact
  ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode
            = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                ConnectionRole.EntityLogicalName, _connectionRole2Id),
     AssociatedObjectTypeCode = Contact.EntityLogicalName
  };
  _serviceProxy.Create(newContactConnectionRole2TypeCode);



Code to Associate the connection roles

  AssociateRequest associateConnectionRoles = new AssociateRequest
  {
     Target = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     RelatedEntities = new EntityReferenceCollection()
     {
         new EntityReference(ConnectionRole.EntityLogicalName,
                                _connectionRole2Id)
     },
     // The name of the relationship connection role association
     // relationship in MS CRM
     Relationship = new Relationship()
     {
       PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive    relationship.
       SchemaName = "connectionroleassociation_association"
     }
  };
  _serviceProxy.Execute(associateConnectionRoles);



Code to Update the connectionrole instance

  ConnectionRole connectionRole = new ConnectionRole
  {
     ConnectionRoleId = _connectionRole1Id,
     Name = "Updated Connection Role",
     Description = "This is an updated connection role.",
     Category = new OptionSetValue(Categories.Other)
  };
  _serviceProxy.Update(connectionRole);



Code to create a connection between the account and the contact and assign a connection role to a record

  // Create an Account
  Account setupAccount = new Account { Name = "Example Account" };
  Guid _accountId = _serviceProxy.Create(setupAccount);

  // Create a Contact
  Contact setupContact = new Contact { LastName = "Example Contact" };
  Guid _contactId = _serviceProxy.Create(setupContact);


  // Create a connection between the account and the contact.
  // Assign a connection role to a record.
  Connection newConnection = new Connection
  {
     Record1Id = new EntityReference(Account.EntityLogicalName,
                            _accountId),
     Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     Record2RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     Record2Id = new EntityReference(Contact.EntityLogicalName,
                            _contactId)
  };
  Guid _connectionId = _serviceProxy.Create(newConnection);




Code to retrieves all connections related to contact record

  QueryExpression query = new QueryExpression
  {
     EntityName = Connection.EntityLogicalName,
     ColumnSet = new ColumnSet("connectionid"),
     Criteria = new FilterExpression
     {
          FilterOperator = LogicalOperator.And,
          Conditions =
          {
             // You can safely query against only record1id or
             // record2id - CRM will find all connections this
             // entity is a part of either way.
             new ConditionExpression
             {
                AttributeName = "record1id",
                Operator = ConditionOperator.Equal,
                Values = { _contactId }
             }
          }
       }
   };
   EntityCollection results = _serviceProxy.RetrieveMultiple(query);



Code to retrieves all connections related to specified object type code

   QueryExpression allQuery = new QueryExpression
   {
      EntityName = ConnectionRole.EntityLogicalName,
      ColumnSet = new ColumnSet("connectionroleid", "name"),
      Distinct = true,
      LinkEntities =
      {
         new LinkEntity
         {
            LinkToEntityName =
            ConnectionRoleObjectTypeCode.EntityLogicalName,
            LinkToAttributeName = "connectionroleid",
            LinkFromEntityName = ConnectionRole.EntityLogicalName,
            LinkFromAttributeName = "connectionroleid",
            LinkCriteria = new FilterExpression
            {
               FilterOperator = LogicalOperator.And,
               // Set a condition to only get connection roles
               // related to all entities (object type code = 0).
               Conditions =
               {
                    new ConditionExpression
                    {
                       AttributeName = "associatedobjecttypecode",
                       Operator = ConditionOperator.Equal,
                       Values = { 0 }
                     }
                }
             }
           }
        }
    };
    EntityCollection typecoderesults = _serviceProxy.RetrieveMultiple(allQuery);



Code to retrieves all connection roles that have this role listed as a reciprocal role

    QueryExpression reciprocalrolequery = new QueryExpression
    {
      EntityName = ConnectionRole.EntityLogicalName,
      ColumnSet = new ColumnSet("connectionroleid"),
      LinkEntities =
      {
         new LinkEntity
         {
            JoinOperator = JoinOperator.Inner,
            LinkFromEntityName =  ConnectionRole.EntityLogicalName,
            LinkFromAttributeName = "connectionroleid",
            LinkToEntityName = "connectionroleassociation",
            LinkToAttributeName = "connectionroleid",
            LinkCriteria = new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions =
                {
                    new ConditionExpression
                    {
                       AttributeName = "associatedconnectionroleid",
                       Operator = ConditionOperator.Equal,
                       Values = { _connectionRole2Id }                                      
                     }
                 }
             }
           }
       }
    };

    EntityCollection reciprocalroleresults = _serviceProxy.RetrieveMultiple(reciprocalrolequery);




Complete Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
           serverConfig.HomeRealmUri,
           serverConfig.Credentials,
           serverConfig.DeviceCredentials))
{
  _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

  // Define some anonymous types to define the range
  // of possible connection property values.
  var Categories = new
  {
    Business = 1,
    Family = 2,
    Social = 3,
    Sales = 4,
    Other = 5
  };


  // Create the Connection Role 1
  ConnectionRole newConnectionRole1 = new ConnectionRole
  {
    Name = "Example Connection Role 1",
    Category = new OptionSetValue(Categories.Business),
  };
  Guid _connectionRole1Id = _serviceProxy.Create(newConnectionRole1);

  // Create a related Connection Role Object Type Code record for Account
  ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode
           = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                  ConnectionRole.EntityLogicalName, _connectionRole1Id),
     AssociatedObjectTypeCode = Account.EntityLogicalName
  };

  _serviceProxy.Create(newAccountConnectionRole1TypeCode);

  // Create a related Connection Role Object Type Code record for Contact
  ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode
            = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                ConnectionRole.EntityLogicalName, _connectionRole1Id),
     AssociatedObjectTypeCode = Contact.EntityLogicalName
  };

  _serviceProxy.Create(newContactConnectionRole1TypeCode);



  // Create the Connection Role 2
  ConnectionRole newConnectionRole2 = new ConnectionRole
  {
     Name = "Example Connection Role 2",
     Category = new OptionSetValue(Categories.Business),
  };
  Guid _connectionRole2Id = _serviceProxy.Create(newConnectionRole2);

  // Create a related Connection Role 2 Object Type Code record for Account
  ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode
       = new ConnectionRoleObjectTypeCode
  {
      ConnectionRoleId = new EntityReference(
                  ConnectionRole.EntityLogicalName, _connectionRole2Id),
      AssociatedObjectTypeCode = Account.EntityLogicalName
  };
  _serviceProxy.Create(newAccountConnectionRole2TypeCode);

  // Create a related Connection Role 2 Object Type Code record for Contact
  ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode
            = new ConnectionRoleObjectTypeCode
  {
     ConnectionRoleId = new EntityReference(
                ConnectionRole.EntityLogicalName, _connectionRole2Id),
     AssociatedObjectTypeCode = Contact.EntityLogicalName
  };
  _serviceProxy.Create(newContactConnectionRole2TypeCode);



  // Associate the connection roles
  AssociateRequest associateConnectionRoles = new AssociateRequest
  {
     Target = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     RelatedEntities = new EntityReferenceCollection()
     {
         new EntityReference(ConnectionRole.EntityLogicalName,
                                _connectionRole2Id)
     },
     // The name of the relationship connection role association
     // relationship in MS CRM
     Relationship = new Relationship()
     {
       PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive    relationship.
       SchemaName = "connectionroleassociation_association"
     }
  };
  _serviceProxy.Execute(associateConnectionRoles);



  // Update the connectionrole instance.
  ConnectionRole connectionRole = new ConnectionRole
  {
     ConnectionRoleId = _connectionRole1Id,
     Name = "Updated Connection Role",
     Description = "This is an updated connection role.",
     Category = new OptionSetValue(Categories.Other)
  };
  _serviceProxy.Update(connectionRole);


  // Create an Account
  Account setupAccount = new Account { Name = "Example Account" };
  Guid _accountId = _serviceProxy.Create(setupAccount);

  // Create a Contact
  Contact setupContact = new Contact { LastName = "Example Contact" };
  Guid _contactId = _serviceProxy.Create(setupContact);


  // Create a connection between the account and the contact.
  // Assign a connection role to a record.
  Connection newConnection = new Connection
  {
     Record1Id = new EntityReference(Account.EntityLogicalName,
                            _accountId),
     Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     Record2RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                            _connectionRole1Id),
     Record2Id = new EntityReference(Contact.EntityLogicalName,
                            _contactId)
  };
  Guid _connectionId = _serviceProxy.Create(newConnection);


  // This query retrieves all connections related to contact record.
  QueryExpression query = new QueryExpression
  {
     EntityName = Connection.EntityLogicalName,
     ColumnSet = new ColumnSet("connectionid"),
     Criteria = new FilterExpression
     {
          FilterOperator = LogicalOperator.And,
          Conditions =
          {
             // You can safely query against only record1id or
             // record2id - CRM will find all connections this
             // entity is a part of either way.
             new ConditionExpression
             {
                AttributeName = "record1id",
                Operator = ConditionOperator.Equal,
                Values = { _contactId }
             }
          }
       }
   };
   EntityCollection results = _serviceProxy.RetrieveMultiple(query);


   // This query retrieves all connections related to specified object type code.
   QueryExpression allQuery = new QueryExpression
   {
      EntityName = ConnectionRole.EntityLogicalName,
      ColumnSet = new ColumnSet("connectionroleid", "name"),
      Distinct = true,
      LinkEntities =
      {
         new LinkEntity
         {
            LinkToEntityName =
            ConnectionRoleObjectTypeCode.EntityLogicalName,
            LinkToAttributeName = "connectionroleid",
            LinkFromEntityName = ConnectionRole.EntityLogicalName,
            LinkFromAttributeName = "connectionroleid",
            LinkCriteria = new FilterExpression
            {
               FilterOperator = LogicalOperator.And,
               // Set a condition to only get connection roles
               // related to all entities (object type code = 0).
               Conditions =
               {
                    new ConditionExpression
                    {
                       AttributeName = "associatedobjecttypecode",
                       Operator = ConditionOperator.Equal,
                       Values = { 0 }
                     }
                }
             }
           }
        }
    };
    EntityCollection typecoderesults = _serviceProxy.RetrieveMultiple(allQuery);


    // This query retrieves all connection roles that have this role
    // listed as a reciprocal role.
    QueryExpression reciprocalrolequery = new QueryExpression
    {
      EntityName = ConnectionRole.EntityLogicalName,
      ColumnSet = new ColumnSet("connectionroleid"),
      LinkEntities =
      {
         new LinkEntity
         {
            JoinOperator = JoinOperator.Inner,
            LinkFromEntityName =  ConnectionRole.EntityLogicalName,
            LinkFromAttributeName = "connectionroleid",
            LinkToEntityName = "connectionroleassociation",
            LinkToAttributeName = "connectionroleid",
            LinkCriteria = new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions =
                {
                    new ConditionExpression
                    {
                       AttributeName = "associatedconnectionroleid",
                       Operator = ConditionOperator.Equal,
                       Values = { _connectionRole2Id }                                      
                     }
                 }
             }
           }
       }
    };

    EntityCollection reciprocalroleresults = _serviceProxy.RetrieveMultiple(reciprocalrolequery);

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.