/// <summary>
 /// Create some account records to retrieve duplicates
 /// </summary>
 private void CreateAccountRecords()
 {
     var crmAccount = new Account { Name="Microsoft"};
      
     _accountId1 = _serviceProxy.Create(crmAccount);
     _accountId2 = _serviceProxy.Create(crmAccount);
     Console.WriteLine(String.Concat("Creating duplicate records:\n\taccount 1 - ",
         _accountId1.Value, "\n\taccount 2 - ", _accountId2.Value));
 }
Exemple #2
0
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                new ColumnSet(new string[] { "firstname", "lastname" }));
            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);
            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account { Name = "Fourth Coffee" };
            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Fourth Coffee.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            var eref = new EntityReference(Account.EntityLogicalName, accountId);
            eref.Name = account.Name;
            records.Add(eref);

            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);
            Console.Write("retrieved, ");

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            retrievedAccount.Address2_PostalCode = null;

            // Shows use of a Money value.
            retrievedAccount.Revenue = new Money(5000000);

            // Shows use of a Boolean value.
            retrievedAccount.CreditOnHold = false;

            // Update the account record.
            service.Update(retrievedAccount);
            Console.WriteLine("and updated.");
        }
Exemple #3
0
 private void CreateRequiredRecords()
 {
     // Create an account to relate the opportunity to.
     var account = new Account
     {
         Name = "Litware, Inc.",
         Address1_StateOrProvince = "Colorado"
     };
     _accountId = (_serviceProxy.Create(account));
 }
Exemple #4
0
  /// <summary>
  /// Creates any entity records that this sample requires.
  /// </summary>
  public void CreateRequiredRecords()
  {
   // Create 3 contacts.
   Contact contact = new Contact()
   {
    FirstName = "Ben",
    LastName = "Andrews",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Redmond",
    Address1_StateOrProvince = "WA"
   };
   Guid benAndrewsContactId = _service.Create(contact);
   _contactIds.Add(benAndrewsContactId);
   
   //Create a task associated with Ben Andrews
   Task task = new Task() { 
    Subject = "Sample Task", 
    RegardingObjectId = new EntityReference() { 
     LogicalName = Contact.EntityLogicalName,
     Id = benAndrewsContactId, 
     Name = contact.FullName 
    } 
   };
   _taskIds.Add(_service.Create(task));
  


   contact = new Contact()
   {
    FirstName = "Colin",
    LastName = "Wilcox",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Bellevue",
    Address1_StateOrProvince = "WA"
   };
   _contactIds.Add(_service.Create(contact));

   contact = new Contact()
   {
    FirstName = "Ben",
    LastName = "Smith",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Bellevue",
    Address1_StateOrProvince = "WA"
   };
   _contactIds.Add(_service.Create(contact));

   // Create 3 leads.
   Lead lead = new Lead()
   {
    FirstName = "Dan",
    LastName = "Wilson",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Redmond",
    Address1_StateOrProvince = "WA"
   };
   _leadIds.Add(_service.Create(lead));

   lead = new Lead()
   {
    FirstName = "Jim",
    LastName = "Wilson",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Bellevue",
    Address1_StateOrProvince = "WA"
   };
   _leadIds.Add(_service.Create(lead));

   lead = new Lead()
   {
    FirstName = "Denise",
    LastName = "Smith",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Bellevue",
    Address1_StateOrProvince = "WA"
   };
   _leadIds.Add(_service.Create(lead));

   // Create 5 customized Accounts for the LINQ samples.
   Account account = new Account
   {
    Name = "A. Datum Corporation",
    Address1_StateOrProvince = "Colorado",
    Address1_Telephone1 = "(206)555-5555",
    PrimaryContactId =
        new EntityReference(Contact.EntityLogicalName, _contactIds[0])
   };
   _accountIds.Add(_service.Create(account));

   account = new Account
   {
    Name = "Adventure Works",
    Address1_StateOrProvince = "Illinois",
    Address1_County = "Lake County",
    Address1_Telephone1 = "(206)555-5555",
    OriginatingLeadId =
        new EntityReference(Lead.EntityLogicalName, _leadIds[0])
   };
   _accountIds.Add(_service.Create(account));

   account = new Account
   {
    Name = "Coho Vineyard",
    Address1_StateOrProvince = "Washington",
    Address1_County = "King County",
    Address1_Telephone1 = "(425)555-5555",
    PrimaryContactId =
        new EntityReference(Contact.EntityLogicalName, _contactIds[1]),
    OriginatingLeadId =
        new EntityReference(Lead.EntityLogicalName, _leadIds[0])
   };
   _accountIds.Add(_service.Create(account));

   account = new Account
   {
    Name = "Fabrikam",
    Address1_StateOrProvince = "Washington",
    Address1_Telephone1 = "(425)555-5555",
    PrimaryContactId =
        new EntityReference(Contact.EntityLogicalName, _contactIds[0])
   };
   _accountIds.Add(_service.Create(account));

   account = new Account
   {
    Name = "Humongous Insurance",
    Address1_StateOrProvince = "Missouri",
    Address1_County = "Saint Louis County",
    Address1_Telephone1 = "(314)555-5555",
    PrimaryContactId =
        new EntityReference(Contact.EntityLogicalName, _contactIds[1])
   };
   _accountIds.Add(_service.Create(account));

   // Create 10 basic Account records.
   for (int i = 1; i <= 10; i++)
   {
    account = new Account
    {
     Name = "Fourth Coffee " + i,
     Address1_StateOrProvince = "California"
    };
    _accountIds.Add(_service.Create(account));
   }
  }
Exemple #5
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create two accounts.
            Account account = new Account
            {
                Name = "A. Datum Corporation",
                Address1_StateOrProvince = "Colorado",
                Address1_Telephone1 = "(206)555-5555",
                EMailAddress1 = "*****@*****.**"
            };
            _accountIds.Add(_service.Create(account));

            account = new Account
            {
                Name = "Adventure Works Cycle",
                Address1_StateOrProvince = "Washington",
                Address1_City = "Redmond",
                Address1_Telephone1 = "(206)555-5555",
                EMailAddress1 = "*****@*****.**"
            };
            _accountIds.Add(_service.Create(account));
        }
Exemple #6
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create the first account, which will be merged into
            Account account1 = new Account();
            account1.Name = "Fourth Coffee";
            account1.Description = "Coffee House";

            _account1Id = _serviceProxy.Create(account1);
            Console.WriteLine("Account 1 created with GUID {{{0}}}", _account1Id);
            Console.WriteLine("  Name: {0}", account1.Name);
            Console.WriteLine("  Description: {0}", account1.Description);

            // Create the second account, which will be merged from
            Account account2 = new Account();

            account2.Name = "Fourth Coffee";
            account2.NumberOfEmployees = 55;

            _account2Id = _serviceProxy.Create(account2);
            Console.WriteLine("Account 2 created with GUID {{{0}}}", _account2Id);
            Console.WriteLine("  Name: {0}", account2.Name);
            Console.WriteLine("  Number of Employees: {0}", account2.NumberOfEmployees);
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {

            // Create an account.
            var account = new Account
            {
                Name = "Litware, Inc.",
                Address1_StateOrProvince = "Colorado"
            };
            _accountId = (_serviceProxy.Create(account));

            // Create the two contacts.
            var contact = new Contact()
            {
                FirstName = "Ben",
                LastName = "Andrews",
                EMailAddress1 = "*****@*****.**",
                Address1_City = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1 = "(206)555-5555",
                ParentCustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(_serviceProxy.Create(contact));

            contact = new Contact()
            {
                FirstName = "Colin",
                LastName = "Wilcox",
                EMailAddress1 = "*****@*****.**",
                Address1_City = "Bellevue",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1 = "(425)555-5555",
                ParentCustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(_serviceProxy.Create(contact));

            // Create two opportunities.
            var opportunity = new Opportunity()
            {
                Name = "Litware, Inc. Opportunity 1",
                EstimatedCloseDate = DateTime.Now.AddMonths(6),
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _opportunityIdList.Add(_serviceProxy.Create(opportunity));

            opportunity = new Opportunity()
            {
                Name = "Litware, Inc. Opportunity 2",
                EstimatedCloseDate = DateTime.Now.AddYears(4),
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _opportunityIdList.Add(_serviceProxy.Create(opportunity));
        }
Exemple #8
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetCRUDOperations1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Instantiate an account object.
                    // See the Entity Metadata topic in the SDK documentation to determine 
                    // which attributes must be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the account containing several of its attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });

                    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
                    Console.Write("retrieved ");

                    // Retrieve version number of the account. Shows BigInt attribute usage.
                    long? versionNumber = retrievedAccount.VersionNumber;

                    if (versionNumber != null)
                        Console.WriteLine("version # {0}, ", versionNumber);

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
                    retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
                    retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
                    retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Shows use of EntityReference.
                    retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);

                    // Shows use of Memo attribute.
                    retrievedAccount.Description = "Account for Fourth Coffee.";

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.WriteLine("and updated.");                    

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #9
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Retrieves the user details.
        /// Create an account record.
        /// </summary>
        public void CreateRequiredRecords()
        {
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse user = (WhoAmIResponse)_service.Execute(userRequest);

            // Current user.
            _myUserId = user.UserId;

            // Query to retrieve other users.
            QueryExpression querySystemUser = new QueryExpression
            {
                EntityName = SystemUser.EntityLogicalName,
                ColumnSet = new ColumnSet(new String[] { "systemuserid", "fullname" }),
                Criteria = new FilterExpression()
            };

            querySystemUser.Criteria.AddCondition("businessunitid", 
                ConditionOperator.Equal, user.BusinessUnitId);
            querySystemUser.Criteria.AddCondition("systemuserid", 
                ConditionOperator.NotEqual, _myUserId);
            // Excluding SYSTEM user.
            querySystemUser.Criteria.AddCondition("lastname", 
                ConditionOperator.NotEqual, "SYSTEM");
            // Excluding INTEGRATION user.
            querySystemUser.Criteria.AddCondition("lastname", 
                ConditionOperator.NotEqual, "INTEGRATION");

            DataCollection<Entity> otherUsers = _service.RetrieveMultiple(
                querySystemUser).Entities;

            int count = _service.RetrieveMultiple(querySystemUser).Entities.Count;
            if ( count > 0)
            {
                _otherUserId = (Guid)otherUsers[count-1].Attributes["systemuserid"];

                Console.WriteLine("Retrieved new owner {0} for assignment.",
                    otherUsers[count - 1].Attributes["fullname"]);
            }
            else
            {
                throw new FaultException(
                    "No other user found in the current business unit for assignment.");
            }

            // Create an Account record 
            Account newAccount = new Account
            {
                Name = "Example Account"
            };

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

            return;
        }
 /// <summary>
 /// Create an account that will be deleted in the main portion of the sample.
 /// </summary>
 private void CreateRequiredRecords()
 {
     var account = new Account
     {
         Name = "Fourth Coffee",
         WebSiteURL = "http://www.fourthcoffee.com/"
     };
     _serviceProxy.Create(account);
 }
        /// <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
        }
 /// <summary>
 /// Creates any entity records that this sample requires.
 /// </summary>
 public void CreateRequiredRecords()
 {
     // Instantiate an Account object.
     // See the Entity Metadata topic in the SDK documentation to determine
     // which attributes must be set for each entity.
     Account setupAccount = new Account()
     {
         Name = "Litware, Inc."
     };
     _accountId = _serviceProxy.Create(setupAccount);
 }
Exemple #13
0
        public async Task Run(Authentication auth, Configuration config)
        {
            try
            {
                // Use an HttpClient object to communicate with the Web services.
                using (HttpClient httpClient = new HttpClient())
                {
                    // Define the Web API address of the service and the period of time each request has to execute.
                    httpClient.BaseAddress = new Uri(config.ServiceUrl);
                    httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
                    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");

                    // Set the type of payload that will be accepted.
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    #region Create a entity
                    // Create an in-memory account using the early-bound Account class.
                    Account account = new Account();
                    account.name = "Contoso";
                    account.telephone1 = "555-5555";

                    // It is a best practice to refresh the access token before every message request is sent. Doing so
                    // avoids having to check the expiration date/time of the token. This operation is quick.
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken);

                    // Send the request, and then check the response for success.
                    // POST api/data/accounts
                    HttpResponseMessage response =
                        await HttpClientExtensions.SendAsJsonAsync<Account>(httpClient, HttpMethod.Post, "api/data/accounts", account);

                    if (response.IsSuccessStatusCode)
                        Console.WriteLine("Account '{0}' created.", account.name);
                    else
                        throw new Exception(String.Format("Failed to create account '{0}', reason is '{1}'.",
                                            account.name, response.ReasonPhrase), new CrmHttpResponseException(response.Content));
                    #endregion Create a entity

                    #region Retrieve a entity
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken);

                    // Retrieve the previously created entity using its Uri. Limit returned properties using a select
                    // statement for improved performance.
                    // GET api/data/accounts(<guid>)?$select=name,telephone1

                    string accountUri = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    var retrieveResponse = await httpClient.GetAsync(accountUri + "?$select=name,telephone1");

                    Account retrievedAccount = null;
                    if (retrieveResponse.IsSuccessStatusCode)
                    {
                        // Deserialize the content into an Account object.
                        retrievedAccount = JsonConvert.DeserializeObject<Account>(await retrieveResponse.Content.ReadAsStringAsync());
                        Console.WriteLine("Account '{0}' retrieved.", retrievedAccount.name);
                    }
                    else
                        throw new Exception(String.Format("Failed to retrieve the account, reason is '{0}'.",
                                            retrieveResponse.ReasonPhrase), new CrmHttpResponseException(response.Content));
                    #endregion retrieve a entity

                    #region Update a entity
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken);

                    // Change just the account name.
                    // You should only specify properties you intend to update.
                    JObject accountToUpdate = new JObject();
                    accountToUpdate.Add("name", retrievedAccount.name + " Incorporated");

                    // Send the update request, and then check the response for success. 
                    // Note that accountUri includes the unique identifier for the entity so we do not have to set the accountid property in the updatedAccount object.
                    // PATCH api/data/acounts(<guid>)
                    response = await HttpClientExtensions.SendAsJsonAsync<JObject>(httpClient, new HttpMethod("PATCH"), accountUri, accountToUpdate);

                    if (response.IsSuccessStatusCode)
                        Console.WriteLine("Account '{0}' updated.", accountToUpdate["name"]);
                    else
                        throw new Exception(
                            String.Format("Failed to update account '{0}', reason is '{1}'.", retrievedAccount.name,
                            response.ReasonPhrase), new CrmHttpResponseException(response.Content));
                    #endregion Update a entity

                    #region Delete a entity
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken);

                    // DELETE api/data/accounts(<guid>)
                    // Send the request, and then check the response for success.
                    response = await httpClient.DeleteAsync(accountUri);

                    if (response.IsSuccessStatusCode)
                        Console.WriteLine("Account '{0}' deleted.", retrievedAccount.name);
                    else
                        throw new Exception(
                            String.Format("Failed to delete account '{0}', reason is '{1}'.", retrievedAccount.name,
                            response.ReasonPhrase), new CrmHttpResponseException(response.Content));
                    #endregion Delete a entity
                }
            }
            catch (TimeoutException ex) { DisplayException(ex); }

            catch (HttpRequestException ex) { DisplayException(ex); }
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            #region Creating Accounts

            String accountName = "Contoso, Ltd";
            String websiteUrl = "http://www.contoso.com/";

            Console.WriteLine("  Creating duplicate records (Account name={0}, Website URL={1})", accountName, 
                websiteUrl);
            // Create some duplicate records
            for (int i = 0; i < 2; i++)
            {
                Account account = new Account()
                {
                    Name = accountName,
                    WebSiteURL = websiteUrl
                };
                account.Id = _serviceProxy.Create(account);
                _duplicateAccounts[i] = account;
            }

            accountName = "Contoso Pharmaceuticals";
            Console.WriteLine("  Creating a non-duplicate record (Account name={0}, Website URL={1})", 
                accountName, websiteUrl);
            // Create a record that is NOT a duplicate
            Account distinctAccount = new Account()
            {
                Name = accountName,
                WebSiteURL = websiteUrl
            };
            distinctAccount.Id = _serviceProxy.Create(distinctAccount);
            _account = distinctAccount;

            #endregion

            #region Create and Publish duplicate detection rule

            Console.WriteLine("  Creating a duplicate detection rule");
            // Create a duplicate detection rule
            _rule = new DuplicateRule()
            {
                Name = "Accounts with the same Account name and website url",
                BaseEntityName = Account.EntityLogicalName,
                MatchingEntityName = Account.EntityLogicalName
            };
            _rule.Id = _serviceProxy.Create(_rule);

            // Create a duplicate detection rule condition
            DuplicateRuleCondition nameCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName = "name",
                MatchingAttributeName = "name",
                OperatorCode = new OptionSetValue(0), // value 0 = 'exact match'
                // set the regarding id to point to the rule created earlier,
                // associating this condition with that rule
                RegardingObjectId = _rule.ToEntityReference()
            };
            _serviceProxy.Create(nameCondition);

            DuplicateRuleCondition websiteCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName = "websiteurl",
                MatchingAttributeName = "websiteurl",
                OperatorCode = new OptionSetValue(0),
                RegardingObjectId = _rule.ToEntityReference()
            };
            _serviceProxy.Create(websiteCondition);

            Console.WriteLine("  Publishing duplicate detection rule");
            // Publish the rule
            PublishDuplicateRuleRequest publishRequest = new PublishDuplicateRuleRequest()
            {
                DuplicateRuleId = _rule.Id
            };
            PublishDuplicateRuleResponse publishResponse = (PublishDuplicateRuleResponse)_serviceProxy.Execute(publishRequest);

            // The PublishDuplicateRule request returns before the publish is completed,
            // so we keep retrieving the async job state until it is "Completed"
            Console.WriteLine("  Checking to see if duplicate detection rule has finished publishing");
            WaitForAsyncJobToFinish(publishResponse.JobId, 60);

            #endregion
        }
Exemple #15
0
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

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

			Relationship primaryContactRelationship = new Relationship("account_primary_contact");

			Guid primaryContactId = service.Create(new Contact() { LastName = RootContactLastName.Get<string>(executionContext) });

			//tracingService.Trace("Create an Account with an existing primary contact");
			Account rootAccount = new Account() { Name = RelatedAccountName.Get<string>(executionContext) };
			Contact primaryContact = new Contact()
			{
				EntityState = EntityState.Changed,
				Id = primaryContactId,
				FirstName = RootContactFirstName.Get<string>(executionContext)
			};

			rootAccount.RelatedEntities[primaryContactRelationship] =
				new EntityCollection(new Entity[] { primaryContact }) { EntityName = Contact.EntityLogicalName };

			tracingService.Trace("Execute the Create/Update");
			rootAccount.Id = service.Create(rootAccount);

			//Create the related entities query
			RelationshipQueryCollection retrieveRelatedEntities = new RelationshipQueryCollection();
			retrieveRelatedEntities[primaryContactRelationship] = new QueryExpression(Account.EntityLogicalName)
			{
				ColumnSet = new ColumnSet("name"),
				Criteria = new FilterExpression()
			};

			//Create the request
			RetrieveResponse response = (RetrieveResponse)service.Execute(new RetrieveRequest()
			{
				ColumnSet = new ColumnSet("firstname"),
				RelatedEntitiesQuery = retrieveRelatedEntities,
				Target = new EntityReference(primaryContact.LogicalName, primaryContact.Id)
			});

			tracingService.Trace("Retrieve the record with its related entities");
			Contact retrievedContact = (Contact)response.Entity;
			Account retrievedAccount = (Account)retrievedContact.RelatedEntities[primaryContactRelationship][0];

			tracingService.Trace("Ensure the first name was updated");
			if (retrievedContact.FirstName == primaryContact.FirstName)
			{
				tracingService.Trace("Primary Contact name is correct");
			}
			else
			{
				tracingService.Trace("First Name is \"{0}\", expected \"{1}\".", retrievedContact.FirstName, primaryContact.FirstName);
				throw new InvalidPluginExecutionException("The first name was not changed");
			}
		}
Exemple #16
0
 /// <summary>
 /// Creates any entity records that this sample requires.
 /// </summary>
 public void CreateRequiredRecords()
 {
     // For this sample, all required entities are created in the Run() method.
     Account account = new Account { Name = "Sample Parent Account" };
     _parentAccountId = _serviceProxy.Create(account);
 }
Exemple #17
0
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

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

			tracingService.Trace("Creating Account");

			Account entity = new Account();
			entity.Name = AccountName.Get<string>(executionContext);
			Guid entityId = service.Create(entity);

			tracingService.Trace("Account created with Id {0}", entityId.ToString());

			tracingService.Trace("Create a task for the account");
			Task newTask = new Task();
			newTask.Subject = TaskSubject.Get<string>(executionContext);
			newTask.RegardingObjectId = new EntityReference(Account.EntityLogicalName, entityId);

			Guid taskId = service.Create(newTask);

			tracingService.Trace("Task has been created");

			tracingService.Trace("Retrieve the task using QueryByAttribute");
			QueryByAttribute query = new QueryByAttribute();
			query.Attributes.AddRange(new string[] { "regardingobjectid" });
			query.ColumnSet = new ColumnSet(new string[] { "subject" });
			query.EntityName = Task.EntityLogicalName;
			query.Values.AddRange(new object[] { entityId });

			tracingService.Trace("Executing the Query for entity {0}", query.EntityName);

			//Execute using a request to test the OOB (XRM) message contracts
			RetrieveMultipleRequest request = new RetrieveMultipleRequest();
			request.Query = query;
			Collection<Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

			//Execute a request from the CRM message assembly
			tracingService.Trace("Executing a WhoAmIRequest");
			service.Execute(new WhoAmIRequest());

			if (1 != entityList.Count)
			{
				tracingService.Trace("The entity list was too long");
				throw new InvalidPluginExecutionException("Query did not execute correctly");
			}
			else
			{
				tracingService.Trace("Casting the Task from RetrieveMultiple to strong type");
				Task retrievedTask = (Task)entityList[0];

				if (retrievedTask.ActivityId != taskId)
				{
					throw new InvalidPluginExecutionException("Incorrect task was retrieved");
				}

				tracingService.Trace("Retrieving the entity from IOrganizationService");

				//Retrieve the task using Retrieve
				retrievedTask = (Task)service.Retrieve(Task.EntityLogicalName, retrievedTask.Id, new ColumnSet("subject"));
				if (!string.Equals(newTask.Subject, retrievedTask.Subject, StringComparison.Ordinal))
				{
					throw new InvalidPluginExecutionException("Task's subject did not get retrieved correctly");
				}

				//Update the task
				retrievedTask.Subject = UpdatedTaskSubject.Get<string>(executionContext);
				service.Update(retrievedTask);
			}
		}
Exemple #18
0
        public void CreateRequiredRecords()
        {
            // Create an account
            Account account = new Account
            {
                Name = "Fourth Coffee"
            };
            _accountId = _serviceProxy.Create(account);

            // Create an opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Opportunity 1",
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }                
            };
            _opportunityId = _serviceProxy.Create(newOpportunity);
        }
Exemple #19
0
       //</snippetQuickCampaign3>

        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a new queue instance.
        /// </summary>
        public void CreateRequiredRecords()
        {
            WhoAmIRequest whoRequest = new WhoAmIRequest();
            _currentUser = ((WhoAmIResponse)_serviceProxy.Execute(whoRequest)).UserId;

            //Create an activity objects which will act like a template during QC distrbution. 
            //The activities created by QC will create activities with content that this activity has
            _templateEmailActivity = new Email()
            {
                Subject = "qcCreatedEmailActivity"
            };

            _templateLetterActivity = new Letter()
            {
                Subject = "qcCreatedLetterActivity"
            };

            // Create accounts on which we want to run QC
            _accountIdArray = new Guid[5];
            for (int i = 0; i < 5; i++)
            {
                Account acct = new Account() {
                    Name = "Account For Quick Campaign " + i.ToString()
                };
                _accountIdArray[i] = _serviceProxy.Create(acct);
                Console.WriteLine("Created {0}.", acct.Name);
            }
        }
        /// <summary>
        /// Create any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create an account named Fourth Coffee.
            Account testAccount = new Account
            {
                Name = "Fourth Coffee"
            };

            _accountId = _serviceProxy.Create(testAccount);

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

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

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

            _defaultUnitId = unit.UoMId.Value;

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

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

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

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

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

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

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

            _discountId = _serviceProxy.Create(newDiscount);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

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

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

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

            return;
        }
Exemple #22
0
        /// <summary>
        /// This method shows how to merge two entity records with the Merge message.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig,bool promptForDelete)
        {
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                //Create the Contact and Incident required for this sample.
                CreateRequiredRecords();
 
                //<snippetMerge1>
                // Create the target for the request.
			    EntityReference target = new EntityReference();

			    // Id is the GUID of the account that is being merged into.
                // LogicalName is the type of the entity being merged to, as a string
			    target.Id = _account1Id;
                target.LogicalName = Account.EntityLogicalName;

                // Create the request.
                MergeRequest merge = new MergeRequest();
                // SubordinateId is the GUID of the account merging.
                merge.SubordinateId = _account2Id;
                merge.Target = target;
                merge.PerformParentingChecks = false;

                Console.WriteLine("\nMerging account2 into account1 and adding " +
                    "\"test\" as Address 1 Line 1");

                // Create another account to hold new data to merge into the entity.
                // If you use the subordinate account object, its data will be merged.
                Account updateContent = new Account();
                updateContent.Address1_Line1 = "test";

                // Set the content you want updated on the merged account
                merge.UpdateContent = updateContent;

                // Execute the request.
                MergeResponse merged = (MergeResponse)_serviceProxy.Execute(merge);
                //</snippetMerge1>

                Account mergeeAccount = 
                    (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, 
                    _account2Id, new ColumnSet(allColumns:true));

                if(mergeeAccount.Merged == true)
                {
                    Account mergedAccount =
                        (Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
                        _account1Id, new ColumnSet(allColumns: true));

                    Console.WriteLine("\nAccounts merged successfully into account1");
                    Console.WriteLine("  Name: {0}", mergedAccount.Name);
                    Console.WriteLine("  Description: {0}", mergedAccount.Description);
                    Console.WriteLine("  Number of Employees: {0}", 
                        mergedAccount.NumberOfEmployees);
                    Console.WriteLine("  Address 1 Line 1: {0}", 
                        mergedAccount.Address1_Line1);
                }

                DeleteRequiredRecords(promptForDelete);
            }
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a team, a queue and a role.
        /// Add read queue privileges to the role.
        /// Assign the role to the team so that they can read the queue.
        /// Assign the queue to the team.
        /// </summary>
        public void CreateRequiredRecords()
        {            
            // Instantiate a contact entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentatio to determine 
            // which attributes must be set for each entity.
            Contact setupContact = new Contact
            {
                 FirstName = "John",
                 LastName = "Doe"
            };
            _contactId = _service.Create(setupContact);
            Console.WriteLine("Created {0} {1}", setupContact.FirstName, 
                setupContact.LastName);
            
            // Instantiate an account entity record and set its property values.
            Account setupAccount1 = new Account
            {
                Name = "Example Account 1"
            };
            _account1Id = _service.Create(setupAccount1);
            Console.WriteLine("Created {0}", setupAccount1.Name);

            Account setupAccount2 = new Account
            {
                Name = "Example Account 2"
            };
            _account2Id = _service.Create(setupAccount2);
            Console.WriteLine("Created {0}", setupAccount2.Name);

            Account setupAccount3 = new Account
            {
                Name = "Example Account 3"
            };
            _account3Id = _service.Create(setupAccount3);
            Console.WriteLine("Created {0}", setupAccount3.Name);
        }
  /// <summary>
  /// Creates any entity records that this sample requires.
  /// </summary>
  public void CreateRequiredRecords()
  {
   // Create an account.
   Account account = new Account
   {
    Name = "Litware, Inc."
   };
   _accountId = _service.Create(account);

   // Create the 2 contacts.
   Contact contact = new Contact()
   {
    FirstName = "Ben",
    LastName = "Andrews",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Redmond",
    Address1_StateOrProvince = "WA",
    Address1_Telephone1 = "(206)555-5555",
    ParentCustomerId = new EntityReference
    {
     Id = _accountId,
     LogicalName = account.LogicalName
    }
   };
   _contactIdList.Add(_service.Create(contact));

   contact = new Contact()
   {
    FirstName = "Colin",
    LastName = "Wilcox",
    EMailAddress1 = "*****@*****.**",
    Address1_City = "Bellevue",
    Address1_StateOrProvince = "WA",
    Address1_Telephone1 = "(425)555-5555",
    ParentCustomerId = new EntityReference
    {
     Id = _accountId,
     LogicalName = account.LogicalName
    }
   };
   _contactIdList.Add(_service.Create(contact));
  }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a parent account record.
        /// Create 10 child accounts to the parent account record.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Instantiate a account 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.
            // Create the parent account.
            Account parentAccount = new Account
            {
                Name = "Root Test Account",
                EMailAddress1 = "*****@*****.**"
            };
            
            
            _parentAccountId = _service.Create(parentAccount);

            // Create 10 child accounts.
            _childAccountIds = new Guid[10]; 
            int count = 1;
            while (true)
            {
                Account childAccount = new Account
                {
                    Name = "Child Test Account " + count.ToString(),
                    EMailAddress1 = "child" + count.ToString() + "@root.com",
                    EMailAddress2 = "*****@*****.**",
                    ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId)
                };
                
                _childAccountIds[count - 1] = _service.Create(childAccount);

                // Jump out of the loop after creating 10 child accounts.
                if (count == 10)
                    break;
                // Increment the count.
                count++;
            }            
            return;
        }
        /// <summary>
        /// This method first checks if the logged on user has prvReadPOAA permissions. 
        /// Afterwards,  the method creates the secure custom fields required for this sample,
        /// an account record for testing purposes, and POAA records for the user
        /// and those custom fields.
        /// Finally, the method retrieves the User Shared Attribute permissions for that user.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRetrieveUserSharedAttributePermissions1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetRetrieveUserSharedAttributePermissions2>

                    #region Check if this user has prvReadPOAA
                    // Get the GUID of the current user.
                    WhoAmIRequest whoAmI = new WhoAmIRequest();
                    Guid userLoggedId = 
                        ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
                    Console.WriteLine("User logged: " + userLoggedId);

                    // Check if this user has prvReadPOAA.
                    RetrieveUserPrivilegesRequest userPrivilegesRequest = 
                        new RetrieveUserPrivilegesRequest();
                    userPrivilegesRequest.UserId = userLoggedId;
                    RetrieveUserPrivilegesResponse userPrivilegesResponse =
                        (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest);

                    // Fixed the GUID for prvReadPOAA.
                    Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}");

                    if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA)))
                    {
                        Console.WriteLine("This user DOES have prvReadPOAA");
                    }
                    else
                    {
                        Console.WriteLine("This user DOESN'T have prvReadPOAA");
                    }
                    Console.WriteLine();
                    #endregion Check if this user has prvReadPOAA
                    //</snippetRetrieveUserSharedAttributePermissions2>
                    #region Create an account record

                    // Create an account record
                    Account accountRecord = new Account();
                    accountRecord.Name = "Ane";
                    accountRecord["secret_phone"] = "123456";
                    _accountRecordId = _serviceProxy.Create(accountRecord);
                    Console.WriteLine("Account record created.");

                    #endregion Create an account record

                    #region Create POAA entity for field #1

                    // Create POAA entity for field #1
                    PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretHomeId,
                        ObjectId = new EntityReference
                            (Account.EntityLogicalName, _accountRecordId),
                        PrincipalId = new EntityReference
                            (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Home created.");

                    #endregion Create POAA entity for field #1

                    #region Create POAA entity for field #2

                    // Create POAA entity for field #2
                    poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretPhoneId,
                        ObjectId = new EntityReference
                            (Account.EntityLogicalName, _accountRecordId), 
                        PrincipalId = new EntityReference
                            (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Phone created.");

                    #endregion Create POAA entity for field #2

                    #region Retrieve User Shared Attribute Permissions
                    // Create the query for retrieve User Shared Attribute permissions.
                    QueryExpression queryPOAA =
                        new QueryExpression("principalobjectattributeaccess");
                    queryPOAA.ColumnSet = new ColumnSet
                        (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" });
                    queryPOAA.Criteria.FilterOperator = LogicalOperator.And;
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId));
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("principalid", ConditionOperator.EqualUserId));

                    Console.WriteLine();
                    Console.WriteLine("POAA for user: "******"  principalid: " + ((EntityReference)entity["principalid"]).Id);
                            Console.WriteLine("  attributeid: " + entity["attributeid"].ToString());
                            Console.WriteLine("  readaccess: " + entity["readaccess"].ToString());
                            Console.WriteLine("  updateaccess: " + entity["updateaccess"].ToString());
                            Console.WriteLine();
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("Error: " + exc.Message);
                    }

                    #endregion Retrieve User Shared Attribute Permissions

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

            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #27
0
        //</snippetAuditing3>

        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            Console.Write("Creating an account, ");

            // Account entity category codes.
            var Categories = new { PreferredCustomer = 1, Standard = 2 };

            // Create a new account entity. 
            Account newAccount = new Account { Name = "Example Account" };
            _newAccountId = _service.Create(newAccount);

            Console.WriteLine("then updating the account.");

            // Set the values of some other attributes.
            newAccount.AccountId = _newAccountId;
            newAccount.AccountNumber = "1-A";
            newAccount.AccountCategoryCode = new OptionSetValue(Categories.PreferredCustomer);
            newAccount.Telephone1 = "555-555-5555";

            _service.Update(newAccount);
        }
		/// <summary>
		/// Creates any entity records that this sample requires.
		/// </summary>
		public void CreateRequiredRecords()
		{
			// Create a unit group.
			UoMSchedule unitGroup = new UoMSchedule
			{
				Name = "Example Unit Group",
				BaseUoMName = "Example Primary Unit"
			};
			_unitGroupId = _service.Create(unitGroup);

			// Retrieve the unit.
			QueryExpression unitQuery = new QueryExpression()
			{
				EntityName = UoM.EntityLogicalName,
				ColumnSet = new ColumnSet("uomid", "name"),
				Criteria =
				{
					Conditions = 
					{
						new ConditionExpression ("uomscheduleid", ConditionOperator.Equal, _unitGroupId)
					}
				},
				PageInfo = new PagingInfo
				{
					PageNumber = 1,
					Count = 1
				}
			};
			UoM unit = (UoM)_service.RetrieveMultiple(unitQuery).Entities[0];

			// Create an account.
			Account account = new Account
			{
				Name = "Litware, Inc.",
				Address1_StateOrProvince = "Colorado"
			};
			_accountId = (_service.Create(account));

			// Create the 2 contacts.
			Contact contact = new Contact()
			{
				FirstName = "Ben",
				LastName = "Andrews",
				EMailAddress1 = "*****@*****.**",
				Address1_City = "Redmond",
				Address1_StateOrProvince = "WA",
				Address1_Telephone1 = "(206)555-5555",
				ParentCustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_contactIdList.Add(_service.Create(contact));

			contact = new Contact()
			{
				FirstName = "Colin",
				LastName = "Wilcox",
				EMailAddress1 = "*****@*****.**",
				Address1_City = "Bellevue",
				Address1_StateOrProvince = "WA",
				Address1_Telephone1 = "(425)555-5555",
				ParentCustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_contactIdList.Add(_service.Create(contact));

			// Create pricing and product objects.
			PriceLevel priceLevel = new PriceLevel()
			{
				Name = "Faux Price List"
			};
			_priceLevelId = _service.Create(priceLevel);

			Product product = new Product()
			{
				ProductNumber = "1",
				QuantityDecimal = 4,
				Name = "Faux Product",
				Price = new Money(20.0M),
				DefaultUoMId = new EntityReference
				{
					Id = unit.Id,
					LogicalName = UoM.EntityLogicalName
				},
				DefaultUoMScheduleId = new EntityReference
				{
					Id = _unitGroupId,
					LogicalName = UoMSchedule.EntityLogicalName
				}
			};
			_productId = _service.Create(product);

			ProductPriceLevel productPrice = new ProductPriceLevel()
			{
				PriceLevelId = new EntityReference()
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				ProductId = new EntityReference()
				{
					Id = _productId,
					LogicalName = Product.EntityLogicalName
				},
				UoMId = new EntityReference
				{
					Id = unit.Id,
					LogicalName = UoM.EntityLogicalName
				},
				Amount = new Money(20.0M),
			};
			_productPriceId = _service.Create(productPrice);

			// Create 3 orders.
			SalesOrder order = new SalesOrder()
			{
				Name = "Faux Order",
				DateFulfilled = new DateTime(2010, 8, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			order = new SalesOrder()
			{
				Name = "Old Faux Order",
				DateFulfilled = new DateTime(2010, 4, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			order = new SalesOrder()
			{
				Name = "Oldest Faux Order",
				DateFulfilled = new DateTime(2008, 8, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			// Create 2 opportunities.
			Opportunity opportunity = new Opportunity()
			{
				Name = "Litware, Inc. Opportunity 1",
				EstimatedCloseDate = new DateTime(2011, 1, 1),
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_opportunityIdList.Add(_service.Create(opportunity));

			opportunity = new Opportunity()
			{
				Name = "Litware, Inc. Opportunity 2",
				EstimatedCloseDate = new DateTime(2020, 1, 1),
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_opportunityIdList.Add(_service.Create(opportunity));
		}
Exemple #29
0
        /// <summary>
        /// This method first connects to the organization service. Next, auditing 
        /// is enabled on the organization and an account entity. The account record
        /// is updated and the audit history printed out.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // Enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account
                //<snippetAuditing1>
                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                    new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                org.IsAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);
                //</snippetAuditing1>
                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Retrieve the Record Change History
                Console.WriteLine("Retrieving the account change history.\n");
                //<snippetAuditing5>
                // Retrieve the audit history for the account and display it.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;
                //</snippetAuditing5>

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Display some of the detail information in each audit record. 
                    DisplayAuditDetails(detail);
                }
                #endregion Retrieve the Record Change History

                #region Retrieve the Attribute Change History

                //<snippetAuditing7>
                // Update the Telephone1 attribute in the Account entity record.
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                // Retrieve the attribute change history.
                Console.WriteLine("Retrieving the attribute change history for Telephone1.");

                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Display the attribute change history.
                details = attributeChangeHistoryResponse.AuditDetailCollection;
                //</snippetAuditing7>

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAuditDetails(detail);
                }

                // Save an Audit record ID for later use.
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion Retrieve the Attribute Change History

                #region Retrieve the Audit Details
                //<snippetAuditing8>
                Console.WriteLine("Retrieving audit details for an audit record.");

                // Retrieve the audit details and display them.
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);
                //</snippetAuditing8>
                DisplayAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion Retrieve the Audit Details

                #region Revert Auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled = organizationAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert Auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
           #region Create or Retrieve the necessary system users

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

            #endregion

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

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

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

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

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

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

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

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

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

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

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

            #endregion Create records to support Opportunity records

        }
        /// <summary>
        /// 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
        }