public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid medicationPriceListId = Guid.Empty; try { // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Sample Price List " + GenerateRandomNumber() }; medicationPriceListId = _serviceProxy.Create(newPriceList); foreach (Medication product in Products) { ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, medicationPriceListId), ProductId = new EntityReference(Product.EntityLogicalName, Guid.Parse(product.MedicationId)), UoMId = new EntityReference(UoM.EntityLogicalName, Guid.Parse(UomId)), Amount = new Money(int.Parse(GenerateRandomNumber(2))) }; Guid priceListItemId = _serviceProxy.Create(newPriceListItem); if (priceListItemId == null) { break; } } if (medicationPriceListId != Guid.Empty) { PriceListId = medicationPriceListId.ToString(); Console.WriteLine("Created Price List [" + PriceListId + "]"); } else { throw new Exception("PriceListId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(medicationPriceListId); }
private async Task <Result <Guid> > UpsertPriceLevel(Guid productId, StockItem stockItem) { return(await _crmRepository.GetWithFetchXmlAsync <ProductPriceLevel>( PluralNameConstants.ProductPriceLevels, FetchXmlHelper.FindProductPriceLevelBy( productId, _options.SalesOptions.DefaultPriceList)) .Bind(priceLevel => { Task <Result <Guid> > upsertResult; if (priceLevel == null) { priceLevel = new ProductPriceLevel { Id = Guid.NewGuid(), DefaultPriceList = _options.SalesOptions.DefaultPriceList, ProductId = productId, DefaultUomId = _options.SalesOptions.UoMId, Amount = stockItem.ResellerPriceInc }; upsertResult = _crmRepository.CreateAsync(PluralNameConstants.ProductPriceLevels, priceLevel) .Tap(id => Log.Debug("Product({@ProductId}) Price was created on {@CreatedOn}.", productId, DateTime.Now)); } else { if (priceLevel.Amount == stockItem.ResellerPriceInc) { return Task.FromResult( Result.Ok(priceLevel.Id) .Tap(id => Log.Information("Product Price for Product({@ProductPriceId}) was unchanged.", id))); } priceLevel.Amount = Math.Round(stockItem.ResellerPriceInc, 2); upsertResult = _crmRepository.UpdateAsync(PluralNameConstants.ProductPriceLevels, priceLevel, priceLevel.Id) .Tap(id => Log.Debug("Product({@ProductId}) Price was updated on {@ModifiedOn}.", productId, DateTime.Now)); } return upsertResult; })); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a unit group. UoMSchedule unitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _service.Create(unitGroup); // Retrieve the unit. QueryExpression unitQuery = new QueryExpression() { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = { Conditions = { new ConditionExpression ("uomscheduleid", ConditionOperator.Equal, _unitGroupId) } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; UoM unit = (UoM)_service.RetrieveMultiple(unitQuery).Entities[0]; // Create an account. Account account = new Account { Name = "Litware, Inc.", Address1_StateOrProvince = "Colorado" }; _accountId = (_service.Create(account)); // Create the 2 contacts. Contact contact = new Contact() { FirstName = "Ben", LastName = "Andrews", EMailAddress1 = "*****@*****.**", Address1_City = "Redmond", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(206)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _contactIdList.Add(_service.Create(contact)); contact = new Contact() { FirstName = "Colin", LastName = "Wilcox", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(425)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _contactIdList.Add(_service.Create(contact)); // Create pricing and product objects. PriceLevel priceLevel = new PriceLevel() { Name = "Faux Price List" }; _priceLevelId = _service.Create(priceLevel); Product product = new Product() { ProductNumber = "1", QuantityDecimal = 4, Name = "Faux Product", Price = new Money(20.0M), DefaultUoMId = new EntityReference { Id = unit.Id, LogicalName = UoM.EntityLogicalName }, DefaultUoMScheduleId = new EntityReference { Id = _unitGroupId, LogicalName = UoMSchedule.EntityLogicalName } }; _productId = _service.Create(product); ProductPriceLevel productPrice = new ProductPriceLevel() { PriceLevelId = new EntityReference() { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, ProductId = new EntityReference() { Id = _productId, LogicalName = Product.EntityLogicalName }, UoMId = new EntityReference { Id = unit.Id, LogicalName = UoM.EntityLogicalName }, Amount = new Money(20.0M), }; _productPriceId = _service.Create(productPrice); // Create 3 orders. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); order = new SalesOrder() { Name = "Old Faux Order", DateFulfilled = new DateTime(2010, 4, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); order = new SalesOrder() { Name = "Oldest Faux Order", DateFulfilled = new DateTime(2008, 8, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); // Create 2 opportunities. Opportunity opportunity = new Opportunity() { Name = "Litware, Inc. Opportunity 1", EstimatedCloseDate = new DateTime(2011, 1, 1), CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _opportunityIdList.Add(_service.Create(opportunity)); opportunity = new Opportunity() { Name = "Litware, Inc. Opportunity 2", EstimatedCloseDate = new DateTime(2020, 1, 1), CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _opportunityIdList.Add(_service.Create(opportunity)); }
/// <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> /// This method creates any entity records that this sample requires. /// Create a unit group and price list. /// </summary> public void CreateRequiredRecords() { Console.WriteLine("Creating required records for the sample:"); // 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. unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; Console.WriteLine("Retrieved {0}", unit.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); Console.WriteLine("Created {0}", newPriceList.Name); // Create couple of product records Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", 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("\nCreated {0}", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", 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 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); Product newBundle = new Product { Name = "Example Bundle", ProductNumber = "B001", ProductStructure = new OptionSetValue(3), QuantityDecimal = 0, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id) }; _bundleId = _serviceProxy.Create(newBundle); Console.WriteLine("\nCreated {0}", newBundle.Name); // Create price list item for the bundle ProductPriceLevel newPriceListItem3 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _bundleId), UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), Amount = new Money(200) }; _priceListItem3Id = _serviceProxy.Create(newPriceListItem3); Console.WriteLine("Created price list for {0}", newBundle.Name); return; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a unit group. UoMSchedule unitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _service.Create(unitGroup); // Retrieve the unit. QueryExpression unitQuery = new QueryExpression() { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = { Conditions = { new ConditionExpression("uomscheduleid", ConditionOperator.Equal, _unitGroupId) } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; UoM unit = (UoM)_service.RetrieveMultiple(unitQuery).Entities[0]; // Create an account. Account account = new Account { Name = "Litware, Inc.", Address1_StateOrProvince = "Colorado" }; _accountId = (_service.Create(account)); // Create the 2 contacts. Contact contact = new Contact() { FirstName = "Ben", LastName = "Andrews", EMailAddress1 = "*****@*****.**", Address1_City = "Redmond", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(206)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _contactIdList.Add(_service.Create(contact)); contact = new Contact() { FirstName = "Colin", LastName = "Wilcox", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(425)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _contactIdList.Add(_service.Create(contact)); // Create pricing and product objects. PriceLevel priceLevel = new PriceLevel() { Name = "Faux Price List" }; _priceLevelId = _service.Create(priceLevel); Product product = new Product() { ProductNumber = "1", QuantityDecimal = 4, Name = "Faux Product", Price = new Money(20.0M), DefaultUoMId = new EntityReference { Id = unit.Id, LogicalName = UoM.EntityLogicalName }, DefaultUoMScheduleId = new EntityReference { Id = _unitGroupId, LogicalName = UoMSchedule.EntityLogicalName } }; _productId = _service.Create(product); ProductPriceLevel productPrice = new ProductPriceLevel() { PriceLevelId = new EntityReference() { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, ProductId = new EntityReference() { Id = _productId, LogicalName = Product.EntityLogicalName }, UoMId = new EntityReference { Id = unit.Id, LogicalName = UoM.EntityLogicalName }, Amount = new Money(20.0M), }; _productPriceId = _service.Create(productPrice); // Create 3 orders. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); order = new SalesOrder() { Name = "Old Faux Order", DateFulfilled = new DateTime(2010, 4, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); order = new SalesOrder() { Name = "Oldest Faux Order", DateFulfilled = new DateTime(2008, 8, 1), PriceLevelId = new EntityReference { Id = _priceLevelId, LogicalName = PriceLevel.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName }, FreightAmount = new Money(20.0M) }; _orderIdList.Add(_service.Create(order)); // Create 2 opportunities. Opportunity opportunity = new Opportunity() { Name = "Litware, Inc. Opportunity 1", EstimatedCloseDate = new DateTime(2011, 1, 1), CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _opportunityIdList.Add(_service.Create(opportunity)); opportunity = new Opportunity() { Name = "Litware, Inc. Opportunity 2", EstimatedCloseDate = new DateTime(2020, 1, 1), CustomerId = new EntityReference { Id = _accountId, LogicalName = account.LogicalName } }; _opportunityIdList.Add(_service.Create(opportunity)); }
/// <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 }
/// <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); _salesRepresentativeId = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath)[0]; #endregion #region Create records to support SalesOrder 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 newProduct = new Product { ProductNumber = "1", Name = "Example Product", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _productId = _serviceProxy.Create(newProduct); newProduct.Id = _productId; Console.WriteLine("Created {0}", newProduct.Name); // 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 newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _productId), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20), }; _priceListItemId = _serviceProxy.Create(newPriceListItem); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _productId), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("Published {0}", newProduct.Name); // Create an account record for the sales order's potential customerid Account newAccount = new Account { Name = "Litware, Inc.", Address1_PostalCode = "60661" }; _accountId = _serviceProxy.Create(newAccount); newAccount.Id = _accountId; #endregion Create records to support SalesOrder #region Create SalesOrder record // 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 = newProduct.ToEntityReference(), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(1000.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); #endregion Create SalesOrder record }
internal void AddProduct() { //建立單位群組 var newUnitGroup = new UoMSchedule(); newUnitGroup.Name = "觸控面板單位"; newUnitGroup.BaseUoMName = "觸控面板基本單位"; var unitGroupId = _orgService.Create(newUnitGroup); onLog(string.Format("Create Unit Group => {0}", unitGroupId)); //取得單位群組的預設單位 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); var unit = (UoM)_orgService.RetrieveMultiple(unitQuery).Entities[0]; onLog(string.Format("Get Default Unit Of Unit Group => {0}", unit.Id)); /* * Product.ProductStructure: * 1 表示建立產品 * 2 表示建立產品系列 * 3 表示建立搭售方案 */ //建立產品系列 -> 觸控面板烤爐 var productFamily = new Product(); productFamily.Name = "觸控面板烤爐"; productFamily.ProductNumber = "HPCP"; productFamily.ProductStructure = new OptionSetValue(2); var productCategoryId = _orgService.Create(productFamily); onLog(string.Format("Create Product Family => {0}", productCategoryId)); //建立產品 -> Dehydration-Bake var prod1 = new Product(); prod1.Name = "Dehydration-Bake"; prod1.ProductNumber = "HPCP-DB"; prod1.ProductStructure = new OptionSetValue(1); prod1.ParentProductId = new EntityReference(Product.EntityLogicalName, productCategoryId); prod1.QuantityDecimal = 2; prod1.DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, unitGroupId); prod1.DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id); var prod1Id = _orgService.Create(prod1); onLog(string.Format("Create Product 1=> {0}", prod1Id)); //建立產品 -> Pre-Bake var prod2 = new Product(); prod2.Name = "Pre-Bake"; prod2.ProductNumber = "HPCP-PreB"; prod2.ProductStructure = new OptionSetValue(1); prod2.ParentProductId = new EntityReference(Product.EntityLogicalName, productCategoryId); prod2.QuantityDecimal = 2; prod2.DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, unitGroupId); prod2.DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id); var prod2Id = _orgService.Create(prod2); onLog(string.Format("Create Product 2=> {0}", prod2Id)); //建立產品 -> Post-Bake var prod3 = new Product(); prod3.Name = "Post-Bake"; prod3.ProductNumber = "HPCP-PostB"; prod3.ProductStructure = new OptionSetValue(1); prod3.ParentProductId = new EntityReference(Product.EntityLogicalName, productCategoryId); prod3.QuantityDecimal = 2; prod3.DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, unitGroupId); prod3.DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id); var prod3Id = _orgService.Create(prod3); onLog(string.Format("Create Product 3=> {0}", prod3Id)); //建立價目表 PriceLevel newPriceList = new PriceLevel { Name = "觸控面板單位官網定價" }; var priceLevelId = _orgService.Create(newPriceList); //建立價目表項目 (根據剛剛建立產品的Id來設定) //建立第一個產品價目表項目 ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, priceLevelId), ProductId = new EntityReference(Product.EntityLogicalName, prod1Id), UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), Amount = new Money(20) }; var priceListItem1Id = _orgService.Create(newPriceListItem1); Console.WriteLine("Created price list for {0}", prod1.Name); //建立第二個產品價目表項目 ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, priceLevelId), ProductId = new EntityReference(Product.EntityLogicalName, prod2Id), UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), Amount = new Money(1000) }; var priceListItem2Id = _orgService.Create(newPriceListItem2); Console.WriteLine("Created price list for {0}", prod2.Name); //建立第三個產品價目表項目 ProductPriceLevel newPriceListItem3 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, priceLevelId), ProductId = new EntityReference(Product.EntityLogicalName, prod3Id), UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), Amount = new Money(99) }; var priceListItem3Id = _orgService.Create(newPriceListItem3); Console.WriteLine("Created price list for {0}", prod3.Name); }
/// <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 }
/// <summary> /// Creates any entity records that this sample requires. /// </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("Create {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; // Create a few products Product newProduct = new Product { ProductNumber = "1", Name = "Example Product", ProductStructure = new OptionSetValue(1), QuantityDecimal = 1, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _productId = _serviceProxy.Create(newProduct); newProduct.Id = _productId; Console.WriteLine("Create {0}", newProduct.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the product and apply volume discount ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _productId), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20.0M), }; _priceListItemId = _serviceProxy.Create(newPriceListItem); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _productId), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("Published {0}", newProduct.Name); // Create an account record for the opportunity's potential customerid Account newAccount = new Account { Name = "Litware, Inc.", Address1_PostalCode = "60661" }; _accountId = _serviceProxy.Create(newAccount); newAccount.Id = _accountId; }
public void SubmitPurchaseOrderRequest(Guid workOrderId, Guid technicianId, OrderItemModel[] orderItems, HttpPostedFileBase purchaseOrderReceipt, HttpPostedFileBase purchaseOrderReceipt2, string vendor, string store, string card) { ClientCredentials credential = new ClientCredentials(); credential.UserName.UserName = "******"; credential.UserName.Password = "******"; Guid defaultUnit = new Guid("054ED7A8-A1AE-4D5F-9108-60D387606730"); Guid defaultUnitGroup = new Guid("682A0D63-FD3D-45DD-8C28-C2F5EB546ACE"); Guid defaultPriceList = new Guid("2344F7E8-8FD3-E711-810F-E0071B66CFA1"); Guid productId; Guid priceListId; // Set the org url var organizationURI = "https://advancedretail.crm.dynamics.com/XRMServices/2011/Organization.svc"; OrganizationServiceProxy svc = new OrganizationServiceProxy(new Uri(organizationURI), null, credential, null); svc.EnableProxyTypes(); if (orderItems == null) { throw new ArgumentNullException("orderItems"); } orderItems.ForEach(VaildateOrderItem); string techName = _technicianService.GetTechnicianName(technicianId); var workOrder = _context.IncidentSet.Single(w => w.IncidentId == workOrderId); //Using ticks as a way to have unique PO #'s. This does not "guarantee" a different number //in the case that two work orders are created at the EXACT same time, but the chance that //happens is miniscule. //long time = DateTime.Now.Ticks; //String fileName = Convert.ToString(time); var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var numbers = "0123456789"; var stringChars = new char[8]; var random = new Random(); for (int i = 0; i < 2; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } for (int i = 2; i < 6; i++) { stringChars[i] = numbers[random.Next(numbers.Length)]; } for (int i = 6; i < 8; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var fileName = new String(stringChars); foreach (OrderItemModel orderItem in orderItems) { OptionSetValue myOptionSet = new OptionSetValue(); if (vendor == "Visa") { myOptionSet.Value = 100000000; } else if (vendor == "Vendor 2") { myOptionSet.Value = 100000001; } else if (vendor == "Vendor 3") { myOptionSet.Value = 100000002; } else if (vendor == "Vendor 4") { myOptionSet.Value = 100000003; } else if (vendor == "Vendor 5") { myOptionSet.Value = 100000004; } else { myOptionSet.Value = 100000000; } OptionSetValue cardBool = new OptionSetValue(); if (card == "Yes") { cardBool.Value = 100000000; } else { cardBool.Value = 100000001; } var item1 = new ars_technicianitem { ars_Price = new Money(orderItem.Price), ars_description = orderItem.Item, ars_Quantity = orderItem.Quantity, ars_OrderId = workOrder.ars_Order, new_PONumber = fileName }; _context.AddObject(item1); //var item = new SalesOrderDetail //// This is not creating a new Order, but rather adding line items to the Order. ////This is the difference between the Sales Order and Sales Order Detail. //{ // PricePerUnit = new Money(orderItem.RealPrice), // ProductDescription = orderItem.Item, // IsPriceOverridden = true, // Quantity = orderItem.Quantity, // SalesOrderId = workOrder.ars_Order, // new_ponumber = fileName, // IsProductOverridden = true, // new_vendor = myOptionSet, // new_storename = store, // new_receipt = receiptBool, // new_Cost = new Money(orderItem.RealPrice), // new_ExtCost = new Money(orderItem.RealPrice*orderItem.Quantity), // new_RetailPrice = new Money(orderItem.beforeTaxPrice), // new_technician = techName, // new_card = cardBool, // new_date = DateTime.Now.ToString(), //}; QueryByAttribute query = new QueryByAttribute("product"); query.ColumnSet = new ColumnSet("productid", "defaultuomid"); query.Attributes.AddRange("name"); query.Values.AddRange(orderItem.Item); Entity productent = svc.RetrieveMultiple(query).Entities.ToList().FirstOrDefault(); if (productent == null) { //Entity productent_new = new Entity("product"); var newProduct = new Product { DefaultUoMId = new EntityReference(UoM.EntityLogicalName, defaultUnit), DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, defaultUnitGroup), QuantityDecimal = 2, ProductNumber = orderItem.Item, Name = orderItem.Item, Description = orderItem.Item, }; productId = svc.Create(newProduct); //Create price list item ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, defaultPriceList), ProductId = new EntityReference(Product.EntityLogicalName, productId), UoMId = new EntityReference(UoM.EntityLogicalName, defaultUnit), Amount = new Money(orderItem.RealPrice) }; priceListId = svc.Create(newPriceListItem); } else { //Grab ProductId from productent if it is not null productId = (Guid)productent.Attributes["productid"]; defaultUnit = ((EntityReference)productent.Attributes["defaultuomid"]).Id; } //Create SalesOrderDetail var item = new SalesOrderDetail { PricePerUnit = new Money(orderItem.RealPrice), IsPriceOverridden = true, Quantity = orderItem.Quantity, SalesOrderId = workOrder.ars_Order, new_ponumber = fileName, IsProductOverridden = false, //new_vendor = myOptionSet, //new_storename = store, //new_receipt = receiptBool, new_Cost = new Money(orderItem.RealPrice), new_ExtCost = new Money(orderItem.RealPrice * orderItem.Quantity), new_RetailPrice = new Money(orderItem.beforeTaxPrice), new_technician = techName, //new_card = cardBool, new_date = DateTime.Now.ToString(), ProductId = new EntityReference(Product.EntityLogicalName, productId), UoMId = new EntityReference(UoM.EntityLogicalName, defaultUnit) }; _context.AddObject(item); } if (purchaseOrderReceipt != null) { var annotation = new Annotation { NoteText = String.Format("Purchase order receipt from {0}", techName), ObjectId = workOrder.ars_Order, FileName = purchaseOrderReceipt.GetNonEmptyFileName(), MimeType = purchaseOrderReceipt.ContentType, DocumentBody = purchaseOrderReceipt.ConvertToBase64() }; _context.AddObject(annotation); } if (purchaseOrderReceipt2 != null) { var annotation = new Annotation { NoteText = String.Format("Purchase order receipt from {0}", techName), ObjectId = workOrder.ars_Order, FileName = purchaseOrderReceipt2.GetNonEmptyFileName(), MimeType = purchaseOrderReceipt2.ContentType, DocumentBody = purchaseOrderReceipt2.ConvertToBase64() }; _context.AddObject(annotation); } _context.SaveChanges(); }
/// <summary> /// Create and configure the organization service proxy. /// Initiate creating all entity records that this sample requires. /// Create a product family with two child product records. /// Create a substitute relation between the two products. /// Publish the product family hierarchy, including the child records. /// 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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetCreateandublishProducts1> // Create a product family Product newProductFamily = new Product { Name = "Example Product Family", ProductNumber = "PF001", ProductStructure = new OptionSetValue(2) }; _productFamilyId = _serviceProxy.Create(newProductFamily); Console.WriteLine("\nCreated {0}", newProductFamily.Name); // Create couple of product records under the product family Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0} under the product family", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0} under the product family", newProduct2.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); // Set the product relationship // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional) ProductSubstitute newProductRelation = new ProductSubstitute { SalesRelationshipType = new OptionSetValue(3), Direction = new OptionSetValue(1), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), SubstitutedProductId = new EntityReference(Product.EntityLogicalName, _product2Id) }; _productRelationId = _serviceProxy.Create(newProductRelation); Console.WriteLine("Created a substitute relation between the two products."); //</snippetCreateandublishProducts1> // Prompt the user whether to publish the product family and products bool publishRecords = true; Console.WriteLine("\nDo you want the product records published? (y/n)"); String answer = Console.ReadLine(); publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); if (publishRecords) { PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest { Target = new EntityReference(Product.EntityLogicalName, _productFamilyId) }; PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq); if (published.Results != null) { Console.WriteLine("Published the product records"); } } DeleteRequiredRecords(promptForDelete); } } catch { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </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 { //<snippetBasicContextExamples1> // 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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery<SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery<UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery<UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery<Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // 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 first connects to the Organization service. Afterwards, a /// quote is created. This quote is then converted to an order, and the pricing /// is unlocked and relocked. This is followed by the order being converted /// to an invoice, and the pricing is locked then unlocked. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetProcessingQuotesAndSalesOrders1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won), }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdateRequest> // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // TODO Add demonstration code here #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); #endregion #region Lose Opportunity var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); #endregion #region Convert Opportunity to a Quote // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); #endregion #region Close Quote // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); #endregion #region Convert Quote to SalesOrder // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); Console.WriteLine("Order pricing relocked."); #endregion #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); #endregion #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </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 { //<snippetBasicContextExamples1> // 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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery <SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery <UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery <UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery <Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // 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. /// 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; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate creating all entity records that this sample requires. /// Create a product family with two child product records. /// Create a substitute relation between the two products. /// Publish the product family hierarchy, including the child records. /// 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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); // Create a product family Product newProductFamily = new Product { Name = "Example Product Family", ProductNumber = "PF001", ProductStructure = new OptionSetValue(2) }; _productFamilyId = _serviceProxy.Create(newProductFamily); Console.WriteLine("\nCreated {0}", newProductFamily.Name); // Create couple of product records under the product family Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0} under the product family", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0} under the product family", newProduct2.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); // Set the product relationship // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional) ProductSubstitute newProductRelation = new ProductSubstitute { SalesRelationshipType = new OptionSetValue(3), Direction = new OptionSetValue(1), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), SubstitutedProductId = new EntityReference(Product.EntityLogicalName, _product2Id) }; _productRelationId = _serviceProxy.Create(newProductRelation); Console.WriteLine("Created a substitute relation between the two products."); // Prompt the user whether to publish the product family and products bool publishRecords = true; Console.WriteLine("\nDo you want the product records published? (y/n)"); String answer = Console.ReadLine(); publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); if (publishRecords) { PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest { Target = new EntityReference(Product.EntityLogicalName, _productFamilyId) }; PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq); if (published.Results != null) { Console.WriteLine("Published the product records"); } } DeleteRequiredRecords(promptForDelete); } } catch { // You can handle an exception here or pass it back to the calling method. throw; } }
[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 //<snippetCreateandublishProducts1> // Create a product family Product newProductFamily = new Product { Name = "Example Product Family", ProductNumber = "PF001", ProductStructure = new OptionSetValue(2) }; _productFamilyId = _serviceProxy.Create(newProductFamily); Console.WriteLine("\nCreated '{0}'", newProductFamily.Name); // Create a product property DynamicProperty newProperty = new DynamicProperty { Name = "Example Property", RegardingObjectId = new EntityReference(Product.EntityLogicalName, _productFamilyId), IsReadOnly = true, IsRequired = true, IsHidden = false, DataType = new OptionSetValue(3), //Single line of text DefaultValueString = "Default Value" }; _productPropertyId = _serviceProxy.Create(newProperty); Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name); // Create couple of product records under the product family Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created '{0}' under the product family", newProduct2.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("\nCreated 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); // Set the product relationship // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional) ProductSubstitute newProductRelation = new ProductSubstitute { SalesRelationshipType = new OptionSetValue(3), Direction = new OptionSetValue(1), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), SubstitutedProductId = new EntityReference(Product.EntityLogicalName, _product2Id) }; _productRelationId = _serviceProxy.Create(newProductRelation); Console.WriteLine("\nCreated a substitute relation between the two products."); //</snippetCreateandublishProducts1> // Override a product property at the product level // In this case we will override the property for 'Example Product 1' DynamicProperty newOverrideProperty = new DynamicProperty(); newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productPropertyId); newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverridenPropertyId = _serviceProxy.Create(newOverrideProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet columns = new ColumnSet(); columns.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverridenPropertyId, columns); // Update the attributes retrievedOverridenProperty.Name = "Overridden Example Property"; retrievedOverridenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverridenProperty); Console.WriteLine("\nOverridden the product property for 'Example Product 1'."); // Prompt the user whether to publish the product family and products bool publishRecords = true; Console.WriteLine("\nDo you want the product records published? (y/n)"); String answer = Console.ReadLine(); publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); if (publishRecords) { PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest { Target = new EntityReference(Product.EntityLogicalName, _productFamilyId) }; PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq); if (published.Results != null) { Console.WriteLine("Published the product records"); } // Overwrite a product property Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite."); // Retrieve the StateCode of Product that you want to revise ColumnSet cols = new ColumnSet(); cols.AddColumns("name", "statecode"); Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, cols); // Update the state of the Product to "Under Revision" retrievedPublishedProduct.StateCode = ProductState.UnderRevision; UpdateRequest updatePropertyState = new UpdateRequest { Target = retrievedPublishedProduct }; _serviceProxy.Execute(updatePropertyState); Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name); DynamicProperty newOverwriteProperty = new DynamicProperty(); newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productOverridenPropertyId); newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet myCols = new ColumnSet(); myCols.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId, myCols); // Update the attributes of the cloned property to complete the overwrite retrievedOverwrittenProperty.Name = "Overwritten Example Property"; retrievedOverwrittenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverwrittenProperty); Console.WriteLine("\nOverwritten the product property for 'Example Product 1'."); // Retrieve the StateCode of Product that you want to publish ColumnSet prodCols = new ColumnSet(); prodCols.AddColumns("name", "statecode"); Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, prodCols); // Update the state of the Product to "Active" retrievedRevisedProduct.StateCode = ProductState.Active; UpdateRequest publishProduct1 = new UpdateRequest { Target = retrievedRevisedProduct }; _serviceProxy.Execute(publishProduct1); Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name); } #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// 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 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) }; _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 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 = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); #endregion Create records to support Opportunity records }
/// <summary> /// Create and configure the organization service proxy. /// Initiate creating all entity records that this sample requires. /// Create a product family with a product property and two child product records. /// Create a substitute relation between the two products. /// Override the product property for one of the child products. /// Publish the product family hierarchy, including the child records. /// Revise a child product to overwrite the overridden property. /// Publish the child 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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetCreateandublishProducts1> // Create a product family Product newProductFamily = new Product { Name = "Example Product Family", ProductNumber = "PF001", ProductStructure = new OptionSetValue(2) }; _productFamilyId = _serviceProxy.Create(newProductFamily); Console.WriteLine("\nCreated '{0}'", newProductFamily.Name); // Create a product property DynamicProperty newProperty = new DynamicProperty { Name = "Example Property", RegardingObjectId = new EntityReference(Product.EntityLogicalName, _productFamilyId), IsReadOnly = true, IsRequired = true, IsHidden = false, DataType = new OptionSetValue(3), //Single line of text DefaultValueString = "Default Value" }; _productPropertyId = _serviceProxy.Create(newProperty); Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name); // Create couple of product records under the product family Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created '{0}' under the product family", newProduct2.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("\nCreated 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); // Set the product relationship // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional) ProductSubstitute newProductRelation = new ProductSubstitute { SalesRelationshipType = new OptionSetValue(3), Direction = new OptionSetValue(1), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), SubstitutedProductId = new EntityReference(Product.EntityLogicalName, _product2Id) }; _productRelationId = _serviceProxy.Create(newProductRelation); Console.WriteLine("\nCreated a substitute relation between the two products."); //</snippetCreateandublishProducts1> // Override a product property at the product level // In this case we will override the property for 'Example Product 1' DynamicProperty newOverrideProperty = new DynamicProperty(); newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productPropertyId); newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverridenPropertyId = _serviceProxy.Create(newOverrideProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet columns = new ColumnSet(); columns.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverridenPropertyId, columns); // Update the attributes retrievedOverridenProperty.Name = "Overridden Example Property"; retrievedOverridenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverridenProperty); Console.WriteLine("\nOverridden the product property for 'Example Product 1'."); // Prompt the user whether to publish the product family and products bool publishRecords = true; Console.WriteLine("\nDo you want the product records published? (y/n)"); String answer = Console.ReadLine(); publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); if (publishRecords) { PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest { Target = new EntityReference(Product.EntityLogicalName, _productFamilyId) }; PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq); if (published.Results != null) { Console.WriteLine("Published the product records"); } // Overwrite a product property Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite."); // Retrieve the StateCode of Product that you want to revise ColumnSet cols = new ColumnSet(); cols.AddColumns("name", "statecode"); Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, cols); // Update the state of the Product to "Under Revision" retrievedPublishedProduct.StateCode = ProductState.UnderRevision; UpdateRequest updatePropertyState = new UpdateRequest { Target = retrievedPublishedProduct }; _serviceProxy.Execute(updatePropertyState); Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name); DynamicProperty newOverwriteProperty = new DynamicProperty(); newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productOverridenPropertyId); newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet myCols = new ColumnSet(); myCols.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId, myCols); // Update the attributes of the cloned property to complete the overwrite retrievedOverwrittenProperty.Name = "Overwritten Example Property"; retrievedOverwrittenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverwrittenProperty); Console.WriteLine("\nOverwritten the product property for 'Example Product 1'."); // Retrieve the StateCode of Product that you want to publish ColumnSet prodCols = new ColumnSet(); prodCols.AddColumns("name", "statecode"); Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, prodCols); // Update the state of the Product to "Active" retrievedRevisedProduct.StateCode = ProductState.Active; UpdateRequest publishProduct1 = new UpdateRequest { Target = retrievedRevisedProduct }; _serviceProxy.Execute(publishProduct1); Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name); } DeleteRequiredRecords(promptForDelete); } } catch { // You can handle an exception here or pass it back to the calling method. throw; } }
public EntityReference CreateProduct(ExcelProxyProduct product, EntityReference priceName) { using (var orgContext = new OrganizationServiceContext(service)) { Product entityProduct = new Product() { Id = Guid.NewGuid(), ProductNumber = product.SKU, Name = product.Product, DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>() where i.Name == "Единица измерения по умолчанию" //where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturingname = findVendor(product.Vendor) }; try { /////////////////////////////////////// Guid idNewProduct = service.Create(entityProduct); var productPriceLevel = new ProductPriceLevel() { PriceLevelId = priceName /*(from i in orgContext.CreateQuery<PriceLevel>() where i.Name == "Default Sales USD" //Default Sales USD select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault()*/, UoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), ProductId = new EntityReference { Id = idNewProduct, LogicalName = Product.EntityLogicalName, Name = product.Product } }; var idProductPriceLevel = service.Create(productPriceLevel); var updateNewProduct = new Product() { Id = idNewProduct, PriceLevelId = priceName/*(from i in orgContext.CreateQuery<PriceLevel>() where i.Name == "Default Sales USD " select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault()*/ }; service.Update(updateNewProduct); return new EntityReference { Id = idNewProduct, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }; /////////////////////////////////////// } catch { return null; } } }
public EntityReference CreateProduct(ExcelProxyProduct product) { using (var orgContext = new OrganizationServiceContext(service)) { Product entityProduct = new Product() { Id = Guid.NewGuid(), ProductNumber = product.SKU, Name = product.Product, Price = new Money(Convert.ToDecimal(product.recomendetPriceUSD)), DefaultUoMScheduleId = (from i in orgContext.CreateQuery <UoMSchedule>() where i.Name == "Единица измерения по умолчанию" //where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery <UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturer = findVendor(product.Vendor) }; try { /////////////////////////////////////// Guid idNewProduct = service.Create(entityProduct); var productPriceLevel = new ProductPriceLevel() { PriceLevelId = (from i in orgContext.CreateQuery <PriceLevel>() where i.Name == "Default UAH Pricelist" //Default USD Pricelist select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault(), UoMId = (from i in orgContext.CreateQuery <UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), Amount = new Money(Convert.ToDecimal(product.recomendetPriceUSD)), ProductId = new EntityReference { Id = idNewProduct, LogicalName = Product.EntityLogicalName, Name = product.Product } }; var idProductPriceLevel = service.Create(productPriceLevel); var updateNewProduct = new Product() { Id = idNewProduct, PriceLevelId = (from i in orgContext.CreateQuery <PriceLevel>() where i.Name == "Default USD Pricelist" select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault() }; service.Update(updateNewProduct); return(new EntityReference { Id = idNewProduct, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }); /////////////////////////////////////// } catch { return(null); } } }