Hi saadzag,
I do not have the option to upload files through here.
Below is all the code in my .cs file used in the plugin.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using Arise.CRM.Plugins.Helpers;
using log4net;
namespace Arise.CRM.Plugins
{
public class MarketingListMemberUpload : IPlugin
{
IOrganizationService crmService;
string moduleName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name;
private readonly ILog logger = LogManager.GetLogger(typeof(MarketingListMemberUpload));
// Obtain the execution context from the service provider.
IPluginExecutionContext context;
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory;
//retrieve user record
IOrganizationService service;
public void Execute(IServiceProvider serviceProvider)
{
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
crmService = serviceFactory.CreateOrganizationService(context.UserId);
service = serviceFactory.CreateOrganizationService(context.UserId);
CommonMethods.setLogger(logger, crmService);
string uploadMessage = "";
if (context.MessageName.ToLower() != "create")
{
logger.Info("Plugin:" + moduleName + ": No Create MessageName: MessageName is " + context.MessageName);
return;
}
if (context.PrimaryEntityName.ToLower() != "arise_marketinglistupload")
{
logger.Info("Plugin:" + moduleName + ": No list Primary Entity: Primary Entity is " + context.PrimaryEntityName);
return;
}
try
{
uploadMessage = UploadMarketingListMembers();
if (uploadMessage.Length > 0)
throw new InvalidPluginExecutionException("An error occurred in the plug-in: " + uploadMessage);
}
catch (Exception e)
{
logger.Error("An error occurred in the plug-in: " + e.Message + ". " + ". " + uploadMessage);
throw new InvalidPluginExecutionException("An error occurred in the plug-in: " + e.Message + ". " + uploadMessage);
}
logger.Debug("Plugin: " + moduleName + " (" + context.MessageName + ") - End Execution");
}
private string UploadMarketingListMembers()
{
StringBuilder errormsg = new StringBuilder(1024);
Entity entityPost = (Entity)context.PostEntityImages["PostImage"];
Guid listId = new Guid();
if (entityPost == null)
{
logger.Debug("Entity not found.");
return "Entity not found.";
}
if (entityPost.Attributes.Contains("arise_linkedlist"))
{
listId = ((EntityReference)entityPost["arise_linkedlist"]).Id;
}
else
{
logger.Debug("List Id not retrieved.");
appendErrorLog(entityPost, "List Id not retrieved.");
return "List Id not retrieved.";
}
if (ProcessUpload(listId))
{
try
{
#region Upload
string fileDataBase64 = string.Empty;
string memberList = string.Empty;
string uploadFileName = String.Empty;
// check if notes are available
QueryExpression qe = new QueryExpression("annotation");
qe.ColumnSet = new ColumnSet("documentbody", "filename", "mimetype");
qe.Criteria.AddCondition("objectid", ConditionOperator.Equal, listId);
qe.Criteria.AddCondition("documentbody", ConditionOperator.NotNull);
DataCollection<Entity> notes = crmService.RetrieveMultiple(qe).Entities;
//Can upload members from multiple csv files
foreach (var note in notes)
{
//Get the most recent attachment
fileDataBase64 = note["documentbody"].ToString();
uploadFileName = note.Attributes["filename"].ToString();
logger.Info("Plugin:" + moduleName + "Uploaded File " + note.Attributes["filename"] + " with mime type " + note.Attributes["mimetype"]);
if (!string.IsNullOrEmpty(fileDataBase64))
{
//Make sure the file is a csv file, otherwise ignore
if (uploadFileName.Contains(".csv"))
{
// decode base64 string
byte[] fileContent = Convert.FromBase64String(fileDataBase64);
memberList = Encoding.UTF8.GetString(fileContent);
string[] memberString = memberList.Split('\n');
List<Guid> membersToAdd = new List<Guid>();
try
{
foreach (string member in memberString)
{
if (!string.IsNullOrEmpty(member))
{
// remove starting and ending double quotes.
string tempMember = member.Trim();
tempMember = tempMember.Trim('"');
string[] memberAttributes = tempMember.Split(',');
logger.Debug("Validating CSP " + memberAttributes[0].ToString());
Entity csp = GetCSP(memberAttributes[0].ToString());
if (csp != null)
{
//Validate that the CSP is not already assigned to this marketing list (avoid duplicates)
if (!DuplicateMember(csp.Id, listId))
{
logger.Debug("Adding validated CSP " + memberAttributes[0].ToString());
membersToAdd.Add(csp.Id);
}
else
{
//Log duplicate CSP
errormsg.AppendFormat("CSP {0} was not uploaded. They are already linked to this Marketing List. \n", memberAttributes[0].ToString());
}
}
else
{
//Log CSP not found in system
errormsg.AppendFormat("CSP {0} was not uploaded. A CSP record was not found for them. \n", memberAttributes[0].ToString());
}
}
}
// Create and Execute the request object to add the members.
if (membersToAdd.Count > 0)
{
var addMemberListReq = new AddListMembersListRequest
{
MemberIds = membersToAdd.ToArray(),
ListId = listId
};
service.Execute(addMemberListReq);
}
}
catch (Exception ex)
{
logger.Debug("An error occurred while trying to add a Marketing List Member: " + ex.Message);
appendErrorLog(entityPost, "An error occurred while trying to add a Marketing List Member: " + ex.Message);
return "An error occurred while trying to add a Marketing List Member: " + ex.Message;
}
}
else
{
errormsg.AppendFormat("File {0} was not uploaded because it is not a csv type file. \n", uploadFileName);
}
}
}
//Update the marketing list to set the failures logged and the uploadcompleted flag
Entity uploadRecord = new Entity(entityPost.LogicalName);
uploadRecord["arise_marketinglistuploadid"] = uploadRecord.Id = entityPost.Id;
uploadRecord["arise_uploadfailurelog"] = CommonMethods.Truncate(errormsg.ToString(), 2000);
uploadRecord["arise_uploadcompleted"] = true;
crmService.Update(uploadRecord);
#endregion
}
catch (Exception ex)
{
logger.Debug("An error occurred during the upload process of Marketing List Members: " + ex.Message);
appendErrorLog(entityPost, "An error occurred during the upload process of Marketing List Members: " + ex.Message);
return "An error occurred during the upload process of Marketing List Members: " + ex.Message;
}
}
else
{
logger.Debug("Upload did not process. No async process found.");
appendErrorLog(entityPost, "Upload did not process. No async process found.");
}
return "";
}
private bool ProcessUpload(Guid listid)
{
try
{
string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='arise_marketinglistupload'><attribute name='arise_marketinglistuploadid' /><filter type='and'><condition attribute='arise_uploadmembers' operator='eq' value='1' /></filter><filter type='and'><condition attribute='arise_uploadcompleted' operator='eq' value='0' /></filter><filter type='and'><condition attribute='arise_linkedlist' operator='eq' value='{0}' /></filter></entity></fetch>", listid);
EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));
if (results != null && results.Entities.Count > 0)
return true;
return false;
}
catch (Exception ex)
{
logger.Debug("An error occurred while verifying if an upload can be done: " + ex.Message);
return false;
}
}
private Entity GetCSP(string cspid)
{
string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='contact'><attribute name='fullname' /><attribute name='new_acpidnocomma' /><attribute name='contactid' /><order attribute='fullname' descending='false' /><filter type='and'><condition attribute='new_acpidnocomma' operator='eq' value='{0}' /></filter></entity></fetch>", cspid);
EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));
if (results != null && results.Entities.Count > 0)
return results.Entities[0];
else
return null;
}
private bool DuplicateMember(Guid contactid, Guid listid)
{
string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='listmember'><attribute name='listid' /><attribute name='entityid' /><attribute name='listmemberid' /><filter type='and'><condition attribute='entityid' operator='eq' value='{0}' /></filter><filter type='and'><condition attribute='listid' operator='eq' value='{1}' /></filter></entity></fetch>", contactid, listid);
EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));
if (results != null && results.Entities.Count > 0)
return true;
return false;
}
private void appendErrorLog(Entity entityPost, string ErrorMessage)
{
Entity selfEntity = new Entity(entityPost.LogicalName);
selfEntity["arise_marketinglistuploadid"] = entityPost.Id;
selfEntity["arise_uploadfailurelog"] = CommonMethods.Truncate(ErrorMessage, 2000);
selfEntity["arise_uploadmembers"] = false;
selfEntity["arise_uploadcompleted"] = false;
crmService.Update(selfEntity);
}
}
}