Process Quotes, Sales Orders and Invoices

using System;
using System.ServiceModel;

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

namespace Microsoft.Crm.Sdk.Samples
{


//Demonstrates how to convert a quote to a sales order, and a sales order
//to an invoice. Also demonstrates locking/unlocking prices on both sales orders
//and invoices.

public class ProcessingQuotesAndSalesOrders
{
#region Class Level Members

private Guid _unitGroupId;
private Guid _defaultUnitId;
private Guid _productId;
private Guid _priceListId;
private Guid _priceListItemId;
private Guid _accountId;
private Guid _quoteId;
private Guid _quoteDetailId;
private Guid _salesOrderId;
private Guid _invoiceId;

private OrganizationServiceProxy _serviceProxy;

#endregion Class Level Members

#region How To Sample Code

This method first connects to the Organization service. Afterwards, a
//quote is created. This quote is then converted to an order, and the pricing
//is unlocked and relocked. This is followed by the order being converted
//to an invoice, and the pricing is locked then unlocked.

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

CreateRequiredRecords();

#region Create Quote

// Create a quote
Quote quote = new Quote()
{
CustomerId = new EntityReference(Account.EntityLogicalName,
_accountId),
Name = “Sample”,
PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
_priceListId)
};
_quoteId = _serviceProxy.Create(quote);
quote.Id = _quoteId;

// Set the quote’s product
QuoteDetail quoteDetail = new QuoteDetail()
{
ProductId = new EntityReference(Product.EntityLogicalName,
_productId),
Quantity = 1,
QuoteId = quote.ToEntityReference(),
UoMId = new EntityReference(UoM.EntityLogicalName,
_defaultUnitId)
};
_quoteDetailId = _serviceProxy.Create(quoteDetail);

Console.WriteLine(“Quote created.”);

// Activate the quote
SetStateRequest activateQuote = new SetStateRequest()
{
EntityMoniker = quote.ToEntityReference(),
State = new OptionSetValue((int)QuoteState.Active),
Status = new OptionSetValue(2)
};
_serviceProxy.Execute(activateQuote);

Console.WriteLine(“Quote activated.”);

// Mark the quote as won
// Note: this is necessary in order to convert a quote into a
// SalesOrder.
WinQuoteRequest winQuoteRequest = new WinQuoteRequest()
{
QuoteClose = new QuoteClose()
{
Subject = “Quote Close” + DateTime.Now.ToString(),
QuoteId = quote.ToEntityReference()
},
Status = new OptionSetValue(-1)
};
_serviceProxy.Execute(winQuoteRequest);

Console.WriteLine(“Quote won.”);

#endregion

#region Convert Quote to SalesOrder

// Define columns to be retrieved after creating the order
ColumnSet salesOrderColumns =
new ColumnSet(“salesorderid”, “totalamount”);

// Convert the quote to a sales order
ConvertQuoteToSalesOrderRequest convertQuoteRequest =
new ConvertQuoteToSalesOrderRequest()
{
QuoteId = _quoteId,
ColumnSet = salesOrderColumns
};
ConvertQuoteToSalesOrderResponse convertQuoteResponse =
(ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest);
SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity;
_salesOrderId = salesOrder.Id;

Console.WriteLine(“Converted Quote to SalesOrder.”);

#endregion

#region Lock pricing on SalesOrder

// Note: after converting a won quote to an order, the pricing of
// the order is locked by default.

// Retrieve current price list
ProductPriceLevel priceListItem =
(ProductPriceLevel)_serviceProxy.Retrieve(
ProductPriceLevel.EntityLogicalName,
_priceListItemId,
new ColumnSet(“productpricelevelid”, “amount”)
);

Console.WriteLine(“Current price list retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details before update:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current order total: {0}”,
salesOrder.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

// Update the price list
priceListItem.Amount = new Money(30.0M);

UpdateRequest updatePriceListItem = new UpdateRequest()
{
Target = priceListItem,
};
_serviceProxy.Execute(updatePriceListItem);

Console.WriteLine(“Price list updated.”);

// Retrieve the order
SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
SalesOrder.EntityLogicalName,
_salesOrderId,
new ColumnSet(“salesorderid”, “totalamount”)
);

Console.WriteLine(“Updated order retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details after update:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current order total: {0}”,
updatedSalesOrder.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

// Unlock the order pricing
UnlockSalesOrderPricingRequest unlockOrderRequest =
new UnlockSalesOrderPricingRequest()
{
SalesOrderId = _salesOrderId
};
_serviceProxy.Execute(unlockOrderRequest);

Console.WriteLine(“Order pricing unlocked.”);

// Retrieve the order
updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
SalesOrder.EntityLogicalName,
_salesOrderId,
new ColumnSet(“salesorderid”, “totalamount”)
);

Console.WriteLine(“Updated order retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details after update and unlock:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current order total: {0}”,
updatedSalesOrder.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

// Relock the order pricing
LockSalesOrderPricingRequest lockOrderRequest =
new LockSalesOrderPricingRequest()
{
SalesOrderId = _salesOrderId
};
_serviceProxy.Execute(lockOrderRequest);

Console.WriteLine(“Order pricing relocked.”);

#endregion

#region Convert SalesOrder to Invoice

// Define columns to be retrieved after creating the invoice
ColumnSet invoiceColumns =
new ColumnSet(“invoiceid”, “totalamount”);

// Convert the order to an invoice
ConvertSalesOrderToInvoiceRequest convertOrderRequest =
new ConvertSalesOrderToInvoiceRequest()
{
SalesOrderId = _salesOrderId,
ColumnSet = invoiceColumns
};
ConvertSalesOrderToInvoiceResponse convertOrderResponse =
(ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest);
Invoice invoice = (Invoice)convertOrderResponse.Entity;
_invoiceId = invoice.Id;

Console.WriteLine(“Converted SalesOrder to Invoice.”);

#endregion

#region Lock pricing on Invoice

// Retrieve current price list
priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve(
ProductPriceLevel.EntityLogicalName,
_priceListItemId,
new ColumnSet(“productpricelevelid”, “amount”)
);

Console.WriteLine(“Current price list retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details before lock and update:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current invoice total: {0}”,
invoice.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

// Lock the invoice pricing
LockInvoicePricingRequest lockInvoiceRequest =
new LockInvoicePricingRequest()
{
InvoiceId = _invoiceId
};
_serviceProxy.Execute(lockInvoiceRequest);

Console.WriteLine(“Invoice pricing locked.”);

// Update the price list
priceListItem.Amount = new Money(40.0M);

updatePriceListItem = new UpdateRequest()
{
Target = priceListItem
};
_serviceProxy.Execute(updatePriceListItem);

Console.WriteLine(“Price list updated.”);

// Retrieve the invoice
Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve(
Invoice.EntityLogicalName,
_invoiceId,
new ColumnSet(“invoiceid”, “totalamount”)
);

Console.WriteLine(“Updated invoice retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details after lock and update:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current invoice total: {0}”,
updatedInvoice.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

// Unlock the invoice pricing
UnlockInvoicePricingRequest unlockInvoiceRequest =
new UnlockInvoicePricingRequest()
{
InvoiceId = _invoiceId
};
_serviceProxy.Execute(unlockInvoiceRequest);

Console.WriteLine(“Invoice pricing unlocked.”);

// Retrieve the invoice
updatedInvoice = (Invoice)_serviceProxy.Retrieve(
Invoice.EntityLogicalName,
_invoiceId,
new ColumnSet(“invoiceid”, “totalamount”)
);

Console.WriteLine(“Updated invoice retrieved.”);
Console.WriteLine();

Console.WriteLine(“Details after update and unlock:”);
Console.WriteLine(“—————-”);
Console.WriteLine(“Current invoice total: {0}”,
updatedInvoice.TotalAmount.Value);
Console.WriteLine(“Current price per item: {0}”,
priceListItem.Amount.Value);
Console.WriteLine(““);
Console.WriteLine();

#endregion

DeleteRequiredRecords(promptforDelete);
}
}

// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}

///

/// Creates any entity records that this sample requires.
///

public void CreateRequiredRecords()
{
// Create a unit group
UoMSchedule newUnitGroup = new UoMSchedule
{
Name = “Example Unit Group”,
BaseUoMName = “Example Primary Unit”
};
_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
}
};

// Retrieve the unit.
UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];
_defaultUnitId = unit.UoMId.Value;

// Create a few products
Product newProduct = new Product
{
ProductNumber = “1″,
Name = “Example Product”,
QuantityDecimal = 1,
DefaultUoMScheduleId =
new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
DefaultUoMId =
new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
};
_productId = _serviceProxy.Create(newProduct);
newProduct.Id = _productId;

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

// Create a price list item for the first product and apply volume discount
ProductPriceLevel newPriceListItem = new ProductPriceLevel
{
PriceLevelId =
new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
ProductId =
new EntityReference(Product.EntityLogicalName, _productId),
UoMId =
new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
Amount = new Money(20.0M),
};
_priceListItemId = _serviceProxy.Create(newPriceListItem);

// Create an account record for the opportunity’s potential customerid
Account newAccount = new Account
{
Name = “Litware, Inc.”,
Address1_PostalCode = “60661″
};
_accountId = _serviceProxy.Create(newAccount);
newAccount.Id = _accountId;

}

///

/// Deletes any entity records that were created for this sample.
/// Indicates whether to prompt the user
/// to delete the records created in this sample. ///

public void DeleteRequiredRecords(bool prompt)
{
// The three system users that were created by this sample will continue to
// exist on your system because system users cannot be deleted in Microsoft
// Dynamics CRM. They can only be enabled or disabled.

bool toBeDeleted = true;

if (prompt)
{
// Ask the user if the created entities should be deleted.
Console.Write(“\nDo you want these entity records deleted? (y/n) [y]: “);
String answer = Console.ReadLine();
if (answer.StartsWith(“y”) ||
answer.StartsWith(“Y”) ||
answer == String.Empty)
{
toBeDeleted = true;
}
else
{
toBeDeleted = false;
}
}

if (toBeDeleted)
{
// Delete all records created in this sample.
_serviceProxy.Delete(“invoice”, _invoiceId);
_serviceProxy.Delete(“salesorder”, _salesOrderId);
_serviceProxy.Delete(“quotedetail”, _quoteDetailId);
_serviceProxy.Delete(“quote”, _quoteId);
_serviceProxy.Delete(“account”, _accountId);
_serviceProxy.Delete(“productpricelevel”, _priceListItemId);
_serviceProxy.Delete(“pricelevel”, _priceListId);
_serviceProxy.Delete(“product”, _productId);
_serviceProxy.Delete(“uomschedule”, _unitGroupId);

Console.WriteLine(“Entity record(s) have been deleted.”);
}
}

#endregion How To Sample Code

#region Main method

///

/// Standard Main() method used by most SDK samples.
///

/// static public void Main(string[] args)
{
try
{
// Obtain the target organization’s Web address and client logon
// credentials from the user.
ServerConnection serverConnect = new ServerConnection();
ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

ProcessingQuotesAndSalesOrders app = new ProcessingQuotesAndSalesOrders();
app.Run(config, true);
}
catch (FaultException ex)
{
Console.WriteLine(“The application terminated with an error.”);
Console.WriteLine(“Timestamp: {0}”, ex.Detail.Timestamp);
Console.WriteLine(“Code: {0}”, ex.Detail.ErrorCode);
Console.WriteLine(“Message: {0}”, ex.Detail.Message);
Console.WriteLine(“Plugin Trace: {0}”, ex.Detail.TraceText);
Console.WriteLine(“Inner Fault: {0}”,
null == ex.Detail.InnerFault ? “Has Inner Fault” : “No Inner Fault”);
}
catch (System.TimeoutException ex)
{
Console.WriteLine(“The application terminated with an error.”);
Console.WriteLine(“Message: {0}”, ex.Message);
Console.WriteLine(“Stack Trace: {0}”, ex.StackTrace);
Console.WriteLine(“Inner Fault: {0}”,
null == ex.InnerException.Message ? “Has Inner Fault” : “No Inner Fault”);
}
catch (System.Exception ex)
{
Console.WriteLine(“The application terminated with an error.”);
Console.WriteLine(ex.Message);

// Display the details of the inner exception.
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);

FaultException fe = ex.InnerException
as FaultException;
if (fe != null)
{
Console.WriteLine(“Timestamp: {0}”, fe.Detail.Timestamp);
Console.WriteLine(“Code: {0}”, fe.Detail.ErrorCode);
Console.WriteLine(“Message: {0}”, fe.Detail.Message);
Console.WriteLine(“Plugin Trace: {0}”, fe.Detail.TraceText);
Console.WriteLine(“Inner Fault: {0}”,
null == fe.Detail.InnerFault ? “Has Inner Fault” : “No Inner Fault”);
}
}
}
// Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
// SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

finally
{
Console.WriteLine(“Press to exit.”);
Console.ReadLine();
}
}
#endregion Main method
}
}

This entry was posted in MS Dynamic CRM 2011. Bookmark the permalink.

6 Responses to Process Quotes, Sales Orders and Invoices

  1. Nancy says:

    Thanks for the share!
    Nancy.R

  2. pregnancy says:

    We so appreciate your website post. You’ll find hundreds of approaches we could put it to very good use with no effort in time and hard earned money. Thank you so much for helping make this post give light to many queries we have had before now.

  3. Many thanks for your efforts to have had these things together on this blog. Robin and i also very much liked your insight through your articles on certain things. I realize that you have several demands on your timetable and so the fact that you took equally as much time as you did to guide people like us via this article is actually highly valued.

  4. micro nichos says:

    I merely wanted to tell you how much I appreciate every thing you’ve provided to help enhance the lives of individuals in this subject matter. Through your articles, I’ve gone via just a newcomer to an expert in the area. It’s truly a homage to your endeavours. Thanks

  5. We so appreciate your blog post. You can find a multitude of tactics we could put it to decent use by means of minimum effort on time and hard earned money. Thank you really for helping make the post give light to many questions we have had before now.

  6. We extremely appreciate your site post. You’ll find lots of ways we could put it to great use while using minimal effort with time and financial resources. Thank you really pertaining to helping make the post give light to many queries we have had before now.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>