In my scenario i have to create new lead in creation of email. The email contain one Xml attachment named enquiry. That attachment have some standard tags. I have to read the xml tag and its values.Based on the values i have to create a new lead record. I did this scenario using the following code:
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Xrm;
using System.Xml;
using System.IO;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace OPS.Lead.Create
{
public class GenerateLead : IPlugin
{
XmlDocument doc = new XmlDocument();
IOrganizationService service;
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
try
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.ContainsKey("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = context.InputParameters["Target"] as Entity;
if (entity.LogicalName != "email")
return;
Email email = entity.ToEntity<Email>();
string to = string.Empty;
ColumnSet col = new ColumnSet("to", "from");
entity = service.Retrieve(entity.LogicalName, entity.Id, col);
Guid partyId = new Guid();
EntityCollection Recipients = entity.GetAttributeValue<EntityCollection>("to");
foreach (var party in Recipients.Entities)
{
partyId = party.GetAttributeValue<EntityReference>("partyid").Id;
}
ColumnSet column = new ColumnSet("internalemailaddress");
Entity toRecipent = service.Retrieve(SystemUser.EntityLogicalName, partyId, column);
SystemUser contact = toRecipent.ToEntity<SystemUser>();
to = contact.InternalEMailAddress;
if (!(to == "enquiry@xyz.com"))
return;
try
{
//Retrieve all attachments associated with the email activity.
QueryExpression _attachmentQuery = new QueryExpression
{
EntityName = ActivityMimeAttachment.EntityLogicalName,
ColumnSet = new ColumnSet("activitymimeattachmentid"),
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "objectid",
Operator = ConditionOperator.Equal,
Values = {entity.Id}
},
new ConditionExpression
{
AttributeName = "objecttypecode",
Operator = ConditionOperator.Equal,
Values = {Email.EntityLogicalName}
}
}
}
};
EntityCollection results = service.RetrieveMultiple(_attachmentQuery);
if (results.Entities.Count == 0)
return;
string filename=string.Empty;
foreach (Entity ent in results.Entities)
{
ColumnSet colset = new ColumnSet();
colset.AllColumns = true;
ActivityMimeAttachment emailAttachment = (ActivityMimeAttachment)service.Retrieve("activitymimeattachment", ent.Id, colset);
filename= emailAttachment.FileName;
if (filename.Equals("enquiry"))
{
byte[] fileContent = Convert.FromBase64String(emailAttachment.Body);
using (MemoryStream ms = new MemoryStream(fileContent))
{
doc.Load(ms);
}
}
}
if (filename.Equals("enquiry"))
{
Entity newLead = new Entity("lead");
newLead["subject"] = entity.GetAttributeValue<string>("subject");
newLead["firstname"] = GetTagValue("Firstname");
newLead["lastname"] = GetTagValue("LastName");
newLead["emailaddress1"] = GetTagValue("EmailAddress");
newLead["companyname"] = GetTagValue("Companyname");
newLead["jobtitle"] = GetTagValue("Title");
newLead["mobilephone"] = GetTagValue("MobileNo");
newLead["address1_country"] = GetTagValue("Country");
string numberOfUsers = GetTagValue("Crmusers");
OptionSetValue crmUsers = new OptionSetValue(getOptionSetValue("ln_crmusers", numberOfUsers));
newLead["ln_crmusers"] = crmUsers;
string source = GetTagValue("Channel");
OptionSetValue leadSource = new OptionSetValue(getOptionSetValue("leadsourcecode", source));
newLead["leadsourcecode"] = leadSource;
string NoOfProduct = GetTagValue("ProductImplemented");
OptionSetValue productImplemented = new OptionSetValue(getOptionSetValue("ln_productimplemented", NoOfProduct));
newLead["ln_productimplemented"] = productImplemented;
string durationToBuy = GetTagValue("BuyPeriod");
OptionSetValue buyPeriod = new OptionSetValue(getOptionSetValue("ln_buyplan", durationToBuy));
newLead["ln_buyplan"] = buyPeriod;
string wantDemo = GetTagValue("Demo");
bool demo = false;
if (wantDemo.Equals("true"))
demo = true;
newLead["ln_demo"] = demo;
string broucher = GetTagValue("Brochure");
bool ln_broucher = false;
if (broucher.Equals("true"))
ln_broucher = true;
newLead["ln_brochure"] = ln_broucher;
newLead["description"] = GetTagValue("Comments");
newLead["ownerid"] = new EntityReference(SystemUser.EntityLogicalName, context.UserId);
service.Create(newLead);
}
else
return;
}
catch (FaultException<OrganizationServiceFault> ex)
{
tracingService.Trace("1"+ex.Message);
}
catch (Exception e)
{
tracingService.Trace("2"+e.Message);
}
}
}
catch (Exception exp)
{
tracingService.Trace("3"+exp.Message);
}
}
public string GetTagValue(string element)
{
string values = "";
foreach (XmlNode node in doc.GetElementsByTagName(element))
values = node.InnerText;
return values;
}
public int getOptionSetValue(string attributeName, string optionsetText)
{
int optionSetValue = 0;
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "lead";
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;
foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
{
if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
{
optionSetValue = optionMetadata.Value.Value;
return optionSetValue;
}
}
return optionSetValue;
}
}
}