Пример #1
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create source queue and destination queue.
        /// Create a letter  entity.
        /// Add letter  entity to source queue.
        /// </summary>
        public void CreateRequiredRecords()
        {
            var QueueViewType = new
            {
                Public  = 0,
                Private = 1
            };
            //Create new queues and store their returned GUIDs in variables for later use.
            Queue sourceQueue = new Queue
            {
                Name          = "Source Queue",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue(QueueViewType.Private)
            };

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

            Queue destinationQueue = new Queue
            {
                Name          = "Destination Queue",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue(QueueViewType.Private)
            };

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


            // Create a letter  entity.
            Letter newLetter = new Letter
            {
                Description = "Example Letter"
            };

            _letterId = _serviceProxy.Create(newLetter);
            Console.WriteLine("Created {0}", newLetter.Description);

            // Use AddToQueue message to add an  entity into a queue, which will associate
            // the letter with the first queue.
            AddToQueueRequest addToSourceQueue = new AddToQueueRequest
            {
                DestinationQueueId = _sourceQueueId,
                Target             = new EntityReference(Letter.EntityLogicalName, _letterId)
            };

            _serviceProxy.Execute(addToSourceQueue);
            Console.WriteLine("Added letter record to {0}", sourceQueue.Name);

            // Retrieve/create a user record for assigning the queue item to the user's
            // queue.
            _userId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);

            return;
        }
Пример #2
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Get the current user's information.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

            _currentUserId = userResponse.UserId;

            // Create another user, Kevin Cook.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);
        }
Пример #3
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a second user that we will reference in our sample code.
            Guid userId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);

            // Modify email address of user for sample.
            SystemUser systemUser = new SystemUser
            {
                Id = userId,
                InternalEMailAddress = "*****@*****.**"
            };

            _service.Update(systemUser);
        }
        /// <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 PhoneCall record and supporting account

            Account account = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountId = (_serviceProxy.Create(account));
            account.Id = _accountId;

            // Create Guids for PhoneCalls
            _phoneCallId  = Guid.NewGuid();
            _phoneCall2Id = Guid.NewGuid();

            // Create ActivityPartys for the phone calls' "From" field.
            ActivityParty activityParty = new ActivityParty()
            {
                PartyId    = account.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCallId,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9),
            };

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId    = account.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCall2Id,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            // Create an open phone call.
            PhoneCall phoneCall = new PhoneCall()
            {
                Id            = _phoneCallId,
                Subject       = "Sample Phone Call",
                DirectionCode = false,
                To            = new ActivityParty[] { activityParty },
                OwnerId       = new EntityReference("systemuser", _salesRepresentativeIds[0]),
                ActualEnd     = DateTime.Now
            };
            _serviceProxy.Create(phoneCall);

            // Close the first phone call.
            SetStateRequest closePhoneCall = new SetStateRequest()
            {
                EntityMoniker = phoneCall.ToEntityReference(),
                State         = new OptionSetValue(1),
                Status        = new OptionSetValue(4)
            };
            _serviceProxy.Execute(closePhoneCall);

            // Create a second phone call.
            phoneCall = new PhoneCall()
            {
                Id            = _phoneCall2Id,
                Subject       = "Sample Phone Call 2",
                DirectionCode = true,
                To            = new ActivityParty[] { activityParty },
                OwnerId       = new EntityReference("systemuser", _salesRepresentativeIds[1]),
                ActualEnd     = DateTime.Now
            };
            _serviceProxy.Create(phoneCall);

            // Close the second phone call.
            closePhoneCall = new SetStateRequest()
            {
                EntityMoniker = phoneCall.ToEntityReference(),
                State         = new OptionSetValue(1),
                Status        = new OptionSetValue(4)
            };
            _serviceProxy.Execute(closePhoneCall);

            #endregion
        }
Пример #5
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
        }
Пример #6
0
 /// <summary>
 /// Creates any entity records that this sample requires.
 /// </summary>
 public void CreateRequiredRecords()
 {
     // Create a second user that we will impersonate in our sample code.
     SystemUserProvider.RetrieveSalesManager(_serviceProxy);
 }
        /// <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
        }
Пример #8
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the dashboard.
        /// </summary>
        public void CreateRequiredRecords()
        {
            //Grab the default public view for opportunities.
            QueryExpression mySavedQuery = new QueryExpression
            {
                ColumnSet  = new ColumnSet("savedqueryid"),
                EntityName = SavedQuery.EntityLogicalName,
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "isdefault",
                            Operator      = ConditionOperator.Equal,
                            Values        = { true   }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "querytype",
                            Operator      = ConditionOperator.Equal,
                            Values        = {      0 }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "returnedtypecode",
                            Operator      = ConditionOperator.Equal,
                            Values        = { Opportunity.EntityTypeCode }
                        }
                    }
                }
            };

            //This query should return one and only one result.
            SavedQuery defaultOpportunityQuery = _serviceProxy.RetrieveMultiple(mySavedQuery)
                                                 .Entities.Select(x => (SavedQuery)x).FirstOrDefault();

            // Retrieve visualizations out of the system.
            // This sample assumes that you have the "Top Opportunities"
            // visualization that is installed with Microsoft Dynamics CRM.
            QueryByAttribute visualizationQuery = new QueryByAttribute
            {
                EntityName = SavedQueryVisualization.EntityLogicalName,
                ColumnSet  = new ColumnSet("savedqueryvisualizationid"),
                Attributes = { "name" },
                //If you do not have this visualization, you will need to change
                //this line.
                Values = { "Top Opportunities" }
            };


            SavedQueryVisualization visualization = _serviceProxy.RetrieveMultiple(visualizationQuery).
                                                    Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault();

            //This is the language code for U.S. English. If you are running this code
            //in a different locale, you will need to modify this value.
            int languageCode = 1033;

            //We set up our dashboard and specify the FormXml. Refer to the
            //FormXml schema in the Microsoft Dynamics CRM SDK for more information.
            UserForm dashboard = new UserForm
            {
                Name        = "Sample User Dashboard",
                Description = "Sample user-owned dashboard.",
                FormXml     = String.Format(@"<form>
                                <tabs>
                                    <tab name='Test Dashboard' verticallayout='true'>
                                        <labels>
                                            <label description='Sample User Dashboard' languagecode='{0}' />
                                        </labels>
                                        <columns>
                                            <column width='100%'>
                                                <sections>
                                                    <section name='Information Section'
                                                        showlabel='false' showbar='false'
                                                        columns='111'>
                                                        <labels>
                                                            <label description='Information Section'
                                                                languagecode='{0}' />
                                                        </labels>
                                                        <rows>
                                                            <row>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 1'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='Top10Opportunities'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Chart</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 2'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='Top10Opportunities2'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Grid</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                            </row>
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                        </rows>
                                                    </section>
                                                </sections>
                                            </column>
                                        </columns>
                                    </tab>
                                </tabs>
                            </form>",
                                            languageCode,
                                            defaultOpportunityQuery.SavedQueryId.Value.ToString("B"),
                                            visualization.SavedQueryVisualizationId.Value.ToString("B"))
            };

            _userDashboardId = _serviceProxy.Create(dashboard);

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

            // Create another user to whom the dashboard will be assigned.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);
        }
Пример #9
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the visualization.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a sample account
            Account setupAccount = new Account {
                Name = "Sample Account"
            };

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

            // Create some oppotunity records for the visualization
            Opportunity[] setupOpportunities = new Opportunity[]
            {
                new Opportunity
                {
                    Name           = "Sample Opp 01",
                    EstimatedValue = new Money(120000.00m),
                    ActualValue    = new Money(100000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 02",
                    EstimatedValue = new Money(240000.00m),
                    ActualValue    = new Money(200000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 03",
                    EstimatedValue = new Money(360000.00m),
                    ActualValue    = new Money(300000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 04",
                    EstimatedValue = new Money(500000.00m),
                    ActualValue    = new Money(500000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 05",
                    EstimatedValue = new Money(110000.00m),
                    ActualValue    = new Money(60000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 06",
                    EstimatedValue = new Money(90000.00m),
                    ActualValue    = new Money(70000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 07",
                    EstimatedValue = new Money(620000.00m),
                    ActualValue    = new Money(480000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 08",
                    EstimatedValue = new Money(440000.00m),
                    ActualValue    = new Money(400000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 09",
                    EstimatedValue = new Money(410000.00m),
                    ActualValue    = new Money(400000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                },
                new Opportunity
                {
                    Name           = "Sample Opp 10",
                    EstimatedValue = new Money(650000.00m),
                    ActualValue    = new Money(650000.00m),
                    CustomerId     = new EntityReference(Account.EntityLogicalName,
                                                         _accountId),
                    StepName = "Open"
                }
            };

            _opportunitiyIds = (from opp in setupOpportunities
                                select _serviceProxy.Create(opp)).ToArray();

            Console.WriteLine("Created few opportunity records for {0}.", setupAccount.Name);

            // Create a visualization

            // Set The presentation XML string.
            string presentationXml = @"
                    <Chart Palette='BrightPastel'>
                        <Series>
                            <Series _Template_='All' ShadowOffset='2' 
                                BorderColor='64, 64, 64' BorderDashStyle='Solid'
                                BorderWidth='1' IsValueShownAsLabel='true' 
                                Font='Tahoma, 6.75pt, GdiCharSet=0' 
                                LabelForeColor='100, 100, 100'
                                CustomProperties='FunnelLabelStyle=Outside' 
                                ChartType='Funnel'>
                                <SmartLabelStyle Enabled='True' />
                                <Points />
                            </Series>
                         </Series>
                        <ChartAreas>
                            <ChartArea _Template_='All' BackColor='Transparent'
                                BorderColor='Transparent' 
                                BorderDashStyle='Solid'>
                                <Area3DStyle Enable3D='True' 
                                    IsClustered='True'/>
                            </ChartArea>
                        </ChartAreas>
                        <Legends>
                            <Legend _Template_='All' Alignment='Center' 
                                LegendStyle='Table' Docking='Bottom' 
                                IsEquallySpacedItems='True' BackColor='White'
                                BorderColor='228, 228, 228' BorderWidth='0' 
                                Font='Tahoma, 8pt, GdiCharSet=0' 
                                ShadowColor='0, 0, 0, 0' 
                                ForeColor='100, 100, 100'>
                            </Legend>
                        </Legends>
                        <Titles>
                            <Title _Template_='All'
                                Font='Tahoma, 9pt, style=Bold, GdiCharSet=0'
                                ForeColor='102, 102, 102'>
                            </Title>
                        </Titles>
                        <BorderSkin PageColor='Control'
                            BackColor='CornflowerBlue'
                            BackSecondaryColor='CornflowerBlue' />
                    </Chart>
                    ";

            // Set the data XML string.
            string dataXml = @"
                    <datadefinition>
                        <fetchcollection>
                            <fetch mapping='logical' count='10' 
                                aggregate='true'>
                                <entity name='opportunity'>
                                    <attribute name='actualvalue_base' 
                                        aggregate='sum' 
                                        alias='sum_actualvalue_base' />
                                    <attribute name='stepname' groupby='true' 
                                        alias='stepname' />
                                    <order alias='stepname' descending='false'/>
                                </entity>
                            </fetch>
                        </fetchcollection>
                        <categorycollection>
                            <category>
                                <measurecollection>
                                    <measure alias='sum_actualvalue_base'/>
                                </measurecollection>
                            </category>
                        </categorycollection>
                    </datadefinition>
                    ";

            // Create the visualization entity instance.
            UserQueryVisualization newUserOwnedVisualization = new UserQueryVisualization
            {
                Name                    = "Sample User Visualization",
                Description             = "Sample user-owned visualization.",
                PresentationDescription = presentationXml,
                DataDescription         = dataXml,
                PrimaryEntityTypeCode   = Opportunity.EntityLogicalName,
            };

            _userOwnedVisualizationId = _serviceProxy.Create(newUserOwnedVisualization);

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

            // Create another user to whom the visualization will be assigned.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);
        }
Пример #10
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 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
        }