Code Cleanup: Assemblies

This commit is contained in:
Rick Falkvinge
2014-12-04 23:55:03 +01:00
parent 93abb92c67
commit fa3b05da6f
458 changed files with 13969 additions and 13709 deletions
+210 -182
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
@@ -19,54 +20,66 @@ namespace Swarmops.Utility.BotCode
public class MailProcessor
{
#region Exception declarations
public class RemoveRecipientException : Exception
{
public RemoveRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public class IgnoreRecipientException : Exception
{
public IgnoreRecipientException (string message, Exception innerException)
public IgnoreRecipientException(string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class InvalidRecipientException : IgnoreRecipientException
{
public InvalidRecipientException (string message, Exception innerException)
public InvalidRecipientException(string message, Exception innerException)
: base(message, innerException)
{ }
}
public class RetryRecipientException : Exception
{
public RetryRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public class ReportAndRetryRecipientException : RetryRecipientException
{
public ReportAndRetryRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class InvalidSenderException : Exception
{
public InvalidSenderException (string message, Exception innerException)
public InvalidSenderException(string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class RemoveRecipientException : Exception
{
public RemoveRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class ReportAndRetryRecipientException : RetryRecipientException
{
public ReportAndRetryRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class RetryRecipientException : Exception
{
public RetryRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
#endregion
static QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8);
static QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
static Dictionary<Encoding, QuotedPrintable> QuotedPrintableEncoder = InitQpDictionary();
private static readonly QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8);
private static readonly QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
private static readonly Dictionary<Encoding, QuotedPrintable> QuotedPrintableEncoder = InitQpDictionary();
private static int mailQueueSize;
private static readonly Object lockObject = new Object();
#region Static initialisation
static private Dictionary<Encoding, QuotedPrintable> InitQpDictionary ()
private static Dictionary<Encoding, QuotedPrintable> InitQpDictionary()
{
Dictionary<Encoding, QuotedPrintable> qp = new Dictionary<Encoding, QuotedPrintable>();
qp[Encoding.UTF8] = qpUTF8;
@@ -76,7 +89,7 @@ namespace Swarmops.Utility.BotCode
#endregion
public static void Run ()
public static void Run()
{
// If there is mail in the outbound mail queue, do not add more. (This is a primitive
// protection against dupes. Better will come that doesn't force idle time like this.)
@@ -103,7 +116,6 @@ namespace Swarmops.Utility.BotCode
foreach (OutboundMail mail in mails)
{
// If we have already processed past our limit, return for now.
if (maxBatchSize < 1)
{
@@ -118,8 +130,8 @@ namespace Swarmops.Utility.BotCode
// Yes! Mark it as started and mail our author.
mail.StartProcessDateTime = DateTime.Now;
if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
{
string mailBody = string.Empty;
@@ -133,17 +145,17 @@ namespace Swarmops.Utility.BotCode
// If we are debugging, and stepping through this program, avoid the misery of many simultaneous threads.
if (System.Diagnostics.Debugger.IsAttached)
if (Debugger.IsAttached)
{
batchSize = 1; // Do NOT multithread while debugging
}
while (true)
{
if (!System.Diagnostics.Debugger.IsAttached)
if (!Debugger.IsAttached)
{
HeartBeater.Instance.Beat();
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
}
OutboundMailRecipients recipients = mail.GetNextRecipientBatch(batchSize);
@@ -156,16 +168,19 @@ namespace Swarmops.Utility.BotCode
mail.SetProcessed();
if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail)
// TODO: Set special flag
{
string body = "Your mail has completed transmitting to " + mail.RecipientCount.ToString("#,##0") +
string body = "Your mail has completed transmitting to " +
mail.RecipientCount.ToString("#,##0") +
" intended recipients. Out of these, " + mail.RecipientsFail.ToString("#,##0") +
" failed because of invalid, empty, or otherwise bad e-mail addresses. These people have not received your message.\r\n";
new Mail.MailTransmitter(
new MailTransmitter(
Strings.MailSenderName, Strings.MailSenderAddress,
"Mail transmission completed: " + mail.Title, body, Person.FromIdentity(mail.AuthorPersonId),
"Mail transmission completed: " + mail.Title, body,
Person.FromIdentity(mail.AuthorPersonId),
true).Send();
}
@@ -176,165 +191,154 @@ namespace Swarmops.Utility.BotCode
break; //the while loop
}
else
List<IAsyncResult> sendInProgress = new List<IAsyncResult>();
List<WaitHandle> waitHandlesList = new List<WaitHandle>();
foreach (OutboundMailRecipient recipient in recipients)
{
List<IAsyncResult> sendInProgress = new List<IAsyncResult>();
List<WaitHandle> waitHandlesList = new List<WaitHandle>();
foreach (OutboundMailRecipient recipient in recipients)
// Skip known invalid mail addresses
if (recipient.Person != null
&& (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable))
{
// Skip known invalid mail addresses
if (recipient.Person != null
&& (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable))
{
lock (lockObject)
{
recipient.Delete();
recipient.OutboundMail.IncrementFailures();
}
continue;
}
// Start the transmission process, asynchronously
lock (lockObject)
{
MailTransmissionDelegate asyncTransmitter = new MailTransmissionDelegate(TransmitOneMail);
MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState();
asyncState.dlgt = asyncTransmitter;
asyncState.recipient = recipient;
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, new AsyncCallback(MailSent), asyncState);
sendInProgress.Add(asyncResult);
waitHandlesList.Add(asyncResult.AsyncWaitHandle);
mailQueueSize++;
recipient.Delete();
recipient.OutboundMail.IncrementFailures();
}
System.Threading.Thread.Sleep(25); // Allow some time
continue;
}
// now wait for them to finish;
int numberStillExecuting = sendInProgress.Count;
int numberExecutingLast = numberStillExecuting + 1;
DateTime lastProgress = DateTime.Now;
// Start the transmission process, asynchronously
while (numberStillExecuting > 0)
lock (lockObject)
{
WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true);
lock (lockObject)
MailTransmissionDelegate asyncTransmitter = TransmitOneMail;
MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState();
asyncState.dlgt = asyncTransmitter;
asyncState.recipient = recipient;
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, MailSent, asyncState);
sendInProgress.Add(asyncResult);
waitHandlesList.Add(asyncResult.AsyncWaitHandle);
mailQueueSize++;
}
Thread.Sleep(25); // Allow some time
}
// now wait for them to finish;
int numberStillExecuting = sendInProgress.Count;
int numberExecutingLast = numberStillExecuting + 1;
DateTime lastProgress = DateTime.Now;
while (numberStillExecuting > 0)
{
WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true);
lock (lockObject)
{
numberStillExecuting = 0;
waitHandlesList = new List<WaitHandle>();
for (int i = 0; i < sendInProgress.Count; ++i)
{
numberStillExecuting = 0;
waitHandlesList = new List<WaitHandle>();
IAsyncResult iares = sendInProgress[i];
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) iares.AsyncState;
for (int i = 0; i < sendInProgress.Count; ++i)
if (asyncState.dlgt != null)
{
IAsyncResult iares = sendInProgress[i];
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)iares.AsyncState;
if (asyncState.dlgt != null)
if (!asyncState.callbackCompleted)
{
if (!asyncState.callbackCompleted)
waitHandlesList.Add(iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
{
//Just finalised
if (asyncState.exception != null)
{
waitHandlesList.Add(iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
{
//Just finalised
if (asyncState.exception != null)
if (asyncState.exception is RetryRecipientException)
{
if (asyncState.exception is RetryRecipientException)
//Failed in sending due to some reason that can clear up by itself.
asyncState.dlgt = null;
}
else
{
//Make sure recipient is deleted
try
{
//Failed in sending due to some reason that can clear up by itself.
asyncState.dlgt = null;
asyncState.recipient.Delete();
// if RemoveRecipientException everything went ok except for the removal
if (asyncState.exception is RemoveRecipientException)
asyncState.recipient.OutboundMail.IncrementSuccesses();
asyncState.dlgt = null; // mark as done;
mailQueueSize--;
}
else
catch
{
//Make sure recipient is deleted
try
{
asyncState.recipient.Delete();
// if RemoveRecipientException everything went ok except for the removal
if (asyncState.exception is RemoveRecipientException)
asyncState.recipient.OutboundMail.IncrementSuccesses();
asyncState.dlgt = null; // mark as done;
mailQueueSize--;
}
catch
{ //Keep looping until recipient removed
numberStillExecuting++;
}
//Keep looping until recipient removed
numberStillExecuting++;
}
}
}
}
}
}
}
if (numberExecutingLast != numberStillExecuting)
lastProgress = DateTime.Now;
if (numberExecutingLast != numberStillExecuting)
lastProgress = DateTime.Now;
numberExecutingLast = numberStillExecuting;
numberExecutingLast = numberStillExecuting;
if (lastProgress.AddSeconds(60 * 2) < DateTime.Now)
if (lastProgress.AddSeconds(60*2) < DateTime.Now)
{
// since last change, something must have hanged
lock (lockObject)
{
// since last change, something must have hanged
lock (lockObject)
{
mailQueueSize = -1000;
}
throw new Exception("Timeout in MailProcessor");
mailQueueSize = -1000;
}
throw new Exception("Timeout in MailProcessor");
}
}
}
}
}
internal class MailTransmissionAsyncState
{
internal MailTransmissionDelegate dlgt = null;
internal Exception exception = null;
internal OutboundMailRecipient recipient = null;
internal bool callbackCompleted = false;
}
internal delegate OutboundMailRecipient MailTransmissionDelegate (OutboundMailRecipient recipient);
internal static OutboundMailRecipient TransmitOneMail (OutboundMailRecipient recipient)
internal static OutboundMailRecipient TransmitOneMail(OutboundMailRecipient recipient)
{
try
{
// If the mail address in illegal format, do not try to send anything:
if (!Formatting.ValidateEmailFormat(recipient.EmailPerson.Email.Trim()))
{
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
if (recipient.Person != null && recipient.Person.MailUnreachable)
{
string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
if (recipient.Person != null && recipient.Person.NeverMail)
{
string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new IgnoreRecipientException(msg, null);
}
// Otherwise, let's start processing
OutboundMail mail = recipient.OutboundMail;
@@ -384,35 +388,39 @@ namespace Swarmops.Utility.BotCode
try
{
message.From = new MailAddress(mail.Author.PartyEmail,
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited +
")"),
currentEncoding);
if (mail.Author.Identity == 1)
{
//TODO: Create alternative party mail optional data field, or organization chairman (based on roles) differently
// Ugly hack
message.From = new MailAddress("rick.falkvinge@piratpartiet.se",
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
qp.EncodeMailHeaderString(mail.Author.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
}
}
catch (Exception ex)
{
throw new InvalidSenderException("Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId).ToString() + ";" + mail.Author.PartyEmail, ex);
throw new InvalidSenderException(
"Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId) + ";" +
mail.Author.PartyEmail, ex);
}
}
else
{
try
{
FunctionalMail.AddressItem aItem = mail.Organization.GetFunctionalMailAddressInh(mail.AuthorType);
message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name),
currentEncoding);
message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name),
currentEncoding);
}
catch (Exception ex)
{
throw new InvalidSenderException("Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int)mail.AuthorType).ToString(), ex);
throw new InvalidSenderException(
"Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int) mail.AuthorType), ex);
}
}
@@ -422,13 +430,16 @@ namespace Swarmops.Utility.BotCode
try
{
message.To.Add(new MailAddress(recipient.Person.PartyEmail,
qp.EncodeMailHeaderString(recipient.Person.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding));
qp.EncodeMailHeaderString(recipient.Person.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding));
}
catch (FormatException e)
{
string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity.ToString() + "], mail [" +
recipient.Person.PartyEmail + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity +
"], mail [" +
recipient.Person.PartyEmail + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
}
}
@@ -437,13 +448,15 @@ namespace Swarmops.Utility.BotCode
try
{
message.To.Add(new MailAddress(recipient.EmailPerson.Email,
qp.EncodeMailHeaderString(recipient.EmailPerson.Name),
currentEncoding));
qp.EncodeMailHeaderString(recipient.EmailPerson.Name),
currentEncoding));
}
catch (FormatException e)
{
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
}
}
@@ -485,7 +498,9 @@ namespace Swarmops.Utility.BotCode
}
catch (Exception ex)
{
throw new RemoveRecipientException("TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
throw new RemoveRecipientException(
"TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
}
}
message.BodyEncoding = currentEncoding;
@@ -512,9 +527,13 @@ namespace Swarmops.Utility.BotCode
}
}
if (text == "")
throw new RemoveRecipientException("Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
else if (html == "" || ex != null)
throw new RemoveRecipientException("Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
throw new RemoveRecipientException(
"Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
if (html == "" || ex != null)
throw new RemoveRecipientException(
"Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
ContentType textContentType = new ContentType(MediaTypeNames.Text.Plain);
textContentType.CharSet = currentEncoding.BodyName;
@@ -567,10 +586,10 @@ namespace Swarmops.Utility.BotCode
string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
if (System.Diagnostics.Debugger.IsAttached)
if (Debugger.IsAttached)
{
System.Diagnostics.Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
System.Threading.Thread.Sleep(200); //simulate delay
Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
Thread.Sleep(200); //simulate delay
}
@@ -592,7 +611,7 @@ namespace Swarmops.Utility.BotCode
{
// Temporary error (SMTP 4xx). Try again.
System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e);
}
@@ -604,18 +623,22 @@ namespace Swarmops.Utility.BotCode
recipients.Add(address.Address);
}
ExceptionMail.Send(new ArgumentException("Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " + String.Join(", ", recipients.ToArray()), e));
ExceptionMail.Send(
new ArgumentException(
"Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " +
String.Join(", ", recipients.ToArray()), e));
if (mail.AuthorType == MailAuthorType.Person)
{
try
{
mail.Author.SendOfficerNotice("Failed recipient(s): " + String.Join(", ", recipients.ToArray()),
"Some recipients failed inexplicably in a mail from you.", 1);
mail.Author.SendOfficerNotice(
"Failed recipient(s): " + String.Join(", ", recipients.ToArray()),
"Some recipients failed inexplicably in a mail from you.", 1);
}
catch (Exception ex)
{
throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId.ToString(), ex);
throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId, ex);
}
}
}
@@ -624,28 +647,26 @@ namespace Swarmops.Utility.BotCode
}
catch (InvalidRecipientException ex)
{
throw ex;
}
catch (RetryRecipientException ex)
{
System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure
Thread.Sleep(2000);
// Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
internal static void MailSent (IAsyncResult result)
internal static void MailSent(IAsyncResult result)
{
lock (lockObject)
{
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)result.AsyncState;
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) result.AsyncState;
MailTransmissionDelegate asyncTransmitter = asyncState.dlgt;
OutboundMailRecipient recipient = asyncState.recipient;
try
@@ -667,7 +688,7 @@ namespace Swarmops.Utility.BotCode
catch (ReportAndRetryRecipientException e)
{
asyncState.exception = e;
System.Diagnostics.Debug.WriteLine(e.ToString());
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
catch (RetryRecipientException e)
@@ -696,13 +717,13 @@ namespace Swarmops.Utility.BotCode
catch (Exception ex)
{
// Return this exception in asyncState since it is important to stop flooding.
asyncState.exception = new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex);
asyncState.exception =
new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex);
ExceptionMail.Send(asyncState.exception, true); //Report the secondary exception
}
System.Diagnostics.Debug.WriteLine(e.ToString());
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
@@ -710,7 +731,14 @@ namespace Swarmops.Utility.BotCode
}
}
private static int mailQueueSize;
private static Object lockObject = new Object();
internal class MailTransmissionAsyncState
{
internal bool callbackCompleted = false;
internal MailTransmissionDelegate dlgt = null;
internal Exception exception = null;
internal OutboundMailRecipient recipient = null;
}
internal delegate OutboundMailRecipient MailTransmissionDelegate(OutboundMailRecipient recipient);
}
}