public static OrganizationServiceProxy Connect() { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CRM"]; if (settings == null) throw new ConfigurationException("No CRM Connection String was found."); Uri uri = new Uri(settings.ConnectionString); ClientCredentials credentials = null; string user = ConfigurationManager.AppSettings["User"]; string password = ConfigurationManager.AppSettings["Password"]; if (!string.IsNullOrWhiteSpace(user)) { credentials = new ClientCredentials(); credentials.UserName.UserName = ""; credentials.UserName.Password = ""; } OrganizationServiceProxy proxy = new OrganizationServiceProxy(uri, null, credentials, null); proxy.EnableProxyTypes(typeof(Toyota.Tsusho.CRM.API.Contact).Assembly); return proxy; }
public CrmServiceFactory() { Uri organizationUri = GetOrganizationUri(); if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.UserName)) throw new CrmException("A value must be supplied for username in the <crmFramework> section in web.config"); if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.Password)) throw new CrmException("A value must be supplied for password in the <crmFramework> section in web.config"); if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.Domain)) throw new CrmException("A value must be supplied for domain in the <crmFramework> section in web.config"); IServiceManagement<IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(organizationUri); ClientCredentials clientCredentials = new ClientCredentials(); clientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; clientCredentials.UserName.UserName = string.Format("{0}@{1}", CrmConnectorSection.Instance.UserName, CrmConnectorSection.Instance.Domain); clientCredentials.UserName.Password = CrmConnectorSection.Instance.Password; OrganizationServiceProxy organizationServiceProxy = new OrganizationServiceProxy( serviceManagement, clientCredentials); organizationServiceProxy.EnableProxyTypes(); _organizationServiceProxy = organizationServiceProxy; }
public void conUpdate(Microsoft.Crm.Sdk.Samples.ServerConnection.Configuration serverconfig, ArrayList data) { try { using (_serviceProxy = Microsoft.Crm.Sdk.Samples.ServerConnection.GetOrganizationProxy(serverconfig)) { String a_id = (String)data[0]; Guid _contactId = new Guid(a_id); _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; Contact contactToUpdate = new Contact { FirstName = (String)data[1], EMailAddress1 = (String)data[2], Address1_City = (String)data[3], Address1_Country = (String)data[4], Address1_Latitude = Convert.ToDouble(data[5]), Address1_Longitude = Convert.ToDouble(data[6]), ContactId = _contactId }; _service.Update(contactToUpdate); } } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { throw; } }
/// <summary> /// Run the sample. /// </summary> /// <param name="serverConfig">configuration for the server.</param> /// <param name="promptToDelete"> /// whether or not to prompt the user to delete created records. /// </param> public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { using (_context = new ServiceContext(_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.Title == "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, pass in false as the // first parameter. PerformBulkDelete(true, promptToDelete); } else { throw new ArgumentException("Standard Email Templates are missing"); } } } }
public void Run(ServerConnection.Configuration serverConfig, string solutionPath) { try { using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { byte[] data = File.ReadAllBytes(solutionPath); Guid importId = Guid.NewGuid(); Console.WriteLine("\n Importing solution {0} into Server {1}.", solutionPath, serverConfig.OrganizationUri); _serviceProxy.EnableProxyTypes(); ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest() { CustomizationFile = data, ImportJobId = importId }; ThreadStart starter = () =>ProgressReport(serverConfig, importId); Thread t = new Thread(starter); t.Start(); _serviceProxy.Execute(importSolutionRequest); Console.Write("Solution {0} successfully imported into {1}", solutionPath, serverConfig.OrganizationUri); } } catch (Exception ex) { } }
protected XrmServiceContext CreateXrmServiceContext(MergeOption? mergeOption = null) { //string organizationUri = ConfigurationManager.AppSettings["CRM_OrganisationUri"]; string organizationUri = "https://existornest2.api.crm4.dynamics.com/XRMServices/2011/Organization.svc"; IServiceManagement<IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri)); AuthenticationProviderType OrgAuthType = OrganizationServiceManagement.AuthenticationType; AuthenticationCredentials authCredentials = GetCredentials(OrgAuthType); AuthenticationCredentials tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials); OrganizationServiceProxy organizationProxy = null; SecurityTokenResponse responseToken = tokenCredentials.SecurityTokenResponse; if (ConfigurationManager.AppSettings["CRM_AuthenticationType"] == "ActiveDirectory") { using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, authCredentials.ClientCredentials)) { organizationProxy.EnableProxyTypes(); } } else { using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken)) { organizationProxy.EnableProxyTypes(); } } IOrganizationService service = (IOrganizationService)organizationProxy; var context = new XrmServiceContext(service); if (context != null && mergeOption != null) context.MergeOption = mergeOption.Value; return context; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Delete a new queue instance. /// Optionally delete any entity records that were created for this sample. /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<snippetDeleteQueue1> // Delete the queue instance. _serviceProxy.Delete(Queue.EntityLogicalName, _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 pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Call the method to create any data that this sample requires. /// Query the connections. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // 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 { EntityName = Connection.EntityLogicalName, 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 // entity is a part of either way. new ConditionExpression { AttributeName = "record1id", Operator = ConditionOperator.Equal, Values = { _contactId } } } } }; EntityCollection results = _serviceProxy.RetrieveMultiple(query); // TODO: Here you could do a variety of tasks with the // connections retrieved, such as listing the connected entities, // finding reciprocal connections, etc. //</snippetQueryConnections1> Console.WriteLine("Retrieved {0} connectionrole instances.", results.Entities.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 pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// it creates a system user account with a given active directory account. /// Note: Creating a user is only supported in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetCreateAUser1> // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = _serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = _domain + _userName, FirstName = _firstName, LastName = _lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = _serviceProxy.Create(user); Console.WriteLine("Created a system user {0} for '{1}, {2}'", userId, _lastName, _firstName); } //</snippetCreateAUser1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); //<snippetQueryByAttribute1> // Create query using QueryByAttribute. QueryByAttribute querybyattribute = new QueryByAttribute("account"); querybyattribute.ColumnSet = new ColumnSet("name", "address1_city", "emailaddress1"); // Attribute to query. querybyattribute.Attributes.AddRange("address1_city"); // Value of queried attribute to return. querybyattribute.Values.AddRange("Redmond"); // Query passed to service proxy. EntityCollection retrieved = _service.RetrieveMultiple(querybyattribute); System.Console.WriteLine("Query Using QueryByAttribute"); System.Console.WriteLine("==============================="); // Iterate through returned collection. foreach (var c in retrieved.Entities) { System.Console.WriteLine("Name: " + c.Attributes["name"]); if( c.Attributes.Contains("address1_city") ) System.Console.WriteLine("Address: " + c.Attributes["address1_city"]); if( c.Attributes.Contains("emailaddress1") ) System.Console.WriteLine("E-mail: " + c.Attributes["emailaddress1"]); } System.Console.WriteLine("==============================="); //</snippetQueryByAttribute1> 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 pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Create a team, a queue and a role. /// Add read queue privileges to the role. /// Assign the role to the team so that they can read the queue. /// Assign the queue to the team. /// Optionally delete any entity records that were created for this sample. // </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssociateDisassociate1> // Associate the accounts to the contact record. // Create a collection of the entities that will be // associated to the contact. EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id)); relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id)); // Create an object that defines the relationship between the contact and account. Relationship relationship = new Relationship("account_primary_contact"); //Associate the contact with the 3 accounts. _service.Associate(Contact.EntityLogicalName, _contactId, relationship, relatedEntities); Console.WriteLine("The entities have been associated."); //Disassociate the records. _service.Disassociate(Contact.EntityLogicalName, _contactId, relationship, relatedEntities); //</snippetAssociateDisassociate1> Console.WriteLine("The entities have been disassociated."); 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 pass it back to the calling method. throw; } }
/// <summary> /// This method first creates a new currency within the system, setting its /// exchange rate to a pre-defined value. It then issues a /// RetrieveExchangeRateRequest to get the exchange rate from the created /// currency to the organization's base currency. Finally, it retrieves the /// organization's base currency and displays the conversion rate. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetTransactionCurrencyExchangeRate1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) // using the service context makes retrieving entities easier using (_context = new ServiceContext(_serviceProxy)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); String currentOrganizatoinUniqueName = GetCurrentOrganizationName(serverConfig); CreateRequiredRecords(); RetrieveExchangeRateRequest request = new RetrieveExchangeRateRequest() { TransactionCurrencyId = _currency.Id }; RetrieveExchangeRateResponse response = (RetrieveExchangeRateResponse)_serviceProxy.Execute(request); Console.WriteLine(" Retrieved exchange rate for created currency"); // get the base currency for the current org var baseCurrencyName = (from currency in _context.TransactionCurrencySet join org in _context.OrganizationSet on currency.Id equals org.BaseCurrencyId.Id where org.Name == currentOrganizatoinUniqueName select currency.CurrencyName).FirstOrDefault(); Console.WriteLine(" This organization's base currency is {0}", baseCurrencyName); Console.WriteLine( " The conversion from {0} -> {1} is {2}", _currency.CurrencyName, baseCurrencyName, response.ExchangeRate); DeleteRequiredRecords(promptforDelete); } //</snippetTransactionCurrencyExchangeRate1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Demonstrates how to programmatically install and uninstall the Microsoft /// Dynamics CRM sample data records. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">Not applicable for this sample.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetImportOrRemoveSampleData1> // Prompt user to install/uninstall sample data. Console.WriteLine("Would you like to:"); Console.WriteLine("1) Install sample data for Microsoft Dynamics CRM?"); Console.WriteLine("2) Uninstall sample data for Microsoft Dynamics CRM?"); Console.Write("Press [1] to Install, [2] to Uninstall: "); String answer = Console.ReadLine(); // Update the sample data based on the user's response. switch (answer) { case "1": Console.WriteLine("Installing sample data..."); InstallSampleDataRequest request = new InstallSampleDataRequest(); InstallSampleDataResponse response = (InstallSampleDataResponse)_serviceProxy.Execute(request); Console.WriteLine("Sample data successfully installed."); break; case "2": Console.WriteLine("Uninstalling sample data..."); UninstallSampleDataRequest request2 = new UninstallSampleDataRequest(); UninstallSampleDataResponse response2 = (UninstallSampleDataResponse)_serviceProxy.Execute(request2); Console.WriteLine("Sample data successfully uninstalled."); break; default: Console.WriteLine("Neither option was selected. No changes have been made to your records."); break; } } //</snippetImportOrRemoveSampleData1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. /// Initiate method to create any entity records that this sample requires. /// Retrieves new owner's details. /// Update the queue item record to assign it to new owner. /// Optionally delete any entity records that were created for this sample. /// <para name="organizationFriendlyName">The friendly name of the /// target organization.</para> /// <para name="discoveryServer">The name of the discovery server.</para> /// <param name="promptForDelete">Indicates whether to prompt the user to /// delete the records created in this sample.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssignQueueItemWorker1> // 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.EntityLogicalName, 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); //</snippetAssignQueueItemWorker1> 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 pass it back to the calling method. throw; } }
/// <summary> /// Run the sample. /// </summary> /// <param name="serverConfig">configuration for the server.</param> /// <param name="promptToDelete"> /// whether or not to prompt the user to delete created records. /// </param> public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); PerformBulkDeleteBackup(); DeleteRequiredRecords(promptToDelete); } }
internal static IOrganizationService GetOrganizationProxy(string serverBaseUrl, string domain, string user, string password) { IServiceConfiguration<IOrganizationService> orgServiceConfiguration = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>( new Uri(String.Format("{0}/XRMServices/2011/Organization.svc", serverBaseUrl)) ); ClientCredentials credentials = new ClientCredentials(); credentials.Windows.ClientCredential = new System.Net.NetworkCredential(user, password, domain); OrganizationServiceProxy organizationServiceProxy = new OrganizationServiceProxy(orgServiceConfiguration, credentials); organizationServiceProxy.EnableProxyTypes(); return organizationServiceProxy; }
protected XrmServiceContext CreateXrmServiceContext(MergeOption? mergeOption = null) { string organizationUri = ConfigurationManager.AppSettings["organizationUri"]; //IServiceManagement<IOrganizationService> OrganizationServiceManagement = null; //AuthenticationProviderType OrgAuthType; //AuthenticationCredentials authCredentials = null; //AuthenticationCredentials tokenCredentials = null; //OrganizationServiceProxy organizationProxy = null; //SecurityTokenResponse responseToken = null; //try //{ // OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri)); // OrgAuthType = OrganizationServiceManagement.AuthenticationType; // authCredentials = GetCredentials(OrgAuthType); // tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials); // organizationProxy = null; // responseToken = tokenCredentials.SecurityTokenResponse; //} //catch //{ //} IServiceManagement<IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri)); AuthenticationProviderType OrgAuthType = OrganizationServiceManagement.AuthenticationType; AuthenticationCredentials authCredentials = GetCredentials(OrgAuthType); AuthenticationCredentials tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials); OrganizationServiceProxy organizationProxy = null; SecurityTokenResponse responseToken = tokenCredentials.SecurityTokenResponse; if (ConfigurationManager.AppSettings["CRM_AuthenticationType"] == "ActiveDirectory") { using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, authCredentials.ClientCredentials)) { organizationProxy.EnableProxyTypes(); } } else { using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken)) { organizationProxy.EnableProxyTypes(); } } IOrganizationService service = (IOrganizationService)organizationProxy; var context = new XrmServiceContext(service); if (context != null && mergeOption != null) context.MergeOption = mergeOption.Value; return context; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate creating all entity records that this sample requires. /// Create a bundle record. /// Add products to a bundle. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures 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(); //<snippetAddProductstoBundle1> // Add products to a bundle ProductAssociation newAssociation1 = new ProductAssociation { AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product1Id), ProductId = new EntityReference(Product.EntityLogicalName, _bundleId), Quantity = new decimal(15), ProductIsRequired = new OptionSetValue(0), // Adding this as an optional product UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id) }; _product1AssociationId = _serviceProxy.Create(newAssociation1); ProductAssociation newAssociation2 = new ProductAssociation { AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product2Id), ProductId = new EntityReference(Product.EntityLogicalName, _bundleId), Quantity = new decimal(20), ProductIsRequired = new OptionSetValue(1), // Adding this as a mandatory product UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), }; _product2AssociationId = _serviceProxy.Create(newAssociation2); // Verify if the product association is created if ((_product1AssociationId != null) && (_product1AssociationId != null)) { Console.WriteLine("\nAdded both the products to the bundle"); } //</snippetAddProductstoBundle1> DeleteRequiredRecords(promptForDelete); } } catch { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve the history limit of a report. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetGetReportHistoryLimit1> // Query for an an existing report: Account Overview. This is a default report in Microsoft Dynamics CRM. QueryByAttribute reportQuery = new QueryByAttribute(Report.EntityLogicalName); reportQuery.AddAttributeValue("name", "Account Overview"); reportQuery.ColumnSet = new ColumnSet("reportid"); // Get the report. EntityCollection retrieveReports = _serviceProxy.RetrieveMultiple(reportQuery); // Convert retrieved Entity to a report Report retrievedReport = (Report)retrieveReports.Entities[0]; Console.WriteLine("Retrieved the 'Account Overview' report."); // Use the Download Report Definition message. GetReportHistoryLimitRequest reportHistoryRequest = new GetReportHistoryLimitRequest { ReportId = retrievedReport.ReportId.Value }; GetReportHistoryLimitResponse reportHistoryResponse = (GetReportHistoryLimitResponse)_serviceProxy.Execute(reportHistoryRequest); // Access the history limit data int historyLimit = reportHistoryResponse.HistoryLimit; Console.WriteLine("The report history limit is {0}.", historyLimit); //</snippetGetReportHistoryLimit1> } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve organization-owned visualizations. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetRetrieveVisualizationsAttachedToAnEntity1> // Create a query for retrieving all organization-owned visualizations // that are attached to the account entity. QueryExpression mySavedQuery = new QueryExpression { EntityName = SavedQueryVisualization.EntityLogicalName, ColumnSet = new ColumnSet("name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "primaryentitytypecode", Operator = ConditionOperator.Equal, Values = {Account.EntityLogicalName} } } } }; // Retrieve a collection of organization-owned visualizations that are attached to the account entity. DataCollection<Entity> results = _serviceProxy.RetrieveMultiple(mySavedQuery).Entities; // Display the names of the retrieved organization-owned visualizations. Console.WriteLine("Retrieved the following visualizations for the Account entity:"); foreach (Entity entity in results) { SavedQueryVisualization orgVisualization = (SavedQueryVisualization)entity; Console.WriteLine("{0}", orgVisualization.Name); } //</snippetRetrieveVisualizationsAttachedToAnEntity1> } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public IOrganizationService Connect() { var creds = new ClientCredentials(); creds.UserName.UserName = UserName; creds.UserName.Password = Password; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"https://ukraine.crm.softlinegroup.com/XrmServices/2011/Organization.svc"), null, creds, null); serviceProxy.EnableProxyTypes(); serviceProxy.Authenticate(); return (IOrganizationService)serviceProxy; }
/// <summary> /// This method first connects to the organization service. Afterwards, /// auditing is enabled on the organization, account entity, and a couple /// of attributes. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); // Log the start time to ensure deletion of records created during execution. _executionDate = DateTime.Today; ImportRecords(); DeleteRequiredRecords(promptforDelete); } }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); CreateMarketingList(); DistributeCampaign(); DeleteRecords(promptforDelete); } }
private void Connect(string server, string org) { string url = "http://" + server + "/" + org + "/XRMServices/2011/Organization.svc"; Uri OrganizationUri = new Uri(url); ClientCredentials Credentials = new ClientCredentials(); Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; serviceproxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null); serviceproxy.EnableProxyTypes(); service = (IOrganizationService)serviceproxy; CheckConnection(); }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); DoQueryExpressionToFetchXmlConversion(); DoFetchXmlToQueryExpressionConversion(); DeleteRequiredRecords(promptforDelete); } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// End the recurring appointment series. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetEndRecurringAppointmentSeries1> // Retrieve a recurring appointment series RecurringAppointmentMaster retrievedRecurringAppointmentSeries = (RecurringAppointmentMaster)_serviceProxy.Retrieve(RecurringAppointmentMaster.EntityLogicalName, _recurringAppointmentMasterId, new ColumnSet(true)); // Use the DeleteOpenInstances message to end the series to the // last occurring past instance date w.r.t. the series end date // (i.e., 20 days from today). Effectively, that means that the // series will end after the third instance (day 14) as this // instance is the last occuring past instance w.r.t the specified // series end date (20 days from today). // Also specify that the state of past instances (w.r.t. the series // end date) be set to 'completed'. DeleteOpenInstancesRequest endAppointmentSeries = new DeleteOpenInstancesRequest { Target = retrievedRecurringAppointmentSeries, SeriesEndDate = DateTime.Today.AddDays(20), StateOfPastInstances = (int)AppointmentState.Completed }; _serviceProxy.Execute(endAppointmentSeries); Console.WriteLine("The recurring appointment series has been ended after the third occurrence."); //</snippetEndRecurringAppointmentSeries1> 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 pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Call the method to create any data that this sample requires. /// Update the connectionrole instance. /// Optionally delete any entity records that were created for this sample. /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<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 pass it back to the calling method. throw; } }
static void Main(string[] args) { //new Program().ss(); string UserName = @"softline\savchinvv"; string Password = @"IH@veToBeABoss"; var creds = new ClientCredentials(); creds.UserName.UserName = UserName; creds.UserName.Password = Password; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"http://msk02crm13web06/UkraineTest13/XRMServices/2011/Organization.svc"), null, creds, null); serviceProxy.EnableProxyTypes(); serviceProxy.Authenticate(); var serviceCRM = (IOrganizationService)serviceProxy; ; using (var orgContext = new OrganizationServiceContext(serviceCRM)) { var ann = (from q in orgContext.CreateQuery<Annotation>() select q).FirstOrDefault(); //if (!ann.IsDocument.Value || ann.ObjectId.LogicalName.ToLower() != "quote") return; var tempFile = SaveFile(ann.FileName, ann.DocumentBody); //Scopes for use with the Google Drive API string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile}; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker .AuthorizeAsync(new ClientSecrets { ClientId = @"560656622534-clntle0fod1nerinp6tp9o0ovdnnq570.apps.googleusercontent.com" , ClientSecret = "zkYePr5TCLt9JwL9gSJGd5PZ", } , scopes , Environment.UserName , CancellationToken.None , new FileDataStore("Daimto.GoogleDrive.Auth.Store") ).Result; DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample", }); var file = uploadFile(service, tempFile,"Drive"); } }
private static IOrganizationService GetOrgService(ServerConnection serverConnection, bool reAuthenticate = false) { OrganizationServiceProxy serviceProxy; ServerConnection.Configuration serverConfig = serverConnection.GetServerConfiguration(reAuthenticate); // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. serviceProxy.EnableProxyTypes(); return (IOrganizationService)serviceProxy; } }
/// <summary> /// Creates a sales order and shows how to close using the FulfillSalesOrderRequest /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateCustomer(); CreateSalesOrder(); CloseSalesOrder(); DeleteRequiredRecords(promptforDelete); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// basic LINQ queries are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures 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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // Create the ServiceContext object that will generate // the IQueryable collections for LINQ calls. ServiceContext svcContext = new ServiceContext(_service); // Loop through all CRM account using the IQueryable interface // on the ServiceContext object //<snippetCreateALinqQuery1> var accounts = from a in svcContext.AccountSet select new Account { Name = a.Name, Address1_County = a.Address1_County }; System.Console.WriteLine("List all accounts in CRM"); System.Console.WriteLine("========================"); foreach (var a in accounts) { System.Console.WriteLine(a.Name + " " + a.Address1_County); } //</snippetCreateALinqQuery1> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //List all accounts in CRM //======================== //Fourth Coffee //School of Fine Art Lake County //Tailspin Toys King County //Woodgrove Bank //Contoso, Ltd. Saint Louis County //<End of Listing> System.Console.WriteLine(); // Retrieve all accounts owned by the user who has read access rights // to the accounts and where the last name of the user is not Cannon. //<snippetCreateALinqQuery2> var queryAccounts = from a in svcContext.AccountSet join owner in svcContext.SystemUserSet on a.OwnerId.Id equals owner.SystemUserId where owner.LastName != "Cannon" select new Account { Name = a.Name, Address1_City = a.Address1_City }; System.Console.WriteLine("Accounts not owned by user w/ last name 'Cannon'"); System.Console.WriteLine("================================================"); foreach (var a in queryAccounts) { System.Console.WriteLine(a.Name + " " + a.Address1_County); } //</snippetCreateALinqQuery2> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Accounts not owned by user w/ last name 'Cannon' //================================================ //Fourth Coffee //School of Fine Art //Tailspin Toys //Woodgrove Bank //Contoso, Ltd. //<End of Listing> System.Console.WriteLine(); // Return a count of all accounts which have a county specified // in their address. //<snippetCreateALinqQuery3> int accountsWithCounty = (from a in svcContext.AccountSet where (a.Address1_County != null) select new Account { Name = a.Name, Address1_City = a.Address1_City }).ToArray().Count(); System.Console.Write("Number of accounts with a county specified: "); System.Console.WriteLine(accountsWithCounty); //</snippetCreateALinqQuery3> System.Console.WriteLine(); //OUTPUT: //Number of accounts with a county specified: 3 System.Console.WriteLine(); // Return a count of states in which we have an account. This // uses the 'distinct' keyword which counts a state only one time. //<snippetCreateALinqQuery4> int statesWithAccounts = (from a in svcContext.AccountSet where (a.Address1_StateOrProvince != null) select a.Address1_StateOrProvince) .Distinct().ToArray().Count(); System.Console.Write("Number of unique states that contain accounts: "); System.Console.WriteLine(statesWithAccounts); //</snippetCreateALinqQuery4> System.Console.WriteLine(); //OUTPUT: //Number of unique states that contain accounts: 3 System.Console.WriteLine(); // Return contacts where the city equals Redmond AND the first // name is Joe OR John. //<snippetCreateALinqQuery5> var queryContacts = from c in svcContext.ContactSet where (c.Address1_City == "Redmond") && (c.FirstName.Equals("Joe") || c.FirstName.Equals("John")) select new Contact { FirstName = c.FirstName, LastName = c.LastName, Address1_City = c.Address1_City }; System.Console.WriteLine("Contacts in Redmond named Joe OR John"); System.Console.WriteLine("====================================="); foreach (var c in queryContacts) { System.Console.WriteLine(c.FirstName + " " + c.LastName + " " + c.Address1_City); } //</snippetCreateALinqQuery5> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Contacts in Redmond named Joe OR John //===================================== //Joe Redmond //John Redmond //Joe Redmond //<End of Listing> System.Console.WriteLine(); 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 pass it back to the calling method. throw; } }
/// <summary> /// This sample demonstrates how to execute a collection of message requests in a single database transaction, /// by using a single web service call and optionally return the results. /// </summary> /// <seealso cref="https://msdn.microsoft.com/en-us/library/gg328075.aspx#bkmk_transaction"/> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { ExecuteTransactionRequest requestToCreateRecords = null; try { // Get a reference to the organization service. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // Enable early-bound type support to add/update entity records required for this sample. _serviceProxy.EnableProxyTypes(); #region Execute Transaction to create records //<snippetExecuteTransaction1> // Create an ExecuteTransactionRequest object. requestToCreateRecords = new ExecuteTransactionRequest() { // Create an empty organization request collection. Requests = new OrganizationRequestCollection(), ReturnResponses = true }; // Create several (local, in memory) entities in a collection. EntityCollection input = GetCollectionOfEntitiesToCreate(); // Add a CreateRequest for each entity to the request collection. foreach (var entity in input.Entities) { CreateRequest createRequest = new CreateRequest { Target = entity }; requestToCreateRecords.Requests.Add(createRequest); } // Execute all the requests in the request collection using a single web method call. try { var responseForCreateRecords = (ExecuteTransactionResponse)_serviceProxy.Execute(requestToCreateRecords); int i = 0; // Display the results returned in the responses. foreach (var responseItem in responseForCreateRecords.Responses) { if (responseItem != null) { DisplayResponse(requestToCreateRecords.Requests[i], responseItem); } i++; } } catch (FaultException <OrganizationServiceFault> ex) { Console.WriteLine("Create request failed for the account{0} and the reason being: {1}", ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message); throw; } //</snippetExecuteTransaction1> #endregion Execute Transaction to create records #region Execute Transaction to update records //<snippetExecuteTransaction2> ExecuteTransactionRequest requestForUpdates = new ExecuteTransactionRequest() { Requests = new OrganizationRequestCollection() }; // Update the entities that were previously created. EntityCollection update = GetCollectionOfEntitiesToUpdate(); foreach (var entity in update.Entities) { UpdateRequest updateRequest = new UpdateRequest { Target = entity }; requestForUpdates.Requests.Add(updateRequest); } try { ExecuteTransactionResponse responseForUpdates = (ExecuteTransactionResponse)_serviceProxy.Execute(requestForUpdates); Console.WriteLine("Entity records are updated."); } catch (FaultException <OrganizationServiceFault> ex) { Console.WriteLine("Update request failed for the account{0} and the reason being: {1}", ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message); } //</snippetExecuteTransaction2> #endregion Execute Transaction for update records //<snippetExecuteTransaction3> DeleteRequiredRecords(promptforDelete); //</snippetExecuteTransaction3> } } catch (FaultException <OrganizationServiceFault> fault) { // Check if the maximum batch size has been exceeded. The maximum batch size is only included in the fault if it // the input request collection count exceeds the maximum batch size. if (fault.Detail.ErrorDetails.Contains("MaxBatchSize")) { int maxBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]); if (maxBatchSize < requestToCreateRecords.Requests.Count) { // Here you could reduce the size of your request collection and re-submit the ExecuteTransaction request. // For this sample, that only issues a few requests per batch, we will just print out some info. However, // this code will never be executed because the default max batch size is 1000. Console.WriteLine("The input request collection contains %0 requests, which exceeds the maximum allowed (%1)", requestToCreateRecords.Requests.Count, maxBatchSize); } } // Re-throw so Main() can process the fault. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// creates a follow-up task activity when a new account is created. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { _serviceProxy.EnableProxyTypes(); #region Create XAML // Define the workflow XAML. string xamlWF = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""FollowupWithAccount"" xmlns=""https://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxsw=""clr-namespace:Microsoft.Xrm.Sdk.Workflow;assembly=Microsoft.Xrm.Sdk.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""https://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:FollowupWithAccount.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:FollowupWithAccount.InputEntities> <this:FollowupWithAccount.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:FollowupWithAccount.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Sequence DisplayName=""CreateStep1""> <Sequence.Variables> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_3"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_4"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_5"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_6"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_7"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_8"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_9"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_10"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_11"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_12"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_13"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_14"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_15"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_16"" /> <Variable x:TypeArguments=""mxsw:XrmTimeSpan"" Name=""CreateStep1_17""> <Variable.Default> <Literal x:TypeArguments=""mxsw:XrmTimeSpan""> <mxsw:XrmTimeSpan Days=""30"" Hours=""0"" Minutes=""0"" Months=""0"" Years=""0"" /> </Literal> </Variable.Default> </Variable> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_18"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_19"" /> </Sequence.Variables> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" Value=""[New Entity(&quot;task&quot;)]"" /> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""Send e-mail to the "", ""String"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""account"" Value=""[CreateStep1_4]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_4 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_3]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""&amp;#160;customer."", ""String"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_5]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_2, CreateStep1_3, CreateStep1_5 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""subject"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_1]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""account"" Value=""[CreateStep1_7]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_7 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_6]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""regardingobjectid"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_6]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""account"" Value=""[CreateStep1_9]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_9 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_8]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""category"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_8]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""createdby"" Entity=""[InputEntities(&quot;related_createdby#systemuser&quot;)]"" EntityName=""systemuser"" Value=""[CreateStep1_11]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_11 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_10]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""ownerid"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_10]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.OptionSetValue, ""1"", ""Picklist"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_12]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""prioritycode"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_12]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""createdon"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""account"" Value=""[CreateStep1_16]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_16 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_15]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_15, CreateStep1_17 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_14]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_14 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_13]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""scheduledend"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_13]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""createdon"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""account"" Value=""[CreateStep1_19]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_19 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_18]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""scheduledstart"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" Value=""[CreateStep1_18]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""task"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter&quot;)]"" Value=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>"; #endregion Create XAML #region Create Workflow // Create the workflow. Workflow workflow = new Workflow() { Name = "SampleFollowupWithAccountWorkflow", Type = new OptionSetValue((int)WorkflowType.Definition), Category = new OptionSetValue((int)WorkflowCategory.Workflow), Scope = new OptionSetValue((int)WorkflowScope.User), LanguageCode = 1033, // U.S. English TriggerOnCreate = true, OnDemand = true, PrimaryEntity = Account.EntityLogicalName, Description = @"Follow up with the customer. Check if there are any new issues that need resolution.", Xaml = xamlWF }; _workflowId = _serviceProxy.Create(workflow); Console.WriteLine("Created Workflow: " + workflow.Name); #endregion Create Workflow #region Activate Workflow // Activate the workflow. var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); Console.WriteLine("Activated Workflow: " + workflow.Name); #endregion Activate Workflow #region Create Account Record CreateRequiredRecords(); #endregion Create Account Record 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 pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service and service context. /// Afterwards, several LINQ query techniques are demonstrated. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUseLinqWithDotNetDataServicesDE1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); // Retrieve records with Skip/Take record paging. Setting a page size // can help you manage your Skip and Take calls, since Skip must be // passed a multiple of Take's parameter value. //<snippetUseLinqWithDotNetDataServicesDE2> int pageSize = 5; var accountsByPage = from a in orgContext.CreateQuery("account") select a["name"]; System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts"); System.Console.WriteLine("======================================"); foreach (var name in accountsByPage.Skip(2 * pageSize).Take(pageSize)) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE2> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Skip 10 accounts, then Take 5 accounts //====================================== //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Fourth Coffee 10 //<End of Listing> // Use orderBy to order items retrieved. //<snippetUseLinqWithDotNetDataServicesDE3> var orderedAccounts = from a in orgContext.CreateQuery("account") orderby a["name"] select a["name"]; System.Console.WriteLine("Display accounts ordered by name"); System.Console.WriteLine("================================"); foreach (var name in orderedAccounts) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE3> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Display accounts ordered by name //================================ //A. Datum Corporation //Adventure Works //Coho Vineyard //Fabrikam //Fourth Coffee 1 //Fourth Coffee 10 //Fourth Coffee 2 //Fourth Coffee 3 //Fourth Coffee 4 //Fourth Coffee 5 //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Humongous Insurance //<End of Listing> // Filter multiple entities using LINQ. //<snippetUseLinqWithDotNetDataServicesDE4> var query = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] } }; Console.WriteLine("Join account and contact"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in query) { Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE4> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account and contact //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Contact Name: Ben Andrews //Account Phone: (206)555-5555 //Contact Name: Ben Andrews //Account Phone: (425)555-5555 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> // Build a complex query with LINQ. This query includes multiple // JOINs and a complex WHERE statement. //<snippetUseLinqWithDotNetDataServicesDE5> var complexQuery = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] join l in orgContext.CreateQuery("lead") on a["originatingleadid"] equals l["leadid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] }, Lead = new { LeadId = l["leadid"] } }; Console.WriteLine("Join account, contact and lead"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in complexQuery) { Console.WriteLine("Lead ID: {0}", record.Lead.LeadId); Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE5> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account, contact and lead //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> DeleteRequiredRecords(promptforDelete); } //</snippetUseLinqWithDotNetDataServicesDE1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Deployment service. Then, /// a variety of messages are used to retrieve deployment information. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUseDeploymentServiceMessages1> // Connect to the Organization service. // The using statement assures 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(); // Instantiate DeploymentServiceClient for calling the service. DeploymentServiceClient serviceClient = Deployment.Proxy.ProxyClientHelper.CreateClient( new Uri(serverConfig.DiscoveryUri.ToString() .Replace("Services", "Deployment") .Replace("Discovery", "Deployment"))); // Setting credentials from the current security context. if (serverConfig.Credentials == null) { serviceClient.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } else { serviceClient.ClientCredentials.Windows.ClientCredential = serverConfig.Credentials.Windows.ClientCredential; } // Retrieve all deployed instances of Microsoft Dynamics CRM. var organizations = serviceClient.RetrieveAll(DeploymentEntityType.Organization); // Print list of all retrieved organizations. Console.WriteLine("Organizations in your deployment"); Console.WriteLine("================================"); foreach (var organization in organizations) { Console.WriteLine(organization.Name); } Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Retrieve details of first organization from previous call. Deployment.Organization deployment = (Deployment.Organization)serviceClient.Retrieve( DeploymentEntityType.Organization, organizations[0]); // Print out retrieved details about your organization. Console.WriteLine(String.Format( "Selected deployment details for {0}", serverConfig.OrganizationName)); Console.WriteLine("========================================="); Console.Write("Friendly Name: "); Console.WriteLine(deployment.FriendlyName); Console.Write("Unique Name: "); Console.WriteLine(deployment.UniqueName); Console.Write("Organization Version: "); Console.WriteLine(deployment.Version); Console.Write("SQL Server Name: "); Console.WriteLine(deployment.SqlServerName); Console.Write("SRS URL: "); Console.WriteLine(deployment.SrsUrl); Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Retrieve license and user information for your organization. TrackLicenseRequest licenseRequest = new TrackLicenseRequest(); TrackLicenseResponse licenseResponse = (TrackLicenseResponse)serviceClient.Execute(licenseRequest); // Print out the number of servers and the user list. Console.WriteLine(String.Format( "License and user information for {0}", serverConfig.OrganizationName)); Console.WriteLine("========================================="); Console.Write("Number of servers: "); Console.WriteLine(licenseResponse.Servers != null ? licenseResponse.Servers.Count.ToString() : "null"); Console.WriteLine("Users:"); foreach (OrganizationUserInfo user in licenseResponse.Users.ToArray()) { Console.WriteLine(user.FullName); } Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Retrieve advanced settings for your organization. // Note that the columnset must contain at least one column. Setting // AllColumns to true results in an error. RetrieveAdvancedSettingsRequest request = new RetrieveAdvancedSettingsRequest { ConfigurationEntityName = "Server", ColumnSet = new ColumnSet( new string[] { "Id", "FullName", "Name", "Roles", "State", "Version" }) }; ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).Entity; // Print out all advanced settings where IsWritable==true. Console.WriteLine("Advanced deployment settings that can be updated"); Console.WriteLine("================================================"); foreach (var setting in configuration.Attributes) { if (setting.Key != "Id") { Console.WriteLine( String.Format("{0}: {1}", setting.Key, setting.Value)); } } Console.WriteLine("<End of Listing>"); Console.WriteLine(); } //</snippetUseDeploymentServiceMessages1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first creates 3 accounts with the same name, then issues a BulkDetectDuplicates /// request to show the duplicate detection. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBulkDetectDuplicates1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Create the BulkDetectDuplicatesRequest object Console.WriteLine(" Creating the BulkDetectDuplicatesRequest object"); BulkDetectDuplicatesRequest request = new BulkDetectDuplicatesRequest() { JobName = "Detect Duplicate Accounts", Query = new QueryExpression() { EntityName = Account.EntityLogicalName, ColumnSet = new ColumnSet(true) }, RecurrencePattern = String.Empty, RecurrenceStartTime = DateTime.Now, ToRecipients = new Guid[0], CCRecipients = new Guid[0] }; // Execute the request Console.WriteLine(" Executing BulkDetectDuplicatesRequest"); _response = (BulkDetectDuplicatesResponse)_serviceProxy .Execute(request); #region check success Console.WriteLine(" Waiting for job to complete..."); WaitForAsyncJobToFinish(_response.JobId, 120); QueryByAttribute query = new QueryByAttribute() { ColumnSet = new ColumnSet(true), EntityName = "duplicaterecord" }; query.Attributes.Add("asyncoperationid"); query.Values.Add(_response.JobId); EntityCollection results = _serviceProxy.RetrieveMultiple(query); // check to make sure each id is found in the collection var duplicateIds = results.Entities.Select((entity) => ((DuplicateRecord)entity).BaseRecordId.Id); foreach (var id in _duplicateAccounts.Select((account) => account.Id)) { if (!duplicateIds.Contains(id)) { throw new Exception(String.Format( "Account with ID {0} was not detected as a duplicate", id)); } } Console.WriteLine(" All accounts detected as duplicates successfully"); #endregion Console.WriteLine(); DeleteRequiredRecords(promptforDelete); } //</snippetBulkDetectDuplicates1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create the custom entity. /// Optionally delete the custom entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // The custom prefix would typically be passed in as an argument or // determined by the publisher of the custom solution. String prefix = "new_"; String customEntityName = prefix + "instantmessage"; // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = customEntityName, DisplayName = new Label("Instant Message", 1033), DisplayCollectionName = new Label("Instant Messages", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; _serviceProxy.Execute(request); //Entity must be published // Add few attributes to the custom activity entity. CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontfamily", DisplayName = new Label("Font Family", 1033), MaxLength = 100 } }; CreateAttributeResponse fontFamilyAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontFamilyAttributeRequest); CreateAttributeRequest fontColorAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontcolor", DisplayName = new Label("Font Color", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontColorAttributeRequest); CreateAttributeRequest fontSizeAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new IntegerAttributeMetadata { SchemaName = prefix + "fontSize", DisplayName = new Label("Font Size", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontSizeAttributeRequest); Console.WriteLine("The custom activity has been created."); DeleteCustomEntity(prefix, promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create a risk assessment. /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetMarketingAutomation1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); Entity riskAssessment = new Entity("msemr_riskassessment"); riskAssessment["msemr_name"] = "Operational Risk"; //Setting context type as encounter riskAssessment["msemr_contexttype"] = new OptionSetValue(935000000); //Encounter Guid encounterId = Encounter.GetEncounterId(_serviceProxy, "E23556"); if (encounterId != Guid.Empty) { riskAssessment["msemr_contextencounter"] = new EntityReference("msemr_encounter", encounterId); } //Setting performer type as practitioner riskAssessment["msemr_performertype"] = new OptionSetValue(935000000); //Practitioner Guid performerpractitionerContactId = SDKFunctions.GetContactId(_serviceProxy, "James Kirk"); if (performerpractitionerContactId != Guid.Empty) { riskAssessment["msemr_performerpractitioner"] = new EntityReference("contact", performerpractitionerContactId); } //Setting reason type as codeable concept riskAssessment["msemr_reasontype"] = new OptionSetValue(935000000); //Codeable concept Guid reasonconceptCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Risk Assessment Reason Code", 935000126); if (reasonconceptCodeableConceptId != Guid.Empty) { riskAssessment["msemr_reasonconcept"] = new EntityReference("msemr_codeableconcept", reasonconceptCodeableConceptId); } //Setting subject type as codeable patient riskAssessment["msemr_subjecttype"] = new OptionSetValue(935000000); //Patient Guid subjectpatientContactId = SDKFunctions.GetContactId(_serviceProxy, "James Kirk"); if (subjectpatientContactId != Guid.Empty) { riskAssessment["msemr_subjectpatient"] = new EntityReference("contact", subjectpatientContactId); } riskAssessment["msemr_occurrencetype"] = new OptionSetValue(935000000); //Time riskAssessment["msemr_occurrencestartdate"] = DateTime.Now; riskAssessment["msemr_occurrenceenddate"] = DateTime.Now; riskAssessment["msemr_occurrencedatetime"] = DateTime.Now; Guid conditionId = SDKFunctions.GetConditionId(_serviceProxy, "Tooth loss"); if (conditionId != Guid.Empty) { riskAssessment["msemr_condition"] = new EntityReference("msemr_condition", conditionId); } Guid methodCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Method", 935000124); if (methodCodeableConceptId != Guid.Empty) { riskAssessment["msemr_method"] = new EntityReference("msemr_codeableconcept", methodCodeableConceptId); } Guid codeCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Code", 935000123); if (codeCodeableConceptId != Guid.Empty) { riskAssessment["msemr_code"] = new EntityReference("msemr_codeableconcept", codeCodeableConceptId); } riskAssessment["msemr_basedon"] = ""; riskAssessment["msemr_parent"] = ""; riskAssessment["msemr_basis"] = ""; riskAssessment["msemr_status"] = new OptionSetValue(935000000); //Registered riskAssessment["msemr_comment"] = ""; riskAssessment["msemr_mitigation"] = ""; riskAssessment["msemr_riskassessmentnumber"] = "RAN865"; Guid riskAssessmentId = _serviceProxy.Create(riskAssessment); // Verify that the record has been created. if (riskAssessmentId != Guid.Empty) { Console.WriteLine("Succesfully created {0}.", riskAssessmentId); } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Create few types of attributes. /// Insert status in the existing status list. /// Retrieve attribute. /// Update attribute. /// Update existing state value. /// Optionally delete/revert any attributes /// that were created/changed for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _productVersion = Version.Parse(((RetrieveVersionResponse)_serviceProxy.Execute(new RetrieveVersionRequest())).Version); //<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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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); //Multi-select attribute requires version 9.0 or higher. if (_productVersion > new Version("9.0")) { // Create a multi-select optionset MultiSelectPicklistAttributeMetadata multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_MultiSelectOptionSet", LogicalName = "new_multiselectoptionset", DisplayName = new Label("Multi-Select OptionSet", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Multi-Select OptionSet description", _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option", _languageCode), null), new OptionMetadata(new Label("Second Option", _languageCode), null), new OptionMetadata(new Label("Third Option", _languageCode), null) } } }; // Add to list addedAttributes.Add(multiSelectOptionSetAttribute); } // 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 { EntityName = Contact.EntityLogicalName, 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", EntityLogicalName = Contact.EntityLogicalName, 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 status named '{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 { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // 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, EntityName = Contact.EntityLogicalName, 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", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. _serviceProxy.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, 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", EntityLogicalName = Contact.EntityLogicalName, 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 { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // 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", EntityLogicalName = Contact.EntityLogicalName, // 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 pass it back to the calling method. throw; } }
static void Main(string[] args) { IOrganizationService orgService = null; Uri serviceUri = new Uri("https://testesmart9.api.crm2.dynamics.com/XRMServices/2011/Organization.svc"); string userName = "******"; string password = "******"; // gera as credenciais ClientCredentials credentials = new ClientCredentials(); credentials.UserName.UserName = userName; credentials.UserName.Password = password; // gerar serviço de organização OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(serviceUri, null, credentials, null); serviceProxy.EnableProxyTypes(); orgService = (IOrganizationService)serviceProxy; //retornar guid do usuario atual Guid idUsuario = new Guid(); idUsuario = ((WhoAmIResponse)orgService.Execute(new WhoAmIRequest())).UserId; Console.WriteLine(idUsuario.ToString()); ////criar leads (Late Bound) //Entity novoLead = new Entity("lead"); //novoLead.Attributes["firstname"] = "Daniel"; //novoLead.Attributes["lastname"] = "Costa Ruy"; //novoLead["emailaddress1"] = "*****@*****.**"; //novoLead["telephone1"] = "(11) 3000-0003"; //Guid idNovoLead = orgService.Create(novoLead); //Console.WriteLine("lead criado com sucesso!" + idNovoLead.ToString()); //Entity atualizalead = new Entity("lead", idNovoLead); //atualizalead["subject"] = "Novo Cliente Elton"; //orgService.Update(atualizalead); ////criar leads(Early Bound) Lead novoLead = new Lead(); novoLead.FirstName = "Daniel"; novoLead.LastName = "Costa Ruy"; novoLead.EMailAddress1 = "*****@*****.**"; novoLead.Telephone1 = "(11)4789-1385"; Guid idLead = orgService.Create(novoLead); Console.WriteLine("Lead criado com sucesso!", novoLead.ToString()); Console.ReadKey(); }
/// <summary> /// This method first creates XAML to define the custom workflow. Afterwards, /// it creates the workflow record with this XAML and then activates it. Finally /// it checks if it is activated and, if so, deactivates it. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Activate the workflow. Console.WriteLine("\nActivating the workflow..."); var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); // Verify that the workflow is activated. Workflow retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); // Deactivate the workflow. if (retrievedWorkflow.StateCode == WorkflowState.Activated) { Console.WriteLine("\nDeactivating the workflow..."); SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue((int)workflow_statuscode.Draft) }; _serviceProxy.Execute(deactivateRequest); } // Verify that the workflow is deactivated (in a draft state). retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); 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 pass it back to the calling method. throw; } }
/// <summary> /// Demonstrates sharing records by exercising various access messages including: /// Grant, Modify, Revoke, RetrievePrincipalAccess, and /// RetrievePrincipalsAndAccess. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig) { try { // we need this to support communicating with Dynamics Online Instances ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //<snippetSharingRecords1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); int patientcount = int.Parse(ConfigurationManager.AppSettings["cdm:createpatientcount"]); int practitionercount = int.Parse(ConfigurationManager.AppSettings["cdm:createpractitionercount"]); int relatedpersoncount = int.Parse(ConfigurationManager.AppSettings["cdm:createrelatedpersoncount"]); int contactcount = int.Parse(ConfigurationManager.AppSettings["cdm:createcontactcount"]); int practitionerrolecount = int.Parse(ConfigurationManager.AppSettings["cdm:practitionerrolecount"]); int practitionerqualificationcount = int.Parse(ConfigurationManager.AppSettings["cdm:practitionerqualificationcount"]); int patientallergycount = int.Parse(ConfigurationManager.AppSettings["cdm:patientallergycount"]); int patientnutritionordercount = int.Parse(ConfigurationManager.AppSettings["cdm:patientnutritionordercount"]); int patientconditioncount = int.Parse(ConfigurationManager.AppSettings["cdm:patientconditioncount"]); int patientdevicecount = int.Parse(ConfigurationManager.AppSettings["cdm:patientdevicecount"]); int patientprocedurecount = int.Parse(ConfigurationManager.AppSettings["cdm:patientprocedurecount"]); int patientreferralcount = int.Parse(ConfigurationManager.AppSettings["cdm:patientreferralcount"]); int patientmedicationrequestcount = int.Parse(ConfigurationManager.AppSettings["cdm:patientmedicationrequestcount"]); string filepath = ConfigurationManager.AppSettings["cdm:temporaryfilepath"]; Console.WriteLine("Start Time: " + DateTime.Now.ToString()); List <Profile> localcontacts = null; List <Profile> localpatients = null; List <Profile> localpractitioners = null; List <Profile> localrelatedpersons = null; string practitonerFile = string.Empty; string relatedpersonsFile = string.Empty; string patientsFile = string.Empty; #region Create Standard Contancts if (contactcount > 0) { CreateCDMHealthData createContacts = new CreateCDMHealthData(); createContacts.ContactType = Profile.ContactType.Standard; createContacts.FileName = filepath + "relatedpersons_" + relatedpersoncount.ToString() + "_" + Guid.NewGuid().ToString() + ".tab"; localcontacts = Contact.GenerateProfilesByCount(contactcount, "NA"); foreach (Profile contact in localcontacts) { createContacts.IncomingContacts.Enqueue(contact); } createContacts.CreateCount = createContacts.IncomingContacts.Count; createContacts.EmailDomain = ConfigurationManager.AppSettings["cdm:emaildomain"]; createContacts.Clients = int.Parse(ConfigurationManager.AppSettings["cdm:clients"]); Console.WriteLine("\r\nCreating [" + createContacts.CreateCount.ToString() + "] Contacts\r\n"); practitonerFile = createContacts.CreateContacts(_serviceProxy); } #endregion #region Create Practitioners if (practitionercount > 0) { PractitionerConfiguration configuration = new PractitionerConfiguration(); configuration.Qualifications = practitionerqualificationcount; configuration.Roles = practitionerrolecount; CreateCDMHealthData createPractitioners = new CreateCDMHealthData(); createPractitioners.ContactType = Profile.ContactType.Practitioner; createPractitioners.FileName = filepath + "practitioners_" + practitionercount.ToString() + "_" + Guid.NewGuid().ToString() + ".json"; localpractitioners = Practitioner.GenerateProfilesByCount(practitionercount, configuration); foreach (Profile practitioner in localpractitioners) { createPractitioners.IncomingContacts.Enqueue(practitioner); } createPractitioners.CreateCount = createPractitioners.IncomingContacts.Count; createPractitioners.EmailDomain = ConfigurationManager.AppSettings["cdm:emaildomain"]; createPractitioners.Clients = int.Parse(ConfigurationManager.AppSettings["cdm:clients"]); //; Console.WriteLine("\r\nCreating [" + createPractitioners.CreateCount.ToString() + "] Practitioners\r\n"); practitonerFile = createPractitioners.CreateContacts(_serviceProxy); } #endregion #region Create Related Persons if (relatedpersoncount > 0) { CreateCDMHealthData createRelatedPersons = new CreateCDMHealthData(); createRelatedPersons.FileName = filepath + "relatedpersons_" + relatedpersoncount.ToString() + "_" + Guid.NewGuid().ToString() + ".json"; createRelatedPersons.ContactType = Profile.ContactType.RelatedPerson; localrelatedpersons = RelatedPerson.GenerateProfilesByCount(relatedpersoncount, "NA"); foreach (Profile relatedperson in localrelatedpersons) { createRelatedPersons.IncomingContacts.Enqueue(relatedperson); } createRelatedPersons.CreateCount = createRelatedPersons.IncomingContacts.Count; createRelatedPersons.EmailDomain = ConfigurationManager.AppSettings["cdm:emaildomain"]; createRelatedPersons.Clients = int.Parse(ConfigurationManager.AppSettings["cdm:clients"]); //; Console.WriteLine("\r\nCreating [" + createRelatedPersons.CreateCount.ToString() + "] Related Persons\r\n"); relatedpersonsFile = createRelatedPersons.CreateContacts(_serviceProxy); } #endregion #region Create Patients if (patientcount > 0) { PatientConfiguration configuration = new PatientConfiguration(); configuration.PractionerFileName = practitonerFile; configuration.RelatedPersonsFileName = relatedpersonsFile; configuration.AllergyIntoleranceCount = patientallergycount; configuration.NutritionOrderCount = patientnutritionordercount; configuration.ConditionCount = patientconditioncount; configuration.DeviceCount = patientdevicecount; configuration.ProcedureCount = patientprocedurecount; configuration.MedicationCount = patientmedicationrequestcount; CreateCDMHealthData createPatients = new CreateCDMHealthData(); createPatients.FileName = filepath + "patients_" + patientcount.ToString() + "_" + Guid.NewGuid().ToString() + ".json"; createPatients.ContactType = Profile.ContactType.Patient; localpatients = Patient.GenerateProfilesByCount(patientcount, configuration); foreach (Profile patient in localpatients) { createPatients.IncomingContacts.Enqueue(patient); } createPatients.CreateCount = createPatients.IncomingContacts.Count; createPatients.EmailDomain = ConfigurationManager.AppSettings["cdm:emaildomain"]; createPatients.Clients = int.Parse(ConfigurationManager.AppSettings["cdm:clients"]); //; Console.WriteLine("\r\nCreating [" + createPatients.CreateCount.ToString() + "] Patients\r\n"); patientsFile = createPatients.CreateContacts(_serviceProxy); } #endregion Console.WriteLine("End Time: " + DateTime.Now.ToString()); return; } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve status options for the Incident entity /// Use GetValidStatusOptions to get valid status transitions for each status option /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); String entityLogicalName = "incident"; // Retrieve status options for the Incident entity //Retrieve just the incident entity and its attributes MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); MetadataPropertiesExpression entityProperties = 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 entity query EntityQueryExpression query = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProperties, 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.EntityMetadata[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, entityLogicalName); List <StatusOption> validStatusOptions = GetValidStatusOptions(entityLogicalName, 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(""); } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private int DisplayPluginControl(Lazy <IXrmToolBoxPlugin, IPluginMetadata> plugin) { var tabIndex = 0; Guid pluginControlInstanceId = Guid.NewGuid(); try { var pluginControl = (UserControl)plugin.Value.GetControl(); // ReSharper disable once SuspiciousTypeConversion.Global var host = pluginControl as IMessageBusHost; if (host != null) { host.OnOutgoingMessage += MainForm_MessageBroker; } var statusBarMessager_old = pluginControl as IStatusBarMessager; if (statusBarMessager_old != null) { statusBarMessager_old.SendMessageToStatusBar += StatusBarMessager_SendMessageToStatusBar; } var statusBarMessager = pluginControl as IStatusBarMessenger; if (statusBarMessager != null) { statusBarMessager.SendMessageToStatusBar += StatusBarMessager_SendMessageToStatusBar; } if (service != null) { var crmSvcClient = currentConnectionDetail.GetCrmServiceClient(); OrganizationServiceProxy clonedService = crmSvcClient.OrganizationServiceProxy; OrganizationWebProxyClient clonedWebClientService = crmSvcClient.OrganizationWebProxyClient; if (clonedService != null) { clonedService.SdkClientVersion = currentConnectionDetail.OrganizationVersion; } if (clonedWebClientService != null) { clonedWebClientService.SdkClientVersion = currentConnectionDetail.OrganizationVersion; } var earlyBoundProxiedControl = pluginControl as IEarlyBoundProxy; if (earlyBoundProxiedControl != null) { clonedService?.EnableProxyTypes(earlyBoundProxiedControl.GetEarlyBoundProxyAssembly()); } if (clonedService != null) { ((IXrmToolBoxPluginControl)pluginControl).UpdateConnection(clonedService, currentConnectionDetail); } else { ((IXrmToolBoxPluginControl)pluginControl).UpdateConnection(clonedWebClientService, currentConnectionDetail); } } ((IXrmToolBoxPluginControl)pluginControl).OnRequestConnection += MainForm_OnRequestConnection; ((IXrmToolBoxPluginControl)pluginControl).OnCloseTool += MainForm_OnCloseTool; string name = string.Format("{0} ({1})", plugin.Metadata.Name, currentConnectionDetail != null ? currentConnectionDetail.ConnectionName : "Not connected"); var newTab = new TabPage(name) { Tag = plugin }; tabControl1.TabPages.Add(newTab); pluginControl.Dock = DockStyle.Fill; pluginControl.Width = newTab.Width; pluginControl.Height = newTab.Height; pluginControl.Tag = pluginControlInstanceId; newTab.Controls.Add(pluginControl); tabIndex = tabControl1.TabPages.Count - 1; tabControl1.SelectTab(tabIndex); var pluginInOption = currentOptions.MostUsedList.FirstOrDefault(i => i.Name == plugin.Value.GetType().FullName); if (pluginInOption == null) { pluginInOption = new PluginUseCount { Name = plugin.Value.GetType().FullName, Count = 0 }; currentOptions.MostUsedList.Add(pluginInOption); } pluginInOption.Count++; if (currentOptions.LastAdvertisementDisplay == new DateTime() || currentOptions.LastAdvertisementDisplay > DateTime.Now || currentOptions.LastAdvertisementDisplay.AddDays(7) < DateTime.Now) { bool displayAdvertisement = true; try { var assembly = Assembly.LoadFile(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory + "\\McTools.StopAdvertisement.dll"); if (assembly != null) { Type type = assembly.GetType("McTools.StopAdvertisement.LicenseManager"); if (type != null) { MethodInfo methodInfo = type.GetMethod("IsValid"); if (methodInfo != null) { object classInstance = Activator.CreateInstance(type, null); if ((bool)methodInfo.Invoke(classInstance, null)) { displayAdvertisement = false; } } } } } catch (FileNotFoundException) { } if (displayAdvertisement) { var sc = new SupportScreen(); sc.ShowDialog(this); currentOptions.LastAdvertisementDisplay = DateTime.Now; } } if (currentOptions.AllowLogUsage.HasValue && currentOptions.AllowLogUsage.Value) { #pragma warning disable CS4014 // Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel LogUsage.DoLog(plugin); #pragma warning restore CS4014 // Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel } currentOptions.Save(); } catch (Exception error) { MessageBox.Show(this, "An error occured when trying to display this plugin: " + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(tabIndex); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// creates/retrieves a system user, /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user is prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole); _roleId = salesRole.Id; // Associate the user with the role. if (_roleId != Guid.Empty & amp; & _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Role is associated with the user."); } } 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 pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //Create export folder for ribbon xml files if not already exist. if (!Directory.Exists(exportFolder)) { Directory.CreateDirectory(exportFolder); } //Retrieve the Appliation Ribbon RetrieveApplicationRibbonRequest appribReq = new RetrieveApplicationRibbonRequest(); RetrieveApplicationRibbonResponse appribResp = (RetrieveApplicationRibbonResponse)_serviceProxy.Execute(appribReq); System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml"); File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml)); //Write the path where the file has been saved. Console.WriteLine(applicationRibbonPath); //Retrieve system Entity Ribbons RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest() { RibbonLocationFilter = RibbonLocationFilters.All }; foreach (System.String entityName in entitiesWithRibbons) { entRibReq.EntityName = entityName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } //Check for custom entities RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity }; RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer); foreach (EntityMetadata em in resp.EntityMetadata) { if (em.IsCustomEntity == true & amp; & em.IsIntersect == false) { entRibReq.EntityName = em.LogicalName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Creates required records for this sample. CreateRequiredRecords(); // Qualify a lead to create an opportunity QualifyLeadRequest qualifyRequest = new QualifyLeadRequest { LeadId = new EntityReference(Lead.EntityLogicalName, _leadId), Status = new OptionSetValue((int)lead_statuscode.Qualified), CreateOpportunity = true }; QualifyLeadResponse qualifyResponse = (QualifyLeadResponse)_serviceProxy.Execute(qualifyRequest); _opportunityId = qualifyResponse.CreatedEntities[0].Id; if (_opportunityId != Guid.Empty) { Console.WriteLine("\nQualified Lead to create an Opportunity record."); } // Verify the curently active BPF instance for the qualified Opportunity record RetrieveProcessInstancesRequest procOpp1Req = new RetrieveProcessInstancesRequest { EntityId = _opportunityId, EntityLogicalName = Opportunity.EntityLogicalName }; RetrieveProcessInstancesResponse procOpp1Resp = (RetrieveProcessInstancesResponse)_serviceProxy.Execute(procOpp1Req); // Declare variables to store values returned in response Entity activeProcessInstance = null; if (procOpp1Resp.Processes.Entities.Count > 0) { activeProcessInstance = procOpp1Resp.Processes.Entities[0]; // First record is the active process instance _processOpp1Id = activeProcessInstance.Id; // Id of the active process instance, which will be used // later to retrieve the active path of the process instance Console.WriteLine("Current active process instance for the Opportunity record: '{0}'", activeProcessInstance["name"].ToString()); _procInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower(); } else { Console.WriteLine("No process instances found for the opportunity record; aborting the sample."); Environment.Exit(1); } // Retrieve the active stage ID of the active process instance _activeStageId = new Guid(activeProcessInstance.Attributes["processstageid"].ToString()); // Retrieve the process stages in the active path of the current process instance RetrieveActivePathRequest pathReq = new RetrieveActivePathRequest { ProcessInstanceId = _processOpp1Id }; RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)_serviceProxy.Execute(pathReq); Console.WriteLine("\nRetrieved stages in the active path of the process instance:"); for (int i = 0; i < pathResp.ProcessStages.Entities.Count; i++) { Console.WriteLine("\tStage {0}: {1} (StageId: {2})", i + 1, pathResp.ProcessStages.Entities[i].Attributes["stagename"], pathResp.ProcessStages.Entities[i].Attributes["processstageid"]); // Retrieve the active stage name and active stage position based on the activeStageId for the process instance if (pathResp.ProcessStages.Entities[i].Attributes["processstageid"].ToString() == _activeStageId.ToString()) { _activeStageName = pathResp.ProcessStages.Entities[i].Attributes["stagename"].ToString(); _activeStagePosition = i; } } // Display the active stage name and Id Console.WriteLine("\nActive stage for the process instance: '{0}' (StageID: {1})", _activeStageName, _activeStageId); // Prompt the user to move to the next stage. If user choses to do so: // Set the next stage (_activeStagePosition + 1) as the active stage for the process instance bool moveToNextStage = true; Console.WriteLine("\nDo you want to move to the next stage (y/n):"); String answer = Console.ReadLine(); moveToNextStage = (answer.StartsWith("y") || answer.StartsWith("Y")); if (moveToNextStage) { // Retrieve the stage ID of the next stage that you want to set as active _activeStageId = (Guid)pathResp.ProcessStages.Entities[_activeStagePosition + 1].Attributes["processstageid"]; // Retrieve the process instance record to update its active stage ColumnSet cols1 = new ColumnSet(); cols1.AddColumn("activestageid"); Entity retrievedProcessInstance = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols1); // Update the active stage to the next stage retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, _activeStageId); _serviceProxy.Update(retrievedProcessInstance); // Retrieve the process instance record again to verify its active stage information ColumnSet cols2 = new ColumnSet(); cols2.AddColumn("activestageid"); Entity retrievedProcessInstance1 = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols2); EntityReference activeStageInfo = retrievedProcessInstance1["activestageid"] as EntityReference; if (activeStageInfo.Id == _activeStageId) { Console.WriteLine("\nChanged active stage for the process instance to: '{0}' (StageID: {1})", activeStageInfo.Name, activeStageInfo.Id); } } // Prompts to delete the required records DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics 365 throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
public override Guid WriteToCDS(string cdsUrl, string cdsUserName, string cdsPassword) { Guid referralrequestId = Guid.Empty; try { #region Get our Login Information // setup the variables OrganizationServiceProxy _serviceProxy; // homeRealmUri will stay null for now Uri homeRealmUri = null; // setup credentials from whatever is in the app.config ClientCredentials credentials; // same for organizationuri comes from app.config Uri organizationUri; // set the organization uri from what was in the app.config organizationUri = new Uri(cdsUrl); credentials = new ClientCredentials(); credentials.UserName.UserName = cdsUserName; credentials.UserName.Password = cdsPassword; #endregion ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (_serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null)) { // To impersonate set the GUID of CRM user here (which I merely took from CRM itself // would need not to use this caller id in the future (as it will change per instance of CRM) //_serviceProxy.CallerId = new Guid("14D40CB7-81D5-E311-93F5-00155D00330C"); _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); //enable using proxy types _serviceProxy.EnableProxyTypes(); HealthCDM.msemr_referralrequest addReferrralRequest = new HealthCDM.msemr_referralrequest(); addReferrralRequest.msemr_SubjectPatient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PatientId))); addReferrralRequest.msemr_Requestor = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PractitionerId))); addReferrralRequest.msemr_Status = new OptionSetValue(Status); addReferrralRequest.msemr_OccurrenceDate = OccurrendateDate; addReferrralRequest.msemr_Description = Description; addReferrralRequest.msemr_Priority = new OptionSetValue(Priority); addReferrralRequest.msemr_Intent = new OptionSetValue(Intent); addReferrralRequest.msemr_name = Description; try { referralrequestId = _serviceProxy.Create(addReferrralRequest); if (referralrequestId != Guid.Empty) { ReferralRequestId = referralrequestId.ToString(); Console.WriteLine("Created Patient Referral Request [" + ReferralRequestId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("ReferralRequestId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(referralrequestId); }
/// <summary> /// This method first connects to the Organization service. Afterwards, it /// creates/retrieves a system user, and /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetRemoveRoleFromUser1> // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve a user. SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>(); if (user != null) { Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName); // Find the role. QueryExpression query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); // Disassociate the role. if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved.", _givenRole); _serviceProxy.Disassociate( "systemuser", user.Id, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("role", salesRole.Id) }); Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName); } } } //</snippetRemoveRoleFromUser1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Create a new queue instance. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // 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); 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 pass it back to the calling method. throw; } }
/// <summary> /// This method shows how to merge two entity records with the Merge message. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { using (_serviceProxy = 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. EntityReference target = new EntityReference(); // Id is the GUID of the account that is being merged into. // LogicalName is the type of the entity being merged to, as a string target.Id = _account1Id; target.LogicalName = Account.EntityLogicalName; // Create the request. MergeRequest merge = new MergeRequest(); // SubordinateId is the GUID of the account merging. merge.SubordinateId = _account2Id; merge.Target = target; merge.PerformParentingChecks = false; Console.WriteLine("\nMerging account2 into account1 and adding " + "\"test\" as Address 1 Line 1"); // Create another account to hold new data to merge into the entity. // If you use the subordinate account object, its data will be merged. Account updateContent = new Account(); updateContent.Address1_Line1 = "test"; // Set the content you want updated on the merged account merge.UpdateContent = updateContent; // Execute the request. MergeResponse merged = (MergeResponse)_serviceProxy.Execute(merge); //</snippetMerge1> Account mergeeAccount = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account2Id, new ColumnSet(allColumns: true)); if (mergeeAccount.Merged == true) { Account mergedAccount = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account1Id, new ColumnSet(allColumns: true)); Console.WriteLine("\nAccounts merged successfully into account1"); Console.WriteLine(" Name: {0}", mergedAccount.Name); Console.WriteLine(" Description: {0}", mergedAccount.Description); Console.WriteLine(" Number of Employees: {0}", mergedAccount.NumberOfEmployees); Console.WriteLine(" Address 1 Line 1: {0}", mergedAccount.Address1_Line1); } DeleteRequiredRecords(promptForDelete); } }
/// <summary> /// This sample creates a role that is not linked to any entity type. All /// connection roles that apply to all are found and shown. Then the role is /// linked to the account entity and it is demonstrated that the role only works /// for accounts at this point, not for all. Subsequently the link to the account /// entity is removed and it is shown that the role is now applicable to all /// entities again. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { //<snippetQueryConnectionRolesByEntityTypeCode1> // Connect to the Organization service. // The using statement assures 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 { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to all entities (object type code = 0). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.Equal, Values = { 0 } } } } } } }; EntityCollection results = _serviceProxy.RetrieveMultiple(allQuery); // Here you could perform operations on all of // the connectionroles found by the query. Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Query to find roles which apply only to accounts. QueryExpression accountQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, 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 = "associatedobjecttypecode", Operator = ConditionOperator.In, Values = { Account.EntityLogicalName } } } } } } }; results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Create a related Connection Role Object Type Code record for // Account. ConnectionRoleObjectTypeCode setupAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; 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 unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine(@"Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Remove the link from account entity. _serviceProxy.Delete(ConnectionRoleObjectTypeCode.EntityLogicalName, setupAccountConnectionRoleTypeCode.Id); Console.WriteLine("Removed link from connectionrole to account entity."); // Run the query to find unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); DeleteRequiredRecords(promptForDelete); } //</snippetQueryConnectionRolesByEntityTypeCode1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBasicContextExamples1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery <SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list, "); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("quote, "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", QuantityOnHand = 2, ProductNumber = "WIDG-A", ProductStructure = new OptionSetValue(1), Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery <UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery <UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.Write("product, "); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("associating product to price list, "); // Publish Product SetStateRequest publishRequest1 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _productId), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest1); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.Write("adding product to quote, "); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery <Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This sample demonstrates how to execute a collection of message requests using a single web service /// call and optionally return the results. /// </summary> /// <seealso cref="http://msdn.microsoft.com/en-us/library/gg328075.aspx"/> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetExecuteMultiple1> // Get a reference to the organization service. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // Enable early-bound type support to add/update entity records required for this sample. _serviceProxy.EnableProxyTypes(); #region Execute Multiple with Results // Create an ExecuteMultipleRequest object. requestWithResults = new ExecuteMultipleRequest() { // Assign settings that define execution behavior: continue on error, return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = true }, // Create an empty organization request collection. Requests = new OrganizationRequestCollection() }; // Create several (local, in memory) entities in a collection. EntityCollection input = GetCollectionOfEntitiesToCreate(); // Add a CreateRequest for each entity to the request collection. foreach (var entity in input.Entities) { CreateRequest createRequest = new CreateRequest { Target = entity }; requestWithResults.Requests.Add(createRequest); } // Execute all the requests in the request collection using a single web method call. ExecuteMultipleResponse responseWithResults = (ExecuteMultipleResponse)_serviceProxy.Execute(requestWithResults); // Display the results returned in the responses. foreach (var responseItem in responseWithResults.Responses) { // A valid response. if (responseItem.Response != null) { DisplayResponse(requestWithResults.Requests[responseItem.RequestIndex], responseItem.Response); } // An error has occurred. else if (responseItem.Fault != null) { DisplayFault(requestWithResults.Requests[responseItem.RequestIndex], responseItem.RequestIndex, responseItem.Fault); } } //</snippetExecuteMultiple1> #endregion Execute Multiple with Results #region Execute Multiple with No Results ExecuteMultipleRequest requestWithNoResults = new ExecuteMultipleRequest() { // Set the execution behavior to not continue after the first error is received // and to not return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = false }, Requests = new OrganizationRequestCollection() }; // Update the entities that were previously created. EntityCollection update = GetCollectionOfEntitiesToUpdate(); foreach (var entity in update.Entities) { UpdateRequest updateRequest = new UpdateRequest { Target = entity }; requestWithNoResults.Requests.Add(updateRequest); } ExecuteMultipleResponse responseWithNoResults = (ExecuteMultipleResponse)_serviceProxy.Execute(requestWithNoResults); // There should be no responses unless there was an error. Only the first error // should be returned. That is the behavior defined in the settings. if (responseWithNoResults.Responses.Count > 0) { foreach (var responseItem in responseWithNoResults.Responses) { if (responseItem.Fault != null) { DisplayFault(requestWithNoResults.Requests[responseItem.RequestIndex], responseItem.RequestIndex, responseItem.Fault); } } } else { Console.WriteLine("All account records have been updated successfully."); } #endregion Execute Multiple with No Results #region Execute Multiple with Continue On Error ExecuteMultipleRequest requestWithContinueOnError = new ExecuteMultipleRequest() { // Set the execution behavior to continue on an error and not return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, Requests = new OrganizationRequestCollection() }; // Update the entities but introduce some bad attribute values so we get errors. EntityCollection updateWithErrors = GetCollectionOfEntitiesToUpdateWithErrors(); foreach (var entity in updateWithErrors.Entities) { UpdateRequest updateRequest = new UpdateRequest { Target = entity }; requestWithContinueOnError.Requests.Add(updateRequest); } ExecuteMultipleResponse responseWithContinueOnError = (ExecuteMultipleResponse)_serviceProxy.Execute(requestWithContinueOnError); // There should be no responses except for those that contain an error. if (responseWithContinueOnError.Responses.Count > 0) { if (responseWithContinueOnError.Responses.Count < requestWithContinueOnError.Requests.Count) { Console.WriteLine("Response collection contain a mix of successful response objects and errors."); } foreach (var responseItem in responseWithContinueOnError.Responses) { if (responseItem.Fault != null) { DisplayFault(requestWithContinueOnError.Requests[responseItem.RequestIndex], responseItem.RequestIndex, responseItem.Fault); } } } else { // No errors means all transactions are successful. Console.WriteLine("All account records have been updated successfully."); } #endregion Execute Multiple with Continue On Error DeleteRequiredRecords(promptforDelete); } } // <snippetExecuteMultiple2> catch (FaultException <OrganizationServiceFault> fault) { // Check if the maximum batch size has been exceeded. The maximum batch size is only included in the fault if it // the input request collection count exceeds the maximum batch size. if (fault.Detail.ErrorDetails.Contains("MaxBatchSize")) { int maxBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]); if (maxBatchSize < requestWithResults.Requests.Count) { // Here you could reduce the size of your request collection and re-submit the ExecuteMultiple request. // For this sample, that only issues a few requests per batch, we will just print out some info. However, // this code will never be executed because the default max batch size is 1000. Console.WriteLine("The input request collection contains %0 requests, which exceeds the maximum allowed (%1)", requestWithResults.Requests.Count, maxBatchSize); } } // Re-throw so Main() can process the fault. throw; } // </snippetExecuteMultiple2> }
/// <summary> /// Create an e-mail activity instance from the specified e-mail message. /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create a contact to send an email to (To: field) Contact emailContact = new Contact() { FirstName = "Lisa", LastName = "Andrews", EMailAddress1 = "*****@*****.**" }; _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.EntityLogicalName, 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 EntityCollection(new ActivityMimeAttachment[0]); deliverEmailRequest.Attachments.EntityName = ActivityMimeAttachment.EntityLogicalName; // 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.EntityLogicalName, 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 pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, a /// case is created. The IsValidStateTransition is used to test if a state change /// is valid. The case is closed, re-opened and then closed with SetState. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { using (_serviceProxy = 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 EntityReference to represent an open case EntityReference caseReference = new EntityReference() { LogicalName = Incident.EntityLogicalName, Id = _caseIncidentId }; IsValidStateTransitionRequest checkState = new IsValidStateTransitionRequest(); // Set the transition request to an open case checkState.Entity = 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); } }
/// <summary> /// This method first creates sample articles and publishes them, then searches /// for the articles by body, keyword and title. Finally, it retrieves the /// articles by top incident subject and top incident product. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) // Using the ServiceContext class makes the queries easier using (_context = new ServiceContext(_serviceProxy)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Search Knowledge base by Body // Create the request SearchByBodyKbArticleRequest searchByBodyRequest = new SearchByBodyKbArticleRequest() { SubjectId = _subjectId, UseInflection = true, // allows for a different tense or // inflection to be substituted for the search text SearchText = "contained", // will also match on 'contains' QueryExpression = new QueryExpression() { ColumnSet = new ColumnSet("articlexml"), EntityName = KbArticle.EntityLogicalName } }; // Execute the request Console.WriteLine(" Searching for published article with 'contained' in the body"); SearchByBodyKbArticleResponse seachByBodyResponse = (SearchByBodyKbArticleResponse)_context.Execute(searchByBodyRequest); // Check success var retrievedArticleBodies = seachByBodyResponse.EntityCollection.Entities .Select((entity) => ((KbArticle)entity).ArticleXml); if (retrievedArticleBodies.Count() == 0) { throw new Exception("No articles found"); } Console.WriteLine(" Results of search (article bodies found):"); foreach (var body in retrievedArticleBodies) { Console.WriteLine(body); } #endregion #region Search knowledge base by Keyword // Create the request SearchByKeywordsKbArticleRequest searchByKeywordRequest = new SearchByKeywordsKbArticleRequest() { SubjectId = _subjectId, UseInflection = true, SearchText = "Search", QueryExpression = new QueryExpression() { ColumnSet = new ColumnSet("keywords"), EntityName = KbArticle.EntityLogicalName } }; // Execute the request Console.WriteLine(); Console.WriteLine(" Searching for published article with 'search' as a keyword"); var searchByKeywordResponse = (SearchByKeywordsKbArticleResponse)_context.Execute(searchByKeywordRequest); // Check success var retrievedArticleKeywords = searchByKeywordResponse.EntityCollection.Entities .Select((entity) => (KbArticle)entity); if (retrievedArticleKeywords.Count() == 0) { throw new Exception("No articles found"); } Console.WriteLine(" Results of search (keywords found):"); foreach (var article in retrievedArticleKeywords) { Console.WriteLine(article.KeyWords); } #endregion #region Search knowledge base by Title // create the request SearchByTitleKbArticleRequest searchByTitleRequest = new SearchByTitleKbArticleRequest() { SubjectId = _subjectId, UseInflection = false, SearchText = "code", QueryExpression = new QueryExpression() { ColumnSet = new ColumnSet("title"), EntityName = KbArticle.EntityLogicalName } }; // execute the request Console.WriteLine(); Console.WriteLine(" Searching for published articles with 'code' in the title"); var searchByTitleResponse = (SearchByTitleKbArticleResponse) _context.Execute(searchByTitleRequest); // check success var retrievedArticles = searchByTitleResponse.EntityCollection.Entities .Select((entity) => (KbArticle)entity); Console.WriteLine(" Results of search (titles found):"); foreach (var article in retrievedArticles) { Console.WriteLine(article.Title); } #endregion #region Retrieve by top incident subject // create the request var retrieveByTopIncidentSubjectRequest = new RetrieveByTopIncidentSubjectKbArticleRequest() { SubjectId = _subjectId }; // execute request Console.WriteLine(); Console.WriteLine(" Searching for the top articles in subject 'Default Subject'"); var retrieveByTopIncidentSubjectResponse = (RetrieveByTopIncidentSubjectKbArticleResponse) _context.Execute(retrieveByTopIncidentSubjectRequest); // check success var articles = retrieveByTopIncidentSubjectResponse.EntityCollection.Entities.Select( (entity) => (KbArticle)entity); Console.WriteLine(" Top articles in subject 'Default Subject':"); foreach (var article in articles) { Console.WriteLine(article.Title); } #endregion #region Retrieve by top incident product // create the request var retrieveByTopIncidentProductRequest = new RetrieveByTopIncidentProductKbArticleRequest() { ProductId = _product.Id }; // execute request Console.WriteLine(); Console.WriteLine(" Searching for the top articles for product 'Sample Product'"); var retrieveByTopIncidentProductResponse = (RetrieveByTopIncidentProductKbArticleResponse) _context.Execute(retrieveByTopIncidentProductRequest); // check success articles = retrieveByTopIncidentProductResponse.EntityCollection.Entities.Select( (entity) => (KbArticle)entity); Console.WriteLine(" Top articles for product 'Sample Product':"); foreach (var article in articles) { Console.WriteLine(article.Title); } #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 pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetExportRibbonXml1> // Connect to the Organization service. // The using statement assures 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 export folder for ribbon xml files if not already exist. if (!Directory.Exists(exportFolder)) { Directory.CreateDirectory(exportFolder); } //<snippetExportRibbonXml3> //Retrieve the Appliation Ribbon RetrieveApplicationRibbonRequest appribReq = new RetrieveApplicationRibbonRequest(); RetrieveApplicationRibbonResponse appribResp = (RetrieveApplicationRibbonResponse)_serviceProxy.Execute(appribReq); System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml"); File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml)); //</snippetExportRibbonXml3> //Write the path where the file has been saved. Console.WriteLine(applicationRibbonPath); //<snippetExportRibbonXml4> //Retrieve system Entity Ribbons RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest() { RibbonLocationFilter = RibbonLocationFilters.All }; #region retrieval code bool isDone = false; while (!isDone) { Console.WriteLine("\nRetrieve all ribbons or specific ribbons? (a)ll/(s)pecific: "); string input = Console.ReadLine(); if (input == "a") { foreach (System.String entityName in entitiesWithRibbons) { entRibReq.EntityName = entityName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } //</snippetExportRibbonXml4> //<snippetExportRibbonXml5> //Check for custom entities RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity }; RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer); foreach (EntityMetadata em in resp.EntityMetadata) { if (em.IsCustomEntity == true && em.IsIntersect == false) { entRibReq.EntityName = em.LogicalName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } } isDone = true; } else if (input == "s") { // first do system entities int i = 0; foreach (System.String entityName in entitiesWithRibbons) { Console.WriteLine("[{0}] {1}", i++, entityName); } Console.WriteLine("Enter the numbers of the entities to download, separated by commas: "); string entityNums = Console.ReadLine(); string[] entityNumsArr = entityNums.Split(new char[] { ',' }); foreach (string numStr in entityNumsArr) { int num; if (Int32.TryParse(numStr, out num)) { if (num >= 0 && num < entitiesWithRibbons.Length) { string entityName = entitiesWithRibbons[num]; entRibReq.EntityName = entityName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } else { Console.WriteLine("No element index {0} in entitiesWithRibbons, skipping...", num); } } } // next check for custom entities RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity }; RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer); i = 0; foreach (EntityMetadata em in resp.EntityMetadata) { if (em.IsCustomEntity == true && em.IsIntersect == false) { Console.WriteLine("[{0}] {1}", i, em.LogicalName); } i++; } Console.WriteLine("Enter the numbers of the entities to download, separated by commas: "); entityNums = Console.ReadLine(); entityNumsArr = entityNums.Split(new char[] { ',' }); //foreach (EntityMetadata em in resp.EntityMetadata) foreach (string numStr in entityNumsArr) { int index; if (Int32.TryParse(numStr, out index)) { if (index >= 0 && index < resp.EntityMetadata.Length) { EntityMetadata em = resp.EntityMetadata[index]; if (em.IsCustomEntity == true && em.IsIntersect == false) { entRibReq.EntityName = em.LogicalName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } } } } Console.WriteLine(""); isDone = true; } } #endregion } //</snippetExportRibbonXml5> //</snippetExportRibbonXml1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create a custom entity. /// Update the custom entity. /// Optionally delete the custom entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the custom entity. CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Bank Account", 1033), DisplayCollectionName = new Label("Bank Accounts", 1033), Description = new Label("An entity to store information about customer bank accounts", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_accountname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Account Name", 1033), Description = new Label("The primary attribute for the Bank Account entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The Bank Account custom entity has been created."); // Add some attributes to the Bank Account entity CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_bankname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Bank Name", 1033), Description = new Label("The name of the bank.", 1033) } }; _serviceProxy.Execute(createBankNameAttributeRequest); Console.WriteLine("\nA Bank Name attribute has been added to the Bank Account entity."); CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_balance", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Balance", 1033), Description = new Label("Account Balance at the last known date", 1033), } }; _serviceProxy.Execute(createBalanceAttributeRequest); Console.WriteLine("A Balance attribute has been added to the Bank Account entity."); CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_checkeddate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Date", 1033), Description = new Label("The date the account balance was last confirmed", 1033) } }; _serviceProxy.Execute(createCheckedDateRequest); Console.WriteLine("A date attribute has been added to the Bank Account entity."); //Create a customer lookup attribute to link the bank account with an account or a contact record. CreateCustomerRelationshipsRequest createCustomerReq = new CreateCustomerRelationshipsRequest { Lookup = new LookupAttributeMetadata { Description = new Label("The owner of the bank account", 1033), DisplayName = new Label("Account owner", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired), SchemaName = "new_customerid" }, OneToManyRelationships = new OneToManyRelationshipMetadata[] { new OneToManyRelationshipMetadata() { ReferencedEntity = "account", ReferencingEntity = _customEntityName, SchemaName = "new_bankaccount_customer_account", }, new OneToManyRelationshipMetadata() { ReferencedEntity = "contact", ReferencingEntity = _customEntityName, SchemaName = "new_bankaccount_customer_contact", } }, }; _serviceProxy.Execute(createCustomerReq); Console.WriteLine("A customer lookup attribute has been added to the Bank Account entity \nto link it with the Account or Contact entity."); //Create a lookup attribute to link the bank account with a contact record. CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The referral (lead) from the bank account owner", 1033), DisplayName = new Label("Referral", 1033), LogicalName = "new_parent_leadid", SchemaName = "New_Parent_leadId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Bank Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = "lead", ReferencedAttribute = "leadid", ReferencingEntity = _customEntityName, SchemaName = "new_lead_new_bankaccount" } }; _serviceProxy.Execute(req); Console.WriteLine("A lookup attribute has been added to the Bank Account entity \nto link it with the Lead entity."); //Create an Image attribute for the custom entity // Only one Image attribute can be added to an entity that doesn't already have one. CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to represent the bank account.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("An image attribute has been added to the Bank Account entity."); RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest); EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata; // Disable Mail merge BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false); // Enable Notes UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest { Entity = BankAccountEntity, HasNotes = true }; _serviceProxy.Execute(updateBankAccountRequest); Console.WriteLine("\nThe Bank Account entity has been updated"); //Update the entity form so the new fields are visible UpdateEntityForm(_customEntityName); // Customizations must be published after an entity is updated. PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); Console.WriteLine("\nCustomizations were published."); //Provides option to view the entity in the default solution ShowEntityInBrowser(promptForDelete, BankAccountEntity); //Provides option to view the entity form with the fields added ShowEntityFormInBrowser(promptForDelete, BankAccountEntity); 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 pass it back to the calling method. throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Create a recurring appointment. /// Retrieve the recurring appointment. /// Update the retrieved recurring appointment. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetCRUDRecurringAppointment1> // Define an anonymous type to define the possible recurrence pattern values. var RecurrencePatternTypes = new { Daily = 0, Weekly = 1, Monthly = 2, Yearly = 3 }; // Define an anonymous type to define the possible values for days // of the week var DayOfWeek = new { Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, Wednesday = 0x08, Thursday = 0x10, Friday = 0x20, Saturday = 0x40 }; // Define an anonymous type to define the possible values // for the recurrence rule pattern end type. var RecurrenceRulePatternEndType = new { NoEndDate = 1, Occurrences = 2, PatternEndDate = 3 }; // Create a recurring appointment RecurringAppointmentMaster newRecurringAppointment = new RecurringAppointmentMaster { Subject = "Sample Recurring Appointment", StartTime = DateTime.Now.AddHours(1), EndTime = DateTime.Now.AddHours(2), RecurrencePatternType = new OptionSetValue(RecurrencePatternTypes.Weekly), Interval = 1, DaysOfWeekMask = DayOfWeek.Thursday, PatternStartDate = DateTime.Today, Occurrences = 10, PatternEndType = new OptionSetValue(RecurrenceRulePatternEndType.Occurrences) }; _recurringAppointmentMasterId = _serviceProxy.Create(newRecurringAppointment); Console.WriteLine("Created {0}.", newRecurringAppointment.Subject); // Retrieve the newly created recurring appointment QueryExpression recurringAppointmentQuery = new QueryExpression { EntityName = RecurringAppointmentMaster.EntityLogicalName, ColumnSet = new ColumnSet("subject"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "subject", Operator = ConditionOperator.Equal, Values = { "Sample Recurring Appointment" } }, new ConditionExpression { AttributeName = "interval", Operator = ConditionOperator.Equal, Values = { 1 } } } }, PageInfo = new PagingInfo { Count = 1, PageNumber = 1 } }; RecurringAppointmentMaster retrievedRecurringAppointment = _serviceProxy.RetrieveMultiple(recurringAppointmentQuery). Entities.Select(x => (RecurringAppointmentMaster)x).FirstOrDefault(); Console.WriteLine("Retrieved the recurring appointment."); // Update the recurring appointment. // Update the following for the retrieved recurring appointment series: // 1. Update the subject. // 2. Update the number of occurences to 5. // 3. Update the appointment interval to 2. retrievedRecurringAppointment.Subject = "Updated Recurring Appointment"; retrievedRecurringAppointment.Occurrences = 5; retrievedRecurringAppointment.Interval = 2; _serviceProxy.Update(retrievedRecurringAppointment); Console.WriteLine("Updated the subject, occurrences, and interval of the recurring appointment."); //</snippetCRUDRecurringAppointment1> 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 pass it back to the calling method. throw; } }