Code cleanup: spacing

This commit is contained in:
Rick Falkvinge
2014-12-05 22:12:51 +01:00
parent c2d3a5edb4
commit bfdd5d8a53
412 changed files with 9095 additions and 9037 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ namespace Swarmops.Utility.BotCode
{
public class ActivityMailer
{
[Obsolete("Disabled/Deprecated for Swarmops", true)]
[Obsolete ("Disabled/Deprecated for Swarmops", true)]
public static void Run()
{
/* Nope. Disable this.
+27 -26
View File
@@ -55,11 +55,11 @@ namespace Swarmops.Utility.BotCode
}
public void ComposeBallots(BallotCompositionMethod method)
public void ComposeBallots (BallotCompositionMethod method)
{
FinalBallots = new Dictionary<int, MeetingElectionCandidates>();
QuotedMasterList = GenerateBallot(this.rawElectionResult, -1, BallotCompositionMethod.Unmixed);
QuotedMasterList = GenerateBallot (this.rawElectionResult, -1, BallotCompositionMethod.Unmixed);
if (this.geographicLists.Count == 0)
{
GenerateGeographicLists();
@@ -67,16 +67,16 @@ namespace Swarmops.Utility.BotCode
foreach (Geography ballotGeography in BallotGeographies)
{
FinalBallots[ballotGeography.Identity] = GenerateBallot(this.geographicLists[ballotGeography.Identity],
FinalBallots[ballotGeography.Identity] = GenerateBallot (this.geographicLists[ballotGeography.Identity],
22,
method);
}
}
public bool CandidatePersonIdDefected(int personId)
public bool CandidatePersonIdDefected (int personId)
{
return this.defectionsLookup.ContainsKey(personId);
return this.defectionsLookup.ContainsKey (personId);
}
@@ -86,23 +86,23 @@ namespace Swarmops.Utility.BotCode
{
foreach (Geography ballotGeography in BallotGeographies)
{
if (candidate.Person.Geography.Inherits(ballotGeography))
if (candidate.Person.Geography.Inherits (ballotGeography))
{
// This candidate is under this particular geography, so add to list
if (!this.geographicLists.ContainsKey(ballotGeography.Identity))
if (!this.geographicLists.ContainsKey (ballotGeography.Identity))
{
this.geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates();
}
this.geographicLists[ballotGeography.Identity].Add(candidate);
this.geographicLists[ballotGeography.Identity].Add (candidate);
}
}
}
}
private MeetingElectionCandidates GenerateBallot(MeetingElectionCandidates rawList, int candidateCount,
private MeetingElectionCandidates GenerateBallot (MeetingElectionCandidates rawList, int candidateCount,
BallotCompositionMethod method)
{
MeetingElectionCandidates result = new MeetingElectionCandidates();
@@ -117,7 +117,7 @@ namespace Swarmops.Utility.BotCode
for (int rawIndex = 0; rawIndex < rawList.Count; rawIndex++)
{
if (CandidatePersonIdDefected(rawList[rawIndex].PersonId))
if (CandidatePersonIdDefected (rawList[rawIndex].PersonId))
{
takenCandidates[rawIndex] = true;
}
@@ -136,22 +136,22 @@ namespace Swarmops.Utility.BotCode
//
// Should we add a candidate from the raw list or from the quoted master list?
int masterPosition = GetMasterListPosition(result.Count + 1, method);
int masterPosition = GetMasterListPosition (result.Count + 1, method);
if (masterPosition > 0)
{
// We should add a candidate from the master list, no quota calculations, BUT ONLY if this candidate
// hasn't already been added from the district list.
int rawListIndex = FindCandidateIndex(QuotedMasterList[masterPosition - 1].InternalPollCandidateId,
int rawListIndex = FindCandidateIndex (QuotedMasterList[masterPosition - 1].InternalPollCandidateId,
rawList);
if (rawListIndex >= 0 && !takenCandidates.ContainsKey(rawListIndex))
if (rawListIndex >= 0 && !takenCandidates.ContainsKey (rawListIndex))
{
// The master list candidate is also on the district list, but has not been added. Add
// the candidate in the master list position.
result.Add(QuotedMasterList[masterPosition - 1]);
result.Add (QuotedMasterList[masterPosition - 1]);
takenCandidates[rawListIndex] = true;
continue;
}
@@ -160,7 +160,7 @@ namespace Swarmops.Utility.BotCode
{
// The master list candidate is not on the district list. Add the candidate.
result.Add(QuotedMasterList[masterPosition - 1]);
result.Add (QuotedMasterList[masterPosition - 1]);
continue;
}
@@ -174,14 +174,14 @@ namespace Swarmops.Utility.BotCode
int nextCandidateIndex = 0;
while (takenCandidates.ContainsKey(nextCandidateIndex))
while (takenCandidates.ContainsKey (nextCandidateIndex))
{
nextCandidateIndex++;
}
PersonGender candidateGender = rawList[nextCandidateIndex].Person.Gender;
double currentMaleQuota = CalculateListMaleQuota(result, candidateGender);
double currentMaleQuota = CalculateListMaleQuota (result, candidateGender);
// Here, we account an extremely rare situation where the correct quota is not even obtainable, e.g.
// for position #3 where #1 is male and #2 is female and with a quota of 40%. Either way, it will
@@ -191,7 +191,7 @@ namespace Swarmops.Utility.BotCode
? PersonGender.Female
: PersonGender.Male);
double alternateMaleQuota = CalculateListMaleQuota(result, oppositeGender);
double alternateMaleQuota = CalculateListMaleQuota (result, oppositeGender);
// If currentMaleQuota is outside of bounds AND the alternate quota IS inside of bounds...
@@ -203,7 +203,8 @@ namespace Swarmops.Utility.BotCode
try
{
nextCandidateIndex = GetNextSpecificGenderCandidate(rawList, takenCandidates, oppositeGender);
nextCandidateIndex = GetNextSpecificGenderCandidate (rawList, takenCandidates,
oppositeGender);
}
catch (ArgumentOutOfRangeException)
{
@@ -212,7 +213,7 @@ namespace Swarmops.Utility.BotCode
}
}
result.Add(rawList[nextCandidateIndex]);
result.Add (rawList[nextCandidateIndex]);
takenCandidates[nextCandidateIndex] = true;
}
@@ -220,7 +221,7 @@ namespace Swarmops.Utility.BotCode
}
private static int FindCandidateIndex(int candidateId, MeetingElectionCandidates list)
private static int FindCandidateIndex (int candidateId, MeetingElectionCandidates list)
{
for (int index = 0; index < list.Count; index++)
{
@@ -234,7 +235,7 @@ namespace Swarmops.Utility.BotCode
}
private static double CalculateListMaleQuota(MeetingElectionCandidates candidates,
private static double CalculateListMaleQuota (MeetingElectionCandidates candidates,
PersonGender nextCandidateGender)
{
if (candidates.Count < 1)
@@ -261,12 +262,12 @@ namespace Swarmops.Utility.BotCode
}
private static int GetNextSpecificGenderCandidate(MeetingElectionCandidates candidates,
private static int GetNextSpecificGenderCandidate (MeetingElectionCandidates candidates,
Dictionary<int, bool> takenCandidates, PersonGender desiredGender)
{
int index = 0;
while (takenCandidates.ContainsKey(index) || candidates[index].Person.Gender != desiredGender)
while (takenCandidates.ContainsKey (index) || candidates[index].Person.Gender != desiredGender)
{
index++; // potential out-of-range exception here, if there aren't enough candidates
}
@@ -280,7 +281,7 @@ namespace Swarmops.Utility.BotCode
/// <param name="currentPosition">The position of a particular ballot.</param>
/// <param name="method">The composition method to use.</param>
/// <returns>The position to pick from the master list, or zero if not from the master list.</returns>
private int GetMasterListPosition(int currentPosition, BallotCompositionMethod method)
private int GetMasterListPosition (int currentPosition, BallotCompositionMethod method)
{
if (method == BallotCompositionMethod.Unmixed)
{
@@ -317,7 +318,7 @@ namespace Swarmops.Utility.BotCode
return 0;
}
throw new NotImplementedException("Unimplemented method");
throw new NotImplementedException ("Unimplemented method");
}
}
+7 -7
View File
@@ -15,7 +15,7 @@ namespace Swarmops.Utility.BotCode
// Every hour of the day, we check that this has been recorded for the day. This is just in case
// the bot isn't running at midnight, to make sure that we get one entry per day.
if (SwarmDb.GetDatabaseForReading().GetBlogTopList(DateTime.Today) == null)
if (SwarmDb.GetDatabaseForReading().GetBlogTopList (DateTime.Today) == null)
{
ScrapeAndStore();
}
@@ -25,30 +25,30 @@ namespace Swarmops.Utility.BotCode
{
string scrapeData = string.Empty;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://knuff.se/topp50/knuffpoaeng/");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://knuff.se/topp50/knuffpoaeng/");
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
using (Stream stream = request.GetResponse().GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(1252)))
using (StreamReader reader = new StreamReader (stream, Encoding.GetEncoding (1252)))
{
scrapeData = reader.ReadToEnd();
}
}
Regex regex = new Regex("<h4 .*?><a href.*?>(?<blogname>.*?)</a>", RegexOptions.None);
Regex regex = new Regex ("<h4 .*?><a href.*?>(?<blogname>.*?)</a>", RegexOptions.None);
Match match = regex.Match(scrapeData);
Match match = regex.Match (scrapeData);
List<string> rankingList = new List<string>();
while (match.Success)
{
string blogName = match.Groups["blogname"].Value;
rankingList.Add(blogName);
rankingList.Add (blogName);
match = match.NextMatch();
}
SwarmDb.GetDatabaseForWriting().StoreBlogTopList(DateTime.Today, rankingList.ToArray());
SwarmDb.GetDatabaseForWriting().StoreBlogTopList (DateTime.Today, rankingList.ToArray());
}
}
}
+14 -14
View File
@@ -19,10 +19,10 @@ namespace Swarmops.Utility.BotCode
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(rssUrl);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create (rssUrl);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
RssReader reader = new RssReader(resp.GetResponseStream());
RssReader reader = new RssReader (resp.GetResponseStream());
try
{
@@ -35,23 +35,23 @@ namespace Swarmops.Utility.BotCode
string url = item.Link;
DateTime dateTime = item.PubDate;
int dividerIndex = item.Title.LastIndexOf('(');
int dividerIndex = item.Title.LastIndexOf ('(');
if (item.Title.EndsWith("))"))
if (item.Title.EndsWith ("))"))
{
dividerIndex = item.Title.Substring(0, item.Title.Length - 7).LastIndexOf('(');
dividerIndex = item.Title.Substring (0, item.Title.Length - 7).LastIndexOf ('(');
}
string title = item.Title.Substring(0, dividerIndex).Trim();
string blogName = item.Title.Substring(dividerIndex + 1, item.Title.Length - dividerIndex - 2);
string title = item.Title.Substring (0, dividerIndex).Trim();
string blogName = item.Title.Substring (dividerIndex + 1, item.Title.Length - dividerIndex - 2);
bool newEntry = MediaEntry.CreateFromKeyword(keyword, blogName, true, url, title, dateTime);
bool newEntry = MediaEntry.CreateFromKeyword (keyword, blogName, true, url, title, dateTime);
if (newEntry)
{
try
{
PingCreeper(url);
PingCreeper (url);
}
catch (Exception)
{
@@ -62,7 +62,7 @@ namespace Swarmops.Utility.BotCode
}
catch (Exception e)
{
throw new ReaderException("feed:" + rssUrl + ", Status=" + resp.StatusCode, e);
throw new ReaderException ("feed:" + rssUrl + ", Status=" + resp.StatusCode, e);
}
finally
@@ -72,9 +72,9 @@ namespace Swarmops.Utility.BotCode
}
}
private static void PingCreeper(string referringUrl)
private static void PingCreeper (string referringUrl)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://gnuheter.com/creeper/image");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://gnuheter.com/creeper/image");
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
request.Referer = referringUrl;
@@ -83,8 +83,8 @@ namespace Swarmops.Utility.BotCode
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
public ReaderException (string message, Exception innerException)
: base (message, innerException)
{
}
}
+7 -7
View File
@@ -6,7 +6,7 @@ namespace Swarmops.Utility.BotCode
{
public class BotLog
{
public static void Write(int generation, string code, string message)
public static void Write (int generation, string code, string message)
{
string line = string.Empty;
@@ -20,23 +20,23 @@ namespace Swarmops.Utility.BotCode
line += " ";
}
line += string.Format("{0,-16} ", code);
line += string.Format ("{0,-16} ", code);
line += message;
LogWrite(line);
LogWrite (line);
}
private static void LogWrite(string message)
private static void LogWrite (string message)
{
DateTime now = DateTime.Now;
string logFileName = "/var/log/swarmops/backend-log-" +
now.ToString("yyyy-MM-dd-HH") + ".log";
now.ToString ("yyyy-MM-dd-HH") + ".log";
using (StreamWriter writer = new StreamWriter(logFileName, true, Encoding.GetEncoding(1252)))
using (StreamWriter writer = new StreamWriter (logFileName, true, Encoding.GetEncoding (1252)))
{
writer.WriteLine("[" + now.ToString("HH:mm:ss.fff") + "] " + message);
writer.WriteLine ("[" + now.ToString ("HH:mm:ss.fff") + "] " + message);
}
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ namespace Swarmops.Utility.BotCode
{
// This entire class could use a tune-up. More event types will come, too.
[Obsolete("Deprecated for Swarmops. Way too much hardcoded. Rewrite, generalize, or scrap.", true)]
[Obsolete ("Deprecated for Swarmops. Way too much hardcoded. Rewrite, generalize, or scrap.", true)]
public static void Run()
{
/*
+11 -11
View File
@@ -38,17 +38,17 @@ namespace Swarmops.Utility.BotCode
public void Beat()
{
Beat(this.lastFilename);
Beat (this.lastFilename);
}
public void Beat(string filename)
public void Beat (string filename)
{
lock (lockObject)
{
this.lastFilename = filename;
}
if ((DateTime.Now.Subtract(this.lastBeat).TotalSeconds > 10)
if ((DateTime.Now.Subtract (this.lastBeat).TotalSeconds > 10)
&& (this.FlagRestartRequested == false))
{
try
@@ -59,18 +59,18 @@ namespace Swarmops.Utility.BotCode
if (nowString == Persistence.Key["PirateBot-L-Heartbeat"])
{
writeFile(filename, DateTime.Now.ToString());
writeFile (filename, DateTime.Now.ToString());
}
else
{
SuggestRestart();
throw new Exception("Failed to update HeartBeat");
throw new Exception ("Failed to update HeartBeat");
}
}
catch (Exception e)
{
SuggestRestart();
throw new Exception("Failed to update HeartBeat", e);
throw new Exception ("Failed to update HeartBeat", e);
}
}
}
@@ -78,16 +78,16 @@ namespace Swarmops.Utility.BotCode
public void SuggestRestart()
{
if (!File.Exists("./piratebotexit.flag"))
File.Create("./piratebotexit.flag");
if (!File.Exists ("./piratebotexit.flag"))
File.Create ("./piratebotexit.flag");
this.FlagRestartRequested = true;
}
public static void writeFile(string sPath, string content)
public static void writeFile (string sPath, string content)
{
StreamWriter writeStream = new StreamWriter(new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite),
StreamWriter writeStream = new StreamWriter (new FileStream (sPath, FileMode.Create, FileAccess.ReadWrite),
Encoding.Default);
writeStream.Write(content);
writeStream.Write (content);
writeStream.Close();
}
}
+37 -37
View File
@@ -14,28 +14,28 @@ namespace Swarmops.Utility.BotCode
foreach (MeetingElection poll in polls)
{
Console.Write("Looking at poll #" + poll.Identity + "...");
Console.Write ("Looking at poll #" + poll.Identity + "...");
if (DateTime.Now > poll.VotingCloses)
{
Console.Write(" after closedatetime " + poll.VotingCloses.ToString("yyyy-MM-dd HH:mm") + "...");
Console.Write (" after closedatetime " + poll.VotingCloses.ToString ("yyyy-MM-dd HH:mm") + "...");
// Poll should be CLOSED, definitely CLOSED.
if (poll.VotingOpen)
{
Console.WriteLine(" CLOSING.");
Console.WriteLine (" CLOSING.");
poll.VotingOpen = false; // Closes poll
poll.Creator.SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
Person.FromIdentity(1)
.SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
poll.Creator.SendNotice ("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
Person.FromIdentity (1)
.SendNotice ("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
ReportPollResults(poll, false);
ReportPollResults (poll, false);
}
else
{
Console.WriteLine(" no action.");
Console.WriteLine (" no action.");
}
}
else if (DateTime.Now > poll.VotingOpens)
@@ -44,17 +44,17 @@ namespace Swarmops.Utility.BotCode
{
// Poll should be OPEN.
Console.Write("after opendatetime " + poll.VotingOpens.ToString("yyyy-MM-dd HH:mm") + "...");
Console.Write ("after opendatetime " + poll.VotingOpens.ToString ("yyyy-MM-dd HH:mm") + "...");
if (!poll.VotingOpen)
{
Console.WriteLine("OPENING for " + poll.Organization.Name + ":");
Console.WriteLine ("OPENING for " + poll.Organization.Name + ":");
// Populate voters, then open for voting
Organizations orgTree = poll.Organization.GetTree();
Memberships memberships = Memberships.ForOrganizations(orgTree);
Memberships memberships = Memberships.ForOrganizations (orgTree);
Dictionary<int, bool> dupeCheck = new Dictionary<int, bool>();
@@ -62,7 +62,7 @@ namespace Swarmops.Utility.BotCode
foreach (Membership membership in memberships)
{
Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count,
Console.Write ("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count,
memberships.Count, membership.PersonId);
if (!membership.Active)
@@ -70,62 +70,62 @@ namespace Swarmops.Utility.BotCode
continue; // paranoid programming
}
if (!membership.Organization.IsOrInherits(poll.Organization))
if (!membership.Organization.IsOrInherits (poll.Organization))
{
continue; // more paranoid programming
}
if (!dupeCheck.ContainsKey(membership.PersonId))
if (!dupeCheck.ContainsKey (membership.PersonId))
{
if (membership.Person.GeographyId == 0)
{
// It's a trap!
Console.Write(" GEOGRAPHY ZERO, ignoring\r\n");
Console.Write (" GEOGRAPHY ZERO, ignoring\r\n");
}
else
{
Geography geo = membership.Person.Geography;
if (geo.Inherits(poll.GeographyId) || geo.Identity == poll.GeographyId)
if (geo.Inherits (poll.GeographyId) || geo.Identity == poll.GeographyId)
{
poll.AddVoter(membership.Person);
poll.AddVoter (membership.Person);
dupeCheck[membership.PersonId] = true;
}
}
}
}
Console.WriteLine(" done.");
Console.Write(" - opening poll...");
Console.WriteLine (" done.");
Console.Write (" - opening poll...");
poll.VotingOpen = true;
Console.WriteLine(" done.");
Console.Write("Sending notices... ");
Console.WriteLine (" done.");
Console.Write ("Sending notices... ");
string body = "Electoral roll for poll \"" + poll.Name + "\" primed. " +
dupeCheck.Count + " people can vote. The vote is now OPEN.";
string subject = "Poll Open: " + poll.Name;
poll.Creator.SendNotice(subject, body, poll.OrganizationId);
Person.FromIdentity(1).SendNotice(subject, body, poll.OrganizationId);
poll.Creator.SendNotice (subject, body, poll.OrganizationId);
Person.FromIdentity (1).SendNotice (subject, body, poll.OrganizationId);
Console.WriteLine(" done.");
Console.WriteLine (" done.");
}
else
{
Console.WriteLine(" already open, no action.");
Console.WriteLine (" already open, no action.");
// Report intermediate results to owner
ReportPollResults(poll, true);
ReportPollResults (poll, true);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
Console.WriteLine (exception.ToString());
throw exception;
}
@@ -134,20 +134,20 @@ namespace Swarmops.Utility.BotCode
}
private static void ReportPollResults(MeetingElection poll, bool stillOpen)
private static void ReportPollResults (MeetingElection poll, bool stillOpen)
{
SchulzeProcessor processor = new SchulzeProcessor();
processor.Candidates = poll.Candidates;
processor.Votes = MeetingElectionVotes.ForInternalPoll(poll);
processor.Votes = MeetingElectionVotes.ForInternalPoll (poll);
processor.Process();
MailRawElectionResults(poll, processor, stillOpen);
MailRawElectionResults (poll, processor, stillOpen);
}
private static void MailRawElectionResults(MeetingElection poll, SchulzeProcessor processor, bool stillOpen)
private static void MailRawElectionResults (MeetingElection poll, SchulzeProcessor processor, bool stillOpen)
{
MeetingElectionCandidates candidates = processor.FinalOrder;
@@ -163,20 +163,20 @@ namespace Swarmops.Utility.BotCode
for (int candidateIndex = 0; candidateIndex < candidates.Count; candidateIndex++)
{
int distance = processor.GetCandidateDistance(candidateIndex);
body += String.Format("{0:D3}. {1} {2}{3}\r\n", candidateIndex + 1,
(distance > 0 ? distance.ToString("D4") : "----"), candidates[candidateIndex].Person.Canonical,
dropoutLookup.ContainsKey(candidates[candidateIndex].PersonId) ? " [hoppat av]" : string.Empty);
int distance = processor.GetCandidateDistance (candidateIndex);
body += String.Format ("{0:D3}. {1} {2}{3}\r\n", candidateIndex + 1,
(distance > 0 ? distance.ToString ("D4") : "----"), candidates[candidateIndex].Person.Canonical,
dropoutLookup.ContainsKey (candidates[candidateIndex].PersonId) ? " [hoppat av]" : string.Empty);
}
int[] recipients = {1, poll.CreatedByPersonId};
// Send to Rick too while stabilizing functionality -- remove as soon as Rick is running in any poll
// Send to Rick too while stabilizing functionality -- remove as soon as Rick is running in any poll
string subject = (stillOpen ? "Intermediate" : "FINAL") + " results for poll - " + poll.Name;
foreach (int personId in recipients)
{
Person.FromIdentity(personId).SendNotice(
Person.FromIdentity (personId).SendNotice (
subject, body, poll.OrganizationId);
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ namespace Swarmops.Utility.BotCode
{
// TODO: Foreach open poll...
MeetingElectionCandidates candidates = MeetingElectionCandidates.ForPoll(MeetingElection.Primaries2010);
MeetingElectionCandidates candidates = MeetingElectionCandidates.ForPoll (MeetingElection.Primaries2010);
foreach (MeetingElectionCandidate candidate in candidates)
{
+99 -95
View File
@@ -23,56 +23,56 @@ namespace Swarmops.Utility.BotCode
public class IgnoreRecipientException : Exception
{
public IgnoreRecipientException(string message, Exception innerException)
: base(message, innerException)
public IgnoreRecipientException (string message, Exception innerException)
: base (message, innerException)
{
}
}
public class InvalidRecipientException : IgnoreRecipientException
{
public InvalidRecipientException(string message, Exception innerException)
: base(message, innerException)
public InvalidRecipientException (string message, Exception innerException)
: base (message, innerException)
{
}
}
public class InvalidSenderException : Exception
{
public InvalidSenderException(string message, Exception innerException)
: base(message, innerException)
public InvalidSenderException (string message, Exception innerException)
: base (message, innerException)
{
}
}
public class RemoveRecipientException : Exception
{
public RemoveRecipientException(string message, Exception innerException)
: base(message, innerException)
public RemoveRecipientException (string message, Exception innerException)
: base (message, innerException)
{
}
}
public class ReportAndRetryRecipientException : RetryRecipientException
{
public ReportAndRetryRecipientException(string message, Exception innerException)
: base(message, innerException)
public ReportAndRetryRecipientException (string message, Exception innerException)
: base (message, innerException)
{
}
}
public class RetryRecipientException : Exception
{
public RetryRecipientException(string message, Exception innerException)
: base(message, innerException)
public RetryRecipientException (string message, Exception innerException)
: base (message, innerException)
{
}
}
#endregion
private static readonly QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8);
private static readonly QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
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();
@@ -83,7 +83,7 @@ namespace Swarmops.Utility.BotCode
{
Dictionary<Encoding, QuotedPrintable> qp = new Dictionary<Encoding, QuotedPrintable>();
qp[Encoding.UTF8] = qpUTF8;
qp[Encoding.GetEncoding("ISO-8859-1")] = qp8859;
qp[Encoding.GetEncoding ("ISO-8859-1")] = qp8859;
return qp;
}
@@ -103,7 +103,7 @@ namespace Swarmops.Utility.BotCode
}
// Look for a mail to process, or keep processing.
OutboundMails mails = OutboundMails.GetTopUnprocessed(100);
OutboundMails mails = OutboundMails.GetTopUnprocessed (100);
mailQueueSize = 0;
if (mails.Count == 0)
@@ -135,9 +135,9 @@ namespace Swarmops.Utility.BotCode
{
string mailBody = string.Empty;
new MailTransmitter(
new MailTransmitter (
Strings.MailSenderName, Strings.MailSenderAddress, "Mail transmission begins: " + mail.Title,
mailBody, Person.FromIdentity(mail.AuthorPersonId), true).Send();
mailBody, Person.FromIdentity (mail.AuthorPersonId), true).Send();
}
}
@@ -158,7 +158,7 @@ namespace Swarmops.Utility.BotCode
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
}
OutboundMailRecipients recipients = mail.GetNextRecipientBatch(batchSize);
OutboundMailRecipients recipients = mail.GetNextRecipientBatch (batchSize);
maxBatchSize -= recipients.Count; // Decrement number of recipients to process on next mail, if any
@@ -173,14 +173,15 @@ namespace Swarmops.Utility.BotCode
// TODO: Set special flag
{
string body = "Your mail has completed transmitting to " +
mail.RecipientCount.ToString("#,##0") +
" intended recipients. Out of these, " + mail.RecipientsFail.ToString("#,##0") +
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 MailTransmitter(
new MailTransmitter (
Strings.MailSenderName, Strings.MailSenderAddress,
"Mail transmission completed: " + mail.Title, body,
Person.FromIdentity(mail.AuthorPersonId),
Person.FromIdentity (mail.AuthorPersonId),
true).Send();
}
@@ -216,13 +217,13 @@ namespace Swarmops.Utility.BotCode
MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState();
asyncState.dlgt = asyncTransmitter;
asyncState.recipient = recipient;
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, MailSent, asyncState);
sendInProgress.Add(asyncResult);
waitHandlesList.Add(asyncResult.AsyncWaitHandle);
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke (recipient, MailSent, asyncState);
sendInProgress.Add (asyncResult);
waitHandlesList.Add (asyncResult.AsyncWaitHandle);
mailQueueSize++;
}
Thread.Sleep(25); // Allow some time
Thread.Sleep (25); // Allow some time
}
// now wait for them to finish;
@@ -233,7 +234,7 @@ namespace Swarmops.Utility.BotCode
while (numberStillExecuting > 0)
{
WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true);
WaitHandle.WaitAny (waitHandlesList.ToArray(), 100, true);
lock (lockObject)
{
numberStillExecuting = 0;
@@ -248,7 +249,7 @@ namespace Swarmops.Utility.BotCode
{
if (!asyncState.callbackCompleted)
{
waitHandlesList.Add(iares.AsyncWaitHandle);
waitHandlesList.Add (iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
@@ -292,14 +293,14 @@ namespace Swarmops.Utility.BotCode
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)
{
mailQueueSize = -1000;
}
throw new Exception("Timeout in MailProcessor");
throw new Exception ("Timeout in MailProcessor");
}
}
}
@@ -307,17 +308,17 @@ namespace Swarmops.Utility.BotCode
}
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()))
if (!Formatting.ValidateEmailFormat (recipient.EmailPerson.Email.Trim()))
{
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);
throw new InvalidRecipientException (msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
@@ -326,7 +327,7 @@ namespace Swarmops.Utility.BotCode
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);
throw new InvalidRecipientException (msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
@@ -335,7 +336,7 @@ namespace Swarmops.Utility.BotCode
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);
throw new IgnoreRecipientException (msg, null);
}
@@ -350,7 +351,7 @@ namespace Swarmops.Utility.BotCode
string email = recipient.EmailPerson.Email.ToLower();
if (mail.MailType == 0 || mail.TemplateName.EndsWith("Plain"))
if (mail.MailType == 0 || mail.TemplateName.EndsWith ("Plain"))
limitToText = true;
// TEST: Does this user require the use of a text-only message (as opposed to multipart/alternative)?
@@ -374,7 +375,7 @@ namespace Swarmops.Utility.BotCode
// Capability tests end here
if (limitToLatin1)
currentEncoding = Encoding.GetEncoding("ISO-8859-1");
currentEncoding = Encoding.GetEncoding ("ISO-8859-1");
else
currentEncoding = Encoding.UTF8;
@@ -387,24 +388,24 @@ namespace Swarmops.Utility.BotCode
{
try
{
message.From = new MailAddress(mail.Author.PartyEmail,
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited +
")"),
message.From = new MailAddress (mail.Author.PartyEmail,
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 + ")"),
message.From = new MailAddress ("rick.falkvinge@piratpartiet.se",
qp.EncodeMailHeaderString (mail.Author.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
}
}
catch (Exception ex)
{
throw new InvalidSenderException(
throw new InvalidSenderException (
"Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId) + ";" +
mail.Author.PartyEmail, ex);
}
@@ -413,13 +414,14 @@ namespace Swarmops.Utility.BotCode
{
try
{
FunctionalMail.AddressItem aItem = mail.Organization.GetFunctionalMailAddressInh(mail.AuthorType);
message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name),
FunctionalMail.AddressItem aItem =
mail.Organization.GetFunctionalMailAddressInh (mail.AuthorType);
message.From = new MailAddress (aItem.Email, qp.EncodeMailHeaderString (aItem.Name),
currentEncoding);
}
catch (Exception ex)
{
throw new InvalidSenderException(
throw new InvalidSenderException (
"Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int) mail.AuthorType), ex);
}
}
@@ -429,9 +431,9 @@ namespace Swarmops.Utility.BotCode
{
try
{
message.To.Add(new MailAddress(recipient.Person.PartyEmail,
qp.EncodeMailHeaderString(recipient.Person.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
message.To.Add (new MailAddress (recipient.Person.PartyEmail,
qp.EncodeMailHeaderString (recipient.Person.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding));
}
catch (FormatException e)
@@ -440,15 +442,15 @@ namespace Swarmops.Utility.BotCode
"], mail [" +
recipient.Person.PartyEmail + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
throw new InvalidRecipientException (msg, e);
}
}
else
{
try
{
message.To.Add(new MailAddress(recipient.EmailPerson.Email,
qp.EncodeMailHeaderString(recipient.EmailPerson.Name),
message.To.Add (new MailAddress (recipient.EmailPerson.Email,
qp.EncodeMailHeaderString (recipient.EmailPerson.Name),
currentEncoding));
}
catch (FormatException e)
@@ -457,7 +459,7 @@ namespace Swarmops.Utility.BotCode
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
throw new InvalidRecipientException (msg, e);
}
}
@@ -494,11 +496,11 @@ namespace Swarmops.Utility.BotCode
{
try
{
text = mail.RenderText(recipient.EmailPerson, culture);
text = mail.RenderText (recipient.EmailPerson, culture);
}
catch (Exception ex)
{
throw new RemoveRecipientException(
throw new RemoveRecipientException (
"TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
}
@@ -518,8 +520,8 @@ namespace Swarmops.Utility.BotCode
{
try
{
text = mail.RenderText(recipient.EmailPerson, culture);
html = mail.RenderHtml(recipient.EmailPerson, culture);
text = mail.RenderText (recipient.EmailPerson, culture);
html = mail.RenderHtml (recipient.EmailPerson, culture);
}
catch (Exception e)
{
@@ -527,18 +529,18 @@ namespace Swarmops.Utility.BotCode
}
}
if (text == "")
throw new RemoveRecipientException(
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(
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);
ContentType textContentType = new ContentType (MediaTypeNames.Text.Plain);
textContentType.CharSet = currentEncoding.BodyName;
ContentType htmlContentType = new ContentType(MediaTypeNames.Text.Html);
ContentType htmlContentType = new ContentType (MediaTypeNames.Text.Html);
htmlContentType.CharSet = currentEncoding.BodyName;
AlternateView textView = null;
@@ -547,13 +549,15 @@ namespace Swarmops.Utility.BotCode
if (limitToLatin1)
{
textView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), textContentType);
htmlView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), htmlContentType);
textView = new AlternateView (new MemoryStream (currentEncoding.GetBytes (text)),
textContentType);
htmlView = new AlternateView (new MemoryStream (currentEncoding.GetBytes (text)),
htmlContentType);
}
else
{
textView = AlternateView.CreateAlternateViewFromString(text, textContentType);
htmlView = AlternateView.CreateAlternateViewFromString(html, htmlContentType);
textView = AlternateView.CreateAlternateViewFromString (text, textContentType);
htmlView = AlternateView.CreateAlternateViewFromString (html, htmlContentType);
}
// A fucking stupid Mono bug forces us to transfer-encode in base64: it can't encode qp properly
@@ -564,8 +568,8 @@ namespace Swarmops.Utility.BotCode
// Add the views in increasing order of preference
message.AlternateViews.Add(textView);
message.AlternateViews.Add(htmlView);
message.AlternateViews.Add (textView);
message.AlternateViews.Add (htmlView);
}
if (mail.AuthorType == MailAuthorType.PirateWeb)
@@ -588,8 +592,8 @@ namespace Swarmops.Utility.BotCode
if (Debugger.IsAttached)
{
Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
Thread.Sleep(200); //simulate delay
Debug.WriteLine ("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
Thread.Sleep (200); //simulate delay
}
@@ -602,17 +606,17 @@ namespace Swarmops.Utility.BotCode
try
{
SmtpClient client = new SmtpClient(smtpServer, 25);
client.Send(message);
SmtpClient client = new SmtpClient (smtpServer, 25);
client.Send (message);
}
catch (SmtpException e)
{
if (e.ToString().StartsWith("System.Net.Mail.SmtpException: 4"))
if (e.ToString().StartsWith ("System.Net.Mail.SmtpException: 4"))
{
// Temporary error (SMTP 4xx). Try again.
Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e);
Thread.Sleep (2000); // Allow 2 seconds pause to wait for smtp-server to become available
throw new ReportAndRetryRecipientException ("Temporary smtp error, will retry.", e);
}
// Otherwise, bad recipient (assume so). Have the mail removed from the queue.
@@ -620,25 +624,25 @@ namespace Swarmops.Utility.BotCode
List<string> recipients = new List<string>();
foreach (MailAddress address in message.To)
{
recipients.Add(address.Address);
recipients.Add (address.Address);
}
ExceptionMail.Send(
new ArgumentException(
ExceptionMail.Send (
new ArgumentException (
"Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " +
String.Join(", ", recipients.ToArray()), e));
String.Join (", ", recipients.ToArray()), e));
if (mail.AuthorType == MailAuthorType.Person)
{
try
{
mail.Author.SendOfficerNotice(
"Failed recipient(s): " + String.Join(", ", recipients.ToArray()),
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, ex);
throw new Exception ("Failed to SendOfficerNotice to :" + mail.AuthorPersonId, ex);
}
}
}
@@ -651,8 +655,8 @@ namespace Swarmops.Utility.BotCode
}
catch (RetryRecipientException ex)
{
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)
@@ -662,7 +666,7 @@ namespace Swarmops.Utility.BotCode
}
internal static void MailSent(IAsyncResult result)
internal static void MailSent (IAsyncResult result)
{
lock (lockObject)
{
@@ -671,7 +675,7 @@ namespace Swarmops.Utility.BotCode
OutboundMailRecipient recipient = asyncState.recipient;
try
{
asyncTransmitter.EndInvoke(result);
asyncTransmitter.EndInvoke (result);
try
{
@@ -681,15 +685,15 @@ namespace Swarmops.Utility.BotCode
catch (Exception ex)
{
// whatever.. The mail is sent, but we couldn't mark it as such, probably a database failure.
asyncState.exception = new RemoveRecipientException("Couldn't remove mail recipient.", ex);
ExceptionMail.Send(asyncState.exception, true);
asyncState.exception = new RemoveRecipientException ("Couldn't remove mail recipient.", ex);
ExceptionMail.Send (asyncState.exception, true);
}
}
catch (ReportAndRetryRecipientException e)
{
asyncState.exception = e;
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
Debug.WriteLine (e.ToString());
ExceptionMail.Send (e, true);
}
catch (RetryRecipientException e)
{
@@ -718,13 +722,13 @@ namespace Swarmops.Utility.BotCode
{
// Return this exception in asyncState since it is important to stop flooding.
asyncState.exception =
new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex);
ExceptionMail.Send(asyncState.exception, true); //Report the secondary exception
new RemoveRecipientException ("Couldn't remove mail recipient after exception.", ex);
ExceptionMail.Send (asyncState.exception, true); //Report the secondary exception
}
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
Debug.WriteLine (e.ToString());
ExceptionMail.Send (e, true);
}
asyncState.callbackCompleted = true;
+39 -39
View File
@@ -34,7 +34,7 @@ namespace Swarmops.Utility.BotCode
case (int) TypedMailTemplate.TemplateType.MemberMail:
// All members at this org and geography
People people = People.FromOrganizationAndGeography(mail.Organization, mail.Geography);
People people = People.FromOrganizationAndGeography (mail.Organization, mail.Geography);
downwardCount = people.Count;
foreach (Person person in people)
{
@@ -44,7 +44,7 @@ namespace Swarmops.Utility.BotCode
case (int) TypedMailTemplate.TemplateType.OfficerMail:
// All officers at this org and geography
int[] officers = Roles.GetAllDownwardRoles(mail.OrganizationId, mail.GeographyId);
int[] officers = Roles.GetAllDownwardRoles (mail.OrganizationId, mail.GeographyId);
downwardCount = officers.Length;
foreach (int personId in officers)
{
@@ -53,18 +53,18 @@ namespace Swarmops.Utility.BotCode
break;
default:
throw new InvalidOperationException("Unhandled mail mode; can't resolve mail id " +
mail.Identity);
throw new InvalidOperationException ("Unhandled mail mode; can't resolve mail id " +
mail.Identity);
}
int[] upwardIds = Roles.GetAllUpwardRoles(mail.OrganizationId, mail.GeographyId);
int[] upwardIds = Roles.GetAllUpwardRoles (mail.OrganizationId, mail.GeographyId);
upwardCount = upwardIds.Length;
foreach (int personId in upwardIds)
{
// Filter for subscription of copies to local mail. Inefficient filter, room for optimization.
if (Person.FromIdentity(personId).IsSubscribing(NewsletterFeed.TypeID.OfficerUpwardCopies))
if (Person.FromIdentity (personId).IsSubscribing (NewsletterFeed.TypeID.OfficerUpwardCopies))
{
officerIds[personId] = true;
}
@@ -75,20 +75,20 @@ namespace Swarmops.Utility.BotCode
List<int> officerIdList = new List<int>();
foreach (int officerId in officerIds.Keys)
{
officerIdList.Add(officerId);
if (personIds.ContainsKey(officerId))
officerIdList.Add (officerId);
if (personIds.ContainsKey (officerId))
{
// If somebody is going to recieve this mail both due to area coverage and
// chain of command, send as chain of command only
personIds.Remove(officerId);
personIds.Remove (officerId);
}
}
List<int> personIdList = new List<int>();
foreach (int personId in personIds.Keys)
{
personIdList.Add(personId);
personIdList.Add (personId);
}
// Check for people who have declined local mail
@@ -101,7 +101,7 @@ namespace Swarmops.Utility.BotCode
{
foreach (int personId in decliners.Keys)
{
personIds.Remove(personId);
personIds.Remove (personId);
}
// Rebuild list after decliners gone
@@ -109,7 +109,7 @@ namespace Swarmops.Utility.BotCode
personIdList = new List<int>();
foreach (int personId in personIds.Keys)
{
personIdList.Add(personId);
personIdList.Add (personId);
}
}
@@ -118,14 +118,14 @@ namespace Swarmops.Utility.BotCode
// Create recipients
mail.AddRecipients(personIdList.ToArray(), false);
mail.AddRecipients(officerIdList.ToArray(), true);
mail.AddRecipients (personIdList.ToArray(), false);
mail.AddRecipients (officerIdList.ToArray(), true);
int countTotal = personIdList.Count + officerIdList.Count;
// Mark as ready
mail.SetRecipientCount(countTotal);
mail.SetRecipientCount (countTotal);
mail.SetResolved();
// TODO: Set recipient count of mail
@@ -134,17 +134,17 @@ namespace Swarmops.Utility.BotCode
string mailBody = "Your outbound mail with the title \"" + mail.Title +
"\" has been resolved for recipients and " +
"will be sent to " + countTotal.ToString("#,##0") + " people.\r\n\r\nOut of these " +
countTotal.ToString("#,##0") + ", " + (downwardCount - declineCount).ToString("#,##0") +
"will be sent to " + countTotal.ToString ("#,##0") + " people.\r\n\r\nOut of these " +
countTotal.ToString ("#,##0") + ", " + (downwardCount - declineCount).ToString ("#,##0") +
" are people within the requested " +
"organization/geography (" + Organization.FromIdentity(mail.OrganizationId).Name + "/" +
Geography.FromIdentity(mail.GeographyId).Name + "), and " +
upwardCount.ToString("#,##0") + " are people in the chain of command who are " +
"organization/geography (" + Organization.FromIdentity (mail.OrganizationId).Name + "/" +
Geography.FromIdentity (mail.GeographyId).Name + "), and " +
upwardCount.ToString ("#,##0") + " are people in the chain of command who are " +
"copied on the mail to know what's happening in the organization. There is normally some overlap between these two groups.\r\n\r\n";
if (declineCount > 1)
{
mailBody += declineCount.ToString("#,##0") +
mailBody += declineCount.ToString ("#,##0") +
" people will not receive the message because they have declined local mail.\r\n\r\n";
}
else if (declineCount == 1)
@@ -158,22 +158,22 @@ namespace Swarmops.Utility.BotCode
: "in " + (mail.ReleaseDateTime - DateTime.Now).Minutes +
" minutes") + ".\r\n";
new MailTransmitter(
new MailTransmitter (
"PirateWeb", "noreply@pirateweb.net",
"Mail resolved: " + mail.Title + " (" + countTotal + " recipients)", mailBody,
Person.FromIdentity(mail.AuthorPersonId), true).Send();
Person.FromIdentity (mail.AuthorPersonId), true).Send();
}
private static People ApplySubscription(People input, int feedId)
private static People ApplySubscription (People input, int feedId)
{
People output = new People();
foreach (Person person in input)
{
if (person.IsSubscribing(feedId))
if (person.IsSubscribing (feedId))
{
output.Add(person);
output.Add (person);
}
}
@@ -181,7 +181,7 @@ namespace Swarmops.Utility.BotCode
}
public static string CreateWelcomeMail(Person person, Organization organization)
public static string CreateWelcomeMail (Person person, Organization organization)
{
// for this person, iterate over all applicable geographies and organizations
@@ -200,7 +200,7 @@ namespace Swarmops.Utility.BotCode
{
foreach (Geography geo in geoLine) // but at the top geography
{
AutoMail autoMail = AutoMail.FromTypeOrganizationAndGeography(AutoMailType.Welcome, org, geo);
AutoMail autoMail = AutoMail.FromTypeOrganizationAndGeography (AutoMailType.Welcome, org, geo);
if (autoMail == null)
{
@@ -212,15 +212,15 @@ namespace Swarmops.Utility.BotCode
try
{
lead = Roles.GetLocalLead(org, geo);
lead = Roles.GetLocalLead (org, geo);
orgMailedLookup[org.Identity] = true;
// Make sure that the chairman doesn't mail at a lower level
// Make sure that the chairman doesn't mail at a lower level
}
catch (ArgumentException)
{
}
if (lead == null && !orgMailedLookup.ContainsKey(org.Identity))
if (lead == null && !orgMailedLookup.ContainsKey (org.Identity))
{
// If we get here, there is a mail template at the highest possible geo for this org, but no local lead.
// That's usually the case with board-centric organizations rather than executive-centric.
@@ -229,7 +229,7 @@ namespace Swarmops.Utility.BotCode
try
{
orgMailedLookup[org.Identity] = true;
lead = Roles.GetChairman(org);
lead = Roles.GetChairman (org);
geoName = "Chairman";
}
catch (ArgumentException)
@@ -257,14 +257,14 @@ namespace Swarmops.Utility.BotCode
welcomemail.pBodyContent = autoMail.Body;
welcomemail.pSubject = autoMail.Title;
OutboundMail newMail = welcomemail.CreateOutboundMail(lead, OutboundMail.PriorityNormal,
org, geo, DateTime.Now.AddMinutes(delay));
newMail.AddRecipient(person.Identity, false);
newMail.SetRecipientCount(1);
OutboundMail newMail = welcomemail.CreateOutboundMail (lead, OutboundMail.PriorityNormal,
org, geo, DateTime.Now.AddMinutes (delay));
newMail.AddRecipient (person.Identity, false);
newMail.SetRecipientCount (1);
newMail.SetResolved();
newMail.SetReadyForPickup();
result += String.Format(" - {0}/{1} by {2} (",
result += String.Format (" - {0}/{1} by {2} (",
org.NameShort, geoName, lead.Canonical);
if (delay == 0)
{
@@ -273,8 +273,8 @@ namespace Swarmops.Utility.BotCode
}
else
{
result += "sending at " + DateTime.Now.AddMinutes(delay).ToString("HH:mm");
delay += 31 + random.Next(52);
result += "sending at " + DateTime.Now.AddMinutes (delay).ToString ("HH:mm");
delay += 31 + random.Next (52);
}
result += ")\r\n";
}
+15 -15
View File
@@ -8,7 +8,7 @@ namespace Swarmops.Utility.BotCode
{
public Dictionary<int, string> OrgColorLookup; // ugly way to transfer data to delegate
[Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)]
[Obsolete ("Too specialized for Swarmops. Plugin or generalize.", true)]
public static void CreateUngPiratUptakeMap()
{
throw new NotImplementedException();
@@ -120,12 +120,12 @@ namespace Swarmops.Utility.BotCode
}*/
public static Color ColorFromAhsb(int a, float h, float s, float b)
public static Color ColorFromAhsb (int a, float h, float s, float b)
{
if (0 == s)
{
return Color.FromArgb(a, Convert.ToInt32(b*255),
Convert.ToInt32(b*255), Convert.ToInt32(b*255));
return Color.FromArgb (a, Convert.ToInt32 (b*255),
Convert.ToInt32 (b*255), Convert.ToInt32 (b*255));
}
float fMax, fMid, fMin;
@@ -142,13 +142,13 @@ namespace Swarmops.Utility.BotCode
fMin = b - (b*s);
}
iSextant = (int) Math.Floor(h/60f);
iSextant = (int) Math.Floor (h/60f);
if (300f <= h)
{
h -= 360f;
}
h /= 60f;
h -= 2f*(float) Math.Floor(((iSextant + 1f)%6f)/2f);
h -= 2f*(float) Math.Floor (((iSextant + 1f)%6f)/2f);
if (0 == iSextant%2)
{
fMid = h*(fMax - fMin) + fMin;
@@ -158,24 +158,24 @@ namespace Swarmops.Utility.BotCode
fMid = fMin - h*(fMax - fMin);
}
iMax = Convert.ToInt32(fMax*255);
iMid = Convert.ToInt32(fMid*255);
iMin = Convert.ToInt32(fMin*255);
iMax = Convert.ToInt32 (fMax*255);
iMid = Convert.ToInt32 (fMid*255);
iMin = Convert.ToInt32 (fMin*255);
switch (iSextant)
{
case 1:
return Color.FromArgb(a, iMid, iMax, iMin);
return Color.FromArgb (a, iMid, iMax, iMin);
case 2:
return Color.FromArgb(a, iMin, iMax, iMid);
return Color.FromArgb (a, iMin, iMax, iMid);
case 3:
return Color.FromArgb(a, iMin, iMid, iMax);
return Color.FromArgb (a, iMin, iMid, iMax);
case 4:
return Color.FromArgb(a, iMid, iMin, iMax);
return Color.FromArgb (a, iMid, iMin, iMax);
case 5:
return Color.FromArgb(a, iMax, iMin, iMid);
return Color.FromArgb (a, iMax, iMin, iMid);
default:
return Color.FromArgb(a, iMax, iMid, iMin);
return Color.FromArgb (a, iMax, iMid, iMin);
}
}
+7 -7
View File
@@ -17,15 +17,15 @@ namespace Swarmops.Utility.BotCode
{
// string rssUrl = String.Format("http://sesam.se/search/?c=m&q={0}&&output=rss", keyword.ToLower());
string rssUrl = String.Format("http://www.frisim.com/rss/?q={0}&k=nyheter", keyword.ToLower());
string rssUrl = String.Format ("http://www.frisim.com/rss/?q={0}&k=nyheter", keyword.ToLower());
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(rssUrl);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create (rssUrl);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
RssReader reader = new RssReader(resp.GetResponseStream());
RssReader reader = new RssReader (resp.GetResponseStream());
try
{
@@ -40,12 +40,12 @@ namespace Swarmops.Utility.BotCode
string title = item.Title;
string mediaName = item.Categories[0].Name;
MediaEntry.CreateFromKeyword(keyword, mediaName, false, url, title, dateTime);
MediaEntry.CreateFromKeyword (keyword, mediaName, false, url, title, dateTime);
}
}
catch (Exception e)
{
throw new ReaderException("feed:" + rssUrl + "Status=" + resp.StatusCode, e);
throw new ReaderException ("feed:" + rssUrl + "Status=" + resp.StatusCode, e);
}
finally
@@ -57,8 +57,8 @@ namespace Swarmops.Utility.BotCode
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
public ReaderException (string message, Exception innerException)
: base (message, innerException)
{
}
}
+3 -3
View File
@@ -11,7 +11,7 @@ namespace Swarmops.Utility.BotCode
private static Dictionary<string, DateTime> feedErrorSignaled = new Dictionary<string, DateTime>();
[Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)]
[Obsolete ("Too specialized for Swarmops. Plugin or generalize.", true)]
public static void Run()
{
/*
@@ -25,8 +25,8 @@ namespace Swarmops.Utility.BotCode
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
public ReaderException (string message, Exception innerException)
: base (message, innerException)
{
}
}
+45 -43
View File
@@ -12,7 +12,8 @@ namespace Swarmops.Utility.BotCode
{
public class PressReleaseChecker
{
[Obsolete("Do not call this function until it's been generalized. Don't delete, though - generalize it.", true)]
[Obsolete ("Do not call this function until it's been generalized. Don't delete, though - generalize it.", true)
]
public static void Run()
{
throw new NotImplementedException();
@@ -25,9 +26,9 @@ namespace Swarmops.Utility.BotCode
*/
}
private static void CheckOneFeed(string readerUrl, string persistAsKey, int orgIdForTemplate)
private static void CheckOneFeed (string readerUrl, string persistAsKey, int orgIdForTemplate)
{
string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey);
string persistenceKey = String.Format ("Pressrelease-Highwater-{0}", persistAsKey);
DateTime highWaterMark = DateTime.MinValue;
@@ -37,7 +38,7 @@ namespace Swarmops.Utility.BotCode
{
string highWaterMarkString = Persistence.Key[persistenceKey];
if (string.IsNullOrEmpty(highWaterMarkString))
if (string.IsNullOrEmpty (highWaterMarkString))
{
//Initialize highwatermark if never used
highWaterMark = DateTime.Now;
@@ -47,19 +48,19 @@ namespace Swarmops.Utility.BotCode
{
try
{
highWaterMark = DateTime.Parse(highWaterMarkString);
highWaterMark = DateTime.Parse (highWaterMarkString);
}
catch (Exception ex)
{
HeartBeater.Instance.SuggestRestart();
throw new Exception(
throw new Exception (
"Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" +
persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " +
DateTime.Now, ex);
}
}
DateTime storedHighWaterMark = highWaterMark;
reader = new RssReader(readerUrl);
reader = new RssReader (readerUrl);
Rss rss = reader.Read();
foreach (RssChannelItem item in rss.Channel.Items)
@@ -67,7 +68,7 @@ namespace Swarmops.Utility.BotCode
// Ignore any items older than the highwater mark.
// Also ignore if older than two days
if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays(-2))
if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays (-2))
{
continue;
}
@@ -81,8 +82,8 @@ namespace Swarmops.Utility.BotCode
if (item.PubDate > storedHighWaterMark)
{
Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(2).ToString();
storedHighWaterMark = item.PubDate.AddMinutes(2);
Persistence.Key[persistenceKey] = item.PubDate.AddMinutes (2).ToString();
storedHighWaterMark = item.PubDate.AddMinutes (2);
// Verify that it was written correctly to database. This is defensive programming to avoid a mail flood,
// in case we can't write to the database for some reason.
@@ -90,18 +91,18 @@ namespace Swarmops.Utility.BotCode
try
{
newStoredHighWaterString = Persistence.Key[persistenceKey];
DateTime temp = DateTime.Parse(newStoredHighWaterString);
DateTime temp = DateTime.Parse (newStoredHighWaterString);
}
catch (Exception ex)
{
throw new Exception(
throw new Exception (
"Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" +
newStoredHighWaterString + "'", ex);
}
if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate)
if (DateTime.Parse (Persistence.Key[persistenceKey]) < item.PubDate)
{
throw new Exception(
throw new Exception (
"Unable to commit new highwater mark to database in PressReleaseChecker.Run()");
}
}
@@ -123,23 +124,23 @@ namespace Swarmops.Utility.BotCode
{
try
{
MediaCategory mediaCategory = MediaCategory.FromName(category.Name);
categories.Add(mediaCategory);
MediaCategory mediaCategory = MediaCategory.FromName (category.Name);
categories.Add (mediaCategory);
if (category.Name.StartsWith("International"))
if (category.Name.StartsWith ("International"))
{
international = true;
}
}
catch (Exception)
{
ExceptionMail.Send(
new Exception("Unrecognized media category in press release: " + category.Name));
ExceptionMail.Send (
new Exception ("Unrecognized media category in press release: " + category.Name));
}
}
}
string mailText = Blog2Mail(item.Content);
string mailText = Blog2Mail (item.Content);
// Create recipient list of relevant reporters
@@ -151,7 +152,7 @@ namespace Swarmops.Utility.BotCode
}
else
{
reporters = Reporters.FromMediaCategories(categories);
reporters = Reporters.FromMediaCategories (categories);
}
// Add officers if not int'l
@@ -161,7 +162,7 @@ namespace Swarmops.Utility.BotCode
if (!international)
{
int[] officerIds = Roles.GetAllDownwardRoles(1, 1);
int[] officerIds = Roles.GetAllDownwardRoles (1, 1);
foreach (int officerId in officerIds)
{
officerLookup[officerId] = true;
@@ -176,13 +177,13 @@ namespace Swarmops.Utility.BotCode
// Send press release
//TODO: hardcoded geo ... using World
Organization org = Organization.FromIdentity(orgIdForTemplate);
Organization org = Organization.FromIdentity (orgIdForTemplate);
Geography geo = Geography.Root;
PressReleaseMail pressreleasemail = new PressReleaseMail();
pressreleasemail.pSubject = item.Title;
pressreleasemail.pDate = DateTime.Now;
pressreleasemail.pBodyContent = Blog2Mail(item.Content);
pressreleasemail.pBodyContent = Blog2Mail (item.Content);
pressreleasemail.pOrgName = org.MailPrefixInherited;
if (allReporters)
{
@@ -194,42 +195,43 @@ namespace Swarmops.Utility.BotCode
}
else
{
pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories);
pressreleasemail.pPostedToCategories =
PressReleaseMail.GetConcatenatedCategoryString (categories);
}
OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService,
OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail (MailAuthorType.PressService,
OutboundMail.PriorityHighest, org, geo);
int recipientCount = 0;
foreach (Reporter recipient in reporters)
{
if (!Formatting.ValidateEmailFormat(recipient.Email))
if (!Formatting.ValidateEmailFormat (recipient.Email))
{
continue;
}
++recipientCount;
newMail.AddRecipient(recipient);
newMail.AddRecipient (recipient);
}
foreach (int key in officerLookup.Keys)
{
Person recipient = Person.FromIdentity(key);
if (!Formatting.ValidateEmailFormat(recipient.Mail))
Person recipient = Person.FromIdentity (key);
if (!Formatting.ValidateEmailFormat (recipient.Mail))
{
continue;
}
++recipientCount;
newMail.AddRecipient(recipient, true);
newMail.AddRecipient (recipient, true);
}
newMail.SetRecipientCount(recipientCount);
newMail.SetRecipientCount (recipientCount);
newMail.SetResolved();
newMail.SetReadyForPickup();
}
}
catch (Exception ex)
{
ExceptionMail.Send(
new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
ExceptionMail.Send (
new Exception ("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
}
finally
{
@@ -237,17 +239,17 @@ namespace Swarmops.Utility.BotCode
}
}
private static string Blog2Mail(string text)
private static string Blog2Mail (string text)
{
return text.
Replace("<h3>", "<h2>").
Replace("</h3>", "</h2>").
Replace("&#8220;", "\"").
Replace("&#8221;", "\"").
Replace("&#8216;", "'").
Replace("&#8217;", "'").
Replace("&#8212;", "--").
Replace("&#8230;", "...");
Replace ("<h3>", "<h2>").
Replace ("</h3>", "</h2>").
Replace ("&#8220;", "\"").
Replace ("&#8221;", "\"").
Replace ("&#8216;", "'").
Replace ("&#8217;", "'").
Replace ("&#8212;", "--").
Replace ("&#8230;", "...");
}
}
}
+63 -63
View File
@@ -16,18 +16,18 @@ namespace Swarmops.Utility.BotCode
// This function should basically not be called. Any time it is called means a security
// risk.
public static string ExportMemberList(int organizationIdRoot, DateTime membersAfter, DateTime membersBefore)
public static string ExportMemberList (int organizationIdRoot, DateTime membersAfter, DateTime membersBefore)
{
Organizations orgs = Organization.FromIdentity(organizationIdRoot).GetTree();
Organizations orgs = Organization.FromIdentity (organizationIdRoot).GetTree();
StringBuilder result = new StringBuilder();
result.Append(
String.Format("All members joining tree of " + orgs[0].Name + " between " +
membersAfter.ToString("yyyy-MMM-dd") + " and " + membersBefore.ToString("yyyy-MMM-dd") +
"\r\n\r\n"));
result.Append (
String.Format ("All members joining tree of " + orgs[0].Name + " between " +
membersAfter.ToString ("yyyy-MMM-dd") + " and " + membersBefore.ToString ("yyyy-MMM-dd") +
"\r\n\r\n"));
membersAfter = membersAfter.Date;
membersBefore = membersBefore.AddDays(1).Date;
membersBefore = membersBefore.AddDays (1).Date;
foreach (Organization org in orgs)
{
@@ -44,28 +44,28 @@ namespace Swarmops.Utility.BotCode
{
if (membership.MemberSince > membersAfter && membership.MemberSince < membersBefore)
{
relevantPersonIds.Add(membership.PersonId);
relevantPersonIds.Add (membership.PersonId);
}
}
People listMembers = People.FromIdentities(relevantPersonIds.ToArray());
People listMembers = People.FromIdentities (relevantPersonIds.ToArray());
List<string> csvResultList = new List<string>();
foreach (Person person in listMembers)
{
csvResultList.Add(
String.Format("{0},{1},{2},{3:yyyy-MMM-dd},{4}",
csvResultList.Add (
String.Format ("{0},{1},{2},{3:yyyy-MMM-dd},{4}",
person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate,
person.IsMale ? "Male" : "Female"));
}
string[] csvResults = csvResultList.ToArray();
Array.Sort(csvResults);
Array.Sort (csvResults);
orgSummary += String.Join("\r\n", csvResults) + "\r\n\r\n";
orgSummary += String.Join ("\r\n", csvResults) + "\r\n\r\n";
result.Append(orgSummary);
result.Append (orgSummary);
}
}
@@ -91,12 +91,12 @@ namespace Swarmops.Utility.BotCode
}
[Obsolete("Generalize and localize this function.", true)]
[Obsolete ("Generalize and localize this function.", true)]
public static void RemindExpiriesMail()
{
// Get expiring
Console.WriteLine("Inside RemindExpiriesMail()");
Console.WriteLine ("Inside RemindExpiriesMail()");
Organizations orgs = Organizations.GetAll();
@@ -104,14 +104,14 @@ namespace Swarmops.Utility.BotCode
Dictionary<string, int> dateLookup = new Dictionary<string, int>();
DateTime lowerBound = DateTime.Today;
DateTime upperBound = lowerBound.AddDays(31);
DateTime upperBound = lowerBound.AddDays (31);
List<string> failedReminders = new List<string>();
int weekDayInteger = (int) DateTime.Today.DayOfWeek;
foreach (Organization org in orgs)
{
Memberships memberships = Memberships.GetExpiring(org, lowerBound, upperBound);
Memberships memberships = Memberships.GetExpiring (org, lowerBound, upperBound);
foreach (Membership membership in memberships)
{
@@ -122,47 +122,47 @@ namespace Swarmops.Utility.BotCode
try
{
Console.Write("Reminding " + membership.Person.Canonical + " about " +
membership.Organization.Name + ".");
SendReminderMail(membership);
Console.Write(".");
PWLog.Write(PWLogItem.Person, membership.PersonId,
Console.Write ("Reminding " + membership.Person.Canonical + " about " +
membership.Organization.Name + ".");
SendReminderMail (membership);
Console.Write (".");
PWLog.Write (PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
Console.Write(".");
Console.Write (".");
string dateString = membership.Expires.ToString("yyyy-MM-dd");
if (!dateLookup.ContainsKey(dateString))
string dateString = membership.Expires.ToString ("yyyy-MM-dd");
if (!dateLookup.ContainsKey (dateString))
{
dateLookup[dateString] = 0;
}
dateLookup[dateString]++;
Console.WriteLine(" done.");
Console.WriteLine (" done.");
}
catch (Exception x)
{
string logText = "FAILED sending mail to " + membership.Person.Mail +
" for reminder of pending renewal in " + membership.Organization.Name + ".";
failedReminders.Add(membership.Person.Canonical);
PWLog.Write(PWLogItem.Person, membership.PersonId,
failedReminders.Add (membership.Person.Canonical);
PWLog.Write (PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
logText, string.Empty);
ExceptionMail.Send(new Exception(logText, x));
ExceptionMail.Send (new Exception (logText, x));
}
}
}
string notifyBody = String.Format("Sending renewal reminders to {0} people:\r\n\r\n", personLookup.Count);
Console.WriteLine("Sending renewal reminders to {0} people", personLookup.Count);
string notifyBody = String.Format ("Sending renewal reminders to {0} people:\r\n\r\n", personLookup.Count);
Console.WriteLine ("Sending renewal reminders to {0} people", personLookup.Count);
List<string> dateSummary = new List<string>();
int total = 0;
foreach (string dateString in dateLookup.Keys)
{
dateSummary.Add(string.Format("{0}: {1,5}", dateString, dateLookup[dateString]));
dateSummary.Add (string.Format ("{0}: {1,5}", dateString, dateLookup[dateString]));
total += dateLookup[dateString];
}
@@ -171,25 +171,25 @@ namespace Swarmops.Utility.BotCode
foreach (string dateString in dateSummary)
{
notifyBody += dateString + "\r\n";
Console.WriteLine(dateString);
Console.WriteLine (dateString);
}
notifyBody += string.Format("Total sent: {0,5}\r\n\r\n", total);
Console.WriteLine("Total sent: {0,5}\r\n\r\n", total);
notifyBody += string.Format ("Total sent: {0,5}\r\n\r\n", total);
Console.WriteLine ("Total sent: {0,5}\r\n\r\n", total);
notifyBody += "FAILED reminders:\r\n";
Console.WriteLine("FAILED reminders:");
Console.WriteLine ("FAILED reminders:");
foreach (string failed in failedReminders)
{
notifyBody += failed + "\r\n";
Console.WriteLine(failed);
Console.WriteLine (failed);
}
if (failedReminders.Count == 0)
{
notifyBody += "none.\r\n";
Console.WriteLine("none.");
Console.WriteLine ("none.");
}
/* no. just no. we should do a global search for "FromIdentity(1)"
@@ -205,7 +205,7 @@ namespace Swarmops.Utility.BotCode
foreach (Organization organization in organizations)
{
Memberships memberships = Memberships.GetExpired(organization);
Memberships memberships = Memberships.GetExpired (organization);
// Mail each expiring member
foreach (Membership membership in memberships)
@@ -222,10 +222,10 @@ namespace Swarmops.Utility.BotCode
foreach (BasicPersonRole basicRole in authority.LocalPersonRoles)
{
PersonRole personRole = PersonRole.FromBasic(basicRole);
PersonRole personRole = PersonRole.FromBasic (basicRole);
if (personRole.OrganizationId == membership.OrganizationId)
{
PWEvents.CreateEvent(EventSource.PirateBot, EventType.DeletedRole, person.Identity,
PWEvents.CreateEvent (EventSource.PirateBot, EventType.DeletedRole, person.Identity,
personRole.OrganizationId, personRole.GeographyId, person.Identity,
(int) personRole.Type,
string.Empty);
@@ -241,7 +241,7 @@ namespace Swarmops.Utility.BotCode
{
if (personMembership.Expires <= DateTime.Now.Date)
{
membershipsToDelete.Add(personMembership);
membershipsToDelete.Add (personMembership);
}
}
@@ -255,7 +255,7 @@ namespace Swarmops.Utility.BotCode
{
membershipsIds += "," + personMembership.MembershipId;
}
membershipsIds = membershipsIds.Substring(1);
membershipsIds = membershipsIds.Substring (1);
string expiredMemberships = "";
foreach (Membership personMembership in membershipsToDelete)
{
@@ -265,7 +265,7 @@ namespace Swarmops.Utility.BotCode
}
}
expiredMemberships += ". ";
expiredmail.pMemberships = expiredMemberships.Substring(2).Trim();
expiredmail.pMemberships = expiredMemberships.Substring (2).Trim();
}
//TODO: URL for renewal, recieving end of this is NOT yet implemented...
@@ -273,13 +273,13 @@ namespace Swarmops.Utility.BotCode
string tokenBase = person.PasswordHash + "-" + membership.Expires.Year;
string stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" +
person.Identity +
"&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8) +
"&SecHash=" + SHA1.Hash (tokenBase).Replace (" ", "").Substring (0, 8) +
"&MID=" + membershipsIds;
expiredmail.pStdRenewLink = stdLink;
expiredmail.pOrgName = organization.MailPrefixInherited;
person.SendNotice(expiredmail, organization.Identity);
person.SendNotice (expiredmail, organization.Identity);
person.DeleteSubscriptionData();
@@ -291,21 +291,21 @@ namespace Swarmops.Utility.BotCode
{
orgIdString += " " + personMembership.OrganizationId;
personMembership.Terminate(EventSource.PirateBot, null, "Member churned in housekeeping.");
personMembership.Terminate (EventSource.PirateBot, null, "Member churned in housekeeping.");
}
}
}
}
}
[Obsolete("Generalize and localize this functionality.", true)]
internal static void RemindExpiries(DateTime dateExpiry)
[Obsolete ("Generalize and localize this functionality.", true)]
internal static void RemindExpiries (DateTime dateExpiry)
{
Organizations orgs = Organizations.GetAll();
foreach (Organization org in orgs)
{
Memberships memberships = Memberships.GetExpiring(org, dateExpiry);
Memberships memberships = Memberships.GetExpiring (org, dateExpiry);
// Mail each expiring member
@@ -313,23 +313,23 @@ namespace Swarmops.Utility.BotCode
{
try
{
SendReminderMail(membership);
PWLog.Write(PWLogItem.Person, membership.PersonId,
SendReminderMail (membership);
PWLog.Write (PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
}
catch (Exception ex)
{
ExceptionMail.Send(
new Exception("Failed to create reminder mail for person " + membership.PersonId, ex));
ExceptionMail.Send (
new Exception ("Failed to create reminder mail for person " + membership.PersonId, ex));
}
}
}
}
[Obsolete("Requires move to plugin or similar, or at least rearch into a hook", true)]
internal static void RemindExpiriesSms(DateTime dateExpiry, string message)
[Obsolete ("Requires move to plugin or similar, or at least rearch into a hook", true)]
internal static void RemindExpiriesSms (DateTime dateExpiry, string message)
{
throw new NotImplementedException();
@@ -371,13 +371,13 @@ namespace Swarmops.Utility.BotCode
}
internal static bool SendReminderSms(Person person, string message)
internal static bool SendReminderSms (Person person, string message)
{
bool result = false;
try
{
person.SendPhoneMessage(message);
person.SendPhoneMessage (message);
result = true;
}
// ignore exceptions
@@ -388,8 +388,8 @@ namespace Swarmops.Utility.BotCode
return result;
}
[Obsolete("Generalize and localize this function.", true)]
public static void SendReminderMail(Membership membership)
[Obsolete ("Generalize and localize this function.", true)]
public static void SendReminderMail (Membership membership)
{
/*
// First, determine the organization template to use. Prioritize a long ancestry.
@@ -493,7 +493,7 @@ namespace Swarmops.Utility.BotCode
public static void TimeoutVolunteers()
{
Volunteers volunteers = Volunteers.GetOpen();
DateTime threshold = DateTime.Today.AddDays(-30);
DateTime threshold = DateTime.Today.AddDays (-30);
foreach (Volunteer volunteer in volunteers)
{
@@ -510,7 +510,7 @@ namespace Swarmops.Utility.BotCode
"Volunteer Timed Out: [" + volunteer.Geography.Name + "]",
String.Empty, officers, true).Send(); */
volunteer.Close("Timed out");
volunteer.Close ("Timed out");
}
}
}
+5 -5
View File
@@ -15,9 +15,9 @@ namespace Swarmops.Utility.BotCode
string lastRun = Persistence.Key["LastSalaryRun"];
string expectedLastRun = today.ToString("yyyyMM", CultureInfo.InvariantCulture);
string expectedLastRun = today.ToString ("yyyyMM", CultureInfo.InvariantCulture);
if (lastRun != null && String.Compare(lastRun, expectedLastRun) >= 0)
if (lastRun != null && String.Compare (lastRun, expectedLastRun) >= 0)
{
// nothing to do, return
@@ -29,14 +29,14 @@ namespace Swarmops.Utility.BotCode
// Process the payroll for all organizations. Assume payday is 25th.
Payroll payroll = Payroll.GetAll();
DateTime payday = new DateTime(today.Year, today.Month, 25);
DateTime payday = new DateTime (today.Year, today.Month, 25);
Dictionary<int, double> salariesTotalPerBudget = new Dictionary<int, double>();
foreach (PayrollItem payrollItem in payroll)
{
Salary salary = Salary.Create(payrollItem, payday);
PWEvents.CreateEvent(EventSource.PirateBot, EventType.SalaryCreated, 0, payrollItem.OrganizationId,
Salary salary = Salary.Create (payrollItem, payday);
PWEvents.CreateEvent (EventSource.PirateBot, EventType.SalaryCreated, 0, payrollItem.OrganizationId,
0, payrollItem.Person.Identity, salary.Identity, string.Empty);
}
}
+23 -23
View File
@@ -38,19 +38,19 @@ namespace Swarmops.Utility.BotCode
//
// We use this translation later as we use indexes as identities in the preference matrix.
Console.Write("Creating list of candidates and index lookup...");
Console.Write ("Creating list of candidates and index lookup...");
this.candidateIds = new List<int>();
this.indexOfCandidateId = new Dictionary<int, int>();
int index = 0;
foreach (MeetingElectionCandidate candidate in Candidates)
{
this.candidateIds.Add(candidate.Identity);
this.candidateIds.Add (candidate.Identity);
this.indexOfCandidateId[candidate.Identity] = index;
index++;
}
Console.WriteLine(" done.");
Console.WriteLine (" done.");
}
@@ -67,15 +67,15 @@ namespace Swarmops.Utility.BotCode
// checked off (as they were not voted for).
this.preferenceXtoY = new int[this.candidateIds.Count, this.candidateIds.Count];
// huuuuuge matrix for 1000+ candidates, zero inited
// huuuuuge matrix for 1000+ candidates, zero inited
int count = 1;
Console.WriteLine("Calculating raw preference matrix.");
Console.WriteLine ("Calculating raw preference matrix.");
foreach (MeetingElectionVote vote in Votes)
{
Console.Write("\r - vote {0:D5} of {1:D5}...", count, Votes.Count);
Console.Write ("\r - vote {0:D5} of {1:D5}...", count, Votes.Count);
Dictionary<int, bool> candidateIdSeen = new Dictionary<int, bool>();
int[] voteCandidateIds = vote.SelectedCandidateIdsInOrder;
@@ -101,7 +101,7 @@ namespace Swarmops.Utility.BotCode
foreach (int candidateId in this.candidateIds)
{
if (!candidateIdSeen.ContainsKey(candidateId))
if (!candidateIdSeen.ContainsKey (candidateId))
{
// Not on vote, so inferior to all candidates on the vote
@@ -116,7 +116,7 @@ namespace Swarmops.Utility.BotCode
count++;
}
Console.WriteLine(" done.");
Console.WriteLine (" done.");
}
@@ -130,11 +130,11 @@ namespace Swarmops.Utility.BotCode
// First part of magic. Establish the direction of pairwise defeats. I think.
Console.WriteLine("Calculating link strengths.");
Console.WriteLine ("Calculating link strengths.");
for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++)
{
Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
Console.Write ("\r - Step 1: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
for (int innerIndex = 0; innerIndex < this.candidateIds.Count; innerIndex++)
{
@@ -151,13 +151,13 @@ namespace Swarmops.Utility.BotCode
}
}
Console.WriteLine(" done.");
Console.WriteLine (" done.");
// Second part of magic, an O(n^3) algorithm. In the famous words of Alfred E. Neuman: Yecch!
for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++)
{
Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
Console.Write ("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
for (int middleIndex = 0; middleIndex < this.candidateIds.Count; middleIndex++)
{
@@ -174,20 +174,20 @@ namespace Swarmops.Utility.BotCode
}
this.linkStrengthXtoY[middleIndex, innerIndex] =
Math.Max(this.linkStrengthXtoY[middleIndex, innerIndex],
Math.Min(this.linkStrengthXtoY[middleIndex, outerIndex],
Math.Max (this.linkStrengthXtoY[middleIndex, innerIndex],
Math.Min (this.linkStrengthXtoY[middleIndex, outerIndex],
this.linkStrengthXtoY[outerIndex, innerIndex]));
}
}
}
Console.WriteLine(" done.");
Console.WriteLine (" done.");
}
private void AssembleFinalOrder()
{
Console.WriteLine("Assembling final list.");
Console.WriteLine ("Assembling final list.");
MeetingElectionCandidates result = new MeetingElectionCandidates();
@@ -198,13 +198,13 @@ namespace Swarmops.Utility.BotCode
while (candidatesRemaining > 0)
{
Console.Write("\r - remaining: {0:D4}", candidatesRemaining);
Console.Write ("\r - remaining: {0:D4}", candidatesRemaining);
// Find the first nontaken candidate
int winningCandidateIndex = 0;
while (candidateAdded.ContainsKey(winningCandidateIndex))
while (candidateAdded.ContainsKey (winningCandidateIndex))
{
winningCandidateIndex++;
}
@@ -223,7 +223,7 @@ namespace Swarmops.Utility.BotCode
compareCandidateIndex < this.candidateIds.Count;
compareCandidateIndex++)
{
if (candidateAdded.ContainsKey(compareCandidateIndex))
if (candidateAdded.ContainsKey (compareCandidateIndex))
{
continue;
}
@@ -244,21 +244,21 @@ namespace Swarmops.Utility.BotCode
// We have the winning candidate among the not-yet-ranked candidates:
MeetingElectionCandidate candidate =
MeetingElectionCandidate.FromIdentity(this.candidateIds[winningCandidateIndex]);
MeetingElectionCandidate.FromIdentity (this.candidateIds[winningCandidateIndex]);
candidateAdded[winningCandidateIndex] = true;
result.Add(candidate);
result.Add (candidate);
candidatesRemaining--;
count++;
}
FinalOrder = result;
Console.WriteLine(", done.");
Console.WriteLine (", done.");
}
public int GetCandidateDistance(int finalOrderIndex)
public int GetCandidateDistance (int finalOrderIndex)
{
// Gets the distance, in preference counts, between candidate [finalOrderIndex] and candidate [finalOrderIndex+1].
// This is purely a diagnostic function and does not contribute to the results calculations.
+2 -2
View File
@@ -4,10 +4,10 @@ namespace Swarmops.Utility.BotCode
{
public class TurnaroundTracker
{
[Obsolete("This is dependent on a specific support system. Should move to plugin.", true)]
[Obsolete ("This is dependent on a specific support system. Should move to plugin.", true)]
public static void Run()
{
throw new NotImplementedException("Disabled for Swarmops");
throw new NotImplementedException ("Disabled for Swarmops");
/*
const string persistenceKey = "PPSE-LastSupportDeltaId";
+2 -2
View File
@@ -4,11 +4,11 @@ namespace Swarmops.Utility.BotCode
{
public static void Run()
{
BotLog.Write(1, "UpdateStatsCache", "Entering (obsoleted does nothing");
BotLog.Write (1, "UpdateStatsCache", "Entering (obsoleted does nothing");
UpdateBallotDistroData();
BotLog.Write(1, "UpdateStatsCache", "Exiting");
BotLog.Write (1, "UpdateStatsCache", "Exiting");
}
private static void UpdateBallotDistroData()