Calculating Cart total with discount applied at runtime in MS Commerce Server

This tip demonstrates how to format a cart at runtime and calculate the total (including discount amount) in MS Commerce Server. The steps are:

Step 1: Create a new basket.

For Example:

Basket newBasket=OrderManager.GetBasket(Guid.NewGuid());

Step 2 : Add lineitems to the cart.
For example:

CommerceServerLineItem csLineItem = new CommerceServerLineItem();
csLineItem.ProductId ="1";
csLineItem.ProductCatalog = "Catalog";
csLineItem.ProductCategory = "ProductCat";
csLineItem.Quantity = 1;
csLineItem.UnitWeight = 2.5;
csLineItem.UnitType ="lbs";

 Step 3 : Execute the basket pipeline component.
For example:

PipelineInfo pipeLineInfo = new PipelineInfo("basket");
PipelineExecutionResult pipeLineExecutionResult = basket.RunPipeline(pipeLineInfo);

 Step 4: Now we can get the actuall amount that must be charged to the customer after the discount applied.We can get the Gross Total, Discount  and Net amount.
For Example:

decimal totalListPrice = newBasket.OrderForms[0].LineItems[0].ListPrice * quantity;
decimal netAmount = newBasket.OrderForms[0].SubTotal;
decimal discount = totalListPrice - netAmount

If we need to show other amounts like Shipping Discount, Tax then perform following steps otherwise move to Step 7

Step 5 : Make sure the tax calculation and shipping calculation components are present in the Total pipeline. Now assign the shipping address to the basket.
For example

OrderAddress csShippingAddress = new OrderAddress;
// TO DO : Assign address to the csShippingAddress
newBasket.SetShippingAddress(csShippingAddress.OrderAddressId);
newBasket.Addresses.Add(csShippingAddress);

Step 6 : Now execute the total pipeline component to get the calculation done.

Step 7 : Now delete the basket to make the memory free.
For example:

newBasket.Delete();
150 150 Burnignorance | Where Minds Meet And Sparks Fly!