public void PriceLevelAddAsyncTestsUsingoAuth()
        {
            //Creating the PriceLevel for Add
            PriceLevel entity = QBOHelper.CreatePriceLevel(qboContextoAuth);

            PriceLevel added = Helper.AddAsync <PriceLevel>(qboContextoAuth, entity);

            QBOHelper.VerifyPriceLevel(entity, added);
        }
        public void PriceLevelDeleteAsyncTestsUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel entity = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, entity);

            Helper.DeleteAsync <PriceLevel>(qboContextoAuth, added);
        }
Exemplo n.º 3
0
        public void PriceLevelFindByIdAsyncTestsUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel entity = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, entity);

            //FindById and verify
            Helper.FindByIdAsync <PriceLevel>(qboContextoAuth, added);
        }
Exemplo n.º 4
0
        public void PriceLevelAddTestUsingoAuth()
        {
            //Creating the PriceLevel for Add
            PriceLevel priceLevel = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, priceLevel);

            //Verify the added PriceLevel
            QBOHelper.VerifyPriceLevel(priceLevel, added);
        }
Exemplo n.º 5
0
        public void PriceLevelFindbyIdTestUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel priceLevel = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, priceLevel);
            PriceLevel found = Helper.FindById <PriceLevel>(qboContextoAuth, added);

            QBOHelper.VerifyPriceLevel(found, added);
        }
        public void CreateFromJArray_Test()
        {
            var priceLevelTokens = JArray.Parse(@"[""5541.30000"",""2.50700000"",""1534614248.123678""]");
            var priceLevel       = PriceLevel.CreateFromJArray(priceLevelTokens);

            Assert.NotNull(priceLevel);
            Assert.Equal(5541.30000M, priceLevel.Price);
            Assert.Equal(2.50700000M, priceLevel.Volume);
            Assert.Equal(1534614248.123678M, priceLevel.Timestamp);
        }
Exemplo n.º 7
0
        public void PriceLevelUpdateTestUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel priceLevel = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, priceLevel);
            //Change the data of added entity
            PriceLevel changed = QBOHelper.UpdatePriceLevel(qboContextoAuth, added);
            //Update the returned entity data
            PriceLevel updated = Helper.Update <PriceLevel>(qboContextoAuth, changed);//Verify the updated PriceLevel

            QBOHelper.VerifyPriceLevel(changed, updated);
        }
        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);
        }
Exemplo n.º 9
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create entity records
            Console.WriteLine("Creating required records for the sample");
            Console.WriteLine("*****************************************");
            // 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);
            Console.WriteLine("*****************************************");

            return;
        }
Exemplo n.º 10
0
        public void PriceLevelUpdatedAsyncTestsUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel entity = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, entity);

            //Update the PriceLevel
            PriceLevel updated = QBOHelper.UpdatePriceLevel(qboContextoAuth, added);
            //Call the service
            PriceLevel updatedReturned = Helper.UpdateAsync <PriceLevel>(qboContextoAuth, updated);

            //Verify updated PriceLevel
            QBOHelper.VerifyPriceLevel(updated, updatedReturned);
        }
Exemplo n.º 11
0
        public void UpdatePriceLevel()
        {
            double currentPrice = 0;
            double baseValue    = 0;

            for (int i = 0; i < ListedItems.Count; i++)
            {
                baseValue    += ListedItems[i].Value.Value;
                currentPrice += ListedItems[i].Value.Price;
            }

            PriceLevel = currentPrice / baseValue * 100;
            Debug.WriteLine(PriceLevel.ToString());
            Ui.UpdateUI();
        }
Exemplo n.º 12
0
        public void SortedDictionarySortsDescendingPriceLevel()
        {
            PriceComparerDescendingZeroFirst     comparer         = new PriceComparerDescendingZeroFirst();
            SortedDictionary <Price, PriceLevel> sortedDictionary = new SortedDictionary <Price, PriceLevel>(comparer);
            Price      price1 = new Price(1);
            PriceLevel level1 = new PriceLevel(price1);

            sortedDictionary.Add(price1, level1);

            Price      price4 = new Price(4);
            PriceLevel level4 = new PriceLevel(price4);

            sortedDictionary.Add(price4, level4);

            Price      price3 = new Price(3);
            PriceLevel level3 = new PriceLevel(price3);

            sortedDictionary.Add(price3, level3);

            Price      price2 = new Price(2);
            PriceLevel level2 = new PriceLevel(price2);

            sortedDictionary.Add(price2, level2);

            Price      price0 = new Price(0);
            PriceLevel level0 = new PriceLevel(price0);

            sortedDictionary.Add(price0, level0);

            Price      price5 = new Price(5);
            PriceLevel level5 = new PriceLevel(price5);

            sortedDictionary.Add(price5, level5);

            List <PriceLevel> expectedPriceLevelSortOrder = new List <PriceLevel>()
            {
                level0, level5, level4, level3, level2, level1
            };

            AssertHelper.SequentiallyEqual(expectedPriceLevelSortOrder, sortedDictionary.Values.ToList());

            List <Price> expectedPriceSortOrder = new List <Price>()
            {
                price0, price5, price4, price3, price2, price1
            };

            AssertHelper.SequentiallyEqual(expectedPriceSortOrder, sortedDictionary.Keys.ToList());
        }
Exemplo n.º 13
0
        public void RemoveOrder_RemovesOrder()
        {
            PriceLevel priceLevel = new PriceLevel(100);
            Order      order1     = new Order()
            {
                IsBuy = true, OrderId = 1, Price = 100, Sequnce = 1
            };

            priceLevel.AddOrder(order1);

            Assert.Equal(1, priceLevel.OrderCount);

            Order order2 = new Order()
            {
                IsBuy = true, OrderId = 2, Price = 100, Sequnce = 2
            };

            priceLevel.AddOrder(order2);

            Assert.Equal(2, priceLevel.OrderCount);

            Order order3 = new Order()
            {
                IsBuy = true, OrderId = 3, Price = 100, Sequnce = 3
            };

            priceLevel.AddOrder(order3);

            Assert.Equal(3, priceLevel.OrderCount);

            Order order4 = new Order()
            {
                IsBuy = true, OrderId = 4, Price = 100, Sequnce = 4
            };

            priceLevel.AddOrder(order4);

            Assert.Equal(4, priceLevel.OrderCount);

            priceLevel.RemoveOrder(order3);

            Assert.Equal(3, priceLevel.OrderCount);
            Assert.Contains(order1, priceLevel);
            Assert.Contains(order2, priceLevel);
            Assert.Contains(order4, priceLevel);
        }
Exemplo n.º 14
0
        public void PriceLevelVoidTestUsingoAuth()
        {
            //Creating the entity for Adding
            PriceLevel entity = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the entity
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, entity);

            //Void the returned entity
            try
            {
                PriceLevel voided = Helper.Void <PriceLevel>(qboContextoAuth, added);
                Assert.AreEqual(EntityStatusEnum.Voided, voided.status);
            }
            catch (IdsException ex)
            {
                Assert.Fail();
            }
        }
Exemplo n.º 15
0
        public void PriceLevelDeleteTestUsingoAuth()
        {
            //Creating the PriceLevel for Adding
            PriceLevel priceLevel = QBOHelper.CreatePriceLevel(qboContextoAuth);
            //Adding the PriceLevel
            PriceLevel added = Helper.Add <PriceLevel>(qboContextoAuth, priceLevel);

            //Delete the returned entity
            try
            {
                PriceLevel deleted = Helper.Delete <PriceLevel>(qboContextoAuth, added);
                Assert.AreEqual(EntityStatusEnum.Deleted, deleted.status);
            }
            catch (IdsException ex)
            {
                Assert.Fail();
            }
        }
        protected override OpResult _Store(PriceLevel _obj)
        {
            if (_obj == null)
            {
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "PriceLevel object cannot be created as it is null"));
            }

            if (Exists(_obj))
            {
                ExecuteNonQuery(GetQuery_UpdateQuery(_obj));
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj));
            }

            ExecuteNonQuery(GetQuery_InsertQuery(_obj));
            _obj.FromDb = true;

            return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Combines the input price levels data based on provided width
        /// </summary>
        /// <param name="data">The input data</param>
        /// <param name="width">Width in term of price not Pips</param>
        /// <param name="symbol">The symbol of price levels</param>
        /// <returns>List<PriceLevel></returns>
        public static List <PriceLevel> GetCombinedLevels(List <PriceLevel> data, double width)
        {
            var ordered = data.OrderBy(priceLevel => priceLevel.Level).ToList();

            var dataCombined = new List <PriceLevel>();

            var currentLevel = new PriceLevel
            {
                Level   = ordered.First().Level,
                Profile = new List <int>()
            };

            ordered.ForEach(priceLevel =>
            {
                if (priceLevel.Level >= currentLevel.Level && priceLevel.Level <= currentLevel.Level + width)
                {
                    // Market profile
                    if (priceLevel.Profile != null)
                    {
                        currentLevel.Profile.AddRange(priceLevel.Profile);
                    }

                    // Volume profile
                    currentLevel.BearishVolume += priceLevel.BearishVolume;
                    currentLevel.BullishVolume += priceLevel.BullishVolume;
                }
                else
                {
                    currentLevel = new PriceLevel
                    {
                        Level   = priceLevel.Level,
                        Profile = new List <int>()
                    };
                }

                if (!dataCombined.Contains(currentLevel))
                {
                    dataCombined.Add(currentLevel);
                }
            });

            return(dataCombined);
        }
        private void MergeUpdates(InventoryItem sourceItem, PriceLevel sourceContractor, PriceLevel sourceElectrician)
        {
            // Merge the inventory item
            var target = Inventory.Items.First(item => item.ListId.Equals(sourceItem.ListId));

            target.EditSequence = sourceItem.EditSequence;
            target.Cost = sourceItem.Cost;
            target.BasePrice = sourceItem.BasePrice;
            target.ContractorPrice = sourceItem.ContractorPrice;
            target.ElectricianPrice = sourceItem.ElectricianPrice;

            // Merge contractor price level
            var targetContractor = PriceLevels.Items.First(level => level.ListId.Equals(sourceContractor.ListId));
            targetContractor.EditSequence = sourceContractor.EditSequence;

            // Merge electrician price level
            var targetElectrician = PriceLevels.Items.First(level => level.ListId.Equals(sourceElectrician.ListId));
            targetElectrician.EditSequence = sourceElectrician.EditSequence;
        }
Exemplo n.º 19
0
        public void PriceLevelBatchUsingoAuth()
        {
            Dictionary <OperationEnum, object> batchEntries = new Dictionary <OperationEnum, object>();

            PriceLevel existing = Helper.FindOrAdd(qboContextoAuth, new PriceLevel());

            batchEntries.Add(OperationEnum.create, QBOHelper.CreatePriceLevel(qboContextoAuth));

            batchEntries.Add(OperationEnum.update, QBOHelper.UpdatePriceLevel(qboContextoAuth, existing));

            batchEntries.Add(OperationEnum.query, "select * from PriceLevel");

            batchEntries.Add(OperationEnum.delete, existing);

            ReadOnlyCollection <IntuitBatchResponse> batchResponses = Helper.BatchTest <PriceLevel>(qboContextoAuth, batchEntries);

            int position = 0;

            foreach (IntuitBatchResponse resp in batchResponses)
            {
                if (resp.ResponseType == ResponseType.Exception)
                {
                    Assert.Fail(resp.Exception.ToString());
                }

                if (resp.ResponseType == ResponseType.Entity)
                {
                    Assert.IsFalse(string.IsNullOrEmpty((resp.Entity as PriceLevel).Id));
                }
                else if (resp.ResponseType == ResponseType.Query)
                {
                    Assert.IsTrue(resp.Entities != null && resp.Entities.Count > 0);
                }
                else if (resp.ResponseType == ResponseType.CdcQuery)
                {
                    Assert.IsTrue(resp.CDCResponse != null && resp.CDCResponse.entities != null && resp.CDCResponse.entities.Count > 0);
                }

                position++;
            }
        }
Exemplo n.º 20
0
        public EntityReference CreatePriceList(string priceListName, EntityReference currencyId)
        {
            this.services.T.Trace("CreatePriceList...");

            Throwers.IfNullOrEmptyArgument(priceListName, "priceListName");
            Throwers.IfNullArgument(currencyId, "currencyId");
            Throwers.IfReferenceTypeIsWrong(currencyId, TransactionCurrency.EntityLogicalName);

            var newPriceLevel =
                new PriceLevel
            {
                Name = priceListName,
                TransactionCurrencyId = currencyId
            };

            var id = this.services.Service.Create(newPriceLevel);

            this.services.T.Trace("CreatePriceList!");

            return(new EntityReference(PriceLevel.EntityLogicalName, id));
        }
Exemplo n.º 21
0
        public void AddOrder_AddsOrder()
        {
            PriceLevel priceLevel = new PriceLevel(100);
            Order      order1     = new Order()
            {
                IsBuy = true, OrderId = 1, Price = 100, Sequnce = 1
            };

            priceLevel.AddOrder(order1);

            Assert.Equal(1, priceLevel.OrderCount);

            Order order2 = new Order()
            {
                IsBuy = true, OrderId = 2, Price = 100, Sequnce = 2
            };

            priceLevel.AddOrder(order2);

            Assert.Equal(2, priceLevel.OrderCount);
            Assert.Contains(order1, priceLevel);
            Assert.Contains(order2, priceLevel);
        }
Exemplo n.º 22
0
        protected void rdoPriceLevelAll_CheckedChanged(Object sender, EventArgs e)
        {
            HtmlInputCheckBox chkList          = null;
            RadioButton       rdoPriceLevelAll = (RadioButton)sender;
            RadioButton       rdoPrice         = null;
            Int64             iContactID       = 0;

            Contacts   clsContacts    = new Contacts();
            PriceLevel enumPriceLevel = PriceLevel.SRP;

            foreach (DataListItem item in lstItem.Items)
            {
                chkList = (HtmlInputCheckBox)item.FindControl("chkList");

                iContactID = Int64.Parse(chkList.Value);

                switch (rdoPriceLevelAll.ID)
                {
                case "rdoPriceAll": enumPriceLevel = PriceLevel.SRP; rdoPrice = (RadioButton)item.FindControl("rdoPrice"); break;

                case "rdoWSPriceAll": enumPriceLevel = PriceLevel.WSPrice; rdoPrice = (RadioButton)item.FindControl("rdoWSPrice"); break;

                case "rdoLevel1All": enumPriceLevel = PriceLevel.One; rdoPrice = (RadioButton)item.FindControl("rdoLevel1"); break;

                case "rdoLevel2All": enumPriceLevel = PriceLevel.Two; rdoPrice = (RadioButton)item.FindControl("rdoLevel2"); break;

                case "rdoLevel3All": enumPriceLevel = PriceLevel.Three; rdoPrice = (RadioButton)item.FindControl("rdoLevel3"); break;

                case "rdoLevel4All": enumPriceLevel = PriceLevel.Four; rdoPrice = (RadioButton)item.FindControl("rdoLevel4"); break;

                case "rdoLevel5All": enumPriceLevel = PriceLevel.Five; rdoPrice = (RadioButton)item.FindControl("rdoLevel5"); break;
                }
                clsContacts.UpdatePriceLevel(iContactID, enumPriceLevel);
                rdoPrice.Checked = rdoPriceLevelAll.Checked;
            }
            clsContacts.CommitAndDispose();
        }
 private DbUpdateStatement GetQuery_UpdateQuery(PriceLevel _obj)
 {
     return(DbMgr.CreateUpdateClause("PriceLevels", GetFields(_obj), "PriceLevelID", _obj.PriceLevelID));
 }
        /// <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>
        /// 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;
        }
        private DbInsertStatement GetQuery_InsertQuery(PriceLevel _obj)
        {
            Dictionary <string, DbFieldEntry> fields = GetFields(_obj);

            return(DbMgr.CreateInsertClause("PriceLevels", fields));
        }
Exemplo n.º 27
0
        /// <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
        }
Exemplo n.º 28
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name        = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

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

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

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

            _defaultUnitId = unit.UoMId.Value;

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

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

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

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

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

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

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

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

            _discountId = _serviceProxy.Create(newDiscount);

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

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

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

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

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

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

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

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

            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State         = new OptionSetValue((int)ProductState.Active),
                Status        = new OptionSetValue(1)
            };

            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");

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

            _accountId = _serviceProxy.Create(newAccount);

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

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

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

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

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

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

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

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

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

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

            #endregion

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

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

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

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


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

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

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

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

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

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

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

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

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

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

            #endregion Create records to support Opportunity records

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

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

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

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

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

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

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

            #endregion Create Opportunity records
        }
Exemplo n.º 30
0
        public void UpdatePriceLevel(Int64 ContactID, PriceLevel PriceLevel)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandType = System.Data.CommandType.Text;

                string SQL = "UPDATE tblContacts SET " +
                                "PriceLevel		=	@PriceLevel " +
                            "WHERE ContactID	=	@ContactID ";

                cmd.Parameters.AddWithValue("PriceLevel", PriceLevel.ToString("d"));
                cmd.Parameters.AddWithValue("ContactID", ContactID);

                cmd.CommandText = SQL;
                base.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                throw base.ThrowException(ex);
            }
        }
		/// <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));
		}
Exemplo n.º 32
0
        /// <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

        }
Exemplo n.º 33
0
        /// <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;
            }
        }
Exemplo n.º 34
0
        /// <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;
        }
Exemplo n.º 35
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

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

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

            _defaultUnitId = unit.UoMId.Value;

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

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

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

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

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

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

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

            _discountId = _serviceProxy.Create(newDiscount);

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

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

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

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

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

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

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

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

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");

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

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

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

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

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

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

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

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

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

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

        }
Exemplo n.º 37
0
        /// <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
        }
Exemplo n.º 38
0
        /// <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);

            return;
        }
        public void PriceLevelSortsOrderBasedOnSequence()
        {
            OrderSequenceComparer comparer = new OrderSequenceComparer();
            Price      price      = new Price(1);
            PriceLevel priceLevel = new PriceLevel(price);

            Order order1 = new Order()
            {
                Sequnce = 1
            };

            priceLevel.AddOrder(order1);

            Order order3 = new Order()
            {
                Sequnce = 3
            };

            priceLevel.AddOrder(order3);

            Order order2 = new Order()
            {
                Sequnce = 2
            };

            priceLevel.AddOrder(order2);

            Order order7 = new Order()
            {
                Sequnce = 7
            };

            priceLevel.AddOrder(order7);

            Order order6 = new Order()
            {
                Sequnce = 6
            };

            priceLevel.AddOrder(order6);

            Order order4 = new Order()
            {
                Sequnce = 4
            };

            priceLevel.AddOrder(order4);

            Order order5 = new Order()
            {
                Sequnce = 5
            };

            priceLevel.AddOrder(order5);

            List <Order> expectedSequence = new List <Order> {
                order1, order2, order3, order4, order5, order6, order7
            };

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

            _unitGroupId = _serviceProxy.Create(newUnitGroup);

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

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

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

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

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

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

            Product newProduct2 = new Product
            {
                ProductNumber = "2",
                Name = "Example Product 2",
                ProductStructure = new OptionSetValue(1),
                QuantityDecimal = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, unit.Id)
            };
            _product2Id = _serviceProxy.Create(newProduct2);

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

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

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

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

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

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

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

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

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");


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

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

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

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

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

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

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

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

            // Create a write-in product with a manual discount
            OpportunityProduct newWriteInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId),
                // set this attribute to make it a write-in product
                IsProductOverridden = true,
                ProductDescription = "Example Write-in Product",
                PricePerUnit = new Money(20.00m),
                Quantity = 5,
                ManualDiscountAmount = new Money(10.50m),
                Tax = new Money(7.16m)
            };
            _writeInProductId = _serviceProxy.Create(newWriteInProduct);

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

            return;
        }