/// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Get the user from the Helper.
            _userId = SystemUserProvider.RetrieveMarketingManager(service);
            Console.Write("User retrieved, ");
            //_userId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).OrganizationId;
            //Console.Write("User retrieved, ");

            // Retrieve the security role needed to assign to the user.
            QueryExpression roleQuery = new QueryExpression
            {
                EntityName = Role.EntityLogicalName,
                ColumnSet  = new ColumnSet("roleid"),
                Criteria   =
                {
                    Conditions =
                    {
                        new ConditionExpression("name", ConditionOperator.Equal,
                                                "Marketing Manager")
                    }
                }
            };

            Role role = (Role)service.RetrieveMultiple(roleQuery).Entities[0];

            _roleId = role.Id;

            // Retrieve the default business unit needed to create the team.
            QueryExpression queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   =
                {
                    Conditions =
                    {
                        new ConditionExpression("parentbusinessunitid", ConditionOperator.Null)
                    }
                }
            };

            // Execute the query.
            BusinessUnit defaultBusinessUnit = (BusinessUnit)service.RetrieveMultiple(
                queryDefaultBusinessUnit).Entities[0];

            // Instantiate a team entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine
            // which attributes must be set for each entity.
            Team setupTeam = new Team
            {
                Name           = "CDS Management Team",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                                                     defaultBusinessUnit.Id)
            };

            // Create a team record.
            _teamId = service.Create(setupTeam);
            Console.Write("Created Team, ");
        }
        /// <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 static void CreateRequiredRecords(CrmServiceClient service)
        {
            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 = service.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 = service.Create(destinationQueue);
            Console.WriteLine("Created {0}", destinationQueue.Name);


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

            _letterId = service.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)
            };

            service.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(service);



            return;
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Get the current user's information.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

            _currentUserId = userResponse.UserId;

            // Create another user, Kevin Cook.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(service);
        }
示例#4
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // For this sample, all required entities are created in the Run() method.
            // Create/Retrieve a user.
            _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(service);

            if (_userId != Guid.Empty)
            {
                Console.WriteLine("{0} user retrieved.", _userId);
            }
        }
示例#5
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Retrieve a sales manager.
            _salesManagerId = SystemUserProvider.RetrieveMarketingManager(service);

            // Create an account.
            var account = new Account()
            {
                Name          = "Fourth Coffee",
                Address1_City = "Seattle"
            };

            _accountId = service.Create(account);
            Console.WriteLine("Required records have been created.");
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Set ldappath and domain values only for an on-premise or IFD environment.
            string ldappath = String.Empty;
            string domain   = String.Empty;

            // TODO Provide a username plus first and last names for an existing system user to disable.
            // You will be given the option, before the program terminates, to enable the account again.
            _userId = SystemUserProvider.RetrieveSystemUser("*****@*****.**", "Firstname",
                                                            "Lastname", domain, service, ref ldappath);

            if (_userId.Equals(Guid.Empty))
            {
                throw new Exception("CreateRequiredRecords(): The specified system user could not be retrieved.");
            }
        }
示例#7
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create/retrieve a user and associate a role.

            _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(service);
            // Find the role.
            var query = new QueryExpression
            {
                EntityName = Role.EntityLogicalName,
                ColumnSet  = new ColumnSet("roleid"),
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "name",
                            Operator      = ConditionOperator.Equal,
                            Values        = { _givenRole }
                        }
                    }
                }
            };

            // Get the role.
            EntityCollection roles = service.RetrieveMultiple(query);

            if (roles.Entities.Count > 0)
            {
                Role salesRole = service.RetrieveMultiple(query).Entities[0].ToEntity <Role>();

                // Associate the user with the role for this sample.
                if (salesRole != null && _userId != Guid.Empty)
                {
                    service.Associate(
                        "systemuser",
                        _userId,
                        new Relationship("systemuserroles_association"),
                        new EntityReferenceCollection()
                    {
                        new EntityReference(Role.EntityLogicalName, salesRole.Id)
                    });
                }
            }
        }
示例#8
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
            #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: _serviceProxy, ldapPath: 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
            Console.WriteLine("Required records have been created.");
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            //Grab the default public view for opportunities.
            var 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 = service.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 = service.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 = service.Create(dashboard);

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

            // Create another user to whom the dashboard will be assigned.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(service);

            Console.WriteLine("Required records have been created.");
        }
示例#10
0
 /// <summary>
 /// This method creates any entity records that this sample requires.
 /// Creates the email activity.
 /// </summary>
 public static void CreateRequiredRecords(CrmServiceClient service)
 {
     // Create a second user that we will impersonate in our sample code.
     SystemUserProvider.RetrieveSalesManager(service);
     Console.WriteLine("Required records have been created.");
 }
        /// <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 a sales manager.
            _salesManagerId =
                SystemUserProvider.RetrieveMarketingManager(service);

            #endregion

            #region Create PhoneCall record and supporting account

            Account newAccount = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountId    = (service.Create(newAccount));
            newAccount.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    = newAccount.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCallId,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId    = newAccount.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 }
            };
            service.Create(phoneCall);

            // Create a second phone call to close
            phoneCall = new PhoneCall()
            {
                Id            = _phoneCall2Id,
                Subject       = "Sample Phone Call 2",
                DirectionCode = false,
                To            = new ActivityParty[] { activityParty },
                ActualEnd     = DateTime.Now
            };
            service.Create(phoneCall);

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

            #endregion
        }
        /// <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);
            _salesRepresentativeId =
                SystemUserProvider.RetrieveSalespersons(service, 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 = 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 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    = service.Create(newProduct);
            newProduct.Id = _productId;
            Console.WriteLine("Created {0}", newProduct.Name);

            // 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 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 = service.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)
            };
            service.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    = service.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 = service.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 = service.Create(orderDetail);

            #endregion Create SalesOrder record
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Retrieve the sales people that will be added to the team.
                    salesPersons = SystemUserProvider.RetrieveSalespersons(service, ref ldapPath);

                    // Get the ID's of the current user and business unit.
                    var who         = new WhoAmIRequest();
                    var whoResponse = (WhoAmIResponse)service.Execute(who);
                    _currentUserId = whoResponse.UserId;
                    businessUnitId = whoResponse.BusinessUnitId;

                    // Create a access team.
                    var team = new Team
                    {
                        AdministratorId = new EntityReference(
                            "systemuser", _currentUserId),
                        Name           = "UserAccess Test Team",
                        BusinessUnitId = new EntityReference(
                            "businessunit", businessUnitId),
                        TeamType = new OptionSetValue((int)TeamTeamType.Access),
                    };

                    _teamId = service.Create(team);
                    Console.WriteLine("Created an access team named '{0}'.", team.Name);

                    // Add two sales people to the access team.
                    var addToTeamRequest = new AddMembersTeamRequest
                    {
                        TeamId    = _teamId,
                        MemberIds = new[] { salesPersons[0], salesPersons[1] }
                    };
                    service.Execute(addToTeamRequest);
                    Console.WriteLine("Added two sales people to the team.");

                    // Grant the team read/write access to an account.
                    var accountReference   = new EntityReference(Account.EntityLogicalName, _accountId);
                    var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal  = teamReference
                        },
                        Target = accountReference
                    };
                    service.Execute(grantAccessRequest);
                    Console.WriteLine("Granted read/write access on the account record to the team.");

                    // Retrieve and display access information for the account.
                    RetrieveAndDisplayEntityAccess(service, accountReference);

                    // Display the account access for the team and its members.
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, currentUserReference,
                                                      "Current User");
                    var firstSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[0]);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, firstSalesPersonReference,
                                                      "Sales Person");
                    var secondSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[1]);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, secondSalesPersonReference,
                                                      "Sales Person");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
示例#14
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a unique identifier for this sample for preventing name conflicts.
            var sampleIdentifier = Guid.NewGuid();

            // Retrieve/create the system users to use for the sample.
            var ldapPath = String.Empty;

            _systemUserIds = SystemUserProvider.RetrieveDelegates(
                service, ref ldapPath);

            // Retrieve the root business unit to use for creating the team for the
            // sample.
            var businessUnitQuery = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression()
            };

            businessUnitQuery.Criteria.AddCondition("parentbusinessunitid",
                                                    ConditionOperator.Null);
            var businessUnitResult = service.RetrieveMultiple(businessUnitQuery);
            var businessUnit       = businessUnitResult.Entities[0].ToEntity <BusinessUnit>();

            // Get the GUID of the current user.
            var who         = new WhoAmIRequest();
            var whoResponse = (WhoAmIResponse)service.Execute(who);

            _currentUserId = whoResponse.UserId;

            // Create a team for use in the sample.
            var team = new Team
            {
                AdministratorId = new EntityReference(
                    "systemuser", _currentUserId),
                Name           = String.Format("User Access Sample Team {0}", sampleIdentifier),
                BusinessUnitId = businessUnit.ToEntityReference()
            };

            _teamId = service.Create(team);

            // Add the second user to the newly created team.
            var addToTeamRequest = new AddMembersTeamRequest
            {
                TeamId    = _teamId,
                MemberIds = new[] { _systemUserIds[1] }
            };

            service.Execute(addToTeamRequest);

            // Create a account for use in the sample.
            var account = new Account
            {
                Name = "User Access Sample Company",
            };

            _accountId = service.Create(account);

            // Create a task to associate to the account.
            var accountReference = new EntityReference(Account.EntityLogicalName, _accountId);
            var task             = new Task
            {
                Subject           = "User Access Sample Task",
                RegardingObjectId = accountReference
            };

            _taskId = service.Create(task);

            // Create a letter to associate to the account.
            var letter = new Letter
            {
                Subject           = "User Access Sample Letter",
                RegardingObjectId = accountReference
            };

            service.Create(letter);
        }
        /// <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
        }
示例#16
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
            #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
            Console.WriteLine("Required records have been created.");
        }
示例#17
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the visualization.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a sample account
            Account setupAccount = new Account {
                Name = "Sample Account"
            };

            _accountId = service.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 service.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.
            var newUserOwnedVisualization = new UserQueryVisualization
            {
                Name                    = "Sample User Visualization",
                Description             = "Sample user-owned visualization.",
                PresentationDescription = presentationXml,
                DataDescription         = dataXml,
                PrimaryEntityTypeCode   = Opportunity.EntityLogicalName,
            };

            _userOwnedVisualizationId = service.Create(newUserOwnedVisualization);

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

            // Create another user to whom the visualization will be assigned.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(service);
        }