using System; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query;
public class SamplePlugin : IPlugin { public void Execute(IServiceProvider serviceProvider) { //Get the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
//Get the service factory and create an organization service. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try { //Create a new account record. Entity account = new Entity("account"); account["name"] = "Sample Account"; Guid accountId = service.Create(account); Console.WriteLine("Created Account with ID: " + accountId);
//Retrieve the created account record. Entity retrievedAccount = service.Retrieve("account", accountId, new ColumnSet("name")); string accountName = retrievedAccount.GetAttributeValue<string>("name"); Console.WriteLine("Retrieved Account: " + accountName);
//Update the account record. retrievedAccount["name"] = "Updated Sample Account"; service.Update(retrievedAccount); Console.WriteLine("Updated Account: " + accountName);
//Create a new contact record. Entity contact = new Entity("contact"); contact["firstname"] = "John"; contact["lastname"] = "Doe"; Guid contactId = service.Create(contact); Console.WriteLine("Created Contact with ID: " + contactId);
//Associate the contact with the account using a relationship. service.Associate("account", accountId, new Relationship("contact_customer_accounts"), new EntityReferenceCollection() { new EntityReference("contact", contactId) }); Console.WriteLine("Associated Contact with Account");
//Assign the contact to a specific team using AssignRequest. AssignRequest assignRequest = new AssignRequest { Assignee = new EntityReference("team", new Guid("TEAM-GUID-HERE")), // Specify the team's GUID Target = new EntityReference("contact", contactId) }; service.Execute(assignRequest); Console.WriteLine("Assigned Contact to Team");
//Retrieve all contacts associated with the account. QueryExpression query = new QueryExpression("contact"); query.Criteria.AddCondition(new ConditionExpression("contactid", ConditionOperator.Equal, contactId)); EntityCollection associatedContacts = service.RetrieveMultiple(query); foreach (var associatedContact in associatedContacts.Entities) { Console.WriteLine("Associated Contact: " + associatedContact.GetAttributeValue<string>("fullname")); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } }
|