My code below is performing very poorly. I used the .Net StopWatch class to find out what piece of code was causing the slowness. This line seems to be the issue:
message.SendAndSaveCopy();
E.G batch of 20 emails: 1st email takes around 2 seconds to send and this time gradually increases until the 20th email, which takes up-to 18 seconds.
public int SendBulkMarketing(bool CheckDelivery)
{
int iCounter = 0;
DataTable dt = null;
try
{
DeliveryReportDAL myDeliveryReportDAL = new DeliveryReportDAL();
dt = myDeliveryReportDAL.GetListMessageToSend('E');
if (dt == null) return iCounter;
iCounter = dt.Rows.Count;
}
catch (Exception ex)
{
new Util().LogError(ex, "SMTP:: SendBulkMarketing 1st catch");
return 0;
}
if (iCounter > 0)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials(Account_UserName, Account_Password, Account_Domain);
service.Url = new Uri(Service_URL);
for (int I = 0; I < iCounter; ++I)
{
try
{
string myGUID = "{" + dt.Rows[I]["GUID"].ToString() + "}";
if (IsValidEmailAddress(dt.Rows[I]["OwnerEmail"].ToString()) == false)
{
DeliveryReportDAL myReport = new DeliveryReportDAL();
myReport.SaveSentStatus(myGUID, 'G', 3);
continue;
}
EmailMessage message = new EmailMessage(service);
message.Subject = dt.Rows[I]["TemplateSubject"].ToString();
message.Body = dt.Rows[I]["TemplateText"].ToString().Replace("\0", " ");
message.ToRecipients.Add(dt.Rows[I]["OwnerEmail"].ToString());
message.IsDeliveryReceiptRequested = true;
Guid myPropertySetId = new Guid(myGUID);
ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "blablabla", MapiPropertyType.String);
ServicePointManager.ServerCertificateValidationCallback =
delegate(object sender1,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{ return true; };
message.SendAndSaveCopy();
DeliveryReportDAL myReport1 = new DeliveryReportDAL();
myReport1.SaveSentStatus(dt.Rows[I]["GUID"].ToString(), 'G', 1);
}
catch (Exception ex)
{
new Util().LogError(ex, "SMTP:: SendBulkMarketing 2nd catch");
}
}
}
return iCounter;
}
I would greatly appreciate any help in improving the performance of my code.
This performance issue is now resolved.
It was a fundamental coding problem. The issue was caused by a separate method call which was being called (not shown in the code snippet provided) inside the for loop. It contains performance heavy functionality, but it did not need to be called inside the for loop.
Moving this performance heavy method call outside of the for loop resolved the issue.