Tuesday, 26 June 2012

Code to create , retrieve ,deactivate , renew an invoiced Contract and Contract Template in CRM 2011


In this article , I am going to explain a Contract Template and several Contracts are created and also demonstrating how to create and work with the Contract entity.

For Better Understanding I divided this article in multiple part

(i)   Create and Retrieve Contract Template
(ii)  Create Contract & Contract Line Item using Contract Template
(iii) Create the clone of the contract
(iv)  Deactivate a contract
(v)   Renew an invoiced contract
(vi)  Renew the canceled contract

Namespace need to include

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



Create and Retrieve Contract Template

 Guid _contractTemplateId;
   QueryExpression templateQuery = new QueryExpression()
   {
      EntityName = ContractTemplate.EntityLogicalName,
      ColumnSet = new ColumnSet("contracttemplateid"),
      Criteria =
      {
          Conditions =
          {
             new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT")
          }
      }
   };
   EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery);
   if (ec.Entities.Count > 0)
   {
       _contractTemplateId = ec.Entities[0].Id;
   }
   else
   {
      ContractTemplate contractTemplate = new ContractTemplate()
      {
         Name = "Sample Contract Template",
         BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly),
                            Abbreviation = "SCT",
         AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases),
         EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------"
      };
      _contractTemplateId = _serviceProxy.Create(contractTemplate);
   }

Create Contract & Contract Line Item using Contract Template

  Contract contract = new Contract()
  {
     Title = "Sample Contract",
     ContractTemplateId = new EntityReference
     {
         Id = _contractTemplateId,
         LogicalName = ContractTemplate.EntityLogicalName
     },
     CustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     BillingCustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     ActiveOn = new DateTime(2015, 1, 1),
     ExpiresOn = new DateTime(2020, 1, 1),
     BillingStartOn = new DateTime(2015, 1, 1),
     BillingEndOn = new DateTime(2020, 1, 1)
  };
  Guid _contractId = _serviceProxy.Create(contract);

  // Create a contract line item.
  ContractDetail contractLineItem = new ContractDetail()
  {
    Title = "Sample Contract Line Item",
    ContractId = new EntityReference
    {
        Id = _contractId,
        LogicalName = Contract.EntityLogicalName
    },
    CustomerId = new EntityReference
    {
       Id = _accountId,
       LogicalName = Account.EntityLogicalName
    },
    ActiveOn = new DateTime(2015, 1, 1),
    ExpiresOn = new DateTime(2020, 1, 1),
    Price = new Money(20.0M),
    TotalAllotments = 20
  };
  _serviceProxy.Create(contractLineItem);


Create the clone of the contract

  CloneContractRequest cloneRequest = new CloneContractRequest()
  {
     ContractId = _contractId,
     IncludeCanceledLines = false
  };
  CloneContractResponse cloneResponse =
                        (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;

  // Create the second clone of the contract.
  cloneRequest = new CloneContractRequest()
                    {
                        ContractId = _contractId,
                        IncludeCanceledLines = true
                    };
  cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;


Deactivate a contract

  SetStateRequest setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _firstCloneId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(2)
  };
  _serviceProxy.Execute(setStateRequest);



  // Now that the contract has been invoiced, it is possible to put
  // the contract on hold.
  setStateRequest = new SetStateRequest()
  {
     EntityMoniker = new EntityReference
     {
        Id = _firstCloneId,
        LogicalName = Contract.EntityLogicalName
     },
     State = new OptionSetValue(3),
     Status = new OptionSetValue(4)
   };
   _serviceProxy.Execute(setStateRequest);


Renew an invoiced contract

  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(3)
  };
  _serviceProxy.Execute(setStateRequest);


  // Cancel the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(4),
    Status = new OptionSetValue(5)
  };
  _serviceProxy.Execute(setStateRequest);


Renew the canceled contract

  RenewContractRequest renewRequest = new RenewContractRequest()
  {
    ContractId = _contractId,
    IncludeCanceledLines = true,
    Status = 1
  };
  RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest);

  // Retrieve Id of renewed contract.
  Guid _renewedId = ((Contract)renewResponse.Entity).ContractId.Value;




Complete Code

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

   Guid _accountId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");

   // Create Contract Template

   // First, attempt to retrieve the Contract Template. Otherwise,
   // create the template.
   Guid _contractTemplateId;
   QueryExpression templateQuery = new QueryExpression()
   {
      EntityName = ContractTemplate.EntityLogicalName,
      ColumnSet = new ColumnSet("contracttemplateid"),
      Criteria =
      {
          Conditions =
          {
             new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT")
          }
      }
   };
   EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery);
   if (ec.Entities.Count > 0)
   {
       _contractTemplateId = ec.Entities[0].Id;
   }
   else
   {
      ContractTemplate contractTemplate = new ContractTemplate()
      {
         Name = "Sample Contract Template",
         BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly),
                            Abbreviation = "SCT",
         AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases),
         EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------"
      };
      _contractTemplateId = _serviceProxy.Create(contractTemplate);
   }




  // Create Contract

  // Create a Contract from the Contract Template.
  Contract contract = new Contract()
  {
     Title = "Sample Contract",
     ContractTemplateId = new EntityReference
     {
         Id = _contractTemplateId,
         LogicalName = ContractTemplate.EntityLogicalName
     },
     CustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     BillingCustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     ActiveOn = new DateTime(2015, 1, 1),
     ExpiresOn = new DateTime(2020, 1, 1),
     BillingStartOn = new DateTime(2015, 1, 1),
     BillingEndOn = new DateTime(2020, 1, 1)
  };
  Guid _contractId = _serviceProxy.Create(contract);

  // Create a contract line item.
  ContractDetail contractLineItem = new ContractDetail()
  {
    Title = "Sample Contract Line Item",
    ContractId = new EntityReference
    {
        Id = _contractId,
        LogicalName = Contract.EntityLogicalName
    },
    CustomerId = new EntityReference
    {
       Id = _accountId,
       LogicalName = Account.EntityLogicalName
    },
    ActiveOn = new DateTime(2015, 1, 1),
    ExpiresOn = new DateTime(2020, 1, 1),
    Price = new Money(20.0M),
    TotalAllotments = 20
  };
  _serviceProxy.Create(contractLineItem);



  // Clone contract twice

  // Create the first clone of the contract.
  CloneContractRequest cloneRequest = new CloneContractRequest()
  {
     ContractId = _contractId,
     IncludeCanceledLines = false
  };
  CloneContractResponse cloneResponse =
                        (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;

  // Create the second clone of the contract.
  cloneRequest = new CloneContractRequest()
                    {
                        ContractId = _contractId,
                        IncludeCanceledLines = true
                    };
  cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;



  // Retrieve all Contracts.
  QueryExpression contractQuery = new QueryExpression()
  {
     EntityName = Contract.EntityLogicalName,
     ColumnSet = new ColumnSet("contractid"),
     Criteria =
     {
        Conditions =
        {
            new ConditionExpression("customerid", ConditionOperator.Equal, _accountId)
        }
     }
  };
  EntityCollection contracts = _serviceProxy.RetrieveMultiple(contractQuery);


  // Deactivate a cloned contract

  // In order to deactivate a contract (put it on hold), it is first
  // necessary to invoice the contract.
  SetStateRequest setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _firstCloneId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(2)
  };
  _serviceProxy.Execute(setStateRequest);



  // Now that the contract has been invoiced, it is possible to put
  // the contract on hold.
  setStateRequest = new SetStateRequest()
  {
     EntityMoniker = new EntityReference
     {
        Id = _firstCloneId,
        LogicalName = Contract.EntityLogicalName
     },
     State = new OptionSetValue(3),
     Status = new OptionSetValue(4)
   };
   _serviceProxy.Execute(setStateRequest);



  // Renew an invoiced contract

  // In order to renew a contract, it must be invoiced first, and
  // then canceled.

  // Invoice the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(3)
  };
  _serviceProxy.Execute(setStateRequest);


  // Cancel the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(4),
    Status = new OptionSetValue(5)
  };
  _serviceProxy.Execute(setStateRequest);



  // Renew the canceled contract.
  RenewContractRequest renewRequest = new RenewContractRequest()
  {
    ContractId = _contractId,
    IncludeCanceledLines = true,
    Status = 1
  };
  RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest);

  // Retrieve Id of renewed contract.
  Guid _renewedId = ((Contract)renewResponse.Entity).ContractId.Value;

}

No comments:

Post a Comment

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