/// <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; } }
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; } }
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; }
//Start of Main public static void Main(string[] args) { Console.WriteLine("The process has started \nTrying to Export Solution"); //Create new user and gets credentials to login and capture desired solution Session loginUser = new Session(); ClientCredentials credentials = GetCredentials(loginUser); using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(loginUser.OrganizationUri,null, credentials, GetDeviceCredentials())) { string outputDir = @"C:\temp\"; //Creates the Export Request ExportSolutionRequest exportRequest = new ExportSolutionRequest(); exportRequest.Managed = true; exportRequest.SolutionName = loginUser.SolutionName; ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest); //Handles the response byte[] exportXml = exportResponse.ExportSolutionFile; string filename = loginUser.SolutionName + "_" + DateToString() + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution Successfully Exported to {0}", outputDir + filename); } }
public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password) { if (org != null) { Uri orgServiceUri = null; orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]); //if (!string.IsNullOrEmpty(OrganisationServiceHostName)) //{ // UriBuilder builder = new UriBuilder(orgServiceUri); // builder.Host = OrganisationServiceHostName; // orgServiceUri = builder.Uri; //} IServiceConfiguration<IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(orgServiceUri); var creds = _credentialsProvider.GetCredentials(orgConfigInfo.AuthenticationType, domain, userName, password); var orgService = new OrganizationServiceProxy(orgConfigInfo, creds); orgService.Timeout = new TimeSpan(0, 5, 0); var req = new WhoAmIRequest(); var response = (WhoAmIResponse)orgService.Execute(req); Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId)); return orgService; } return null; }
/// <summary> /// Check for importlog records /// </summary> /// <param name="service"></param> /// <param name="importFileId"></param> public static void ReportErrors(OrganizationServiceProxy serviceProxy, Guid importFileId) { QueryByAttribute importLogQuery = new QueryByAttribute(); importLogQuery.EntityName = ImportLog.EntityLogicalName; importLogQuery.ColumnSet = new ColumnSet(true); importLogQuery.Attributes.Add("importfileid"); importLogQuery.Values.Add(new object[1]); importLogQuery.Values[0] = importFileId; EntityCollection importLogs = serviceProxy.RetrieveMultiple(importLogQuery); if (importLogs.Entities.Count > 0) { Console.WriteLine("Number of Failures: " + importLogs.Entities.Count.ToString()); Console.WriteLine("Sequence Number Error Number Description Column Header Column Value Line Number"); // Display errors. foreach (ImportLog log in importLogs.Entities) { Console.WriteLine( string.Format("Sequence Number: {0}\nError Number: {1}\nDescription: {2}\nColumn Header: {3}\nColumn Value: {4}\nLine Number: {5}", log.SequenceNumber.Value, log.ErrorNumber.Value, log.ErrorDescription, log.HeaderColumn, log.ColumnValue, log.LineNumber.Value)); } } }
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) { } }
public static IOrganizationService GetOrgService(bool admin = false, string callerId = null, string organization = null) { ClientCredentials credential = new ClientCredentials(); if (Globals.OrganizationServiceUrl.Contains("https")) { credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials; credential.UserName.UserName = Globals.DomainName + @"\" + Globals.AdminUserName; credential.UserName.Password = Globals.AdminPassword; } else { credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials; } OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(Globals.OrganizationServiceUrl), null, credential, null); if (!string.IsNullOrEmpty(callerId)) { orgServiceProxy.CallerId = new Guid(callerId); } return orgServiceProxy; ////credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials; ////credential.UserName.UserName = Globals.DomainName + @"\" + Globals.AdminUserName; ////credential.UserName.Password = Globals.AdminPassword; ////OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(Globals.OrganizationServiceUrl), null, credential, null); ////if (!string.IsNullOrEmpty(callerId)) ////{ //// orgServiceProxy.CallerId = new Guid(callerId); ////} ////return orgServiceProxy; }
public bool connect(string serviceURL, string domainName, string userName, string password) { try { Uri organizationUri = new Uri(serviceURL); Uri homeRealmUri = null; ClientCredentials credentials = new ClientCredentials(); // set default credentials for OrganizationService credentials.Windows.ClientCredential = new NetworkCredential(userName, password, domainName); // credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials; OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null); _service = (IOrganizationService)orgProxy; //to check connection with CRM getAttributeMax("campaign", "exchangerate"); return true; } catch (InvalidOperationException) { throw new connectionException("The URI provided cannot be resolved ( " + serviceURL + " )"); } catch (SecurityNegotiationException) { throw new connectionException("The authentication failed ! Please check the credentials provided."); } catch (Exception ex) { throw new connectionException(ex.Message); } }
/// <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 CrmVcardUpdateService(string userEmail) { if (string.IsNullOrWhiteSpace(userEmail)) { throw new ArgumentException("userEmail must be a valid email address", "userEmail"); } // Establish CRM connection var crmConnection = CrmConnection.Parse(CloudConfigurationManager.GetSetting("CrmConnectionString")); var serviceUri = new Uri(crmConnection.ServiceUri + "/XRMServices/2011/Organization.svc"); this.service = new OrganizationServiceProxy(serviceUri, null, crmConnection.ClientCredentials, null); // This statement is required to enable early-bound type support. this.service.EnableProxyTypes(Assembly.GetAssembly(typeof(SystemUser))); // Create context this.orgContext = new OrganizationServiceContext(this.service); // Retrieve the system user ID of the user to impersonate. this.impersonatedUser = (from user in this.orgContext.CreateQuery<SystemUser>() where user.InternalEMailAddress == userEmail select user).FirstOrDefault(); // We impersonate the user that has sent the email if (this.impersonatedUser == null) { throw new Exception("User not found in CRM"); } this.service.CallerId = this.impersonatedUser.Id; }
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; } }
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; }
/// <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; } }
public AppSendEmails(OrganizationServiceProxy service) { _service = service; _wfemailTemp = new ConsoleEmailTemplate(_service); WhoAmIRequest requst = new WhoAmIRequest(); WhoAmIResponse res = (WhoAmIResponse)_service.Execute(requst); _userid = res.UserId; }
public static IOrganizationService GetOrganisationService(string tenant, string siteUrl) { OrganizationServiceProxy sp; Uri connectionUri = new Uri(siteUrl + (siteUrl.EndsWith("/") ? "" : "/") + tenant + "/XRMServices/2011/Organization.svc"); ClientCredentials cc = new ClientCredentials(); cc.Windows.ClientCredential = (System.Net.NetworkCredential)System.Net.CredentialCache.DefaultCredentials; sp = new OrganizationServiceProxy(connectionUri, null, cc, null); return (IOrganizationService)sp; }
public static List<Guid> RetrieveSalespersons(OrganizationServiceProxy proxy, ref String ldapPath) { List<Guid> reps = new List<Guid>(); reps.Add(RetrieveSystemUser("nanderson", "Nancy", "Anderson", "Salesperson", proxy, ref ldapPath)); reps.Add(RetrieveSystemUser("dbristol", "David", "Bristol", "Salesperson", proxy, ref ldapPath)); return reps; }
public static List<Guid> RetrieveDelegates(OrganizationServiceProxy proxy, ref String ldapPath) { List<Guid> delegates = new List<Guid>(); delegates.Add(RetrieveSystemUser("dwilson", "Dan", "Wilson", "Delegate", proxy, ref ldapPath)); delegates.Add(RetrieveSystemUser("canderson", "Christen", "Anderson", "Delegate", proxy, ref ldapPath)); return delegates; }
/// <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; } }
private Service(Guid controlID) { ClientCredentials clntCredentials = new ClientCredentials(); clntCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("hoanht", "cc50fd77f8", "ivg.vn"); Uri orgUri = new Uri("http://srv-hndev-sp201:5555/Crm2015/XRMServices/2011/Organization.svc"); OrganizationServiceProxy orgService = new OrganizationServiceProxy(orgUri, null, clntCredentials, null); _organizationService = (IOrganizationService)orgService; _controlID = controlID; }
/// <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> /// 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; } }
private static void QueryForSOPSetting(OrganizationServiceProxy proxy, out EntityCollection organizationSettings, out bool IsSOPIntegrationEnabled) { QueryExpression query = new QueryExpression() { EntityName = "organization", ColumnSet = new ColumnSet(true), }; organizationSettings = proxy.RetrieveMultiple(query); IsSOPIntegrationEnabled = organizationSettings.Entities[0].GetAttributeValue<Boolean>("issopintegrationenabled"); }
/// <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. /// 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; } }
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; }
public IOrganizationService crea_ServicioCRM() { bool esIFD = Convert.ToBoolean(this.IFD); ClientCredentials Credencial = new ClientCredentials(); if (esIFD) { Credencial.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials; Credencial.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; Credencial.UserName.UserName = CredencialDominio + @"\" + CredencialUsuario; Credencial.UserName.Password = CredencialContrasena; } else { System.Net.NetworkCredential credenciales = new System.Net.NetworkCredential(CredencialUsuario, CredencialContrasena, CredencialDominio); Credencial.Windows.ClientCredential = credenciales; } Uri HomeRealmUri; HomeRealmUri = null; if (http.Equals("http")) { if (TipoCRM == "OnLine") { CrmConnection conexion = CrmConnection.Parse("Url=https://" + CRMServidor + "; Username="******"; Password="******";"); int int_timeout = 0; if (int.TryParse(TimeOut, out int_timeout)) { conexion.Timeout = new TimeSpan(0, int_timeout, 0); } OrganizationService OService = new OrganizationService(conexion); return((IOrganizationService)OService); } else { Uri OrganizationUri = new Uri("http://" + CRMServidor + "/" + CRMOrganizationName + "/XRMServices/2011/Organization.svc"); OrganizationServiceProxy _serviceProxy; _serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credencial, null); //DESCOMENTAR //_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); return((IOrganizationService)_serviceProxy); } } else { if (CertificateValidation.Length > 0) { bool certificadoValidacion = Convert.ToBoolean(CertificateValidation); Uri OrganizationUri = new Uri("https://" + CRMServidor + "/XRMServices/2011/Organization.svc"); if (certificadoValidacion) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallBack); } else { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallBackTrue); } OrganizationServiceProxy _serviceProxy; _serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credencial, null); //DESCOMENTAR //_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); return((IOrganizationService)_serviceProxy); } else { return(null); } } }
//</snippetLabelQueryExpression0> #endregion Class Level Members /// <summary> /// This method connects to the Organization _service. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> public void Run(ServerConnection.Configuration serverConfig) { 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; //<snippetLabelQueryExpression1> _userId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId; _languageCode = RetrieveUserUILanguageCode(_userId); //</snippetLabelQueryExpression1> //<snippetEntityFilter> // An array SchemaName values for non-intersect, user-owned entities that should not be returned. String[] excludedEntities = { "WorkflowLog", "Template", "CustomerOpportunityRole", "Import", "UserQueryVisualization", "UserEntityInstanceData", "ImportLog", "RecurrenceRule", "QuoteClose", "UserForm", "SharePointDocumentLocation", "Queue", "DuplicateRule", "OpportunityClose", "Workflow", "RecurringAppointmentMaster", "CustomerRelationship", "Annotation", "SharePointSite", "ImportData", "ImportFile", "OrderClose", "Contract", "BulkOperation", "CampaignResponse", "Connection", "Report", "CampaignActivity", "UserEntityUISettings", "IncidentResolution", "GoalRollupQuery", "MailMergeTemplate", "Campaign", "PostFollow", "ImportMap", "Goal", "AsyncOperation", "ProcessSession", "UserQuery", "ActivityPointer", "List", "ServiceAppointment" }; //A filter expression to limit entities returned to non-intersect, user-owned entities not found in the list of excluded entities. MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And); EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false)); EntityFilter.Conditions.Add(new MetadataConditionExpression("OwnershipType", MetadataConditionOperator.Equals, OwnershipTypes.UserOwned)); EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities)); MetadataConditionExpression isVisibileInMobileTrue = new MetadataConditionExpression("IsVisibleInMobile", MetadataConditionOperator.Equals, true); EntityFilter.Conditions.Add(isVisibileInMobileTrue); //</snippetEntityFilter> //<snippetEntityProperties> //A properties expression to limit the properties to be included with entities MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression() { AllProperties = false }; EntityProperties.PropertyNames.AddRange(new string[] { "Attributes" }); //</snippetEntityProperties> //<snippetAttributeQueryExpression> //A condition expresson to return optionset attributes MetadataConditionExpression[] optionsetAttributeTypes = new MetadataConditionExpression[] { new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Picklist), new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State), new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status), new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Boolean) }; //A filter expression to apply the optionsetAttributeTypes condition expression MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.Or); AttributeFilter.Conditions.AddRange(optionsetAttributeTypes); //A Properties expression to limit the properties to be included with attributes MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression() { AllProperties = false }; AttributeProperties.PropertyNames.Add("OptionSet"); AttributeProperties.PropertyNames.Add("AttributeType"); //</snippetAttributeQueryExpression> //<snippetLabelQueryExpression3> //A label query expression to limit the labels returned to only those for the user's preferred language LabelQueryExpression labelQuery = new LabelQueryExpression(); labelQuery.FilterLanguages.Add(_languageCode); //</snippetLabelQueryExpression3> //<snippetInitialRequest> //An entity query expression to combine the filter expressions and property expressions for the query. EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Criteria = EntityFilter, Properties = EntityProperties, AttributeQuery = new AttributeQueryExpression() { Criteria = AttributeFilter, Properties = AttributeProperties }, LabelQuery = labelQuery }; //Retrieve the metadata for the query without a ClientVersionStamp RetrieveMetadataChangesResponse initialRequest = getMetadataChanges(entityQueryExpression, null, DeletedMetadataFilters.OptionSet); //</snippetInitialRequest> //Add option labels to the cache and display the changes addOptionLabelsToCache(initialRequest.EntityMetadata, false); String ClientVersionStamp = initialRequest.ServerVersionStamp; Console.WriteLine("{0} option labels for {1} entities added to the cache.", _optionLabelList.Count, initialRequest.EntityMetadata.Count); Console.WriteLine(""); Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp); Console.WriteLine(""); //Add new custom entity with optionset Console.WriteLine("Adding a custom entity named {0} with a custom optionset attribute named : {1}", _customEntitySchemaName, _customAttributeSchemaName); Console.WriteLine(""); addCustomEntityWithOptionSet(); //Publishing isn't necessary when adding a custom entity //Add new option labels to the cache and display the results ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp); Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp); Console.WriteLine(""); //Add a new option to the custom optionset in the custom entity and publish the custom entity Console.WriteLine("Adding an additional option to the {0} attribute options.", _customAttributeSchemaName); Console.WriteLine(""); addOptionToCustomEntityOptionSet(); //It is necessary to publish updates to metadata. Create and Delete operations are published automatically. publishUpdatedEntity(); //Add the new option label to the cache and display the results ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp); Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Current Options: {0}", _optionLabelList.Count.ToString()); Console.WriteLine(""); //Delete the custom entity Console.WriteLine(""); Console.WriteLine("Deleting the {0} custom entity", _customEntitySchemaName); Console.WriteLine(""); deleteCustomEntityWithOptionSet(); //Publishing isn't necessary when deleting a custom entity //Retrieve metadata changes to remove option labels from deleted attributes and display the results ClientVersionStamp = updateOptionLabelList(entityQueryExpression, ClientVersionStamp); Console.WriteLine("ClientVersionStamp: {0}", ClientVersionStamp); 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; } }
/// <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(); #region How to dump attribute info RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = true }; // Retrieve the MetaData. RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("AttributePicklistValues.xml"); using (StreamWriter sw = new StreamWriter(filename)) { // Create Xml Writer. XmlTextWriter metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { if (currentEntity.IsIntersect.Value == false) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); if (currentEntity.IsCustomizable.Value == true) { metadataWriter.WriteElementString("IsCustomizable", "yes"); } else { metadataWriter.WriteElementString("IsCustomizable", "no"); } #region Attributes // Write Entity's Attributes. metadataWriter.WriteStartElement("Attributes"); foreach (AttributeMetadata currentAttribute in currentEntity.Attributes) { // Only write out main attributes. if (currentAttribute.AttributeOf == null) { // Start Attribute Node metadataWriter.WriteStartElement("Attribute"); // Write Attribute's information. metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName); metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString()); if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata)) { PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute; // Writes the picklist's options metadataWriter.WriteStartElement("Options"); // Writes the attributes of each picklist option for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++) { metadataWriter.WriteStartElement("Option"); metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString()); metadataWriter.WriteEndElement(); } metadataWriter.WriteEndElement(); } else if (currentAttribute.GetType() == typeof(StateAttributeMetadata)) { StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute; // Writes the picklist's options metadataWriter.WriteStartElement("Options"); // Writes the attributes of each picklist option for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++) { metadataWriter.WriteStartElement("Option"); metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString()); metadataWriter.WriteEndElement(); } metadataWriter.WriteEndElement(); } else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata)) { StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute; // Writes the picklist's options metadataWriter.WriteStartElement("Options"); // Writes the attributes of each picklist option for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++) { metadataWriter.WriteStartElement("Option"); metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString()); metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString()); if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata) { metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString()); } metadataWriter.WriteEndElement(); } metadataWriter.WriteEndElement(); } // End Attribute Node metadataWriter.WriteEndElement(); } } // End Attributes Node metadataWriter.WriteEndElement(); #endregion // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } #endregion How to dump attribute info Console.WriteLine("Done."); //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 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 = 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(); // Create the ServiceContext object that will generate // the IQueryable collections for LINQ calls. ServiceContext svcContext = new ServiceContext(_service); #region SQL Query Translated to LINQ // Build the following SQL query using QueryExpression: // // SELECT contact.fullname, contact.address1_telephone1 // FROM contact // LEFT OUTER JOIN account // ON contact.parentcustomerid = account.accountid // AND // account.name = 'Litware, Inc.' // WHERE (contact.address1_stateorprovince = 'WA' // AND // contact.address1_city in ('Redmond', 'Bellevue', 'Kirkland', 'Seattle') // AND // contact.address1_telephone1 like '(206)%' // OR // contact.address1_telephone1 like '(425)%' // AND // contact.emailaddress1 Not NULL // ) //<snippetRetrieveMultipleConditionOperatorsLinq1> var contacts = (from c in svcContext.ContactSet join a in svcContext.AccountSet on c.ParentCustomerId.Id equals a.AccountId where (a.Name == "Litware, Inc.") where (c.Address1_StateOrProvince == "WA" && (c.Address1_Telephone1.StartsWith("(206)") || c.Address1_Telephone1.StartsWith("(425)")) && (c.Address1_City == "Redmond" || c.Address1_City == "Bellevue" || c.Address1_City == "Kirkland" || c.Address1_City == "Seattle") && (c.EMailAddress1 != null && c.EMailAddress1 != "")) select new Contact { ContactId = c.ContactId, FirstName = c.FirstName, LastName = c.LastName, Address1_Telephone1 = c.Address1_Telephone1 }); // Display the results. Console.WriteLine("List all contacts matching specified parameters"); Console.WriteLine("==============================================="); foreach (Contact contact in contacts) { Console.WriteLine("Contact ID: {0}", contact.Id); Console.WriteLine("Contact Name: {0}", contact.FullName); Console.WriteLine("Contact Phone: {0}", contact.Address1_Telephone1); } Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion //</snippetRetrieveMultipleConditionOperatorsLinq1> //OUTPUT: //List all contacts matching specified parameters //=============================================== //Contact ID: a263e139-63a3-e011-aea3-00155dba3818 //Contact Name: //Contact Phone: (206)555-5555 //Contact ID: a463e139-63a3-e011-aea3-00155dba3818 //Contact Name: //Contact Phone: (425)555-5555 //<End of Listing> 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; } }
public CRMInstance(OrganizationServiceProxy service) { Service = service; }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = _serviceProxy.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = _serviceProxy.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); //<snippetWorkingWithLeads1> // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); //</snippetWorkingWithLeads1> foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = _serviceProxy.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRecords(promptforDelete); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// create, retrieve, update, and delete operations are performed on a /// dialog process. /// </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 { //<snippetCRUDDialog1> // 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(); // Define an anonymous type to define the possible values for // workflow category var WorkflowCategory = new { Workflow = 0, Dialog = 1 }; // Instantiate a Workflow object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Workflow sampleDialog = new Workflow { Category = new OptionSetValue((int)WorkflowCategory.Dialog), Name = "Sample Dialog: Call Categorization", PrimaryEntity = PhoneCall.EntityLogicalName, //Language code for U.S. English LanguageCode = 1033, Xaml = File.ReadAllText(pathToXAML) }; // Create a dialog record. _dialogId = _serviceProxy.Create(sampleDialog); Console.Write("{0} created,", sampleDialog.Name); // Activate the dialog. SetStateRequest activateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue(2) }; _serviceProxy.Execute(activateRequest); Console.WriteLine(" and activated."); // Retrieve the dialog containing several of its attributes. ColumnSet cols = new ColumnSet("name", "statecode", "statuscode"); Workflow retrievedDialog = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, _dialogId, cols); Console.Write("Retrieved,"); // Update the dialog. // Deactivate the dialog before you can update it. SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue(1) }; _serviceProxy.Execute(deactivateRequest); // Retrieve the dialog record again to get the unpublished // instance in order to update. Workflow retrievedDialogDeactivated = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, _dialogId, cols); // Update the dialog. retrievedDialogDeactivated.Name = "Updated Dialog: Call Categorization"; _serviceProxy.Update(retrievedDialogDeactivated); Console.Write(" updated,"); // Activate the dialog. SetStateRequest updateActivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue(2) }; _serviceProxy.Execute(updateActivateRequest); Console.WriteLine(" and activated again."); DeleteRequiredRecords(promptforDelete); } //</snippetCRUDDialog1> } // 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 QueryDisplayNames() { // Load the display Names MetadataQueryBuilder builder = new MetadataQueryBuilder(); List <string> entities = new List <string>(); List <string> attributes = new List <string>(); foreach (string entityLogicalName in EntityLookup.Keys) { entities.Add(entityLogicalName); EntityQuery entity = EntityLookup[entityLogicalName]; foreach (string attributeLogicalName in entity.Attributes.Keys) { AttributeQuery attribute = entity.Attributes[attributeLogicalName]; string fieldName = attribute.LogicalName; int pos = fieldName.IndexOf('.'); if (entity.AliasName != null && pos > -1) { fieldName = fieldName.Substr(pos); } attributes.Add(fieldName); } } builder.AddEntities(entities, new List <string>("Attributes", "DisplayName", "DisplayCollectionName")); builder.AddAttributes(attributes, new List <string>("DisplayName", "AttributeType", "IsPrimaryName")); builder.SetLanguage((int)Script.Literal("USER_LANGUAGE_CODE")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(builder.Request); // Update the display names // TODO: Add the lookup relationship in brackets for alias entitie foreach (EntityMetadata entityMetadata in response.EntityMetadata) { // Get the entity EntityQuery entityQuery = EntityLookup[entityMetadata.LogicalName]; entityQuery.DisplayName = entityMetadata.DisplayName.UserLocalizedLabel.Label; entityQuery.DisplayCollectionName = entityMetadata.DisplayCollectionName.UserLocalizedLabel.Label; foreach (AttributeMetadata attribute in entityMetadata.Attributes) { if (entityQuery.Attributes.ContainsKey(attribute.LogicalName)) { // Set the type AttributeQuery attributeQuery = entityQuery.Attributes[attribute.LogicalName]; attributeQuery.AttributeType = attribute.AttributeType; switch (attribute.AttributeType) { case AttributeTypeCode.Lookup: case AttributeTypeCode.Picklist: case AttributeTypeCode.Customer: case AttributeTypeCode.Owner: case AttributeTypeCode.Status: case AttributeTypeCode.State: case AttributeTypeCode.Boolean_: LookupAttributes[attribute.LogicalName] = attributeQuery; break; } attributeQuery.IsPrimaryName = attribute.IsPrimaryName; // If the type is a lookup, then add the 'name' on to the end in the fetchxml // this is so that we search the text value and not the numeric/guid value foreach (Column col in attributeQuery.Columns) { col.Name = attribute.DisplayName.UserLocalizedLabel.Label; col.DataType = attribute.IsPrimaryName.Value ? "PrimaryNameLookup" : attribute.AttributeType.ToString(); } } } } }
public static List <Dynamics365State> GetStates(Dynamics365Entity entity, Dynamics365Connection connection) { ConnectionCache cache = new ConnectionCache(connection); string cacheKey = string.Format("GetStates:{0}", entity.LogicalName); List <Dynamics365State> states = (List <Dynamics365State>)cache[cacheKey]; if (states == null) { states = new List <Dynamics365State>(); RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = entity.LogicalName, EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = false }; using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy) { RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request); StateAttributeMetadata stateMetadata = (StateAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StateAttributeMetadata); if (stateMetadata != null) { foreach (StateOptionMetadata stateOption in stateMetadata.OptionSet.Options) { Dynamics365State state = new Dynamics365State() { Code = (int)stateOption.Value, Name = stateOption.Label.UserLocalizedLabel.Label, LogicalName = stateMetadata.LogicalName }; StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StatusAttributeMetadata); if (statusMetadata != null) { foreach (StatusOptionMetadata statusOption in statusMetadata.OptionSet.Options) { if (statusOption.State == state.Code) { Dynamics365Status status = new Dynamics365Status() { Code = (int)statusOption.Value, Name = statusOption.Label.UserLocalizedLabel.Label, LogicalName = statusMetadata.LogicalName }; state.Statuses.Add(status); } } //state.Statuses.Sort((status1, status2) => status1.Name.CompareTo(status2.Name)); } states.Add(state); } } } //states.Sort((state1, state2) => state1.Name.CompareTo(state2.Name)); cache[cacheKey] = states; } return(states); }
public static Guid RetrieveAUserWithoutAnyRoleAssigned(OrganizationServiceProxy proxy) { String ldapPath = String.Empty; return(RetrieveSystemUser("dpark", "Dan", "Park", "", proxy, ref ldapPath)); }
public static Guid RetrieveMarketingManager(OrganizationServiceProxy proxy, ref String ldapPath) { return(RetrieveSystemUser("ssmith", "Samantha", "Smith", "Marketing Manager", proxy, ref ldapPath)); }
public static Guid RetrieveMarketingManager(OrganizationServiceProxy proxy) { String ldapPath = String.Empty; return(RetrieveMarketingManager(proxy, ref ldapPath)); }
/// <summary> /// Create and configure the organization service proxy. /// Configure an existing queue's email property values. /// 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(); // Define some anonymous types to define the range // of possible queue property values. var IncomingEmailDeliveryMethods = new { None = 0, EmailRouter = 2, ForwardMailbox = 3 }; var IncomingEmailFilteringMethods = new { AllEmailMessages = 0, EmailMessagesInResponseToCrmEmail = 1, EmailMessagesFromCrmLeadsContactsAndAccounts = 2 }; var OutgoingEmailDeliveryMethods = new { None = 0, EmailRouter = 2 }; // Update a queue instance and set its email property values. Queue configureQueue = new Queue() { QueueId = _queueId, IncomingEmailDeliveryMethod = new OptionSetValue( IncomingEmailDeliveryMethods.EmailRouter), IncomingEmailFilteringMethod = new OptionSetValue( IncomingEmailFilteringMethods.EmailMessagesInResponseToCrmEmail), OutgoingEmailDeliveryMethod = new OptionSetValue( OutgoingEmailDeliveryMethods.None), // TODO: Update with appropriate address // for accessing the e-mail router. EMailAddress = "*****@*****.**", }; _serviceProxy.Update(configureQueue); Console.WriteLine("Configured the queue's email property values."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service. Afterwards a dynamic /// list is created and associated to the campaign and the campaign's activity. /// Then the dynamic list is copied to a static list and associated with the same /// campaign and campaign activity. Finally the sample distributes the campaign /// to both the dynamic and static lists. /// </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 { //<snippetMarketingAutomation1> // 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 Create Dynamic List // Create FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; //<snippetAddItemCampaign> // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = _serviceProxy.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. Campaign campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = _serviceProxy.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. AddItemCampaignRequest addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); //</snippetAddItemCampaign> //<snippetAddItemCampaignActivity> // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = _serviceProxy.Create(campaignActivity); // Add dynamic list to campaign activity. AddItemCampaignActivityRequest addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); //</snippetAddItemCampaignActivity> #endregion #region Associate static list to campaign //<snippetCopyDynamicListToStatic> // Copy the dynamic list to a static list. CopyDynamicListToStaticRequest copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; CopyDynamicListToStaticResponse copyResponse = (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); //</snippetCopyDynamicListToStatic> // Add the static list to the campaign. AddItemCampaignRequest addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. Fax fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list //<snippetDistributeCampaignActivity> // Distribute the campaign activity to the marketing lists. DistributeCampaignActivityRequest distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; _serviceProxy.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); //</snippetDistributeCampaignActivity> #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); var member = (from mb in orgContext.CreateQuery <List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; RetrieveMultipleRequest memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; RetrieveMultipleResponse memberResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #endregion Retrieve collection of entities from marketing list DeleteRequiredRecords(promptforDelete); } //</snippetMarketingAutomation1> } // 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 CrmConnection(OrganizationServiceProxy organizationService, string webApplicationUrl) { this.crmServiceClient = new CrmServiceClient(organizationService); this.WebApplicationUrl = webApplicationUrl; }
/// <summary> /// Create a global option set. /// Set the options for that option set. /// Create a new reference to that option set on an entity. /// Update the option set's properties. /// Check the global option set for dependencies. /// Delete the option set. /// </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(); //<snippetWorkwithGlobalOptionSets1> //<snippetWorkwithGlobalOptionSets2> #region How to create global option set // Define the request object and pass to the service. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest); //</snippetWorkwithGlobalOptionSets2> #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set //<snippetWorkwithGlobalOptionSets3> // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. CreateAttributeRequest createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; _serviceProxy.Execute(createRequest); //</snippetWorkwithGlobalOptionSets3> Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set //<snippetWorkwithGlobalOptionSets4> // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; _serviceProxy.Execute(updateOptionSetRequest); //Publish the OptionSet PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq1); //</snippetWorkwithGlobalOptionSets4> Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set //<snippetWorkwithGlobalOptionSets5> // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq2); //</snippetWorkwithGlobalOptionSets5> Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name //<snippetWorkwithGlobalOptionSets6> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); //</snippetWorkwithGlobalOptionSets6> #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist //<snippetWorkwithGlobalOptionSets7> // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; _serviceProxy.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq3); //</snippetWorkwithGlobalOptionSets7> Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set //<snippetWorkwithGlobalOptionSets8> // 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. OptionSetName = _globalOptionSetName, // 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); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq4); //</snippetWorkwithGlobalOptionSets8> Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets //<snippetWorkwithGlobalOptionSets9> // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } //</snippetWorkwithGlobalOptionSets9> #endregion How to retrieve all global option sets //</snippetWorkwithGlobalOptionSets1> 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 /// rollup field and rollup query are created. The rollup query is only /// associated with the child goal. Then a parent goal and child goal /// are created. The goals are both rolled up and their results are displayed. /// </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 { //<snippetUsingQueriesToTrackGoals1> // 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 revenue metric, setting the Amount Data Type to 'Money' // and the Metric Type to 'Amount'. Metric sampleMetric = new Metric() { Name = "Sample Revenue Metric", AmountDataType = new OptionSetValue(0), IsAmount = true, }; _metricId = _serviceProxy.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created revenue metric, "); #region Create RollupFields // Create RollupField which targets the actual totals. RollupField actual = new RollupField() { SourceEntity = SalesOrder.EntityLogicalName, SourceAttribute = "totalamount", GoalAttribute = "actualmoney", SourceState = 1, EntityForDateAttribute = SalesOrder.EntityLogicalName, DateAttribute = "datefulfilled", MetricId = sampleMetric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); #endregion #region Create the goal rollup query // The query locates sales orders in the first sales // representative's area (zip code: 60661) and with a value // greater than $1,000. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "First Example Goal Rollup Query", QueryEntityType = SalesOrder.EntityLogicalName, FetchXml = @"<fetch mapping=""logical"" version=""1.0""><entity name=""salesorder""><attribute name=""customerid"" /><attribute name=""name"" /><attribute name=""salesorderid"" /><attribute name=""statuscode"" /><attribute name=""totalamount"" /><order attribute=""name"" /><filter><condition attribute=""totalamount"" operator=""gt"" value=""1000"" /><condition attribute=""billto_postalcode"" operator=""eq"" value=""60661"" /></filter></entity></fetch>" }; _rollupQueryId = _serviceProxy.Create(goalRollupQuery); goalRollupQuery.Id = _rollupQueryId; Console.Write("created rollup query."); Console.WriteLine(); #endregion #region Create two goals: one parent and one child goal // Create the parent goal. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, TargetMoney = new Money(1000.0M), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _parentGoalId = _serviceProxy.Create(parentGoal); parentGoal.Id = _parentGoalId; Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Create the child goal. Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(1000.0M), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = goalRollupQuery.ToEntityReference(), GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _firstChildGoalId = _serviceProxy.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion // Calculate roll-up of goals. // Note: Recalculate can be run against any goal in the tree to cause // a rollup of the whole tree. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = parentGoal.ToEntityReference() }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayMoney QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodaymoney") }; EntityCollection ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", temp.ComputedTargetAsOfTodayMoney.Value); Console.WriteLine("<End of Listing>"); } DeleteRequiredRecords(promptforDelete); } //</snippetUsingQueriesToTrackGoals1> } // 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 { // 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(); ServiceContext svcContext = new ServiceContext(_service); // 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. //<snippetUseLinqQuery1> int pageSize = 5; var accountsByPage = (from a in svcContext.AccountSet select new Account { Name = a.Name, }); System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts"); System.Console.WriteLine("======================================"); foreach (var a in accountsByPage.Skip(2 * pageSize).Take(pageSize)) { System.Console.WriteLine(a.Name); } //</snippetUseLinqQuery1> 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. //<snippetUseLinqQuery2> var orderedAccounts = from a in svcContext.AccountSet orderby a.Name select new Account { Name = a.Name, }; System.Console.WriteLine("Display accounts ordered by name"); System.Console.WriteLine("================================"); foreach (var a in orderedAccounts) { System.Console.WriteLine(a.Name); } //</snippetUseLinqQuery2> 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. //<snippetUseLinqQuery3> var query = from c in svcContext.ContactSet join a in svcContext.AccountSet on c.ContactId equals a.PrimaryContactId.Id where c.LastName == "Wilcox" || c.LastName == "Andrews" where a.Address1_Telephone1.Contains("(206)") || a.Address1_Telephone1.Contains("(425)") select new { Contact = new Contact { FirstName = c.FirstName, LastName = c.LastName, }, Account = new Account { 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); } //</snippetUseLinqQuery3> 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. //<snippetUseLinqQuery4> var complexQuery = from c in svcContext.ContactSet join a in svcContext.AccountSet on c.ContactId equals a.PrimaryContactId.Id join l in svcContext.CreateQuery <Lead>() on a.OriginatingLeadId.Id equals l.LeadId where c.LastName == "Wilcox" || c.LastName == "Andrews" where a.Address1_Telephone1.Contains("(206)") || a.Address1_Telephone1.Contains("(425)") select new { Contact = new Contact { FirstName = c.FirstName, LastName = c.LastName, }, Account = new Account { Address1_Telephone1 = a.Address1_Telephone1 }, Lead = new Lead { 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); } //</snippetUseLinqQuery4> 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> //Retrieve a related Task for a Contact //Shows requirement that LoadProperty must be used to access the related record. //<snippetUseLinqQuery5> Contact benAndrews = svcContext.ContactSet.Where(c => c.FullName == "Ben Andrews").FirstOrDefault(); if (benAndrews != null) { //benAndrews.Contact_Tasks is null until LoadProperty is used. svcContext.LoadProperty(benAndrews, "Contact_Tasks"); Task benAndrewsFirstTask = benAndrews.Contact_Tasks.FirstOrDefault(); if (benAndrewsFirstTask != null) { Console.WriteLine("Ben Andrews first task with Subject: '{0}' retrieved.", benAndrewsFirstTask.Subject); } } //</snippetUseLinqQuery5> 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 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // 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> /// Helper method to create an active directory account /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns>Return true if new account is created or return false if account already exist.</returns> public static Boolean CreateADAccount(String userName, String firstName, String lastName, OrganizationServiceProxy serviceProxy, ref String ldapPath) { // Check to make sure this is not Microsoft Dynamics CRM Online. if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId || serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation) { throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user " + "\nin your Microsoft Dynamics CRM Online organization.", firstName, lastName)); } if (String.IsNullOrEmpty(ldapPath)) { ldapPath = SystemUserProvider.ConsolePromptForLDAPPath(); } // Create an Active Directory user account if it doesn't exist already. if (String.IsNullOrEmpty(ldapPath)) { throw new ArgumentException("Required argument ldapPath was not provided."); } DirectoryEntry directoryEntry; if (serviceProxy.ClientCredentials.Windows != null) { string LUser = serviceProxy.ClientCredentials.Windows.ClientCredential.UserName; string LPwd = serviceProxy.ClientCredentials.Windows.ClientCredential.Password; directoryEntry = new DirectoryEntry(ldapPath, LUser, LPwd); } else { directoryEntry = new DirectoryEntry(ldapPath); } DirectoryEntry userADAccount = null; // Search AD to see if the user already exists. DirectorySearcher search = new DirectorySearcher(directoryEntry); search.Filter = String.Format("(sAMAccountName={0})", userName); search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("givenname"); search.PropertiesToLoad.Add("sn"); search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); Boolean accountCreated = false; if (result == null) { // Create the Active Directory account. userADAccount = directoryEntry.Children.Add("CN= " + userName, "user"); userADAccount.Properties["samAccountName"].Value = userName; userADAccount.Properties["givenName"].Value = firstName; userADAccount.Properties["sn"].Value = lastName; userADAccount.CommitChanges(); accountCreated = true; } else { // Use the existing AD account. userADAccount = result.GetDirectoryEntry(); accountCreated = false; } // Set the password for the account. String password = "******"; userADAccount.Invoke("SetPassword", new object[] { password }); userADAccount.CommitChanges(); directoryEntry.Close(); userADAccount.Close(); // Enable the newly created Active Directory account. userADAccount.Properties["userAccountControl"].Value = (int)userADAccount.Properties["userAccountControl"].Value & ~0x2; userADAccount.CommitChanges(); // Wait 10 seconds for the AD account to propagate. Thread.Sleep(10000); return(accountCreated); }
/// <summary> /// Main entry point for the application. /// </summary> /// <param name="CmdArgs">Entities to place on the diagram</param> public static int Main(string[] args) { String filename = String.Empty; VisioApi.Application application; VisioApi.Document document; DiagramBuilder builder = new DiagramBuilder(); try { // Obtain the target organization's Web address and client logon // credentials from the user. ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration config = serverConnect.GetServerConfiguration(); // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(config)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Load Visio and create a new document. application = new VisioApi.Application(); application.Visible = false; // Not showing the UI increases rendering speed builder.VersionName = application.Version; document = application.Documents.Add(String.Empty); builder._application = application; builder._document = document; // Load the metadata. Console.WriteLine("Loading Metadata..."); RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships, RetrieveAsIfPublished = true, }; RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request); builder._metadataResponse = response; // Diagram all entities if given no command-line parameters, otherwise diagram // those entered as command-line parameters. if (args.Length < 1) { ArrayList entities = new ArrayList(); foreach (EntityMetadata entity in response.EntityMetadata) { // Only draw an entity if it does not exist in the excluded entity table. if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode())) { entities.Add(entity.LogicalName); } else { Console.WriteLine("Excluding entity: {0}", entity.LogicalName); } } builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities"); filename = "AllEntities.vsd"; } else { builder.BuildDiagram(args, String.Join(", ", args)); filename = String.Concat(args[0], ".vsd"); } // Save the diagram in the current directory using the name of the first // entity argument or "AllEntities" if none were given. Close the Visio application. document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename); application.Quit(); } } 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("Plugin Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "No Inner Fault" : "Has 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 ? "No Inner Fault" : ex.InnerException.Message); } 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("Plugin Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } } // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. finally { //Console.WriteLine("Rendering complete."); Console.WriteLine("Rendering complete. Press any key to continue."); Console.ReadLine(); } return(0); }
public static Guid RetrieveSalesManager(OrganizationServiceProxy proxy, ref String ldapPath) { return(RetrieveSystemUser("kcook", "Kevin", "Cook", "Sales Manager", proxy, ref ldapPath)); }
public static void SetUp() { account = new Entity("account"); account.SetAttributeValue("name", "Unit Test " + DateTime.Now.ToLocaleTimeString()); account.Id = OrganizationServiceProxy.Create(account).ToString(); }
/// <summary> /// Retrieves the requested SystemUser record. If the record does not exist, a new /// Microsoft Dynamics CRM SystemUser record is created and an associated Active /// Directory account is created, if it doesn't currently exist. /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="roleStr">The string representing the Microsoft Dynamics CRM security /// role for the user</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns></returns> public static Guid RetrieveSystemUser(String userName, String firstName, String lastName, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { String domain; Guid userId = Guid.Empty; if (serviceProxy == null) { throw new ArgumentNullException("serviceProxy"); } if (String.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException("UserName"); } if (String.IsNullOrWhiteSpace(firstName)) { throw new ArgumentNullException("FirstName"); } if (String.IsNullOrWhiteSpace(lastName)) { throw new ArgumentNullException("LastName"); } // Obtain the current user's information. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)serviceProxy.Execute(who); Guid currentUserId = whoResp.UserId; SystemUser currentUser = serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity <SystemUser>(); // Extract the domain and create the LDAP object. String[] userPath = currentUser.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) { domain = userPath[0] + "\\"; } else { domain = String.Empty; } SystemUser existingUser = GetUserIdIfExist(serviceProxy, domain, userName, firstName, lastName); if (existingUser != null) { userId = existingUser.SystemUserId.Value; if (!String.IsNullOrWhiteSpace(roleStr)) { // Check to make sure the user is assigned the correct role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Associate the user with the role when needed. if (!UserInRole(serviceProxy, userId, role.Id)) { AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id) }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } } } else { // Create the system user in Microsoft Dynamics CRM if the user doesn't // already exist. userId = CreateSystemUser(userName, firstName, lastName, domain, roleStr, serviceProxy, ref ldapPath); } return(userId); }
private void InstantiateService() { try { if (SelectedConfiguration == null) { throw new Exception("Please choose a configuration."); } //Get the Password string password = String.Empty; PasswordWindow pw = new PasswordWindow(); pw.Owner = Application.Current.MainWindow; bool?submitted = pw.ShowDialog(); if (submitted.Value) { password = pw.GetPassword(); } else { ErrorWindow needPassword = new ErrorWindow("You need to supply a Password and Submit. Try again."); needPassword.Owner = Application.Current.MainWindow; needPassword.ShowDialog(); return; } _serverConnect = new ConsolelessServerConnection(); ConsolelessServerConnection.Configuration _config = new ConsolelessServerConnection.Configuration(); _config = _serverConnect.GetServerConfiguration( SelectedConfiguration.Attribute("server").Value, SelectedConfiguration.Attribute("orgName").Value, SelectedConfiguration.Attribute("userName").Value, password, SelectedConfiguration.Attribute("domain").Value); _serviceProxy = new OrganizationServiceProxy(_config.OrganizationUri, _config.HomeRealmUri, _config.Credentials, _config.DeviceCredentials); // This statement is required to enable early-bound type support. _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors .Add(new ProxyTypesBehavior()); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_serviceProxy); //Set the ActiveConnection ActiveConfiguration = SelectedConfiguration; //If all worked, retrieve the solutions. LoadSolutions(); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.AppendLine(e.Message); sb.AppendLine(); sb.AppendLine("Please fix the Connection information and try again."); ErrorWindow errorWindow = new ErrorWindow(sb.ToString()); errorWindow.Owner = Application.Current.MainWindow; var x = errorWindow.ShowDialog(); } }
public static void Teardown() { // Tidy Up OrganizationServiceProxy.Delete_(account.LogicalName, new Guid(account.Id)); }
/// <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(); //<snippetStateModelTransitions.run> 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(""); } //</snippetStateModelTransitions.run> } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // 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; } }
public static Guid RetrieveVPSales(OrganizationServiceProxy proxy, ref String ldapPath) { return(RetrieveSystemUser("mtucker", "Michael", "Tucker", "Vice President of Sales", proxy, ref ldapPath)); }
/// <summary> /// This method first connects to the Organization service. Afterwards, the /// sample creates a goal and child goals for a particular fiscal period. /// Stretched targets are tracked as well. /// </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 { //<snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1> // 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(); #region Create goal metric // Create the metric, setting the Metric Type to 'Count' and enabling // stretch tracking. Metric metric = new Metric() { Name = "Sample Count Metric", IsAmount = false, IsStretchTracked = true }; _metricId = _serviceProxy.Create(metric); metric.Id = _metricId; Console.Write("Created count metric, "); #endregion #region Create RollupFields // Create RollupField which targets completed (received) phone calls. RollupField actual = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "actualinteger", SourceState = 1, SourceStatus = 4, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "actualend", MetricId = metric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created completed phone call RollupField, "); #endregion #region Create the goal rollup queries // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the length property to be greater than 1,000 // chars and will cause an exception. // The following query locates closed incoming phone calls. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); goalRollupQuery.Id = _rollupQueryIds[0]; // The following query locates closed outgoing phone calls. GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery() { Name = "Example Goal Rollup Query", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery2)); goalRollupQuery2.Id = _rollupQueryIds[1]; Console.Write("created rollup queries for phone calls.\n"); Console.WriteLine(); #endregion #region Create goals // Determine current fiscal period and year. // Note: This sample assumes quarterly fiscal periods. DateTime date = DateTime.Now; int quarterNumber = (date.Month - 1) / 3 + 1; int yearNumber = date.Year; // Create three goals: one parent goal and two child goals. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 8, StretchTargetInteger = 10, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName } }; _parentGoalId = _serviceProxy.Create(parentGoal); parentGoal.Id = _parentGoalId; Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", parentGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", parentGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", parentGoal.FiscalYear.Value); Console.WriteLine("<End of Listing>"); Console.WriteLine(); Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 5, StretchTargetInteger = 6, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference() }; _firstChildGoalId = _serviceProxy.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", firstChildGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", firstChildGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", firstChildGoal.FiscalYear.Value); Console.WriteLine(); Goal secondChildGoal = new Goal() { Title = "Second Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 3, StretchTargetInteger = 4, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[1], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollupQueryActualIntegerId = goalRollupQuery2.ToEntityReference() }; _secondChildGoalId = _serviceProxy.Create(secondChildGoal); Console.WriteLine("Second child goal"); Console.WriteLine("-----------------"); Console.WriteLine("Target: {0}", secondChildGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", secondChildGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", secondChildGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", secondChildGoal.FiscalYear.Value); Console.WriteLine(); #endregion #region Calculate rollup and display result // Calculate roll-up of goals. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId) }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayInteger QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodayinteger") }; EntityCollection ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage: {0}", temp.Percentage); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayInteger: {0}", temp.ComputedTargetAsOfTodayInteger.Value); Console.WriteLine("<End of Listing>"); } #endregion DeleteRequiredRecords(promptforDelete); } //</snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1> } // 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; } }