/// <summary> /// 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. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetProcessingQuotesAndSalesOrders1> // 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.EnableProxyTypes(); CreateRequiredRecords(); #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity<Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity<Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // 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 Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // 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."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // 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; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // 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("</End of Listing>"); 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."); //</snippetUpdateRequest> // 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("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> 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("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #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; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // 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("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // 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("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // 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("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void TestLoseOpportunity() { using (var context = new Xrm(orgAdminUIService)) { var opportunity = new Opportunity(); opportunity.Id = orgAdminUIService.Create(opportunity); var loseReq = new LoseOpportunityRequest(); var opclose = new OpportunityClose() { ActualRevenue = 1000m, ActualEnd = DateTime.Now, StatusCode = OpportunityClose_StatusCode.Canceled, OpportunityId = opportunity.ToEntityReference() }; loseReq.OpportunityClose = opclose; loseReq.Status = new OptionSetValue((int)Opportunity_StatusCode.Canceled); orgAdminUIService.Execute(loseReq); var retrieved = orgAdminUIService.Retrieve(Opportunity.EntityLogicalName, opportunity.Id, new ColumnSet(true)) as Opportunity; Assert.AreEqual(OpportunityState.Lost, retrieved.StateCode); Assert.AreEqual(Opportunity_StatusCode.Canceled, retrieved.StatusCode); Assert.IsTrue(crm.ContainsEntity(opclose)); Assert.AreEqual("SetFromWinLose", retrieved.Description); } }
// Execute plugin logic protected void Execute(LocalPluginContext context) { var ctx = context.PluginExecutionContext; var opportunityId = ctx.PrimaryEntityId; var message = ctx.MessageName; if (message == "Lose") { var loseRequest = new LoseOpportunityRequest { Parameters = ctx.InputParameters }; opportunityId = loseRequest.OpportunityClose.ToEntity <OpportunityClose>().OpportunityId.Id; } else if (message == "Win") { var winRequest = new WinOpportunityRequest { Parameters = ctx.InputParameters }; opportunityId = winRequest.OpportunityClose.ToEntity <OpportunityClose>().OpportunityId.Id; } var upd = new Opportunity(opportunityId); upd.Description = "SetFromWinLose"; context.OrganizationAdminService.Update(upd); }
public static MsCrmResult CloseOppAsLost(Guid oppId, int statusCode, DateTime actualEnd, IOrganizationService service) { MsCrmResult returnValue = new MsCrmResult(); try { if (oppId != Guid.Empty) { LoseOpportunityRequest req = new LoseOpportunityRequest(); Entity opportunityClose = new Entity("opportunityclose"); opportunityClose["opportunityid"] = new EntityReference("opportunity", oppId); opportunityClose["subject"] = "Lost the Opportunity!"; opportunityClose["actualend"] = actualEnd; req.OpportunityClose = opportunityClose; req.Status = new OptionSetValue(statusCode); // Durum açıklaması "Kaybedildi" LoseOpportunityResponse resp = (LoseOpportunityResponse)service.Execute(req); returnValue.Success = true; returnValue.Result = "Fırsat kaybedildi olarak kapatıldı."; } } catch (Exception ex) { returnValue.Success = false; returnValue.Result = "Beklenmedik bir hata ile karşılaşıldı. Hata = " + ex.Message; } return(returnValue); }
public void Check_if_Opportunity_status_is_Lose_after_set() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var opportunity = new Opportunity() { Id = Guid.NewGuid() }; context.Initialize(new[] { opportunity }); var request = new LoseOpportunityRequest() { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, opportunity.Id) }, Status = new OptionSetValue((int)OpportunityState.Lost) }; service.Execute(request); var opp = (from op in context.CreateQuery <Opportunity>() where op.Id == opportunity.Id select op).FirstOrDefault(); Assert.Equal(opp.StatusCode.Value, (int)OpportunityState.Lost); }
private void TransformEntity(Entity entity) { OptionSetValue statuscode = new OptionSetValue(); OptionSetValue statecode = new OptionSetValue(); statuscode = (OptionSetValue)entity.Attributes["statuscode"]; statecode = (OptionSetValue)entity.Attributes["statecode"]; entity.Attributes.Remove("statuscode"); entity.Attributes.Remove("statecode"); Service.Create(entity); Entity opportunityClose = new Entity("opportunityclose"); opportunityClose.Attributes.Add("opportunityid", new EntityReference("opportunity", entity.Id)); switch (statecode.Value) { case 0: entity.Attributes.Add("statuscode", statuscode); entity.Attributes.Add("statecode", statecode); Service.Update(entity); break; case 1: WinOpportunityRequest winOpportunityRequest = new WinOpportunityRequest(); winOpportunityRequest.Status = statuscode; winOpportunityRequest.RequestId = entity.Id; winOpportunityRequest.OpportunityClose = opportunityClose; Service.Execute(winOpportunityRequest); break; case 2: LoseOpportunityRequest loseOpportunityRequest = new LoseOpportunityRequest(); loseOpportunityRequest.Status = statuscode; loseOpportunityRequest.RequestId = entity.Id; loseOpportunityRequest.OpportunityClose = opportunityClose; Service.Execute(loseOpportunityRequest); break; default: break; } }
public void PerformTestSetup() { MessageName = "Lose"; var opportunityEntity = EntityFactory.CreateOpportunity(); var opportunityClose = new Entity("opportunityclose"); opportunityClose["opportunityid"] = opportunityEntity.ToEntityReference(); opportunityClose["subject"] = "Lost!"; opportunityClose["actualend"] = DateTime.Now; opportunityClose["description"] = "Lost!"; LoseOpportunityRequest = new LoseOpportunityRequest { OpportunityClose = opportunityClose, Status = new OptionSetValue(5) }; }
public LoseOpportunityResponse LoseOpportunity(EntityReference entityReference) { var portal = PortalCrmConfigurationManager.CreatePortalContext(); var context = portal.ServiceContext; var opportunityClose = new Entity("opportunityclose"); opportunityClose.Attributes["subject"] = "Opportunity closed as lost via Web Portal" + DateTime.Now.ToString(CultureInfo.InvariantCulture); opportunityClose.Attributes["opportunityid"] = entityReference; var loseOpportunityRequest = new LoseOpportunityRequest() { OpportunityClose = opportunityClose, Status = new OptionSetValue((int)OpportunityStatusCode.Canceled) }; var loseOpportunityResponse = (LoseOpportunityResponse)context.Execute(loseOpportunityRequest); return(loseOpportunityResponse); }
protected override void ExecuteWorkflowLogic() { var opportunityClose = new Entity("opportunityclose") { ["subject"] = Subject.Get(Context.ExecutionContext), ["opportunityid"] = Opportunity.Get(Context.ExecutionContext), ["actualrevenue"] = ActualRevenue.Get(Context.ExecutionContext), ["actualend"] = CloseDate.Get(Context.ExecutionContext), ["competitorid"] = Competitor.Get(Context.ExecutionContext), ["description"] = Description.Get(Context.ExecutionContext) }; var loseOpportunityRequest = new LoseOpportunityRequest() { Status = OpportunityStatus.Get(Context.ExecutionContext), OpportunityClose = opportunityClose }; Context.UserService.Execute(loseOpportunityRequest); }
/// <summary> /// <c>Lose</c> an opportunity. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.loseopportunityrequest(v=crm.7).aspx /// </para> /// </summary> /// <param name="id"><c>Opportunity</c> Id</param> /// <param name="competitorId">Competitor</param> /// <param name="status"><see cref="OpportunityLostStatusCode"/> status code</param> /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param> /// <param name="opportunitycloseSubject"><c>OpportunityClose</c> subject</param> /// <param name="opportunitycloseDescription"><c>OpportunityClose</c> description</param> /// <param name="opportunitycloseActualEnd"><c>OpportunityClose</c> actual end date. Default value is <c>DateTime.UtcNow</c> or <c>DateTime.Now</c> depend on <c>useUtc</c> parameter on constructor</param> /// <param name="opportunitycloseActualRevenue"><c>OpportunityClose</c> actual revenue. Mostly this parameter's value is 0 (zero) when you lost an opportunity</param> /// <returns><see cref="LoseOpportunityResponse"/></returns> public LoseOpportunityResponse Lose(Guid id, Guid?competitorId, OpportunityLostStatusCode status, int customStatusCode = 0, string opportunitycloseSubject = "", string opportunitycloseDescription = "", DateTime?opportunitycloseActualEnd = null, decimal opportunitycloseActualRevenue = 0) { ExceptionThrow.IfGuidEmpty(id, "id"); int statusCode = (int)status; opportunitycloseSubject = !string.IsNullOrEmpty(opportunitycloseSubject) ? opportunitycloseSubject.Trim() : "Opportunity Close - Lose"; if (status == OpportunityLostStatusCode.CustomStatusCode) { ExceptionThrow.IfNegative(customStatusCode, "customStatusCode"); statusCode = customStatusCode; } LoseOpportunityRequest request = new LoseOpportunityRequest() { OpportunityClose = PrepareOpportunityCloseEntity(id, opportunitycloseSubject, opportunitycloseDescription, competitorId, opportunitycloseActualEnd, opportunitycloseActualRevenue), Status = new OptionSetValue(statusCode) }; return((LoseOpportunityResponse)this.OrganizationService.Execute(request)); }
/// <summary> /// This will close an opportunity as either Won or lost in CRM /// </summary> /// <param name="opportunityId">ID of the opportunity to close</param> /// <param name="fieldList">List of fields for the Opportunity Close Entity</param> /// <param name="opportunityStatusCode">Status code of Opportunity, Should be either 1 or 2, defaults to 1 ( won )</param> /// <param name="batchId">Optional: if set to a valid GUID, generated by the Create Batch Request Method, will assigned the request to the batch for later execution, on fail, runs the request immediately </param> /// <param name="cdsServiceClient">Connected CDS Service Client</param> /// <param name="bypassPluginExecution">Adds the bypass plugin behavior to this request. Note: this will only apply if the caller has the prvBypassPlugins permission to bypass plugins. If its attempted without the permission the request will fault.</param> /// <returns></returns> public static Guid CloseOpportunity(this CdsServiceClient cdsServiceClient, Guid opportunityId, Dictionary <string, CdsDataTypeWrapper> fieldList, int opportunityStatusCode = 3, Guid batchId = default(Guid), bool bypassPluginExecution = false) { cdsServiceClient.logEntry.ResetLastError(); // Reset Last Error if (cdsServiceClient._CdsService == null) { cdsServiceClient.logEntry.Log("Crm Service not initialized", TraceEventType.Error); return(Guid.Empty); } if (opportunityId == Guid.Empty) { return(Guid.Empty); } if (opportunityStatusCode < 3) { return(Guid.Empty); } Guid actId = Guid.Empty; Entity uEnt = new Entity("opportunityclose"); AttributeCollection PropertyList = new AttributeCollection(); #region MapCode if (fieldList != null) { foreach (KeyValuePair <string, CdsDataTypeWrapper> field in fieldList) { cdsServiceClient.AddValueToPropertyList(field, PropertyList); } } // Add the key... // check to see if the key is in the import set allready if (fieldList != null && !fieldList.ContainsKey("opportunityid")) { PropertyList.Add(new KeyValuePair <string, object>("opportunityid", opportunityId)); } if (fieldList != null && fieldList.ContainsKey("activityid")) { actId = (Guid)fieldList["activityid"].Value; } else { actId = Guid.NewGuid(); uEnt.Id = actId; } #endregion uEnt.Attributes.AddRange(PropertyList.ToArray()); // 2 types of close supported... Won or Lost. if (opportunityStatusCode == 3) { WinOpportunityRequest req = new WinOpportunityRequest(); req.OpportunityClose = uEnt; req.Status = new OptionSetValue(opportunityStatusCode); if (cdsServiceClient.AddRequestToBatch(batchId, req, "Calling Close Opportunity as Won", "Request to Close Opportunity as Won Queued", bypassPluginExecution)) { return(Guid.Empty); } WinOpportunityResponse resp = (WinOpportunityResponse)cdsServiceClient.CdsCommand_Execute(req, "Closing a Opportunity in CRM as Won", bypassPluginExecution); if (resp != null) { return(actId); } else { return(Guid.Empty); } } else { LoseOpportunityRequest req = new LoseOpportunityRequest(); req.OpportunityClose = uEnt; req.Status = new OptionSetValue(opportunityStatusCode); if (cdsServiceClient.AddRequestToBatch(batchId, req, "Calling Close Opportunity as Lost", "Request to Close Opportunity as Lost Queued", bypassPluginExecution)) { return(Guid.Empty); } LoseOpportunityResponse resp = (LoseOpportunityResponse)cdsServiceClient.CdsCommand_Execute(req, "Closing a Opportunity in CRM as Lost", bypassPluginExecution); if (resp != null) { return(actId); } else { return(Guid.Empty); } } }
public static void executeMultipleCloseOpportunity(EntityCollection entities, IOrganizationService service) { ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = true }, Requests = new OrganizationRequestCollection() }; foreach (Entity e in entities.Entities) { if (((OptionSetValue)e["statecode"]).Value == 1) { WinOpportunityRequest req = new WinOpportunityRequest(); Entity opportunityClose = new Entity("opportunityclose"); opportunityClose["opportunityid"] = new EntityReference("opportunity", e.Id); opportunityClose["subject"] = "Win the Opportunity!"; opportunityClose["actualend"] = (DateTime)e["actualend"]; req.OpportunityClose = opportunityClose; req.Status = (OptionSetValue)e["statuscode"]; multipleRequest.Requests.Add(req); } else if (((OptionSetValue)e["statecode"]).Value == 2) { LoseOpportunityRequest req = new LoseOpportunityRequest(); Entity opportunityClose = new Entity("opportunityclose"); opportunityClose["opportunityid"] = new EntityReference("opportunity", e.Id); opportunityClose["subject"] = "Lost the Opportunity!"; opportunityClose["actualend"] = (DateTime)e["actualend"]; req.OpportunityClose = opportunityClose; req.Status = (OptionSetValue)e["statuscode"]; multipleRequest.Requests.Add(req); } } //This is how to get responses ExecuteMultipleResponse executeResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest); if (executeResponse.Results != null) { //Loop through responses foreach (ExecuteMultipleResponseItem responseItem in executeResponse.Responses) { if (responseItem.Response != null) { //Awesome, command completed as expected //success++; } else if (responseItem.Fault != null) { OrganizationRequest req = multipleRequest.Requests[responseItem.RequestIndex]; if (req.Parameters.Contains("Target")) { Entity entity = (Entity)req.Parameters["Target"]; GeneralHelper.WriteToText(entity.Id + ";OPPCLOSE-" + responseItem.Fault.Message, @"C:\sahibinden\migration_" + entity.LogicalName + "_" + DateTime.Now.ToShortDateString() + ".txt"); } else { GeneralHelper.WriteToText(Guid.Empty + ";OPPCLOSE-" + responseItem.Fault.Message, @"C:\sahibinden\migration_" + "noentity" + "_" + DateTime.Now.ToShortDateString() + ".txt"); } //Uh oh, error //error++; } else { //Error reporting error; } } } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // TODO Add demonstration code here #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); #endregion #region Lose Opportunity var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); #endregion #region Convert Opportunity to a Quote // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); #endregion #region Close Quote // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); #endregion #region Create Quote's Product // 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 Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _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 Cancel Sales Order // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); #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("</End of Listing>"); 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("</End of Listing>"); 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("</End of Listing>"); 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 // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // 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("</End of Listing>"); Console.WriteLine(); // 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("</End of Listing>"); 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("</End of Listing>"); Console.WriteLine(); // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); #endregion #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// 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. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetProcessingQuotesAndSalesOrders1> // 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.EnableProxyTypes(); CreateRequiredRecords(); #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won), }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // 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 Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // 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."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // 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; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // 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("</End of Listing>"); 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."); //</snippetUpdateRequest> // 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("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> 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("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #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; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // 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("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // 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("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // 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("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }