/// <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;
            }
        }
Exemplo n.º 2
0
        public static WinOpportunityResponse WinOpportunity(
            this IOrganizationService service,
            EntityReference opportunity,
            DateTime?actualEnd    = null,
            Decimal?actualRevenue = null)
        {
            var opportunityClose = new Entity(OpportunityCloseMessage.Name);

            opportunityClose.AddOrUpdateAttribute(OpportunityCloseMessage.OpportunityFieldName, opportunity);
            opportunityClose.AddOrUpdateAttribute(OpportunityCloseMessage.ActualEndFieldName, actualEnd ?? DateTime.Now);

            if (actualRevenue != null)
            {
                opportunityClose.AddOrUpdateAttribute(OpportunityCloseMessage.ActualRevenueFieldName, new Money(actualRevenue.Value));
            }

            var request = new WinOpportunityRequest
            {
                OpportunityClose = opportunityClose,
                Status           = OpportunityStatusCode.Won.ToOptionSetValue()
            };

            var response = service.Execute <WinOpportunityResponse>(request);

            return(response);
        }
        public void Check_if_Opportunity_status_is_Win_after_set()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var opportunity = new Opportunity()
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new[] { opportunity });

            var request = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose
                {
                    OpportunityId = new EntityReference(Opportunity.EntityLogicalName, opportunity.Id)
                },
                Status = new OptionSetValue((int)OpportunityState.Won)
            };

            service.Execute(request);

            var opp = (from op in context.CreateQuery <Opportunity>()
                       where op.Id == opportunity.Id
                       select op).FirstOrDefault();

            Assert.Equal(opp.StatusCode.Value, (int)OpportunityState.Won);
        }
        /// <summary>
        /// <c>Win</c> an opportunity.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.winopportunityrequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>Opportunity</c> Id</param>
        /// <param name="status"><see cref="OpportunityWonStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="opportunitycloseSubject"><c>OpportunityClose</c> subjec</param>
        /// <param name="opportunitycloseDescription"><c>OpportunityClose</c> description</param>
        /// <param name="opportunitycloseActualEnd"><c>OpportunityClose</c> actual end date. Default value is <c>DateTime.UtcNow</c> or <c>DateTime.Now</c> depend on <c>useUtc</c> parameter on constructor</param>
        /// <param name="useOpportunityTotalAmountValue">Set <c>true</c>, if you want to use <c>Opportunity</c>'s current <c>Total Amount</c> value, otherwise if you want new value set <c>false</c> and set value of <c>opportunitycloseActualRevenue</c> parameter</param>
        /// <param name="opportunitycloseActualRevenue"><c>OpportunityClose</c> actual revenue.</param>
        /// <returns><see cref="WinOpportunityResponse"/></returns>
        public WinOpportunityResponse Win(Guid id, OpportunityWonStatusCode status, int customStatusCode = 0, string opportunitycloseSubject = "", string opportunitycloseDescription = "", DateTime?opportunitycloseActualEnd = null, bool useOpportunityTotalAmountValue = false, decimal opportunitycloseActualRevenue = 0)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

            opportunitycloseSubject = !string.IsNullOrEmpty(opportunitycloseSubject) ? opportunitycloseSubject.Trim() : "Opportunity Close - Won";

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

            if (useOpportunityTotalAmountValue)
            {
                opportunitycloseActualRevenue = GetTotalAmount(id);
            }

            WinOpportunityRequest request = new WinOpportunityRequest()
            {
                OpportunityClose = PrepareOpportunityCloseEntity(id, opportunitycloseSubject, opportunitycloseDescription, null, opportunitycloseActualEnd, opportunitycloseActualRevenue),
                Status           = new OptionSetValue(statusCode)
            };

            return((WinOpportunityResponse)this.OrganizationService.Execute(request));
        }
Exemplo n.º 5
0
 public static void SetOpportunityState(OrganizationServiceProxy service, Guid opportunityId)
 {
     try
     {
         var request          = new WinOpportunityRequest();
         var opportunityClose = new Entity("opportunityclose");
         opportunityClose.Attributes.Add("opportunityid", new EntityReference("opportunity", opportunityId));
         request.OpportunityClose = opportunityClose;
         var oStatus = new OptionSetValue {
             Value = (int)OpportunityStatusCode.Ordered
         };
         request.Status = oStatus;
         var resp = (WinOpportunityResponse)service.Execute(request);
     }
     catch (Exception ex)
     {
         LogService.LogMessage(service, new Log()
         {
             Level        = (int)LogType.Error,
             Name         = ex.Message,
             FunctionName = ClassName + " | " + MethodBase.GetCurrentMethod().Name,
             Message      = ex.InnerException != null ? ex.InnerException.Message : ex.Message
         });
     }
 }
        public async Task ExecuteAsync_WinOpportunityRequest_When_Caller_Is_Null_Then_Ok()
        {
            var opportunityId        = new Guid("{5D0E46CA-49F1-EA11-AAF2-005056B42CD8}");
            var opportunityEntityRef = new EntityReference(OpportunityEntityName, opportunityId);

            await CrmClient.CreateAsync(new Entity(OpportunityEntityName, opportunityId));

            var opportunityCloseEntity = new Entity("opportunityclose");

            opportunityCloseEntity.SetAttributeValue("subject", "Won Opportunity");
            opportunityCloseEntity.SetAttributeValue("opportunityid", opportunityEntityRef);

            var action = new WinOpportunityRequest()
            {
                OpportunityClose = opportunityCloseEntity,
                Status           = 3
            };

            try
            {
                await CrmClient.ExecuteAsync(action);
            }
            finally
            {
                await CrmClient.DeleteAsync(opportunityEntityRef);
            }
        }
Exemplo n.º 7
0
        // Execute plugin logic
        protected void Execute(LocalPluginContext context)
        {
            var ctx           = context.PluginExecutionContext;
            var opportunityId = ctx.PrimaryEntityId;
            var message       = ctx.MessageName;

            if (message == "Lose")
            {
                var loseRequest = new LoseOpportunityRequest {
                    Parameters = ctx.InputParameters
                };
                opportunityId = loseRequest.OpportunityClose.ToEntity <OpportunityClose>().OpportunityId.Id;
            }
            else if (message == "Win")
            {
                var winRequest = new WinOpportunityRequest {
                    Parameters = ctx.InputParameters
                };
                opportunityId = winRequest.OpportunityClose.ToEntity <OpportunityClose>().OpportunityId.Id;
            }
            var upd = new Opportunity(opportunityId);

            upd.Description = "SetFromWinLose";
            context.OrganizationAdminService.Update(upd);
        }
Exemplo n.º 8
0
        public void TestWinOpportunity()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var opportunity = new Opportunity();
                opportunity.Id = orgAdminUIService.Create(opportunity);

                var winReq  = new WinOpportunityRequest();
                var opclose = new OpportunityClose()
                {
                    ActualRevenue = 1000m,
                    ActualEnd     = DateTime.Now,
                    StateCode     = OpportunityCloseState.Completed,
                    StatusCode    = OpportunityClose_StatusCode.Completed,
                    OpportunityId = opportunity.ToEntityReference()
                };
                winReq.OpportunityClose = opclose;
                winReq.Status           = new OptionSetValue((int)Opportunity_StatusCode.Won);

                orgAdminUIService.Execute(winReq);

                var retrieved = orgAdminUIService.Retrieve(Opportunity.EntityLogicalName, opportunity.Id, new ColumnSet(true)) as Opportunity;
                Assert.AreEqual(OpportunityState.Won, retrieved.StateCode);
                Assert.AreEqual(Opportunity_StatusCode.Won, retrieved.StatusCode);
                Assert.IsTrue(crm.ContainsEntity(opclose));
                Assert.AreEqual("SetFromWinLose", retrieved.Description);
            }
        }
Exemplo n.º 9
0
        internal static void OpportunityClosed(Guid QuoteId, IOrganizationService service)
        {
            Entity q = service.Retrieve("quote", QuoteId, new ColumnSet("customerid", "ownerid"));
            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "customerid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(((EntityReference)q.Attributes["customerid"]).Id);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "ownerid";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(((EntityReference)q.Attributes["ownerid"]).Id);

            ConditionExpression con3 = new ConditionExpression();

            con3.AttributeName = "statecode";
            con3.Operator      = ConditionOperator.Equal;
            con3.Values.Add(0);

            FilterExpression filter = new FilterExpression();

            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);
            filter.Conditions.Add(con2);
            filter.Conditions.Add(con3);


            QueryExpression Query = new QueryExpression("opportunity");

            Query.ColumnSet = new ColumnSet(true);
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                Guid oppId = Result.Entities[0].Id;

                var OpportunityClose = new Entity("opportunityclose");
                OpportunityClose.Attributes.Add("opportunityid", Result.Entities[0].ToEntityReference());
                WinOpportunityRequest req = new WinOpportunityRequest()
                {
                    OpportunityClose = OpportunityClose,
                    Status           = new OptionSetValue(3)
                };
                service.Execute(req);
            }
        }
Exemplo n.º 10
0
        public void updateOpportunityState()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            Guid oppId = new Guid("3A399DB7-21C5-E511-80ED-3863BB346A70");

            Entity oppEntity = new Entity("opportunityclose");

            oppEntity.Attributes.Add("opportunityid", new EntityReference("opportunity", oppId));

            WinOpportunityRequest winOppReq = new WinOpportunityRequest();

            winOppReq.OpportunityClose = oppEntity;
            winOppReq.Status           = new OptionSetValue(3);

            WinOpportunityResponse winOppResp = (WinOpportunityResponse)service.Execute(winOppReq);
        }
Exemplo n.º 11
0
        private void TransformEntity(Entity entity)
        {
            OptionSetValue statuscode = new OptionSetValue();
            OptionSetValue statecode  = new OptionSetValue();

            statuscode = (OptionSetValue)entity.Attributes["statuscode"];
            statecode  = (OptionSetValue)entity.Attributes["statecode"];
            entity.Attributes.Remove("statuscode");
            entity.Attributes.Remove("statecode");
            Service.Create(entity);

            Entity opportunityClose = new Entity("opportunityclose");

            opportunityClose.Attributes.Add("opportunityid", new EntityReference("opportunity", entity.Id));
            switch (statecode.Value)
            {
            case 0:
                entity.Attributes.Add("statuscode", statuscode);
                entity.Attributes.Add("statecode", statecode);
                Service.Update(entity);
                break;

            case 1:
                WinOpportunityRequest winOpportunityRequest = new WinOpportunityRequest();
                winOpportunityRequest.Status           = statuscode;
                winOpportunityRequest.RequestId        = entity.Id;
                winOpportunityRequest.OpportunityClose = opportunityClose;

                Service.Execute(winOpportunityRequest);
                break;

            case 2:
                LoseOpportunityRequest loseOpportunityRequest = new LoseOpportunityRequest();
                loseOpportunityRequest.Status           = statuscode;
                loseOpportunityRequest.RequestId        = entity.Id;
                loseOpportunityRequest.OpportunityClose = opportunityClose;
                Service.Execute(loseOpportunityRequest);
                break;

            default:
                break;
            }
        }
Exemplo n.º 12
0
        protected override void ExecuteWorkflowLogic()
        {
            var opportunityClose = new Entity("opportunityclose")
            {
                ["subject"]       = Subject.Get(Context.ExecutionContext),
                ["opportunityid"] = Opportunity.Get(Context.ExecutionContext),
                ["actualrevenue"] = ActualRevenue.Get(Context.ExecutionContext),
                ["actualend"]     = CloseDate.Get(Context.ExecutionContext),
                ["description"]   = Description.Get(Context.ExecutionContext)
            };

            var winOpportunityRequest = new WinOpportunityRequest()
            {
                Status           = OpportunityStatus.Get(Context.ExecutionContext),
                OpportunityClose = opportunityClose
            };

            Context.UserService.Execute(winOpportunityRequest);
        }
        public WinOpportunityResponse WinOpportunity(EntityReference entityReference)
        {
            var portal  = PortalCrmConfigurationManager.CreatePortalContext();
            var context = portal.ServiceContext;

            var opportunityClose = new Entity("opportunityclose");

            opportunityClose.Attributes["subject"]       = "Opportunity won via Web Portal" + DateTime.Now.ToString(CultureInfo.InvariantCulture);
            opportunityClose.Attributes["opportunityid"] = entityReference;

            var winQuoteRequest = new WinOpportunityRequest()
            {
                OpportunityClose = opportunityClose,
                Status           = new OptionSetValue((int)OpportunityStatusCode.Won)
            };

            var winOpportunityResponse = (WinOpportunityResponse)context.Execute(winQuoteRequest);

            return(winOpportunityResponse);
        }
Exemplo n.º 14
0
        public void PerformTestSetup()
        {
            MessageName = "Win";

            var opportunityEntity = EntityFactory.CreateOpportunity();

            OpportunityId = opportunityEntity.Id;

            var opportunityClose = new Entity("opportunityclose");

            opportunityClose["opportunityid"] = opportunityEntity.ToEntityReference();
            opportunityClose["subject"]       = "Won!";
            opportunityClose["actualend"]     = DateTime.Now;
            opportunityClose["description"]   = "Won!";

            WinOpportunityRequest = new WinOpportunityRequest
            {
                OpportunityClose = opportunityClose,
                Status           = new OptionSetValue(3)
            };
        }
Exemplo n.º 15
0
        public static void CloseOppAsWin(Guid oppId, int statusCode, DateTime actualEnd, IOrganizationService service)
        {
            try
            {
                if (oppId != Guid.Empty)
                {
                    WinOpportunityRequest req = new WinOpportunityRequest();
                    Entity opportunityClose   = new Entity("opportunityclose");
                    opportunityClose["opportunityid"] = new EntityReference("opportunity", oppId);
                    opportunityClose["subject"]       = "Win the Opportunity!";
                    opportunityClose["actualend"]     = actualEnd;

                    req.OpportunityClose = opportunityClose;
                    req.Status           = new OptionSetValue(statusCode);
                    WinOpportunityResponse resp = (WinOpportunityResponse)service.Execute(req);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 16
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region "Load CRM Service from context"

            Common objCommon = new Common(executionContext);
            objCommon.tracingService.Trace("Load CRM Service from context --- OK");

            #endregion

            #region "Read Parameters"
            EntityReference opportunity = this.Opportunity.Get(executionContext);
            if (opportunity == null)
            {
                return;
            }

            objCommon.tracingService.Trace("OpportunityID=" + opportunity.Id);
            #endregion

            #region "WinOpportuntity Execution"
            var winOpportunityReq = new WinOpportunityRequest
            {
                Status = new OptionSetValue()
            };

            winOpportunityReq.OpportunityClose = new Entity
            {
                LogicalName = "opportunityclose"
            };

            winOpportunityReq.OpportunityClose.Attributes.Add("OpportunityId", new EntityReference(opportunity.LogicalName, opportunity.Id));

            var winOpportunityRes =
                (WinOpportunityResponse)objCommon.service.Execute(winOpportunityReq);
            Console.WriteLine("  Executed OK.");
            #endregion
        }
Exemplo n.º 17
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a sample account record.
        /// Create 3 opportunity records associate to the account record.
        /// Mark all 3 opportunity records as won.
        /// </summary>
        public void CreateRequiredRecords()
        {
            
            var OpportunityStatusCodes = new
            {
                Won = 3
            };

            // Instantiate a account entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation
            // to determine which attributes must be set for each entity.
            Account setupAccount = new Account
            { 
                Name = "Example Account" 
            };
            
            _accountId = _service.Create(setupAccount);

            Console.WriteLine("Created {0}.", setupAccount.Name);


            EntityReference setupCustomer = new EntityReference
            {
                LogicalName = Account.EntityLogicalName,
                Id = _accountId
            };

            // Create 3 sample opportunities.
            // Instantiate opportunity entity records and set there property values.
            // See the Entity Metadata topic in the SDK documentation
            // to determine which attributes must be set for each entity.
            Opportunity[] setupOpportunities = new[]
                {
                    new Opportunity
                    {
                        Name = "Sample Opp 1",
                        EstimatedValue = new Money {Value = 120000.00m},
                        CustomerId = setupCustomer,
                    },
                    new Opportunity
                    {
                        Name = "Sample Opp With Duplicate Name",
                        EstimatedValue = new Money { Value = 240000.00m},
                        CustomerId = setupCustomer,
                    },
                    new Opportunity
                    {
                        Name = "Sample Opp With Duplicate Name",
                        EstimatedValue = new Money{ Value = 360000.00m},
                        CustomerId = setupCustomer,
                    },
                };

            _setupOpportunitiyIds = (from opp in setupOpportunities
                                           select _service.Create(opp)).ToArray();

            // "Win" each of the opportunities
            foreach (Guid oppId in _setupOpportunitiyIds)
            {
                WinOpportunityRequest winRequest = new WinOpportunityRequest
                {
                    OpportunityClose = new OpportunityClose
                    {
                        OpportunityId = new EntityReference
                        {
                            LogicalName = "opportunity",
                            Id = oppId
                        },

                        // Mark these entities as won in the year 2008 to 
                        // have some testable results.
                        ActualEnd = new DateTime(2009, 11, 1, 12, 0, 0)                        
                    },
                    Status = new OptionSetValue(OpportunityStatusCodes.Won)
                };
                _service.Execute(winRequest);
            }

            Console.WriteLine("Created {0} sample opportunity records and updated as won for this sample.", _setupOpportunitiyIds.Length);
            
            return;
        }
Exemplo n.º 18
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a sample account record.
        /// Create 3 opportunity records associate to the account record.
        /// Mark all 3 opportunity records as won.
        /// </summary>
        public void CreateRequiredRecords()
        {
            var OpportunityStatusCodes = new
            {
                Won = 3
            };

            // Instantiate a account entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation
            // to determine which attributes must be set for each entity.
            Account setupAccount = new Account
            {
                Name = "Example Account"
            };

            _accountId = _service.Create(setupAccount);

            Console.WriteLine("Created {0}.", setupAccount.Name);


            EntityReference setupCustomer = new EntityReference
            {
                LogicalName = Account.EntityLogicalName,
                Id          = _accountId
            };

            // Create 3 sample opportunities.
            // Instantiate opportunity entity records and set there property values.
            // See the Entity Metadata topic in the SDK documentation
            // to determine which attributes must be set for each entity.
            Opportunity[] setupOpportunities = new[]
            {
                new Opportunity
                {
                    Name           = "Sample Opp 1",
                    EstimatedValue = new Money {
                        Value = 120000.00m
                    },
                    CustomerId = setupCustomer,
                },
                new Opportunity
                {
                    Name           = "Sample Opp With Duplicate Name",
                    EstimatedValue = new Money {
                        Value = 240000.00m
                    },
                    CustomerId = setupCustomer,
                },
                new Opportunity
                {
                    Name           = "Sample Opp With Duplicate Name",
                    EstimatedValue = new Money {
                        Value = 360000.00m
                    },
                    CustomerId = setupCustomer,
                },
            };

            _setupOpportunitiyIds = (from opp in setupOpportunities
                                     select _service.Create(opp)).ToArray();

            // "Win" each of the opportunities
            foreach (Guid oppId in _setupOpportunitiyIds)
            {
                WinOpportunityRequest winRequest = new WinOpportunityRequest
                {
                    OpportunityClose = new OpportunityClose
                    {
                        OpportunityId = new EntityReference
                        {
                            LogicalName = "opportunity",
                            Id          = oppId
                        },

                        // Mark these entities as won in the year 2008 to
                        // have some testable results.
                        ActualEnd = new DateTime(2009, 11, 1, 12, 0, 0)
                    },
                    Status = new OptionSetValue(OpportunityStatusCodes.Won)
                };
                _service.Execute(winRequest);
            }

            Console.WriteLine("Created {0} sample opportunity records and updated as won for this sample.", _setupOpportunitiyIds.Length);

            return;
        }
        /// <summary>
        /// This will close an opportunity as either Won or lost in CRM
        /// </summary>
        /// <param name="opportunityId">ID of the opportunity to close</param>
        /// <param name="fieldList">List of fields for the Opportunity Close Entity</param>
        /// <param name="opportunityStatusCode">Status code of Opportunity, Should be either 1 or 2,  defaults to 1 ( won )</param>
        /// <param name="batchId">Optional: if set to a valid GUID, generated by the Create Batch Request Method, will assigned the request to the batch for later execution, on fail, runs the request immediately </param>
        /// <param name="cdsServiceClient">Connected CDS Service Client</param>
        /// <param name="bypassPluginExecution">Adds the bypass plugin behavior to this request. Note: this will only apply if the caller has the prvBypassPlugins permission to bypass plugins.  If its attempted without the permission the request will fault.</param>
        /// <returns></returns>
        public static Guid CloseOpportunity(this CdsServiceClient cdsServiceClient, Guid opportunityId, Dictionary <string, CdsDataTypeWrapper> fieldList, int opportunityStatusCode = 3, Guid batchId = default(Guid), bool bypassPluginExecution = false)
        {
            cdsServiceClient.logEntry.ResetLastError();              // Reset Last Error
            if (cdsServiceClient._CdsService == null)
            {
                cdsServiceClient.logEntry.Log("Crm Service not initialized", TraceEventType.Error);
                return(Guid.Empty);
            }

            if (opportunityId == Guid.Empty)
            {
                return(Guid.Empty);
            }

            if (opportunityStatusCode < 3)
            {
                return(Guid.Empty);
            }

            Guid   actId = Guid.Empty;
            Entity uEnt  = new Entity("opportunityclose");
            AttributeCollection PropertyList = new AttributeCollection();

            #region MapCode
            if (fieldList != null)
            {
                foreach (KeyValuePair <string, CdsDataTypeWrapper> field in fieldList)
                {
                    cdsServiceClient.AddValueToPropertyList(field, PropertyList);
                }
            }

            // Add the key...
            // check to see if the key is in the import set allready
            if (fieldList != null && !fieldList.ContainsKey("opportunityid"))
            {
                PropertyList.Add(new KeyValuePair <string, object>("opportunityid", opportunityId));
            }

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

            // 2 types of close supported... Won or Lost.
            if (opportunityStatusCode == 3)
            {
                WinOpportunityRequest req = new WinOpportunityRequest();
                req.OpportunityClose = uEnt;
                req.Status           = new OptionSetValue(opportunityStatusCode);

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

                WinOpportunityResponse resp = (WinOpportunityResponse)cdsServiceClient.CdsCommand_Execute(req, "Closing a Opportunity in CRM as Won", bypassPluginExecution);
                if (resp != null)
                {
                    return(actId);
                }
                else
                {
                    return(Guid.Empty);
                }
            }
            else
            {
                LoseOpportunityRequest req = new LoseOpportunityRequest();
                req.OpportunityClose = uEnt;
                req.Status           = new OptionSetValue(opportunityStatusCode);

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

                LoseOpportunityResponse resp = (LoseOpportunityResponse)cdsServiceClient.CdsCommand_Execute(req, "Closing a Opportunity in CRM as Lost", bypassPluginExecution);
                if (resp != null)
                {
                    return(actId);
                }
                else
                {
                    return(Guid.Empty);
                }
            }
        }
Exemplo n.º 20
0
        public static void executeMultipleCloseOpportunity(EntityCollection entities, IOrganizationService service)
        {
            ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };

            foreach (Entity e in entities.Entities)
            {
                if (((OptionSetValue)e["statecode"]).Value == 1)
                {
                    WinOpportunityRequest req = new WinOpportunityRequest();
                    Entity opportunityClose   = new Entity("opportunityclose");
                    opportunityClose["opportunityid"] = new EntityReference("opportunity", e.Id);
                    opportunityClose["subject"]       = "Win the Opportunity!";
                    opportunityClose["actualend"]     = (DateTime)e["actualend"];

                    req.OpportunityClose = opportunityClose;
                    req.Status           = (OptionSetValue)e["statuscode"];

                    multipleRequest.Requests.Add(req);
                }
                else if (((OptionSetValue)e["statecode"]).Value == 2)
                {
                    LoseOpportunityRequest req = new LoseOpportunityRequest();
                    Entity opportunityClose    = new Entity("opportunityclose");
                    opportunityClose["opportunityid"] = new EntityReference("opportunity", e.Id);
                    opportunityClose["subject"]       = "Lost the Opportunity!";
                    opportunityClose["actualend"]     = (DateTime)e["actualend"];

                    req.OpportunityClose = opportunityClose;
                    req.Status           = (OptionSetValue)e["statuscode"];

                    multipleRequest.Requests.Add(req);
                }
            }

            //This is how to get responses
            ExecuteMultipleResponse executeResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

            if (executeResponse.Results != null)
            {
                //Loop through responses
                foreach (ExecuteMultipleResponseItem responseItem in executeResponse.Responses)
                {
                    if (responseItem.Response != null)
                    {
                        //Awesome, command completed as expected
                        //success++;
                    }
                    else if (responseItem.Fault != null)
                    {
                        OrganizationRequest req = multipleRequest.Requests[responseItem.RequestIndex];

                        if (req.Parameters.Contains("Target"))
                        {
                            Entity entity = (Entity)req.Parameters["Target"];

                            GeneralHelper.WriteToText(entity.Id + ";OPPCLOSE-" + responseItem.Fault.Message, @"C:\sahibinden\migration_" + entity.LogicalName + "_" + DateTime.Now.ToShortDateString() + ".txt");
                        }
                        else
                        {
                            GeneralHelper.WriteToText(Guid.Empty + ";OPPCLOSE-" + responseItem.Fault.Message, @"C:\sahibinden\migration_" + "noentity" + "_" + DateTime.Now.ToShortDateString() + ".txt");
                        }
                        //Uh oh, error
                        //error++;
                    }
                    else
                    {
                        //Error reporting error;
                    }
                }
            }
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {

            #region Create or Retrieve the necessary system users

            // Retrieve the ldapPath
            String ldapPath = String.Empty;
            // Retrieve the sales team - 1 sales manager and 2 sales representatives.
            _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath);
            _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);

            #endregion

            #region Create records to support Opportunity records
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };
            _unitGroupId = _serviceProxy.Create(newUnitGroup);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet = new ColumnSet("uomid", "name"),
                Criteria = new FilterExpression
                {
                    Conditions = 
                        {
                            new ConditionExpression 
                            {
                                AttributeName = "uomscheduleid",
                                Operator = ConditionOperator.Equal,
                                Values = { _unitGroupId }
                            }
                        }
                },
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count = 1
                }
            };

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

            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber = "1",
                Name = "Example Product 1",
                ProductStructure = new OptionSetValue(1),
                QuantityDecimal = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                    _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };
            _product1Id = _serviceProxy.Create(newProduct1);
            Console.WriteLine("Created {0}", newProduct1.Name);


            Product newProduct2 = new Product
            {
                ProductNumber = "2",
                Name = "Example Product 2",
                ProductStructure = new OptionSetValue(1),
                QuantityDecimal = 3,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                    _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };
            _product2Id = _serviceProxy.Create(newProduct2);
            Console.WriteLine("Created {0}", newProduct2.Name);

            // Create a new discount list
            DiscountType newDiscountType = new DiscountType
            {
                Name = "Example Discount List",
                IsAmountType = false
            };
            _discountTypeId = _serviceProxy.Create(newDiscountType);

            // Create a new discount
            Discount newDiscount = new Discount
            {
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                    _discountTypeId),
                LowQuantity = 5,
                HighQuantity = 10,
                Percentage = 3
            };
            _discountId = _serviceProxy.Create(newDiscount);

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

            // Create a price list item for the first product and apply volume discount
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(20),
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                    _discountTypeId)
            };
            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

            // Create a price list item for the second product
            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(15)
            };
            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

            // Publish Product 1
            SetStateRequest publishRequest1 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest1);            

            // Publish Product 2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published {0} and {1}", newProduct1.Name, newProduct2.Name);

            // Create an account record for the opportunity's potential customerid 
            Account newAccount = new Account
            {
                Name = "Litware, Inc.",
                Address1_PostalCode = "60661"
            };
            _accountIds.Add(_serviceProxy.Create(newAccount));

            newAccount = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountIds.Add(_serviceProxy.Create(newAccount));

            #endregion Create records to support Opportunity records

            #region Create Opportunity records
            // Create a new opportunity with user specified estimated revenue
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountIds[0]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue = new Money(400.00m),
                FreightAmount = new Money(10.00m),
                DiscountAmount = new Money(0.10m),
                DiscountPercentage = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId = new EntityReference
                {
                    Id = _salesRepresentativeIds[0],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(_serviceProxy.Create(newOpportunity));

            Opportunity secondOpportunity = new Opportunity
            {
                Name = "Example Opportunity 2",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountIds[1]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue = new Money(400.00m),
                FreightAmount = new Money(10.00m),
                DiscountAmount = new Money(0.10m),
                DiscountPercentage = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId = new EntityReference
                {
                    Id = _salesRepresentativeIds[1],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(_serviceProxy.Create(secondOpportunity));

            // Create a catalog product
            OpportunityProduct catalogProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[0]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8,
                Tax = new Money(12.42m),
            };
            _catalogProductId = _serviceProxy.Create(catalogProduct);
 
            // Create another catalog product and override the list price
            OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[1]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 3,
                Tax = new Money(2.88m),
                IsPriceOverridden = true,
                PricePerUnit = new Money(12)
            };
            _catalogProductPriceOverrideId = _serviceProxy.Create(
                catalogProductPriceOverride);

            // create a new write-in opportunity product with a manual discount applied
            OpportunityProduct writeInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[1]),
                IsProductOverridden = true,
                ProductDescription = "Example Write-in Product",
                PricePerUnit = new Money(20.00m),
                Quantity = 5,
                ManualDiscountAmount = new Money(10.50m),
                Tax = new Money(7.16m)
            };
            _writeInProductId = _serviceProxy.Create(writeInProduct);

            // Close the opportunities as 'Won'
            WinOpportunityRequest winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id = _opportunityIds[0],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            _serviceProxy.Execute(winRequest);

            winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id = _opportunityIds[1],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            _serviceProxy.Execute(winRequest);

            #endregion Create Opportunity records
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            #region Create or Retrieve the necessary system users

            // Retrieve the ldapPath
            String ldapPath = String.Empty;
            // Retrieve the sales team - 1 sales manager and 2 sales representatives.
            _salesManagerId         = SystemUserProvider.RetrieveSalesManager(service, ref ldapPath);
            _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(service, ref ldapPath);

            #endregion

            #region Create records to support Opportunity records
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name        = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };
            _unitGroupId = service.Create(newUnitGroup);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet  = new ColumnSet("uomid", "name"),
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "uomscheduleid",
                            Operator      = ConditionOperator.Equal,
                            Values        = { _unitGroupId }
                        }
                    }
                },
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count      = 1
                }
            };

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

            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber        = "1",
                Name                 = "Example Product 1",
                ProductStructure     = new OptionSetValue(1),
                QuantityDecimal      = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                                                           _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };
            _product1Id = service.Create(newProduct1);
            Console.WriteLine("Created {0}", newProduct1.Name);


            Product newProduct2 = new Product
            {
                ProductNumber        = "2",
                Name                 = "Example Product 2",
                ProductStructure     = new OptionSetValue(1),
                QuantityDecimal      = 3,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                                                           _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };
            _product2Id = service.Create(newProduct2);
            Console.WriteLine("Created {0}", newProduct2.Name);

            // Create a new discount list
            DiscountType newDiscountType = new DiscountType
            {
                Name         = "Example Discount List",
                IsAmountType = false
            };
            _discountTypeId = service.Create(newDiscountType);

            // Create a new discount
            Discount newDiscount = new Discount
            {
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                                                     _discountTypeId),
                LowQuantity  = 5,
                HighQuantity = 10,
                Percentage   = 3
            };
            _discountId = service.Create(newDiscount);

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

            // Create a price list item for the first product and apply volume discount
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
            {
                PriceLevelId   = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId      = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId          = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount         = new Money(20),
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                                                     _discountTypeId)
            };
            _priceListItem1Id = service.Create(newPriceListItem1);

            // Create a price list item for the second product
            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId        = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount       = new Money(15)
            };
            _priceListItem2Id = service.Create(newPriceListItem2);

            // Publish Product 1
            SetStateRequest publishRequest1 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id),
                State         = new OptionSetValue((int)ProductState.Active),
                Status        = new OptionSetValue(1)
            };
            service.Execute(publishRequest1);

            // Publish Product 2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State         = new OptionSetValue((int)ProductState.Active),
                Status        = new OptionSetValue(1)
            };
            service.Execute(publishRequest2);
            Console.WriteLine("Published {0} and {1}", newProduct1.Name, newProduct2.Name);

            // Create an account record for the opportunity's potential customerid
            Account newAccount = new Account
            {
                Name = "Litware, Inc.",
                Address1_PostalCode = "60661"
            };
            _accountIds.Add(service.Create(newAccount));

            newAccount = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountIds.Add(service.Create(newAccount));

            #endregion Create records to support Opportunity records

            #region Create Opportunity records
            // Create a new opportunity with user specified estimated revenue
            Opportunity newOpportunity = new Opportunity
            {
                Name       = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                                                 _accountIds[0]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                                                   _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue            = new Money(400.00m),
                FreightAmount             = new Money(10.00m),
                DiscountAmount            = new Money(0.10m),
                DiscountPercentage        = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId     = new EntityReference
                {
                    Id          = _salesRepresentativeIds[0],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(service.Create(newOpportunity));

            Opportunity secondOpportunity = new Opportunity
            {
                Name       = "Example Opportunity 2",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                                                 _accountIds[1]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                                                   _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue            = new Money(400.00m),
                FreightAmount             = new Money(10.00m),
                DiscountAmount            = new Money(0.10m),
                DiscountPercentage        = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId     = new EntityReference
                {
                    Id          = _salesRepresentativeIds[1],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(service.Create(secondOpportunity));

            // Create a catalog product
            OpportunityProduct catalogProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                    _opportunityIds[0]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                                                _product1Id),
                UoMId    = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8,
                Tax      = new Money(12.42m),
            };
            _catalogProductId = service.Create(catalogProduct);

            // Create another catalog product and override the list price
            OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                    _opportunityIds[1]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                                                _product2Id),
                UoMId             = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity          = 3,
                Tax               = new Money(2.88m),
                IsPriceOverridden = true,
                PricePerUnit      = new Money(12)
            };
            _catalogProductPriceOverrideId = service.Create(
                catalogProductPriceOverride);

            // create a new write-in opportunity product with a manual discount applied
            OpportunityProduct writeInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                    _opportunityIds[1]),
                IsProductOverridden  = true,
                ProductDescription   = "Example Write-in Product",
                PricePerUnit         = new Money(20.00m),
                Quantity             = 5,
                ManualDiscountAmount = new Money(10.50m),
                Tax = new Money(7.16m)
            };
            _writeInProductId = service.Create(writeInProduct);

            // Close the opportunities as 'Won'
            WinOpportunityRequest winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id          = _opportunityIds[0],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd     = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            service.Execute(winRequest);

            winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id          = _opportunityIds[1],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd     = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            service.Execute(winRequest);

            #endregion Create Opportunity records
        }
Exemplo n.º 23
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;
            }
        }
Exemplo n.º 24
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();
            }
        }