/// <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;
            }
        }
Example #2
0
        /// <summary>
        /// <c>Cancel</c> the <c>SalesOrder</c>.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.cancelsalesorderrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>SalesOrder</c> Id</param>
        /// <param name="status"><see cref="SalesOrderCanceledStatusCode"/> 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="ordercloseSubject"><c>OrderClose</c> subject</param>
        /// <param name="ordercloseDescription"><c>OrderClose</c> description</param>
        /// <param name="ordercloseActualEnd"><c>OrderClose</c> actual end date</param>
        /// <returns>
        /// <see cref="CancelSalesOrderResponse"/>
        /// </returns>
        public CancelSalesOrderResponse Cancel(Guid id, SalesOrderCanceledStatusCode status, int customStatusCode = 0, string ordercloseSubject = "", string ordercloseDescription = "", DateTime?ordercloseActualEnd = null)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

            if (status == SalesOrderCanceledStatusCode.CustomStatusCode)
            {
                ExceptionThrow.IfNegative(customStatusCode, "customStatusCode");
                statusCode = customStatusCode;
            }

            if (string.IsNullOrEmpty(ordercloseSubject))
            {
                var salesorderEntity = this.Get(id, "ordernumber");
                ordercloseSubject = string.Format("Salesorder Close (Cancel) - {0}", salesorderEntity.GetAttributeValue <string>("ordernumber"));
            }

            CancelSalesOrderRequest request = new CancelSalesOrderRequest()
            {
                OrderClose = PrepareOrderCloseEntity(id, ordercloseSubject, ordercloseDescription, ordercloseActualEnd),
                Status     = new OptionSetValue(statusCode)
            };

            return((CancelSalesOrderResponse)this.OrganizationService.Execute(request));
        }
        private void DoCreate(IPluginExecutionContext context, IOrganizationService orgService)
        {
            Entity postEntity = orgService.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId,
                                                    new ColumnSet("new_originalcontractnumber", "new_ordertype"));
            EntityCollection originalContracts;

            if (postEntity.Contains("new_originalcontractnumber") && postEntity.Contains("new_ordertype"))
            {
                if (((OptionSetValue)postEntity["new_ordertype"]).Value == 100000000)   //如果是购车订单则处理
                {
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = C_EntityName,
                        ColumnSet  = new ColumnSet(true),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "new_contractnumber",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { postEntity["new_originalcontractnumber"].ToString() }
                                }
                            }
                        }
                    };
                    originalContracts = orgService.RetrieveMultiple(query);

                    if (originalContracts.Entities.Count > 0)   //存在原合同,则取消原合同
                    {
                        //SetStateRequest setStateRequest = new SetStateRequest()
                        //{
                        //    EntityMoniker = new EntityReference
                        //    {
                        //        Id = originalContracts[0].Id,
                        //        LogicalName = C_EntityName
                        //    },
                        //    State = new OptionSetValue(2),
                        //    Status =
                        //};

                        Entity orderclose = new Entity("orderclose");
                        orderclose["salesorderid"] = new EntityReference {
                            Id = originalContracts[0].Id, LogicalName = C_EntityName
                        };

                        CancelSalesOrderRequest setStateRequest = new CancelSalesOrderRequest();
                        setStateRequest.OrderClose = orderclose;
                        setStateRequest.Status     = new OptionSetValue(4);

                        orgService.Execute(setStateRequest);
                    }
                }
            }
        }
        public void PerformTestSetup()
        {
            MessageName = "Cancel";

            var orderEntity = EntityFactory.CreateSalesOrder();

            var orderCloseEntity = new Entity("orderclose");

            orderCloseEntity["salesorderid"] = orderEntity.ToEntityReference();

            CancelSalesOrderRequest = new CancelSalesOrderRequest
            {
                OrderClose = orderCloseEntity,
                Status     = new OptionSetValue(4)
            };
        }
        protected override void ExecuteWorkflowLogic()
        {
            var cancelSalesOrderRequest = new CancelSalesOrderRequest()
            {
                Status     = SalesOrderStatus.Get(Context.ExecutionContext),
                OrderClose = new Entity("orderclose")
                {
                    ["subject"]      = Subject.Get(Context.ExecutionContext),
                    ["salesorderid"] = SalesOrder.Get(Context.ExecutionContext),
                    ["actualend"]    = CloseDate.Get(Context.ExecutionContext),
                    ["description"]  = Description.Get(Context.ExecutionContext)
                }
            };

            Context.UserService.Execute(cancelSalesOrderRequest);
        }
Example #6
0
        public Boolean AlterarStatus(Guid id, int stateCode, int statusCode)
        {
            if ((int)Domain.Enum.Pedido.StateCode.Cancelada == stateCode)
            {
                CancelSalesOrderResponse cancelResponse = null;
                Entity cancelaPedido = new Entity("orderclose");
                cancelaPedido["salesorderid"] = new EntityReference(SDKore.Crm.Util.Utility.GetEntityName <Intelbras.CRM2013.Domain.Model.Pedido>(), id);

                CancelSalesOrderRequest requestCancel = new CancelSalesOrderRequest();

                requestCancel.OrderClose = cancelaPedido;
                requestCancel.Status     = new OptionSetValue(statusCode);
                cancelResponse           = (CancelSalesOrderResponse)this.Execute(requestCancel);
                if (cancelResponse != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                SetStateResponse resp = null;

                SetStateRequest request = new SetStateRequest
                {
                    EntityMoniker = new EntityReference("salesorder", id),
                    State         = new OptionSetValue(stateCode),
                    Status        = new OptionSetValue(statusCode)
                };

                resp = (SetStateResponse)this.Execute(request);


                if (resp != null)
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Cancel Sales order
        /// </summary>
        /// <param name="salesOrderId">Sales order id to close</param>
        /// <param name="fieldList">List of fields to add</param>
        /// <param name="orderStatusCode">Status code of the order</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 CancelSalesOrder(this CdsServiceClient cdsServiceClient, Guid salesOrderId, Dictionary <string, CdsDataTypeWrapper> fieldList, int orderStatusCode = 4, 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 (salesOrderId == Guid.Empty)
            {
                return(Guid.Empty);
            }

            if (orderStatusCode < 4)
            {
                return(Guid.Empty);
            }

            Guid   actId = Guid.Empty;
            Entity uEnt  = new Entity("orderclose");
            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("salesorderid"))
            {
                PropertyList.Add(new KeyValuePair <string, object>("salesorderid", salesOrderId));
            }

            if (fieldList != null && fieldList.ContainsKey("activityid"))
            {
                actId = (Guid)fieldList["activityid"].Value;
            }
            else
            {
                actId   = Guid.NewGuid();
                uEnt.Id = actId;
            }
            #endregion
            uEnt.Attributes.AddRange(PropertyList.ToArray());

            CancelSalesOrderRequest req = new CancelSalesOrderRequest();
            req.OrderClose = uEnt;
            req.Status     = new OptionSetValue(orderStatusCode);

            if (cdsServiceClient.AddRequestToBatch(batchId, req, "Calling Close Sales Order", "Request to Close Sales Order Queued", bypassPluginExecution))
            {
                return(Guid.Empty);
            }


            CancelSalesOrderResponse resp = (CancelSalesOrderResponse)cdsServiceClient.CdsCommand_Execute(req, "Closing a Sales Order in CRM as Closed", bypassPluginExecution);
            if (resp != null)
            {
                return(actId);
            }
            else
            {
                return(Guid.Empty);
            }
        }
Example #8
0
        [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();
            }
        }
Example #9
0
        /// <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;
            }
        }