/// <summary> /// This method first connects to the Organization service. Afterwards, it /// retrieves roles. /// </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 { //<snippetRetrieveRolesForOrg1> // 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)) { QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("name", "roleid") }; EntityCollection entities = _serviceProxy.RetrieveMultiple(query); // Write the name and ID of each role to the console. foreach (Entity item in entities.Entities) { Role role = item.ToEntity<Role>(); Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id); } } //</snippetRetrieveRolesForOrg1> } // 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 void Connect() { ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration serverConfig = serverConnect.GetServerConfiguration(); this.service = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials); }
/// <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; } }
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) { } }
/// <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"); } } } }
/// <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> /// 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 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> /// 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 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> /// 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> /// 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> /// 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); } }
/// <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; } }
/// <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); } }
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; } }
static public void Main(string[] args) { // The connection to the Organization web service. OrganizationServiceProxy serviceProxy = null; try { // Obtain the target organization's web address and client logon credentials // from the user by using a helper class. ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration config = serverConnect.GetServerConfiguration(); // Establish an authenticated connection to the Organization web service. serviceProxy = new OrganizationServiceProxy(config.OrganizationUri, config.HomeRealmUri, config.Credentials, config.DeviceCredentials); CRUDOperations app = new CRUDOperations(); // Create any records that must exist in the database. These record references are // stored in a collection so the records can be deleted later. EntityReferenceCollection records = app.CreateRequiredEntityRecords(serviceProxy); // Perform the primary operation of this sample. app.Run(serviceProxy, records); // Delete all remaining records that were created by this sample. app.DeleteEntityRecords(serviceProxy, records, true); } // Some exceptions to consider catching. //<snippetCRUDOperations3> catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> e) { HandleException(e); } catch (TimeoutException e) { HandleException(e); } catch (SecurityTokenValidationException e) { HandleException(e); } catch (ExpiredSecurityTokenException e) { HandleException(e); } catch (MessageSecurityException e) { HandleException(e); } catch (SecurityNegotiationException e) { HandleException(e); } catch (SecurityAccessDeniedException e) { HandleException(e); } catch (Exception e) { HandleException(e); } //</snippetCRUDOperations3> finally { // Always dispose the service object to close the service connection and free resources. if (serviceProxy != null) serviceProxy.Dispose(); Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <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; } }
/// <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> /// Enables dupe detection and retrieves duplicates. /// </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(); EnableDuplicateDetectionForOrg(); EnableDuplicateDetectionForEntity(Account.EntityLogicalName); PublishRulesForEntity(Account.EntityLogicalName); CreateAccountRecords(); RetrieveDuplicates(); DeleteRequiredRecords(promptforDelete); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, it /// creates/retrieves a system user, and /// updates the system user to disable/enable the user 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 { //<snippetDisableOrEnableUser1> // 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.LastName, user.FirstName); SetStateRequest request = new SetStateRequest() { EntityMoniker = user.ToEntityReference(), // Sets the user to disabled. State = new OptionSetValue(1), // Required by request but always valued at -1 in this context. Status = new OptionSetValue(-1) /* //Sets the user to enabled. State = new OptionSetValue(0), // Required by request but always valued at -1 in this context. Status = new OptionSetValue(-1) */ }; _serviceProxy.Execute(request); Console.WriteLine("User account is disabled."); } DeleteRequiredRecords(promptforDelete); } //</snippetDisableOrEnableUser1> } // 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 user dashbaord is assigned to another user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // 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(); //<snippetAssignDashboardToUser1> AssignRequest assignRequest = new AssignRequest { Assignee = new EntityReference { LogicalName = SystemUser.EntityLogicalName, // Here we could assign the visualization to the newly created user Id = _otherUserId }, Target = new EntityReference { LogicalName = UserForm.EntityLogicalName, Id = _userDashboardId } }; _serviceProxy.Execute(assignRequest); Console.WriteLine("The user dashboard has been assigned to Kevin Cook."); //</snippetAssignDashboardToUser1> 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. /// Create a new connection between the account and the contact. /// 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(); //<snippetCreateConnection1> // Create a connection between the account and the contact. // Assign a connection role to a record. Connection newConnection = new Connection { Record1Id = new EntityReference(Account.EntityLogicalName, _accountId), Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), Record2RoleId = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), Record2Id = new EntityReference(Contact.EntityLogicalName, _contactId) }; _connectionId = _serviceProxy.Create(newConnection); //</snippetCreateConnection1> Console.WriteLine( "Created a connection between the account and the contact."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Demonstrates how to programmatically create a Workflow from an existing /// Process Template. /// </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 { //<snippetCreateProcessFromTemplate1> // 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(); OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy); CreateRequiredRecords(); CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest() { WorkflowName = "Workflow From Template", WorkflowTemplateId = _processTemplateId }; // Execute request. CreateWorkflowFromTemplateResponse response = (CreateWorkflowFromTemplateResponse)_serviceProxy.Execute(request); _processId = response.Id; // Verify success. // Retrieve the name of the workflow. ColumnSet cols = new ColumnSet("name"); Workflow newWorkflow = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols); if (newWorkflow.Name == "Workflow From Template") { Console.WriteLine("Created {0}.", request.WorkflowName); } DeleteRequiredRecords(promptforDelete); } //</snippetCreateProcessFromTemplate1> } // 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> /// Creates an import mapping, retrieves the xml, modifies the name, /// and re-imports the import mappings /// </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(); CreateImportMapping(); RetrieveMappingXml(); ChangeMappingName(); ImportMappingsByXml(); DeleteRequiredRecords(promptforDelete); } }
/// <summary> /// Convert a fax to a task. /// <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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetConvertFaxToTask1> // Retrieve the fax. Fax retrievedFax = (Fax)_serviceProxy.Retrieve(Fax.EntityLogicalName, _faxId, new ColumnSet(true)); // Create a task. Task task = new Task() { Subject = "Follow Up: " + retrievedFax.Subject, ScheduledEnd = retrievedFax.CreatedOn.Value.AddDays(7), }; _taskId = _serviceProxy.Create(task); // Verify that the task has been created if (_taskId != Guid.Empty) { Console.WriteLine("Created a task for the fax: '{0}'.", task.Subject); } //</snippetConvertFaxToTask1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Demonstrates the RetrieveOrganization and RetrieveOrganizations messages /// of the Discovery service. /// </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 { //<snippetDiscoveryService1> // Connect to the Discovery service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serverConfig)) { // You can choose to use the interface instead of the proxy. IDiscoveryService service = _serviceProxy; #region RetrieveOrganizations Message //<snippetDiscoveryService2> // Retrieve details about all organizations discoverable via the // Discovery service. RetrieveOrganizationsRequest orgsRequest = new RetrieveOrganizationsRequest() { AccessType = EndpointAccessType.Default, Release = OrganizationRelease.Current }; RetrieveOrganizationsResponse organizations = (RetrieveOrganizationsResponse)service.Execute(orgsRequest); //</snippetDiscoveryService2> // Print each organization's friendly name, unique name and URLs // for each of its endpoints. Console.WriteLine(); Console.WriteLine("Retrieving details of each organization:"); foreach (OrganizationDetail organization in organizations.Details) { Console.WriteLine("Organization Name: {0}", organization.FriendlyName); Console.WriteLine("Unique Name: {0}", organization.UniqueName); Console.WriteLine("Endpoints:"); foreach (var endpoint in organization.Endpoints) { Console.WriteLine(" Name: {0}", endpoint.Key); Console.WriteLine(" URL: {0}", endpoint.Value); } } Console.WriteLine("End of listing"); Console.WriteLine(); #endregion RetrieveOrganizations Message #region RetrieveOrganization Message //<snippetDiscoveryService3> // Retrieve details about a single organization discoverable via the Discovery service. // RetrieveOrganizationRequest orgRequest = new RetrieveOrganizationRequest() { UniqueName = organizations.Details[organizations.Details.Count - 1].UniqueName, AccessType = EndpointAccessType.Default, Release = OrganizationRelease.Current }; RetrieveOrganizationResponse org = (RetrieveOrganizationResponse)service.Execute(orgRequest); //</snippetDiscoveryService3> // Print the organization's friendly name, unique name and URLs // for each of its endpoints. Console.WriteLine(); Console.WriteLine("Retrieving details of specific organization:"); Console.WriteLine("Organization Name: {0}", org.Detail.FriendlyName); Console.WriteLine("Unique Name: {0}", org.Detail.UniqueName); Console.WriteLine("Endpoints:"); foreach (KeyValuePair <EndpointType, string> endpoint in org.Detail.Endpoints) { Console.WriteLine(" Name: {0}", endpoint.Key); Console.WriteLine(" URL: {0}", endpoint.Value); } Console.WriteLine("End of listing"); Console.WriteLine(); #endregion RetrieveOrganization Message } //</snippetDiscoveryService1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.DiscoveryServiceFault> ) { // 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, an /// opportunity is created to demonstrate a negative estimated value. This is /// followed by the creation of a quote with a negative product quantity. /// Finally, a sales order with a negative product price is shown. /// </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 { //<snippetWorkingWithNegativePrices1> // 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(); CreateRequiredRecords(); #region Opportunity with negative estimated value // Create a new opportunity with user-specified negative // estimated value. Opportunity opportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(-400.00m), FreightAmount = new Money(10.00m), ActualValue = new Money(-390.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityId = _serviceProxy.Create(opportunity); opportunity.Id = _opportunityId; // Create a catalog product for the opportunity. OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = opportunity.ToEntityReference(), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created opportunity with negative estimated value."); #endregion #region Quote with negative quantity // Create the quote. Quote quote = new Quote() { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample Quote", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _quoteId = _serviceProxy.Create(quote); quote.Id = _quoteId; // Set the quote's product quantity to a negative value. QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = -4, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Created quote with negative quantity."); #endregion #region Sales Order with negative price // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(-40.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); Console.WriteLine("Created order with negative price per unit."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithNegativePrices1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the custom entity. //<snippetCreateUpdateEntityMetadata1> 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."); //</snippetCreateUpdateEntityMetadata1> // Add some attributes to the Bank Account entity //<snippetCreateUpdateEntityMetadata2> 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); //</snippetCreateUpdateEntityMetadata2> Console.WriteLine("\nA Bank Name attribute has been added to the Bank Account entity."); //<snippetCreateUpdateEntityMetadata3> 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); //</snippetCreateUpdateEntityMetadata3> Console.WriteLine("A Balance attribute has been added to the Bank Account entity."); //<snippetCreateUpdateEntityMetadata4> 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."); //</snippetCreateUpdateEntityMetadata4> //Create a customer lookup attribute to link the bank account with an account or a contact record. //<snippetCreateUpdateEntityMetadata13> 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); //</snippetCreateUpdateEntityMetadata13> 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. //<snippetCreateUpdateEntityMetadata5> 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); //</snippetCreateUpdateEntityMetadata5> Console.WriteLine("A lookup attribute has been added to the Bank Account entity \nto link it with the Lead entity."); //<snippetCreateUpdateEntityMetadata11> //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."); //</snippetCreateUpdateEntityMetadata11> //<snippetCreateUpdateEntityMetadata9> //<snippetCreateUpdateEntityMetadata.RetrieveEntity> RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest); //</snippetCreateUpdateEntityMetadata.RetrieveEntity> //<snippetCreateUpdateEntityMetadata8> 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); //</snippetCreateUpdateEntityMetadata8> //</snippetCreateUpdateEntityMetadata9> 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. //<snippetCreateUpdateEntityMetadata6> PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); //</snippetCreateUpdateEntityMetadata6> 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> /// </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(); //<snippetDumpOptionSetInfo1> #region How to dump option set info RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("AllOptionSetValues.xml"); using (StreamWriter sw = new StreamWriter(filename)) { // Create Xml Writer. XmlTextWriter metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { foreach (OptionSetMetadataBase optionSetMetadataBase in retrieveAllOptionSetsResponse.OptionSetMetadata) { if (optionSetMetadataBase.OptionSetType != null) { if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Picklist) { OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSetMetadataBase; // Start OptionSet Node metadataWriter.WriteStartElement("OptionSet"); metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Picklist.ToString()); metadataWriter.WriteElementString("OptionSetDisplayName", (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); // Writes the options metadataWriter.WriteStartElement("Options"); foreach (OptionMetadata option in optionSetMetadata.Options) { metadataWriter.WriteStartElement("Option"); metadataWriter.WriteElementString("OptionValue", option.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", option.Label.UserLocalizedLabel.Label.ToString()); metadataWriter.WriteEndElement(); } metadataWriter.WriteEndElement(); // End OptionSet Node metadataWriter.WriteEndElement(); } else if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Boolean) { BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSetMetadataBase; // Start OptionSet Node metadataWriter.WriteStartElement("OptionSet"); metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Boolean.ToString()); if (optionSetMetadata.DisplayName.LocalizedLabels.Count != 0) { metadataWriter.WriteElementString("OptionSetDisplayName", optionSetMetadata.DisplayName.LocalizedLabels[0].Label); } else { metadataWriter.WriteElementString("OptionSetDisplayName", "UNDEFINED"); } // Writes the TrueOption metadataWriter.WriteStartElement("TrueOption"); metadataWriter.WriteElementString("OptionValue", optionSetMetadata.TrueOption.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label.ToString()); metadataWriter.WriteEndElement(); // Writes the FalseOption metadataWriter.WriteStartElement("FalseOption"); metadataWriter.WriteElementString("OptionValue", optionSetMetadata.FalseOption.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label.ToString()); metadataWriter.WriteEndElement(); // End OptionSet Node metadataWriter.WriteEndElement(); } } } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } #endregion How to dump option set info Console.WriteLine("Done."); //</snippetDumpOptionSetInfo1> //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> /// Based on the Main() method used by most SDK samples. /// </summary> /// <param name="args"></param> static public void Main(string[] args) { try { // Obtain the target organization's Web address and client logon // credentials from the user. ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration config = serverConnect.GetServerConfiguration(); MetadataQuerySample app = new MetadataQuerySample(); app.Run(config); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp); Console.WriteLine("Code: {0}", ex.Detail.ErrorCode); Console.WriteLine("Message: {0}", ex.Detail.Message); Console.WriteLine("Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "Has Inner Fault" : "No Inner Fault"); } catch (System.TimeoutException ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Message: {0}", ex.Message); Console.WriteLine("Stack Trace: {0}", ex.StackTrace); Console.WriteLine("Inner Fault: {0}", null == ex.InnerException.Message ? "Has Inner Fault" : "No Inner Fault"); } catch (System.Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>; if (fe != null) { Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp); Console.WriteLine("Code: {0}", fe.Detail.ErrorCode); Console.WriteLine("Message: {0}", fe.Detail.Message); Console.WriteLine("Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "Has Inner Fault" : "No Inner Fault"); } } } //Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, //SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. finally { Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <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 { //<snippetInvokeDuplicateDetectionForCreateAndUpdate1> // 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 and account record with the named Proseware, Inc. and already existing Account Number. Account account = new Account { Name = "Proseware, Inc.", AccountNumber = "ACC005" }; // Create operation by suppressing duplicate detection CreateRequest reqCreate = new CreateRequest(); reqCreate.Target = account; reqCreate.Parameters.Add("SuppressDuplicateDetection", true); // Change to false to activate the duplicate detection. CreateResponse createResponse = (CreateResponse)_service.Execute(reqCreate); _dupAccountId = createResponse.id; Console.Write("Account: {0} {1} created with SuppressDuplicateDetection to true, ", account.Name, account.AccountNumber); // Retrieve the account containing with its few attributes. ColumnSet cols = new ColumnSet( new String[] { "name", "accountnumber" }); Account retrievedAccount = (Account)_service.Retrieve("account", _dupAccountId, cols); Console.Write("retrieved, "); // Update the existing account with new account number. retrievedAccount.AccountNumber = "ACC006"; // Update operation – update record, if a duplicate is not found. UpdateRequest reqUpdate = new UpdateRequest(); reqUpdate.Target = retrievedAccount; reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated. // Update the account record. UpdateResponse updateResponse = (UpdateResponse)_service.Execute(reqUpdate); Console.WriteLine("and updated."); DeleteRequiredRecords(promptforDelete); } //</snippetInvokeDuplicateDetectionForCreateAndUpdate1> } // 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; } }