Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(Microsoft.Xrm.Sdk.OrganizationRequest)

Here are the examples of the csharp api Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(Microsoft.Xrm.Sdk.OrganizationRequest) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

211 Examples 7

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these enreplacedy records deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                // TODO Delete enreplacedy records
                _serviceProxy.Delete(Contract.EnreplacedyLogicalName, _secondCloneId);
                _serviceProxy.Delete(Contract.EnreplacedyLogicalName, _renewedId);
                _serviceProxy.Delete(Contract.EnreplacedyLogicalName, _contractId);
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EnreplacedyMoniker = new EnreplacedyReference
                    {
                        Id = _firstCloneId,
                        LogicalName = Contract.EnreplacedyLogicalName
                    },
                    State = new OptionSetValue((int)ContractState.Invoiced),
                    Status = new OptionSetValue(3)
                };
                _serviceProxy.Execute(setStateRequest);
                setStateRequest = new SetStateRequest()
                {
                    EnreplacedyMoniker = new EnreplacedyReference
                    {
                        Id = _firstCloneId,
                        LogicalName = Contract.EnreplacedyLogicalName
                    },
                    State = new OptionSetValue((int)ContractState.Canceled),
                    Status = new OptionSetValue(5)
                };
                _serviceProxy.Execute(setStateRequest);
                _serviceProxy.Delete(Contract.EnreplacedyLogicalName, _firstCloneId);
                _serviceProxy.Delete(Account.EnreplacedyLogicalName, _accountId);
                Console.WriteLine("Enreplacedy records have been deleted.");
            }
        }

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create enreplacedy records
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };
            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Create {0}", newUnitGroup.Name);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EnreplacedyName = UoM.EnreplacedyLogicalName,
                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).Enreplacedies[0];
            _defaultUnitId = unit.UoMId.Value;

            // Create a few products
            Product newProduct = new Product
            {
                ProductNumber = "1",
                Name = "Example Product",
                ProductStructure = new OptionSetValue(1),
                QuanreplacedyDecimal = 1,
                DefaultUoMScheduleId =
                    new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, _unitGroupId),
                DefaultUoMId =
                    new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId)
            };
            _productId = _serviceProxy.Create(newProduct);
            newProduct.Id = _productId;
            Console.WriteLine("Create {0}", newProduct.Name);

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

            // Create a price list item for the product and apply volume discount
            ProductPriceLevel newPriceLisreplacedem = new ProductPriceLevel
            {
                PriceLevelId =
                    new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId =
                    new EnreplacedyReference(Product.EnreplacedyLogicalName, _productId),
                UoMId =
                    new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20.0M),
            };
            _priceLisreplacedemId = _serviceProxy.Create(newPriceLisreplacedem);

            // Publish the product
            SetStateRequest publishRequest = new SetStateRequest
            {
                EnreplacedyMoniker = new EnreplacedyReference(Product.EnreplacedyLogicalName, _productId),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest);
            Console.WriteLine("Published {0}", newProduct.Name);

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

            Console.WriteLine("Required records have been created.");
        }

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create enreplacedy records
            #region Create or Retrieve the necessary system users

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

            #endregion

            #region Create PhoneCall record and supporting account

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

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

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

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId = account.ToEnreplacedyReference(),
                ActivityId = new EnreplacedyReference
                {
                    Id = _phoneCall2Id,
                    LogicalName = PhoneCall.EnreplacedyLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

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

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

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

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

            #endregion
            Console.WriteLine("Required records have been created.");
        }

19 Source : SendBulkEmailAndMonitor.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy is properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create and send SendBulkEmail

                    Console.WriteLine();
                    Console.WriteLine("Creating and sending SendBulkEmail.");

                    // Get a system user to use as the sender.
                    WhoAmIRequest emailSenderRequest = new WhoAmIRequest();
                    WhoAmIResponse emailSenderResponse =
                        _serviceProxy.Execute(emailSenderRequest) as WhoAmIResponse;

                    // Set trackingId for bulk mail request.
                    Guid trackingId = Guid.NewGuid();

                    SendBulkMailRequest bulkMailRequest = new SendBulkMailRequest()
                    {
                        // Create a query expression for the bulk operation to use to retrieve 
                        // the contacts in the email list.
                        Query = new QueryExpression()
                        {
                            EnreplacedyName = Contact.EnreplacedyLogicalName,
                            ColumnSet = new ColumnSet(new String[] { "contactid" }),
                            Criteria = new FilterExpression()
                            {
                                Conditions = 
                            {
                                new ConditionExpression("contactid",ConditionOperator.In, _contactsIds)
                            }
                            }
                        },
                        // Set the Sender.
                        Sender = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, emailSenderResponse.UserId),
                        // Set the RegardingId - this field is required.
                        RegardingId = Guid.Empty,
                        RegardingType = SystemUser.EnreplacedyLogicalName,
                        // Use a built-in Microsoft Dynamics CRM email template.
                        // NOTE: The email template's "template type" must match the type of 
                        // customers in the email list.  Our list contains contacts, so our 
                        // template must be for contacts.
                        TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),
                        RequestId = trackingId
                    };

                    // Execute the async bulk email request
                    SendBulkMailResponse resp = (SendBulkMailResponse)
                        _serviceProxy.Execute(bulkMailRequest);

                    Console.WriteLine("  Sent Bulk Email.");
                    #endregion

                    #region Monitoring SendBulkEmail

                    Console.WriteLine();
                    Console.WriteLine("Starting monitoring process..");

                    // Now that we've executed the bulk operation, we need to retrieve it 
                    // using our tracking Id.

                    QueryByAttribute bulkQuery = new QueryByAttribute()
                    {
                        EnreplacedyName = AsyncOperation.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet(new string[] { "requestid", "statecode" }),
                        Attributes = { "requestid" },
                        Values = { trackingId }
                    };

                    // Retrieve the bulk email async operation.
                    EnreplacedyCollection aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);

                    Console.WriteLine("  Retrieved Bulk Email Async Operation.");

                    // Monitor the async operation via polling.
                    int secondsTicker = ARBITRARY_MAX_POLLING_TIME;

                    AsyncOperation createdBulkMailOperation = null;

                    Console.WriteLine("  Checking operation's state for " + ARBITRARY_MAX_POLLING_TIME + " seconds.");
                    Console.WriteLine();

                    while (secondsTicker > 0)
                    {
                        // Make sure the async operation was retrieved.
                        if (aResponse.Enreplacedies.Count > 0)
                        {
                            // Grab the one bulk operation that has been created.
                            createdBulkMailOperation = (AsyncOperation)aResponse.Enreplacedies[0];

                            // Check the operation's state.
                            if (createdBulkMailOperation.StateCode.Value !=
                                AsyncOperationState.Completed)
                            {
                                // The operation has not yet completed. 
                                // Wait a second for the status to change.
                                System.Threading.Thread.Sleep(1000);
                                secondsTicker--;

                                // Retrieve a fresh version the bulk delete operation.
                                aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
                            }
                            else
                            {
                                // Stop polling because the operation's state is now complete.
                                secondsTicker = 0;
                            }
                        }
                        else
                        {
                            // Wait a second for the async operation to activate.
                            System.Threading.Thread.Sleep(1000);
                            secondsTicker--;

                            // Retrieve the enreplacedy again
                            aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
                        }
                    }

                    // When the bulk email operation has completed, all sent emails will 
                    // have a status of "Pending Send" and will be picked up by your email 
                    // router.  Alternatively, you can then use BackgroundSendEmail to download
                    // all the emails created with the SendBulkEmail message. 
                    // See the BackgroundSendEmail sample for an example.
                    #endregion

                    #region Check success

                    // Validate async operation succeeded
                    if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed)
                    {
                        Console.WriteLine("Operation Completed.");
                    }
                    else
                    {
                        Console.WriteLine("Operation not completed yet.");
                    }

                    #endregion

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

19 Source : SendEmail.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Create a contact to send an email to (To: field)
            Contact emailContact = new Contact
            {
                FirstName = "Nancy",
                LastName = "Anderson",
                EMailAddress1 = "[email protected]"
            };
            _contactId = _serviceProxy.Create(emailContact);
            Console.WriteLine("Created a contact: {0}.", emailContact.FirstName + " " + emailContact.LastName);

            // Get a system user to send the email (From: field)
            WhoAmIRequest systemUserRequest = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);
            _userId = systemUserResponse.UserId;

            // Create the 'From:' activity party for the email
            ActivityParty fromParty = new ActivityParty
            {
                PartyId = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, _userId)
            };

            // Create the 'To:' activity party for the email
            ActivityParty toParty = new ActivityParty
            {
                PartyId = new EnreplacedyReference(Contact.EnreplacedyLogicalName, _contactId)
            };
            Console.WriteLine("Created activity parties.");

            // Create an e-mail message.
            Email email = new Email
            {
                To = new ActivityParty[] { toParty },
                From = new ActivityParty[] { fromParty },
                Subject = "SDK Sample e-mail",
                Description = "SDK Sample for SendEmail Message.",
                DirectionCode = true
            };
            _emailId = _serviceProxy.Create(email);
            Console.WriteLine("Create {0}.", email.Subject);
        }

19 Source : SystemUserProvider.cs
with MIT License
from microsoft

public static Guid RetrieveSystemUser(String userName, String firstName,
            String lastName, String roleStr, OrganizationServiceProxy serviceProxy,
            ref String ldapPath)
        {
            String domain;
            Guid userId = Guid.Empty;

            if (serviceProxy == null)
                throw new ArgumentNullException("serviceProxy");

            if (String.IsNullOrWhiteSpace(userName))
                throw new ArgumentNullException("UserName");

            if (String.IsNullOrWhiteSpace(firstName))
                throw new ArgumentNullException("FirstName");

            if (String.IsNullOrWhiteSpace(lastName))
                throw new ArgumentNullException("LastName");

            // Obtain the current user's information.
            WhoAmIRequest who = new WhoAmIRequest();
            WhoAmIResponse replacedsp = (WhoAmIResponse)serviceProxy.Execute(who);
            Guid currentUserId = replacedsp.UserId;

            SystemUser currentUser =
                serviceProxy.Retrieve(SystemUser.EnreplacedyLogicalName, currentUserId, new ColumnSet("domainname")).ToEnreplacedy<SystemUser>();

            // Extract the domain and create the LDAP object.
            String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
            if (userPath.Length > 1)
                domain = userPath[0] + "\\";
            else
                domain = String.Empty;



            SystemUser existingUser = GetUserIdIfExist(serviceProxy, domain, userName, firstName, lastName);


            if (existingUser != null)
            {
                userId = existingUser.SystemUserId.Value;

                if (!String.IsNullOrWhiteSpace(roleStr))
                {
                    // Check to make sure the user is replacedigned the correct role.
                    Role role = RetrieveRoleByName(serviceProxy, roleStr);

                    // replacedociate the user with the role when needed.
                    if (!UserInRole(serviceProxy, userId, role.Id))
                    {
                        replacedociateRequest replacedociate = new replacedociateRequest()
                        {
                            Target = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, userId),
                            RelatedEnreplacedies = new EnreplacedyReferenceCollection()
                        {
                            new EnreplacedyReference(Role.EnreplacedyLogicalName, role.Id)
                        },
                            Relationship = new Relationship("systemuserroles_replacedociation")
                        };
                        serviceProxy.Execute(replacedociate);
                    }
                }
            }
            else
            {
                // Create the system user in Microsoft Dynamics CRM if the user doesn't 
                // already exist.
                userId = CreateSystemUser(userName, firstName, lastName, domain,
                    roleStr, serviceProxy, ref ldapPath);
            }

            return userId;
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void PostToRecordWalls()
        {
            Console.WriteLine("\r\n== Working with Record Walls ==");
            // Create the leads.
            CreateRequiredRecords();

            // Follow each of the leads.
            _follow1 = new PostFollow
            {
                RegardingObjectId = _lead1.ToEnreplacedyReference()
            };
            _serviceContext.AddObject(_follow1);

            _follow2 = new PostFollow
            {
                RegardingObjectId = _lead2.ToEnreplacedyReference()
            };
            _serviceContext.AddObject(_follow2);

            _follow3 = new PostFollow
            {
                RegardingObjectId = _lead3.ToEnreplacedyReference()
            };
            _serviceContext.AddObject(_follow3);

            _serviceContext.SaveChanges();
            Console.WriteLine("  The 3 leads are now followed.");

            // Create posts, mentions, and comments related to the leads.
            // Create a post related to lead 1 with a mention and a comment.
            _leadPost1 = new Post
            {
                RegardingObjectId = _lead1.ToEnreplacedyReference(),
                Source = new OptionSetValue((int)PostSource.AutoPost),
                // Include a mention in the post text.
                Text = String.Format("This lead is similar to @[{0},{1},\"{2}\"]",
                    Lead.EnreplacedyTypeCode, _lead2.Id, _lead2.FullName)
            };

            _serviceContext.AddObject(_leadPost1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Post 1 has been created.");

            // It isn't necessary to keep track of the comment because the comment will
            // be deleted when its parent post is deleted.
            var comment1 = new PostComment
            {
                PostId = _leadPost1.ToEnreplacedyReference(),
                Text = "Sample comment 1"
            };
            _serviceContext.AddObject(comment1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Comment 1 has been created.");

            // Create a post related to lead 2 with three comments.
            var post2 = new Post
            {
                RegardingObjectId = _lead2.ToEnreplacedyReference(),
                Source = new OptionSetValue((int)PostSource.ManualPost),
                Text = "This lead was created for a sample."
            };

            _serviceContext.AddObject(post2);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Post 2 has been created.");

            var comment2 = new PostComment
            {
                PostId = post2.ToEnreplacedyReference(),
                Text = "Sample comment 2"
            };

            var comment3 = new PostComment
            {
                PostId = post2.ToEnreplacedyReference(),
                Text = "Sample comment 3"
            };

            var comment4 = new PostComment
            {
                PostId = post2.ToEnreplacedyReference(),
                Text = "Sample comment 4"
            };

            _serviceContext.AddObject(comment2);
            _serviceContext.AddObject(comment3);
            _serviceContext.AddObject(comment4);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Comments 2, 3, and 4 have been created.");

            // Qualify some leads.  Since there is an active post rule config for
            // qualification of a lead, this should generate an auto post to the record
            // wall of each lead that is qualified.

            // Qualify lead 2.
            var qualifyLead2Request = new QualifyLeadRequest
            {
                CreateAccount = true,
                LeadId = _lead2.ToEnreplacedyReference(),
                Status = new OptionSetValue((int)lead_statuscode.Qualified)
            };

            var qualifyLead2Response = (QualifyLeadResponse)_serviceProxy.Execute(
                qualifyLead2Request);

            // Store the generated Account to delete it later.
            foreach (var enreplacedyRef in qualifyLead2Response.CreatedEnreplacedies)
            {
                _generatedEnreplacedies.Add(enreplacedyRef);
            }

            Console.WriteLine("  Lead 2 was qualified.");

            // Qualify lead 3.
            var qualifyLead3Request = new QualifyLeadRequest
            {
                CreateAccount = true,
                LeadId = _lead3.ToEnreplacedyReference(),
                Status = new OptionSetValue((int)lead_statuscode.Qualified)
            };

            var qualifyLead3Response = (QualifyLeadResponse)_serviceProxy.Execute(
                qualifyLead3Request);

            foreach (var enreplacedyRef in qualifyLead3Response.CreatedEnreplacedies)
            {
                _generatedEnreplacedies.Add(enreplacedyRef);
            }

            Console.WriteLine("  Lead 3 was qualified.");
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void DisplayPersonalWallPage(int pageNumber)
        {
            // Retrieve the page of posts.  We'll only retrieve 5 at a time so that
            // we will have more than one page.
            var pageSize = 5;

            var personalWallPageReq = new RetrievePersonalWallRequest
            {
                CommentsPerPost = 2,
                PageNumber = pageNumber,
                PageSize = pageSize
            };
            var personalWallPageRes =
                (RetrievePersonalWallResponse)_serviceProxy.Execute(personalWallPageReq);

            Console.WriteLine("\r\n  Personal Wall Page {0} Posts:", pageNumber);
            foreach (Post post in personalWallPageRes.EnreplacedyCollection.Enreplacedies)
            {
                DisplayPost(post);
            }
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void ActivateRuleConfig(msdyn_PostRuleConfig qualifyLeadRule)
        {
            _serviceProxy.Execute(new SetStateRequest
            {
                EnreplacedyMoniker = qualifyLeadRule.ToEnreplacedyReference(),
                State = new OptionSetValue((int)msdyn_PostRuleConfigState.Active),
                Status = new OptionSetValue((int)msdyn_postruleconfig_statuscode.Active)
            });
        }

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create enreplacedy records
            #region Create or Retrieve the necessary system users

            // Retrieve a sales manager.
            _salesManagerId =
                SystemUserProvider.RetrieveMarketingManager(serviceProxy: _serviceProxy);

            #endregion

            #region Create PhoneCall record and supporting account

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

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

            // Create ActivityPartys for the phone calls' "From" field.
            ActivityParty activityParty = new ActivityParty()
            {
                PartyId = newAccount.ToEnreplacedyReference(),
                ActivityId = new EnreplacedyReference
                {
                    Id = _phoneCallId,
                    LogicalName = PhoneCall.EnreplacedyLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId = newAccount.ToEnreplacedyReference(),
                ActivityId = new EnreplacedyReference
                {
                    Id = _phoneCall2Id,
                    LogicalName = PhoneCall.EnreplacedyLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

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

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

            // Close the second phone call.
            SetStateRequest closePhoneCall = new SetStateRequest()
            {
                EnreplacedyMoniker = phoneCall.ToEnreplacedyReference(),
                State = new OptionSetValue(1),
                Status = new OptionSetValue(4)
            };
            _serviceProxy.Execute(closePhoneCall);
            Console.WriteLine("Required records have been created.");
            #endregion
        }

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these enreplacedy records deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                // TODO Delete enreplacedy records
                #region Delete incidents, accounts and units of measure

                _serviceProxy.Delete(Incident.EnreplacedyLogicalName, _incident.Id);

                _serviceProxy.Delete(Product.EnreplacedyLogicalName, _product.Id);

                _serviceProxy.Delete(Account.EnreplacedyLogicalName, _account.Id);

                _serviceProxy.Delete(UoMSchedule.EnreplacedyLogicalName, _uomSchedule.Id);

                #endregion

                #region Unpublish articles

                foreach (var article in _articles)
                {
                    _serviceProxy.Execute(new SetStateRequest
                    {
                        EnreplacedyMoniker = article.ToEnreplacedyReference(),
                        Status = new OptionSetValue((int)kbarticle_statuscode.Unapproved),
                        State = new OptionSetValue((int)KbArticleState.Unapproved)
                    });
                }

                #endregion

                #region Delete articles

                foreach (var article in _articles)
                    _serviceProxy.Delete(KbArticle.EnreplacedyLogicalName, article.Id);

                #endregion
                Console.WriteLine("Enreplacedy records have been deleted.");
            }
        }

19 Source : SampleMethod.cs
with MIT License
from microsoft

public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create enreplacedy records
            #region Create or Retrieve the necessary system users

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

            #endregion

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

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EnreplacedyName = UoM.EnreplacedyLogicalName,
                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).Enreplacedies[0];
            _defaultUnitId = unit.UoMId.Value;

            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber = "1",
                Name = "Example Product 1",
                ProductStructure = new OptionSetValue(1),
                QuanreplacedyDecimal = 2,
                DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName,
                    _unitGroupId),
                DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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),
                QuanreplacedyDecimal = 3,
                DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName,
                    _unitGroupId),
                DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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 newPriceLisreplacedem1 = new ProductPriceLevel
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product1Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20)
            };
            _priceLisreplacedem1Id = _serviceProxy.Create(newPriceLisreplacedem1);

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

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

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

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

            #endregion Create records to support Opportunity records
            Console.WriteLine("Required records have been created.");
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void PostToPersonalWalls()
        {
            Console.WriteLine("\r\n== Working with Personal Walls ==");
            // Create manual (user) posts on a user's Personal wall.
            var whoAmIRequest = new WhoAmIRequest();
            var whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute(whoAmIRequest);
            var currentUserRef = new EnreplacedyReference(
                SystemUser.EnreplacedyLogicalName, whoAmIResponse.UserId);

            // Create a post that mentions lead 1.
            // The Regarding object should be set to the user whose wall the post should
            // be posted to (we'll just use the current user).
            _post1 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source = new OptionSetValue((int)PostSource.ManualPost),
                Text = String.Format("I'd rather not pursue @[{0},{1},\"{2}\"]",
                    Lead.EnreplacedyTypeCode, _lead1.Id, _lead1.FullName)
            };

            _serviceContext.AddObject(_post1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall post 1 was created.");

            // Create a related comment.
            var comment1 = new PostComment
            {
                PostId = _post1.ToEnreplacedyReference(),
                Text = "Personal wall comment 1."
            };

            _serviceContext.AddObject(comment1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall comment 1 was created.");

            _post2 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source = new OptionSetValue((int)PostSource.AutoPost),
                Text = "Personal wall post 2."
            };

            _serviceContext.AddObject(_post2);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall post 2 was created.");

            // Create a few related comments.
            var comment2 = new PostComment
            {
                PostId = _post2.ToEnreplacedyReference(),
                Text = "Personal wall comment 2."
            };

            var comment3 = new PostComment
            {
                PostId = _post2.ToEnreplacedyReference(),
                Text = "Personal wall comment 3."
            };

            var comment4 = new PostComment
            {
                PostId = _post2.ToEnreplacedyReference(),
                Text = "Personal wall comment 4."
            };

            var comment5 = new PostComment
            {
                PostId = _post2.ToEnreplacedyReference(),
                Text = "Personal wall comment 5."
            };

            _serviceContext.AddObject(comment2);
            _serviceContext.AddObject(comment3);
            _serviceContext.AddObject(comment4);
            _serviceContext.AddObject(comment5);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall comments 2, 3, 4, and 5 were created.");

            // Create a couple more posts just to show how paging works.
            _post3 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source = new OptionSetValue((int)PostSource.ManualPost),
                Text = "Personal wall post 3."
            };

            _post4 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source = new OptionSetValue((int)PostSource.AutoPost),
                Text = "Personal wall post 4."
            };

            _serviceContext.AddObject(_post3);
            _serviceContext.AddObject(_post4);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall posts 3 and 4 were created.");

            // Retrieve this user's personal wall.
            // Retrieve the first page of posts.
            DisplayPersonalWallPage(1);

            // Retrieve the second page of posts.
            DisplayPersonalWallPage(2);

            // Sleep for a second so that the time of the newly created comment will
            // clearly be later than the previously created posts/comments (otherwise
            // Post 3 will not be escalated to the top of the wall).
            Thread.Sleep(1000);

            // Create a new comment on the last post, which will bring the post to the
            // top.
            var newPostComment = new PostComment
            {
                PostId = _post3.ToEnreplacedyReference(),
                Text = "New comment to show that new comments affect post ordering."
            };

            _serviceContext.AddObject(newPostComment);
            _serviceContext.SaveChanges();
            Console.WriteLine("\r\n  A new comment was created to show effects on post ordering.");

            // Display the first page of the personal wall to showcase the change in
            // ordering.  Post 3 should be at the top.
            DisplayPersonalWallPage(1);

            // Show paging of comments.
            // Retrieve comments 2 at a time, starting with page 1.
            var commentsQuery = new QueryExpression(PostComment.EnreplacedyLogicalName)
            {
                ColumnSet = new ColumnSet(true),
                Criteria = new FilterExpression(LogicalOperator.And),
                PageInfo = new PagingInfo
                {
                    Count = 2,
                    PageNumber = 1,
                    ReturnTotalRecordCount = true
                }
            };

            commentsQuery.Criteria.AddCondition(
                "postid", ConditionOperator.Equal, _post2.Id);

            // Continue querying for comments until there are no further comments to
            // be retrieved.
            EnreplacedyCollection commentsResult;
            do
            {
                commentsResult = _serviceProxy.RetrieveMultiple(commentsQuery);

                // Display the comments that we retrieved.
                Console.WriteLine("\r\n  Comments for lead 2 page {0}",
                    commentsQuery.PageInfo.PageNumber);
                foreach (PostComment comment in commentsResult.Enreplacedies)
                {
                    DisplayComment(comment);
                }

                commentsQuery.PageInfo.PageNumber += 1;
            }
            while (commentsResult.MoreRecords);
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void DisplayRecordWall(Lead lead)
        {
            // Display the first page of the record wall.
            var retrieveRecordWallReq = new RetrieveRecordWallRequest
            {
                Enreplacedy = lead.ToEnreplacedyReference(),
                CommentsPerPost = 2,
                PageSize = 10,
                PageNumber = 1
            };

            var retrieveRecordWallRes =
                (RetrieveRecordWallResponse)_serviceProxy.Execute(retrieveRecordWallReq);

            Console.WriteLine("\r\n  Posts for lead {0}:", lead.FullName);
            foreach (Post post in retrieveRecordWallRes.EnreplacedyCollection.Enreplacedies)
            {
                DisplayPost(post);
            }
        }

19 Source : DumpAttributeInfo.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpAttributeInfo1>
                    #region How to dump attribute info
                    //<snippetDumpAttributeInfo2>
                    RetrieveAllEnreplacediesRequest request = new RetrieveAllEnreplacediesRequest()
                    {
                        EnreplacedyFilters = EnreplacedyFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEnreplacediesResponse response = (RetrieveAllEnreplacediesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
		    // To view this file, right click the file and choose open with Excel. 
		    // Excel will figure out the schema and display the information in columns.
                    String filename = String.Concat("AllAttributeDesc.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDoreplacedent();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EnreplacedyMetadata currentEnreplacedy in response.EnreplacedyMetadata)
                        {

                            //if (currentEnreplacedy.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Enreplacedy Node
                                metadataWriter.WriteStartElement("Enreplacedy");

                                // Write the Enreplacedy's Information.
                                metadataWriter.WriteElementString("EnreplacedySchemaName", currentEnreplacedy.SchemaName);
                                if (currentEnreplacedy.IsCustomizable.Value == true)
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                else
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                if (currentEnreplacedy.IsIntersect.Value == true)
                                    metadataWriter.WriteElementString("IsIntersect", "yes");
                                else
                                    metadataWriter.WriteElementString("IsIntersect", "no");



                                #region Attributes


                                // Write Enreplacedy's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEnreplacedy.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {

                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName);
                                        // Write the Description if it is set.
                                        if (currentAttribute.Description.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString());
                                        }

                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());
                                        if (currentAttribute.DisplayName.UserLocalizedLabel != null)
                                            metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString());
                                        if (currentAttribute.SchemaName != null)
                                            metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString());
                                        if (currentAttribute.IntroducedVersion != null)
                                            metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString());
                                        if (currentAttribute.DeprecatedVersion != null)
                                            metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString());
                                        if (currentAttribute.IsCustomAttribute != null)
                                            metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString());
                                        if (currentAttribute.IsCustomizable != null)
                                            metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString());
                                        if (currentAttribute.RequiredLevel != null)
                                            metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString());
                                        if (currentAttribute.IsValidForCreate != null)
                                            metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString());
                                        if (currentAttribute.IsValidForRead != null)
                                            metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString());
                                        if (currentAttribute.IsValidForUpdate != null)
                                            metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString());
                                        if (currentAttribute.CanBeSecuredForCreate != null)
                                            metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString());
                                        if (currentAttribute.CanBeSecuredForRead != null)
                                            metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString());
                                        if (currentAttribute.CanBeSecuredForUpdate != null)
                                            metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString());
                                        if (currentAttribute.IsAuditEnabled != null)
                                            metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString());
                                        if (currentAttribute.IsManaged != null)
                                            metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString());
                                        if (currentAttribute.IsPrimaryId != null)
                                            metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString());
                                        if (currentAttribute.IsPrimaryName != null) 
                                            metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString());
                                        if (currentAttribute.IsRenameable != null)
                                            metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString());
                                        if (currentAttribute.IsSecured != null)
                                            metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString());
                                        if (currentAttribute.IsValidForAdvancedFind != null) 
                                            metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString());

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Enreplacedy Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDoreplacedent();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpAttributeInfo2>
                    #endregion How to dump attribute info



                   Console.WriteLine("Done.");
                    //</snippetDumpAttributeInfo1>

                    //DeleteRequiredRecords(promptForDelete);
                }
            }

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

19 Source : DeliverPromoteEmail.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();
                    
                    // Create a contact to send an email to (To: field)
                    Contact emailContact = new Contact()
                    {
                        FirstName = "Lisa",
                        LastName = "Andrews",
                        EMailAddress1 = "[email protected]"
                    };
                    _contactId = _serviceProxy.Create(emailContact);
                    Console.WriteLine("Created a sample contact.");

                    // Get a system user to send the email (From: field)
                    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                    WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);

                    ColumnSet cols = new ColumnSet("internalemailaddress");
                    SystemUser emailSender = (SystemUser)_serviceProxy.Retrieve(SystemUser.EnreplacedyLogicalName, systemUserResponse.UserId, cols);

                    //<snippetDeliverPromoteEmail1>

                    // Create the request.
                    DeliverPromoteEmailRequest deliverEmailRequest = new DeliverPromoteEmailRequest
                    {
                        Subject = "SDK Sample Email",
                        To = emailContact.EMailAddress1,
                        From = emailSender.InternalEMailAddress,
                        Bcc = String.Empty,
                        Cc = String.Empty,
                        Importance = "high",
                        Body = "This message will create an email activity.",
                        MessageId = Guid.NewGuid().ToString(),
                        SubmittedBy = "",
                        ReceivedOn = DateTime.Now
                    };                    

                    // We won't attach a file to the email, but the Attachments property is required.
                    deliverEmailRequest.Attachments = new EnreplacedyCollection(new ActivityMimeAttachment[0]);
                    deliverEmailRequest.Attachments.EnreplacedyName = ActivityMimeAttachment.EnreplacedyLogicalName;                    

                    // Execute the request.
                    DeliverPromoteEmailResponse deliverEmailResponse = (DeliverPromoteEmailResponse)_serviceProxy.Execute(deliverEmailRequest);

                    // Verify the success.
                    
                    // Define an anonymous type to define the possible values for
                    // email status
                    var EmailStatus = new
                    {
                        Draft = 1,
                        Completed = 2,
                        Sent = 3,
                        Received = 3,
                        Canceled = 5,
                        PendingSend = 6,
                        Sending = 7,
                        Failed = 8,
                    };

                    // Query for the delivered email, and verify the status code is "Sent".
                    ColumnSet deliveredMailColumns = new ColumnSet("statuscode");
                    Email deliveredEmail = (Email)_serviceProxy.Retrieve(Email.EnreplacedyLogicalName, deliverEmailResponse.EmailId, deliveredMailColumns);

                    _emailId = deliveredEmail.ActivityId.Value;
                    
                    if (deliveredEmail.StatusCode.Value == EmailStatus.Sent)
                    {
                        Console.WriteLine("Successfully created and delivered the e-mail message.");
                    }                   

                    //</snippetDeliverPromoteEmail1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

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

19 Source : SendEmailUsingTemplate.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Create a contact to send an email to (To: field)
            Contact emailContact = new Contact
            {
                FirstName = "David",
                LastName = "Pelton",
                EMailAddress1 = "[email protected]",
                DoNotEMail = false
            };
            _contactId = _serviceProxy.Create(emailContact);
            Console.WriteLine("Created a sample contact.");

            // Get a system user to send the email (From: field)
            WhoAmIRequest systemUserRequest = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);
            _userId = systemUserResponse.UserId;
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void PublishSystemUserAndLead()
        {
            // The systemuser and lead enreplacedies must be published because otherwise the
            // record walls on the respective forms will not update.
            _serviceProxy.Execute(new PublishXmlRequest
            {
                ParameterXml = @"
                    <importexportxml>
                        <enreplacedies>
                            <enreplacedy>systemuser</enreplacedy>
                            <enreplacedy>lead</enreplacedy>
                        </enreplacedies>
                    </importexportxml>"
            });
            Console.WriteLine("  The systemuser and lead enreplacedies were published.");
        }

19 Source : DumpPicklistInfo.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpPicklistInfo1>
                    #region How to dump attribute info
                    //<snippetDumpPicklistInfo2>
                    RetrieveAllEnreplacediesRequest request = new RetrieveAllEnreplacediesRequest()
                    {
                        EnreplacedyFilters = EnreplacedyFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false

                    };

                    // Retrieve the MetaData.
                    RetrieveAllEnreplacediesResponse response = (RetrieveAllEnreplacediesResponse)_serviceProxy.Execute(request);
                    
                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
		    // To view this file, right click the file and choose open with Excel. 
		    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDoreplacedent();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EnreplacedyMetadata currentEnreplacedy in response.EnreplacedyMetadata)
                        {
                            
                            if (currentEnreplacedy.IsIntersect.Value == false)
                            {
                                // Start Enreplacedy Node
                                metadataWriter.WriteStartElement("Enreplacedy");

                                // Write the Enreplacedy's Information.
                                metadataWriter.WriteElementString("EnreplacedySchemaName", currentEnreplacedy.SchemaName);
                                if (currentEnreplacedy.IsCustomizable.Value == true)
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                else
                                    metadataWriter.WriteElementString("IsCustomizable", "no");

                                #region Attributes

                                // Write Enreplacedy's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEnreplacedy.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {

                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();

                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Enreplacedy Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDoreplacedent();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpPicklistInfo2>
                    #endregion How to dump attribute info



                   Console.WriteLine("Done.");
                    //</snippetDumpPicklistInfo1>

                    //DeleteRequiredRecords(promptForDelete);
                }
            }

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

19 Source : StateModelTransitions.cs
with MIT License
from microsoft

public List<StatusOption> GetValidStatusOptions(String enreplacedyLogicalName, int currentStatusValue)
  {

   List<StatusOption> validStatusOptions = new List<StatusOption>();

   //Check enreplacedy Metadata

   //Retrieve just one enreplacedy definition
   MetadataFilterExpression enreplacedyFilter = new MetadataFilterExpression(LogicalOperator.And);
   enreplacedyFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, enreplacedyLogicalName));
   //Return the attributes and the EnforceStateTransitions property
   MetadataPropertiesExpression enreplacedyProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

   //Retrieve only State or Status attributes
   MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

   //Retrieve only the OptionSet property of the attributes
   MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

   //Set the query
   EnreplacedyQueryExpression query = new EnreplacedyQueryExpression()
   {
    Criteria = enreplacedyFilter,
    Properties = enreplacedyProperties,
    AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
   };

   //Retrieve the metadata
   RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
   RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

   //Check the value of EnforceStateTransitions
   Boolean? EnforceStateTransitions = response.EnreplacedyMetadata[0].EnforceStateTransitions;

   //Capture the state and status attributes
   StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
   StateAttributeMetadata stateAttribute = new StateAttributeMetadata();

   foreach (AttributeMetadata attributeMetadata in response.EnreplacedyMetadata[0].Attributes)
   {
    switch (attributeMetadata.AttributeType)
    {
     case AttributeTypeCode.Status:
      statusAttribute = (StatusAttributeMetadata)attributeMetadata;
      break;
     case AttributeTypeCode.State:
      stateAttribute = (StateAttributeMetadata)attributeMetadata;
      break;
    }
   }


   if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
   {
    //When EnforceStateTransitions is true use the TransitionData to filter the valid options
    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value == currentStatusValue)
     {
      if (option.TransitionData != String.Empty)
      {
       XDoreplacedent transitionData = XDoreplacedent.Parse(option.TransitionData);

       IEnumerable<XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

       foreach (XElement e in elements)
       {
        int statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
        String statusLabel = GetOptionSetLabel(statusAttribute, statusOptionValue);

        string stateLabel = String.Empty;
        int? stateValue = null;
        foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
        {
         if (statusOption.Value.Value == statusOptionValue)
         {
          stateValue = statusOption.State.Value;
          stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
         }

        }


        validStatusOptions.Add(new StatusOption()
        {
         StateLabel = stateLabel,
         StateValue = stateValue.Value,
         StatusLabel = statusLabel,
         StatusValue = option.Value.Value
        });
       }
      }
     }
    }

   }
   else
   {
    ////When EnforceStateTransitions is false do not filter the available options

    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value != currentStatusValue)
     {

      String statusLabel = "";
      try
      {
       statusLabel = option.Label.UserLocalizedLabel.Label;
      }
      catch (Exception)
      {
       statusLabel = option.Label.LocalizedLabels[0].Label;
      };

      String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

      validStatusOptions.Add(new StatusOption()
      {
       StateLabel = stateLabel,
       StateValue = option.State.Value,
       StatusLabel = statusLabel,
       StatusValue = option.Value.Value

      });
     }
    }
   }
   return validStatusOptions;

  }

19 Source : WorkWithAttributes.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetWorkWithAttributes1>
                    #region How to create attributes
                    //<snippetWorkWithAttributes2>
                    // Create storage for new attributes being created
                    addedAttributes = new List<AttributeMetadata>();

                    // Create a boolean attribute
                    BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_boolean",
                        DisplayName = new Label("Sample Boolean", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Boolean Attribute", _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", _languageCode), 1),
                            new OptionMetadata(new Label("False", _languageCode), 0)
                            )
                    };

                    // Add to list
                    addedAttributes.Add(boolAttribute);

                    // Create a date time attribute
                    DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_datetime",
                        DisplayName = new Label("Sample DateTime", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("DateTime Attribute", _languageCode),
                        // Set extended properties
                        Format = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(dtAttribute);

                    // Create a decimal attribute	
                    DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_decimal",
                        DisplayName = new Label("Sample Decimal", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Decimal Attribute", _languageCode),
                        // Set extended properties
                        MaxValue = 100,
                        MinValue = 0,
                        Precision = 1
                    };

                    // Add to list
                    addedAttributes.Add(decimalAttribute);

                    // Create a integer attribute	
                    IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_integer",
                        DisplayName = new Label("Sample Integer", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Integer Attribute", _languageCode),
                        // Set extended properties
                        Format = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };

                    // Add to list
                    addedAttributes.Add(integerAttribute);

                    // Create a memo attribute 
                    MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_memo",
                        DisplayName = new Label("Sample Memo", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Memo Attribute", _languageCode),
                        // Set extended properties
                        Format = StringFormat.TextArea,
                        ImeMode = ImeMode.Disabled,
                        MaxLength = 500
                    };

                    // Add to list
                    addedAttributes.Add(memoAttribute);

                    // Create a money attribute	
                    MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_money",
                        DisplayName = new Label("Money Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Money Attribue", _languageCode),
                        // Set extended properties
                        MaxValue = 1000.00,
                        MinValue = 0.00,
                        Precision = 1,
                        PrecisionSource = 1,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(moneyAttribute);

                    // Create a picklist attribute	
                    PicklistAttributeMetadata pickListAttribute =
                        new PicklistAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_picklist",
                        DisplayName = new Label("Sample Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Picklist Attribute", _languageCode),
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = false,
                                OptionSetType = OptionSetType.Picklist,
                                Options = 
                            {
                                new OptionMetadata(
                                    new Label("Created", _languageCode), null),
                                new OptionMetadata(
                                    new Label("Updated", _languageCode), null),
                                new OptionMetadata(
                                    new Label("Deleted", _languageCode), null)
                            }
                            }
                    };

                    // Add to list
                    addedAttributes.Add(pickListAttribute);

                    // Create a string attribute
                    StringAttributeMetadata stringAttribute = new StringAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_string",
                        DisplayName = new Label("Sample String", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("String Attribute", _languageCode),
                        // Set extended properties
                        MaxLength = 100
                    };

                    // Add to list
                    addedAttributes.Add(stringAttribute);

                    // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
                    // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

                    // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

                    foreach (AttributeMetadata anAttribute in addedAttributes)
                    {
                        // Create the request.
                        CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
                        {
                            EnreplacedyName = Contact.EnreplacedyLogicalName,
                            Attribute = anAttribute
                        };

                        // Execute the request.
                        _serviceProxy.Execute(createAttributeRequest);

                        Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
                    }
                    //</snippetWorkWithAttributes2>
                    #endregion How to create attributes

                    #region How to insert status
                    //<snippetWorkWithAttributes3>
                    // Use InsertStatusValueRequest message to insert a new status 
                    // in an existing status attribute. 
                    // Create the request.
                    InsertStatusValueRequest insertStatusValueRequest =
                        new InsertStatusValueRequest
                    {
                        AttributeLogicalName = "statuscode",
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        Label = new Label("Dormant", _languageCode),
                        StateCode = 0
                    };

                    // Execute the request and store newly inserted value 
                    // for cleanup, used later part of this sample. 
                    _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute(
                        insertStatusValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertStatusValueRequest.Label.LocalizedLabels[0].Label,
                        _insertedStatusValue);
                    //</snippetWorkWithAttributes3>
                    #endregion How to insert status

                    #region How to retrieve attribute
                    //<snippetWorkWithAttributes4>
                    // Create the request
                    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                    {
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        LogicalName = "new_string",
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false

                    };

                    // Execute the request
                    RetrieveAttributeResponse attributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

                    Console.WriteLine("Retrieved the attribute {0}.",
                        attributeResponse.AttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes4>
                    #endregion How to retrieve attribute
                    
                    #region How to update attribute
                    //<snippetWorkWithAttributes5>
                    // Modify the retrieved attribute
                    AttributeMetadata retrievedAttributeMetadata =
                        attributeResponse.AttributeMetadata;
                    retrievedAttributeMetadata.DisplayName =
                        new Label("Update String Attribute", _languageCode);

                    // Update an attribute retrieved via RetrieveAttributeRequest
                    UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
                    {
                        Attribute = retrievedAttributeMetadata,
                        EnreplacedyName = Contact.EnreplacedyLogicalName,
                        MergeLabels = false
                    };

                    // Execute the request
                    _serviceProxy.Execute(updateRequest);

                    Console.WriteLine("Updated the attribute {0}.",
                        retrievedAttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes5>
                    #endregion How to update attribute

                    #region How to update state value
                    //<snippetWorkWithAttributes6>
                    // Modify the state value label from Active to Open.
                    // Create the request.
                    UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
                    {
                        AttributeLogicalName = "statecode",
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        Value = 1,
                        Label = new Label("Open", _languageCode)
                    };

                    // Execute the request.
                    _serviceProxy.Execute(updateStateValue);

                    Console.WriteLine(
                        "Updated {0} state attribute of {1} enreplacedy from 'Active' to '{2}'.",
                        updateStateValue.AttributeLogicalName,
                        updateStateValue.EnreplacedyLogicalName,
                        updateStateValue.Label.LocalizedLabels[0].Label
                        );
                    //</snippetWorkWithAttributes6>
                    #endregion How to update state value

                    #region How to insert a new option item in a local option set
                    //<snippetWorkWithAttributes7>
                    // Create a request.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        AttributeLogicalName = "new_picklist",
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        Label = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request.
                    int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                        insertOptionValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                        insertOptionValue);
                    //</snippetWorkWithAttributes7>
                    #endregion How to insert a new option item in a local option set

                    #region How to change the order of options of a local option set
                    //<snippetWorkWithAttributes8>
                    // Use the RetrieveAttributeRequest message to retrieve  
                    // a attribute by it's logical name.
                    RetrieveAttributeRequest retrieveAttributeRequest =
                        new RetrieveAttributeRequest
                    {
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        LogicalName = "new_picklist",
                            // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                            // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                            RetrieveAsIfPublished = false

                        };

                    // Execute the request.
                    RetrieveAttributeResponse retrieveAttributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(
                        retrieveAttributeRequest);

                    // Access the retrieved attribute.
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)
                        retrieveAttributeResponse.AttributeMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in  
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        AttributeLogicalName = "new_picklist",
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        // Set the changed order using Select linq function 
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    Console.WriteLine("Option Set option order changed");
                    //</snippetWorkWithAttributes8>
                    #endregion How to change the order of options of a global option set

                    // NOTE: All customizations must be published before they can be used.
                    _serviceProxy.Execute(new PublishAllXmlRequest());
                    Console.WriteLine("Published all customizations.");
                    //</snippetWorkWithAttributes1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

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

19 Source : SystemUserProvider.cs
with MIT License
from microsoft

private static Guid CreateSystemUser(String userName, String firstName,
            String lastName, String domain, String roleStr,
            OrganizationServiceProxy serviceProxy, ref String ldapPath)
        {
            CreateADAccount(userName, firstName, lastName, serviceProxy, ref ldapPath);

            // Retrieve the default business unit needed to create the user.
            QueryExpression businessUnitQuery = new QueryExpression
            {
                EnreplacedyName = BusinessUnit.EnreplacedyLogicalName,
                ColumnSet = new ColumnSet("businessunitid"),
                Criteria =
                {
                    Conditions =
                    {
                        new ConditionExpression("parentbusinessunitid", 
                            ConditionOperator.Null)
                    }
                }
            };

            BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple(
                businessUnitQuery).Enreplacedies[0].ToEnreplacedy<BusinessUnit>();

            //Create a new system user.
            SystemUser user = new SystemUser
            {
                DomainName = domain + userName,
                FirstName = firstName,
                LastName = lastName,
                BusinessUnitId = new EnreplacedyReference
                {
                    LogicalName = BusinessUnit.EnreplacedyLogicalName,
                    Name = BusinessUnit.EnreplacedyLogicalName,
                    Id = defaultBusinessUnit.Id
                }
            };
            Guid userId = serviceProxy.Create(user);

            if (!String.IsNullOrWhiteSpace(roleStr))
            {
                // Retrieve the specified security role.
                Role role = RetrieveRoleByName(serviceProxy, roleStr);

                // replacedign the security role to the newly created Microsoft Dynamics CRM user.
                replacedociateRequest replacedociate = new replacedociateRequest()
                {
                    Target = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, userId),
                    RelatedEnreplacedies = new EnreplacedyReferenceCollection()
                {
                    new EnreplacedyReference(Role.EnreplacedyLogicalName, role.Id),
                },
                    Relationship = new Relationship("systemuserroles_replacedociation")
                };
                serviceProxy.Execute(replacedociate);
            }
            return userId;
        }

19 Source : UserAccessAuditing.cs
with MIT License
from microsoft

public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want to delete the account record? (y/n) [y]: ");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
            }

            if (deleteRecords)
            {
                _serviceProxy.Delete(Account.EnreplacedyLogicalName, _newAccountId);
                Console.WriteLine("The account record has been deleted.");
            }

            if (prompt)
            {
                Console.WriteLine("\nDo you want to delete ALL audit records? (y/n) [n]: ");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                // Get the list of audit parreplacedions.
                RetrieveAuditParreplacedionListResponse parreplacedionRequest =
                    (RetrieveAuditParreplacedionListResponse)_serviceProxy.Execute(new RetrieveAuditParreplacedionListRequest());
                AuditParreplacedionDetailCollection parreplacedions = parreplacedionRequest.AuditParreplacedionDetailCollection;

                // Create a delete request with an end date earlier than possible.
                DeleteAuditDataRequest deleteRequest = new DeleteAuditDataRequest();
                deleteRequest.EndDate = new DateTime(2000, 1, 1);

                // Check if parreplacedions are not supported as is the case with SQL Server Standard edition.
                if (parreplacedions.IsLogicalCollection)
                {
                    // Delete all audit records created up until now.
                    deleteRequest.EndDate = DateTime.Now;
                }

                // Otherwise, delete all parreplacedions that are older than the current parreplacedion.
                // Hint: The parreplacedions in the collection are returned in sorted order where the 
                // parreplacedion with the oldest end date is at index 0.  Also, if the parreplacedion's
                // end date is greater than the current date, neither the parreplacedion nor any
                // audit records contained in the parreplacedion can be deleted.
                else
                {
                    for (int n = parreplacedions.Count - 1; n >= 0; --n)
                    {
                        if (parreplacedions[n].EndDate <= DateTime.Now && parreplacedions[n].EndDate > deleteRequest.EndDate)
                        {
                            deleteRequest.EndDate = (DateTime)parreplacedions[n].EndDate;
                            break;
                        }
                    }
                }

                // Delete the audit records.
                if (deleteRequest.EndDate != new DateTime(2000, 1, 1))
                {
                    _serviceProxy.Execute(deleteRequest);
                    Console.WriteLine("Audit records have been deleted.");
                }
                else
                    Console.WriteLine("There were no audit records that could be deleted.");
            }
        }

19 Source : ConvertFaxToTask.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Get the current user.
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
            _userId = userResponse.UserId;

            // Create the activity party for sending and receiving the fax.
            ActivityParty party = new ActivityParty
            {
                PartyId = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, _userId)
            };

            // Create the fax object.
            Fax fax = new Fax
            {
                Subject = "Sample Fax",
                From = new ActivityParty[] { party },
                To = new ActivityParty[] { party }
            };
            _faxId = _serviceProxy.Create(fax);
            Console.WriteLine("Created a fax: '{0}'.", fax.Subject);
        }

19 Source : SendEmail.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetSendEmail1>

                    // Use the SendEmail message to send an e-mail message.
                    SendEmailRequest sendEmailreq = new SendEmailRequest
                    {
                        EmailId = _emailId,
                        TrackingToken = "",
                        IssueSend = true
                    };

                    SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);
                    Console.WriteLine("Sent the e-mail message.");              

                    //</snippetSendEmail1>

                    DeleteRequiredRecords(promptforDelete);
                }
            }

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

19 Source : SendEmailUsingTemplate.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();                    

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetSendEmailUsingTemplate1>

                    // Create the 'From:' activity party for the email
                    ActivityParty fromParty = new ActivityParty
                    {
                        PartyId = new EnreplacedyReference(SystemUser.EnreplacedyLogicalName, _userId)
                    };

                    // Create the 'To:' activity party for the email
                    ActivityParty toParty = new ActivityParty
                    {
                        PartyId = new EnreplacedyReference(Contact.EnreplacedyLogicalName, _contactId)
                    };

                    Console.WriteLine("Created activity parties.");

                    // Create an e-mail message.
                    Email email = new Email
                    {
                        To = new ActivityParty[] { toParty },
                        From = new ActivityParty[] { fromParty },
                        Subject = "SDK Sample e-mail",
                        Description = "SDK Sample for SendEmailFromTemplate Message.",
                        DirectionCode = true
                    };

                    //Create a query expression to get one of Email Template of type "contact"

                    QueryExpression queryBuildInTemplates = new QueryExpression{
                        EnreplacedyName = "template",
                        ColumnSet = new ColumnSet("templateid", "templatetypecode"),
                        Criteria = new FilterExpression()
                    };
                    queryBuildInTemplates.Criteria.AddCondition("templatetypecode",
                        ConditionOperator.Equal, "contact");
                    EnreplacedyCollection templateEnreplacedyCollection = _serviceProxy.RetrieveMultiple(queryBuildInTemplates);

                    if (templateEnreplacedyCollection.Enreplacedies.Count > 0) 
                    {
                        _templateId = (Guid)templateEnreplacedyCollection.Enreplacedies[0].Attributes["templateid"];
                    }
                    else
                    {
                        throw new ArgumentException("Standard Email Templates are missing");
                    }             

                    // Create the request
                    SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
                    {
                        Target = email,

                        // Use a built-in Email Template of type "contact".
                        TemplateId = _templateId,

                        // The regarding Id is required, and must be of the same type as the Email Template.
                        RegardingId = _contactId,
                        RegardingType = Contact.EnreplacedyLogicalName
                    };

                    SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);

                    // Verify that the e-mail has been created
                    _emailId = emailUsingTemplateResp.Id;
                    if (!_emailId.Equals(Guid.Empty))
                    {
                        Console.WriteLine("Successfully sent an e-mail message using the template.");
                    }

                    //</snippetSendEmailUsingTemplate1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

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

19 Source : AuthenticateWithNoHelp.cs
with MIT License
from microsoft

public void Run()
        {
            //<snippetAuthenticateWithNoHelp1>
            IServiceManagement<IDiscoveryService> serviceManagement =
                        ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
                        new Uri(_discoveryServiceAddress));

            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            // Set the credentials.
            AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);


            String organizationUri = String.Empty;
            // Get the discovery service proxy.
            using (DiscoveryServiceProxy discoveryProxy =
                GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                // Obtain organization information from the Discovery service. 
                if (discoveryProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
                    // Obtains the Web address (Uri) of the target organization.
                    organizationUri = FindOrganization(_organizationUniqueName,
                        orgs.ToArray()).Endpoints[EndpointType.OrganizationService];

                }
            }
            //</snippetAuthenticateWithNoHelp1>


            if (!String.IsNullOrWhiteSpace(organizationUri))
            {
                //<snippetAuthenticateWithNoHelp3>
                IServiceManagement<IOrganizationService> orgServiceManagement =
                    ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
                    new Uri(organizationUri));

                // Set the credentials.
                AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);

                // Get the organization service proxy.
                using (OrganizationServiceProxy organizationProxy =
                    GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
                {
                    // This statement is required to enable early-bound type support.
                    organizationProxy.EnableProxyTypes();

                    // Now make an SDK call with the organization service proxy.
                    // Display information about the logged on user.
                    Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
                        new WhoAmIRequest())).UserId;
                    SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
                        new ColumnSet(new string[] { "firstname", "lastname" })).ToEnreplacedy<SystemUser>();
                    Console.WriteLine("Logged on user is {0} {1}.",
                        systemUser.FirstName, systemUser.LastName);
                }
                //</snippetAuthenticateWithNoHelp3>
            }

        }

19 Source : BulkDeleteOperations.cs
with MIT License
from microsoft

private void PerformBulkDelete(bool useRecurrence, bool promptToDelete)
        {
            try
            {
                Console.WriteLine("Performing Bulk Delete Operation");

                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var userRequest = new WhoAmIRequest();
                var userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                Console.WriteLine("  Requesting user retrieved.");

                // Create a condition for a bulk delete request.
                // NOTE: If no records are found that match this condition, the bulk delete
                // will not fail.  It will succeed with 0 successes and 0 failures.
                var deleteCondition = new ConditionExpression(
                    "name", ConditionOperator.Equal, "Fourth Coffee");

                // Create a fiter expression for the bulk delete request.
                var deleteFilter = new FilterExpression();
                deleteFilter.Conditions.Add(deleteCondition);

                // Create the bulk delete query set.
                var bulkDeleteQuery = new QueryExpression
                {
                    EnreplacedyName = Account.EnreplacedyLogicalName,
                    Distinct = false,
                    Criteria = deleteFilter
                };

                // Create the bulk delete request.
                var bulkDeleteRequest = new BulkDeleteRequest
                {
                    JobName = "Sample Bulk Delete",
                    QuerySet = new[] { bulkDeleteQuery },
                    StartDateTime = DateTime.Now,
                    ToRecipients = new[] { currentUserId },
                    CCRecipients = new Guid[] {},
                    SendEmailNotification = true,
                    RecurrencePattern = String.Empty
                    
                };

                // Create a recurring BulkDeleteOperation.
                if (useRecurrence)
                {
                    bulkDeleteRequest.RecurrencePattern = "FREQ=DAILY;INTERVAL=1;";
                }

                // Submit the bulk delete job.
                // NOTE: Because this is an asynchronous operation, the response will be
                // immediate.
                var bulkDeleteResponse =
                    (BulkDeleteResponse)_serviceProxy.Execute(bulkDeleteRequest);
                _asyncOperationId = bulkDeleteResponse.JobId;

                Console.WriteLine("  The Bulk Delete Request was made and the Bulk\n" +
                                  "    Delete Operation should be created.");

                // To monitor the asynchronous operation, retrieve the
                // bulkdeleteoperation object.
                // NOTE: There will be a period of time from when the async operation
                // request was submitted to the time when a successful query for that
                // async operation can be made.  When using plug-ins, events can be
                // subscribed to that will fire when the async operation status changes.
                var bulkQuery = new QueryByAttribute();
                bulkQuery.ColumnSet = new ColumnSet(true);
                bulkQuery.EnreplacedyName = BulkDeleteOperation.EnreplacedyLogicalName;

                // NOTE: When the bulk delete operation was submitted, the GUID that was
                // returned was the asyncoperationid, not the bulkdeleteoperationid.
                bulkQuery.Attributes.Add("asyncoperationid");
                bulkQuery.Values.Add(bulkDeleteResponse.JobId);

                // With only the asyncoperationid at this point, a RetrieveMultiple is
                // required to get the bulk delete operation created above.
                var enreplacedyCollection =
                    _serviceProxy.RetrieveMultiple(bulkQuery);
                BulkDeleteOperation createdBulkDeleteOperation = null;
                
                // When creating a recurring BulkDeleteOperation, the BulkDeleteOperation
                // will be in suspended status after the current instance has completed.
                // When creating a non-recurring BulkDeleteOperation, it will be in
                // Completed status when it is finished.
                var bulkOperationEnded = useRecurrence
                    ? BulkDeleteOperationState.Suspended
                    : BulkDeleteOperationState.Completed;

                createdBulkDeleteOperation = RetrieveBulkDeleteOperation(
                    bulkQuery, enreplacedyCollection, bulkOperationEnded);
                _bulkDeleteOperationId = createdBulkDeleteOperation.Id;

                if (createdBulkDeleteOperation != null)
                {
                    // If the BulkDeleteOperation is recurring, the status will be
                    // "Waiting" after the operation completes this instance.  If it is
                    // non-recurring, the status will be "Succeeded".
                    var bulkOperationSuccess = useRecurrence
                        ? bulkdeleteoperation_statuscode.Waiting
                        : bulkdeleteoperation_statuscode.Succeeded;

                    InspectBulkDeleteOperation(createdBulkDeleteOperation,
                        bulkOperationEnded, bulkOperationSuccess, useRecurrence);

                    DeleteRecords(promptToDelete);
                }
                else
                {
                    Console.WriteLine("  The Bulk Delete Operation could not be retrieved.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
        }

19 Source : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

private void RevertPostConfig(msdyn_PostConfig originalConfig,
            msdyn_PostConfig newConfig)
        {
            if (originalConfig != null)
            {
                // Revert the rule configs.
                foreach (var rule in _postRuleConfigs.Where(
                    x => x.msdyn_PostConfigId.Id == newConfig.msdyn_PostConfigId))
                {
                    // Set the state to the original value.
                    _serviceProxy.Execute(new SetStateRequest
                    {
                        EnreplacedyMoniker = rule.ToEnreplacedyReference(),
                        State = new OptionSetValue((int)rule.statecode),
                        Status = rule.statuscode
                    });
                }

                // Update the config to the values from the original config.
                // Make sure the context is not tracking the new config and is tracking
                // the original config.
                if (!_serviceContext.IsAttached(originalConfig))
                {
                    if (_serviceContext.IsAttached(newConfig))
                    {
                        _serviceContext.Detach(newConfig);
                    }
                    _serviceContext.Attach(originalConfig);
                }
                _serviceContext.UpdateObject(originalConfig);
                _serviceContext.SaveChanges();
                Console.WriteLine(
                    "  The {0} activity feed configuration was reverted.",
                    originalConfig.msdyn_EnreplacedyName);
            }
            else
            {
                _serviceProxy.Delete(newConfig.LogicalName,
                    newConfig.Id);
                Console.WriteLine(
                    "  The {0} activity feed configuration was deleted.",
                    newConfig.msdyn_EnreplacedyName);
            }
        }

19 Source : AddPrincipalToQueue.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            var QueueViewType = new
            {
                Public = 0,
                Private = 1
            };
            // Create a queue instance and set its property values.
            Queue newQueue = new Queue
            {
                Name = "Example Queue",
                Description = "This is an example queue.",
                QueueViewType = new OptionSetValue(QueueViewType.Private)
            };

            // Create a new queue and store its returned GUID in a variable for later use.
            _queueId = _serviceProxy.Create(newQueue);
            Console.WriteLine("Created {0}", newQueue.Name);

            // Retrieve the default business unit for the creation of the team and role.
            QueryExpression queryDefaultBusinessUnit = new QueryExpression
            {
                EnreplacedyName = BusinessUnit.EnreplacedyLogicalName,
                ColumnSet = new ColumnSet("businessunitid"),
                Criteria = new FilterExpression
                {
                    Conditions = 
                        {
                            new ConditionExpression 
                            { 
                                AttributeName = "parentbusinessunitid", 
                                Operator = ConditionOperator.Null 
                            }
                        }
                }
            };

            BusinessUnit defaultBusinessUnit =
                (BusinessUnit)_serviceProxy.RetrieveMultiple(
                queryDefaultBusinessUnit).Enreplacedies[0];

            // Create a new example team.
            Team setupTeam = new Team
            {
                Name = "Example Team",
                BusinessUnitId = new EnreplacedyReference(BusinessUnit.EnreplacedyLogicalName,
                    defaultBusinessUnit.BusinessUnitId.Value)
            };

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

            // Create a new example role.
            Role setupRole = new Role
            {
                Name = "Example Role",
                BusinessUnitId = new EnreplacedyReference(BusinessUnit.EnreplacedyLogicalName,
                    defaultBusinessUnit.BusinessUnitId.Value)
            };

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

            // Retrieve the prvReadQueue and prvAppendToQueue privileges.
            QueryExpression queryQueuePrivileges = new QueryExpression
            {
                EnreplacedyName = Privilege.EnreplacedyLogicalName,
                ColumnSet = new ColumnSet("privilegeid", "name"),
                Criteria = new FilterExpression
                {
                    Conditions = 
                        {
                            new ConditionExpression
                            { 
                                AttributeName = "name", 
                                Operator = ConditionOperator.In,
                                Values = { "prvReadQueue", "prvAppendToQueue" }
                            }
                        }
                }
            };

            DataCollection<Enreplacedy> retrievedQueuePrivileges =
                _serviceProxy.RetrieveMultiple(queryQueuePrivileges).Enreplacedies;

            Console.WriteLine("Retrieved prvReadQueue and prvAppendToQueue privileges.");

            // Define a list to hold the RolePrivileges we'll need to add
            List<RolePrivilege> rolePrivileges = new List<RolePrivilege>();

            foreach (Privilege privilege in retrievedQueuePrivileges)
            {
                RolePrivilege rolePrivilege = new RolePrivilege(
                    (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value);
                rolePrivileges.Add(rolePrivilege);
            }

            // Add the prvReadQueue and prvAppendToQueue privileges to the example role.
            AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest
            {
                RoleId = _roleId,
                Privileges = rolePrivileges.ToArray()
            };
            _serviceProxy.Execute(addPrivilegesRequest);
            Console.WriteLine("Retrieved privileges are added to {0}.", setupRole.Name);


            // Add the example role to the example team.
            _serviceProxy.replacedociate(
                       Team.EnreplacedyLogicalName,
                       _teamId,
                       new Relationship("teamroles_replacedociation"),
                       new EnreplacedyReferenceCollection() { new EnreplacedyReference(Role.EnreplacedyLogicalName, _roleId) });

            // It takes some time for the privileges to propogate to the team.  
            // Verify this is complete before continuing.

            bool teamLacksPrivilege = true;
            while (teamLacksPrivilege)
            {
                RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest =
                    new RetrieveTeamPrivilegesRequest
                {
                    TeamId = _teamId
                };

                RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse =
                    (RetrieveTeamPrivilegesResponse)_serviceProxy.Execute(
                    retrieveTeamPrivilegesRequest);

                if (retrieveTeamPrivilegesResponse.RolePrivileges.Any(
                    rp => rp.PrivilegeId == rolePrivileges[0].PrivilegeId) &&
                    retrieveTeamPrivilegesResponse.RolePrivileges.Any(
                    rp => rp.PrivilegeId == rolePrivileges[1].PrivilegeId))
                {
                    teamLacksPrivilege = false;
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }

            Console.WriteLine("{0} has been added to {1}",
               setupRole.Name, setupTeam.Name);
            return;
        }

19 Source : AddToQueue.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    Guid CurrentUserId = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;



                    //<snippetRetrieveUserQueues>
                    // Get known private queues for the user 
                    // by using RetrieveUserQueuesRequest message.
                    RetrieveUserQueuesRequest retrieveUserQueuesRequest = new RetrieveUserQueuesRequest
                    {
                        UserId = CurrentUserId,
                        IncludePublic = true
                    };
                    RetrieveUserQueuesResponse retrieveUserQueuesResponse =
                        (RetrieveUserQueuesResponse)_serviceProxy.Execute(retrieveUserQueuesRequest);
                    EnreplacedyCollection queues = (EnreplacedyCollection)retrieveUserQueuesResponse.EnreplacedyCollection;

                    Guid sourceQueueId = new Guid();
                    Guid destinationQueueId = new Guid();

                    foreach (Enreplacedy enreplacedy in queues.Enreplacedies)
                    {
                        Queue queue = (Queue)enreplacedy;
                        switch (queue.Name)
                        {
                            case "Source Queue":
                                sourceQueueId = queue.Id;
                                break;
                            case "Destination Queue":
                                destinationQueueId = queue.Id;
                                break;
                        }
                    }

                    //<snippetAddToQueue1>
                    // Move a record from a source queue to a destination queue
                    // by using the AddToQueue request message.
                    AddToQueueRequest routeRequest = new AddToQueueRequest
                    {
                        SourceQueueId = sourceQueueId,
                        Target = new EnreplacedyReference(Letter.EnreplacedyLogicalName, _letterId),
                        DestinationQueueId = destinationQueueId
                    };

                    // Execute the Request
                    _serviceProxy.Execute(routeRequest);
                    //</snippetAddToQueue1>                      

                    Console.WriteLine(@"The letter record has been moved to a new queue.");

                    //</snippetRetrieveUserQueues>
                    DeleteRequiredRecords(promptForDelete);

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

19 Source : AddToQueue.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            var QueueViewType = new
            {
                Public = 0,
                Private = 1
            };
            //Create new queues and store their returned GUIDs in variables for later use.
            Queue sourceQueue = new Queue
                {
                    Name = "Source Queue",
                    Description = "This is an example queue.",
                    QueueViewType = new OptionSetValue(QueueViewType.Private)
                };

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

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

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


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

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

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

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

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

            return;
        }

19 Source : StateModelTransitions.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
  {
   try
   {

                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
     // This statement is required to enable early-bound type support.
     _serviceProxy.EnableProxyTypes();
     //<snippetStateModelTransitions.run>
     String enreplacedyLogicalName = "incident";
     // Retrieve status options for the Incident enreplacedy

     //Retrieve just the incident enreplacedy and its attributes
     MetadataFilterExpression enreplacedyFilter = new MetadataFilterExpression(LogicalOperator.And);
     enreplacedyFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, enreplacedyLogicalName));
     MetadataPropertiesExpression enreplacedyProperties = new MetadataPropertiesExpression(new string[] { "Attributes" });
     
     //Retrieve just the status attribute and the OptionSet property
     MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
     attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
     MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });
     
     //Instantiate the enreplacedy query
     EnreplacedyQueryExpression query = new EnreplacedyQueryExpression()
     {
      Criteria = enreplacedyFilter,
      Properties = enreplacedyProperties,
      AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
     };

     //Retrieve the metadata
     RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
     RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);


     StatusAttributeMetadata statusAttribute = (StatusAttributeMetadata)response.EnreplacedyMetadata[0].Attributes[0];
     OptionMetadataCollection statusOptions = statusAttribute.OptionSet.Options;
     //Loop through each of the status options
     foreach (StatusOptionMetadata option in statusOptions)
     {
      String StatusOptionLabel = GetOptionSetLabel(statusAttribute, option.Value.Value);
      Console.WriteLine("[{0}] {1} records can transition to:", StatusOptionLabel, enreplacedyLogicalName);
      List<StatusOption> validStatusOptions = GetValidStatusOptions(enreplacedyLogicalName, option.Value.Value);
      //Loop through each valid transition for the option
      foreach (StatusOption opt in validStatusOptions)
      {
       Console.WriteLine("{0,-3}{1,-10}{2,-5}{3,-10}", opt.StateValue, opt.StateLabel, opt.StatusValue, opt.StatusLabel);
      }
      Console.WriteLine("");
     }
     //</snippetStateModelTransitions.run>
    }
   }

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

19 Source : WorkWithAttributes.cs
with MIT License
from microsoft

public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine(
                    "\nDo you want these enreplacedy records to be deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                #region How to delete attribute
                //<snippetWorkWithAttributes9>
                // Delete all attributes created for this sample.
                foreach (AttributeMetadata anAttribute in addedAttributes)
                {
                    // Create the request object
                    DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest
                    {
                        // Set the request properties 
                        EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                        LogicalName = anAttribute.SchemaName
                    };
                    // Execute the request
                    _serviceProxy.Execute(deleteAttribute);
                }
                //</snippetWorkWithAttributes9>
                #endregion How to delete attribute

                #region How to remove inserted status value
                //<snippetWorkWithAttributes10>
                // Delete the newly inserted status value.
                // Create the request object
                DeleteOptionValueRequest deleteRequest = new DeleteOptionValueRequest
                {
                    AttributeLogicalName = "statuscode",
                    EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                    Value = _insertedStatusValue
                };

                // Execute the request
                _serviceProxy.Execute(deleteRequest);
                
                Console.WriteLine("Deleted all attributes created for this sample.");
                //</snippetWorkWithAttributes10>
                #endregion How to remove inserted status value

                #region Revert the changed state value
                //<snippetWorkWithAttributes11>
                // Revert the state value label from Open to Active.
                // Create the request.
                UpdateStateValueRequest revertStateValue = new UpdateStateValueRequest
                {
                    AttributeLogicalName = "statecode",
                    EnreplacedyLogicalName = Contact.EnreplacedyLogicalName,
                    Value = 1,
                    Label = new Label("Active", _languageCode)
                };

                // Execute the request.
                _serviceProxy.Execute(revertStateValue);

                // NOTE: All customizations must be published before they can be used.
                _serviceProxy.Execute(new PublishAllXmlRequest());

                Console.WriteLine(
                    "Reverted {0} state attribute of {1} enreplacedy from 'Open' to '{2}'.",
                    revertStateValue.AttributeLogicalName,
                    revertStateValue.EnreplacedyLogicalName,
                    revertStateValue.Label.LocalizedLabels[0].Label
                    );
                //</snippetWorkWithAttributes11>
                #endregion Revert the changed state value
            }
        }

19 Source : UserAccessAuditing.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                #region Enable Auditing

                // Enable auditing on the organization and for user access by editing the
                // organization's settings.
                // First, get the organization's ID from the system user record.
                var whoAmIReq = new WhoAmIRequest();
                var whoAmIRes = (WhoAmIResponse)_serviceProxy.Execute(whoAmIReq);
                Guid orgId = whoAmIRes.OrganizationId;
                _systemUserId = whoAmIRes.UserId;

                // Next, retrieve the organization's record.
                var org = (Organization)_serviceProxy.Retrieve(
                    Organization.EnreplacedyLogicalName, orgId,
                    new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));

                // Finally, enable auditing on the organization, including auditing for
                // user access.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool userAccessAuditingFlag = org.IsUserAccessAuditEnabled.Value;
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    org.IsAuditEnabled = true;
                    org.IsUserAccessAuditEnabled = true;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Enabled auditing for the organization and for user access.");
                    Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
                }

                // Enable auditing on the account enreplacedy, since no audits will be created
                // when we create/update an account enreplacedy, otherwise.
                var oldAccountAuditing = EnableEnreplacedyAuditing(Account.EnreplacedyLogicalName, true);

                #endregion Enable Auditing

                #region Make Audited Service Calls

                CreateRequiredRecords();

                // Make an update request to the Account enreplacedy to be tracked by auditing.
                var newAccount = new Account();
                newAccount.AccountId = _newAccountId;
                newAccount.AccountNumber = "1-A";
                newAccount.AccountCategoryCode = new OptionSetValue(
                    (int)AccountAccountCategoryCode.PreferredCustomer);
                newAccount.Telephone1 = "555-555-5555";

                _serviceProxy.Update(newAccount);

                Console.WriteLine("Created an account and made updates which should be captured by auditing.");

                #endregion Make Audited Service Calls

                #region Revert auditing

                // Set the organization and account auditing flags back to the old values
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    // Only revert them if they were actually changed to begin with.
                    org.IsAuditEnabled = organizationAuditingFlag;
                    org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Reverted organization and user access auditing to their previous values.");
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
                }

                // Revert the account enreplacedy auditing.
                EnableEnreplacedyAuditing(Account.EnreplacedyLogicalName, oldAccountAuditing);

                #endregion Revert auditing

                #region Show Audited Records

                // Select all columns for convenience.
                var query = new QueryExpression(Audit.EnreplacedyLogicalName)
                {
                    ColumnSet = new ColumnSet(true),
                    Criteria = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                    (int)AuditAction.UserAccessAuditStarted,
                    (int)AuditAction.UserAccessAuditStopped,
                    (int)AuditAction.UserAccessviaWebServices,
                    (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user or the "SYSTEM"
                    // user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _systemUserId);
                    userFilter.AddCondition(
                        "useridname", ConditionOperator.Equal, "SYSTEM");
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                Console.WriteLine("Retrieved audit records:");
                foreach (Audit audit in results.Enreplacedies)
                {
                    Console.Write("\r\n  Action: {0},  User: {1},"
                        + "\r\n    Created On: {2}, Operation: {3}",
                        (AuditAction)audit.Action.Value,
                        audit.UserId.Name,
                        audit.CreatedOn.Value.ToLocalTime(),
                        (AuditOperation)audit.Operation.Value);

                    // Display the name of the related object (which will be the user
                    // for audit records with Action UserAccessviaWebServices.
                    if (!String.IsNullOrEmpty(audit.ObjectId.Name))
                    {
                        Console.WriteLine(
                            ",\r\n    Related Record: {0}", audit.ObjectId.Name);
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                }

                #endregion Show Audited Records

                DeleteRequiredRecords(promptforDelete);
            }
        }

19 Source : UserAccessAuditing.cs
with MIT License
from microsoft

private bool EnableEnreplacedyAuditing(String enreplacedyLogicalName, bool flag)
        {
            // Retrieve the enreplacedy metadata.
            RetrieveEnreplacedyRequest enreplacedyRequest = new RetrieveEnreplacedyRequest
            {
                LogicalName = enreplacedyLogicalName,
                EnreplacedyFilters = EnreplacedyFilters.Attributes
            };

            RetrieveEnreplacedyResponse enreplacedyResponse =
                (RetrieveEnreplacedyResponse)_serviceProxy.Execute(enreplacedyRequest);

            // Enable auditing on the enreplacedy. By default, this also enables auditing
            // on all the enreplacedy's attributes.
            EnreplacedyMetadata enreplacedyMetadata = enreplacedyResponse.EnreplacedyMetadata;

            bool oldValue = enreplacedyMetadata.IsAuditEnabled.Value;
            enreplacedyMetadata.IsAuditEnabled = new BooleanManagedProperty(flag);

            UpdateEnreplacedyRequest updateEnreplacedyRequest = new UpdateEnreplacedyRequest { Enreplacedy = enreplacedyMetadata };

            UpdateEnreplacedyResponse updateEnreplacedyResponse =
                (UpdateEnreplacedyResponse)_serviceProxy.Execute(updateEnreplacedyRequest);

            return oldValue;
        }

19 Source : AddPrincipalToQueue.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    ////<snippetAddPrincipalToQueue1>                
                    ColumnSet columnSet = new ColumnSet("name");
                    Enreplacedy team = _serviceProxy.Retrieve(Team.EnreplacedyLogicalName, _teamId, columnSet);
                    AddPrincipalToQueueRequest addPrincipalToQueueRequest = new AddPrincipalToQueueRequest
                    {
                        Principal = team,
                        QueueId = _queueId
                    };

                    _serviceProxy.Execute(addPrincipalToQueueRequest);

                    //</snippetAddPrincipalToQueue1>  

                    Console.WriteLine("The team has been added to the queue.");

                    DeleteRequiredRecords(promptForDelete);

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

19 Source : BulkDeleteBackup.cs
with MIT License
from microsoft

private void PerformBulkDeleteBackup()
        {
            try
            {
                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var userRequest = new WhoAmIRequest();
                var userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                //<snippetBulkDelete>
                // Create a condition for a bulk delete request.
                // NOTE: This sample uses very specific queries for deleting records
                // that have been manually exported in order to free space.
                QueryExpression opportunitiesQuery = BuildOpportunityQuery();

                // Create the bulk delete request.
                BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();

                // Set the request properties.
                bulkDeleteRequest.JobName = "Backup Bulk Delete";

                // Querying activities
                bulkDeleteRequest.QuerySet = new QueryExpression[]
                {
                    opportunitiesQuery,
                    BuildActivityQuery(Task.EnreplacedyLogicalName),
                    BuildActivityQuery(Fax.EnreplacedyLogicalName),
                    BuildActivityQuery(PhoneCall.EnreplacedyLogicalName),
                    BuildActivityQuery(Email.EnreplacedyLogicalName),
                    BuildActivityQuery(Letter.EnreplacedyLogicalName),
                    BuildActivityQuery(Appointment.EnreplacedyLogicalName),
                    BuildActivityQuery(ServiceAppointment.EnreplacedyLogicalName),
                    BuildActivityQuery(CampaignResponse.EnreplacedyLogicalName),
                    BuildActivityQuery(RecurringAppointmentMaster.EnreplacedyLogicalName)
                };

                // Set the start time for the bulk delete.
                bulkDeleteRequest.StartDateTime = DateTime.Now;

                // Set the required recurrence pattern.
                bulkDeleteRequest.RecurrencePattern = String.Empty;

                // Set email activity properties.
                bulkDeleteRequest.SendEmailNotification = false;
                bulkDeleteRequest.ToRecipients = new Guid[] { currentUserId };
                bulkDeleteRequest.CCRecipients = new Guid[] { };

                // Submit the bulk delete job.
                // NOTE: Because this is an asynchronous operation, the response will be immediate.
                _bulkDeleteResponse =
                    (BulkDeleteResponse)_serviceProxy.Execute(bulkDeleteRequest);
                Console.WriteLine("The bulk delete operation has been requested.");
                //</snippetBulkDelete>

                CheckSuccess();
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }

19 Source : CleanUpQueueItems.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();


                    //<snippetCleanUpQueueItems1>
                    // Retrieve the queueitem with inactive phone calls from a queue            
                    RemoveFromQueueRequest removeFromQueueRequest = new RemoveFromQueueRequest
                    {
                        QueueItemId = _queueItemId
                    };
                    _serviceProxy.Execute(removeFromQueueRequest);

                    //</snippetCleanUpQueueItems1>  

                    Console.WriteLine("Inactive phonecalls have been deleted from the queue.");

                    DeleteRequiredRecords(promptForDelete);

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

19 Source : ConvertOpportunityToQuote.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetConvertOpportunityToQuote1>
                    // Convert an opportunity to quote.
                    GenerateQuoteFromOpportunityRequest quoteRequest = new GenerateQuoteFromOpportunityRequest()
                    {
                        // Columns that will be transferred
                        ColumnSet = new ColumnSet("name", "customerid"),
                        OpportunityId = _opportunityId
                    };

                    GenerateQuoteFromOpportunityResponse quoteResponse =
                        (GenerateQuoteFromOpportunityResponse)_serviceProxy.Execute(quoteRequest);

                    _quoteId = quoteResponse.Enreplacedy.Id;
                    //</snippetConvertOpportunityToQuote1>
                    Console.WriteLine("Created the quote from an opportunity.");

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            catch
            {
                // You can handle an exception here or preplaced it back to the calling method.
                throw;
            }
		}

19 Source : ConvertOpportunityToQuote.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Create a unit group.
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);

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

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

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

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

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

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

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

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

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

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

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

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

            ProductPriceLevel newPriceLisreplacedem2 = new ProductPriceLevel
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product2Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, unit.Id),
                Amount = new Money(20)
            };
            _priceLisreplacedem2Id = _serviceProxy.Create(newPriceLisreplacedem2);

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

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

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


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

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

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

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

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

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

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

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

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

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

            return;
        }

19 Source : CreateConnection.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Create a Connection Role for account and contact
            ConnectionRole newConnectionRole = new ConnectionRole
            {
                Name = "Example Connection Role",
                Category = new OptionSetValue((int)connectionrole_category.Business)
            };

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

            // Create a related Connection Role Object Type Code record for Account
            ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode
                = new ConnectionRoleObjectTypeCode
                {
                    ConnectionRoleId = new EnreplacedyReference(
                        ConnectionRole.EnreplacedyLogicalName, _connectionRoleId),
                    replacedociatedObjectTypeCode = Account.EnreplacedyLogicalName
                };

            _serviceProxy.Create(newAccountConnectionRoleTypeCode);
            Console.WriteLine(
                "Created a related Connection Role Object Type Code record for Account."
                );

            // Create a related Connection Role Object Type Code record for Contact
            ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode
                = new ConnectionRoleObjectTypeCode
                {
                    ConnectionRoleId = new EnreplacedyReference(
                        ConnectionRole.EnreplacedyLogicalName, _connectionRoleId),
                    replacedociatedObjectTypeCode = Contact.EnreplacedyLogicalName
                };

            _serviceProxy.Create(newContactConnectionRoleTypeCode);
            Console.WriteLine(
                "Created a related Connection Role Object Type Code record for Contact."
                );

            // replacedociate the connection role with itself.
            replacedociateRequest replacedociateConnectionRoles = new replacedociateRequest
            {
                Target = new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                    _connectionRoleId),
                RelatedEnreplacedies = new EnreplacedyReferenceCollection()
                        {
                            new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                                _connectionRoleId)
                        },
                // The name of the relationship connection role replacedociation 
                // relationship in MS CRM.
                Relationship = new Relationship()
                {
                    PrimaryEnreplacedyRole = EnreplacedyRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship.
                    SchemaName = "connectionrolereplacedociation_replacedociation"
                }
            };

            _serviceProxy.Execute(replacedociateConnectionRoles);
            Console.WriteLine("replacedociated the connection role with itself.");

            // Create an Account
            Account setupAccount = new Account { Name = "Example Account" };
            _accountId = _serviceProxy.Create(setupAccount);
            Console.WriteLine("Created {0}.", setupAccount.Name);

            // Create a Contact
            Contact setupContact = new Contact { LastName = "Example Contact" };
            _contactId = _serviceProxy.Create(setupContact);
            Console.WriteLine("Created {0}.", setupContact.LastName);

            return;
        }

19 Source : CreateOpportunity.cs
with MIT License
from microsoft

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
            {
                EnreplacedyName = UoM.EnreplacedyLogicalName,
                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).Enreplacedies[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),
                QuanreplacedyDecimal = 2,
                DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, 
                    _unitGroupId),
                DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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),
               QuanreplacedyDecimal = 3,
               DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, 
                   _unitGroupId),
               DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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 EnreplacedyReference(DiscountType.EnreplacedyLogicalName, 
                    _discountTypeId),
                LowQuanreplacedy = 5,
                HighQuanreplacedy = 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 newPriceLisreplacedem1 = new ProductPriceLevel 
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product1Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20),
                DiscountTypeId = new EnreplacedyReference(DiscountType.EnreplacedyLogicalName, 
                    _discountTypeId)
            };

            _priceLisreplacedem1Id = _serviceProxy.Create(newPriceLisreplacedem1);
            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 newPriceLisreplacedem2 = new ProductPriceLevel
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product2Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(15)
            };

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

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

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EnreplacedyMoniker = new EnreplacedyReference(Product.EnreplacedyLogicalName, _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);

            return;
        }

19 Source : CreateReciprocalConnectionRole.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();
                    
                    // Create the Connection Role 1
                    ConnectionRole newConnectionRole1 = new ConnectionRole
                    {
                        Name = "Example Connection Role 1",
                        Category = new OptionSetValue((int)connectionrole_category.Business),
                    };

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

                    // Create a related Connection Role Object Type Code record for Account
                    ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode
                        = new ConnectionRoleObjectTypeCode
                        {
                            ConnectionRoleId = new EnreplacedyReference(
                                ConnectionRole.EnreplacedyLogicalName, _connectionRole1Id),
                            replacedociatedObjectTypeCode = Account.EnreplacedyLogicalName
                        };

                    _serviceProxy.Create(newAccountConnectionRole1TypeCode);
                    Console.WriteLine(
                        "Created a related Connection Role 1 Object Type Code record for Account."
                        );

                    // Create a related Connection Role Object Type Code record for Contact
                    ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode
                        = new ConnectionRoleObjectTypeCode
                        {
                            ConnectionRoleId = new EnreplacedyReference(
                                ConnectionRole.EnreplacedyLogicalName, _connectionRole1Id),
                            replacedociatedObjectTypeCode = Contact.EnreplacedyLogicalName
                        };

                    _serviceProxy.Create(newContactConnectionRole1TypeCode);
                    Console.WriteLine(
                        "Created a related Connection Role 1 Object Type Code record for Contact."
                        );

                    // Create the Connection Role 2
                    ConnectionRole newConnectionRole2 = new ConnectionRole
                    {
                        Name = "Example Connection Role 2",
                        Category = new OptionSetValue((int)connectionrole_category.Business),
                    };

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

                    // Create a related Connection Role 2 Object Type Code record for Account
                    ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode
                        = new ConnectionRoleObjectTypeCode
                        {
                            ConnectionRoleId = new EnreplacedyReference(
                                ConnectionRole.EnreplacedyLogicalName, _connectionRole2Id),
                            replacedociatedObjectTypeCode = Account.EnreplacedyLogicalName
                        };

                    _serviceProxy.Create(newAccountConnectionRole2TypeCode);
                    Console.WriteLine(
                        "Created a related Connection Role 2 Object Type Code record for Account."
                        );

                    // Create a related Connection Role 2 Object Type Code record for Contact
                    ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode
                        = new ConnectionRoleObjectTypeCode
                        {
                            ConnectionRoleId = new EnreplacedyReference(
                                ConnectionRole.EnreplacedyLogicalName, _connectionRole2Id),
                            replacedociatedObjectTypeCode = Contact.EnreplacedyLogicalName
                        };

                    _serviceProxy.Create(newContactConnectionRole2TypeCode);
                    Console.WriteLine(
                        "Created a related Connection Role 2 Object Type Code record for Contact."
                        );
                    //<snippetreplacedociateReciprocalConnectionRoles>
                    // replacedociate the connection roles
                     replacedociateRequest replacedociateConnectionRoles = new replacedociateRequest
                    {
                        Target = new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                            _connectionRole1Id),
                        RelatedEnreplacedies = new EnreplacedyReferenceCollection()
                        {
                            new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                                _connectionRole2Id)
                        },
                        // The name of the relationship connection role replacedociation 
                        // relationship in MS CRM
                        Relationship = new Relationship()
                        {
                            PrimaryEnreplacedyRole = EnreplacedyRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship.
                            SchemaName = "connectionrolereplacedociation_replacedociation"
                        }
                    };

                    _serviceProxy.Execute(replacedociateConnectionRoles);
                    Console.WriteLine("replacedociated the connection roles.");
                    //</snippetreplacedociateReciprocalConnectionRoles>

                    DeleteRequiredRecords(promptForDelete);

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

19 Source : ProcessingQuotesAndSalesOrders.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetProcessingQuotesAndSalesOrders1>
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create Opportunities

                    // Create an opportunity
                    var crmOpportunity = new Opportunity
                    {
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName, _accountId),
                        Name = "Sample",
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId)
                    };
                    _opportunityId = _serviceProxy.Create(crmOpportunity);

                    crmOpportunity = new Opportunity
                    {
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName, _accountId),
                        Name = "Another Sample",
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId)
                    };
                    _loseOpportunityId = _serviceProxy.Create(crmOpportunity);

                    Console.WriteLine("Opportunities created.");

                    #endregion

                    #region Win Opportunity

                    //<snippetWinOpportunity>
                    // Close the opportunity as won
                    var winOppRequest = new WinOpportunityRequest
                    {
                        OpportunityClose = new OpportunityClose
                        {
                            OpportunityId = new EnreplacedyReference
                                (Opportunity.EnreplacedyLogicalName, _opportunityId)
                        },
                        Status = new OptionSetValue((int)opportunity_statuscode.Won)
                    };

                    _serviceProxy.Execute(winOppRequest);

                    Console.WriteLine("Opportunity closed as Won.");
                    //</snippetWinOpportunity>

                    #endregion

                    #region Lose Opportunity
                    //<snippetLoseOpportunity>
                    var loseOppRequest = new LoseOpportunityRequest
                    {
                        OpportunityClose = new OpportunityClose
                        {
                            OpportunityId = new EnreplacedyReference
                                (Opportunity.EnreplacedyLogicalName, _loseOpportunityId)
                        },
                        Status = new OptionSetValue((int)opportunity_statuscode.Canceled)
                    };

                    _serviceProxy.Execute(loseOppRequest);

                    Console.WriteLine("Opportunity closed as Lost.");
                    //</snippetLoseOpportunity>

                    #endregion

                    #region Convert Opportunity to a Quote

                    //<snippetGenerateQuoteFromOpportunity>
                    // Convert the opportunity to a quote
                    var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
                    {
                        OpportunityId = _opportunityId,
                        ColumnSet = new ColumnSet("quoteid", "name")
                    };

                    var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
                        _serviceProxy.Execute(genQuoteFromOppRequest);

                    Quote quote = genQuoteFromOppResponse.Enreplacedy.ToEnreplacedy<Quote>();
                    _quoteId = quote.Id;

                    Console.WriteLine("Quote generated from the Opportunity.");
                    //</snippetGenerateQuoteFromOpportunity>

                    #endregion

                    #region Close Quote

                    //<snippetCloseQuote>
                    // convert the opportunity to a quote
                    genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
                    {
                        OpportunityId = _opportunityId,
                        ColumnSet = new ColumnSet("quoteid", "name")
                    };
                    genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
                        _serviceProxy.Execute(genQuoteFromOppRequest);

                    Quote closeQuote = genQuoteFromOppResponse.Enreplacedy.ToEnreplacedy<Quote>();
                    _closeQuoteId = closeQuote.Id;

                    // Activate the quote
                    SetStateRequest activateQuote = new SetStateRequest()
                    {
                        EnreplacedyMoniker = closeQuote.ToEnreplacedyReference(),
                        State = new OptionSetValue((int)QuoteState.Active),
                        Status = new OptionSetValue((int)quote_statuscode.InProgress)
                    };
                    _serviceProxy.Execute(activateQuote);

                    // Close the quote
                    CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest()
                    {
                        QuoteClose = new QuoteClose()
                        {
                            QuoteId = closeQuote.ToEnreplacedyReference(),
                            Subject = "Quote Close " + DateTime.Now.ToString()
                        },
                        Status = new OptionSetValue(-1)
                    };
                    _serviceProxy.Execute(closeQuoteRequest);

                    Console.WriteLine("Quote Closed");
                    //</snippetCloseQuote>

                    #endregion

                    #region Create Quote's Product

                    // Set the quote's product
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                            _productId),
                        Quanreplacedy = 1,
                        QuoteId = quote.ToEnreplacedyReference(),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName,
                            _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Quote Product created.");

                    // Activate the quote
                    activateQuote = new SetStateRequest()
                    {
                        EnreplacedyMoniker = quote.ToEnreplacedyReference(),
                        State = new OptionSetValue((int)QuoteState.Active),
                        Status = new OptionSetValue((int)quote_statuscode.InProgress)
                    };
                    _serviceProxy.Execute(activateQuote);

                    Console.WriteLine("Quote activated.");

                    //<snippetWinQuote>

                    // Mark the quote as won
                    // Note: this is necessary in order to convert a quote into a 
                    // SalesOrder.
                    WinQuoteRequest winQuoteRequest = new WinQuoteRequest()
                    {
                        QuoteClose = new QuoteClose()
                        {
                            Subject = "Quote Close" + DateTime.Now.ToString(),
                            QuoteId = quote.ToEnreplacedyReference()
                        },
                        Status = new OptionSetValue(-1)
                    };
                    _serviceProxy.Execute(winQuoteRequest);

                    Console.WriteLine("Quote won.");
                    //</snippetWinQuote>

                    #endregion

                    #region Convert Quote to SalesOrder


                    //<snippetConvertQuoteToSalesOrder>
                    // Define columns to be retrieved after creating the order
                    ColumnSet salesOrderColumns =
                        new ColumnSet("salesorderid", "totalamount");

                    // Convert the quote to a sales order
                    ConvertQuoteToSalesOrderRequest convertQuoteRequest =
                        new ConvertQuoteToSalesOrderRequest()
                        {
                            QuoteId = _quoteId,
                            ColumnSet = salesOrderColumns
                        };
                    ConvertQuoteToSalesOrderResponse convertQuoteResponse =
                        (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest);
                    SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Enreplacedy;
                    _salesOrderId = salesOrder.Id;

                    //</snippetConvertQuoteToSalesOrder>
                    Console.WriteLine("Converted Quote to SalesOrder.");

                    #endregion

                    #region Cancel Sales Order

                    //<snippetCancelSalesOrder>

                    // Define columns to be retrieved after creating the order
                    salesOrderColumns = new ColumnSet("salesorderid", "totalamount");

                    // Convert the quote to a sales order
                    convertQuoteRequest =
                        new ConvertQuoteToSalesOrderRequest()
                        {
                            QuoteId = _quoteId,
                            ColumnSet = salesOrderColumns
                        };
                    convertQuoteResponse =
                        (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest);
                    SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Enreplacedy;
                    _closeSalesOrderId = closeSalesOrder.Id;

                    CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest()
                    {
                        OrderClose = new OrderClose()
                        {
                            SalesOrderId = closeSalesOrder.ToEnreplacedyReference(),
                            Subject = "Close Sales Order " + DateTime.Now
                        },
                        Status = new OptionSetValue(-1)
                    };
                    _serviceProxy.Execute(cancelRequest);

                    Console.WriteLine("Canceled sales order");
                    //</snippetCancelSalesOrder>

                    #endregion

                    #region Lock pricing on SalesOrder

                    // Note: after converting a won quote to an order, the pricing of 
                    // the order is locked by default.

                    //<snippetUpdateRequest>

                    // Retrieve current price list
                    ProductPriceLevel priceLisreplacedem =
                        (ProductPriceLevel)_serviceProxy.Retrieve(
                            ProductPriceLevel.EnreplacedyLogicalName,
                            _priceLisreplacedemId,
                            new ColumnSet("productpricelevelid", "amount")
                        );

                    Console.WriteLine("Current price list retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details before update:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current order total: {0}",
                        salesOrder.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    // Update the price list
                    priceLisreplacedem.Amount = new Money(30.0M);

                    UpdateRequest updatePriceLisreplacedem = new UpdateRequest()
                    {
                        Target = priceLisreplacedem,
                    };
                    _serviceProxy.Execute(updatePriceLisreplacedem);

                    Console.WriteLine("Price list updated.");
                    //</snippetUpdateRequest>

                    // Retrieve the order
                    SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
                            SalesOrder.EnreplacedyLogicalName,
                            _salesOrderId,
                            new ColumnSet("salesorderid", "totalamount")
                        );

                    Console.WriteLine("Updated order retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details after update:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current order total: {0}",
                        updatedSalesOrder.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    //<snippetUnlockSalesOrderPricing>
                    // Unlock the order pricing
                    UnlockSalesOrderPricingRequest unlockOrderRequest =
                        new UnlockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
                    _serviceProxy.Execute(unlockOrderRequest);
                    //</snippetUnlockSalesOrderPricing>

                    Console.WriteLine("Order pricing unlocked.");

                    // Retrieve the order
                    updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
                            SalesOrder.EnreplacedyLogicalName,
                            _salesOrderId,
                            new ColumnSet("salesorderid", "totalamount")
                        );

                    Console.WriteLine("Updated order retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details after update and unlock:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current order total: {0}",
                        updatedSalesOrder.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    //<snippetLockSalesOrderPricing>
                    // Relock the order pricing
                    LockSalesOrderPricingRequest lockOrderRequest =
                        new LockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
                    _serviceProxy.Execute(lockOrderRequest);

                    //</snippetLockSalesOrderPricing>

                    Console.WriteLine("Order pricing relocked.");

                    #endregion

                    //<snippetConvertSalesOrderToInvoice> 
                    #region Convert SalesOrder to Invoice

                    // Define columns to be retrieved after creating the invoice
                    ColumnSet invoiceColumns =
                        new ColumnSet("invoiceid", "totalamount");

                    // Convert the order to an invoice
                    ConvertSalesOrderToInvoiceRequest convertOrderRequest =
                        new ConvertSalesOrderToInvoiceRequest()
                        {
                            SalesOrderId = _salesOrderId,
                            ColumnSet = invoiceColumns
                        };
                    ConvertSalesOrderToInvoiceResponse convertOrderResponse =
                        (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest);
                    Invoice invoice = (Invoice)convertOrderResponse.Enreplacedy;
                    _invoiceId = invoice.Id;

                    //</snippetConvertSalesOrderToInvoice>
                    Console.WriteLine("Converted SalesOrder to Invoice.");

                    #endregion

                    #region Lock pricing on Invoice

                    // Note: after converting a SalesOrder to Invoice, the pricing of 
                    // the Invoice is locked by default.

                    // Retrieve current price list
                    priceLisreplacedem = (ProductPriceLevel)_serviceProxy.Retrieve(
                            ProductPriceLevel.EnreplacedyLogicalName,
                            _priceLisreplacedemId,
                            new ColumnSet("productpricelevelid", "amount")
                        );

                    Console.WriteLine("Current price list retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details before lock and update:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current invoice total: {0}",
                        invoice.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    //<snippetUpdatePriceList>
                    // Update the price list
                    priceLisreplacedem.Amount = new Money(40.0M);

                    updatePriceLisreplacedem = new UpdateRequest()
                    {
                        Target = priceLisreplacedem
                    };
                    _serviceProxy.Execute(updatePriceLisreplacedem);

                    Console.WriteLine("Price list updated.");
                    //</snippetUpdatePriceList>

                    //<snippetUnlockInvoicePricing>

                    // Retrieve the invoice
                    Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve(
                            Invoice.EnreplacedyLogicalName,
                            _invoiceId,
                            new ColumnSet("invoiceid", "totalamount")
                        );

                    Console.WriteLine("Updated invoice retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details after lock and update:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current invoice total: {0}",
                        updatedInvoice.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    // Unlock the invoice pricing
                    UnlockInvoicePricingRequest unlockInvoiceRequest =
                        new UnlockInvoicePricingRequest()
                        {
                            InvoiceId = _invoiceId
                        };
                    _serviceProxy.Execute(unlockInvoiceRequest);

                    Console.WriteLine("Invoice pricing unlocked.");
                    //</snippetUnlockInvoicePricing>

                    // Retrieve the invoice
                    updatedInvoice = (Invoice)_serviceProxy.Retrieve(
                            Invoice.EnreplacedyLogicalName,
                            _invoiceId,
                            new ColumnSet("invoiceid", "totalamount")
                        );

                    Console.WriteLine("Updated invoice retrieved.");
                    Console.WriteLine();

                    Console.WriteLine("Details after update and unlock:");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Current invoice total: {0}",
                        updatedInvoice.TotalAmount.Value);
                    Console.WriteLine("Current price per item: {0}",
                        priceLisreplacedem.Amount.Value);
                    Console.WriteLine("</End of Listing>");
                    Console.WriteLine();

                    //<snippetLockInvoicePricing>
                    // Relock the invoice pricing
                    LockInvoicePricingRequest lockInvoiceRequest =
                        new LockInvoicePricingRequest()
                        {
                            InvoiceId = _invoiceId
                        };
                    _serviceProxy.Execute(lockInvoiceRequest);

                    Console.WriteLine("Invoice pricing relocked.");
                    //</snippetLockInvoicePricing>

                    #endregion

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

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

19 Source : ProcessingQuotesAndSalesOrders.cs
with MIT License
from microsoft

public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };
            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Create {0}", newUnitGroup.Name);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EnreplacedyName = UoM.EnreplacedyLogicalName,
                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).Enreplacedies[0];
            _defaultUnitId = unit.UoMId.Value;

            // Create a few products
            Product newProduct = new Product
            {
                ProductNumber = "1",
                Name = "Example Product",
                ProductStructure = new OptionSetValue(1),
                QuanreplacedyDecimal = 1,
                DefaultUoMScheduleId =
                    new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, _unitGroupId),
                DefaultUoMId =
                    new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId)
            };
            _productId = _serviceProxy.Create(newProduct);
            newProduct.Id = _productId;
            Console.WriteLine("Create {0}", newProduct.Name);

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

            // Create a price list item for the product and apply volume discount
            ProductPriceLevel newPriceLisreplacedem = new ProductPriceLevel
            {
                PriceLevelId =
                    new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId =
                    new EnreplacedyReference(Product.EnreplacedyLogicalName, _productId),
                UoMId =
                    new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20.0M),
            };
            _priceLisreplacedemId = _serviceProxy.Create(newPriceLisreplacedem);

            // Publish the product
            SetStateRequest publishRequest = new SetStateRequest
            {
                EnreplacedyMoniker = new EnreplacedyReference(Product.EnreplacedyLogicalName, _productId),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest);
            Console.WriteLine("Published {0}", newProduct.Name);

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

        }

19 Source : RetrieveOpportunity.cs
with MIT License
from microsoft

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
            {
                EnreplacedyName = UoM.EnreplacedyLogicalName,
                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).Enreplacedies[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),
                QuanreplacedyDecimal = 2,
                DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, 
                    _unitGroupId),
                DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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),
               QuanreplacedyDecimal = 3,
               DefaultUoMScheduleId = new EnreplacedyReference(UoMSchedule.EnreplacedyLogicalName, 
                   _unitGroupId),
               DefaultUoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _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 EnreplacedyReference(DiscountType.EnreplacedyLogicalName, 
                    _discountTypeId),
                LowQuanreplacedy = 5,
                HighQuanreplacedy = 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 newPriceLisreplacedem1 = new ProductPriceLevel 
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product1Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20),
                DiscountTypeId = new EnreplacedyReference(DiscountType.EnreplacedyLogicalName, 
                    _discountTypeId)
            };

            _priceLisreplacedem1Id = _serviceProxy.Create(newPriceLisreplacedem1);
            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 newPriceLisreplacedem2 = new ProductPriceLevel
            {
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName, _priceListId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, _product2Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Amount = new Money(20)
            };

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

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

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EnreplacedyMoniker = new EnreplacedyReference(Product.EnreplacedyLogicalName, _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 EnreplacedyReference(Account.EnreplacedyLogicalName,
                    _accountId),
                PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                    _priceListId)
            };

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

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

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId = new EnreplacedyReference(Opportunity.EnreplacedyLogicalName,
                    _opportunityId),
                ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                    _product2Id),
                UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                Quanreplacedy = 1
            };

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

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

            return;
        }

19 Source : RollupByObject.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement replacedures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create QueryExpression
                    // Create QueryExpression
                    QueryExpression query = new QueryExpression()
                    {
                        EnreplacedyName = Opportunity.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("name", "accountid"),
                        Criteria =
                        {
                            Filters = 
                            {
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions = 
                                    {
                                        new ConditionExpression("name", ConditionOperator.Equal, "Opportunity 1")
                                    },
                                }
                            }
                        },
                    };
                    Console.WriteLine("Created QueryExpression.");
                    #endregion Create QueryExpression
                    
                    #region Create RollupRequest
                    //<snippetRollup1>
                    // Create RollupRequest
                    RollupRequest rollupRequest = new RollupRequest();
                    rollupRequest.Query = query;
                    rollupRequest.Target = new EnreplacedyReference("account", _accountId);
                    rollupRequest.RollupType = RollupType.Extended;
                    Console.WriteLine("Created RollupRequest.");
                    #endregion Create RollupRequest

                    #region Execute RollupRequest
                    // Execute RollupRequest
                    RollupResponse rollupResponse = (RollupResponse)_serviceProxy.Execute(rollupRequest);
                    Console.WriteLine("Executed RollupRequest.");
                    //</snippetRollup1>
                    #endregion Execute RollupRequest

                    #region Show RollupResponse results
                    // Show RollupResponse results
                    Console.WriteLine("RollupResponse Results:");
                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("Count: " + rollupResponse.Results.Count);
                    for (int i = 0; i < rollupResponse.Results.Count; i++ )
                    {
                        Console.WriteLine();
                        Console.WriteLine("LogicalName: " + rollupResponse.EnreplacedyCollection.Enreplacedies[i].LogicalName);
                        Console.WriteLine("Id: " + rollupResponse.EnreplacedyCollection.Enreplacedies[i].Id);
                    }
                    #endregion Show RollupResponse results

                    DeleteRequiredRecords(promptforDelete);
                }
            }

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

19 Source : WorkingWithTimeZones.cs
with MIT License
from microsoft

private void RetrieveAllTimeZonesForLocale()
        {
            if (!_localeId.HasValue)
                return;
            
            Console.WriteLine(String.Concat("Retrieving time zones for locale id: ",
                _localeId.Value));

            var response = (GetAllTimeZonesWithDisplayNameResponse) _serviceProxy.Execute(
                new GetAllTimeZonesWithDisplayNameRequest
                {
                    LocaleId = _localeId.Value,
                });

            for (int i = 0; i < response.EnreplacedyCollection.Enreplacedies.Count; i++)
            {
                var timeZoneDefinition = response.EnreplacedyCollection
                    .Enreplacedies[i].ToEnreplacedy<TimeZoneDefinition>();

                Console.WriteLine(String.Concat(timeZoneDefinition.UserInterfaceName,
                    " found for ", _localeId.Value));
            }
        }

19 Source : WorkingWithTimeZones.cs
with MIT License
from microsoft

private void GetTimeZoneCodeByLocaleAndName()
        {
            if (string.IsNullOrWhiteSpace(_timeZoneName) || !_localeId.HasValue)
                return;

            var request = new GetTimeZoneCodeByLocalizedNameRequest
            {
                LocaleId = _localeId.Value,
                LocalizedStandardName = _timeZoneName
            };

            var response = (GetTimeZoneCodeByLocalizedNameResponse)
                _serviceProxy.Execute(request);

            Console.WriteLine(String.Concat("Time zone code: ", response.TimeZoneCode,
                " retrieved for locale id: ", _localeId.Value, ", and time zone name: ",
                _timeZoneName));
        }

See More Examples