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;

}

Run ondemand workflow from C# code in CRM 2011


In this article , I am going to explain how to run ondemand workflow using C# code.

Code To get ondemand workflow


String _workflowName = "workflowname";
try
{
   ServerConnection serverConnect = new ServerConnection();
   ServerConnection.Configuration serverConfig = serverConnect.GetServerConfiguration();

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


   Workflow _Workflow = null;
   // Create the ColumnSet that indicates the properties to be retrieved.
   ColumnSet _columnsWorkflow = new ColumnSet(new string[] { "name", "workflowid" });

  // Create the ConditionExpression for association Name field.
  ConditionExpression _conditionAssociationName = new ConditionExpression();

  //Set the condition for the retrieval to be based on the workflow name.
  _conditionAssociationName.AttributeName = "name";
  _conditionAssociationName.Operator = ConditionOperator.Equal;
  _conditionAssociationName.Values.Add(_workflowName);

  ConditionExpression _type = new ConditionExpression();
  _type.AttributeName = "type";
  _type.Operator = ConditionOperator.Equal;
  _type.Values.Add("1");

  //Create the FilterExpression.
  FilterExpression _filterRetrieveWorkflow = new FilterExpression();
  _filterRetrieveWorkflow.FilterOperator = LogicalOperator.And;
 _filterRetrieveWorkflow.AddCondition(_conditionAssociationName);
 _filterRetrieveWorkflow.AddCondition(_type);

 //Create the QueryExpression object.
 QueryExpression _queryRetrieveWorkflow = new QueryExpression();
 _queryRetrieveWorkflow.EntityName = Workflow.EntityLogicalName;
 _queryRetrieveWorkflow.ColumnSet = _columnsWorkflow;
 _queryRetrieveWorkflow.Criteria = _filterRetrieveWorkflow;

 //Retrieve the workflow
 EntityCollection workflows = service.RetrieveMultiple(_queryRetrieveWorkflow);
 if (workflows.Entities.Count > 0)
 {
   _Workflow = (Workflow)workflows.Entities[0];
   EntityCollection entityCollection = GetentityCollections(service);

   //Workflow execute request and response
   ExecuteWorkflowRequest _requestExecuteWorkflow = new ExecuteWorkflowRequest();
   ExecuteWorkflowResponse _responseExecuteWorkflow = new ExecuteWorkflowResponse();
   _requestExecuteWorkflow.WorkflowId = _Workflow.Id;//.workflowid.Value;

   //Opportunity entity
   foreach (Entity entity in entityCollection.Entities)
  {
    Entity _association = (Entity)entity;
   _requestExecuteWorkflow.EntityId = new Guid(_association.Attributes["opportunityid"].ToString());
    _responseExecuteWorkflow =  (ExecuteWorkflowResponse)service.Execute(_requestExecuteWorkflow);

   }

  }
}
catch (System.Web.Services.Protocols.SoapException ex)
{
    string _error = ex.Detail.InnerText;
}
catch (Exception ex)
{
   if (ex.InnerException != null)
   {
    string _error = ex.InnerException.Message;
    }
}




Code To get all opportunity on which we need to run workflow


private EntityCollection GetentityCollections(IOrganizationService _crmService)
{
   QueryExpression fullUserQuery = new QueryExpression();
   fullUserQuery.EntityName = Opportunity.EntityLogicalName;

   ColumnSet _columns = new ColumnSet(new string[] { "opportunityid" });
   fullUserQuery.ColumnSet = _columns;
   fullUserQuery.Criteria = new FilterExpression();

   fullUserQuery.Criteria.Conditions.Add(new  ConditionExpression("opportunityratingcode", ConditionOperator.Equal, "3"));
   fullUserQuery.Criteria.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.Equal, 0));

   RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();

   retrieveRequest.Query = fullUserQuery;

   return ((RetrieveMultipleResponse)_crmService.Execute(retrieveRequest)).EntityCollection;
}