コード例 #1
0
        public JsonResult CreateOpportunityProduct(OpportunityProduct opportunityProduct)
        {
            var newOpportunityProductId =
                OpportunityService.CreateOpportunityProduct(GetHttpClient(), opportunityProduct);

            return(Json(newOpportunityProductId, JsonRequestBehavior.AllowGet));
        }
コード例 #2
0
    public static void createOppProductBlock(OpportunityProduct oppProduct, int i, Transform parentTransform, Transform Block, SubRingDiskController subRingDiskCtrl)
    {
        Vector3 setRotation = parentTransform.rotation.eulerAngles;

        setRotation.x = -90.0f;

        float posX = (i < 1) ? 1.29f : 1.29f + (i * (1.29f * 0.14f));;
        float posY = 0f;

        Transform currentBlock = (Transform)Instantiate(Block, new Vector3(0, 0, 0), Quaternion.identity);

        currentBlock.SetParent(parentTransform);
        currentBlock.localScale    = new Vector3(0.5f, 0.5f, 0.5f);;
        currentBlock.rotation      = Quaternion.Euler(setRotation);
        currentBlock.localPosition = new Vector3(posX, posY, 0f);



        //get an instance of the component.
        Transform blockInstance = currentBlock.GetComponent <Transform>();

        BlockController blockController = blockInstance.GetComponent <BlockController>();

        blockController.speed = oppProduct.Priority;
        blockController.order = i;

        blockController.objectId    = oppProduct.Id;
        blockController.objectName  = oppProduct.Name;
        blockController.objectType  = "OpportunityProduct";
        blockController.labels      = new string[] { "Product", "List Price", "Sales Price", "Quantity", "Total Price" };
        blockController.fields      = new string[] { oppProduct.Product, oppProduct.ListPrice.ToString("$0,0.00"), oppProduct.UnitPrice.ToString("$0,0.00"), "" + oppProduct.Quantity + "", oppProduct.TotalPrice.ToString("$0,0.00") };
        blockController.description = oppProduct.Description;
        blockController.parentSubRingDiskController = subRingDiskCtrl;
        blockController.setText("Opportunity Product");
    }
コード例 #3
0
        public async Task <int> Create(T entity, byte[] error)
        {
            int status = 0;

            if (typeof(T) == typeof(Inventory))
            {
                Inventory inventory = (Inventory)(object)(entity);
                status = await Task.Run(() => Warehouse_Wrapper.addInventory(inventory, error, _ConnectionString));
            }
            if (typeof(T) == typeof(ProductInInventory))
            {
                ProductInInventory product = (ProductInInventory)(object)(entity);
                status = await Task.Run(() => Warehouse_Wrapper.addProductToInventory(product, error, _ConnectionString));
            }
            if (typeof(T) == typeof(Product))
            {
                Product product = (Product)(object)(entity);
                status = await Task.Run(() => Warehouse_Wrapper.addProduct(product, error, _ConnectionString));
            }

            if (typeof(T) == typeof(Order))
            {
                Order order = (Order)(object)(entity);
                status = await Task.Run(() => Warehouse_Wrapper.addOrder(order, error, _ConnectionString));
            }

            if (typeof(T) == typeof(ProductInOrder))
            {
                ProductInOrder product = (ProductInOrder)(object)(entity);
                status = await Task.Run(() => Warehouse_Wrapper.addProductToOrder(product, error, _ConnectionString));
            }

            if (typeof(T) == typeof(Customer))
            {
                Customer customer = (Customer)(object)entity;
                if (_ConnectionString != null)
                {
                    status = await Task.Run(() => Crm_Wrapper.AddCustomer(customer, error, _ConnectionString));
                }
            }

            if (typeof(T) == typeof(Opportunity))
            {
                Opportunity opportunity = (Opportunity)(object)(entity);
                status = await Task.Run(() => Crm_Wrapper.AddOpportunity(opportunity, error, _ConnectionString));
            }

            if (typeof(T) == typeof(OpportunityProduct))
            {
                OpportunityProduct product = (OpportunityProduct)(object)(entity);
                status = await Task.Run(() => Crm_Wrapper.AddOpportunityProduct(product, error, _ConnectionString));
            }

            return(status);
        }
コード例 #4
0
        public async Task <ActionResult <string> > AddOpportunityProduct(OpportunityProduct product)
        {
            byte[] error  = new byte[500];
            int    status = await _opportunityProductRepository.Create(product, error);

            if (status != 0)
            {
                string z = System.Text.Encoding.ASCII.GetString(error);
                z.Remove(z.IndexOf('\0'));
                return(BadRequest(z.Remove(z.IndexOf('\0'))));
            }
            return(Ok("successfuly added"));
        }
コード例 #5
0
        public JsonResult CreateOpportunityAndOpportunityProduct(Opportunity opportunity,
                                                                 OpportunityProduct opportunityProduct)
        {
            var httpClient = GetHttpClient();

            var newOpportunityId = OpportunityService.CreateOpporutnity(httpClient, opportunity);

            opportunityProduct.OpportunityId = newOpportunityId;

            if (newOpportunityId == Guid.Empty)
            {
                return(Json(newOpportunityId, JsonRequestBehavior.AllowGet));
            }

            var newOpportunityProductId =
                OpportunityService.CreateOpportunityProduct(httpClient, opportunityProduct);

            return(Json(newOpportunityId, JsonRequestBehavior.AllowGet));
        }
コード例 #6
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            CrmServiceContext           xrm            = new CrmServiceContext(service);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {
                EntityReference entity = (EntityReference)context.InputParameters["Target"];
                try
                {
                    if (entity.LogicalName == "opportunityproduct")
                    {
                        //get opportunity product
                        OpportunityProduct product = xrm.OpportunityProductSet.Where(p => p.Id == entity.Id).FirstOrDefault();
                        if (product != null)
                        {
                            //base amount
                            decimal total = product.Quantity.Value * product.PricePerUnit.Value;
                            product.BaseAmount = new Money(total);
                            //discount and tax
                            product.new_CustomDiscount = new Money(total * (decimal)0.15);
                            decimal manualDiscount = product.ManualDiscountAmount != null ? product.ManualDiscountAmount.Value : (decimal)0;
                            decimal tax            = product.Tax != null ? product.Tax.Value : (decimal)0;
                            //extended amount
                            product.ExtendedAmount = new Money((decimal)(product.BaseAmount.Value - product.new_CustomDiscount.Value - manualDiscount + tax));
                            //update product
                            xrm.UpdateObject(product);
                            xrm.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new  InvalidPluginExecutionException($"An error occurred in Calculation plug-in: {ex.Message}");
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name        = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Created {0}", newUnitGroup.Name);

            // 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;

            Console.WriteLine("Retrieved {0}", unit.Name);

            // 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);
            Console.WriteLine("Created {0}", newDiscountType.Name);

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

            _discountId = _serviceProxy.Create(newDiscount);

            Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name);

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);
            Console.WriteLine("Created {0}", newPriceList.Name);

            // 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);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

            // 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(20)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);
            Console.WriteLine("Created price list item for the {0}.", newProduct1.Name);

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

            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            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 both the products");

            // Create an account record for the opporutnity's potential customerid
            Account newAccount = new Account
            {
                Name = "Example Account"
            };

            _accountId = _serviceProxy.Create(newAccount);

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

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name       = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                                                 _accountId),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                                                   _priceListId)
            };

            _opportunityId = _serviceProxy.Create(newOpportunity);
            Console.WriteLine("Created {0}.", newOpportunity.Name);

            // Create some opportunity products
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                                                _product1Id),
                UoMId    = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8
            };

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                                                _product2Id),
                UoMId    = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 1
            };

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

            Console.WriteLine("Created few opportunity products.");

            return;
        }
コード例 #8
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Created {0}", newUnitGroup.Name);

            // 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;

            Console.WriteLine("Retrieved {0}", unit.Name);
          
            // 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);
            Console.WriteLine("Created {0}", newDiscountType.Name);

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

            _discountId = _serviceProxy.Create(newDiscount);

            Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name);

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);
            Console.WriteLine("Created {0}", newPriceList.Name);

            // 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);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

            // 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(20)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);
            Console.WriteLine("Created price list item for the {0}.", newProduct1.Name);

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

            //Publish Product2
            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 both the products");

            // Create an account record for the opporutnity's potential customerid 
            Account newAccount = new Account
            {
                Name = "Example Account"
            };
            _accountId = _serviceProxy.Create(newAccount);

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

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountId),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId)
            };

            _opportunityId = _serviceProxy.Create(newOpportunity);
            Console.WriteLine("Created {0}.", newOpportunity.Name);

            // Create some opportunity products
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8
            };

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 1
            };

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

            Console.WriteLine("Created few opportunity products.");

            return;
        }
コード例 #9
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
        }
コード例 #10
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered WebFormFill.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("WebFormFill.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            ITracingService t = tracingService;

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                // TODO: Implement your custom Workflow business logic.

                #region 1. Get the Web Form Fill from the workflow context.

                t.Trace("1. Get the Form Fill from the workflow context.");
                cldrkt_webformfill webFormFill = (cldrkt_webformfill)service.Retrieve(
                    context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet {
                    AllColumns = true
                });

                #endregion 1. Get the Web Form Fill from the workflow context.

                #region 2. Get the transaction owner and response email sender.

                QueryExpression userQuery = new QueryExpression {
                    EntityName = SystemUser.EntityLogicalName,
                    ColumnSet  = new ColumnSet {
                        AllColumns = true
                    },
                    Criteria = new FilterExpression {
                        Conditions =
                        {
                            new ConditionExpression {
                                AttributeName = "domainname",
                                Operator      = ConditionOperator.Equal,
                                Values        =     { "*****@*****.**"},
                            }
                        }
                    }
                };
                t.Trace("2.1 Get the system user who will send the email.");
                SystemUser user = (SystemUser)service.RetrieveMultiple(userQuery).Entities.FirstOrDefault();
                t.Trace("2.2 The sender is: " + user.FullName.ToString());

                #endregion 2. Get the transaction owner and response email sender.

                #region 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist.

                t.Trace("3. Find or create the Contact from the email address." + webFormFill.cldrkt_Email);

                Contact contact = new Contact {
                    EMailAddress1 = webFormFill.cldrkt_Email,
                    FirstName     = webFormFill.cldrkt_FirstName,
                    Id            = Guid.NewGuid(),
                    LastName      = webFormFill.cldrkt_LastName,
                    Telephone1    = webFormFill.cldrkt_BusinessPhone,
                };

                t.Trace("3.1 Look up the Contact using the email address entered: " + webFormFill.cldrkt_Email.ToString());

                QueryExpression contactsQuery = new QueryExpression {
                    EntityName = Contact.EntityLogicalName,
                    ColumnSet  = new ColumnSet {
                        AllColumns = true
                    },
                    Criteria = new FilterExpression {
                        Conditions =
                        {
                            new ConditionExpression {
                                AttributeName = "emailaddress1",
                                Operator      = ConditionOperator.Equal,
                                Values        =     { contact.EMailAddress1},
                            }
                        }
                    }
                };

                Contact c = (Contact)service.RetrieveMultiple(contactsQuery).Entities.FirstOrDefault();

                if (c != null)
                {
                    contact.Id = c.Id;                             // Will overwrite existing Contact data with entered data.
                    contact.ParentCustomerId = c.ParentCustomerId; // So it will be there for the Account lookup.
                    t.Trace("3.2.1 The existing contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1);
                }
                else
                {
                    t.Trace("3.3.1 Create a new contact.");
                    contact.Id = service.Create(contact);
                    t.Trace("3.3.2 The new contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1);
                }
                service.Update(contact);

                #endregion 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist.

                #region 4. Look up or create the Account and map this Contact to it.

                t.Trace("4. Look up or create the Account and map this Contact to it.");
                //t.Trace("4. Contact is " + contact.FullName);
                //t.Trace("4. Contact.Id is " + contact.Id);
                //t.Trace("4. contact.ParentCustomerId is " + contact.ParentCustomerId.ToString());

                Account account = new Account {
                    Name = webFormFill.cldrkt_Organization,
                };

                // Look up or create the parent Account.
                if (contact.ParentCustomerId != null)
                {
                    t.Trace("4.1 Build the parent account query.");

                    // Look up the  parent account.
                    QueryExpression parentAccountQuery = new QueryExpression {
                        EntityName = Account.EntityLogicalName,
                        ColumnSet  = new ColumnSet {
                            AllColumns = true
                        },
                        Criteria = new FilterExpression {
                            Conditions =
                            {
                                new ConditionExpression {
                                    AttributeName = "accountid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        =     { contact.ParentCustomerId.Id,},
                                }
                            },
                        },
                    };
                    t.Trace("4.2 Look up Account a.");

                    Account a = (Account)service.RetrieveMultiple(parentAccountQuery).Entities.FirstOrDefault();

                    t.Trace("4.3 If a exists, use it. Otherwise create a new Account.");

                    if (a != null)
                    {
                        t.Trace("4.3.1 The Account exists.");
                        account = a;
                        t.Trace("4.2.2 The existing Account is " + account.Name);
                    }
                    else
                    {
                        t.Trace("4.3.2 Create a new Account.");
                        account.Id = a.Id;
                        t.Trace("4.3.1 The new Account is " + account.Id.ToString());
                    }
                }
                else
                {
                    t.Trace("4.4 Create a new Account.");
                    account.Id = service.Create(account);
                };

                // Map the contact to the account.
                account.PrimaryContactId = new EntityReference {
                    Id          = contact.Id,
                    LogicalName = Contact.EntityLogicalName,
                };
                service.Update(account);

                // Map the account to the contact.
                contact.ParentCustomerId = new EntityReference {
                    Id          = account.Id,
                    LogicalName = Account.EntityLogicalName,
                };
                service.Update(contact);

                #endregion 4. Look up or create the Account and map this Contact to it.

                #region 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response.

                t.Trace("5. Get the Campaign Activity, if any...");
                CampaignActivity campaignActivity = new CampaignActivity();
                CampaignResponse campaignResponse = new CampaignResponse();

                Guid campaignActivityId = Guid.Empty;

                t.Trace("5.1 webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID);
                if (String.IsNullOrWhiteSpace(webFormFill.cldrkt_CampaignActivityID))
                {
                    campaignActivityId = Guid.Empty;
                }
                else
                {
                    t.Trace("5.2 We have a webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID);

                    Guid.TryParse(webFormFill.cldrkt_CampaignActivityID, out campaignActivityId);

                    t.Trace("5.2.1 CampaignActivityID is " + campaignActivityId.ToString());

                    if (campaignActivityId != Guid.Empty)
                    {
                        t.Trace("5.2.2 Look up the Campaign Activity...");
                        campaignActivity = (CampaignActivity)service.Retrieve(
                            CampaignActivity.EntityLogicalName, campaignActivityId, new ColumnSet {
                            AllColumns = true
                        });

                        t.Trace("5.2.3 campaignActivityId: " + campaignActivityId);
                        t.Trace("5.2.4 campaignActivity.Id: " + campaignActivity.Id.ToString());

                        if (campaignActivity != null) // Found a Campaign Activity.
                        {
                            // Create a Campaign Response.
                            t.Trace("5.3 Create a Campaign Response...");

                            campaignResponse.ChannelTypeCode = new OptionSetValue((int)636280001); // 636280001: Web Page Form fill

                            campaignResponse.Customer = new ActivityParty[] {
                                new ActivityParty {
                                    PartyId = new EntityReference(Contact.EntityLogicalName, contact.Id)
                                }
                            };

                            campaignResponse.FirstName         = webFormFill.cldrkt_FirstName;
                            campaignResponse.LastName          = webFormFill.cldrkt_LastName;
                            campaignResponse.EMailAddress      = webFormFill.cldrkt_Email;
                            campaignResponse.Telephone         = webFormFill.cldrkt_BusinessPhone;
                            campaignResponse.CompanyName       = webFormFill.cldrkt_Organization;
                            campaignResponse.PromotionCodeName = webFormFill.cldrkt_PromotionCode;

                            campaignResponse.cldrkt_CampaignActivityId = new EntityReference {
                                Id          = campaignActivity.Id,
                                LogicalName = CampaignActivity.EntityLogicalName,
                            };
                            campaignResponse.OriginatingActivityId = new EntityReference {
                                Id          = webFormFill.Id,
                                LogicalName = cldrkt_webformfill.EntityLogicalName,
                            };
                            campaignResponse.RegardingObjectId = new EntityReference // Required, must be the parent campaign
                            {
                                Id          = campaignActivity.RegardingObjectId.Id,
                                LogicalName = Campaign.EntityLogicalName,
                            };

                            campaignResponse.ReceivedOn = webFormFill.CreatedOn;

                            campaignResponse.Subject = webFormFill.Subject; //TODO: Change to an available field.

                            t.Trace("5.2.5 Create the Campaign Response.");

                            campaignResponse.ActivityId = service.Create(campaignResponse);
                            t.Trace("5.3.1 campaignResponse.ActivityId: " + campaignResponse.ActivityId);
                            t.Trace("5.3.2 campaignResponse.Id: " + campaignResponse.Id.ToString());

                            // Update the Campaign Response.
                            t.Trace("5.4 Update the Campaign Response.");

                            if (campaignResponse.Id != Guid.Empty)
                            {
                                service.Update(campaignResponse);
                                t.Trace("5.4.1 campaignResponse.Id = " + campaignResponse.Id.ToString());
                            }

                            // Add the Campaign Activity to the Web Form Fill.
                            t.Trace("5.5. Add the Campaign Activity to the Web Form fill");

                            webFormFill.cldrkt_Campaign = new EntityReference {
                                Id          = campaignActivity.RegardingObjectId.Id,
                                LogicalName = campaignActivity.RegardingObjectId.LogicalName,
                            };
                            webFormFill.cldrkt_CampaignActivity = new EntityReference {
                                Id          = campaignActivity.Id,
                                LogicalName = campaignActivity.LogicalName,
                            };
                            webFormFill.cldrkt_CampaignResponse = new EntityReference {
                                Id          = campaignResponse.Id,
                                LogicalName = campaignResponse.LogicalName,
                            };
                            t.Trace("5.6 Update the webFormFill.");
                            service.Update(webFormFill);
                        }
                    }
                }

                #endregion 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response.

                #region 6. Create a new Opportunity and map it to the Contact.

                t.Trace("6. Create a new Opportunity and map it to the Contact. ");

                string productNumber =  // Defaulting to SMSP.  The Product Number has to be valid.
                                       String.IsNullOrEmpty(webFormFill.cldrkt_ProductNumber) ? "SMSP-License" : webFormFill.cldrkt_ProductNumber;

                QueryExpression productQuery = new QueryExpression {
                    EntityName = Product.EntityLogicalName,
                    ColumnSet  = new ColumnSet {
                        AllColumns = true
                    },
                    Criteria = new FilterExpression {
                        Conditions =
                        {
                            new ConditionExpression {
                                AttributeName = "productnumber",
                                Operator      = ConditionOperator.Equal,
                                Values        =     { productNumber},
                            }
                        }
                    }
                };

                t.Trace("6.1.1 Look up the product. ");

                Product product = (Product)service.RetrieveMultiple(productQuery).Entities.FirstOrDefault();

                t.Trace("6.1.2 product.Id is " + product.Id.ToString() + " product.ProductId is " + product.ProductId);

                t.Trace("6.1.3 product.ProductId is " + product.Id.ToString() + " ");

                t.Trace("6.2 Create the Opportunity. ");
                t.Trace("6.2.0 campaignActivity.Id is " + campaignActivity.Id.ToString());
                t.Trace("6.2.1 campaignActivity.RegardingObjectId.Id is " + campaignActivity.RegardingObjectId.Id.ToString());
                t.Trace("6.2.2 account.Name and product.ProductNumber are " + account.Name + " " + product.ProductNumber);
                t.Trace("6.2.3  product.PriceLevelId is " + product.PriceLevelId.Id.ToString());

                Opportunity opportunity = new Opportunity {
                    CampaignId            = campaignActivity.RegardingObjectId,
                    cldrkt_EstimatedUsers = (int?)webFormFill.cldrkt_ProductQuantity,
                    Name = webFormFill.Subject, // Required.
                    cldrkt_DateofLastContact  = webFormFill.CreatedOn,
                    IsRevenueSystemCalculated = true,
                    ParentAccountId           = new EntityReference {
                        Id          = account.Id,
                        LogicalName = Account.EntityLogicalName,
                    },
                    ParentContactId = new EntityReference {
                        Id          = contact.Id,
                        LogicalName = Contact.EntityLogicalName,
                    },
                    PriceLevelId          = product.PriceLevelId,          // Required
                    StepName              = "1-Conversation",
                    TransactionCurrencyId = product.TransactionCurrencyId, // Required.
                };

                t.Trace("6.2.5 opportunity.TransactionCurrencyId is " + opportunity.TransactionCurrencyId.Name.ToString());
                t.Trace("6.2.6 TransactionCurrencyId.Id is " + opportunity.TransactionCurrencyId.Id.ToString());
                t.Trace("6.2.6.1 opportunity.ParentContactId.Id is " + opportunity.ParentContactId.Id.ToString());

                opportunity.Id = service.Create(opportunity);
                service.Update(opportunity);

                t.Trace("6.2.7 opportunity.Id is " + opportunity.Id.ToString());
                t.Trace("6.2.7.1 ShowMe price is " + Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity));

                t.Trace("6.3 Create the OpportunityProduct.");
                OpportunityProduct opportunityProduct = new OpportunityProduct {
                    OpportunityId = new EntityReference {
                        LogicalName = Opportunity.EntityLogicalName,
                        Id          = opportunity.Id,
                    },
                    ProductId = new EntityReference {
                        LogicalName = Product.EntityLogicalName,
                        Id          = product.Id,
                    },
                    UoMId = new EntityReference {
                        LogicalName = UoM.EntityLogicalName,
                        Id          = product.DefaultUoMId.Id,
                    },
                    Quantity     = webFormFill.cldrkt_ProductQuantity,
                    PricePerUnit = new Money {
                        Value = Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity),
                    },
                    IsPriceOverridden = true,
                };

                t.Trace("6.3.1 Creating the opportunityProduct. ");
                opportunityProduct.Id = service.Create(opportunityProduct);

                t.Trace("6.3.2 opportunityProduct.Id is " + opportunityProduct.Id.ToString());
                t.Trace("6.3.3 opportunityProductProductId.Id is " + opportunityProduct.ProductId.Id.ToString());

                t.Trace("6.3.4 opportunityProduct.Quantity is " + opportunityProduct.Quantity);
                t.Trace("6.3.5 opportunityProduct.Quantity.Value is " + opportunityProduct.Quantity.Value);
                t.Trace("6.3.6 opportunityProduct.PricePerUnit is " + opportunityProduct.PricePerUnit);
                t.Trace("6.3.7 opportunityProduct.PricePerUnit.Value is " + opportunityProduct.PricePerUnit.Value);

                service.Update(opportunityProduct);
                service.Update(opportunity);

                #endregion 6. Create a new Opportunity and map it to the Contact.

                #region 7. Get the response email template.

                t.Trace(" 7. Get the email template from the Web Form Fill, otherwise use a default template");
                QueryExpression templateQuery = new QueryExpression {
                    EntityName = Template.EntityLogicalName,
                    ColumnSet  = new ColumnSet {
                        AllColumns = true
                    },
                    Criteria = new FilterExpression {
                        Conditions =
                        {
                            new ConditionExpression {
                                AttributeName = "title",
                                Operator      = ConditionOperator.Equal,
                                Values        =     { webFormFill.cldrkt_EmailTemplateTitle},
                            }
                        }
                    }
                };

                Template emailTemplate          = new Template();
                Guid     defaultEmailTemplateId = Guid.Parse("d4fe12fd-72d2-e311-9e62-6c3be5be5e68"); // Default, SMSP demo request
                Guid     emailTemplateId        = new Guid();

                if (String.IsNullOrEmpty(webFormFill.cldrkt_EmailTemplateTitle))
                {
                    emailTemplateId = defaultEmailTemplateId;
                    t.Trace("7.1 No email template set from the web form.");
                }
                else
                {
                    t.Trace("7.2.1 Looking up Template from webFormFill: " + webFormFill.cldrkt_EmailTemplateTitle);

                    emailTemplate = (Template)service.RetrieveMultiple(templateQuery).Entities.FirstOrDefault();
                    if (emailTemplate == null)
                    {
                        t.Trace("Template is null");
                    }
                    else
                    {
                        t.Trace("Template is not null.");
                        t.Trace("Template type is: " + emailTemplate.TemplateTypeCode.ToString());
                    }

                    t.Trace("7.2.1 Looked up Template using the Title. ");

                    emailTemplateId = emailTemplate == null ? defaultEmailTemplateId : emailTemplate.Id;
                    t.Trace("7.2.2 emailTemplateId: " + emailTemplateId.ToString());
                }

                t.Trace("7.3.1 The email template is " + emailTemplate.Title.ToString() + " type of " + emailTemplate.TemplateTypeCode + " Id: " + emailTemplateId.ToString());

                #endregion 7. Get the response email template.

                #region 8. Create and send the response email.

                t.Trace("8. Create and send the email message.");
                t.Trace("8. Send from: " + user.FullName.ToString());
                t.Trace("8. Send to: " + contact.Id.ToString() + " using template " + emailTemplate.Title + " with Id " + emailTemplateId.ToString());
                // Create an email using an Opportunity template. "To" is a Contact type.
                SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest {
                    Target = new Email {
                        To = new ActivityParty[] { new ActivityParty {
                                                       PartyId = new EntityReference(Contact.EntityLogicalName, opportunity.ParentContactId.Id)
                                                   } },
                        From = new ActivityParty[] { new ActivityParty {
                                                         PartyId = new EntityReference(SystemUser.EntityLogicalName, user.Id)
                                                     } },
                        Subject       = "",
                        Description   = "",
                        DirectionCode = true,
                    },
                    RegardingId   = opportunity.Id, // Required, and the type must match the Email Template type.
                    RegardingType = emailTemplate.TemplateTypeCode,

                    TemplateId = emailTemplateId,
                };

                t.Trace("8.1 Send email to: " + opportunity.ParentContactId.Id.ToString() + " from: " + user.DomainName);
                t.Trace("8.1.1 Contact ID is: " + contact.Id.ToString() + ", email template is " + emailTemplate.Id.ToString() + ", opportunity is " + opportunity.Id.ToString());
                t.Trace("8.1.2 email template id is: " + emailUsingTemplateReq.TemplateId.ToString());

                SendEmailFromTemplateResponse email = (SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq);

                t.Trace("8.2 Email sent: " + email.Id.ToString());

                #endregion 8. Create and send the response email.

                #region 9. Add this Contact to the Marketing List, and create the list if it doesn't exist.

                t.Trace("9. Add this Contact to the Marketing List. " + contact.Id.ToString() + " to List " + webFormFill.cldrkt_AddToMarketingList);

                List staticContactList = new List {
                    CreatedFromCode = new OptionSetValue((int)2),        // Required.  Account = 1, Contact = 2, Lead = 4.
                    Id          = Guid.NewGuid(),                        // Required.
                    ListName    = webFormFill.cldrkt_AddToMarketingList, // Required.
                    LogicalName = List.EntityLogicalName,
                    OwnerId     = new EntityReference {                  // Required.
                        Id          = user.Id,
                        LogicalName = SystemUser.EntityLogicalName,
                    },
                    StatusCode = new OptionSetValue((int)0),
                    Type       = false, // Required.  True = dynamic, false = static.
                };

                QueryExpression listQuery = new QueryExpression {
                    EntityName = List.EntityLogicalName,
                    ColumnSet  = new ColumnSet {
                        AllColumns = true
                    },
                    Criteria = new FilterExpression {
                        Conditions =
                        {
                            new ConditionExpression {
                                AttributeName = "listname",
                                Operator      = ConditionOperator.Equal,
                                Values        =     { webFormFill.cldrkt_AddToMarketingList},
                            }
                        }
                    }
                };
                t.Trace("9.1 Get this list, if it exists: " + webFormFill.cldrkt_AddToMarketingList);

                Entity list = service.RetrieveMultiple(listQuery).Entities.FirstOrDefault();
                t.Trace("9.2 Look up the list.");

                if (list == null)
                {
                    t.Trace("9.3.1 Create a new list: " + staticContactList.Id.ToString());
                    staticContactList.Id = service.Create(staticContactList);
                }
                else
                {
                    t.Trace("9.3.2 Use the list we found: " + list.Id.ToString());
                    staticContactList.Id = list.Id;
                }

                t.Trace("9.4 Add the Contact " + contact.Id.ToString() + " to List " + staticContactList.Id.ToString());
                AddMemberListRequest addMemberListRequest = new AddMemberListRequest {
                    EntityId = contact.Id,
                    ListId   = staticContactList.Id,
                };

                service.Execute(addMemberListRequest);

                #endregion 9. Add this Contact to the Marketing List, and create the list if it doesn't exist.

                #region 10. Update the entities we've worked on.

                t.Trace("10. Update the entities we've worked on. ");

                webFormFill.RegardingObjectId = new EntityReference {
                    Id = contact.Id, LogicalName = Contact.EntityLogicalName,
                };
                service.Update(webFormFill);

                service.Update(contact);
                service.Update(opportunityProduct);
                service.Update(opportunity);
                service.Update(webFormFill);

                #endregion 10. Update the entities we've worked on.

                //throw new InvalidPluginExecutionException("Finished processing the Web Form Fill update.");
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting WebFormFill.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
コード例 #11
0
ファイル: CreateOpportunity.cs プロジェクト: cesugden/Scripts
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate method to create any data that this sample requires.
        /// Create a new opportunity and few opportunity product 
        /// including write-in product.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetCreateOpportunity1>

                    // Create a new opportunity with user specified estimated revenue
                    Opportunity newOpportunity = new Opportunity
                    {
                        Name = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
                        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
                    };

                    _opportunityId = _serviceProxy.Create(newOpportunity);
                    Console.WriteLine("Created {0} with user specified estimated revenue.",
                        newOpportunity.Name);

                    // Create a new opportunity product from the catalog

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

                    _catalogProductId = _serviceProxy.Create(catalogProduct);
                    Console.WriteLine("Created the catalog product.");

                    // Create anothter catalog product and override the list price
                    OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
                    {
                        OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                            _opportunityId),
                        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);
                    Console.WriteLine(@"Created another catalog product and 
                    overriden the list price.");

                    // create a new write-in opportunity product with a manual discount applied
                    OpportunityProduct writeInProduct = new OpportunityProduct
                    {
                        OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                            _opportunityId),
                        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);
                    Console.WriteLine("Created {0}.", writeInProduct.ProductDescription);
                    //</snippetCreateOpportunity1>                

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // 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;
            }			
		}
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group, few products, price list and price list items.
        /// Create an account record.
        /// Create few opportunities, opportunity products and a write-in product.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group.
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name        = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);

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

            // retrieve the unit id.
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet  = new ColumnSet("uomid", "name"),
                Criteria   = new FilterExpression(),
                PageInfo   = new PagingInfo
                {
                    PageNumber = 1,
                    Count      = 1
                }
            };

            unitQuery.Criteria.AddCondition("uomscheduleid", ConditionOperator.Equal, _unitGroupId);

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

            Console.WriteLine("Retrieved {0}", unit.Name);


            // 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, unit.Id)
            };

            _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      = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, unit.Id)
            };

            _product2Id = _serviceProxy.Create(newProduct2);

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

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);

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

            // Create a price list items for the products
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId    = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId        = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Amount       = new Money(20)
            };

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

            Console.WriteLine("Created price list for {0}", newProduct1.Name);

            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId        = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Amount       = new Money(20)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

            Console.WriteLine("Created price list for {0}", newProduct2.Name);

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

            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            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 both the products");


            // Create an account record for the opportunity's potential customerid
            Account newAccount = new Account
            {
                Name = "Example Account"
            };

            _accountId = _serviceProxy.Create(newAccount);

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

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name          = "Example Opportunity",
                CustomerId    = new EntityReference(Account.EntityLogicalName, _accountId),
                PriceLevelId  = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                FreightAmount = new Money(10.00m)
            };

            _opportunityId = _serviceProxy.Create(newOpportunity);

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

            // Create an opportunity product
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                ProductId     = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId         = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Quantity      = 3,
                Tax           = new Money(4.80m)
            };

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            Console.WriteLine("Created opportunity product for {0} and {1}", newOpportunity.Name, newProduct1.Name);

            // Create a catalog product and override the price per unit
            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId     = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                ProductId         = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId             = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Quantity          = 1,
                IsPriceOverridden = true,
                PricePerUnit      = new Money(12),
                Tax = new Money(0.96m)
            };

            _opportunityProduct2Id = _serviceProxy.Create(newOpportunityProduct2);

            Console.WriteLine("Created opportunity product for {0} and {1}", newOpportunity.Name, newProduct2.Name);

            // Create a write-in product with a manual discount
            OpportunityProduct newWriteInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                // set this attribute to make it a write-in product
                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(newWriteInProduct);

            Console.WriteLine("Created {0}", newWriteInProduct.ProductDescription);

            return;
        }
        /// <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
        }
コード例 #14
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, an
        /// opportunity is created to demonstrate a negative estimated value. This is
        /// followed by the creation of a quote with a negative product quantity.
        /// Finally, a sales order with a negative product price is shown.
        /// </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
            {
                //<snippetWorkingWithNegativePrices1>
                // 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 Opportunity with negative estimated value

                    // Create a new opportunity with user-specified negative
                    // estimated value.
                    Opportunity opportunity = new Opportunity
                    {
                        Name       = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                                                           _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue            = new Money(-400.00m),
                        FreightAmount             = new Money(10.00m),
                        ActualValue = new Money(-390.00m),
                        OwnerId     = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _opportunityId = _serviceProxy.Create(opportunity);
                    opportunity.Id = _opportunityId;

                    // Create a catalog product for the opportunity.
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = opportunity.ToEntityReference(),
                        ProductId     = new EntityReference(Product.EntityLogicalName,
                                                            _product1Id),
                        UoMId = new EntityReference(UoM.EntityLogicalName,
                                                    _defaultUnitId),
                        Quantity = 8,
                        Tax      = new Money(12.42m),
                    };
                    _catalogProductId = _serviceProxy.Create(catalogProduct);

                    Console.WriteLine("Created opportunity with negative estimated value.");

                    #endregion

                    #region Quote with negative quantity

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

                    // Set the quote's product quantity to a negative value.
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                                                        _product1Id),
                        Quantity = -4,
                        QuoteId  = quote.ToEntityReference(),
                        UoMId    = new EntityReference(UoM.EntityLogicalName,
                                                       _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Created quote with negative quantity.");

                    #endregion

                    #region Sales Order with negative price

                    // Create the sales order.
                    SalesOrder order = new SalesOrder()
                    {
                        Name          = "Faux Order",
                        DateFulfilled = new DateTime(2010, 8, 1),
                        PriceLevelId  = new EntityReference(PriceLevel.EntityLogicalName,
                                                            _priceListId),
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                        FreightAmount = new Money(20.0M)
                    };
                    _orderId = _serviceProxy.Create(order);
                    order.Id = _orderId;

                    // Add the product to the order with the price overriden with a
                    // negative value.
                    SalesOrderDetail orderDetail = new SalesOrderDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                                                        _product1Id),
                        Quantity          = 4,
                        SalesOrderId      = order.ToEntityReference(),
                        IsPriceOverridden = true,
                        PricePerUnit      = new Money(-40.0M),
                        UoMId             = new EntityReference(UoM.EntityLogicalName,
                                                                _defaultUnitId)
                    };
                    _orderDetailId = _serviceProxy.Create(orderDetail);

                    Console.WriteLine("Created order with negative price per unit.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetWorkingWithNegativePrices1>
            }

            // 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;
            }
        }
コード例 #15
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate method to create any data that this sample requires.
        /// Retrieve opportunity and opportunity products.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();


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

                    // Retrieve Opportunity record.
                    Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
                        Opportunity.EntityLogicalName,
                        _opportunityId,
                        new ColumnSet("name"));

                    Console.WriteLine("Retrieved {0}", checkOpportunity.Name);

                    // Retrieve the related opportunity products
                    QueryExpression opportunityProductsQuery = new QueryExpression
                    {
                        EntityName = OpportunityProduct.EntityLogicalName,
                        ColumnSet  = new ColumnSet("opportunityproductid", "volumediscountamount"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "opportunityid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _opportunityId }
                                }
                            }
                        }
                    };

                    DataCollection <Entity> opportunityProducts = _serviceProxy.RetrieveMultiple(
                        opportunityProductsQuery).Entities;

                    foreach (Entity entity in opportunityProducts)
                    {
                        OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
                        Console.WriteLine("Retrieved Opportunity Product {0}",
                                          opportunityProduct.OpportunityProductId.Value);
                    }

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // 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;
            }
        }
コード例 #16
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 Opportunity with negative estimated value

                    // Create a new opportunity with user-specified negative
                    // estimated value.
                    Opportunity opportunity = new Opportunity
                    {
                        Name       = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                                                           _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue            = new Money(-400.00m),
                        FreightAmount             = new Money(10.00m),
                        ActualValue = new Money(-390.00m),
                        OwnerId     = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _opportunityId = _serviceProxy.Create(opportunity);
                    opportunity.Id = _opportunityId;

                    // Create a catalog product for the opportunity.
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = opportunity.ToEntityReference(),
                        ProductId     = new EntityReference(Product.EntityLogicalName,
                                                            _product1Id),
                        UoMId = new EntityReference(UoM.EntityLogicalName,
                                                    _defaultUnitId),
                        Quantity = 8,
                        Tax      = new Money(12.42m),
                    };
                    _catalogProductId = _serviceProxy.Create(catalogProduct);

                    Console.WriteLine("Created opportunity with negative estimated value.");

                    #endregion

                    #region Quote with negative quantity

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

                    // Set the quote's product quantity to a negative value.
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                                                        _product1Id),
                        Quantity = -4,
                        QuoteId  = quote.ToEntityReference(),
                        UoMId    = new EntityReference(UoM.EntityLogicalName,
                                                       _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Created quote with negative quantity.");

                    #endregion

                    #region Sales Order with negative price

                    // Create the sales order.
                    SalesOrder order = new SalesOrder()
                    {
                        Name          = "Faux Order",
                        DateFulfilled = new DateTime(2010, 8, 1),
                        PriceLevelId  = new EntityReference(PriceLevel.EntityLogicalName,
                                                            _priceListId),
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                        FreightAmount = new Money(20.0M)
                    };
                    _orderId = _serviceProxy.Create(order);
                    order.Id = _orderId;

                    // Add the product to the order with the price overriden with a
                    // negative value.
                    SalesOrderDetail orderDetail = new SalesOrderDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                                                        _product1Id),
                        Quantity          = 4,
                        SalesOrderId      = order.ToEntityReference(),
                        IsPriceOverridden = true,
                        PricePerUnit      = new Money(-40.0M),
                        UoMId             = new EntityReference(UoM.EntityLogicalName,
                                                                _defaultUnitId)
                    };
                    _orderDetailId = _serviceProxy.Create(orderDetail);

                    Console.WriteLine("Created order with negative price per unit.");

                    #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();
            }
        }
コード例 #17
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group, few products, price list and price list items.
        /// Create an account record.
        /// Create few opportunities, opportunity products and a write-in product.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group.
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);

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

            // retrieve the unit id.
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet = new ColumnSet("uomid", "name"),
                Criteria = new FilterExpression(),
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count = 1
                }
            };
            unitQuery.Criteria.AddCondition("uomscheduleid", ConditionOperator.Equal, _unitGroupId);

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

            Console.WriteLine("Retrieved {0}", unit.Name);

            
            // 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, unit.Id)
            };
           _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 = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id)
            };
            _product2Id = _serviceProxy.Create(newProduct2);

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

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

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

            // Create a price list items for the products
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Amount = new Money(20)
            };
            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

            Console.WriteLine("Created price list for {0}", newProduct1.Name);

            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Amount = new Money(20)
            };
            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

            Console.WriteLine("Created price list for {0}", newProduct2.Name);

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

            //Publish Product2
            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 both the products");


            // Create an account record for the opportunity's potential customerid
            Account newAccount = new Account
            {
                Name = "Example Account"
            };
            _accountId = _serviceProxy.Create(newAccount);

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

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName, _accountId),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                FreightAmount = new Money(10.00m)
            };
            _opportunityId = _serviceProxy.Create(newOpportunity);

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

            // Create an opportunity product 
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id),
                Quantity = 3,
                Tax = new Money(4.80m)
            };
            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            Console.WriteLine("Created opportunity product for {0} and {1}", newOpportunity.Name, newProduct1.Name);

            // Create a catalog product and override the price per unit
            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
               OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
               ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
               UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id),
               Quantity = 1,
               IsPriceOverridden = true,
               PricePerUnit = new Money(12),
               Tax = new Money(0.96m)
            };
            _opportunityProduct2Id = _serviceProxy.Create(newOpportunityProduct2);

            Console.WriteLine("Created opportunity product for {0} and {1}", newOpportunity.Name, newProduct2.Name);

            // Create a write-in product with a manual discount
            OpportunityProduct newWriteInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                // set this attribute to make it a write-in product
                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(newWriteInProduct);

            Console.WriteLine("Created {0}", newWriteInProduct.ProductDescription);

            return;
        }
コード例 #18
0
    public void init(JSONObject json)
    {
        if (json.GetValue("Id") != null)
        {
            this.Id = json.GetString("Id");
        }
        if (json.GetValue("Acount") != null)
        {
            this.accountName = json.GetString("Acount");
        }
        if (json.GetValue("Amount") != null)
        {
            this.amount = json.GetString("Amount");
        }
        if (json.GetValue("CloseDate") != null)
        {
            this.closeDate = json.GetString("CloseDate");
        }
        //if(json.GetValue("Contract") != null ) {this.contract = json.GetString("Contract");}
        if (json.GetValue("CreatedBy") != null)
        {
            this.createdBy = json.GetString("CreatedBy");
        }
        if (json.GetValue("Description") != null)
        {
            this.description = json.GetString("Description");
        }
        if (json.GetValue("ExpectedRevenue") != null)
        {
            this.expectedRevenue = json.GetNumber("ExpectedRevenue");
        }
        if (json.GetValue("ForecastCategoryName") != null)
        {
            this.forecastCategoryName = json.GetString("ForecastCategoryName");
        }
        if (json.GetValue("LastModifiedBy") != null)
        {
            this.lastModifiedBy = json.GetString("LastModifiedBy");
        }
        if (json.GetValue("LeadSource") != null)
        {
            this.leadSource = json.GetString("LeadSource");
        }
        if (json.GetValue("NextStep") != null)
        {
            this.nextStep = json.GetString("NextStep");
        }
        if (json.GetValue("Name") != null)
        {
            this.oppName = json.GetString("Name");
        }
        if (json.GetValue("Owner") != null)
        {
            this.owner = json.GetString("Owner");
        }
        if (json.GetValue("Pricebook2") != null)
        {
            this.pricebook2 = json.GetString("Pricebook2");
        }
        if (json.GetValue("IsPrivate") != null)
        {
            this.isPrivate = json.GetBoolean("IsPrivate");
        }
        if (json.GetValue("Probability") != null)
        {
            this.probability = json.GetNumber("Probability");
        }
        if (json.GetValue("TotalOpportunityQuantity") != null)
        {
            this.quantity = json.GetNumber("TotalOpportunityQuantity");
        }
        if (json.GetValue("StageName") != null)
        {
            this.stageName = json.GetString("StageName");
        }
        if (json.GetValue("Type") != null)
        {
            this.type = json.GetString("Type");
        }
        if (json.GetValue("Urgent__c") != null)
        {
            this.urgent = (float)json.GetNumber("Urgent__c");
        }
        if (json.GetValue("Urgent__c") != null)
        {
            this.urgent = (float)json.GetNumber("Urgent__c");
        }

        //create and add account.
        if (json.GetObject("Account") != null)
        {
            Account account = Account.CreateInstance("Account") as Account;
            account.init(json.GetObject("Account"));

            this.account = account;
        }


        //create and add opportunitylineitems/oppProducts
        if (json.GetObject("OpportunityLineItems") != null)
        {
            JSONArray rowRecords = json.GetObject("OpportunityLineItems").GetArray("records");

            List <OpportunityProduct> oppProducts = new List <OpportunityProduct>();

            foreach (JSONValue row in rowRecords)
            {
                OpportunityProduct oppProduct = OpportunityProduct.CreateInstance("OpportunityProduct") as OpportunityProduct;
                Debug.Log("opp product" + row.ToString());
                JSONObject rec = JSONObject.Parse(row.ToString());
                oppProduct.init(rec);
                oppProducts.Add(oppProduct);
            }

            this.oppProducts = oppProducts;
        }

        //create and add campaign.
        if (json.GetObject("Campaign") != null)
        {
            Campaign campaign = Campaign.CreateInstance("Campaign") as Campaign;
            campaign.init(json.GetObject("Campaign"));

            this.campaign = campaign;
        }

        //create and add account.
        if (json.GetObject("Contract") != null)
        {
            Contract contract = Contract.CreateInstance("Contract") as Contract;
            contract.init(json.GetObject("Contract"));

            this.contract = contract;
        }
    }
コード例 #19
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                try
                {
                    IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                    var contexto = new OrganizationServiceContext(service);

                    string json = string.Empty;
                    if (context.InputParameters.Contains("OpportunityClose") &&
                        context.InputParameters["OpportunityClose"] is Entity)
                    {
                        Entity oppClose = (Entity)context.InputParameters["OpportunityClose"];
                        var    opp      = new OpportunityLocal();
                        var    aco      = new AccountLocal();
                        opp.accountlocal            = aco;
                        opp.productopportunitylocal = new List <ProductOpportunityLocal>();
                        if (oppClose.Attributes.Contains("opportunityid"))
                        {
                            //Pega a referência da oportunidade que está sendo fechada
                            var oppRef = (EntityReference)oppClose["opportunityid"];
                            //Recupera todos os campos da oportunidade
                            var opportunityWin = service.Retrieve(oppRef.LogicalName, oppRef.Id, new ColumnSet(true));
                            //Atribuir os valores da oportunidade
                            opp.SetOpportunityLocal(opportunityWin);

                            if (opportunityWin.Attributes.ContainsKey("parentaccountid"))
                            {
                                //Pega a referência da conta
                                var acoRef = (EntityReference)opportunityWin["parentaccountid"];
                                //Recupera produtos da oportunidade
                                var opportunityWinAccount = service.Retrieve("account", acoRef.Id, new ColumnSet(true));
                                //Atribuir os valores da conta
                                aco.SetAccountLocal(opportunityWinAccount);

                                //Montar Oportunidade
                                opp.accountlocal = aco;
                            }

                            QueryExpression opportunityProductsQuery = new QueryExpression
                            {
                                EntityName = OpportunityProduct.EntityLogicalName,
                                ColumnSet  = new ColumnSet(true),
                                Criteria   = new FilterExpression
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "opportunityid",
                                            Operator      = ConditionOperator.Equal,
                                            Values        = { oppRef.Id }
                                        }
                                    }
                                }
                            };

                            DataCollection <Entity> opportunityProducts = service.RetrieveMultiple(opportunityProductsQuery).Entities;
                            foreach (Entity entity in opportunityProducts)
                            {
                                OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
                                var pop = new ProductOpportunityLocal();
                                pop.SetProductOpportunityLocal(opportunityProduct);
                                opp.productopportunitylocal.Add(pop);
                            }
                        }

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OpportunityLocal));
                            serializer.WriteObject(memoryStream, opp);
                            json = Encoding.UTF8.GetString(memoryStream.ToArray());
                        }


                        string URI = "http://posttestserver.com/post.php?dir=xiaoxiao";

                        using (WebClient wc = new WebClient())
                        {
                            string responseJson = string.Empty;
                            wc.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
                            wc.Headers[HttpRequestHeader.Accept]      = "application/json; charset=utf-8";

                            string HtmlResult = wc.UploadString(URI, json);
                        }
                    }
                }

                catch (WebException exception)
                {
                    string str = string.Empty;
                    if (exception.Response != null)
                    {
                        using (StreamReader reader =
                                   new StreamReader(exception.Response.GetResponseStream()))
                        {
                            str = reader.ReadToEnd();
                        }
                        exception.Response.Close();
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                                  "The timeout elapsed while attempting to issue the request.", exception);
                    }
                    throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                            "A Web exception occurred while attempting to issue the request. {0}: {1}",
                                                                            exception.Message, str), exception);
                }
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }
        }
コード例 #20
0
    public static void createOppProductBlock(OpportunityProduct oppProduct, int i, Transform parentTransform, Transform Block, SubRingDiskController subRingDiskCtrl)
    {
        Vector3 setRotation = parentTransform.rotation.eulerAngles;
        setRotation.x = -90.0f;

        float posX = (i < 1) ? 1.29f : 1.29f + (i * (1.29f * 0.14f));;
        float posY = 0f;

        Transform currentBlock = (Transform)Instantiate(Block, new Vector3(0, 0, 0), Quaternion.identity);
        currentBlock.SetParent(parentTransform);
        currentBlock.localScale = new Vector3(0.5f, 0.5f, 0.5f);;
        currentBlock.rotation = Quaternion.Euler(setRotation);
        currentBlock.localPosition = new Vector3(posX, posY, 0f);

        //get an instance of the component.
        Transform blockInstance = currentBlock.GetComponent<Transform>();

        BlockController blockController = blockInstance.GetComponent<BlockController>();

        blockController.speed = oppProduct.Priority;
        blockController.order = i;

        blockController.objectId = oppProduct.Id;
        blockController.objectName = oppProduct.Name;
        blockController.objectType = "OpportunityProduct";
        blockController.labels = new string[]{"Product", "List Price", "Sales Price", "Quantity", "Total Price"};
        blockController.fields = new string[]{oppProduct.Product, oppProduct.ListPrice.ToString ("$0,0.00"), oppProduct.UnitPrice.ToString ("$0,0.00"), "" + oppProduct.Quantity + "", oppProduct.TotalPrice.ToString ("$0,0.00")};
        blockController.description = oppProduct.Description;
        blockController.parentSubRingDiskController = subRingDiskCtrl;
        blockController.setText ("Opportunity Product");
    }
コード例 #21
0
ファイル: Crm_Wrapper.cs プロジェクト: mohamedElsayed96/Muon
 public static extern int AddOpportunityProduct(OpportunityProduct product, byte[] error, ConnectionString connection);
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate method to create any data that this sample requires.
        /// Create a new opportunity and few opportunity product
        /// including write-in product.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetCreateOpportunity1>

                    // Create a new opportunity with user specified estimated revenue
                    Opportunity newOpportunity = new Opportunity
                    {
                        Name       = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                        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
                    };

                    _opportunityId = _serviceProxy.Create(newOpportunity);
                    Console.WriteLine("Created {0} with user specified estimated revenue.",
                                      newOpportunity.Name);

                    // Create a new opportunity product from the catalog

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

                    _catalogProductId = _serviceProxy.Create(catalogProduct);
                    Console.WriteLine("Created the catalog product.");

                    // Create anothter catalog product and override the list price
                    OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
                    {
                        OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                            _opportunityId),
                        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);
                    Console.WriteLine(@"Created another catalog product and 
                    overriden the list price.");

                    // create a new write-in opportunity product with a manual discount applied
                    OpportunityProduct writeInProduct = new OpportunityProduct
                    {
                        OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                                                            _opportunityId),
                        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);
                    Console.WriteLine("Created {0}.", writeInProduct.ProductDescription);
                    //</snippetCreateOpportunity1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // 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;
            }
        }
コード例 #23
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, an 
        /// opportunity is created to demonstrate a negative estimated value. This is
        /// followed by the creation of a quote with a negative product quantity. 
        /// Finally, a sales order with a negative product price is shown.
        /// </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
            {
                //<snippetWorkingWithNegativePrices1>
                // 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 Opportunity with negative estimated value

                    // Create a new opportunity with user-specified negative 
                    // estimated value.
                    Opportunity opportunity = new Opportunity
                    {
                        Name = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue = new Money(-400.00m),
                        FreightAmount = new Money(10.00m),
                        ActualValue = new Money(-390.00m),
                        OwnerId = new EntityReference
                        {
                            Id = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _opportunityId = _serviceProxy.Create(opportunity);
                    opportunity.Id = _opportunityId;

                    // Create a catalog product for the opportunity.
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = opportunity.ToEntityReference(),
                        ProductId = new EntityReference(Product.EntityLogicalName,
                            _product1Id),
                        UoMId = new EntityReference(UoM.EntityLogicalName,
                            _defaultUnitId),
                        Quantity = 8,
                        Tax = new Money(12.42m),
                    };
                    _catalogProductId = _serviceProxy.Create(catalogProduct);

                    Console.WriteLine("Created opportunity with negative estimated value.");

                    #endregion

                    #region Quote with negative quantity

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

                    // Set the quote's product quantity to a negative value.
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                            _product1Id),
                        Quantity = -4,
                        QuoteId = quote.ToEntityReference(),
                        UoMId = new EntityReference(UoM.EntityLogicalName, 
                            _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Created quote with negative quantity.");

                    #endregion

                    #region Sales Order with negative price

                    // Create the sales order.
                    SalesOrder order = new SalesOrder()
                    {
                        Name = "Faux Order",
                        DateFulfilled = new DateTime(2010, 8, 1),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId),
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
                        FreightAmount = new Money(20.0M)
                    };
                    _orderId = _serviceProxy.Create(order);
                    order.Id = _orderId;

                    // Add the product to the order with the price overriden with a
                    // negative value.
                    SalesOrderDetail orderDetail = new SalesOrderDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName, 
                            _product1Id),
                        Quantity = 4,
                        SalesOrderId = order.ToEntityReference(),
                        IsPriceOverridden = true,
                        PricePerUnit = new Money(-40.0M),
                        UoMId = new EntityReference(UoM.EntityLogicalName, 
                            _defaultUnitId)
                    };
                    _orderDetailId = _serviceProxy.Create(orderDetail);

                    Console.WriteLine("Created order with negative price per unit.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetWorkingWithNegativePrices1>
            }

            // 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;
            }
        }
コード例 #24
0
        public static Guid CreateOpportunityProduct(HttpClient httpClient, OpportunityProduct opportunityProduct)
        {
            try
            {
                var opportunityProductJObject = new JObject()
                {
                    ["*****@*****.**"] = "/opportunities(" + opportunityProduct.OpportunityId + ")",
                    ["*****@*****.**"]     = "/products(" + opportunityProduct.ProductId + ")",
                    ["*****@*****.**"]         = "/uoms(" + opportunityProduct.UomId + ")",
                    ["quantity"]            = 1,
                    ["ispriceoverridden"]   = opportunityProduct.IsPriceOverriden,
                    ["blu_productcategory"] = opportunityProduct.ProductCategory,
                    ["blu_sellableto"]      = opportunityProduct.SellableTo,
                    ["blu_onbackorder"]     = opportunityProduct.OnBackOrder,
                    ["blu_freereport"]      = opportunityProduct.FreeReport
                };

                if (opportunityProduct.ReportPriority != 0)
                {
                    opportunityProductJObject["blu_reportpriority"] = opportunityProduct.ReportPriority;
                }

                if (opportunityProduct.IsPriceOverriden)
                {
                    opportunityProductJObject["priceperunit"] = opportunityProduct.Amount;
                }

                var request = new HttpRequestMessage(HttpMethod.Post,
                                                     webApiQueryUrl + "opportunityproducts")
                {
                    Content = new StringContent(opportunityProductJObject.ToString(), Encoding.UTF8, "application/json")
                };
                var response = httpClient.SendAsync(request);
                if (!response.Result.IsSuccessStatusCode)
                {
                    var error = response.Result.Content.ReadAsStringAsync();
                    LogService.LogMessage(httpClient, new Log()
                    {
                        Level        = (int)LogType.Error,
                        Name         = "Create Opportunity Product Error",
                        FunctionName = ClassName + " | " + MethodBase.GetCurrentMethod().Name,
                        Message      = error.Result.ToString()
                    });
                    return(Guid.Empty);
                }
                var recordUrl = response.Result.Headers.GetValues("OData-EntityId").FirstOrDefault();
                if (recordUrl == null)
                {
                    return(Guid.Empty);
                }
                var splitRetrievedData = recordUrl.Split('[', '(', ')', ']');
                var recordId           = Guid.Parse(splitRetrievedData[1]);
                return(recordId);
            }
            catch (Exception ex)
            {
                LogService.LogMessage(httpClient, new Log()
                {
                    Level        = (int)LogType.Error,
                    Name         = ex.Message,
                    FunctionName = ClassName + " | " + MethodBase.GetCurrentMethod().Name,
                    Message      = ex.InnerException != null ? ex.InnerException.Message : ex.Message
                });
                return(Guid.Empty);
            }
        }