Tuesday, 1 May 2012

Code to Create an Opportunity Record and convert to Quote


In this article , I am going to explain in detail how to create Opportunity and convert opportunity to Quote

For better understanding , i divided code into multiple parts. explaining below

1. Creating a Unit Group
2. Creating a Few Products
3. Creating a Discount List and new Discount record
4. Creating a Price List and Price List Item
5. Creating a Opportunity
6. Creating a Opportunity Products
   (i)   Simple Opportunity Product Record
   (ii)  Creating a catalog product and override the price per unit
   (iii) Creating a write-in product with a manual discount
7. Retrieving Opportunity & Opportunity Products Record
8. Converting Opportunity to Quote



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.Crm.Sdk.Messages;



Code to create a Unit Group

  UoMSchedule newUnitGroup = new UoMSchedule
  {
      Name = "Unit Group 1",
      BaseUoMName = "Primary Unit"
  };
  Guid _unitGroupId = _serviceProxy.Create(newUnitGroup);

  // Retrieve the default unit id that was automatically created
  // when we created the Unit Group
  QueryExpression unitQuery = new QueryExpression
  {
    EntityName = UoM.EntityLogicalName,
    ColumnSet = new ColumnSet("uomid", "name"),
    Criteria = new FilterExpression
    {
       Conditions =
       {
          new ConditionExpression
             {
                AttributeName = "uomscheduleid",
                Operator = ConditionOperator.Equal,
                Values = { _unitGroupId }
              }
        }
     },
     PageInfo = new PagingInfo
     {
       PageNumber = 1,
       Count = 1
     }
  };
  UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];
  Guid _defaultUnitId = unit.UoMId.Value;



Code to create Products

  Product newProduct1 = new Product
  {
    ProductNumber = "1",
    Name = "Product 1",
    QuantityDecimal = 2,
    DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                            _unitGroupId),
    DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
  };
  Guid _product1Id = _serviceProxy.Create(newProduct1);

  Product newProduct2 = new Product
  {
      ProductNumber = "2",
      Name = "Product 2",
      QuantityDecimal = 3,
      DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                            _unitGroupId),
      DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
  };
  Guid _product2Id = _serviceProxy.Create(newProduct2);




Code to create Discount List and new Discount record

  DiscountType newDiscountType = new DiscountType
  {
     Name = "Discount List",
     IsAmountType = false
  };
  Guid _discountTypeId = _serviceProxy.Create(newDiscountType);

  // Create a new discount
  Discount newDiscount = new Discount
  {
    DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                            _discountTypeId),
    LowQuantity = 5,
    HighQuantity = 10,
    Percentage = 3
  };
  Guid _discountId = _serviceProxy.Create(newDiscount);



Code to create Price List and Price List Item

  PriceLevel newPriceList = new PriceLevel
  {
     Name = "Price List"
  };
  Guid _priceListId = _serviceProxy.Create(newPriceList);

  // Create a price list item for the first product and apply volume discount
  ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
  {
      PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Amount = new Money(20),
      DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                            _discountTypeId)
  };
  Guid _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

  // Create a price list item for the second product
  ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
  {
     PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
     ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
     UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
     Amount = new Money(20)
   };
   Guid _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);




Code to create Opportunity

   // Create a new opportunity
   Opportunity newOpportunity = new Opportunity
   {
      Name = "Example Opportunity",
      CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
      PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId)
   };
   Guid _opportunityId = _serviceProxy.Create(newOpportunity);





Code to create Opportunity Products


   // Create some opportunity products
   OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Quantity = 3,
      Tax = new Money(4.80m)
   };
   Guid _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

   // Create a catalog product and override the price per unit
   OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Quantity = 1,
      IsPriceOverridden = true,
      PricePerUnit = new Money(12),
      Tax = new Money(0.96m)
   };
   Guid _opportunityProduct2Id = _serviceProxy.Create(
                        newOpportunityProduct2);

   // Create a write-in product with a manual discount
   OpportunityProduct newWriteInProduct = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      // set this attribute to make it a write-in product
      IsProductOverridden = true,
      ProductDescription = "Example Write-in Product",
      PricePerUnit = new Money(20.00m),
      Quantity = 5,
      ManualDiscountAmount = new Money(10.50m),
      Tax = new Money(7.16m)
   };
   Guid _writeInProductId = _serviceProxy.Create(newWriteInProduct);



Code to Retrieving Opportunity & Opportunity Products Record

  Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
  Opportunity.EntityLogicalName, _opportunityId,new ColumnSet("name"));

  // Retrieve the related opportunity products
  QueryExpression opportunityProductsQuery = new QueryExpression
  {
     EntityName = OpportunityProduct.EntityLogicalName,
     ColumnSet = new ColumnSet("opportunityproductid", "volumediscountamount"),
     Criteria = new FilterExpression
     {
        Conditions =
        {
          new ConditionExpression
          {
             AttributeName = "opportunityid",
             Operator = ConditionOperator.Equal,
             Values = { _opportunityId }
           }
        }
     }
  };

  DataCollection<Entity> opportunityProducts = _serviceProxy.RetrieveMultiple(
                        opportunityProductsQuery).Entities;

  foreach (Entity entity in opportunityProducts)
  {
     OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
  }




Code to Converting Opportunity to Quote

  GenerateQuoteFromOpportunityRequest quoteRequest = new GenerateQuoteFromOpportunityRequest()
  {
    // Columns that will be transferred
    ColumnSet = new ColumnSet("name", "customerid"),
    OpportunityId = _opportunityId
  };
  GenerateQuoteFromOpportunityResponse quoteResponse =
                        (GenerateQuoteFromOpportunityResponse)_serviceProxy.Execute(quoteRequest);
  Guid _quoteId = quoteResponse.Entity.Id;




Complete Code

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

  // Create a unit group
  UoMSchedule newUnitGroup = new UoMSchedule
  {
      Name = "Unit Group 1",
      BaseUoMName = "Primary Unit"
  };
  Guid _unitGroupId = _serviceProxy.Create(newUnitGroup);

  // Retrieve the default unit id that was automatically created
  // when we created the Unit Group
  QueryExpression unitQuery = new QueryExpression
  {
    EntityName = UoM.EntityLogicalName,
    ColumnSet = new ColumnSet("uomid", "name"),
    Criteria = new FilterExpression
    {
       Conditions =
       {
          new ConditionExpression
             {
                AttributeName = "uomscheduleid",
                Operator = ConditionOperator.Equal,
                Values = { _unitGroupId }
              }
        }
     },
     PageInfo = new PagingInfo
     {
       PageNumber = 1,
       Count = 1
     }
  };
  UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];
  Guid _defaultUnitId = unit.UoMId.Value;



  // Create a few products
  Product newProduct1 = new Product
  {
    ProductNumber = "1",
    Name = "Product 1",
    QuantityDecimal = 2,
    DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                            _unitGroupId),
    DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
  };
  Guid _product1Id = _serviceProxy.Create(newProduct1);

  Product newProduct2 = new Product
  {
      ProductNumber = "2",
      Name = "Product 2",
      QuantityDecimal = 3,
      DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                            _unitGroupId),
      DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
  };
  Guid _product2Id = _serviceProxy.Create(newProduct2);



  // Create a new discount list
  DiscountType newDiscountType = new DiscountType
  {
     Name = "Discount List",
     IsAmountType = false
  };
  Guid _discountTypeId = _serviceProxy.Create(newDiscountType);

  // Create a new discount
  Discount newDiscount = new Discount
  {
    DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                            _discountTypeId),
    LowQuantity = 5,
    HighQuantity = 10,
    Percentage = 3
  };
  Guid _discountId = _serviceProxy.Create(newDiscount);




  // Create a price list
  PriceLevel newPriceList = new PriceLevel
  {
     Name = "Price List"
  };
  Guid _priceListId = _serviceProxy.Create(newPriceList);

  // Create a price list item for the first product and apply volume discount
  ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
  {
      PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Amount = new Money(20),
      DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                            _discountTypeId)
  };
  Guid _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

  // Create a price list item for the second product
  ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
  {
     PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
     ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
     UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
     Amount = new Money(20)
   };
   Guid _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);



   // Create an account record for the opporutnity's potential customerid
   Account newAccount = new Account
   {
      Name = "Account"
   };
   Guid _accountId = _serviceProxy.Create(newAccount);



   // Create a new opportunity
   Opportunity newOpportunity = new Opportunity
   {
      Name = "Example Opportunity",
      CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
      PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId)
   };
   Guid _opportunityId = _serviceProxy.Create(newOpportunity);

   // Create some opportunity products
   OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Quantity = 3,
      Tax = new Money(4.80m)
   };
   Guid _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

   // Create a catalog product and override the price per unit
   OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
      UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
      Quantity = 1,
      IsPriceOverridden = true,
      PricePerUnit = new Money(12),
      Tax = new Money(0.96m)
   };
   Guid _opportunityProduct2Id = _serviceProxy.Create(
                        newOpportunityProduct2);

   // Create a write-in product with a manual discount
   OpportunityProduct newWriteInProduct = new OpportunityProduct
   {
      OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
      // set this attribute to make it a write-in product
      IsProductOverridden = true,
      ProductDescription = "Example Write-in Product",
      PricePerUnit = new Money(20.00m),
      Quantity = 5,
      ManualDiscountAmount = new Money(10.50m),
      Tax = new Money(7.16m)
   };
   Guid _writeInProductId = _serviceProxy.Create(newWriteInProduct);



  // Retrieve Opportunity record.              
  Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
  Opportunity.EntityLogicalName, _opportunityId,new ColumnSet("name"));

  // Retrieve the related opportunity products
  QueryExpression opportunityProductsQuery = new QueryExpression
  {
     EntityName = OpportunityProduct.EntityLogicalName,
     ColumnSet = new ColumnSet("opportunityproductid", "volumediscountamount"),
     Criteria = new FilterExpression
     {
        Conditions =
        {
          new ConditionExpression
          {
             AttributeName = "opportunityid",
             Operator = ConditionOperator.Equal,
             Values = { _opportunityId }
           }
        }
     }
  };

  DataCollection<Entity> opportunityProducts = _serviceProxy.RetrieveMultiple(
                        opportunityProductsQuery).Entities;

  foreach (Entity entity in opportunityProducts)
  {
     OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
  }



  // Convert an opportunity to quote.
  GenerateQuoteFromOpportunityRequest quoteRequest = new GenerateQuoteFromOpportunityRequest()
  {
    // Columns that will be transferred
    ColumnSet = new ColumnSet("name", "customerid"),
    OpportunityId = _opportunityId
  };
  GenerateQuoteFromOpportunityResponse quoteResponse =
                        (GenerateQuoteFromOpportunityResponse)_serviceProxy.Execute(quoteRequest);
  Guid _quoteId = quoteResponse.Entity.Id;
}

No comments:

Post a Comment

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