/// <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;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a <c>Quote</c> from an <c>Opportunity</c>.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.generatequotefromopportunityrequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="opportunityId"><c>Opportunity</c> Id</param>
        /// <param name="retrievedColumns">
        /// Default attributes are "quoteid", "name", "quotenumber", "revisionnumber".
        /// If you need more or different attributes please set this parameter
        /// </param>
        /// <returns>
        /// Returns created <c>Quote</c> in <see cref="GenerateQuoteFromOpportunityResponse.Entity"/> property with attributes that defined in <c>retrievedQuoteColums</c> parameter
        /// </returns>
        public GenerateQuoteFromOpportunityResponse CreateFromOpportunity(Guid opportunityId, params string[] retrievedColumns)
        {
            ExceptionThrow.IfGuidEmpty(opportunityId, "opportunityId");

            string[] columns = !retrievedColumns.IsNullOrEmpty() ? retrievedColumns : _quoteColumns;

            GenerateQuoteFromOpportunityRequest request = new GenerateQuoteFromOpportunityRequest
            {
                OpportunityId = opportunityId,
                ColumnSet     = new ColumnSet(columns)
            };

            return((GenerateQuoteFromOpportunityResponse)this.OrganizationService.Execute(request));
        }
Ejemplo n.º 3
0
        public void CreateQuoteFromOpp()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            Guid oppId = new Guid("B1488A7A-3FEC-E511-8102-3863BB3660F0");

            /*****Step 1: Create Quote with Line Item from Opportunity***********/
            var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
            {
                OpportunityId = oppId,
                ColumnSet     = new ColumnSet(CONSTANT.QUOTE_ID_FIELD, CONSTANT.QUOTE_NAME_FIELD)
            };

            var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
                                          service.Execute(genQuoteFromOppRequest);
            Guid quoteId = genQuoteFromOppResponse.Entity.Id;



            /********** Step 3: Set Current Quote as Primary and reset all older quote with Primary as false*********/
            setCurrentQuotAsPrimary(service, oppId, quoteId);

            /**********Step 4 : Create Product Configuration From Quote*********************/
            createProductConfigFromQuote(service, quoteId);

            /****************Step 5 : Update Opportunity with Quote Created********************/
            // Update Opporunity
            Entity opportunity = new Entity(CONSTANT.OPPORTUNITY_ENTITY);

            opportunity.Id = oppId;

            // Reset Trigger Flag to Flalse
            opportunity.Attributes.Add(CONSTANT.OPPORTUNITY_TRIGGERED_ACTION_FIELD, false);
            // Set above created quote to use further
            opportunity.Attributes.Add(CONSTANT.OPPORTUNITY_TRIGGERED_QUOTE_FIELD, new EntityReference(CONSTANT.QUOTE_ENTITY, quoteId));

            if (quoteId != Guid.Empty)
            {
                service.Update(opportunity);
            }


            /********* Step 2 : Delete recently created quote line items*********/
            deleteQuoteProducts(service, quoteId);


            Console.WriteLine("Quote generated from the Opportunity.");
        }
        public GenerateQuoteFromOpportunityResponse GenerateQuoteFromOpportunity(EntityReference entityReference)
        {
            var portal  = PortalCrmConfigurationManager.CreatePortalContext();
            var context = portal.ServiceContext;

            var quoteColumns = new ColumnSet("quoteid", "name");

            // Convert the quote to	a sales	order
            var generateQuoteFromOpportunityRequest =
                new GenerateQuoteFromOpportunityRequest()
            {
                OpportunityId = entityReference.Id,
                ColumnSet     = quoteColumns
            };

            var generateQuoteFromOpportunityResponse = (GenerateQuoteFromOpportunityResponse)context.Execute(generateQuoteFromOpportunityRequest);

            return(generateQuoteFromOpportunityResponse);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate creating all entity records that this sample requires.
        /// Convert an opportunity to quote
        /// Optionally delete any entity records that were created for this sample.
        /// </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
            {
                // 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();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetConvertOpportunityToQuote1>
                    // Convert an opportunity to quote.
                    GenerateQuoteFromOpportunityRequest quoteRequest = new GenerateQuoteFromOpportunityRequest()
                    {
                        // Columns that will be transferred
                        ColumnSet     = new ColumnSet("name", "customerid"),
                        OpportunityId = _opportunityId
                    };

                    GenerateQuoteFromOpportunityResponse quoteResponse =
                        (GenerateQuoteFromOpportunityResponse)_serviceProxy.Execute(quoteRequest);

                    _quoteId = quoteResponse.Entity.Id;
                    //</snippetConvertOpportunityToQuote1>
                    Console.WriteLine("Created the quote from an opportunity.");

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            catch
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Ejemplo n.º 6
0
        private void GenerateQuotationFromOpportunity(Guid opportunityGUID, IOrganizationService service, CodeActivityContext context)
        {
            try
            {
                var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
                {
                    OpportunityId = opportunityGUID,
                    ColumnSet     = new ColumnSet("quoteid", "name")
                };

                var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
                                              service.Execute(genQuoteFromOppRequest);

                Quote quote    = genQuoteFromOppResponse.Entity.ToEntity <Quote>();
                Guid  _quoteId = quote.Id;
            }
            catch (InvalidPluginExecutionException ex)
            {
                if (ex != null)
                {
                    throw new InvalidPluginExecutionException("1) Unable to Create Proposal." + ex.Message + "Contact Your Administrator");
                }
                else
                {
                    throw new InvalidPluginExecutionException("2) Unable to Create Proposal." + ex.Message + "Contact Administrator");
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("3) Unable to Send Create Proposal." + ex.Message + "Contact Your Administrator.", ex);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("4) Unable to Send Create Proposal." + ex.Message + "Contact Your Administrator.", ex);
            }
        }
Ejemplo n.º 7
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();
            }
        }
Ejemplo n.º 8
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;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate creating all entity records that this sample requires.
        /// Convert an opportunity to quote
        /// Optionally delete any entity records that were created for this sample.
        /// </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
            {
                // 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();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetConvertOpportunityToQuote1>
                    // Convert an opportunity to quote.
                    GenerateQuoteFromOpportunityRequest quoteRequest = new GenerateQuoteFromOpportunityRequest()
                    {
                        // Columns that will be transferred
                        ColumnSet = new ColumnSet("name", "customerid"),
                        OpportunityId = _opportunityId
                    };

                    GenerateQuoteFromOpportunityResponse quoteResponse =
                        (GenerateQuoteFromOpportunityResponse)_serviceProxy.Execute(quoteRequest);

                    _quoteId = quoteResponse.Entity.Id;
                    //</snippetConvertOpportunityToQuote1>
                    Console.WriteLine("Created the quote from an opportunity.");

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            catch
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
		}