Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.EnableProxyTypes()

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

183 Examples 7

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

                    //<snippetCRUDEmailAttachments1>

                    // Create three e-mail attachments
                    for (int i = 0; i < 3; i++)
                    {
                        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
                        {
                            ObjectId = new EnreplacedyReference(Email.EnreplacedyLogicalName, _emailId),
                            ObjectTypeCode = Email.EnreplacedyLogicalName,
                            Subject = String.Format("Sample Attachment {0}", i),
                            Body = System.Convert.ToBase64String(
                                    new ASCIIEncoding().GetBytes("Example Attachment")),
                            FileName = String.Format("ExampleAttachment{0}.txt", i)
                        };

                        _emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);
                    }

                    Console.WriteLine("Created three e-mail attachments for the e-mail activity.");

                    // Retrieve an attachment including its id, subject, filename and body.
                    ActivityMimeAttachment _singleAttachment =
                        (ActivityMimeAttachment)_serviceProxy.Retrieve(
                                                    ActivityMimeAttachment.EnreplacedyLogicalName,
                                                    _emailAttachmentId[0],
                                                    new ColumnSet("activitymimeattachmentid",
                                                        "subject",
                                                        "filename",
                                                        "body"));

                    Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);

                    // Update attachment
                    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
                    _serviceProxy.Update(_singleAttachment);

                    Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);

                    // Retrieve all attachments replacedociated with the email activity.
                    QueryExpression _attachmentQuery = new QueryExpression
                    {
                        EnreplacedyName = ActivityMimeAttachment.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("activitymimeattachmentid"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "objectid",
                                Operator = ConditionOperator.Equal,
                                Values = {_emailId}
                            },
                            new ConditionExpression
                            {
                                AttributeName = "objecttypecode",
                                Operator = ConditionOperator.Equal,
                                Values = {Email.EnreplacedyLogicalName}
                            }
                        }
                        }
                    };

                    EnreplacedyCollection results = _serviceProxy.RetrieveMultiple(
                        _attachmentQuery);

                    Console.WriteLine("Retrieved all the e-mail attachments.");

                    //</snippetCRUDEmailAttachments1>

                    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 : WorkingWithActivityParties.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetWorkingWithActivityParties1>
                // 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();

                    OrganizationServiceContext orgContext =
                        new OrganizationServiceContext(_serviceProxy);

                    // Retrieve the Contact records that we created previously.
                    List<Contact> contacts = (from c in orgContext.CreateQuery<Contact>()
                                              where c.Address1_City == "Sammamish"
                                              select new Contact
                                              {
                                                  ContactId = c.ContactId,
                                                  FirstName = c.FirstName,
                                                  LastName = c.LastName
                                              }).ToList<Contact>();
                    Console.Write("Contacts retrieved, ");

                    // Create an Activity Party record for each Contact.
                    var activityParty1 = new ActivityParty
                    {
                        PartyId = new EnreplacedyReference(Contact.EnreplacedyLogicalName,
                            contacts[0].ContactId.Value),
                    };

                    var activityParty2 = new ActivityParty
                    {
                        PartyId = new EnreplacedyReference(Contact.EnreplacedyLogicalName,
                            contacts[1].ContactId.Value),
                    };

                    var activityParty3 = new ActivityParty
                    {
                        PartyId = new EnreplacedyReference(Contact.EnreplacedyLogicalName,
                            contacts[2].ContactId.Value),
                    };

                    Console.Write("ActivityParty instances created, ");

                    // Create Letter Activity and set From and To fields to the
                    // respective Activity Party enreplacedies.
                    var letter = new Letter
                    {
                        RegardingObjectId = new EnreplacedyReference(Contact.EnreplacedyLogicalName,
                            contacts[2].ContactId.Value),
                        Subject = "Sample Letter Activity",
                        ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
                        Description = @"Greetings, Mr. Andreshak,

This is a sample letter activity as part of the Microsoft Dynamics CRM SDK.

Sincerely,
Mary Kay Andersen

cc: Denise Smith",
                        From = new ActivityParty[] { activityParty1 },
                        To = new ActivityParty[] { activityParty3, activityParty2 }
                    };
                    orgContext.AddObject(letter);
                    orgContext.SaveChanges();

                    Console.WriteLine("and Letter Activity created.");

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

            // 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 : UploadAndDownloadAttachment.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetUploadAndDownloadAttachment1>
                // 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();

                    #region Create and Upload annotation attachment

                    // Instantiate an Annotation object.
                    // See the Enreplacedy Metadata topic in the SDK doreplacedentation to determine
                    // which attributes must be set for each enreplacedy.
                    Annotation setupAnnotation = new Annotation()
                    {
                        Subject = "Example Annotation",
                        FileName = "ExampleAnnotationAttachment.txt",
                        DoreplacedentBody = Convert.ToBase64String(
                            new UnicodeEncoding().GetBytes("Sample Annotation Text")),
                        MimeType = "text/plain"
                    };

                    // Create the Annotation object.
                    _annotationId = _serviceProxy.Create(setupAnnotation);

                    Console.Write("{0} created with an attachment", setupAnnotation.Subject);

                    #endregion Create and Upload annotation attachment

                    #region Download attachment from annotation record

                    // Define columns to retrieve from the annotation record.
                    ColumnSet cols = new ColumnSet("filename", "doreplacedentbody");
                   

                    // Retrieve the annotation record.
                    Annotation retrievedAnnotation = 
                        (Annotation)_serviceProxy.Retrieve("annotation", _annotationId, cols);
                    Console.WriteLine(", and retrieved.");
                    _fileName = retrievedAnnotation.FileName;

                    // Download the attachment in the current execution folder.
                    using (FileStream fileStream = new FileStream(retrievedAnnotation.FileName, FileMode.OpenOrCreate))
                    {
                        byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DoreplacedentBody);
                        fileStream.Write(fileContent, 0, fileContent.Length);
                    }

                    Console.WriteLine("Attachment downloaded.");

                    #endregion Download attachment from annotation record

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

            // 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 : 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 : 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 : ConvertFaxToTask.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();

                    //<snippetConvertFaxToTask1>               

                    // Retrieve the fax.
                    Fax retrievedFax = (Fax)_serviceProxy.Retrieve(Fax.EnreplacedyLogicalName, _faxId, new ColumnSet(true));

                    // Create a task.
                    Task task = new Task()
                    {
                        Subject = "Follow Up: " + retrievedFax.Subject,
                        ScheduledEnd = retrievedFax.CreatedOn.Value.AddDays(7),
                    };
                    _taskId = _serviceProxy.Create(task);

                    // Verify that the task has been created                    
                    if (_taskId != Guid.Empty)
                    {
                        Console.WriteLine("Created a task for the fax: '{0}'.", task.Subject);
                    }                   

                    //</snippetConvertFaxToTask1>

                    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 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 : ImpersonateWithOnBehalfOfPrivilege.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetImpersonateWithOnBehalfOfPrivilege1>
                //<snippetImpersonateWithOnBehalfOfPrivilege2>
                // Connect to the Organization service. 
                // The using statement ensures 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();

                    // Retrieve the system user ID of the user to impersonate.
                    OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
                    _userId = (from user in orgContext.CreateQuery<SystemUser>()
                              where user.FullName == "Kevin Cook"
                              select user.SystemUserId.Value).FirstOrDefault();

                    // To impersonate another user, set the OrganizationServiceProxy.CallerId
                    // property to the ID of the other user.
                    _serviceProxy.CallerId = _userId;

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

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

                    // Retrieve the account containing several of its attributes.
                    // CreatedBy should reference the impersonated SystemUser.
                    // CreatedOnBehalfBy should reference the running SystemUser.
                    ColumnSet cols = new ColumnSet(
                        "name",
                        "createdby",
                        "createdonbehalfby",
                        "address1_postalcode",
                        "lastusedincampaign");

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

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

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

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

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

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.Write("updated, ");

                    // Delete the account record.
                    _serviceProxy.Delete(Account.EnreplacedyLogicalName, _accountId);
                    Console.WriteLine("and deleted.");

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

            // 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 : WorkingWithActivityFeeds.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();
                _serviceContext = new ServiceContext(_serviceProxy);

                try
                {
                    ConfigureActivityFeeds();
                    PostToRecordWalls();
                    PostToPersonalWalls();
                    ShowRecordWalls();
                    DeleteRequiredRecords(promptForDelete);
                }
                catch (InvalidSampleExecutionException e)
                {
                    Console.WriteLine(e.Message);
                    DeleteRequiredRecords(promptForDelete);
                }
            }
        }

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 : 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 : 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 : Program.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // Enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

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

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

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

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

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

                // Enable auditing on account enreplacedies.
                bool accountAuditingFlag = EnableEnreplacedyAuditing(Account.EnreplacedyLogicalName, true);
                //</snippetAuditing1>
                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

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

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

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

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

                #region Retrieve the Attribute Change History

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

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

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

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

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

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

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

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

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

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

                #endregion Retrieve the Audit Details

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

                EnableEnreplacedyAuditing(Account.EnreplacedyLogicalName, accountAuditingFlag);

                #endregion Revert Auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }

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 : 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 : BulkDeleteBackup.cs
with MIT License
from microsoft

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

                PerformBulkDeleteBackup();
                DeleteRequiredRecords(promptToDelete);
            }
        }

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

                    //<snippetConfigureQueueEmail1>
                    // Define some anonymous types to define the range 
                    // of possible queue property values.
                    var IncomingEmailDeliveryMethods = new
                    {
                        None = 0,
                        EmailRouter = 2,
                        ForwardMailbox = 3
                    };

                    var IncomingEmailFilteringMethods = new
                    {
                        AllEmailMessages = 0,
                        EmailMessagesInResponseToCrmEmail = 1,
                        EmailMessagesFromCrmLeadsContactsAndAccounts = 2
                    };

                    var OutgoingEmailDeliveryMethods = new
                    {
                        None = 0,
                        EmailRouter = 2
                    };

                    // Update a queue instance and set its email property values.
                    Queue configureQueue = new Queue()
                    {
                        QueueId = _queueId,
                        IncomingEmailDeliveryMethod = new OptionSetValue(
                            IncomingEmailDeliveryMethods.EmailRouter),
                        IncomingEmailFilteringMethod = new OptionSetValue(
                            IncomingEmailFilteringMethods.EmailMessagesInResponseToCrmEmail),
                        OutgoingEmailDeliveryMethod = new OptionSetValue(
                            OutgoingEmailDeliveryMethods.None),

                        // TODO: Update with appropriate address 
                        // for accessing the e-mail router. 
                        EMailAddress = "[email protected]",                        
                    };

                    _serviceProxy.Update(configureQueue);
                    //</snippetConfigureQueueEmail1>  

                    Console.WriteLine("Configured the queue's email property values.");

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

                    //<snippetCreateConnection1>
                    // Create a connection between the account and the contact.
                    // replacedign a connection role to a record.
                    Connection newConnection = new Connection
                    {
                        Record1Id = new EnreplacedyReference(Account.EnreplacedyLogicalName,
                            _accountId),
                        Record1RoleId = new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                            _connectionRoleId),                             
                        Record2RoleId = new EnreplacedyReference(ConnectionRole.EnreplacedyLogicalName,
                            _connectionRoleId),                            
                        Record2Id = new EnreplacedyReference(Contact.EnreplacedyLogicalName,
                            _contactId)
                    };

                    _connectionId = _serviceProxy.Create(newConnection);
                    //</snippetCreateConnection1>  

                    Console.WriteLine(
                        "Created a connection between the account and the contact.");

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


                    //<snippetCreateConnectionRole1>
                    // Define some anonymous types to define the range 
                    // of possible connection property values.
                    var Categories = new
                    {
                        Business = 1,
                        Family = 2,
                        Social = 3,
                        Sales = 4,
                        Other = 5
                    };

                    // Create a Connection Role for account and contact
                    ConnectionRole newConnectionRole = new ConnectionRole
                    {
                        Name = "Example Connection Role",
                        Category = new OptionSetValue(Categories.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.");
                    //</snippetCreateConnectionRole1>  

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

                    //<snippetCreateQueue1> 			
                    // Define some anonymous types to define the range of possible 
                    // queue property values.
                    var IncomingEmailDeliveryMethods = new
                    {
                        None = 0,
                        EmailRouter = 2,
                        ForwardMailbox = 3
                    };

                    var IncomingEmailFilteringMethods = new
                    {
                        AllEmailMessages = 0,
                        EmailMessagesInResponseToCrmEmail = 1,
                        EmailMessagesFromCrmLeadsContactsAndAccounts = 2
                    };

                    var OutgoingEmailDeliveryMethods = new
                    {
                        None = 0,
                        EmailRouter = 2
                    };

                    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.",
                        IncomingEmailDeliveryMethod = new OptionSetValue(
                            IncomingEmailDeliveryMethods.None),
                        IncomingEmailFilteringMethod = new OptionSetValue(
                            IncomingEmailFilteringMethods.AllEmailMessages),
                        OutgoingEmailDeliveryMethod = new OptionSetValue(
                            OutgoingEmailDeliveryMethods.None),
                        QueueViewType = new OptionSetValue(
                            QueueViewType.Private)
                    };

                    // Create a new queue instance.
                    _queueId = _serviceProxy.Create(newQueue);
                    //</snippetCreateQueue1>

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

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



                    //<snippetDeleteQueue1> 			
                    // Delete the queue instance.
                    _serviceProxy.Delete(Queue.EnreplacedyLogicalName, _queueId);

                    //</snippetDeleteQueue1>

                    Console.WriteLine("Deleted a queue instance.");
                }
            }
            // 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 : QueryConnectionRolesByEntityTypeCode.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                //<snippetQueryConnectionRolesByEnreplacedyTypeCode1>
                // 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();

                    // Define some anonymous types to define the range 
                    // of possible connection property values.
                    var Categories = new
                    {
                        Business = 1,
                        Family = 2,
                        Social = 3,
                        Sales = 4,
                        Other = 5
                    };

                    // Create a Connection Role.
                    ConnectionRole setupConnectionRole = new ConnectionRole
                    {
                        Name = "Example Connection Role",
                        Category = new OptionSetValue(Categories.Business),
                    };

                    _connectionRoleId = _serviceProxy.Create(setupConnectionRole);
                    setupConnectionRole.Id = _connectionRoleId;

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

                    // Query for all Connection Roles.
                    QueryExpression allQuery = new QueryExpression
                    {
                        EnreplacedyName = ConnectionRole.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("connectionroleid", "name"),
                        Distinct = true,
                        LinkEnreplacedies = 
                        {
                            new LinkEnreplacedy
                            {
                                LinkToEnreplacedyName = 
                                ConnectionRoleObjectTypeCode.EnreplacedyLogicalName,
                                LinkToAttributeName = "connectionroleid",
                                LinkFromEnreplacedyName = ConnectionRole.EnreplacedyLogicalName,
                                LinkFromAttributeName = "connectionroleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    // Set a condition to only get connection roles  
                                    // related to all enreplacedies (object type code = 0).
                                    Conditions = 
                                    {
                                        new ConditionExpression 
                                        {
                                             AttributeName = "replacedociatedobjecttypecode",
                                             Operator = ConditionOperator.Equal,
                                             Values = { 0 }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    EnreplacedyCollection results = _serviceProxy.RetrieveMultiple(allQuery);

                    // Here you could perform operations on all of 
                    // the connectionroles found by the query.

                    Console.WriteLine("Retrieved {0} unreplacedociated connectionrole instance(s).",
                        results.Enreplacedies.Count);

                    // Query to find roles which apply only to accounts.
                    QueryExpression accountQuery = new QueryExpression
                    {
                        EnreplacedyName = ConnectionRole.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("connectionroleid", "name"),
                        Distinct = true,
                        LinkEnreplacedies = 
                        {
                            new LinkEnreplacedy
                            {
                                LinkToEnreplacedyName = 
                                ConnectionRoleObjectTypeCode.EnreplacedyLogicalName,
                                LinkToAttributeName = "connectionroleid",
                                LinkFromEnreplacedyName = ConnectionRole.EnreplacedyLogicalName,
                                LinkFromAttributeName = "connectionroleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    // Set a condition to only get connection roles  
                                    // related to accounts (object type code = 1).
                                    Conditions = 
                                    {
                                        new ConditionExpression 
                                        {
                                             AttributeName = "replacedociatedobjecttypecode",
                                             Operator = ConditionOperator.In,
                                             Values = { Account.EnreplacedyLogicalName }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Enreplacedies.Count);

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

                    setupAccountConnectionRoleTypeCode.Id = 
                        _serviceProxy.Create(setupAccountConnectionRoleTypeCode);

                    Console.Write("Created a related Connection Role Object Type Code");
                    Console.Write(" record for Account.");

                    // Run the query to find unreplacedociated connectionroles again.
                    results = _serviceProxy.RetrieveMultiple(allQuery);
                    
                    Console.WriteLine(@"Retrieved {0} unreplacedociated connectionrole instance(s).",
                        results.Enreplacedies.Count);

                    // Run the account-only query again.
                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Enreplacedies.Count);

                    // Remove the link from account enreplacedy.
                    _serviceProxy.Delete(ConnectionRoleObjectTypeCode.EnreplacedyLogicalName, 
                        setupAccountConnectionRoleTypeCode.Id);

                    Console.WriteLine("Removed link from connectionrole to account enreplacedy.");

                    // Run the query to find unreplacedociated connectionroles again.
                    results = _serviceProxy.RetrieveMultiple(allQuery);

                    Console.WriteLine("Retrieved {0} unreplacedociated connectionrole instance(s).",
                        results.Enreplacedies.Count);

                    // Run the account-only query again.
                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Enreplacedies.Count);

                    DeleteRequiredRecords(promptForDelete);
                }
                //</snippetQueryConnectionRolesByEnreplacedyTypeCode1>
            }
            // 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 : QueryConnectionRolesByReciprocalRole.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();

                    //<snippetQueryConnectionRolesByReciprocalRole1>
                    // This query retrieves all connection roles that have this role
                    // listed as a reciprocal role.
                    QueryExpression query = new QueryExpression
                    {
                        EnreplacedyName = ConnectionRole.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("connectionroleid"),
                        LinkEnreplacedies = 
                    {
                        new LinkEnreplacedy
                        {
                            JoinOperator = JoinOperator.Inner,
                            LinkFromEnreplacedyName =  ConnectionRole.EnreplacedyLogicalName,
                            LinkFromAttributeName = "connectionroleid",
                            LinkToEnreplacedyName = "connectionrolereplacedociation",
                            LinkToAttributeName = "connectionroleid",
                            LinkCriteria = new FilterExpression
                            {
                                FilterOperator = LogicalOperator.And,
                                Conditions = 
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "replacedociatedconnectionroleid",
                                        Operator = ConditionOperator.Equal,
                                        Values = { _reciprocalConnectionRoleId }                                        
                                    }
                                }
                            }
                        }
                    }
                    };

                    EnreplacedyCollection results = _serviceProxy.RetrieveMultiple(query);

                    // TODO: Here you would perform some operation on the retrieved
                    // roles. 
                    //</snippetQueryConnectionRolesByReciprocalRole1>  

                    Console.WriteLine("Retrieved {0} connectionrole instance.", results.Enreplacedies.Count);

                    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 : WorkingWithLeads.cs
with MIT License
from microsoft

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

                Console.WriteLine("=== Creating and Qualifying Leads ===");

                // Create two leads.
                var lead1 = new Lead
                {
                    CompanyName = "A. Datum Corporation",
                    FirstName = "Henriette",
                    LastName = "Andersen",
                    Subject = "Sample Lead 1"
                };

                _lead1Id = _serviceProxy.Create(lead1);
                NotifyEnreplacedyCreated(Lead.EnreplacedyLogicalName, _lead1Id);

                var lead2 = new Lead
                {
                    CompanyName = "Adventure Works",
                    FirstName = "Michael",
                    LastName = "Sullivan",
                    Subject = "Sample Lead 2"
                };

                _lead2Id = _serviceProxy.Create(lead2);
                NotifyEnreplacedyCreated(Lead.EnreplacedyLogicalName, _lead2Id);

                //<snippetWorkingWithLeads1>
                // Qualify the first lead, creating an account and a contact from it, but
                // not creating an opportunity.
                var qualifyIntoAccountContactReq = new QualifyLeadRequest
                {
                    CreateAccount = true,
                    CreateContact = true,
                    LeadId = new EnreplacedyReference(Lead.EnreplacedyLogicalName, _lead1Id),
                    Status = new OptionSetValue((int)lead_statuscode.Qualified)
                };

                var qualifyIntoAccountContactRes = 
                    (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq);
                Console.WriteLine("  The first lead was qualified.");
                //</snippetWorkingWithLeads1>
                foreach (var enreplacedy in qualifyIntoAccountContactRes.CreatedEnreplacedies)
                {
                    NotifyEnreplacedyCreated(enreplacedy.LogicalName, enreplacedy.Id);
                    if (enreplacedy.LogicalName == Account.EnreplacedyLogicalName)
                    {
                        _leadAccountId = enreplacedy.Id;
                    }
                    else if (enreplacedy.LogicalName == Contact.EnreplacedyLogicalName)
                    {
                        _contactId = enreplacedy.Id;
                    }
                }

                // Retrieve the organization's base currency ID for setting the
                // transaction currency of the opportunity.
                var query = new QueryExpression("organization");
		        query.ColumnSet = new ColumnSet("basecurrencyid");
		        var result = _serviceProxy.RetrieveMultiple(query);
		        var currencyId = (EnreplacedyReference)result.Enreplacedies[0]["basecurrencyid"];

                // Qualify the second lead, creating an opportunity from it, and not
                // creating an account or a contact.  We use an existing account for the
                // opportunity customer instead.
                var qualifyIntoOpportunityReq = new QualifyLeadRequest
                {
                    CreateOpportunity = true,
                    OpportunityCurrencyId = currencyId,
                    OpportunityCustomerId = new EnreplacedyReference(
                        Account.EnreplacedyLogicalName,
                        _accountId),
                    Status = new OptionSetValue((int)lead_statuscode.Qualified),
                    LeadId = new EnreplacedyReference(Lead.EnreplacedyLogicalName, _lead2Id)
                };

                var qualifyIntoOpportunityRes =
                    (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq);
                Console.WriteLine("  The second lead was qualified.");

                foreach (var enreplacedy in qualifyIntoOpportunityRes.CreatedEnreplacedies)
                {
                    NotifyEnreplacedyCreated(enreplacedy.LogicalName, enreplacedy.Id);
                    if (enreplacedy.LogicalName == Opportunity.EnreplacedyLogicalName)
                    {
                        _opportunityId = enreplacedy.Id;
                    }
                }

                DeleteRecords(promptforDelete);
            }
        }

19 Source : WorkingWithNegativePrices.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetWorkingWithNegativePrices1>
                // 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 Opportunity with negative estimated value

                    // Create a new opportunity with user-specified negative 
                    // estimated value.
                    Opportunity opportunity = new Opportunity
                    {
                        Name = "Example Opportunity",
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName,
                            _accountId),
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue = new Money(-400.00m),
                        FreightAmount = new Money(10.00m),
                        ActualValue = new Money(-390.00m),
                        OwnerId = new EnreplacedyReference
                        {
                            Id = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EnreplacedyLogicalName
                        }
                    };
                    _opportunityId = _serviceProxy.Create(opportunity);
                    opportunity.Id = _opportunityId;

                    // Create a catalog product for the opportunity.
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = opportunity.ToEnreplacedyReference(),
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                            _product1Id),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName,
                            _defaultUnitId),
                        Quanreplacedy = 8,
                        Tax = new Money(12.42m),
                    };
                    _catalogProductId = _serviceProxy.Create(catalogProduct);

                    Console.WriteLine("Created opportunity with negative estimated value.");

                    #endregion

                    #region Quote with negative quanreplacedy

                    // Create the quote.
                    Quote quote = new Quote()
                    {
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName, 
                            _accountId),
                        Name = "Sample Quote",
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId)
                    };
                    _quoteId = _serviceProxy.Create(quote);
                    quote.Id = _quoteId;

                    // Set the quote's product quanreplacedy to a negative value.
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                            _product1Id),
                        Quanreplacedy = -4,
                        QuoteId = quote.ToEnreplacedyReference(),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, 
                            _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Created quote with negative quanreplacedy.");

                    #endregion

                    #region Sales Order with negative price

                    // Create the sales order.
                    SalesOrder order = new SalesOrder()
                    {
                        Name = "Faux Order",
                        DateFulfilled = new DateTime(2010, 8, 1),
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId),
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName,
                            _accountId),
                        FreightAmount = new Money(20.0M)
                    };
                    _orderId = _serviceProxy.Create(order);
                    order.Id = _orderId;

                    // Add the product to the order with the price overriden with a
                    // negative value.
                    SalesOrderDetail orderDetail = new SalesOrderDetail()
                    {
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName, 
                            _product1Id),
                        Quanreplacedy = 4,
                        SalesOrderId = order.ToEnreplacedyReference(),
                        IsPriceOverridden = true,
                        PricePerUnit = new Money(-40.0M),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, 
                            _defaultUnitId)
                    };
                    _orderDetailId = _serviceProxy.Create(orderDetail);

                    Console.WriteLine("Created order with negative price per unit.");

                    #endregion

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

            // 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 : BulkDeleteOperations.cs
with MIT License
from microsoft

public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                using (_context = new AdventureWorksCycleServiceContext(_serviceProxy))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // This statments checks whether Standard Email templates are present
                    var emailTemplateId = (
                                       from emailTemplate in _context.TemplateSet
                                       where emailTemplate.replacedle == "Contact Reconnect"
                                       select emailTemplate.Id
                                      ).FirstOrDefault();             
                           
                    if (emailTemplateId != Guid.Empty)
                    {
                        CreateRequiredRecords();

                        // Perform the bulk delete.  If you want to perform a recurring delete
                        // operation, then leave this as it is.  Otherwise, preplaced in false as the
                        // first parameter.
                        PerformBulkDelete(true, promptToDelete);
                    }
                    else
                    {
                        throw new ArgumentException("Standard Email Templates are missing");
                    }
                }
            }
        }

19 Source : AssignQueueItemWorker.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();

                    //<snippetreplacedignQueueItemWorker1>
                    // Retrieve the current user information.
                    WhoAmIRequest whoAmIRequest = new WhoAmIRequest();
                    WhoAmIResponse whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute(
                        whoAmIRequest);

                    ColumnSet columnSet = new ColumnSet("fullname");
                    SystemUser currentUser = (SystemUser)_serviceProxy.Retrieve(
                        SystemUser.EnreplacedyLogicalName,
                        whoAmIResponse.UserId, columnSet);
                    String currentUserName = currentUser.FullName;
                    _userId = currentUser.Id;

                    // Create an instance of an existing queueitem in order to specify 
                    // the user that will be working on it using PickFromQueueRequest.

                    PickFromQueueRequest pickFromQueueRequest = new PickFromQueueRequest
                    {
                        QueueItemId = _queueItemId,
                        WorkerId = _userId
                    };

                    _serviceProxy.Execute(pickFromQueueRequest);
                    //</snippetreplacedignQueueItemWorker1>  

                    Console.WriteLine("The letter queue item is queued for new owner {0}.",
                        currentUserName);

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

                    //<snippetCreateOpportunity1>

                    // Create a new opportunity with user specified estimated revenue
                    Opportunity newOpportunity = new Opportunity
                    {
                        Name = "Example Opportunity",
                        CustomerId = new EnreplacedyReference(Account.EnreplacedyLogicalName,
                            _accountId),
                        PriceLevelId = new EnreplacedyReference(PriceLevel.EnreplacedyLogicalName,
                            _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue = new Money(400.00m),
                        FreightAmount = new Money(10.00m),
                        DiscountAmount = new Money(0.10m),
                        DiscountPercentage = 0.20m
                    };

                    _opportunityId = _serviceProxy.Create(newOpportunity);
                    Console.WriteLine("Created {0} with user specified estimated revenue.",
                        newOpportunity.Name);

                    // Create a new opportunity product from the catalog

                    // Create a catalog product
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = new EnreplacedyReference(Opportunity.EnreplacedyLogicalName,
                            _opportunityId),
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                            _product1Id),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                        Quanreplacedy = 8,
                        Tax = new Money(12.42m)
                    };

                    _catalogProductId = _serviceProxy.Create(catalogProduct);
                    Console.WriteLine("Created the catalog product.");

                    // Create anothter catalog product and override the list price
                    OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
                    {
                        OpportunityId = new EnreplacedyReference(Opportunity.EnreplacedyLogicalName,
                            _opportunityId),
                        ProductId = new EnreplacedyReference(Product.EnreplacedyLogicalName,
                            _product2Id),
                        UoMId = new EnreplacedyReference(UoM.EnreplacedyLogicalName, _defaultUnitId),
                        Quanreplacedy = 3,
                        Tax = new Money(2.88m),
                        IsPriceOverridden = true,
                        PricePerUnit = new Money(12)
                    };

                    _catalogProductPriceOverrideId = _serviceProxy.Create(
                        catalogProductPriceOverride);
                    Console.WriteLine(@"Created another catalog product and 
                    overriden the list price.");

                    // create a new write-in opportunity product with a manual discount applied
                    OpportunityProduct writeInProduct = new OpportunityProduct
                    {
                        OpportunityId = new EnreplacedyReference(Opportunity.EnreplacedyLogicalName,
                            _opportunityId),
                        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(writeInProduct);
                    Console.WriteLine("Created {0}.", writeInProduct.ProductDescription);
                    //</snippetCreateOpportunity1>                

                    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 : 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 : FulfillSalesOrder.cs
with MIT License
from microsoft

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

                CreateCustomer();
                CreateSalesOrder();
                CloseSalesOrder();
                DeleteRequiredRecords(promptforDelete);
            }
        }

19 Source : Merge.cs
with MIT License
from microsoft

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

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

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

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

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

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

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

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

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

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

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

                DeleteRequiredRecords(promptForDelete);
            }
        }

19 Source : QueryConnections.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();

                    //<snippetQueryConnections1>
                    // This query retrieves all connections this contact is part of.
                    QueryExpression query = new QueryExpression
                    {
                        EnreplacedyName = Connection.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("connectionid"),
                        Criteria = new FilterExpression
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions = 
                        {
                            // You can safely query against only record1id or
                            // record2id - CRM will find all connections this 
                            // enreplacedy is a part of either way.
                            new ConditionExpression
                            {
                                AttributeName = "record1id",
                                Operator = ConditionOperator.Equal,
                                Values = { _contactId }
                            }
                        }
                        }
                    };

                    EnreplacedyCollection results = _serviceProxy.RetrieveMultiple(query);

                    // TODO: Here you could do a variety of tasks with the 
                    // connections retrieved, such as listing the connected enreplacedies,
                    // finding reciprocal connections, etc.
                    //</snippetQueryConnections1>  

                    Console.WriteLine("Retrieved {0} connectionrole instances.", results.Enreplacedies.Count);

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

                    //<snippetRemoveQueueItemWorker1>
                    // Remove worker from queue item to release queued object
                    // from worker's queue using ReleaseToQueueRequest

                    ReleaseToQueueRequest releaseToQueueRequest = new ReleaseToQueueRequest
                    {
                        QueueItemId = _queueItemId
                    };
                    _serviceProxy.Execute(releaseToQueueRequest);

                    Console.WriteLine("Released the queued object from worker queue.");
                    //</snippetRemoveQueueItemWorker1>                 

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

                    //<snippetRetrieveOpportunity1>
                    // Retrieve Opportunity record.                
                    Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
                        Opportunity.EnreplacedyLogicalName,
                        _opportunityId,
                        new ColumnSet("name"));

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

                    // Retrieve the related opportunity products
                    QueryExpression opportunityProductsQuery = new QueryExpression
                    {
                        EnreplacedyName = OpportunityProduct.EnreplacedyLogicalName,
                        ColumnSet = new ColumnSet("opportunityproductid", "volumediscountamount"),
                        Criteria = new FilterExpression
                        {
                            Conditions = 
                        {
                            new ConditionExpression 
                            {
                                AttributeName = "opportunityid",
                                Operator = ConditionOperator.Equal,
                                Values = { _opportunityId }
                            }
                        }
                        }
                    };

                    DataCollection<Enreplacedy> opportunityProducts = _serviceProxy.RetrieveMultiple(
                        opportunityProductsQuery).Enreplacedies;

                    foreach (Enreplacedy enreplacedy in opportunityProducts)
                    {
                        OpportunityProduct opportunityProduct = (OpportunityProduct)enreplacedy;
                        Console.WriteLine("Retrieved Opportunity Product {0}",
                            opportunityProduct.OpportunityProductId.Value);
                    }
                    //</snippetRetrieveOpportunity1>                

                    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 : 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 : SerializeAndDeserialize.cs
with MIT License
from microsoft

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

                CreateRequiredRecords();

                #region Retrieve the contact from Microsoft CRM

                // Create the column set object that indicates the fields to be retrieved.
                var columns = new ColumnSet(
                    "contactid",
                    "firstname",
                    "lastname",
                    "jobreplacedle");

                // Retrieve the contact from Microsoft CRM using the ID of the record that was just created.
                // The EnreplacedyLogicalName indicates the EnreplacedyType of the object being retrieved.
                var contact = (Contact)_serviceProxy.Retrieve(
                    Contact.EnreplacedyLogicalName, _contactId, columns);

                Console.WriteLine("The contact for the sample has been retrieved.");

                #endregion

                #region Serialize the contact into XML and save it

                // Serialize the contact into XML and write it to the hard drive.
                var earlyBoundSerializer = new DataContractSerializer(typeof(Contact));

                // Create a unique file name for the XML.
                String earlyboundFile = "Contact_early_" + contact.ContactId.Value.ToString("B") + ".xml";

                // Write the serialized object to a file.  The using statement will
                // ensure that the FileStream is disposed of correctly.  The FileMode
                // will ensure that the file is overwritten if it already exists.
                using (var file = new FileStream(earlyboundFile, FileMode.Create))
                {
                    // Write the XML to disk.
                    earlyBoundSerializer.WriteObject(file, contact);
                }

                Console.WriteLine(
                    "The early-bound contact instance has been serialized to a file, {0}.",
                    earlyboundFile);

                // Convert the contact to a late-bound enreplacedy instance and serialize it to disk.
                var lateboundContact = contact.ToEnreplacedy<Enreplacedy>();
                String lateboundFile = "Contact_late_" + lateboundContact.Id.ToString("B") + ".xml";

                var lateBoundSerializer = new DataContractSerializer(typeof(Enreplacedy));
                // Write the serialized object to a file.
                using (var file = new FileStream(lateboundFile, FileMode.Create))
                {
                    lateBoundSerializer.WriteObject(file, lateboundContact);
                }

                Console.WriteLine(
                    "The late-bound contact instance has been serialized to a file, {0}.",
                    lateboundFile);

                #endregion

                #region De-serialize the Microsoft CRM contact from XML

                Contact deserializedContact = null;
                using (var file = new FileStream(earlyboundFile, FileMode.Open))
                {
                    deserializedContact = (Contact)earlyBoundSerializer.ReadObject(file);
                    Console.WriteLine("The contact has been de-serialized: {0} {1}",
                        deserializedContact.FirstName, deserializedContact.LastName);
                }

                #endregion

                #region Update contact in Microsoft CRM

                // Update the contact in Microsoft CRM to prove that the de-serialization worked.
                deserializedContact.Jobreplacedle = "Plumber";
                _serviceProxy.Update(deserializedContact);

                Console.WriteLine("The contact was updated in Microsoft CRM.");

                #endregion

                DeleteRequiredRecords(promptToDelete);
            }
        }

19 Source : UpdateConnectionRole.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();

                    //<snippetUpdateConnectionRole1>
                    // Define some anonymous types to define the range 
                    // of possible connection property values.
                    var Categories = new
                    {
                        Business = 1,
                        Family = 2,
                        Social = 3,
                        Sales = 4,
                        Other = 5
                    };

                    // Update the connectionrole instance.
                    ConnectionRole connectionRole = new ConnectionRole
                    {
                        ConnectionRoleId = _connectionRoleId,
                        Name = "Updated Connection Role",
                        Description = "This is an updated connection role.",
                        Category = new OptionSetValue(Categories.Other)
                    };

                    _serviceProxy.Update(connectionRole);

                    //</snippetUpdateConnectionRole1>  

                    Console.WriteLine("Updated the connectionrole instance.");

                    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 : ValidateAndSetState.cs
with MIT License
from microsoft

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

                //Create the Contact and Incident required for this sample.
                CreateRequiredRecords();

                //<snippetIsValidStateTransition>
                // Create an EnreplacedyReference to represent an open case
                EnreplacedyReference caseReference = new EnreplacedyReference()
                {
                    LogicalName = Incident.EnreplacedyLogicalName,
                    Id = _caseIncidentId
                };

                IsValidStateTransitionRequest checkState = 
                    new IsValidStateTransitionRequest();

                // Set the transition request to an open case
                checkState.Enreplacedy = caseReference;

                // Check to see if a new state of "resolved" and 
                // a new status of "problem solved" are valid
                checkState.NewState = IncidentState.Resolved.ToString();
                checkState.NewStatus = (int)incident_statuscode.ProblemSolved;

                // Execute the request
                IsValidStateTransitionResponse checkStateResponse = 
                    (IsValidStateTransitionResponse)_serviceProxy.Execute(checkState);
                //</snippetIsValidStateTransition>  

                // Handle the response
                if (checkStateResponse.IsValid)
                {
                    String changeAnswer = "y"; // default to "y" unless prompting for delete
                    if (promptForDelete)
                    {
                        // The case can be closed
                        Console.WriteLine("Validate State Request returned that the case " +
                                          "can be closed.");
                        Console.Write("\nDo you want to change the record state? " +
                                          "(y/n) [y]: ");
                        changeAnswer = Console.ReadLine();
                        Console.WriteLine();
                    }

                    if (changeAnswer.StartsWith("y") || changeAnswer.StartsWith("Y")
                        || changeAnswer == String.Empty)
                    {
                        // Call function to change the incident to the closed state
                        CloseIncident(caseReference);
                        // Re-open the incident and change its state
                        SetState(caseReference);
                    }
                }
                else
                {
                    // The case cannot be closed
                    Console.WriteLine("Validate State Request returned that the " +
                                      "change is not valid.");
                }

                DeleteRequiredRecords(promptForDelete);
            }
        }

19 Source : ChangeTrackingSample.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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Check CRM version
                    if(CheckCRMVersion())
                    {
                        // Import the ChangeTrackingSample solution if it is not already installed.
                        ImportChangeTrackingSolution();

                        // Wait for enreplacedy and key index to be active.
                        WaitForEnreplacedyAndKeysToBeActive(_serviceProxy, _customBooksEnreplacedyName.ToLower());

                        // Create 10 demo records.
                        CreateRequiredRecords();

                        //<snippetChangeTrackingSample1>
                        string token;

                        // Initialize page number.
                        int pageNumber = 1;
                        List<Enreplacedy> initialrecords = new List<Enreplacedy>();

                        // Retrieve records by using Change Tracking feature.
                        RetrieveEnreplacedyChangesRequest request = new RetrieveEnreplacedyChangesRequest();
                        request.EnreplacedyName = _customBooksEnreplacedyName.ToLower();
                        request.Columns = new ColumnSet("sample_bookcode", "sample_name", "sample_author");
                        request.PageInfo = new PagingInfo() { Count = 5000, PageNumber = 1, ReturnTotalRecordCount = false };


                        // Initial Synchronization. Retrieves all records as well as token value.
                        Console.WriteLine("Initial synchronization....retrieving all records.");
                        while (true)
                        {
                            RetrieveEnreplacedyChangesResponse response = (RetrieveEnreplacedyChangesResponse)_serviceProxy.Execute(request);

                            initialrecords.AddRange(response.EnreplacedyChanges.Changes.Select(x => (x as NewOrUpdatedItem).NewOrUpdatedEnreplacedy).ToArray());
                            initialrecords.ForEach(x => Console.WriteLine("initial record id:{0}", x.Id));
                            if (!response.EnreplacedyChanges.MoreRecords)
                            {
                                // Store token for later query
                                token = response.EnreplacedyChanges.DataToken;
                                break;

                            }
                            // Increment the page number to retrieve the next page.
                            request.PageInfo.PageNumber++;
                            // Set the paging cookie to the paging cookie returned from current results.
                            request.PageInfo.PagingCookie = response.EnreplacedyChanges.PagingCookie;
                        }
                        //</snippetChangeTrackingSample1>

                        // Display the initial records.
                        // Do you like to view the records in browser? Add code.
                        if (PromptForView())
                        {
                            ViewEnreplacedyListInBrowser();
                        }

                        // Delay 10 seconds, then create/update/delete records
                        Console.WriteLine("waiting 10 seconds until next operation..");
                        Thread.Sleep(10000);


                        // Add another 10 records, 1 update, and 1 delete.
                        UpdateRecords();

                        // Second Synchronization. Basically do the same.
                        // Reset paging
                        pageNumber = 1;
                        request.PageInfo.PageNumber = pageNumber;
                        request.PageInfo.PagingCookie = null;
                        // replacedign token
                        request.DataVersion = token;

                        // Instantiate cache.
                        List<Enreplacedy> updatedRecords = new List<Enreplacedy>();
                        List<EnreplacedyReference> deletedRecords = new List<EnreplacedyReference>();

                        while (true)
                        {

                            RetrieveEnreplacedyChangesResponse results = (RetrieveEnreplacedyChangesResponse)_serviceProxy.Execute(request);

                            updatedRecords.AddRange(results.EnreplacedyChanges.Changes.Where(x => x.Type == ChangeType.NewOrUpdated).Select(x => (x as NewOrUpdatedItem).NewOrUpdatedEnreplacedy).ToArray());
                            deletedRecords.AddRange(results.EnreplacedyChanges.Changes.Where(x => x.Type == ChangeType.RemoveOrDeleted).Select(x => (x as RemovedOrDeletedItem).RemovedItem).ToArray());


                            if (!results.EnreplacedyChanges.MoreRecords)
                                break;

                            // Increment the page number to retrieve the next page.
                            request.PageInfo.PageNumber++;
                            // Set the paging cookie to the paging cookie returned from current results.
                            request.PageInfo.PagingCookie = results.EnreplacedyChanges.PagingCookie;
                        }

                        // Do synchronizig work here.
                        Console.WriteLine("Retrieving changes since the last sync....");
                        updatedRecords.ForEach(x => Console.WriteLine("new or updated record id:{0}!", x.Id));
                        deletedRecords.ForEach(x => Console.WriteLine("record id:{0} deleted!", x.Id));

                        // Prompt to view the records in the browser.
                        if (PromptForView())
                        {
                            Console.WriteLine("Retrieving the changes for the sample_book enreplacedy.....");
                            ViewEnreplacedyListInBrowser();
                        }

                        // Prompts to delete the ChangeTrackingSample managed solution.
                        DeleteChangeTrackingSampleSolution(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 : UseAsyncDeploymentServiceMessages.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(serverConfig, promptforDelete);

		    //<snippetUseAsyncDeploymentServiceMessages1>
                    // Instantiate DeploymentServiceClient for calling the service.
                    client =
                        ProxyClientHelper.CreateClient(
                        new Uri(serverConfig.DiscoveryUri.ToString()
                            .Replace("Services", "Deployment")
                            .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context. 
                    if (serverConfig.Credentials == null)
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }

                    using (client)
                    {
                        // Set properties for the new organization
                        Microsoft.Xrm.Sdk.Deployment.Organization organization = 
                            new Microsoft.Xrm.Sdk.Deployment.Organization
                        {
                            BaseCurrencyCode = "USD",
                            BaseCurrencyName = "US Dollar",
                            BaseCurrencyPrecision = 2,
                            BaseCurrencySymbol = "$",
                            BaseLanguageCode = 1033,
                            FriendlyName = _friendlyName,
                            UniqueName = _uniqueName,
                            SqlCollation = "Latin1_General_CI_AI",
                            SqlServerName = _sqlServerName,
                            SrsUrl = _srsUrl,
                            SqmIsEnabled = false
                        };

                        // Create a request for the deployment web service
                        // CRM server app pool must have permissions on SQL server
                        BeginCreateOrganizationRequest request = 
                            new BeginCreateOrganizationRequest
                        {
                            Organization = organization,
                            SysAdminName = _sysAdminName
                        };

                        // Execute the request
                        BeginCreateOrganizationResponse response = 
                            (BeginCreateOrganizationResponse)client.Execute(request);

                        // The operation is asynchronous, so the response object contains
                        // a unique identifier for the operation
                        Guid operationId = response.OperationId;

                        // Retrieve the Operation using the OperationId
                        RetrieveRequest retrieveOperationStatus = new RetrieveRequest();
                        retrieveOperationStatus.EnreplacedyType = 
                            DeploymentEnreplacedyType.DeferredOperationStatus;
                        retrieveOperationStatus.InstanceTag = 
                            new EnreplacedyInstanceId { Id = operationId };

                        RetrieveResponse retrieveResponse;
                        DeferredOperationStatus deferredOperationStatus;

                        Console.WriteLine("Retrieving state of the job...");

                        // Retrieve the Operation State until Organization is created
                        do
                        {
                            // Wait 3 secs to not overload server
                            Thread.Sleep(3000);

                            retrieveResponse =
                            (RetrieveResponse)client.Execute(retrieveOperationStatus);

                            deferredOperationStatus = 
                                ((DeferredOperationStatus)retrieveResponse.Enreplacedy);
                        }
                        while (deferredOperationStatus.State != 
                            DeferredOperationState.Processing &&
                            deferredOperationStatus.State != 
                            DeferredOperationState.Completed);

                        // Poll OrganizationStatusRequest
                        RetrieveRequest retrieveReqServer = new RetrieveRequest();
                        retrieveReqServer.EnreplacedyType = DeploymentEnreplacedyType.Organization;
                        retrieveReqServer.InstanceTag = new EnreplacedyInstanceId();
                        retrieveReqServer.InstanceTag.Name = organization.UniqueName;

                        RetrieveResponse retrieveRespServer;
                        OrganizationState orgState;

                        Console.WriteLine("Retrieving state of the organization...");

                        // Retrieve and check the Organization State until is enabled
                        do
                        {
                            retrieveRespServer =
                                (RetrieveResponse)client.Execute(retrieveReqServer);
                            _organizationID = 
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Enreplacedy).Id;
                            orgState =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Enreplacedy).State;

                            // Wait 5 secs to not overload server
                            Thread.Sleep(5000);
                        }
                        while (orgState != OrganizationState.Enabled);

                        Console.WriteLine("Organization has been created!");

         		    //</snippetUseAsyncDeploymentServiceMessages1>
                        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

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

                _timeZoneId = new Guid("42B2880D-BED5-4AA3-BD69-418052D38B7E");
                _timeZoneName = "Central Standard Time";
                RetrieveCurrentUsersSettings();
                     
                RetrieveAllTimeZonesForLocale();
                GetTimeZoneCodeByLocaleAndName();
                RetrieveTimeZoneById();
                RetrieveTimeZonesLessThan50();
                RetrieveLocalTimeFromUTCTime(new DateTime(1981, 6, 6, 9, 5, 0));
                RetrieveUTCTimeFromLocalTime(new DateTime(2012, 1, 1, 0, 0, 0));
            }
        }

19 Source : UsingExportAndImportMappings.cs
with MIT License
from microsoft

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

                CreateImportMapping();
                RetrieveMappingXml();
                ChangeMappingName();
                ImportMappingsByXml();

                DeleteRequiredRecords(promptforDelete);
            }
        }

19 Source : ConvertDateandTimeBehavior.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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, 
                    serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Check if you are running the correct version of CRM.
                    // This sample requires that the CRM version be 7.1.0.xxxx or later.
                    RetrieveVersionRequest crmVersionReq = new RetrieveVersionRequest();
                    RetrieveVersionResponse crmVersionResp = (RetrieveVersionResponse)_serviceProxy.Execute(crmVersionReq);

                    if (String.CompareOrdinal("7.1.0.0", crmVersionResp.Version) < 0)
                    {
                        // Create required records for the sample.
                        CreateRequiredRecords();

                        // Use the ConvertDateandTimeBehaviorRequest SDK message to change
                        // the behavior of the date and time values in the custom attribute
                        // (new_SampleDateTimeAttribute) for the account enreplacedy.
                        //<snippetConvertDateandTimeBehavior1>
                        ConvertDateAndTimeBehaviorRequest request = new ConvertDateAndTimeBehaviorRequest()
                        {
                            Attributes = new EnreplacedyAttributeCollection() 
                                    { 
                                        new KeyValuePair<string, StringCollection>("account", new StringCollection() 
                                        { "new_sampledatetimeattribute" }) 
                                    },
                            ConversionRule = DateTimeBehaviorConversionRule.SpecificTimeZone.Value,
                            TimeZoneCode = 190, // Time zone code for India Standard Time (IST) in CRM
                            AutoConvert = false // Conversion must be done using ConversionRule
                        };

                        // Execute the request
                        ConvertDateAndTimeBehaviorResponse response = (ConvertDateAndTimeBehaviorResponse)_serviceProxy.Execute(request);
                        //</snippetConvertDateandTimeBehavior1>
                        
                        Console.WriteLine("***************************************");
                        Console.WriteLine("Executed the ConvertDateAndTimeBehaviorRequest SDK message.\n");

                        // Wait for two seconds to let the async job be created
                        System.Threading.Thread.Sleep(2000);

                        if (response.JobId != null)
                        {
                            Console.WriteLine("An async job created with ID: {0}", response.JobId.ToString());
                        }

                        // Retrieve the job completion details based on the Job ID                    
                        ColumnSet cs = new ColumnSet("statecode", "statuscode", "friendlymessage", "message");
                        Console.WriteLine("Waiting for the async job to complete...\n");
                        
                        AsyncOperation crmAsyncJob = new AsyncOperation();
                        while (response.JobId != null && waitCount > 0)
                        {
                            // Check to see if the async operation is complete
                            crmAsyncJob =
                              (AsyncOperation)_serviceProxy.Retrieve(AsyncOperation.EnreplacedyLogicalName,
                                           response.JobId, cs);
                            if (crmAsyncJob.StateCode.HasValue &&
                                    crmAsyncJob.StateCode.Value == AsyncOperationState.Completed && 
                                    crmAsyncJob.StatusCode.Value == (int)asyncoperation_statuscode.Succeeded)
                            {
                                waitCount = 0;                                
                                
                                Console.WriteLine("The async job is complete.\n");
                                Console.WriteLine("****************************");
                                Console.WriteLine(crmAsyncJob.FriendlyMessage);
                                Console.WriteLine("****************************");
                                Console.WriteLine(crmAsyncJob.Message);
                                Console.WriteLine("****************************\n");

                                // Retrieve both the account records created earlier to check the date value
                                Console.WriteLine("Retrieving the date and time values after the conversion...\n");
                                // Create a column set to define which attributes should be retrieved.
                                ColumnSet attributes = new ColumnSet(new string[] { "name", "new_sampledatetimeattribute" });

                                Account retrievedAccount1 = (Account)_serviceProxy.Retrieve(Account.EnreplacedyLogicalName, _account1ID, attributes);
                                Account retrievedAccount2 = (Account)_serviceProxy.Retrieve(Account.EnreplacedyLogicalName, _account2ID, attributes);

                                Console.WriteLine("'{0}' is: {1}", retrievedAccount1.GetAttributeValue<String>("name"), retrievedAccount1.GetAttributeValue<DateTime>("new_sampledatetimeattribute"));
                                Console.WriteLine("'{0}' is: {1}\n", retrievedAccount2.GetAttributeValue<String>("name"), retrievedAccount2.GetAttributeValue<DateTime>("new_sampledatetimeattribute"));
                                Console.WriteLine("The behavior converted to DateOnly for account record ('Sample Account 1')\nbased on the specified conversion rule.\n");
                                Console.WriteLine("No changes to 'Sample Account 2' because it was already DateOnly.\n");
                                Console.WriteLine("***************************************\n");
                            }
                            else
                            {
                                waitCount--;
                                System.Threading.Thread.Sleep(1000);
                            }
                        }

                        // If the async job is taking tool long to process,
                        // inform the user about the same.
                        if (waitCount == 0 && crmAsyncJob.StateCode.Value != (AsyncOperationState.Completed))
                        {
                            Console.WriteLine("The async job is taking too long to complete. Aborting the sample.");
                        }

                        // Prompt the user to delete the records and attribute created by the sample.
                        DeleteRequiredRecords(promptForDelete);
                    }
                    else
                    {
                        Console.WriteLine("This sample cannot be run against the current version of CRM.");
                        Console.WriteLine("Upgrade your CRM instance to the latest version to run this sample.");
                    }
                }
            }

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

See More Examples