diff --git a/Backend/CommsTransmitter.cs b/Backend/CommsTransmitter.cs index ef4ada4b..68903231 100644 --- a/Backend/CommsTransmitter.cs +++ b/Backend/CommsTransmitter.cs @@ -28,7 +28,7 @@ namespace Swarmops.Backend ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; - PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); + PayloadEnvelope envelope = PayloadEnvelope.FromXml (comm.PayloadXml); comm.StartTransmission(); @@ -36,12 +36,12 @@ namespace Swarmops.Backend { try { - transmitter.Transmit(envelope, recipient.Person); + transmitter.Transmit (envelope, recipient.Person); recipient.CloseSuccess(); } catch (OutboundCommTransmitException e) { - recipient.CloseFailed(e.Description); + recipient.CloseFailed (e.Description); } } diff --git a/Backend/Program.cs b/Backend/Program.cs index b3e51845..59725aa5 100644 --- a/Backend/Program.cs +++ b/Backend/Program.cs @@ -19,19 +19,19 @@ namespace Swarmops.Backend private const string heartbeatFile = "/var/run/swarmops/backend/heartbeat.txt"; private static bool testMode; - private static void Main(string[] args) + private static void Main (string[] args) { testMode = false; UnixSignal[] killSignals = { - new UnixSignal(Signum.SIGINT), - new UnixSignal(Signum.SIGTERM) + new UnixSignal (Signum.SIGINT), + new UnixSignal (Signum.SIGTERM) }; - BotLog.Write(0, "MainCycle", string.Empty); - BotLog.Write(0, "MainCycle", "-----------------------------------------------"); - BotLog.Write(0, "MainCycle", string.Empty); + BotLog.Write (0, "MainCycle", string.Empty); + BotLog.Write (0, "MainCycle", "-----------------------------------------------"); + BotLog.Write (0, "MainCycle", string.Empty); if (args.Length > 0) { @@ -59,20 +59,20 @@ namespace Swarmops.Backend OnMidnight(); */ - Console.WriteLine("Testing database access..."); + Console.WriteLine ("Testing database access..."); - Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name); - Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash); + Console.WriteLine (SwarmDb.GetDatabaseForReading().GetPerson (1).Name); + Console.WriteLine (SwarmDb.GetDatabaseForReading().GetPerson (1).PasswordHash); - Console.WriteLine("Creating OutboundComm..."); + Console.WriteLine ("Creating OutboundComm..."); - OutboundComm.CreateNotification(null, NotificationResource.System_Startup); + OutboundComm.CreateNotification (null, NotificationResource.System_Startup); - Console.WriteLine("Transmitting..."); + Console.WriteLine ("Transmitting..."); OutboundComms comms = OutboundComms.GetOpen(); - Console.WriteLine("{0} open items in outbound comms.", comms.Count); + Console.WriteLine ("{0} open items in outbound comms.", comms.Count); foreach (OutboundComm comm in comms) { @@ -84,29 +84,29 @@ namespace Swarmops.Backend ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; - PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); + PayloadEnvelope envelope = PayloadEnvelope.FromXml (comm.PayloadXml); foreach (OutboundCommRecipient recipient in recipients) { - transmitter.Transmit(envelope, recipient.Person); + transmitter.Transmit (envelope, recipient.Person); } } - Console.Write("\r\nAll tests run. Waiting for mail queue to flush... "); + Console.Write ("\r\nAll tests run. Waiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { - Thread.Sleep(50); + Thread.Sleep (50); } - Console.WriteLine("done."); - BotLog.Write(0, "MainCycle", "Exiting self-tests"); + Console.WriteLine ("done."); + BotLog.Write (0, "MainCycle", "Exiting self-tests"); return; } if (args[0].ToLower() == "console") { - Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n"); + Console.WriteLine ("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n"); // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- @@ -115,21 +115,21 @@ namespace Swarmops.Backend // ----------------------- INSERT ANY ONE-OFF ACTIONS HERE ------------------------- - Console.Write("\r\nWaiting for mail queue to flush... "); + Console.Write ("\r\nWaiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { - Thread.Sleep(50); + Thread.Sleep (50); } - Console.WriteLine("done."); + Console.WriteLine ("done."); return; } if (args[0].ToLower() == "rsm") { - Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS"); + Console.WriteLine ("Testing character encoding: räksmörgås RÄKSMÖRGÅS"); return; } } @@ -147,11 +147,11 @@ namespace Swarmops.Backend smtpClient.Credentials = null; // mono bug smtpClient.Send (message);*/ - Console.WriteLine(" * Swarmops Backend starting"); + Console.WriteLine (" * Swarmops Backend starting"); - BotLog.Write(0, "MainCycle", "Backend STARTING"); + BotLog.Write (0, "MainCycle", "Backend STARTING"); - OutboundComm.CreateNotification(null, NotificationResource.System_Startup); + OutboundComm.CreateNotification (null, NotificationResource.System_Startup); // Checking for schemata upgrade @@ -174,7 +174,7 @@ namespace Swarmops.Backend while (!exitFlag) // exit is handled by signals handling at end of loop { - BotLog.Write(0, "MainCycle", "Cycle Start"); + BotLog.Write (0, "MainCycle", "Cycle Start"); cycleStartTime = DateTime.Now; @@ -219,7 +219,7 @@ namespace Swarmops.Backend // so that failure in one should not stop the others from running. This particular // code should never run. - ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true); + ExceptionMail.Send (new Exception ("Failed in swarmops-backend main loop", e), true); } lastSecond = cycleStartTime.Second; @@ -228,23 +228,23 @@ namespace Swarmops.Backend // Wait for a maximum of ten seconds - while (DateTime.Now < cycleStartTime.AddSeconds(10) && !exitFlag) + while (DateTime.Now < cycleStartTime.AddSeconds (10) && !exitFlag) { // block until a SIGINT or SIGTERM signal is generated, or one second has passed. - int signalIndex = UnixSignal.WaitAny(killSignals, 1000); + int signalIndex = UnixSignal.WaitAny (killSignals, 1000); if (signalIndex < 1000) { exitFlag = true; - Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting"); - BotLog.Write(0, "MainCycle", + Console.WriteLine ("Caught signal " + killSignals[signalIndex].Signum + ", exiting"); + BotLog.Write (0, "MainCycle", "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend"); } } } - Console.WriteLine(" * Swarmops Backend stopping"); - BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices"); + Console.WriteLine (" * Swarmops Backend stopping"); + BotLog.Write (0, "MainCycle", "BACKEND EXITING, sending backend-termination notices"); /* if (HeartBeater.Instance.WasKilled) @@ -253,7 +253,7 @@ namespace Swarmops.Backend ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false); }*/ - BotLog.Write(0, "MainCycle", "...done"); + BotLog.Write (0, "MainCycle", "...done"); /* while (!MailTransmitter.CanExit) @@ -261,14 +261,14 @@ namespace Swarmops.Backend System.Threading.Thread.Sleep(50); }*/ - Thread.Sleep(2000); + Thread.Sleep (2000); } private static void OnEveryTenSeconds() { try { - BotLog.Write(0, "MainCycle", "Ten-second entry"); + BotLog.Write (0, "MainCycle", "Ten-second entry"); CommsTransmitter.Run(); @@ -280,7 +280,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -291,7 +291,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -302,14 +302,14 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } - BotLog.Write(0, "MainCycle", "Ten-second exit"); + BotLog.Write (0, "MainCycle", "Ten-second exit"); } catch (Exception e) { - ExceptionMail.Send(e, true); + ExceptionMail.Send (e, true); } } @@ -317,11 +317,11 @@ namespace Swarmops.Backend { try { - BotLog.Write(0, "MainCycle", "One-minute process (empty)"); + BotLog.Write (0, "MainCycle", "One-minute process (empty)"); } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } // empty } @@ -331,7 +331,7 @@ namespace Swarmops.Backend { try { - BotLog.Write(0, "MainCycle", "Five-minute entry"); + BotLog.Write (0, "MainCycle", "Five-minute entry"); try { @@ -342,7 +342,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -354,7 +354,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -366,7 +366,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -381,7 +381,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -393,7 +393,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -405,7 +405,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -417,16 +417,16 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } - BotLog.Write(0, "MainCycle", "Five-minute exit"); + BotLog.Write (0, "MainCycle", "Five-minute exit"); } catch (Exception e) { - ExceptionMail.Send(e, true); - TestTrace(e.ToString()); + ExceptionMail.Send (e, true); + TestTrace (e.ToString()); } } @@ -436,7 +436,7 @@ namespace Swarmops.Backend DateTime startTime = DateTime.Now; try { - BotLog.Write(0, "MainCycle", "One-hour entry"); + BotLog.Write (0, "MainCycle", "One-hour entry"); try { @@ -446,7 +446,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -457,7 +457,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -468,7 +468,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -479,7 +479,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -490,7 +490,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -501,14 +501,14 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } - BotLog.Write(0, "MainCycle", "One-hour exit"); + BotLog.Write (0, "MainCycle", "One-hour exit"); } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } } @@ -516,7 +516,7 @@ namespace Swarmops.Backend { try { - BotLog.Write(0, "MainCycle", "Midnight entry"); + BotLog.Write (0, "MainCycle", "Midnight entry"); try { @@ -529,7 +529,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -540,7 +540,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -551,7 +551,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -562,7 +562,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -573,7 +573,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -584,7 +584,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -595,25 +595,25 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } - BotLog.Write(0, "MainCycle", "Midnight exit"); + BotLog.Write (0, "MainCycle", "Midnight exit"); } catch (Exception e) { - ExceptionMail.Send(e, true); - TestTrace(e.ToString()); + ExceptionMail.Send (e, true); + TestTrace (e.ToString()); } } private static void OnNoon() { - BotLog.Write(0, "MainCycle", "Noon entry"); + BotLog.Write (0, "MainCycle", "Noon entry"); try { - if (!PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) + if (!PilotInstallationIds.IsPilot (PilotInstallationIds.PiratePartySE)) { // PPSE is still running PW4 code for this, so don't run for PPSE @@ -630,7 +630,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -644,7 +644,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -655,7 +655,7 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } try @@ -666,11 +666,11 @@ namespace Swarmops.Backend } catch (Exception e) { - TraceAndReport(e); + TraceAndReport (e); } - BotLog.Write(0, "MainCycle", "Noon exit"); + BotLog.Write (0, "MainCycle", "Noon exit"); } private static void OnTuesdayMorning() @@ -683,26 +683,26 @@ namespace Swarmops.Backend } catch (Exception e) { - ExceptionMail.Send(e, true); + ExceptionMail.Send (e, true); if (testMode) { - Console.WriteLine(e.ToString()); + Console.WriteLine (e.ToString()); } } } - private static void TraceAndReport(Exception e) + private static void TraceAndReport (Exception e) { - TestTrace(" failed.\r\n"); - ExceptionMail.Send(e, true); - TestTrace(e.ToString()); + TestTrace (" failed.\r\n"); + ExceptionMail.Send (e, true); + TestTrace (e.ToString()); } - private static void TestTrace(string message) + private static void TestTrace (string message) { if (testMode) { - Console.Write(message); + Console.Write (message); } } } diff --git a/Backend/Properties/AssemblyInfo.cs b/Backend/Properties/AssemblyInfo.cs index 4b0d447e..40103ab0 100644 --- a/Backend/Properties/AssemblyInfo.cs +++ b/Backend/Properties/AssemblyInfo.cs @@ -5,24 +5,24 @@ using System.Runtime.InteropServices; // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Swarmops Backend")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Disorganized")] -[assembly: AssemblyProduct("Swarmops")] -[assembly: AssemblyCopyright("In Public Domain")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("Swarmops Backend")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("Disorganized")] +[assembly: AssemblyProduct ("Swarmops")] +[assembly: AssemblyCopyright ("In Public Domain")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("948b695d-d8cc-442c-93a1-1e8928c1a5e8")] +[assembly: Guid ("948b695d-d8cc-442c-93a1-1e8928c1a5e8")] // Version information for an assembly consists of the following four values: // @@ -35,5 +35,5 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] \ No newline at end of file diff --git a/Basic/Config.cs b/Basic/Config.cs index 8fc48a31..b8eb7c8a 100644 --- a/Basic/Config.cs +++ b/Basic/Config.cs @@ -11,12 +11,12 @@ namespace Swarmops.Basic { string portString = ConfigurationManager.AppSettings["SmtpPort"]; - if (String.IsNullOrEmpty(portString)) + if (String.IsNullOrEmpty (portString)) { return 587; } - return Int32.Parse(portString); + return Int32.Parse (portString); } } @@ -26,7 +26,7 @@ namespace Swarmops.Basic { string smtpHost = ConfigurationManager.AppSettings["SmtpHost"]; - if (String.IsNullOrEmpty(smtpHost)) + if (String.IsNullOrEmpty (smtpHost)) { return "piratesmtp"; } diff --git a/Basic/Diagnostics/Logging.cs b/Basic/Diagnostics/Logging.cs index d7b7cccc..67ec9635 100644 --- a/Basic/Diagnostics/Logging.cs +++ b/Basic/Diagnostics/Logging.cs @@ -5,30 +5,30 @@ namespace Swarmops.Basic.Diagnostics { public class Logging { - public static void LogError(LogSource source, string message) + public static void LogError (LogSource source, string message) { EventLog eventLog = new EventLog(); eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Error); + eventLog.WriteEntry (message, EventLogEntryType.Error); } - public static void LogException(LogSource source, Exception exception) + public static void LogException (LogSource source, Exception exception) { - LogError(source, exception.ToString()); + LogError (source, exception.ToString()); } - public static void LogWarning(LogSource source, string message) + public static void LogWarning (LogSource source, string message) { EventLog eventLog = new EventLog(); eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Warning); + eventLog.WriteEntry (message, EventLogEntryType.Warning); } - public static void LogInformation(LogSource source, string message) + public static void LogInformation (LogSource source, string message) { EventLog eventLog = new EventLog(); eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Information); + eventLog.WriteEntry (message, EventLogEntryType.Information); } } diff --git a/Basic/Enums/MailAuthorType.cs b/Basic/Enums/MailAuthorType.cs index c17cdb30..9b71d987 100644 --- a/Basic/Enums/MailAuthorType.cs +++ b/Basic/Enums/MailAuthorType.cs @@ -21,15 +21,15 @@ namespace Swarmops.Basic.Enums public static Dictionary initList() { Dictionary retval = new Dictionary(); - retval.Add(MailAuthorType.MemberService, - new AddressItem("medlemsservice@piratpartiet.se", "Piratpartiet Medlemsservice")); - retval.Add(MailAuthorType.PirateWeb, new AddressItem("noreply@pirateweb.net", "PirateWeb")); - retval.Add(MailAuthorType.ActivistService, - new AddressItem("aktivistservice@piratpartiet.se", "Piratpartiet Aktivistservice")); - retval.Add(MailAuthorType.Service, new AddressItem("service@piratpartiet.se", "Piratpartiet Service")); - retval.Add(MailAuthorType.PressService, new AddressItem("press@piratpartiet.se", "Piratpartiet Press")); - retval.Add(MailAuthorType.Accounting, - new AddressItem("accounting@piratpartiet.se", "Piratpartiet Accounting")); + retval.Add (MailAuthorType.MemberService, + new AddressItem ("medlemsservice@piratpartiet.se", "Piratpartiet Medlemsservice")); + retval.Add (MailAuthorType.PirateWeb, new AddressItem ("noreply@pirateweb.net", "PirateWeb")); + retval.Add (MailAuthorType.ActivistService, + new AddressItem ("aktivistservice@piratpartiet.se", "Piratpartiet Aktivistservice")); + retval.Add (MailAuthorType.Service, new AddressItem ("service@piratpartiet.se", "Piratpartiet Service")); + retval.Add (MailAuthorType.PressService, new AddressItem ("press@piratpartiet.se", "Piratpartiet Press")); + retval.Add (MailAuthorType.Accounting, + new AddressItem ("accounting@piratpartiet.se", "Piratpartiet Accounting")); return retval; } @@ -38,7 +38,7 @@ namespace Swarmops.Basic.Enums private readonly string email; private readonly string name; - public AddressItem(string email, string name) + public AddressItem (string email, string name) { this.email = email; this.name = name; diff --git a/Basic/Enums/RoleTypeClass.cs b/Basic/Enums/RoleTypeClass.cs index 59d96bf8..7eefc3ce 100644 --- a/Basic/Enums/RoleTypeClass.cs +++ b/Basic/Enums/RoleTypeClass.cs @@ -215,25 +215,25 @@ namespace Swarmops.Basic.Enums private static RoleType[] CreateAllRoleTypes() { List retList = new List(); - retList.AddRange(AllOrganizationalRoleTypes); - retList.AddRange(AllSystemRoleTypes); - retList.AddRange(AllLocalRoleTypes); - foreach (RoleType rt in Enum.GetValues(typeof (RoleType))) + retList.AddRange (AllOrganizationalRoleTypes); + retList.AddRange (AllSystemRoleTypes); + retList.AddRange (AllLocalRoleTypes); + foreach (RoleType rt in Enum.GetValues (typeof (RoleType))) { - if (!retList.Contains(rt)) - retList.Add(rt); + if (!retList.Contains (rt)) + retList.Add (rt); } return retList.ToArray(); } - public static RoleClass ClassOfRole(RoleType r) + public static RoleClass ClassOfRole (RoleType r) { - if (Array.IndexOf(AllLocalRoleTypes, r) > -1) + if (Array.IndexOf (AllLocalRoleTypes, r) > -1) return RoleClass.Local; - if (Array.IndexOf(AllOrganizationalRoleTypes, r) > -1) + if (Array.IndexOf (AllOrganizationalRoleTypes, r) > -1) return RoleClass.Organization; - if (Array.IndexOf(AllSystemRoleTypes, r) > -1) + if (Array.IndexOf (AllSystemRoleTypes, r) > -1) return RoleClass.System; return RoleClass.Undefined; } diff --git a/Basic/Interfaces/IHandleProvider.cs b/Basic/Interfaces/IHandleProvider.cs index 02cad426..f93da85b 100644 --- a/Basic/Interfaces/IHandleProvider.cs +++ b/Basic/Interfaces/IHandleProvider.cs @@ -5,11 +5,11 @@ namespace Swarmops.Basic.Interfaces { public interface IHandleProvider { - string GetPersonHandle(int personId); - void SetPersonHandle(int personId, string newHandle); - HandleErrorType CanSetHandle(string newHandle); + string GetPersonHandle (int personId); + void SetPersonHandle (int personId, string newHandle); + HandleErrorType CanSetHandle (string newHandle); - int GetPersonByHandle(string handle); + int GetPersonByHandle (string handle); } } @@ -31,7 +31,7 @@ namespace Swarmops.Basic.Exceptions private readonly string attemptedHandle; private readonly HandleErrorType errorType; - public HandleException(string attemptedHandle, HandleErrorType errorType) + public HandleException (string attemptedHandle, HandleErrorType errorType) { this.attemptedHandle = attemptedHandle; this.errorType = errorType; diff --git a/Basic/Properties/AssemblyInfo.cs b/Basic/Properties/AssemblyInfo.cs index b0fe2384..4b4c19b6 100644 --- a/Basic/Properties/AssemblyInfo.cs +++ b/Basic/Properties/AssemblyInfo.cs @@ -6,14 +6,14 @@ using System.Reflection; // associated with an assembly. // -[assembly: AssemblyTitle("PirateWeb Type Library")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("PirateWeb Type Library")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // // Version information for an assembly consists of the following four values: @@ -26,7 +26,7 @@ using System.Reflection; // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion ("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the @@ -54,6 +54,6 @@ using System.Reflection; // documentation for more information on this. // -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] \ No newline at end of file +[assembly: AssemblyDelaySign (false)] +[assembly: AssemblyKeyFile ("")] +[assembly: AssemblyKeyName ("")] \ No newline at end of file diff --git a/Basic/Types/BasicAddressValidationRun.cs b/Basic/Types/BasicAddressValidationRun.cs index 3915ea01..9d9edc5d 100644 --- a/Basic/Types/BasicAddressValidationRun.cs +++ b/Basic/Types/BasicAddressValidationRun.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types { private readonly int validationRunId; - public BasicAddressValidationRun(int validationRunId) + public BasicAddressValidationRun (int validationRunId) { this.validationRunId = validationRunId; } diff --git a/Basic/Types/BasicBallot.cs b/Basic/Types/BasicBallot.cs index 88e2fe14..101942d1 100644 --- a/Basic/Types/BasicBallot.cs +++ b/Basic/Types/BasicBallot.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicBallot : IHasIdentity { - public BasicBallot(int ballotId, int electionId, int organizationId, int geographyId, string name, int count, + public BasicBallot (int ballotId, int electionId, int organizationId, int geographyId, string name, int count, string deliveryAddress) { BallotId = ballotId; @@ -16,8 +16,8 @@ namespace Swarmops.Basic.Types DeliveryAddress = deliveryAddress; } - public BasicBallot(BasicBallot original) - : this( + public BasicBallot (BasicBallot original) + : this ( original.BallotId, original.ElectionId, original.OrganizationId, original.GeographyId, original.Name, original.Count, original.DeliveryAddress) { diff --git a/Basic/Types/BasicChurnDataPoint.cs b/Basic/Types/BasicChurnDataPoint.cs index ae7c816d..9b8e3ed0 100644 --- a/Basic/Types/BasicChurnDataPoint.cs +++ b/Basic/Types/BasicChurnDataPoint.cs @@ -29,7 +29,7 @@ namespace Swarmops.Basic.Types public readonly int OrganizationId; public readonly int PersonId; - public BasicChurnDataPoint(ChurnDataType dataType, DateTime decisionDateTime, DateTime expiryDate, + public BasicChurnDataPoint (ChurnDataType dataType, DateTime decisionDateTime, DateTime expiryDate, int personId, int organizationId) { this.DataType = dataType; @@ -39,8 +39,8 @@ namespace Swarmops.Basic.Types this.OrganizationId = organizationId; } - public BasicChurnDataPoint(BasicChurnDataPoint original) : - this( + public BasicChurnDataPoint (BasicChurnDataPoint original) : + this ( original.DataType, original.DecisionDateTime, original.ExpiryDate, original.PersonId, original.OrganizationId) { diff --git a/Basic/Types/BasicCity.cs b/Basic/Types/BasicCity.cs index ccb1ed5f..f7113294 100644 --- a/Basic/Types/BasicCity.cs +++ b/Basic/Types/BasicCity.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicCity : IHasIdentity { - public BasicCity(int cityId, string name, int countryId, int geographyId) + public BasicCity (int cityId, string name, int countryId, int geographyId) { CityId = cityId; Name = name; @@ -14,12 +14,12 @@ namespace Swarmops.Basic.Types GeographyId = geographyId; } - public BasicCity(BasicCity original) - : this(original.CityId, original.Name, original.CountryId, original.GeographyId) + public BasicCity (BasicCity original) + : this (original.CityId, original.Name, original.CountryId, original.GeographyId) { } - [Obsolete("Do not call this ctor directly. It exists to enable serialization.", true)] + [Obsolete ("Do not call this ctor directly. It exists to enable serialization.", true)] public BasicCity() { // this ctor should never be called from code diff --git a/Basic/Types/BasicCommunicationTurnaround.cs b/Basic/Types/BasicCommunicationTurnaround.cs index d42b751f..e8377e0a 100644 --- a/Basic/Types/BasicCommunicationTurnaround.cs +++ b/Basic/Types/BasicCommunicationTurnaround.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicCommunicationTurnaround : IHasIdentity { - public BasicCommunicationTurnaround(int organizationId, int communicationTypeId, int communicationId, + public BasicCommunicationTurnaround (int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeOpened, DateTime dateTimeFirstResponse, int personIdFirstResponse, DateTime dateTimeClosed, int personIdClosed, bool open, bool responded) { @@ -21,8 +21,8 @@ namespace Swarmops.Basic.Types Responded = responded; } - public BasicCommunicationTurnaround(BasicCommunicationTurnaround original) : - this( + public BasicCommunicationTurnaround (BasicCommunicationTurnaround original) : + this ( original.OrganizationId, original.CommunicationTypeId, original.CommunicationId, original.DateTimeOpened, original.DateTimeFirstResponse, original.PersonIdFirstResponse, original.DateTimeClosed, original.PersonIdClosed, original.Open, original.Responded) diff --git a/Basic/Types/BasicCountry.cs b/Basic/Types/BasicCountry.cs index 6c698c1e..1a913533 100644 --- a/Basic/Types/BasicCountry.cs +++ b/Basic/Types/BasicCountry.cs @@ -6,16 +6,16 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicCountry : IHasIdentity { - public BasicCountry(int countryId, string name, string code) + public BasicCountry (int countryId, string name, string code) { CountryId = countryId; Name = name; Code = code; } - public BasicCountry(int countryId, string name, string code, string defaultCulture, string currencyCode, + public BasicCountry (int countryId, string name, string code, string defaultCulture, string currencyCode, int geographyId, int postalCodeLength) - : this(countryId, name, code) + : this (countryId, name, code) { Culture = defaultCulture; CurrencyCode = currencyCode; @@ -23,14 +23,14 @@ namespace Swarmops.Basic.Types PostalCodeLength = postalCodeLength; } - public BasicCountry(BasicCountry original) - : this( + public BasicCountry (BasicCountry original) + : this ( original.CountryId, original.Name, original.Code, original.Culture, original.CurrencyCode, original.GeographyId, original.PostalCodeLength) { } - [Obsolete("Do not call this function directly. It exists to enable serialization.", true)] + [Obsolete ("Do not call this function directly. It exists to enable serialization.", true)] public BasicCountry() { // this does not initialize the Basic Country, but exists to enable serialization. @@ -53,7 +53,7 @@ namespace Swarmops.Basic.Types return 1; } - throw new NotImplementedException("BasicCountry.CurrencyId"); + throw new NotImplementedException ("BasicCountry.CurrencyId"); } } diff --git a/Basic/Types/BasicCurrency.cs b/Basic/Types/BasicCurrency.cs index 0cd7bf20..58b1c79f 100644 --- a/Basic/Types/BasicCurrency.cs +++ b/Basic/Types/BasicCurrency.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicCurrency : IHasIdentity { - public BasicCurrency(int currencyId, string code, string name, string sign) + public BasicCurrency (int currencyId, string code, string name, string sign) { CurrencyId = currencyId; Code = code; @@ -12,8 +12,8 @@ namespace Swarmops.Basic.Types Sign = sign; } - public BasicCurrency(BasicCurrency original) - : this(original.CurrencyId, original.Code, original.Name, original.Sign) + public BasicCurrency (BasicCurrency original) + : this (original.CurrencyId, original.Code, original.Name, original.Sign) { // empty copy ctor } diff --git a/Basic/Types/BasicDocument.cs b/Basic/Types/BasicDocument.cs index 0a9700f4..04079f72 100644 --- a/Basic/Types/BasicDocument.cs +++ b/Basic/Types/BasicDocument.cs @@ -25,7 +25,7 @@ namespace Swarmops.Basic.Types #endregion - public BasicDocument(int documentId, string serverFileName, string clientFileName, string description, + public BasicDocument (int documentId, string serverFileName, string clientFileName, string description, DocumentType documentType, int foreignId, Int64 fileSize, int uploadedByPersonId, DateTime uploadedDateTime) { this.documentId = documentId; @@ -39,8 +39,8 @@ namespace Swarmops.Basic.Types this.uploadedDateTime = uploadedDateTime; } - public BasicDocument(BasicDocument original) : - this(original.documentId, original.serverFileName, original.clientFileName, original.description, + public BasicDocument (BasicDocument original) : + this (original.documentId, original.serverFileName, original.clientFileName, original.description, original.documentType, original.foreignId, original.fileSize, original.uploadedByPersonId, original.uploadedDateTime) { diff --git a/Basic/Types/BasicElection.cs b/Basic/Types/BasicElection.cs index 90cad9ac..6b7210b9 100644 --- a/Basic/Types/BasicElection.cs +++ b/Basic/Types/BasicElection.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicElection : IHasIdentity { - public BasicElection(int electionId, string name, int geographyId, DateTime date) + public BasicElection (int electionId, string name, int geographyId, DateTime date) { ElectionId = electionId; Name = name; @@ -13,8 +13,8 @@ namespace Swarmops.Basic.Types Date = date; } - public BasicElection(BasicElection original) : - this(original.ElectionId, original.Name, original.GeographyId, original.Date) + public BasicElection (BasicElection original) : + this (original.ElectionId, original.Name, original.GeographyId, original.Date) { // empty copy ctor } diff --git a/Basic/Types/BasicExceptionLog.cs b/Basic/Types/BasicExceptionLog.cs index d1acccb2..0927bac0 100644 --- a/Basic/Types/BasicExceptionLog.cs +++ b/Basic/Types/BasicExceptionLog.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicExceptionLog { - public BasicExceptionLog(int ExceptionId, DateTime ExceptionDateTime, string Source, string ExceptionText) + public BasicExceptionLog (int ExceptionId, DateTime ExceptionDateTime, string Source, string ExceptionText) { this.ExceptionId = ExceptionId; this.ExceptionDateTime = ExceptionDateTime; @@ -12,8 +12,8 @@ namespace Swarmops.Basic.Types this.ExceptionText = ExceptionText; } - public BasicExceptionLog(BasicExceptionLog original) : - this(original.ExceptionId, original.ExceptionDateTime, original.Source, original.ExceptionText) + public BasicExceptionLog (BasicExceptionLog original) : + this (original.ExceptionId, original.ExceptionDateTime, original.Source, original.ExceptionText) { // empty copy ctor } diff --git a/Basic/Types/BasicExpenseClaim.cs b/Basic/Types/BasicExpenseClaim.cs index 13459fdc..7cad8ed9 100644 --- a/Basic/Types/BasicExpenseClaim.cs +++ b/Basic/Types/BasicExpenseClaim.cs @@ -11,7 +11,7 @@ namespace Swarmops.Basic.Types /// /// Normal constructor /// - public BasicExpenseClaim(int expenseClaimId, int claimingPersonId, DateTime createdDateTime, + public BasicExpenseClaim (int expenseClaimId, int claimingPersonId, DateTime createdDateTime, bool open, bool attested, bool documented, bool claimed, int organizationId, int geographyId, int budgetId, DateTime expenseDate, string description, double preApprovedAmount, Int64 amountCents, bool repaid, bool keepSeparate) @@ -37,8 +37,8 @@ namespace Swarmops.Basic.Types /// /// Copy constructor /// - public BasicExpenseClaim(BasicExpenseClaim original) - : this(original.Identity, original.ClaimingPersonId, original.CreatedDateTime, + public BasicExpenseClaim (BasicExpenseClaim original) + : this (original.Identity, original.ClaimingPersonId, original.CreatedDateTime, original.Open, original.Attested, original.Validated, original.Claimed, original.OrganizationId, original.GeographyId, original.BudgetId, original.ExpenseDate, original.Description, diff --git a/Basic/Types/BasicExternalActivity.cs b/Basic/Types/BasicExternalActivity.cs index 3d7cd747..0d7045ae 100644 --- a/Basic/Types/BasicExternalActivity.cs +++ b/Basic/Types/BasicExternalActivity.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types { public class BasicExternalActivity : IHasIdentity { - public BasicExternalActivity(int externalActivityId, int organizationId, int geographyId, + public BasicExternalActivity (int externalActivityId, int organizationId, int geographyId, ExternalActivityType type, DateTime dateTime, string description, int createdByPersonId, DateTime createdDateTime, int dupeOfActivityId) @@ -22,8 +22,8 @@ namespace Swarmops.Basic.Types DupeOfActivityId = dupeOfActivityId; } - public BasicExternalActivity(BasicExternalActivity original) : - this( + public BasicExternalActivity (BasicExternalActivity original) : + this ( original.ExternalActivityId, original.OrganizationId, original.GeographyId, original.Type, original.DateTime, original.Description, original.CreatedByPersonId, original.CreatedDateTime, original.DupeOfActivityId) { diff --git a/Basic/Types/BasicExternalCredential.cs b/Basic/Types/BasicExternalCredential.cs index ac7a0c42..2d50ee48 100644 --- a/Basic/Types/BasicExternalCredential.cs +++ b/Basic/Types/BasicExternalCredential.cs @@ -9,7 +9,7 @@ namespace Swarmops.Basic.Types public readonly string Password; public readonly string ServiceName; - public BasicExternalCredential(int externalCredentialId, string serviceName, string login, string password) + public BasicExternalCredential (int externalCredentialId, string serviceName, string login, string password) { this.ExternalCredentialId = externalCredentialId; this.ServiceName = serviceName; diff --git a/Basic/Types/BasicExternalIdentity.cs b/Basic/Types/BasicExternalIdentity.cs index 45070fe5..44799ab2 100644 --- a/Basic/Types/BasicExternalIdentity.cs +++ b/Basic/Types/BasicExternalIdentity.cs @@ -13,7 +13,7 @@ namespace Swarmops.Basic.Types private readonly ExternalIdentityType typeOfAccount; private readonly string userID; - public BasicExternalIdentity(int ExternalIdentityIdentity, + public BasicExternalIdentity (int ExternalIdentityIdentity, ExternalIdentityType TypeOfAccount, string ExternalSystem, string UserID, @@ -28,8 +28,8 @@ namespace Swarmops.Basic.Types this.typeOfAccount = TypeOfAccount; } - public BasicExternalIdentity(BasicExternalIdentity original) - : this( + public BasicExternalIdentity (BasicExternalIdentity original) + : this ( original.Identity, original.TypeOfAccount, original.ExternalSystem, original.UserID, original.Password, original.AttachedToPersonID) { diff --git a/Basic/Types/BasicGeography.cs b/Basic/Types/BasicGeography.cs index 455b9b38..65047d25 100644 --- a/Basic/Types/BasicGeography.cs +++ b/Basic/Types/BasicGeography.cs @@ -9,12 +9,12 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicGeography : IHasIdentity { - public BasicGeography(int geographyId, int parentGeographyId, string name) - : this(geographyId, parentGeographyId, name, 0) + public BasicGeography (int geographyId, int parentGeographyId, string name) + : this (geographyId, parentGeographyId, name, 0) { } - public BasicGeography(int geographyId, int parentGeographyId, string name, int generation) + public BasicGeography (int geographyId, int parentGeographyId, string name, int generation) { GeographyId = geographyId; ParentGeographyId = parentGeographyId; @@ -22,12 +22,12 @@ namespace Swarmops.Basic.Types Generation = generation; } - public BasicGeography(BasicGeography original) - : this(original.GeographyId, original.ParentGeographyId, original.Name, original.Generation) + public BasicGeography (BasicGeography original) + : this (original.GeographyId, original.ParentGeographyId, original.Name, original.Generation) { } - [Obsolete("Do not use this ctor. It is provided to enable serializability.", true)] + [Obsolete ("Do not use this ctor. It is provided to enable serializability.", true)] public BasicGeography() { // provided for serializability - does not initialize fields diff --git a/Basic/Types/BasicGeographyDesignation.cs b/Basic/Types/BasicGeographyDesignation.cs index c5141bdc..acfe42ef 100644 --- a/Basic/Types/BasicGeographyDesignation.cs +++ b/Basic/Types/BasicGeographyDesignation.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicGeographyDesignation { - public BasicGeographyDesignation(int geographyId, int countryId, + public BasicGeographyDesignation (int geographyId, int countryId, string designation, GeographyLevel geoLevelId) { GeographyId = geographyId; @@ -13,8 +13,8 @@ namespace Swarmops.Basic.Types GeographyLevel = geoLevelId; } - public BasicGeographyDesignation(BasicGeographyDesignation original) : - this(original.GeographyId, original.CountryId, original.Designation, original.GeographyLevel) + public BasicGeographyDesignation (BasicGeographyDesignation original) : + this (original.GeographyId, original.CountryId, original.Designation, original.GeographyLevel) { // empty copy ctor } diff --git a/Basic/Types/BasicInboundInvoice.cs b/Basic/Types/BasicInboundInvoice.cs index bbf14e2d..aee203bd 100644 --- a/Basic/Types/BasicInboundInvoice.cs +++ b/Basic/Types/BasicInboundInvoice.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicInboundInvoice : IHasIdentity { - public BasicInboundInvoice(int inboundInvoiceId, int organizationId, DateTime createdDateTime, + public BasicInboundInvoice (int inboundInvoiceId, int organizationId, DateTime createdDateTime, DateTime dueDate, Int64 amountCents, int budgetId, string supplier, string payToAccount, string ocr, string invoiceReference, bool attested, bool open, DateTime closedDateTime, int closedByPersonId) @@ -26,8 +26,8 @@ namespace Swarmops.Basic.Types ClosedByPersonId = closedByPersonId; } - public BasicInboundInvoice(BasicInboundInvoice original) - : this(original.InboundInvoiceId, original.OrganizationId, original.CreatedDateTime, + public BasicInboundInvoice (BasicInboundInvoice original) + : this (original.InboundInvoiceId, original.OrganizationId, original.CreatedDateTime, original.DueDate, original.AmountCents, original.BudgetId, original.Supplier, original.PayToAccount, original.Ocr, original.InvoiceReference, original.Attested, original.Open, original.ClosedDateTime, original.ClosedByPersonId) diff --git a/Basic/Types/BasicInternalPoll.cs b/Basic/Types/BasicInternalPoll.cs index 771d9c60..3051ebb9 100644 --- a/Basic/Types/BasicInternalPoll.cs +++ b/Basic/Types/BasicInternalPoll.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicInternalPoll : IHasIdentity { - public BasicInternalPoll(int internalPollId, int createdByPersonId, int organizationId, int geographyId, + public BasicInternalPoll (int internalPollId, int createdByPersonId, int organizationId, int geographyId, string name, bool runningOpen, bool votingOpen, int maxVoteLength, DateTime runningOpens, DateTime runningCloses, DateTime votingOpens, DateTime votingCloses, InternalPollResultsType resultsType) { @@ -24,8 +24,8 @@ namespace Swarmops.Basic.Types ResultsType = resultsType; } - public BasicInternalPoll(BasicInternalPoll original) - : this( + public BasicInternalPoll (BasicInternalPoll original) + : this ( original.InternalPollId, original.CreatedByPersonId, original.OrganizationId, original.GeographyId, original.Name, original.RunningOpen, original.VotingOpen, original.MaxVoteLength, original.RunningOpens, original.RunningCloses, diff --git a/Basic/Types/BasicInternalPollCandidate.cs b/Basic/Types/BasicInternalPollCandidate.cs index d1b7aa3b..3b49b8aa 100644 --- a/Basic/Types/BasicInternalPollCandidate.cs +++ b/Basic/Types/BasicInternalPollCandidate.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicInternalPollCandidate : IHasIdentity { - public BasicInternalPollCandidate(int internalPollCandidateId, int internalPollId, int personId, + public BasicInternalPollCandidate (int internalPollCandidateId, int internalPollId, int personId, string candidacyStatement) { InternalPollCandidateId = internalPollCandidateId; @@ -13,8 +13,8 @@ namespace Swarmops.Basic.Types CandidacyStatement = candidacyStatement; } - public BasicInternalPollCandidate(BasicInternalPollCandidate original) - : this( + public BasicInternalPollCandidate (BasicInternalPollCandidate original) + : this ( original.InternalPollCandidateId, original.InternalPollId, original.PersonId, original.CandidacyStatement) { diff --git a/Basic/Types/BasicInternalPollVote.cs b/Basic/Types/BasicInternalPollVote.cs index c4ca3767..542aaa1a 100644 --- a/Basic/Types/BasicInternalPollVote.cs +++ b/Basic/Types/BasicInternalPollVote.cs @@ -4,15 +4,15 @@ namespace Swarmops.Basic.Types { public class BasicInternalPollVote : IHasIdentity { - public BasicInternalPollVote(int internalPollVoteId, int internalPollId, string verificationCode) + public BasicInternalPollVote (int internalPollVoteId, int internalPollId, string verificationCode) { InternalPollVoteId = internalPollVoteId; InternalPollId = internalPollId; VerificationCode = verificationCode; } - public BasicInternalPollVote(BasicInternalPollVote original) - : this(original.InternalPollVoteId, original.InternalPollId, original.VerificationCode) + public BasicInternalPollVote (BasicInternalPollVote original) + : this (original.InternalPollVoteId, original.InternalPollId, original.VerificationCode) { // empty copy ctor } diff --git a/Basic/Types/BasicInternalPollVoteDetail.cs b/Basic/Types/BasicInternalPollVoteDetail.cs index e807ac42..4702e04c 100644 --- a/Basic/Types/BasicInternalPollVoteDetail.cs +++ b/Basic/Types/BasicInternalPollVoteDetail.cs @@ -2,15 +2,15 @@ namespace Swarmops.Basic.Types { public class BasicInternalPollVoteDetail { - public BasicInternalPollVoteDetail(int internalPollVoteId, int internalPollCandidateId, int position) + public BasicInternalPollVoteDetail (int internalPollVoteId, int internalPollCandidateId, int position) { InternalPollVoteId = internalPollVoteId; InternalPollCandidateId = internalPollCandidateId; Position = position; } - public BasicInternalPollVoteDetail(BasicInternalPollVoteDetail original) - : this(original.InternalPollVoteId, original.InternalPollCandidateId, original.Position) + public BasicInternalPollVoteDetail (BasicInternalPollVoteDetail original) + : this (original.InternalPollVoteId, original.InternalPollCandidateId, original.Position) { // empty copy ctor } diff --git a/Basic/Types/BasicInternalPollVoter.cs b/Basic/Types/BasicInternalPollVoter.cs index c1fbea7d..7ec36b7f 100644 --- a/Basic/Types/BasicInternalPollVoter.cs +++ b/Basic/Types/BasicInternalPollVoter.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types { public class BasicInternalPollVoter { - public BasicInternalPollVoter(int personId, int internalPollId, bool open, DateTime closedDateTime) + public BasicInternalPollVoter (int personId, int internalPollId, bool open, DateTime closedDateTime) { PersonId = personId; InternalPollId = internalPollId; @@ -12,8 +12,8 @@ namespace Swarmops.Basic.Types ClosedDateTime = closedDateTime; } - public BasicInternalPollVoter(BasicInternalPollVoter original) - : this(original.PersonId, original.InternalPollId, original.Open, original.ClosedDateTime) + public BasicInternalPollVoter (BasicInternalPollVoter original) + : this (original.PersonId, original.InternalPollId, original.Open, original.ClosedDateTime) { // empty copy ctor } diff --git a/Basic/Types/BasicMailTemplate.cs b/Basic/Types/BasicMailTemplate.cs index 084c59b8..8be5dd06 100644 --- a/Basic/Types/BasicMailTemplate.cs +++ b/Basic/Types/BasicMailTemplate.cs @@ -14,7 +14,7 @@ namespace Swarmops.Basic.Types /// /// Basic constructor. /// - public BasicMailTemplate(int templateId, + public BasicMailTemplate (int templateId, string templateName, string languageCode, string countryCode, @@ -33,8 +33,8 @@ namespace Swarmops.Basic.Types /// /// Copy constructor. /// - public BasicMailTemplate(BasicMailTemplate original) - : this(original.templateId, + public BasicMailTemplate (BasicMailTemplate original) + : this (original.templateId, original.templateName, original.languageCode, original.countryCode, diff --git a/Basic/Types/BasicMediaCategory.cs b/Basic/Types/BasicMediaCategory.cs index afafa62d..53779a9c 100644 --- a/Basic/Types/BasicMediaCategory.cs +++ b/Basic/Types/BasicMediaCategory.cs @@ -16,14 +16,14 @@ namespace Swarmops.Basic.Types #endregion - public BasicMediaCategory(int mediaCategoryId, string name) + public BasicMediaCategory (int mediaCategoryId, string name) { this.mediaCategoryId = mediaCategoryId; this.name = name; } - public BasicMediaCategory(BasicMediaCategory original) : - this(original.mediaCategoryId, original.name) + public BasicMediaCategory (BasicMediaCategory original) : + this (original.mediaCategoryId, original.name) { } diff --git a/Basic/Types/BasicMediaEntry.cs b/Basic/Types/BasicMediaEntry.cs index 107a169d..c1556372 100644 --- a/Basic/Types/BasicMediaEntry.cs +++ b/Basic/Types/BasicMediaEntry.cs @@ -22,7 +22,7 @@ namespace Swarmops.Basic.Types #endregion - public BasicMediaEntry(int id, int keywordId, string mediaName, bool isBlog, string title, string url, + public BasicMediaEntry (int id, int keywordId, string mediaName, bool isBlog, string title, string url, DateTime dateTime) { this.id = id; @@ -34,15 +34,15 @@ namespace Swarmops.Basic.Types this.dateTime = dateTime; } - public BasicMediaEntry(BasicMediaEntry original) - : this( + public BasicMediaEntry (BasicMediaEntry original) + : this ( original.id, original.keywordId, original.mediaName, original.isBlog, original.title, original.url, original.dateTime) { } public BasicMediaEntry() - : this(0, 0, string.Empty, false, string.Empty, string.Empty, DateTime.MinValue) + : this (0, 0, string.Empty, false, string.Empty, string.Empty, DateTime.MinValue) { } diff --git a/Basic/Types/BasicMediaKeyword.cs b/Basic/Types/BasicMediaKeyword.cs index 9608285a..92eb268a 100644 --- a/Basic/Types/BasicMediaKeyword.cs +++ b/Basic/Types/BasicMediaKeyword.cs @@ -18,20 +18,20 @@ namespace Swarmops.Basic.Types #endregion - public BasicMediaKeyword(int id, string keyword) + public BasicMediaKeyword (int id, string keyword) { this.id = id; this.keyword = keyword; } - public BasicMediaKeyword(BasicMediaKeyword original) + public BasicMediaKeyword (BasicMediaKeyword original) { this.id = original.id; this.keyword = original.keyword; } public BasicMediaKeyword() - : this(0, string.Empty) + : this (0, string.Empty) { } diff --git a/Basic/Types/BasicMedium.cs b/Basic/Types/BasicMedium.cs index 5a9d6f26..c24e0deb 100644 --- a/Basic/Types/BasicMedium.cs +++ b/Basic/Types/BasicMedium.cs @@ -18,15 +18,15 @@ namespace Swarmops.Basic.Types #endregion - public BasicMedium(int mediumId, string name, PoliticalAffiliation politicalAffiliation) + public BasicMedium (int mediumId, string name, PoliticalAffiliation politicalAffiliation) { this.mediumId = mediumId; this.name = name; this.politicalAffiliation = politicalAffiliation; } - public BasicMedium(int mediumId, string name) - : this(mediumId, name, PoliticalAffiliation.NotPolitical) + public BasicMedium (int mediumId, string name) + : this (mediumId, name, PoliticalAffiliation.NotPolitical) { } diff --git a/Basic/Types/BasicMembership.cs b/Basic/Types/BasicMembership.cs index 4d88c9a3..ef009b1a 100644 --- a/Basic/Types/BasicMembership.cs +++ b/Basic/Types/BasicMembership.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicMembership : IHasIdentity { - public BasicMembership(int personId, int organizationId) + public BasicMembership (int personId, int organizationId) { PersonId = personId; OrganizationId = organizationId; @@ -13,14 +13,14 @@ namespace Swarmops.Basic.Types DateTerminated = DateTime.MinValue; } - public BasicMembership(int personId, int organizationId, DateTime memberSince, DateTime expires) - : this(personId, organizationId) + public BasicMembership (int personId, int organizationId, DateTime memberSince, DateTime expires) + : this (personId, organizationId) { MemberSince = memberSince; Expires = expires; } - public BasicMembership(int membershipId, int personId, int organizationId, DateTime memberSince, + public BasicMembership (int membershipId, int personId, int organizationId, DateTime memberSince, DateTime expires, bool active, DateTime dateTerminated) { MembershipId = membershipId; @@ -32,8 +32,8 @@ namespace Swarmops.Basic.Types DateTerminated = dateTerminated; } - public BasicMembership(BasicMembership original) - : this( + public BasicMembership (BasicMembership original) + : this ( original.MembershipId, original.PersonId, original.OrganizationId, original.MemberSince, original.Expires, original.Active, original.DateTerminated) { diff --git a/Basic/Types/BasicMembershipPaymentStatus.cs b/Basic/Types/BasicMembershipPaymentStatus.cs index 97a54955..52b04184 100644 --- a/Basic/Types/BasicMembershipPaymentStatus.cs +++ b/Basic/Types/BasicMembershipPaymentStatus.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicMembershipPaymentStatus { - public BasicMembershipPaymentStatus(int membershipId, MembershipPaymentStatus status, DateTime statusDateTime) + public BasicMembershipPaymentStatus (int membershipId, MembershipPaymentStatus status, DateTime statusDateTime) { MembershipId = membershipId; Status = status; diff --git a/Basic/Types/BasicNewsletter.cs b/Basic/Types/BasicNewsletter.cs index f9a0a08d..ceca985f 100644 --- a/Basic/Types/BasicNewsletter.cs +++ b/Basic/Types/BasicNewsletter.cs @@ -17,7 +17,7 @@ namespace Swarmops.Basic.Types private readonly int organizationId; private readonly string title; - public BasicNewsletter(int newsletterId, string title, string introduction, string body, + public BasicNewsletter (int newsletterId, string title, string introduction, string body, int authorId, int templateId, int feedId) { this.newsletterId = newsletterId; @@ -30,10 +30,10 @@ namespace Swarmops.Basic.Types this.newsletterFeedId = feedId; } - public BasicNewsletter(int newsletterId, string title, string introduction, string body, + public BasicNewsletter (int newsletterId, string title, string introduction, string body, int authorId, int templateId, int feedId, int organizationId, int geographyId) : - this(newsletterId, title, introduction, body, authorId, templateId, feedId) + this (newsletterId, title, introduction, body, authorId, templateId, feedId) { this.organizationId = organizationId; this.geographyId = geographyId; diff --git a/Basic/Types/BasicNewsletterFeed.cs b/Basic/Types/BasicNewsletterFeed.cs index d0dd4af2..14d6e41f 100644 --- a/Basic/Types/BasicNewsletterFeed.cs +++ b/Basic/Types/BasicNewsletterFeed.cs @@ -22,7 +22,7 @@ namespace Swarmops.Basic.Types /// public readonly int OrganizationId; - public BasicNewsletterFeed(int newsletterId, int organizationId, bool defaultSubscribed, string name) + public BasicNewsletterFeed (int newsletterId, int organizationId, bool defaultSubscribed, string name) { this.NewsletterFeedId = newsletterId; this.OrganizationId = organizationId; @@ -35,8 +35,8 @@ namespace Swarmops.Basic.Types this.Name = string.Empty; } - public BasicNewsletterFeed(BasicNewsletterFeed original) - : this(original.NewsletterFeedId, original.OrganizationId, original.DefaultSubscribed, original.Name) + public BasicNewsletterFeed (BasicNewsletterFeed original) + : this (original.NewsletterFeedId, original.OrganizationId, original.DefaultSubscribed, original.Name) { } } diff --git a/Basic/Types/BasicNewsletterTemplate.cs b/Basic/Types/BasicNewsletterTemplate.cs index fe66ac52..dd2b7e68 100644 --- a/Basic/Types/BasicNewsletterTemplate.cs +++ b/Basic/Types/BasicNewsletterTemplate.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types public string HtmlTemplate; public string TextTemplate; - public BasicNewsletterTemplate(string htmlTemplate, string textTemplate) + public BasicNewsletterTemplate (string htmlTemplate, string textTemplate) { this.HtmlTemplate = htmlTemplate; this.TextTemplate = textTemplate; diff --git a/Basic/Types/BasicObjectOptionalData.cs b/Basic/Types/BasicObjectOptionalData.cs index fbe160b5..51adf3b4 100644 --- a/Basic/Types/BasicObjectOptionalData.cs +++ b/Basic/Types/BasicObjectOptionalData.cs @@ -9,7 +9,7 @@ namespace Swarmops.Basic.Types { protected Dictionary OptionalData; - public BasicObjectOptionalData(ObjectType objectType, int objectId, + public BasicObjectOptionalData (ObjectType objectType, int objectId, Dictionary initialData) { ObjectType = objectType; @@ -17,8 +17,8 @@ namespace Swarmops.Basic.Types this.OptionalData = initialData; } - public BasicObjectOptionalData(BasicObjectOptionalData original) - : this(original.ObjectType, original.ObjectId, original.OptionalData) + public BasicObjectOptionalData (BasicObjectOptionalData original) + : this (original.ObjectType, original.ObjectId, original.OptionalData) { // empty ctor } diff --git a/Basic/Types/BasicOrganization.cs b/Basic/Types/BasicOrganization.cs index 6b3e4141..47f18c86 100644 --- a/Basic/Types/BasicOrganization.cs +++ b/Basic/Types/BasicOrganization.cs @@ -19,25 +19,25 @@ namespace Swarmops.Basic.Types { } - public BasicOrganization(int organizationId, string name, string nameInternational) + public BasicOrganization (int organizationId, string name, string nameInternational) { OrganizationId = organizationId; Name = name; NameInternational = nameInternational; } - public BasicOrganization(int organizationId, int parentOrganizationId, string name, string nameInternational) : - this(organizationId, name, nameInternational) + public BasicOrganization (int organizationId, int parentOrganizationId, string name, string nameInternational) : + this (organizationId, name, nameInternational) { ParentOrganizationId = parentOrganizationId; } - public BasicOrganization(int organizationId, int parentOrganizationId, string name, string nameInternational, + public BasicOrganization (int organizationId, int parentOrganizationId, string name, string nameInternational, string nameShort, string domain, string mailPrefix, int anchorGeographyId, bool acceptsMembers, bool autoAssignNewMembers, int defaultCountryId) - : this(organizationId, parentOrganizationId, name, nameInternational) + : this (organizationId, parentOrganizationId, name, nameInternational) { this.nameShort = nameShort; Domain = domain; @@ -48,8 +48,8 @@ namespace Swarmops.Basic.Types DefaultCountryId = defaultCountryId; } - public BasicOrganization(BasicOrganization original) - : this( + public BasicOrganization (BasicOrganization original) + : this ( original.Identity, original.ParentOrganizationId, original.Name, original.NameInternational, original.NameShort, original.Domain, original.MailPrefix, original.AnchorGeographyId, original.AcceptsMembers, original.AutoAssignNewMembers, original.DefaultCountryId) diff --git a/Basic/Types/BasicOutboundInvoice.cs b/Basic/Types/BasicOutboundInvoice.cs index 6868adc1..3d2f37a2 100644 --- a/Basic/Types/BasicOutboundInvoice.cs +++ b/Basic/Types/BasicOutboundInvoice.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicOutboundInvoice : IHasIdentity { - public BasicOutboundInvoice(int outboundInvoiceId, string customerName, string invoiceAddressPaper, + public BasicOutboundInvoice (int outboundInvoiceId, string customerName, string invoiceAddressPaper, string invoiceAddressMail, int currencyId, int organizationId, int budgetId, DateTime createdDateTime, int createdByPersonId, DateTime dueDate, int reminderCount, string reference, bool domestic, bool open, bool sent, string securityCode, string theirReference) @@ -30,8 +30,8 @@ namespace Swarmops.Basic.Types } - public BasicOutboundInvoice(BasicOutboundInvoice original) : - this( + public BasicOutboundInvoice (BasicOutboundInvoice original) : + this ( original.OutboundInvoiceId, original.CustomerName, original.InvoiceAddressPaper, original.InvoiceAddressMail, original.CurrencyId, original.OrganizationId, original.BudgetId, original.CreatedDateTime, original.CreatedByPersonId, original.DueDate, original.ReminderCount, original.Reference, original.Domestic, diff --git a/Basic/Types/BasicOutboundInvoiceItem.cs b/Basic/Types/BasicOutboundInvoiceItem.cs index 7c7d7e13..9dbecf11 100644 --- a/Basic/Types/BasicOutboundInvoiceItem.cs +++ b/Basic/Types/BasicOutboundInvoiceItem.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicOutboundInvoiceItem : IHasIdentity { - public BasicOutboundInvoiceItem(int outboundInvoiceItemId, int outboundInvoiceId, string description, + public BasicOutboundInvoiceItem (int outboundInvoiceItemId, int outboundInvoiceId, string description, Int64 amountCents) { OutboundInvoiceItemId = outboundInvoiceItemId; @@ -14,8 +14,9 @@ namespace Swarmops.Basic.Types AmountCents = amountCents; } - public BasicOutboundInvoiceItem(BasicOutboundInvoiceItem original) : - this(original.OutboundInvoiceItemId, original.OutboundInvoiceId, original.Description, original.AmountCents) + public BasicOutboundInvoiceItem (BasicOutboundInvoiceItem original) : + this (original.OutboundInvoiceItemId, original.OutboundInvoiceId, original.Description, original.AmountCents + ) { // empty copy ctor } diff --git a/Basic/Types/BasicOutboundMail.cs b/Basic/Types/BasicOutboundMail.cs index dfa69373..ed332158 100644 --- a/Basic/Types/BasicOutboundMail.cs +++ b/Basic/Types/BasicOutboundMail.cs @@ -16,7 +16,7 @@ namespace Swarmops.Basic.Types /// /// Basic constructor. This is for database use and NOT for public construction. /// - public BasicOutboundMail(int outboundMailId, MailAuthorType authorType, int authorPersonId, string title, + public BasicOutboundMail (int outboundMailId, MailAuthorType authorType, int authorPersonId, string title, string body, int mailPriority, int mailTypeId, int organizationId, int geographyId, DateTime createdDateTime, DateTime releaseDateTime, bool readyForPickup, bool resolved, @@ -51,10 +51,10 @@ namespace Swarmops.Basic.Types /// /// Constructor used by OutboundMail after creating record in db. NOT for other use /// - public BasicOutboundMail(int outboundMailId, MailAuthorType authorType, int authorPersonId, string title, + public BasicOutboundMail (int outboundMailId, MailAuthorType authorType, int authorPersonId, string title, string body, int mailPriority, int mailType, int organizationId, int geographyId, DateTime createdDateTime, DateTime releaseDateTime) - : this(outboundMailId, authorType, authorPersonId, title, body, + : this (outboundMailId, authorType, authorPersonId, title, body, mailPriority, mailType, organizationId, geographyId, createdDateTime, releaseDateTime, false, false, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, 0, 0, 0) @@ -66,8 +66,8 @@ namespace Swarmops.Basic.Types /// Copy constructor. Used when PirateWeb.Logic constructs an OutboundMail object. /// /// The original to copy. - public BasicOutboundMail(BasicOutboundMail original) - : this( + public BasicOutboundMail (BasicOutboundMail original) + : this ( original.outboundMailId, original.authorType, original.authorPersonId, original.title, original.body, original.mailPriority, original.mailType, original.organizationId, original.geographyId, original.createdDateTime, original.releaseDateTime, diff --git a/Basic/Types/BasicOutboundMailRecipient.cs b/Basic/Types/BasicOutboundMailRecipient.cs index 1ba40727..1ea1bd7d 100644 --- a/Basic/Types/BasicOutboundMailRecipient.cs +++ b/Basic/Types/BasicOutboundMailRecipient.cs @@ -9,7 +9,7 @@ namespace Swarmops.Basic.Types /// /// Normal constructor. /// - public BasicOutboundMailRecipient(int outboundMailRecipientId, int outboundMailId, int personId, bool asOfficer, + public BasicOutboundMailRecipient (int outboundMailRecipientId, int outboundMailId, int personId, bool asOfficer, int personType) { this.outboundMailId = outboundMailId; @@ -22,8 +22,8 @@ namespace Swarmops.Basic.Types /// /// Copy constructor. /// - public BasicOutboundMailRecipient(BasicOutboundMailRecipient original) - : this( + public BasicOutboundMailRecipient (BasicOutboundMailRecipient original) + : this ( original.outboundMailRecipientId, original.outboundMailId, original.personId, original.asOfficer, original.personType) { diff --git a/Basic/Types/BasicPWEvent.cs b/Basic/Types/BasicPWEvent.cs index fd1723d8..464d4fb8 100644 --- a/Basic/Types/BasicPWEvent.cs +++ b/Basic/Types/BasicPWEvent.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPWEvent { - public BasicPWEvent(int eventId, DateTime dateTime, bool open, DateTime processedDateTime, EventType eventType, + public BasicPWEvent (int eventId, DateTime dateTime, bool open, DateTime processedDateTime, EventType eventType, EventSource eventSource, int actingPersonId, int affectedPersonId, int organizationId, int geographyId, int parameterInt, string parameterText) { diff --git a/Basic/Types/BasicPWLog.cs b/Basic/Types/BasicPWLog.cs index 80bf4bee..b9456b8e 100644 --- a/Basic/Types/BasicPWLog.cs +++ b/Basic/Types/BasicPWLog.cs @@ -17,7 +17,7 @@ namespace Swarmops.Basic.Types private string valueAfter; private string valueBefore; - public BasicPWLog(DateTime dateTimeUtc, + public BasicPWLog (DateTime dateTimeUtc, int actingPersonId, string affectedItemType, int affectedItemId, diff --git a/Basic/Types/BasicPaperLetter.cs b/Basic/Types/BasicPaperLetter.cs index dc792994..cba92d0e 100644 --- a/Basic/Types/BasicPaperLetter.cs +++ b/Basic/Types/BasicPaperLetter.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types { public class BasicPaperLetter : IHasIdentity { - public BasicPaperLetter(int paperLetterId, int organizationId, string fromName, string replyAddress, + public BasicPaperLetter (int paperLetterId, int organizationId, string fromName, string replyAddress, DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId, DateTime uploadedDateTime) { @@ -22,8 +22,8 @@ namespace Swarmops.Basic.Types UploadedDateTime = uploadedDateTime; } - public BasicPaperLetter(BasicPaperLetter original) - : this(original.PaperLetterId, original.OrganizationId, original.FromName, original.ReplyAddress, + public BasicPaperLetter (BasicPaperLetter original) + : this (original.PaperLetterId, original.OrganizationId, original.FromName, original.ReplyAddress, original.ReceivedDate, original.ToPersonId, original.ToPersonInRole, original.Personal, original.UploadedByPersonId, original.UploadedDateTime) diff --git a/Basic/Types/BasicParley.cs b/Basic/Types/BasicParley.cs index f3e0dae5..85d626f0 100644 --- a/Basic/Types/BasicParley.cs +++ b/Basic/Types/BasicParley.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicParley : IHasIdentity { - public BasicParley(int parleyId, int organizationId, int personId, int budgetId, DateTime createdDateTime, + public BasicParley (int parleyId, int organizationId, int personId, int budgetId, DateTime createdDateTime, bool open, bool attested, string name, int geographyId, string description, string informationUrl, DateTime startDate, DateTime endDate, Int64 budgetCents, Int64 guaranteeCents, Int64 attendanceFeeCents, DateTime closedDateTime) @@ -29,8 +29,8 @@ namespace Swarmops.Basic.Types ClosedDateTime = closedDateTime; } - public BasicParley(BasicParley original) - : this( + public BasicParley (BasicParley original) + : this ( original.ParleyId, original.OrganizationId, original.PersonId, original.BudgetId, original.CreatedDateTime, original.Open, original.Attested, original.Name, original.GeographyId, original.Description, original.InformationUrl, original.StartDate, original.EndDate, diff --git a/Basic/Types/BasicParleyAttendee.cs b/Basic/Types/BasicParleyAttendee.cs index 7dc0169d..a42cf648 100644 --- a/Basic/Types/BasicParleyAttendee.cs +++ b/Basic/Types/BasicParleyAttendee.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicParleyAttendee : IHasIdentity { - public BasicParleyAttendee(int parleyAttendeeId, int parleyId, int personId, DateTime signupDateTime, + public BasicParleyAttendee (int parleyAttendeeId, int parleyId, int personId, DateTime signupDateTime, bool active, DateTime cancelDateTime, bool invoiced, int outboundInvoiceId, bool isGuest) { ParleyAttendeeId = parleyAttendeeId; @@ -18,8 +18,8 @@ namespace Swarmops.Basic.Types OutboundInvoiceId = outboundInvoiceId; } - public BasicParleyAttendee(BasicParleyAttendee original) - : this( + public BasicParleyAttendee (BasicParleyAttendee original) + : this ( original.ParleyAttendeeId, original.ParleyId, original.PersonId, original.SignupDateTime, original.Active, original.CancelDateTime, original.Invoiced, original.OutboundInvoiceId, original.IsGuest) diff --git a/Basic/Types/BasicParleyOption.cs b/Basic/Types/BasicParleyOption.cs index 4ec39789..c49fcb2b 100644 --- a/Basic/Types/BasicParleyOption.cs +++ b/Basic/Types/BasicParleyOption.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicParleyOption : IHasIdentity { - public BasicParleyOption(int parleyOptionId, int parleyId, string description, Int64 amountCents, bool active) + public BasicParleyOption (int parleyOptionId, int parleyId, string description, Int64 amountCents, bool active) { ParleyOptionId = parleyOptionId; ParleyId = parleyId; @@ -14,8 +14,8 @@ namespace Swarmops.Basic.Types Active = active; } - public BasicParleyOption(BasicParleyOption original) - : this( + public BasicParleyOption (BasicParleyOption original) + : this ( original.ParleyOptionId, original.ParleyId, original.Description, original.AmountCents, original.Active) { // empty copy ctor diff --git a/Basic/Types/BasicPayment.cs b/Basic/Types/BasicPayment.cs index f4f2ee68..54d4d87f 100644 --- a/Basic/Types/BasicPayment.cs +++ b/Basic/Types/BasicPayment.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPayment : IHasIdentity { - public BasicPayment(int paymentId, int paymentGroupId, Int64 amountCents, string reference, string fromAccount, + public BasicPayment (int paymentId, int paymentGroupId, Int64 amountCents, string reference, string fromAccount, string key, bool hasImage, int outboundInvoiceId) { PaymentId = paymentId; @@ -18,8 +18,8 @@ namespace Swarmops.Basic.Types OutboundInvoiceId = outboundInvoiceId; } - public BasicPayment(BasicPayment original) - : this( + public BasicPayment (BasicPayment original) + : this ( original.PaymentId, original.PaymentGroupId, original.AmountCents, original.Reference, original.FromAccount, original.Key, original.HasImage, original.OutboundInvoiceId) { diff --git a/Basic/Types/BasicPaymentCode.cs b/Basic/Types/BasicPaymentCode.cs index f67e5f85..813bb534 100644 --- a/Basic/Types/BasicPaymentCode.cs +++ b/Basic/Types/BasicPaymentCode.cs @@ -20,7 +20,7 @@ namespace Swarmops.Basic.Types #endregion - public BasicPaymentCode(int paymentCodeId, string paymentCode, string issuedToPhoneNumber, int issuedToPersonId, + public BasicPaymentCode (int paymentCodeId, string paymentCode, string issuedToPhoneNumber, int issuedToPersonId, bool claimed) { this.paymentCodeId = paymentCodeId; @@ -30,8 +30,8 @@ namespace Swarmops.Basic.Types this.claimed = claimed; } - public BasicPaymentCode(BasicPaymentCode original) - : this( + public BasicPaymentCode (BasicPaymentCode original) + : this ( original.paymentCodeId, original.paymentCode, original.issuedToPhoneNumber, original.issuedToPersonId, original.claimed) { diff --git a/Basic/Types/BasicPaymentGroup.cs b/Basic/Types/BasicPaymentGroup.cs index 76bbc27f..55982fc7 100644 --- a/Basic/Types/BasicPaymentGroup.cs +++ b/Basic/Types/BasicPaymentGroup.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPaymentGroup : IHasIdentity { - public BasicPaymentGroup(int paymentGroupId, int organizationId, DateTime dateTime, int currencyId, + public BasicPaymentGroup (int paymentGroupId, int organizationId, DateTime dateTime, int currencyId, Int64 amountCents, string tag, int createdByPersonId, DateTime createdDateTime, bool open) { PaymentGroupId = paymentGroupId; @@ -19,8 +19,8 @@ namespace Swarmops.Basic.Types Open = open; } - public BasicPaymentGroup(BasicPaymentGroup original) - : this( + public BasicPaymentGroup (BasicPaymentGroup original) + : this ( original.PaymentGroupId, original.OrganizationId, original.DateTime, original.CurrencyId, original.AmountCents, original.Tag, original.CreatedByPersonId, original.CreatedDateTime, original.Open) { diff --git a/Basic/Types/BasicPaymentInformation.cs b/Basic/Types/BasicPaymentInformation.cs index 36d97c2b..6a6ce121 100644 --- a/Basic/Types/BasicPaymentInformation.cs +++ b/Basic/Types/BasicPaymentInformation.cs @@ -2,14 +2,14 @@ namespace Swarmops.Basic.Types { public class BasicPaymentInformation { - public BasicPaymentInformation(PaymentInformationType type, string data) + public BasicPaymentInformation (PaymentInformationType type, string data) { Type = type; Data = data; } - public BasicPaymentInformation(BasicPaymentInformation original) - : this(original.Type, original.Data) + public BasicPaymentInformation (BasicPaymentInformation original) + : this (original.Type, original.Data) { // empty copy ctor } diff --git a/Basic/Types/BasicPayout.cs b/Basic/Types/BasicPayout.cs index fdc00535..937cd91f 100644 --- a/Basic/Types/BasicPayout.cs +++ b/Basic/Types/BasicPayout.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPayout : IHasIdentity { - public BasicPayout(int payoutId, int organizationId, string bank, string account, + public BasicPayout (int payoutId, int organizationId, string bank, string account, string reference, Int64 amountCents, DateTime expectedTransactionDate, bool open, DateTime createdDateTime, int createdByPersonId) { @@ -21,8 +21,8 @@ namespace Swarmops.Basic.Types CreatedByPersonId = createdByPersonId; } - public BasicPayout(BasicPayout original) : - this(original.PayoutId, original.OrganizationId, original.Bank, original.Account, + public BasicPayout (BasicPayout original) : + this (original.PayoutId, original.OrganizationId, original.Bank, original.Account, original.Reference, original.AmountCents, original.ExpectedTransactionDate, original.Open, original.CreatedDateTime, original.CreatedByPersonId) { diff --git a/Basic/Types/BasicPayrollAdjustment.cs b/Basic/Types/BasicPayrollAdjustment.cs index cc979af2..fcd59242 100644 --- a/Basic/Types/BasicPayrollAdjustment.cs +++ b/Basic/Types/BasicPayrollAdjustment.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPayrollAdjustment : IHasIdentity { - public BasicPayrollAdjustment(int payrollAdjustmentId, int payrollItemId, PayrollAdjustmentType type, + public BasicPayrollAdjustment (int payrollAdjustmentId, int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, string description, bool open, int salaryId) { @@ -19,8 +19,8 @@ namespace Swarmops.Basic.Types } - public BasicPayrollAdjustment(BasicPayrollAdjustment original) - : this( + public BasicPayrollAdjustment (BasicPayrollAdjustment original) + : this ( original.PayrollAdjustmentId, original.PayrollItemId, original.Type, original.AmountCents, original.Description, original.Open, original.SalaryId) { diff --git a/Basic/Types/BasicPayrollItem.cs b/Basic/Types/BasicPayrollItem.cs index 87a33227..49e4e555 100644 --- a/Basic/Types/BasicPayrollItem.cs +++ b/Basic/Types/BasicPayrollItem.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicPayrollItem : IHasIdentity { - public BasicPayrollItem(int payrollItemId, int personId, int organizationId, int countryId, + public BasicPayrollItem (int payrollItemId, int personId, int organizationId, int countryId, DateTime employedDate, int reportsToPersonId, Int64 baseSalaryCents, int budgetId, bool open, DateTime terminatedDate, int subtractiveTaxLevelId, double additiveTaxLevel) @@ -24,8 +24,8 @@ namespace Swarmops.Basic.Types AdditiveTaxLevel = additiveTaxLevel; } - public BasicPayrollItem(BasicPayrollItem original) - : this(original.PayrollItemId, original.PersonId, original.OrganizationId, original.CountryId, + public BasicPayrollItem (BasicPayrollItem original) + : this (original.PayrollItemId, original.PersonId, original.OrganizationId, original.CountryId, original.EmployedDate, original.ReportsToPersonId, original.BaseSalaryCents, original.BudgetId, original.Open, original.TerminatedDate, original.SubtractiveTaxLevelId, original.AdditiveTaxLevel) { diff --git a/Basic/Types/BasicPermission.cs b/Basic/Types/BasicPermission.cs index a244e0a4..016619ec 100644 --- a/Basic/Types/BasicPermission.cs +++ b/Basic/Types/BasicPermission.cs @@ -7,7 +7,7 @@ namespace Swarmops.Basic.Types public Permission PermissionType; public RoleType RoleType; - public BasicPermission(RoleType pRoleType, Permission pPermissionType) + public BasicPermission (RoleType pRoleType, Permission pPermissionType) { this.RoleType = pRoleType; this.PermissionType = pPermissionType; diff --git a/Basic/Types/BasicPerson.cs b/Basic/Types/BasicPerson.cs index f721c81e..9607acb5 100644 --- a/Basic/Types/BasicPerson.cs +++ b/Basic/Types/BasicPerson.cs @@ -7,13 +7,13 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicPerson : IEmailPerson, IHasIdentity { - public BasicPerson(string name, string email) + public BasicPerson (string name, string email) { Name = name; Email = email; } - public BasicPerson(int personId, string passwordHash, string name, string email, string street, + public BasicPerson (int personId, string passwordHash, string name, string email, string street, string postalCode, string cityName, int countryId, string phone, int geographyId, DateTime birthdate, PersonGender gender) { @@ -31,8 +31,8 @@ namespace Swarmops.Basic.Types Gender = gender; } - public BasicPerson(BasicPerson original) - : this(original.PersonId, original.PasswordHash, original.Name, original.Email, original.Street, + public BasicPerson (BasicPerson original) + : this (original.PersonId, original.PasswordHash, original.Name, original.Email, original.Street, original.PostalCode, original.CityName, original.CountryId, original.Phone, original.GeographyId, original.Birthdate, original.Gender) { diff --git a/Basic/Types/BasicPersonRole.cs b/Basic/Types/BasicPersonRole.cs index 45d21849..d02ca1b6 100644 --- a/Basic/Types/BasicPersonRole.cs +++ b/Basic/Types/BasicPersonRole.cs @@ -31,7 +31,7 @@ namespace Swarmops.Basic.Types /// The node-specific role. /// The organization Id. /// The node Id. - public BasicPersonRole(int roleId, int personId, RoleType type, int organizationId, int geographyId) + public BasicPersonRole (int roleId, int personId, RoleType type, int organizationId, int geographyId) { this.roleId = roleId; this.personId = personId; @@ -43,8 +43,8 @@ namespace Swarmops.Basic.Types /// /// Copy constructor. /// - public BasicPersonRole(BasicPersonRole original) - : this(original.roleId, original.personId, original.type, original.organizationId, original.geographyId) + public BasicPersonRole (BasicPersonRole original) + : this (original.roleId, original.personId, original.type, original.organizationId, original.geographyId) { } diff --git a/Basic/Types/BasicPostalCode.cs b/Basic/Types/BasicPostalCode.cs index 366126bc..b058db06 100644 --- a/Basic/Types/BasicPostalCode.cs +++ b/Basic/Types/BasicPostalCode.cs @@ -5,20 +5,20 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicPostalCode { - public BasicPostalCode(int postalCodeId, string postalCode, int cityId, int countryId) + public BasicPostalCode (int postalCodeId, string postalCode, int cityId, int countryId) { PostalCodeId = postalCodeId; - PostalCode = postalCode.Replace(" ", ""); + PostalCode = postalCode.Replace (" ", ""); CityId = cityId; CountryId = countryId; } - public BasicPostalCode(BasicPostalCode original) - : this(original.PostalCodeId, original.PostalCode, original.CityId, original.CountryId) + public BasicPostalCode (BasicPostalCode original) + : this (original.PostalCodeId, original.PostalCode, original.CityId, original.CountryId) { } - [Obsolete("Do not call this ctor directly. It exists to enable serialization.", true)] + [Obsolete ("Do not call this ctor directly. It exists to enable serialization.", true)] public BasicPostalCode() { // this should never be called from code diff --git a/Basic/Types/BasicRefund.cs b/Basic/Types/BasicRefund.cs index 39ad2415..56f1b19f 100644 --- a/Basic/Types/BasicRefund.cs +++ b/Basic/Types/BasicRefund.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicRefund : IHasIdentity { - public BasicRefund(int refundId, int paymentId, bool open, Int64 amountCents, int createdByPersonId, + public BasicRefund (int refundId, int paymentId, bool open, Int64 amountCents, int createdByPersonId, DateTime createdDateTime, DateTime closedDateTime) { RefundId = refundId; @@ -17,8 +17,8 @@ namespace Swarmops.Basic.Types ClosedDateTime = closedDateTime; } - public BasicRefund(BasicRefund original) - : this( + public BasicRefund (BasicRefund original) + : this ( original.RefundId, original.PaymentId, original.Open, original.AmountCents, original.CreatedByPersonId, original.CreatedDateTime, original.ClosedDateTime) { diff --git a/Basic/Types/BasicReporter.cs b/Basic/Types/BasicReporter.cs index 1add44ff..b9edce63 100644 --- a/Basic/Types/BasicReporter.cs +++ b/Basic/Types/BasicReporter.cs @@ -18,7 +18,7 @@ namespace Swarmops.Basic.Types #endregion - public BasicReporter(int reporterId, string name, string email, int[] mediaCategoryIds) + public BasicReporter (int reporterId, string name, string email, int[] mediaCategoryIds) { this.reporterId = reporterId; this.name = name; @@ -26,8 +26,8 @@ namespace Swarmops.Basic.Types this.mediaCategoryIds = mediaCategoryIds; } - public BasicReporter(BasicReporter original) : - this(original.reporterId, original.name, original.email, original.mediaCategoryIds) + public BasicReporter (BasicReporter original) : + this (original.reporterId, original.name, original.email, original.mediaCategoryIds) { } diff --git a/Basic/Types/BasicSalary.cs b/Basic/Types/BasicSalary.cs index 81f5a339..dbbaad8a 100644 --- a/Basic/Types/BasicSalary.cs +++ b/Basic/Types/BasicSalary.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicSalary : IHasIdentity { - public BasicSalary(int salaryId, int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, + public BasicSalary (int salaryId, int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents, bool attested, bool netPaid, bool taxPaid, bool open) { @@ -22,8 +22,8 @@ namespace Swarmops.Basic.Types Open = open; } - public BasicSalary(BasicSalary original) - : this( + public BasicSalary (BasicSalary original) + : this ( original.SalaryId, original.PayrollItemId, original.PayoutDate, original.BaseSalaryCents, original.NetSalaryCents, original.SubtractiveTaxCents, original.AdditiveTaxCents, original.Attested, original.NetPaid, diff --git a/Basic/Types/BasicSupplier.cs b/Basic/Types/BasicSupplier.cs index 31a8b4c1..d670d9b0 100644 --- a/Basic/Types/BasicSupplier.cs +++ b/Basic/Types/BasicSupplier.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicSupplier : IHasIdentity { - public BasicSupplier(int supplierId, string name, string email, string passwordHash, string bankAccount, + public BasicSupplier (int supplierId, string name, string email, string passwordHash, string bankAccount, DateTime createdDateTime, int createdByPersonId) { SupplierId = supplierId; @@ -17,8 +17,8 @@ namespace Swarmops.Basic.Types CreatedByPersonId = createdByPersonId; } - public BasicSupplier(BasicSupplier original) - : this( + public BasicSupplier (BasicSupplier original) + : this ( original.SupplierId, original.Name, original.Email, original.PasswordHash, original.BankAccount, original.CreatedDateTime, original.CreatedByPersonId) { diff --git a/Basic/Types/BasicSwarmopsLogEntry.cs b/Basic/Types/BasicSwarmopsLogEntry.cs index 9819e671..d77a6dd3 100644 --- a/Basic/Types/BasicSwarmopsLogEntry.cs +++ b/Basic/Types/BasicSwarmopsLogEntry.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types { public class BasicSwarmopsLogEntry : IHasIdentity { - public BasicSwarmopsLogEntry(int swarmopsLogEntryId, int personId, DateTime dateTime, int entryTypeId, + public BasicSwarmopsLogEntry (int swarmopsLogEntryId, int personId, DateTime dateTime, int entryTypeId, string entryXml) { SwarmopsLogEntryId = swarmopsLogEntryId; @@ -15,8 +15,8 @@ namespace Swarmops.Basic.Types EntryXml = entryXml; } - public BasicSwarmopsLogEntry(BasicSwarmopsLogEntry original) - : this( + public BasicSwarmopsLogEntry (BasicSwarmopsLogEntry original) + : this ( original.SwarmopsLogEntryId, original.PersonId, original.DateTime, original.EntryTypeId, original.EntryXml) { diff --git a/Basic/Types/BasicUptakeGeography.cs b/Basic/Types/BasicUptakeGeography.cs index 05d92a9f..4671578e 100644 --- a/Basic/Types/BasicUptakeGeography.cs +++ b/Basic/Types/BasicUptakeGeography.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types private int geoId; private int orgId; - public BasicUptakeGeography(int pOrgId, int pGeoId) + public BasicUptakeGeography (int pOrgId, int pGeoId) { this.orgId = pOrgId; this.geoId = pGeoId; @@ -15,7 +15,7 @@ namespace Swarmops.Basic.Types { } - public BasicUptakeGeography(BasicUptakeGeography other) + public BasicUptakeGeography (BasicUptakeGeography other) { this.orgId = other.orgId; this.geoId = other.geoId; diff --git a/Basic/Types/BasicVolunteer.cs b/Basic/Types/BasicVolunteer.cs index 0689fc4e..b3ddaf8a 100644 --- a/Basic/Types/BasicVolunteer.cs +++ b/Basic/Types/BasicVolunteer.cs @@ -13,7 +13,7 @@ namespace Swarmops.Basic.Types private readonly int personId; private readonly int volunteerId; - public BasicVolunteer(int volunteerId, int personId, int ownerPersonId, DateTime openedDateTime, + public BasicVolunteer (int volunteerId, int personId, int ownerPersonId, DateTime openedDateTime, bool open, DateTime closedDateTime, string closingComments) { this.volunteerId = volunteerId; @@ -25,8 +25,8 @@ namespace Swarmops.Basic.Types this.closingComments = closingComments; } - public BasicVolunteer(BasicVolunteer original) - : this(original.volunteerId, original.personId, original.ownerPersonId, original.openedDateTime, + public BasicVolunteer (BasicVolunteer original) + : this (original.volunteerId, original.personId, original.ownerPersonId, original.openedDateTime, original.open, original.closedDateTime, original.closingComments) { // copy ctor diff --git a/Basic/Types/BasicVolunteerRole.cs b/Basic/Types/BasicVolunteerRole.cs index 31652e92..1e524ff7 100644 --- a/Basic/Types/BasicVolunteerRole.cs +++ b/Basic/Types/BasicVolunteerRole.cs @@ -13,7 +13,7 @@ namespace Swarmops.Basic.Types private readonly int volunteerId; private readonly int volunteerRoleId; - public BasicVolunteerRole(int volunteerRoleId, int volunteerId, int organizationId, int geographyId, + public BasicVolunteerRole (int volunteerRoleId, int volunteerId, int organizationId, int geographyId, RoleType roleType, bool open, bool assigned) { this.volunteerRoleId = volunteerRoleId; @@ -25,8 +25,8 @@ namespace Swarmops.Basic.Types this.assigned = assigned; } - public BasicVolunteerRole(BasicVolunteerRole original) - : this(original.volunteerRoleId, original.volunteerId, original.organizationId, original.geographyId, + public BasicVolunteerRole (BasicVolunteerRole original) + : this (original.volunteerRoleId, original.volunteerId, original.organizationId, original.geographyId, original.roleType, original.open, original.assigned) { } diff --git a/Basic/Types/Communications/BasicAutoMail.cs b/Basic/Types/Communications/BasicAutoMail.cs index a5ba80ad..a17f843c 100644 --- a/Basic/Types/Communications/BasicAutoMail.cs +++ b/Basic/Types/Communications/BasicAutoMail.cs @@ -16,7 +16,7 @@ namespace Swarmops.Basic.Types.Communications /// /// Basic constructor. /// - public BasicAutoMail(int autoMailId, AutoMailType type, int organizationId, int geographyId, + public BasicAutoMail (int autoMailId, AutoMailType type, int organizationId, int geographyId, int authorPersonId, string title, string body) { this.autoMailId = autoMailId; @@ -32,8 +32,8 @@ namespace Swarmops.Basic.Types.Communications /// /// Copy constructor. /// - public BasicAutoMail(BasicAutoMail original) - : this(original.autoMailId, original.type, original.organizationId, original.geographyId, + public BasicAutoMail (BasicAutoMail original) + : this (original.autoMailId, original.type, original.organizationId, original.geographyId, original.authorPersonId, original.title, original.body) { } diff --git a/Basic/Types/Communications/BasicOutboundComm.cs b/Basic/Types/Communications/BasicOutboundComm.cs index f33c9059..ec0c8f28 100644 --- a/Basic/Types/Communications/BasicOutboundComm.cs +++ b/Basic/Types/Communications/BasicOutboundComm.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types.Communications { public class BasicOutboundComm : IHasIdentity { - public BasicOutboundComm(int outboundCommId, int senderPersonId, int fromPersonId, int organizationId, + public BasicOutboundComm (int outboundCommId, int senderPersonId, int fromPersonId, int organizationId, DateTime createdDateTime, string resolverClass, string recipientDataXml, bool resolved, DateTime resolvedDateTime, OutboundCommPriority priority, string transmitterClass, string payloadXml, bool open, DateTime startTransmitDateTime, DateTime closedDateTime, int recipientCount, @@ -33,8 +33,8 @@ namespace Swarmops.Basic.Types.Communications } - public BasicOutboundComm(BasicOutboundComm original) : - this( + public BasicOutboundComm (BasicOutboundComm original) : + this ( original.OutboundCommId, original.SenderPersonId, original.FromPersonId, original.OrganizationId, original.CreatedDateTime, original.ResolverClass, original.RecipientDataXml, original.Resolved, original.ResolvedDateTime, original.Priority, original.TransmitterClass, original.PayloadXml, diff --git a/Basic/Types/Communications/BasicOutboundCommRecipient.cs b/Basic/Types/Communications/BasicOutboundCommRecipient.cs index 1d587460..4b0b2577 100644 --- a/Basic/Types/Communications/BasicOutboundCommRecipient.cs +++ b/Basic/Types/Communications/BasicOutboundCommRecipient.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types.Communications { public class BasicOutboundCommRecipient : IHasIdentity { - public BasicOutboundCommRecipient(int outboundCommRecipientId, int outboundCommId, int personId, bool open, + public BasicOutboundCommRecipient (int outboundCommRecipientId, int outboundCommId, int personId, bool open, bool success, string failReason) { OutboundCommRecipientId = outboundCommRecipientId; @@ -15,8 +15,8 @@ namespace Swarmops.Basic.Types.Communications FailReason = failReason; } - public BasicOutboundCommRecipient(BasicOutboundCommRecipient original) : - this( + public BasicOutboundCommRecipient (BasicOutboundCommRecipient original) : + this ( original.OutboundCommRecipientId, original.OutboundCommId, original.PersonId, original.Open, original.Success, original.FailReason) { diff --git a/Basic/Types/Financial/BasicCashAdvance.cs b/Basic/Types/Financial/BasicCashAdvance.cs index ed0a836a..0b870837 100644 --- a/Basic/Types/Financial/BasicCashAdvance.cs +++ b/Basic/Types/Financial/BasicCashAdvance.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types.Financial [Serializable] public class BasicCashAdvance : IHasIdentity { - public BasicCashAdvance(int cashAdvanceId, int organizationId, int personId, DateTime createdDateTime, + public BasicCashAdvance (int cashAdvanceId, int organizationId, int personId, DateTime createdDateTime, int createdByPersonId, int financialAccountId, Int64 amountCents, string description, bool open, bool attested, bool paidOut, int attestedByPersonId, DateTime attestedDateTime) @@ -26,8 +26,8 @@ namespace Swarmops.Basic.Types.Financial AttestedDateTime = attestedDateTime; } - public BasicCashAdvance(BasicCashAdvance original) : - this( + public BasicCashAdvance (BasicCashAdvance original) : + this ( original.CashAdvanceId, original.OrganizationId, original.PersonId, original.CreatedDateTime, original.CreatedByPersonId, original.BudgetId, original.AmountCents, original.Description, original.Open, original.Attested, diff --git a/Basic/Types/Financial/BasicFinancialAccount.cs b/Basic/Types/Financial/BasicFinancialAccount.cs index c0d9fce9..a71ca594 100644 --- a/Basic/Types/Financial/BasicFinancialAccount.cs +++ b/Basic/Types/Financial/BasicFinancialAccount.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialAccount : IHasIdentity { - public BasicFinancialAccount(int financialAccountId, string name, FinancialAccountType accountType, + public BasicFinancialAccount (int financialAccountId, string name, FinancialAccountType accountType, int organizationId, int parentFinancialAccountId, int ownerPersonId, bool open, int openedYear, int closedYear, bool active, bool expensable, bool administrative, int linkBackward, int linkForward) @@ -26,8 +26,8 @@ namespace Swarmops.Basic.Types.Financial LinkForward = linkForward; } - public BasicFinancialAccount(BasicFinancialAccount original) : - this( + public BasicFinancialAccount (BasicFinancialAccount original) : + this ( original.Identity, original.Name, original.AccountType, original.OrganizationId, original.ParentFinancialAccountId, original.OwnerPersonId, original.Open, original.OpenedYear, original.ClosedYear, original.Active, original.Expensable, original.Administrative, original.LinkBackward, diff --git a/Basic/Types/Financial/BasicFinancialAccountRow.cs b/Basic/Types/Financial/BasicFinancialAccountRow.cs index b6416ee1..9aab0549 100644 --- a/Basic/Types/Financial/BasicFinancialAccountRow.cs +++ b/Basic/Types/Financial/BasicFinancialAccountRow.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialAccountRow { - public BasicFinancialAccountRow(int financialAccountId, int financialTransactionId, DateTime dateTime, + public BasicFinancialAccountRow (int financialAccountId, int financialTransactionId, DateTime dateTime, string comment, Int64 amountCents, DateTime rowDateTime, int rowCreatedByPersonId) { FinancialAccountId = financialAccountId; @@ -16,8 +16,8 @@ namespace Swarmops.Basic.Types.Financial RowCreatedByPersonId = rowCreatedByPersonId; } - public BasicFinancialAccountRow(BasicFinancialAccountRow original) - : this( + public BasicFinancialAccountRow (BasicFinancialAccountRow original) + : this ( original.FinancialAccountId, original.FinancialTransactionId, original.TransactionDateTime, original.Description, original.AmountCents, original.RowDateTime, original.RowCreatedByPersonId) diff --git a/Basic/Types/Financial/BasicFinancialDependency.cs b/Basic/Types/Financial/BasicFinancialDependency.cs index f7a9535a..72b08de2 100644 --- a/Basic/Types/Financial/BasicFinancialDependency.cs +++ b/Basic/Types/Financial/BasicFinancialDependency.cs @@ -7,7 +7,7 @@ namespace Swarmops.Basic.Types.Financial /// public class BasicFinancialDependency { - public BasicFinancialDependency(int objectId, FinancialDependencyType dependencyType, int foreignId) + public BasicFinancialDependency (int objectId, FinancialDependencyType dependencyType, int foreignId) { ObjectId = objectId; DependencyType = dependencyType; diff --git a/Basic/Types/Financial/BasicFinancialTransaction.cs b/Basic/Types/Financial/BasicFinancialTransaction.cs index 1df04f62..9024b5e2 100644 --- a/Basic/Types/Financial/BasicFinancialTransaction.cs +++ b/Basic/Types/Financial/BasicFinancialTransaction.cs @@ -11,7 +11,7 @@ namespace Swarmops.Basic.Types.Financial private readonly int organizationId; private string description; - public BasicFinancialTransaction(int financialTransactionId, int organizationId, DateTime dateTime, + public BasicFinancialTransaction (int financialTransactionId, int organizationId, DateTime dateTime, string description, string importHash) { this.financialTransactionId = financialTransactionId; @@ -21,8 +21,8 @@ namespace Swarmops.Basic.Types.Financial this.importHash = importHash; } - public BasicFinancialTransaction(BasicFinancialTransaction original) : - this( + public BasicFinancialTransaction (BasicFinancialTransaction original) : + this ( original.financialTransactionId, original.organizationId, original.dateTime, original.description, original.importHash) { diff --git a/Basic/Types/Financial/BasicFinancialTransactionRow.cs b/Basic/Types/Financial/BasicFinancialTransactionRow.cs index c69a6088..f25dd1f5 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionRow.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionRow.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransactionRow : IHasIdentity { - public BasicFinancialTransactionRow(int financialTransactionRowId, int financialAccountId, + public BasicFinancialTransactionRow (int financialTransactionRowId, int financialAccountId, int financialTransactionId, Int64 amountCents, DateTime createdDateTime, int createdByPersonId) { FinancialTransactionRowId = financialTransactionRowId; @@ -16,8 +16,8 @@ namespace Swarmops.Basic.Types.Financial CreatedByPersonId = createdByPersonId; } - public BasicFinancialTransactionRow(BasicFinancialTransactionRow original) - : this( + public BasicFinancialTransactionRow (BasicFinancialTransactionRow original) + : this ( original.FinancialTransactionRowId, original.FinancialAccountId, original.FinancialTransactionId, original.AmountCents, original.CreatedDateTime, original.CreatedByPersonId) { diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs b/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs index 033eafd9..5d3eafc5 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransactionTagSet : IHasIdentity { - public BasicFinancialTransactionTagSet(int financialTransactionTagSetId, int financialTransactionTagSetTypeId, + public BasicFinancialTransactionTagSet (int financialTransactionTagSetId, int financialTransactionTagSetTypeId, int organizationId, int order, bool allowUntagged, int visibilityLevel, int profitLossType) { FinancialTransactionTagSetId = financialTransactionTagSetId; @@ -16,8 +16,8 @@ namespace Swarmops.Basic.Types.Financial ProfitLossType = profitLossType; } - public BasicFinancialTransactionTagSet(BasicFinancialTransactionTagSet original) : - this( + public BasicFinancialTransactionTagSet (BasicFinancialTransactionTagSet original) : + this ( original.FinancialTransactionTagSetId, original.FinancialTransactionTagSetTypeId, original.OrganizationId, original.Order, original.AllowUntagged, original.VisibilityLevel, original.ProfitLossType) { diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs b/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs index 6102f894..3c957053 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs @@ -4,14 +4,14 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransactionTagSetType : IHasIdentity { - public BasicFinancialTransactionTagSetType(int financialTransactionTagSetTypeId, string resourceName) + public BasicFinancialTransactionTagSetType (int financialTransactionTagSetTypeId, string resourceName) { FinancialTransactionTagSetTypeId = financialTransactionTagSetTypeId; ResourceName = resourceName; } - public BasicFinancialTransactionTagSetType(BasicFinancialTransactionTagSetType original) : - this(original.FinancialTransactionTagSetTypeId, original.ResourceName) + public BasicFinancialTransactionTagSetType (BasicFinancialTransactionTagSetType original) : + this (original.FinancialTransactionTagSetTypeId, original.ResourceName) { // copy ctor } diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagType.cs b/Basic/Types/Financial/BasicFinancialTransactionTagType.cs index 85b0fdcb..40652b59 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagType.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagType.cs @@ -4,7 +4,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransactionTagType : IHasIdentity { - public BasicFinancialTransactionTagType(int financialTransactionTagTypeId, + public BasicFinancialTransactionTagType (int financialTransactionTagTypeId, int parentFinancialTransactionTagTypeId, int financialTransactionTagSetId, string name, bool active, int openedYear, int closedYear) { @@ -17,8 +17,8 @@ namespace Swarmops.Basic.Types.Financial ClosedYear = closedYear; } - public BasicFinancialTransactionTagType(BasicFinancialTransactionTagType original) : - this( + public BasicFinancialTransactionTagType (BasicFinancialTransactionTagType original) : + this ( original.FinancialTransactionTagTypeId, original.ParentFinancialTransactionTagTypeId, original.FinancialTransactionTagSetId, original.Name, original.Active, original.OpenedYear, original.ClosedYear) diff --git a/Basic/Types/Financial/BasicFinancialValidation.cs b/Basic/Types/Financial/BasicFinancialValidation.cs index f239bc5d..f8c1ad46 100644 --- a/Basic/Types/Financial/BasicFinancialValidation.cs +++ b/Basic/Types/Financial/BasicFinancialValidation.cs @@ -6,7 +6,7 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialValidation : IHasIdentity { - public BasicFinancialValidation(int financialValidationId, FinancialValidationType validationType, int personId, + public BasicFinancialValidation (int financialValidationId, FinancialValidationType validationType, int personId, DateTime dateTime, FinancialDependencyType dependencyType, int foreignId) { FinancialValidationId = financialValidationId; @@ -17,8 +17,8 @@ namespace Swarmops.Basic.Types.Financial ForeignId = foreignId; } - public BasicFinancialValidation(BasicFinancialValidation original) - : this( + public BasicFinancialValidation (BasicFinancialValidation original) + : this ( original.Identity, original.ValidationType, original.PersonId, original.DateTime, original.DependencyType, original.ForeignId) { diff --git a/Basic/Types/Governance/BasicMeeting.cs b/Basic/Types/Governance/BasicMeeting.cs index 77419b6d..ceedc0c6 100644 --- a/Basic/Types/Governance/BasicMeeting.cs +++ b/Basic/Types/Governance/BasicMeeting.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types.Governance { public class BasicMeeting : IHasIdentity { - public BasicMeeting(int meetingId, int organizationId, string name, DateTime motionSubmissionEnds, + public BasicMeeting (int meetingId, int organizationId, string name, DateTime motionSubmissionEnds, DateTime amendmentSubmissionEnds, DateTime amendmentVotingStarts, DateTime amendmentVotingEnds, DateTime motionVotingStarts, DateTime motionVotingEnds) { @@ -20,8 +20,8 @@ namespace Swarmops.Basic.Types.Governance MotionVotingEnds = motionVotingEnds; } - public BasicMeeting(BasicMeeting original) : - this( + public BasicMeeting (BasicMeeting original) : + this ( original.MeetingId, original.OrganizationId, original.Name, original.MotionSubmissionEnds, original.AmendmentSubmissionEnds, original.AmendmentVotingStarts, original.AmendmentVotingEnds, original.MotionVotingStarts, original.MotionVotingEnds) diff --git a/Basic/Types/Governance/BasicMotion.cs b/Basic/Types/Governance/BasicMotion.cs index 32498379..e5c0c031 100644 --- a/Basic/Types/Governance/BasicMotion.cs +++ b/Basic/Types/Governance/BasicMotion.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types.Governance { public class BasicMotion : IHasIdentity { - public BasicMotion(int motionId, int meetingId, int sequenceNumber, string designation, int submittedByPersonId, + public BasicMotion (int motionId, int meetingId, int sequenceNumber, string designation, int submittedByPersonId, int createdByPersonId, DateTime createdDateTime, bool amended, int amendedByPersonId, DateTime amendedDateTime, string title, string text, string amendedText, string decisionPoints, string amendedDecisionPoints, string threadUrl, bool open, bool carried) @@ -30,8 +30,8 @@ namespace Swarmops.Basic.Types.Governance Carried = carried; } - public BasicMotion(BasicMotion original) : - this( + public BasicMotion (BasicMotion original) : + this ( original.MotionId, original.MeetingId, original.SequenceNumber, original.Designation, original.SubmittedByPersonId, original.CreatedByPersonId, original.CreatedDateTime, original.Amended, original.AmendedByPersonId, original.AmendedDateTime, original.Title, original.Text, original.AmendedText, diff --git a/Basic/Types/Governance/BasicMotionAmendment.cs b/Basic/Types/Governance/BasicMotionAmendment.cs index 1174400b..0147bd2f 100644 --- a/Basic/Types/Governance/BasicMotionAmendment.cs +++ b/Basic/Types/Governance/BasicMotionAmendment.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic.Types.Governance { public class BasicMotionAmendment : IHasIdentity { - public BasicMotionAmendment(int motionAmendmentId, int motionId, int sequenceNumber, int submittedByPersonId, + public BasicMotionAmendment (int motionAmendmentId, int motionId, int sequenceNumber, int submittedByPersonId, int createdByPersonId, DateTime createdDateTime, string title, string text, string decisionPoint, bool open, bool carried) { @@ -22,8 +22,8 @@ namespace Swarmops.Basic.Types.Governance Carried = carried; } - public BasicMotionAmendment(BasicMotionAmendment original) : - this( + public BasicMotionAmendment (BasicMotionAmendment original) : + this ( original.MotionAmendmentId, original.MotionId, original.SequenceNumber, original.SubmittedByPersonId, original.CreatedByPersonId, original.CreatedDateTime, original.Title, original.Text, original.DecisionPoint, original.Open, original.Carried) diff --git a/Basic/Types/Security/BasicAuthority.cs b/Basic/Types/Security/BasicAuthority.cs index 85059296..4f7655be 100644 --- a/Basic/Types/Security/BasicAuthority.cs +++ b/Basic/Types/Security/BasicAuthority.cs @@ -13,13 +13,13 @@ namespace Swarmops.Basic.Types.Security public readonly int PersonId; public readonly BasicPersonRole[] SystemPersonRoles; - public BasicAuthority(int personId, BasicPersonRole[] systemPersonRoles, + public BasicAuthority (int personId, BasicPersonRole[] systemPersonRoles, BasicPersonRole[] organizationPersonRoles, BasicPersonRole[] nodePersonRoles) { if (personId < 1) { - throw new ArgumentOutOfRangeException("PersonId cannot be " + personId); + throw new ArgumentOutOfRangeException ("PersonId cannot be " + personId); } this.PersonId = personId; @@ -47,13 +47,13 @@ namespace Swarmops.Basic.Types.Security this.SystemPersonRoles.Length + this.OrganizationPersonRoles.Length + this.LocalPersonRoles.Length]; if (this.SystemPersonRoles.Length > 0) - this.SystemPersonRoles.CopyTo(this.AllPersonRoles, 0); + this.SystemPersonRoles.CopyTo (this.AllPersonRoles, 0); if (this.OrganizationPersonRoles.Length > 0) - this.OrganizationPersonRoles.CopyTo(this.AllPersonRoles, this.SystemPersonRoles.Length); + this.OrganizationPersonRoles.CopyTo (this.AllPersonRoles, this.SystemPersonRoles.Length); if (this.LocalPersonRoles.Length > 0) - this.LocalPersonRoles.CopyTo(this.AllPersonRoles, + this.LocalPersonRoles.CopyTo (this.AllPersonRoles, this.SystemPersonRoles.Length + this.OrganizationPersonRoles.Length); } } diff --git a/Basic/Types/XmlSerializableDictionary.cs b/Basic/Types/XmlSerializableDictionary.cs index a5659211..bb84fc83 100644 --- a/Basic/Types/XmlSerializableDictionary.cs +++ b/Basic/Types/XmlSerializableDictionary.cs @@ -3,7 +3,7 @@ using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; -[XmlRoot("dictionary")] +[XmlRoot ("dictionary")] public class SerializableDictionary : Dictionary, IXmlSerializable { @@ -14,10 +14,10 @@ public class SerializableDictionary return null; } - public void ReadXml(XmlReader reader) + public void ReadXml (XmlReader reader) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + XmlSerializer keySerializer = new XmlSerializer (typeof (TKey)); + XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); @@ -27,17 +27,17 @@ public class SerializableDictionary while (reader.NodeType != XmlNodeType.EndElement) { - reader.ReadStartElement("item"); + reader.ReadStartElement ("item"); - reader.ReadStartElement("key"); - TKey key = (TKey) keySerializer.Deserialize(reader); + reader.ReadStartElement ("key"); + TKey key = (TKey) keySerializer.Deserialize (reader); reader.ReadEndElement(); - reader.ReadStartElement("value"); - TValue value = (TValue) valueSerializer.Deserialize(reader); + reader.ReadStartElement ("value"); + TValue value = (TValue) valueSerializer.Deserialize (reader); reader.ReadEndElement(); - Add(key, value); + Add (key, value); reader.ReadEndElement(); reader.MoveToContent(); @@ -45,22 +45,22 @@ public class SerializableDictionary reader.ReadEndElement(); } - public void WriteXml(XmlWriter writer) + public void WriteXml (XmlWriter writer) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + XmlSerializer keySerializer = new XmlSerializer (typeof (TKey)); + XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue)); foreach (TKey key in Keys) { - writer.WriteStartElement("item"); + writer.WriteStartElement ("item"); - writer.WriteStartElement("key"); - keySerializer.Serialize(writer, key); + writer.WriteStartElement ("key"); + keySerializer.Serialize (writer, key); writer.WriteEndElement(); - writer.WriteStartElement("value"); + writer.WriteStartElement ("value"); TValue value = this[key]; - valueSerializer.Serialize(writer, value); + valueSerializer.Serialize (writer, value); writer.WriteEndElement(); writer.WriteEndElement(); diff --git a/Database/Configuration.cs b/Database/Configuration.cs index c5d982ee..7f380d93 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -29,7 +29,7 @@ namespace Swarmops.Database { } - public Configuration(Credentials read, Credentials write, Credentials admin) + public Configuration (Credentials read, Credentials write, Credentials admin) { Read = read; Write = write; @@ -56,7 +56,7 @@ namespace Swarmops.Database string testString = _configuration.Admin.Username; - return !String.IsNullOrEmpty(testString); + return !String.IsNullOrEmpty (testString); } @@ -75,7 +75,8 @@ namespace Swarmops.Database try { using ( - FileStream stream = new FileStream(GetConfigurationFileName(), FileMode.Append, FileAccess.Write, + FileStream stream = new FileStream (GetConfigurationFileName(), FileMode.Append, + FileAccess.Write, FileShare.ReadWrite)) { // do nothing @@ -91,26 +92,26 @@ namespace Swarmops.Database public static void Load() { - XmlSerializer serializer = new XmlSerializer(typeof (Configuration)); + XmlSerializer serializer = new XmlSerializer (typeof (Configuration)); string configFileName = GetConfigurationFileName(); using ( - FileStream readFileStream = new FileStream(configFileName, FileMode.Open, FileAccess.Read, + FileStream readFileStream = new FileStream (configFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { - _configuration = (Configuration) serializer.Deserialize(readFileStream); + _configuration = (Configuration) serializer.Deserialize (readFileStream); } } - public static void Set(Configuration configuration) + public static void Set (Configuration configuration) { - XmlSerializer serializer = new XmlSerializer(typeof (Configuration)); + XmlSerializer serializer = new XmlSerializer (typeof (Configuration)); string fileName = GetConfigurationFileName(); - using (TextWriter writeFileStream = new StreamWriter(fileName)) + using (TextWriter writeFileStream = new StreamWriter (fileName)) { - serializer.Serialize(writeFileStream, configuration); + serializer.Serialize (writeFileStream, configuration); } _configuration = configuration; @@ -135,9 +136,9 @@ namespace Swarmops.Database { // Dev web process. This will throw if we're not in a HttpContext and trying to debug something else. - return HttpContext.Current.Server.MapPath("~/database.config"); + return HttpContext.Current.Server.MapPath ("~/database.config"); } - throw new NotImplementedException("Invalid state"); + throw new NotImplementedException ("Invalid state"); // Dev console process @@ -154,7 +155,7 @@ namespace Swarmops.Database // paramless ctor to enable serialization } - public Credentials(string database, ServerSet servers, string username, string password) + public Credentials (string database, ServerSet servers, string username, string password) { Database = database; ServerSet = servers; @@ -177,10 +178,10 @@ namespace Swarmops.Database ServerPriorities = new List(); } - public ServerSet(string singleServer) + public ServerSet (string singleServer) { ServerPriorities = new List(); - ServerPriorities.Add(singleServer); + ServerPriorities.Add (singleServer); } public List ServerPriorities { get; set; } diff --git a/Database/Database-Activists.cs b/Database/Database-Activists.cs index 71026b55..43028eed 100644 --- a/Database/Database-Activists.cs +++ b/Database/Database-Activists.cs @@ -7,7 +7,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int[] GetActivistPersonIds(int[] geographyIds) + public int[] GetActivistPersonIds (int[] geographyIds) { List result = new List(); @@ -16,63 +16,63 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Activists.PersonId FROM Activists,People WHERE Activists.Active=1 AND Activists.PersonId=People.PersonId AND People.GeographyId IN (" + - JoinIds(geographyIds) + ")", connection); + JoinIds (geographyIds) + ")", connection); DbDataReader reader = command.ExecuteReader(); while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } } return result.ToArray(); } - public void CreateActivist(int personId, bool isPublic, bool isConfirmed) + public void CreateActivist (int personId, bool isPublic, bool isConfirmed) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateActivist", connection); + DbCommand command = GetDbCommand ("CreateActivist", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "public", isPublic); - AddParameterWithName(command, "confirmed", isConfirmed); - AddParameterWithName(command, "dateTimeCreated", DateTime.Now); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "public", isPublic); + AddParameterWithName (command, "confirmed", isConfirmed); + AddParameterWithName (command, "dateTimeCreated", DateTime.Now); command.ExecuteNonQuery(); } } - public int GetActivistCountForGeographies(int[] geographyIds) + public int GetActivistCountForGeographies (int[] geographyIds) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Count(Activists.PersonId) FROM Activists,People WHERE Activists.Active=1 AND Activists.PersonId=People.PersonId AND People.GeographyId IN (" + - JoinIds(geographyIds) + ")", connection); + JoinIds (geographyIds) + ")", connection); DbDataReader reader = command.ExecuteReader(); reader.Read(); - return reader.GetInt32(0); + return reader.GetInt32 (0); } } - public bool GetActivistStatus(int personId) + public bool GetActivistStatus (int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT * From Activists WHERE Active=1 AND PersonId=" + personId, connection); @@ -89,15 +89,15 @@ namespace Swarmops.Database } - public void TerminateActivist(int personId) + public void TerminateActivist (int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("TerminateActivist", connection); + DbCommand command = GetDbCommand ("TerminateActivist", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "personId", personId); command.ExecuteNonQuery(); } diff --git a/Database/Database-Attribute.cs b/Database/Database-Attribute.cs index 142e7124..01568ab8 100644 --- a/Database/Database-Attribute.cs +++ b/Database/Database-Attribute.cs @@ -7,12 +7,12 @@ namespace Swarmops.Database.Attributes /// Needed if a Logic entity is using Database-condition and have to work with a subclass /// i.e. [DbRecordType("Person")] on class Person /// - [AttributeUsage(AttributeTargets.All)] + [AttributeUsage (AttributeTargets.All)] public class DbRecordType : Attribute { private string typeName = ""; - public DbRecordType(string recordname) + public DbRecordType (string recordname) { this.typeName = recordname; } diff --git a/Database/Database-AutoMails.cs b/Database/Database-AutoMails.cs index d31f5634..a550aeaf 100644 --- a/Database/Database-AutoMails.cs +++ b/Database/Database-AutoMails.cs @@ -13,14 +13,14 @@ namespace Swarmops.Database return new BasicAutoMail[0]; } - public BasicAutoMail GetAutoMail(AutoMailType type, int organizationId, int geographyId) + public BasicAutoMail GetAutoMail (AutoMailType type, int organizationId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select AutoMails.AutoMailId,AutoMailTypes.Name,AutoMails.OrganizationId,AutoMails.GeographyId,AutoMails.AuthorPersonId,Title,Body " + "FROM AutoMails JOIN AutoMailTypes USING (AutoMailTypeId) " + "WHERE AutoMailTypes.Name='" + type + "' AND AutoMails.OrganizationId=" + organizationId + @@ -30,7 +30,7 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadAutoMailFromDataReader(reader); + return ReadAutoMailFromDataReader (reader); } return null; // NULL returned - unusual; usually exception is thrown if not found @@ -39,46 +39,46 @@ namespace Swarmops.Database } - private static BasicAutoMail ReadAutoMailFromDataReader(DbDataReader reader) + private static BasicAutoMail ReadAutoMailFromDataReader (DbDataReader reader) { - int autoMailId = reader.GetInt32(0); - AutoMailType type = (AutoMailType) Enum.Parse(typeof (AutoMailType), reader.GetString(1)); - int geographyId = reader.GetInt32(3); - int organizationId = reader.GetInt32(2); - int authorPersonId = reader.GetInt32(4); // appear to be unused? - string title = reader.GetString(5); - string body = reader.GetString(6); + int autoMailId = reader.GetInt32 (0); + AutoMailType type = (AutoMailType) Enum.Parse (typeof (AutoMailType), reader.GetString (1)); + int geographyId = reader.GetInt32 (3); + int organizationId = reader.GetInt32 (2); + int authorPersonId = reader.GetInt32 (4); // appear to be unused? + string title = reader.GetString (5); + string body = reader.GetString (6); - return new BasicAutoMail(autoMailId, type, organizationId, geographyId, authorPersonId, + return new BasicAutoMail (autoMailId, type, organizationId, geographyId, authorPersonId, title, body); } - public int SetAutoMail(AutoMailType type, int organizationId, int geographyId, + public int SetAutoMail (AutoMailType type, int organizationId, int geographyId, int authorPersonId, string title, string body) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetAutoMail", connection); + DbCommand command = GetDbCommand ("SetAutoMail", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "autoMailType", type.ToString()); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "authorPersonId", authorPersonId); - AddParameterWithName(command, "title", title); - AddParameterWithName(command, "body", body); + AddParameterWithName (command, "autoMailType", type.ToString()); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "authorPersonId", authorPersonId); + AddParameterWithName (command, "title", title); + AddParameterWithName (command, "body", body); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetAutoMail(BasicAutoMail autoMail) + public int SetAutoMail (BasicAutoMail autoMail) { - return SetAutoMail(autoMail.Type, autoMail.OrganizationId, autoMail.GeographyId, + return SetAutoMail (autoMail.Type, autoMail.OrganizationId, autoMail.GeographyId, autoMail.AuthorPersonId, autoMail.Title, autoMail.Body); } } diff --git a/Database/Database-Ballots.cs b/Database/Database-Ballots.cs index e3feaf34..3e3110a0 100644 --- a/Database/Database-Ballots.cs +++ b/Database/Database-Ballots.cs @@ -15,46 +15,47 @@ namespace Swarmops.Database "BallotCount,DeliveryAddress " + // 5-6 "FROM Ballots "; - private static BasicBallot ReadBallotFromDataReader(IDataRecord reader) + private static BasicBallot ReadBallotFromDataReader (IDataRecord reader) { - int ballotId = reader.GetInt32(0); - int electionId = reader.GetInt32(1); - string name = reader.GetString(2); - int organizationId = reader.GetInt32(3); - int geographyId = reader.GetInt32(4); - int ballotCount = reader.GetInt32(5); - string deliveryAddress = reader.GetString(6); + int ballotId = reader.GetInt32 (0); + int electionId = reader.GetInt32 (1); + string name = reader.GetString (2); + int organizationId = reader.GetInt32 (3); + int geographyId = reader.GetInt32 (4); + int ballotCount = reader.GetInt32 (5); + string deliveryAddress = reader.GetString (6); - return new BasicBallot(ballotId, electionId, organizationId, geographyId, name, ballotCount, deliveryAddress); + return new BasicBallot (ballotId, electionId, organizationId, geographyId, name, ballotCount, + deliveryAddress); } #endregion #region Record reading - SELECT statements - public BasicBallot GetBallot(int ballotId) + public BasicBallot GetBallot (int ballotId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + ballotFieldSequence + "WHERE BallotId=" + ballotId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadBallotFromDataReader(reader); + return ReadBallotFromDataReader (reader); } - throw new ArgumentException("Unknown Ballot Id: " + ballotId); + throw new ArgumentException ("Unknown Ballot Id: " + ballotId); } } } - public BasicBallot[] GetBallots(params object[] conditions) + public BasicBallot[] GetBallots (params object[] conditions) { List result = new List(); @@ -63,14 +64,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + ballotFieldSequence + ConstructWhereClause("Ballots", conditions), connection); + GetDbCommand ( + "SELECT" + ballotFieldSequence + ConstructWhereClause ("Ballots", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadBallotFromDataReader(reader)); + result.Add (ReadBallotFromDataReader (reader)); } return result.ToArray(); @@ -79,7 +80,7 @@ namespace Swarmops.Database } - public int[] GetBallotCandidates(int ballotId) + public int[] GetBallotCandidates (int ballotId) { List result = new List(); @@ -88,7 +89,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId FROM BallotCandidates WHERE BallotId=" + ballotId + " ORDER BY SortOrder", connection); @@ -96,7 +97,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -105,7 +106,7 @@ namespace Swarmops.Database } - public int[] GetDocumentedCandidates(int electionId, int organizationId) + public int[] GetDocumentedCandidates (int electionId, int organizationId) { List result = new List(); @@ -114,7 +115,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId FROM CandidateDocumentation WHERE ElectionId=" + electionId + " AND OrganizationId=" + organizationId, connection); @@ -122,7 +123,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -130,7 +131,7 @@ namespace Swarmops.Database } } - public Dictionary GetBallotsForPerson(int personId) + public Dictionary GetBallotsForPerson (int personId) { Dictionary result = new Dictionary(); @@ -139,14 +140,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT BallotId,SortOrder FROM BallotCandidates WHERE PersonId=" + personId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetInt32(1); + result[reader.GetInt32 (0)] = reader.GetInt32 (1); } return result; @@ -158,106 +159,106 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateBallot(int electionId, string name, int organizationId, int geographyId, int ballotCount, + public int CreateBallot (int electionId, string name, int organizationId, int geographyId, int ballotCount, string deliveryAddress) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateBallot", connection); + DbCommand command = GetDbCommand ("CreateBallot", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "electionId", electionId); - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "ballotCount", ballotCount); - AddParameterWithName(command, "deliveryAddress", deliveryAddress); + AddParameterWithName (command, "electionId", electionId); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "ballotCount", ballotCount); + AddParameterWithName (command, "deliveryAddress", deliveryAddress); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetBallotCount(int ballotId, int ballotCount) + public void SetBallotCount (int ballotId, int ballotCount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetBallotCount", connection); + DbCommand command = GetDbCommand ("SetBallotCount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "ballotId", ballotId); - AddParameterWithName(command, "ballotCount", ballotCount); + AddParameterWithName (command, "ballotId", ballotId); + AddParameterWithName (command, "ballotCount", ballotCount); command.ExecuteNonQuery(); } } - public void SetBallotDeliveryAddress(int ballotId, string deliveryAddress) + public void SetBallotDeliveryAddress (int ballotId, string deliveryAddress) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetBallotDeliveryAddress", connection); + DbCommand command = GetDbCommand ("SetBallotDeliveryAddress", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "ballotId", ballotId); - AddParameterWithName(command, "deliveryAddress", deliveryAddress); + AddParameterWithName (command, "ballotId", ballotId); + AddParameterWithName (command, "deliveryAddress", deliveryAddress); command.ExecuteNonQuery(); } } - public void CreateBallotCandidate(int ballotId, int personId) + public void CreateBallotCandidate (int ballotId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateBallotCandidate", connection); + DbCommand command = GetDbCommand ("CreateBallotCandidate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "ballotId", ballotId); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "ballotId", ballotId); + AddParameterWithName (command, "personId", personId); command.ExecuteNonQuery(); } } - public void ClearBallotCandidates(int ballotId) + public void ClearBallotCandidates (int ballotId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClearBallotCandidates", connection); + DbCommand command = GetDbCommand ("ClearBallotCandidates", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "ballotId", ballotId); + AddParameterWithName (command, "ballotId", ballotId); command.ExecuteNonQuery(); } } - public void SetCandidateDocumentationReceived(int electionId, int organizationId, int personId) + public void SetCandidateDocumentationReceived (int electionId, int organizationId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCandidateDocumentationReceived", connection); + DbCommand command = GetDbCommand ("SetCandidateDocumentationReceived", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "electionId", electionId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "dateTimeReceived", DateTime.Now); + AddParameterWithName (command, "electionId", electionId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "dateTimeReceived", DateTime.Now); command.ExecuteNonQuery(); } diff --git a/Database/Database-CashAdvances.cs b/Database/Database-CashAdvances.cs index 3e7a7f22..a30d8619 100644 --- a/Database/Database-CashAdvances.cs +++ b/Database/Database-CashAdvances.cs @@ -16,25 +16,25 @@ namespace Swarmops.Database "PaidOut,AttestedByPersonId,AttestedDateTime " + // 10-12 "FROM CashAdvances "; - private static BasicCashAdvance ReadCashAdvanceFromDataReader(IDataRecord reader) + private static BasicCashAdvance ReadCashAdvanceFromDataReader (IDataRecord reader) { - int cashAdvanceId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - DateTime createdDateTime = reader.GetDateTime(3); - int createdByPersonId = reader.GetInt32(4); + int cashAdvanceId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + DateTime createdDateTime = reader.GetDateTime (3); + int createdByPersonId = reader.GetInt32 (4); - int financialAccountId = reader.GetInt32(5); - Int64 amountCents = reader.GetInt64(6); - string description = reader.GetString(7); - bool open = reader.GetBoolean(8); - bool attested = reader.GetBoolean(9); + int financialAccountId = reader.GetInt32 (5); + Int64 amountCents = reader.GetInt64 (6); + string description = reader.GetString (7); + bool open = reader.GetBoolean (8); + bool attested = reader.GetBoolean (9); - bool paidOut = reader.GetBoolean(10); - int attestedByPersonId = reader.GetInt32(11); - DateTime attestedDateTime = reader.GetDateTime(12); + bool paidOut = reader.GetBoolean (10); + int attestedByPersonId = reader.GetInt32 (11); + DateTime attestedDateTime = reader.GetDateTime (12); - return new BasicCashAdvance(cashAdvanceId, organizationId, personId, createdDateTime, createdByPersonId, + return new BasicCashAdvance (cashAdvanceId, organizationId, personId, createdDateTime, createdByPersonId, financialAccountId, amountCents, description, open, attested, paidOut, attestedByPersonId, attestedDateTime); } @@ -43,31 +43,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicCashAdvance GetCashAdvance(int cashAdvanceId) + public BasicCashAdvance GetCashAdvance (int cashAdvanceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + cashAdvanceFieldSequence + - " WHERE CashAdvanceId=" + cashAdvanceId, + GetDbCommand ("SELECT " + cashAdvanceFieldSequence + + " WHERE CashAdvanceId=" + cashAdvanceId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCashAdvanceFromDataReader(reader); + return ReadCashAdvanceFromDataReader (reader); } - throw new ArgumentException("No such CashAdvanceId:" + cashAdvanceId); + throw new ArgumentException ("No such CashAdvanceId:" + cashAdvanceId); } } } - public BasicCashAdvance[] GetCashAdvances(params object[] conditions) + public BasicCashAdvance[] GetCashAdvances (params object[] conditions) { List result = new List(); @@ -76,15 +76,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + cashAdvanceFieldSequence + ConstructWhereClause("CashAdvances", conditions), + GetDbCommand ( + "SELECT " + cashAdvanceFieldSequence + ConstructWhereClause ("CashAdvances", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadCashAdvanceFromDataReader(reader)); + result.Add (ReadCashAdvanceFromDataReader (reader)); } return result.ToArray(); @@ -96,81 +96,81 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateCashAdvance(int personId, int createdByPersonId, int organizationId, int financialAccountId, + public int CreateCashAdvance (int personId, int createdByPersonId, int organizationId, int financialAccountId, Int64 amountCents, string description) { if (description.Length > 128) { - description = description.Substring(0, 128); // varchar(128) field + description = description.Substring (0, 128); // varchar(128) field } using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateCashAdvance", connection); + DbCommand command = GetDbCommand ("CreateCashAdvance", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "description", description); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "description", description); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetCashAdvanceOpen(int cashAdvanceId, bool open) + public void SetCashAdvanceOpen (int cashAdvanceId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCashAdvanceOpen", connection); + DbCommand command = GetDbCommand ("SetCashAdvanceOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "cashAdvanceId", cashAdvanceId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "cashAdvanceId", cashAdvanceId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetCashAdvanceAttested(int cashAdvanceId, bool attested, int attestedByPersonId) + public void SetCashAdvanceAttested (int cashAdvanceId, bool attested, int attestedByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCashAdvanceAttested", connection); + DbCommand command = GetDbCommand ("SetCashAdvanceAttested", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "cashAdvanceId", cashAdvanceId); - AddParameterWithName(command, "attested", attested); - AddParameterWithName(command, "attestedByPersonId", attestedByPersonId); - AddParameterWithName(command, "attestedDateTime", DateTime.Now); + AddParameterWithName (command, "cashAdvanceId", cashAdvanceId); + AddParameterWithName (command, "attested", attested); + AddParameterWithName (command, "attestedByPersonId", attestedByPersonId); + AddParameterWithName (command, "attestedDateTime", DateTime.Now); command.ExecuteNonQuery(); } } - public void SetCashAdvancePaidOut(int cashAdvanceId, bool paidOut) + public void SetCashAdvancePaidOut (int cashAdvanceId, bool paidOut) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCashAdvancePaidOut", connection); + DbCommand command = GetDbCommand ("SetCashAdvancePaidOut", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "cashAdvanceId", cashAdvanceId); - AddParameterWithName(command, "paidOut", paidOut); + AddParameterWithName (command, "cashAdvanceId", cashAdvanceId); + AddParameterWithName (command, "paidOut", paidOut); command.ExecuteNonQuery(); } diff --git a/Database/Database-ChurnData.cs b/Database/Database-ChurnData.cs index 7d05792d..07f27648 100644 --- a/Database/Database-ChurnData.cs +++ b/Database/Database-ChurnData.cs @@ -16,15 +16,15 @@ namespace Swarmops.Database " PersonId,OrganizationId,Churn,DecisionDateTime,ExpiryDateTime " + // 0-4 " FROM ChurnData "; - private static BasicChurnDataPoint ReadChurnDataPointFromDataReader(DbDataReader reader) + private static BasicChurnDataPoint ReadChurnDataPointFromDataReader (DbDataReader reader) { - int personId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - bool churn = reader.GetBoolean(2); - DateTime decisionDateTime = reader.GetDateTime(3); - DateTime expiryDateTime = reader.GetDateTime(4); + int personId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + bool churn = reader.GetBoolean (2); + DateTime decisionDateTime = reader.GetDateTime (3); + DateTime expiryDateTime = reader.GetDateTime (4); - return new BasicChurnDataPoint(churn ? ChurnDataType.Churn : ChurnDataType.Retention, decisionDateTime, + return new BasicChurnDataPoint (churn ? ChurnDataType.Churn : ChurnDataType.Retention, decisionDateTime, expiryDateTime, personId, organizationId); } @@ -32,7 +32,7 @@ namespace Swarmops.Database #region Record reading code -- SELECT statements - public BasicChurnDataPoint[] GetChurnData(params object[] conditions) + public BasicChurnDataPoint[] GetChurnData (params object[] conditions) { List result = new List(); @@ -41,15 +41,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + churnDataFieldSequence + ConstructWhereClause("ChurnData", conditions) + + GetDbCommand ( + "SELECT " + churnDataFieldSequence + ConstructWhereClause ("ChurnData", conditions) + " ORDER BY ExpiryDateTime", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadChurnDataPointFromDataReader(reader)); + result.Add (ReadChurnDataPointFromDataReader (reader)); } return result.ToArray(); @@ -58,7 +58,7 @@ namespace Swarmops.Database } - public BasicChurnDataPoint[] GetChurnDataForOrganization(IHasIdentity organization, DateTime lowerDate, + public BasicChurnDataPoint[] GetChurnDataForOrganization (IHasIdentity organization, DateTime lowerDate, DateTime upperDate) { // Since I don't trust SQL Server to make correct date comparisons, especially given @@ -67,10 +67,10 @@ namespace Swarmops.Database // some 30k records with two unlinked fields isn't that expensive. DateTime minimumDateTime = lowerDate.Date; - DateTime maximumDateTime = upperDate.Date.AddDays(1); + DateTime maximumDateTime = upperDate.Date.AddDays (1); List result = new List(); - BasicChurnDataPoint[] rawData = GetChurnData(organization); + BasicChurnDataPoint[] rawData = GetChurnData (organization); foreach (BasicChurnDataPoint churnPoint in rawData) { @@ -79,7 +79,7 @@ namespace Swarmops.Database if (churnPoint.ExpiryDate >= minimumDateTime && churnPoint.ExpiryDate < maximumDateTime) { - result.Add(churnPoint); + result.Add (churnPoint); } } @@ -90,28 +90,28 @@ namespace Swarmops.Database #region Record creation and manipulation code -- stored procedures - public int LogChurnData(int personId, int organizationId, bool churn, DateTime expiryDateTime) + public int LogChurnData (int personId, int organizationId, bool churn, DateTime expiryDateTime) { - return LogChurnData(personId, organizationId, churn, expiryDateTime, DateTime.Now); + return LogChurnData (personId, organizationId, churn, expiryDateTime, DateTime.Now); } - public int LogChurnData(int personId, int organizationId, bool churn, DateTime expiryDateTime, + public int LogChurnData (int personId, int organizationId, bool churn, DateTime expiryDateTime, DateTime decisionDateTime) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("LogChurnData", connection); + DbCommand command = GetDbCommand ("LogChurnData", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_personId", personId); - AddParameterWithName(command, "p_organizationId", organizationId); - AddParameterWithName(command, "p_churn", churn); - AddParameterWithName(command, "p_decisionDateTime", decisionDateTime); - AddParameterWithName(command, "p_expiryDateTime", expiryDateTime); + AddParameterWithName (command, "p_personId", personId); + AddParameterWithName (command, "p_organizationId", organizationId); + AddParameterWithName (command, "p_churn", churn); + AddParameterWithName (command, "p_decisionDateTime", decisionDateTime); + AddParameterWithName (command, "p_expiryDateTime", expiryDateTime); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-CommunicationTurnarounds.cs b/Database/Database-CommunicationTurnarounds.cs index 187ced3e..194d81bf 100644 --- a/Database/Database-CommunicationTurnarounds.cs +++ b/Database/Database-CommunicationTurnarounds.cs @@ -15,20 +15,21 @@ namespace Swarmops.Database "PersonIdFirstResponse,DateTimeClosed,PersonIdClosed,Open,Responded " + // 5-9 "FROM CommunicationTurnarounds "; - private static BasicCommunicationTurnaround ReadCommunicationTurnaroundFromDataReader(IDataRecord reader) + private static BasicCommunicationTurnaround ReadCommunicationTurnaroundFromDataReader (IDataRecord reader) { - int organizationId = reader.GetInt32(0); - int communicationTypeId = reader.GetInt32(1); - int communicationId = reader.GetInt32(2); - DateTime dateTimeOpened = reader.GetDateTime(3); - DateTime dateTimeFirstResponse = reader.GetDateTime(4); - int personIdFirstResponse = reader.GetInt32(5); - DateTime dateTimeClosed = reader.GetDateTime(6); - int personIdClosed = reader.GetInt32(7); - bool open = reader.GetBoolean(8); - bool awaitingResponse = reader.GetBoolean(9); + int organizationId = reader.GetInt32 (0); + int communicationTypeId = reader.GetInt32 (1); + int communicationId = reader.GetInt32 (2); + DateTime dateTimeOpened = reader.GetDateTime (3); + DateTime dateTimeFirstResponse = reader.GetDateTime (4); + int personIdFirstResponse = reader.GetInt32 (5); + DateTime dateTimeClosed = reader.GetDateTime (6); + int personIdClosed = reader.GetInt32 (7); + bool open = reader.GetBoolean (8); + bool awaitingResponse = reader.GetBoolean (9); - return new BasicCommunicationTurnaround(organizationId, communicationTypeId, communicationId, dateTimeOpened, + return new BasicCommunicationTurnaround (organizationId, communicationTypeId, communicationId, + dateTimeOpened, dateTimeFirstResponse, personIdFirstResponse, dateTimeClosed, personIdClosed, open, awaitingResponse); } @@ -36,7 +37,7 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicCommunicationTurnaround GetCommunicationTurnaround(int organizationId, int communicationTypeId, + public BasicCommunicationTurnaround GetCommunicationTurnaround (int organizationId, int communicationTypeId, int communicationId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -44,7 +45,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + communicationTurnaroundFieldSequence + "WHERE OrganizationId=" + organizationId + " AND CommunicationTypeId=" + communicationTypeId + " AND CommunicationId=" + communicationId + ";", connection); @@ -53,16 +54,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadCommunicationTurnaroundFromDataReader(reader); + return ReadCommunicationTurnaroundFromDataReader (reader); } - throw new ArgumentException("Unknown Communication Id: " + communicationId); + throw new ArgumentException ("Unknown Communication Id: " + communicationId); } } } - public BasicCommunicationTurnaround[] GetCommunicationTurnarounds(params object[] conditions) + public BasicCommunicationTurnaround[] GetCommunicationTurnarounds (params object[] conditions) { List result = new List(); @@ -71,16 +72,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + communicationTurnaroundFieldSequence + - ConstructWhereClause("CommunicationTurnarounds", conditions) + " ORDER BY DateTimeOpened", + ConstructWhereClause ("CommunicationTurnarounds", conditions) + " ORDER BY DateTimeOpened", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadCommunicationTurnaroundFromDataReader(reader)); + result.Add (ReadCommunicationTurnaroundFromDataReader (reader)); } return result.ToArray(); @@ -92,62 +93,63 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public void CreateCommunicationTurnaround(int organizationId, int communicationTypeId, int communicationId, + public void CreateCommunicationTurnaround (int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeOpened) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateCommunicationTurnaround", connection); + DbCommand command = GetDbCommand ("CreateCommunicationTurnaround", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "communicationTypeId", communicationTypeId); - AddParameterWithName(command, "communicationId", communicationId); - AddParameterWithName(command, "dateTimeOpened", dateTimeOpened); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "communicationTypeId", communicationTypeId); + AddParameterWithName (command, "communicationId", communicationId); + AddParameterWithName (command, "dateTimeOpened", dateTimeOpened); command.ExecuteNonQuery(); } } - public void SetCommunicationTurnaroundResponded(int organizationId, int communicationTypeId, int communicationId, + public void SetCommunicationTurnaroundResponded (int organizationId, int communicationTypeId, + int communicationId, DateTime dateTimeResponded, int personIdResponded) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCommunicationTurnaroundResponded", connection); + DbCommand command = GetDbCommand ("SetCommunicationTurnaroundResponded", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "communicationTypeId", communicationTypeId); - AddParameterWithName(command, "communicationId", communicationId); - AddParameterWithName(command, "dateTimeResponded", dateTimeResponded); - AddParameterWithName(command, "personIdResponded", personIdResponded); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "communicationTypeId", communicationTypeId); + AddParameterWithName (command, "communicationId", communicationId); + AddParameterWithName (command, "dateTimeResponded", dateTimeResponded); + AddParameterWithName (command, "personIdResponded", personIdResponded); command.ExecuteNonQuery(); } } - public void SetCommunicationTurnaroundClosed(int organizationId, int communicationTypeId, int communicationId, + public void SetCommunicationTurnaroundClosed (int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeClosed, int personIdClosed) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCommunicationTurnaroundClosed", connection); + DbCommand command = GetDbCommand ("SetCommunicationTurnaroundClosed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "communicationTypeId", communicationTypeId); - AddParameterWithName(command, "communicationId", communicationId); - AddParameterWithName(command, "dateTimeClosed", dateTimeClosed); - AddParameterWithName(command, "personIdClosed", personIdClosed); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "communicationTypeId", communicationTypeId); + AddParameterWithName (command, "communicationId", communicationId); + AddParameterWithName (command, "dateTimeClosed", dateTimeClosed); + AddParameterWithName (command, "personIdClosed", personIdClosed); command.ExecuteNonQuery(); } diff --git a/Database/Database-Conditions.cs b/Database/Database-Conditions.cs index 861b3bb6..b87b2a7c 100644 --- a/Database/Database-Conditions.cs +++ b/Database/Database-Conditions.cs @@ -17,11 +17,11 @@ namespace Swarmops.Database // Example: ConstructWhereClause (Organization.FromIdentity (1), Database.OpenTrue) makes // a WHERE clause that matches OrganizationId=1 and Open=1. // - private static string ConstructWhereClause(string tableName, params object[] conditionParameters) + private static string ConstructWhereClause (string tableName, params object[] conditionParameters) { - List conditionList = ConstructWhereClauseRecurse(tableName, conditionParameters); + List conditionList = ConstructWhereClauseRecurse (tableName, conditionParameters); - string conditions = JoinWhereClauses(conditionList.ToArray()); + string conditions = JoinWhereClauses (conditionList.ToArray()); if (conditions.Trim().Length > 5) { @@ -35,7 +35,7 @@ namespace Swarmops.Database /// /// Internal. Recurses for ConstructWhereClause. /// - private static List ConstructWhereClauseRecurse(string tableName, params object[] conditionParameters) + private static List ConstructWhereClauseRecurse (string tableName, params object[] conditionParameters) { List result = new List(); @@ -43,32 +43,32 @@ namespace Swarmops.Database { if (condition is IHasIdentities) { - result.Add(GetWhereClauseForObjectList(condition as IHasIdentities)); + result.Add (GetWhereClauseForObjectList (condition as IHasIdentities)); } if (condition is IHasIdentity) { - result.Add(GetWhereClauseForObject(condition as IHasIdentity)); + result.Add (GetWhereClauseForObject (condition as IHasIdentity)); } else if (condition is DatabaseCondition) { if ((DatabaseCondition) condition != DatabaseCondition.None) { - result.Add(tableName + "." + GetWhereClauseForCondition((DatabaseCondition) condition)); + result.Add (tableName + "." + GetWhereClauseForCondition ((DatabaseCondition) condition)); } } else if (condition is string) { - result.Add(condition as string); + result.Add (condition as string); } else if (condition is object[]) // params object inherited and added to -- recurse { - List recursed = ConstructWhereClauseRecurse(tableName, condition); + List recursed = ConstructWhereClauseRecurse (tableName, condition); // copy one by one foreach (string recursedCondition in recursed) { - result.Add(recursedCondition); + result.Add (recursedCondition); } } } @@ -77,7 +77,7 @@ namespace Swarmops.Database } - private static string GetWhereClauseForObject(IHasIdentity foreignObject) + private static string GetWhereClauseForObject (IHasIdentity foreignObject) { // This is kind of dangerous and assumes that foreignObject has the same TYPE NAME, // including casing, as part of the DATABASE FIELD used for primary key. @@ -96,11 +96,11 @@ namespace Swarmops.Database return string.Empty; } - return " " + GetForeignTypeString(foreignObject) + "Id=" + foreignObject.Identity + " "; + return " " + GetForeignTypeString (foreignObject) + "Id=" + foreignObject.Identity + " "; } - private static string GetWhereClauseForObjectList(IHasIdentities foreignObjects) + private static string GetWhereClauseForObjectList (IHasIdentities foreignObjects) { // As above, but with a List object. @@ -120,15 +120,15 @@ namespace Swarmops.Database identities = new int[1] {0}; } - return " " + GetForeignTypeString(((List) foreignObjects)[0]) + "Id IN (" + - JoinIds(identities) + ") "; + return " " + GetForeignTypeString (((List) foreignObjects)[0]) + "Id IN (" + + JoinIds (identities) + ") "; } - private static string GetForeignTypeString(IHasIdentity foreignObject) + private static string GetForeignTypeString (IHasIdentity foreignObject) { string typeString = ""; - foreach (object attribute in foreignObject.GetType().GetCustomAttributes(typeof (DbRecordType), true)) + foreach (object attribute in foreignObject.GetType().GetCustomAttributes (typeof (DbRecordType), true)) { if (attribute is DbRecordType) { @@ -139,10 +139,10 @@ namespace Swarmops.Database { typeString = foreignObject.GetType().ToString(); - if (typeString.Contains(".")) + if (typeString.Contains (".")) { - int periodIndex = typeString.LastIndexOf('.'); - typeString = typeString.Substring(periodIndex + 1); + int periodIndex = typeString.LastIndexOf ('.'); + typeString = typeString.Substring (periodIndex + 1); } } @@ -150,7 +150,7 @@ namespace Swarmops.Database } - private static string GetWhereClauseForCondition(DatabaseCondition condition) + private static string GetWhereClauseForCondition (DatabaseCondition condition) { switch (condition) { @@ -167,20 +167,20 @@ namespace Swarmops.Database case DatabaseCondition.ActiveTrue: return "Active=1"; default: - throw new InvalidOperationException( + throw new InvalidOperationException ( "Undefined or unimplemented DatabaseCondition in GetWhereClauseForCondition: " + condition); } } - private static string JoinWhereClauses(params string[] clauses) + private static string JoinWhereClauses (params string[] clauses) { string result = string.Empty; foreach (string clause in clauses) { - if (!String.IsNullOrEmpty(clause)) + if (!String.IsNullOrEmpty (clause)) { result += "AND " + clause; } @@ -188,7 +188,7 @@ namespace Swarmops.Database if (result.Length > 0) { - return result.Substring(3) + " "; // strips first AND; ensures space on both sides in returned string + return result.Substring (3) + " "; // strips first AND; ensures space on both sides in returned string } return string.Empty; diff --git a/Database/Database-ConnectionsCommands.cs b/Database/Database-ConnectionsCommands.cs index 4853b6d3..5529260f 100644 --- a/Database/Database-ConnectionsCommands.cs +++ b/Database/Database-ConnectionsCommands.cs @@ -37,38 +37,38 @@ namespace Swarmops.Database if (specialConnectString == "") specialConnectString = this.ConnectionString; - specialConnectString = specialConnectString.Replace("192.168.0.5", "192.168.0.7"); - // for dev & debug at Rick's + specialConnectString = specialConnectString.Replace ("192.168.0.5", "192.168.0.7"); + // for dev & debug at Rick's connection.ConnectionString = specialConnectString; return connection; } - protected DbCommand GetDbCommand(string commandText, DbConnection connection) + protected DbCommand GetDbCommand (string commandText, DbConnection connection) { DbCommand command = connection.CreateCommand(); if (command.GetType().FullName == "System.Data.OleDb.OleDbCommand") { commandText = commandText. - Replace("%ISTRUE%", string.Empty). - Replace("DISTINCT", string.Empty); - if (commandText.Contains("%ISFALSE%")) + Replace ("%ISTRUE%", string.Empty). + Replace ("DISTINCT", string.Empty); + if (commandText.Contains ("%ISFALSE%")) { - throw new NotImplementedException("%ISFALSE% has not been implemented for OleDbConnections"); + throw new NotImplementedException ("%ISFALSE% has not been implemented for OleDbConnections"); } } else { - commandText = commandText.Replace("%ISTRUE%", "= 1"); - commandText = commandText.Replace("%ISFALSE%", "= 0"); + commandText = commandText.Replace ("%ISTRUE%", "= 1"); + commandText = commandText.Replace ("%ISFALSE%", "= 0"); } command.CommandText = commandText; return command; } - protected void AddParameterWithName(DbCommand command, string parameterName, object value) + protected void AddParameterWithName (DbCommand command, string parameterName, object value) { if (command.Parameters.GetType().Name == "SqlParameterCollection") { @@ -100,7 +100,7 @@ namespace Swarmops.Database } else if (!((Type) value == typeof (string))) { - throw new Exception("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); + throw new Exception ("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); } value = DBNull.Value; } @@ -126,7 +126,7 @@ namespace Swarmops.Database } else if (!(value is string)) { - throw new Exception("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); + throw new Exception ("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); } SqlParameter parameter = null; @@ -144,13 +144,13 @@ namespace Swarmops.Database textLength -= (textLength%256); textLength += 256; } - parameter = new SqlParameter("@" + parameterName, parameterType, textLength); + parameter = new SqlParameter ("@" + parameterName, parameterType, textLength); } else { // For all other types, ignore the length parameter, let the default handle it - parameter = new SqlParameter("@" + parameterName, parameterType); + parameter = new SqlParameter ("@" + parameterName, parameterType); } parameter.Value = value; @@ -158,16 +158,16 @@ namespace Swarmops.Database SqlParameterCollection sqlCollection = command.Parameters as SqlParameterCollection; - sqlCollection.Add(parameter); + sqlCollection.Add (parameter); } else if (command.GetType().FullName == "MySql.Data.MySqlClient.MySqlCommand") { - MySqlParameter newParameter = new MySqlParameter(parameterName, value); - command.Parameters.Add(newParameter); + MySqlParameter newParameter = new MySqlParameter (parameterName, value); + command.Parameters.Add (newParameter); } else { - int i = command.Parameters.Add(value); + int i = command.Parameters.Add (value); if (command.GetType().FullName == "System.Data.OracleClient.OracleCommand") { @@ -181,7 +181,7 @@ namespace Swarmops.Database } // A common function used here and there. Placed here for convenience. - private static string JoinIds(int[] ids) + private static string JoinIds (int[] ids) { if (ids.Length == 0) { @@ -190,19 +190,19 @@ namespace Swarmops.Database StringBuilder builder = new StringBuilder(); - builder.Append(ids[0].ToString()); + builder.Append (ids[0].ToString()); for (int index = 1; index < ids.Length; index++) { - builder.Append(","); - builder.Append(ids[index].ToString()); + builder.Append (","); + builder.Append (ids[index].ToString()); } return builder.ToString(); } // A common function used here and there. Placed here for convenience. - private static string JoinStrings(string[] strs) + private static string JoinStrings (string[] strs) { if (strs.Length == 0) { @@ -211,25 +211,25 @@ namespace Swarmops.Database StringBuilder builder = new StringBuilder(); - builder.Append("'" + strs[0] + "'"); + builder.Append ("'" + strs[0] + "'"); for (int index = 1; index < strs.Length; index++) { - builder.Append(","); - builder.Append("'" + strs[index] + "'"); + builder.Append (","); + builder.Append ("'" + strs[index] + "'"); } return builder.ToString(); } // A common function used here and there. Placed here for convenience. - private static string MySqlDate(DateTime d) + private static string MySqlDate (DateTime d) { - return d.ToString("yyyyMMddHHmmss"); + return d.ToString ("yyyyMMddHHmmss"); } - private string SqlSanitize(string input) + private string SqlSanitize (string input) { string[] forbiddenArray = { @@ -237,14 +237,14 @@ namespace Swarmops.Database "=" }; - string output = input.Replace("'", "''"); // the typical case + string output = input.Replace ("'", "''"); // the typical case string inputLower = input.ToLowerInvariant(); foreach (string forbidden in forbiddenArray) { - if (inputLower.Contains(forbidden)) + if (inputLower.Contains (forbidden)) { - throw new SecurityException("Attempt at SQL injection: parameter passed to SELECT was '" + input + - "'"); + throw new SecurityException ("Attempt at SQL injection: parameter passed to SELECT was '" + input + + "'"); } } diff --git a/Database/Database-Constructors.cs b/Database/Database-Constructors.cs index 86f1b305..0adf1008 100644 --- a/Database/Database-Constructors.cs +++ b/Database/Database-Constructors.cs @@ -22,14 +22,14 @@ namespace Swarmops.Database private readonly string ConnectionString; private readonly DbProviderFactory ProviderFactory; - [Obsolete("Do not use. Hardwireto MySQL.")] - public SwarmDb(DbProviderFactory ProviderFactory, string ConnectionString) + [Obsolete ("Do not use. Hardwireto MySQL.")] + public SwarmDb (DbProviderFactory ProviderFactory, string ConnectionString) { this.ProviderFactory = ProviderFactory; this.ConnectionString = ConnectionString; } - public SwarmDb(string connectionString) + public SwarmDb (string connectionString) { this.ConnectionString = connectionString; } @@ -43,61 +43,61 @@ namespace Swarmops.Database { // TODO: Cache for some ten minutes, perhaps? - string dbVersionString = GetDatabaseForReading().GetKeyValue("DbVersion"); + string dbVersionString = GetDatabaseForReading().GetKeyValue ("DbVersion"); - if (string.IsNullOrEmpty(dbVersionString)) + if (string.IsNullOrEmpty (dbVersionString)) { - GetDatabaseForWriting().SetKeyValue("DbVersion", "1"); + GetDatabaseForWriting().SetKeyValue ("DbVersion", "1"); return 1; } - return Int32.Parse(dbVersionString); + return Int32.Parse (dbVersionString); } } public static SwarmDb GetDatabaseForReading() { - return new SwarmDb(ConstructConnectString(new Configuration().Get().Read)); + return new SwarmDb (ConstructConnectString (new Configuration().Get().Read)); } public static SwarmDb GetDatabaseForWriting() { - return new SwarmDb(ConstructConnectString(new Configuration().Get().Write)); + return new SwarmDb (ConstructConnectString (new Configuration().Get().Write)); } public static SwarmDb GetDatabaseForAdmin() { - return new SwarmDb(ConstructConnectString(new Configuration().Get().Admin)); + return new SwarmDb (ConstructConnectString (new Configuration().Get().Admin)); } - public static SwarmDb GetTestDatabase(Credentials credentials) + public static SwarmDb GetTestDatabase (Credentials credentials) { // For security reasons, this function is only available BEFORE the database has been initialized. if (Configuration.IsConfigured()) { - throw new UnauthorizedAccessException( + throw new UnauthorizedAccessException ( "Cannot probe arbitrary database credentials once database initialized"); } - return new SwarmDb(ConstructConnectString(credentials)); + return new SwarmDb (ConstructConnectString (credentials)); } - private static string ConstructConnectString(Credentials credentials) + private static string ConstructConnectString (Credentials credentials) { - return "server=" + credentials.ServerSet.ServerPriorities[0].Split(';')[0] + ";database=" + + return "server=" + credentials.ServerSet.ServerPriorities[0].Split (';')[0] + ";database=" + credentials.Database + ";user=" + credentials.Username + ";password=" + credentials.Password; } - [Obsolete("Do not use. Use SwarmDb.GetDatabaseForReading(), ...ForWriting() or ...ForAdmin().", true)] + [Obsolete ("Do not use. Use SwarmDb.GetDatabaseForReading(), ...ForWriting() or ...ForAdmin().", true)] public static SwarmDb GetDatabase() { - throw new NotImplementedException("GetDatabase() is obsolete and has been deleted."); + throw new NotImplementedException ("GetDatabase() is obsolete and has been deleted."); } - [Obsolete("Do not use. Use GetDatabaseForAdmin().", true)] + [Obsolete ("Do not use. Use GetDatabaseForAdmin().", true)] public static SwarmDb GetDatabaseAsAdmin() { string connectionString = string.Empty; @@ -108,11 +108,11 @@ namespace Swarmops.Database { // We are running under mono in a backend environment - using (StreamReader reader = new StreamReader(MonoConfigFile.Replace(".config", "-admin.config"))) + using (StreamReader reader = new StreamReader (MonoConfigFile.Replace (".config", "-admin.config"))) { connectionString = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for Linux Backend: [" + connectionString + "]"); } } @@ -121,13 +121,13 @@ namespace Swarmops.Database // We are running a web application, under Mono (production) or Windows (development) using ( StreamReader reader = - new StreamReader( - HttpContext.Current.Server.MapPath(WebConfigFile.Replace(".config", "-admin.config"))) + new StreamReader ( + HttpContext.Current.Server.MapPath (WebConfigFile.Replace (".config", "-admin.config"))) ) { connectionString = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for web: [" + connectionString + "]"); } } @@ -135,11 +135,11 @@ namespace Swarmops.Database { // We are running an application, presumably directly from Visual Studio. // If so, the current working directory is "PirateWeb/30/Console/bin". - using (StreamReader reader = new StreamReader(AppConfigFile.Replace(".config", "-admin.config"))) + using (StreamReader reader = new StreamReader (AppConfigFile.Replace (".config", "-admin.config"))) { connectionString = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for application: [" + connectionString + "]"); } @@ -147,7 +147,7 @@ namespace Swarmops.Database } catch (Exception) { - Logging.LogWarning(LogSource.PirateDb, "Unable to read Database.Config - defaulting"); + Logging.LogWarning (LogSource.PirateDb, "Unable to read Database.Config - defaulting"); // Ignore if we can't read the Database.config } @@ -158,7 +158,7 @@ namespace Swarmops.Database } // If we still have nothing, and we're running from web, then assume we have a dev environment and use the hostname as db, user, and pass. - if (String.IsNullOrEmpty(connectionString)) + if (String.IsNullOrEmpty (connectionString)) { if (HttpContext.Current != null) // dummy comment to force build, remove on sight { @@ -166,13 +166,13 @@ namespace Swarmops.Database connectionString = "server=peregrine;database=" + hostName + ";user=" + hostName + "-admin;password=" + hostName + "-admin"; - // TODO: Replace "peregrine" with "localhost" + // TODO: Replace "peregrine" with "localhost" } else { - throw new InvalidOperationException( + throw new InvalidOperationException ( "No database-as-admin connection string found -- write a connect string into the \"ActivizrAdminConnect\" environment var, or on one line into a file named database-admin.config; see connectionstrings.com for examples"); - // TODO: Replace with custom exception to present config screen + // TODO: Replace with custom exception to present config screen } } @@ -182,7 +182,7 @@ namespace Swarmops.Database _cachedConnectionString = connectionString; } - return new SwarmDb(DbProviderFactories.GetFactory(DefaultProviderName), connectionString); + return new SwarmDb (DbProviderFactories.GetFactory (DefaultProviderName), connectionString); } } } \ No newline at end of file diff --git a/Database/Database-Countries.cs b/Database/Database-Countries.cs index a7b23186..bb135f41 100644 --- a/Database/Database-Countries.cs +++ b/Database/Database-Countries.cs @@ -14,64 +14,64 @@ namespace Swarmops.Database "GeographyId,PostalCodeLength FROM Countries "; // 5-6 - private static BasicCountry ReadCountryFromDataReader(DbDataReader reader) + private static BasicCountry ReadCountryFromDataReader (DbDataReader reader) { - int countryId = reader.GetInt32(0); - string name = reader.GetString(1); - string code = reader.GetString(2).ToUpperInvariant(); - string culture = reader.GetString(3); - string currencyCode = reader.GetString(4); - int geographyId = reader.GetInt32(5); - int postalCodeLength = reader.GetInt32(6); + int countryId = reader.GetInt32 (0); + string name = reader.GetString (1); + string code = reader.GetString (2).ToUpperInvariant(); + string culture = reader.GetString (3); + string currencyCode = reader.GetString (4); + int geographyId = reader.GetInt32 (5); + int postalCodeLength = reader.GetInt32 (6); - return new BasicCountry(countryId, name, code, culture, currencyCode, geographyId, postalCodeLength); + return new BasicCountry (countryId, name, code, culture, currencyCode, geographyId, postalCodeLength); } #endregion #region Record reading code - public BasicCountry GetCountry(string countryCode) + public BasicCountry GetCountry (string countryCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + countryFieldSequence + " WHERE Code='" + - countryCode.ToUpperInvariant().Replace("'", "''") + "'", + countryCode.ToUpperInvariant().Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCountryFromDataReader(reader); + return ReadCountryFromDataReader (reader); } - throw new ArgumentException("Unknown Country Code"); + throw new ArgumentException ("Unknown Country Code"); } } } - public BasicCountry GetCountry(int countryId) + public BasicCountry GetCountry (int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + countryFieldSequence + " WHERE CountryId=" + countryId, + DbCommand command = GetDbCommand ("SELECT " + countryFieldSequence + " WHERE CountryId=" + countryId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCountryFromDataReader(reader); + return ReadCountryFromDataReader (reader); } - throw new ArgumentException("Unknown CountryId"); + throw new ArgumentException ("Unknown CountryId"); } } } @@ -84,13 +84,13 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + countryFieldSequence + " ORDER BY Code", connection); + DbCommand command = GetDbCommand ("SELECT " + countryFieldSequence + " ORDER BY Code", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadCountryFromDataReader(reader)); + result.Add (ReadCountryFromDataReader (reader)); } return result.ToArray(); @@ -125,40 +125,40 @@ namespace Swarmops.Database #endregion - public int CreateCountry(string name, string code, string culture, int geographyId, int postalCodeLength, + public int CreateCountry (string name, string code, string culture, int geographyId, int postalCodeLength, string collation) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateCountry", connection); + DbCommand command = GetDbCommand ("CreateCountry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "code", code); - AddParameterWithName(command, "culture", culture); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "postalCodeLength", postalCodeLength); - AddParameterWithName(command, "collation", collation); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "code", code); + AddParameterWithName (command, "culture", culture); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "postalCodeLength", postalCodeLength); + AddParameterWithName (command, "collation", collation); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetCountryGeographyId(int countryId, int geographyId) + public int SetCountryGeographyId (int countryId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetCountryGeographyId", connection); + DbCommand command = GetDbCommand ("SetCountryGeographyId", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "countryId", countryId); - AddParameterWithName(command, "geographyId", geographyId); + AddParameterWithName (command, "countryId", countryId); + AddParameterWithName (command, "geographyId", geographyId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } } diff --git a/Database/Database-Currencies.cs b/Database/Database-Currencies.cs index a747421f..e887f937 100644 --- a/Database/Database-Currencies.cs +++ b/Database/Database-Currencies.cs @@ -14,67 +14,67 @@ namespace Swarmops.Database " CurrencyId,Code,Name,Sign " + // 0-3 "FROM Currencies "; - private static BasicCurrency ReadCurrencyFromDataReader(IDataRecord reader) + private static BasicCurrency ReadCurrencyFromDataReader (IDataRecord reader) { - int currencyId = reader.GetInt32(0); - string code = reader.GetString(1); - string name = reader.GetString(2); - string sign = reader.GetString(3); + int currencyId = reader.GetInt32 (0); + string code = reader.GetString (1); + string name = reader.GetString (2); + string sign = reader.GetString (3); - return new BasicCurrency(currencyId, code, name, sign); + return new BasicCurrency (currencyId, code, name, sign); } #endregion #region Record reading - SELECT statements - public BasicCurrency GetCurrency(int currencyId) + public BasicCurrency GetCurrency (int currencyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + currencyFieldSequence + "WHERE CurrencyId=" + currencyId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCurrencyFromDataReader(reader); + return ReadCurrencyFromDataReader (reader); } - throw new ArgumentException("Unknown Currency Id: " + currencyId); + throw new ArgumentException ("Unknown Currency Id: " + currencyId); } } } - public BasicCurrency GetCurrency(string currencyCode) + public BasicCurrency GetCurrency (string currencyCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + currencyFieldSequence + "WHERE Code='" + - currencyCode.Replace("'", "''").ToUpperInvariant() + "';", connection); + currencyCode.Replace ("'", "''").ToUpperInvariant() + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCurrencyFromDataReader(reader); + return ReadCurrencyFromDataReader (reader); } - throw new ArgumentException("Unknown Currency Code: " + currencyCode); + throw new ArgumentException ("Unknown Currency Code: " + currencyCode); } } } - public BasicCurrency[] GetCurrencies(params object[] conditions) + public BasicCurrency[] GetCurrencies (params object[] conditions) { List result = new List(); @@ -83,14 +83,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + currencyFieldSequence + ConstructWhereClause("Currencies", conditions), connection); + GetDbCommand ( + "SELECT" + currencyFieldSequence + ConstructWhereClause ("Currencies", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadCurrencyFromDataReader(reader)); + result.Add (ReadCurrencyFromDataReader (reader)); } return result.ToArray(); @@ -102,7 +102,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateCurrency(string code, string name, string sign) + public int CreateCurrency (string code, string name, string sign) { DateTime now = DateTime.Now; @@ -110,19 +110,19 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateCurrency", connection); + DbCommand command = GetDbCommand ("CreateCurrency", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "code", code.ToUpperInvariant()); - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "sign", sign); + AddParameterWithName (command, "code", code.ToUpperInvariant()); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "sign", sign); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetCurrencyExchangeRate(DateTime date, int currencyId, double eur100) + public int SetCurrencyExchangeRate (DateTime date, int currencyId, double eur100) { DateTime now = DateTime.Now; @@ -130,14 +130,14 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SetCurrencyExchangeRate", connection); + DbCommand command = GetDbCommand ("SetCurrencyExchangeRate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "currencyId", currencyId); - AddParameterWithName(command, "date", date.Date); - AddParameterWithName(command, "eur100", eur100); + AddParameterWithName (command, "currencyId", currencyId); + AddParameterWithName (command, "date", date.Date); + AddParameterWithName (command, "eur100", eur100); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-Documents.cs b/Database/Database-Documents.cs index 929bbe08..bb95690d 100644 --- a/Database/Database-Documents.cs +++ b/Database/Database-Documents.cs @@ -10,14 +10,14 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicDocument GetDocument(int documentId) + public BasicDocument GetDocument (int documentId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Documents.DocumentId,Documents.ServerFileName,Documents.ClientFileName,Documents.Description,DocumentTypes.Name AS DocumentType,Documents.ForeignId,Documents.FileSize,Documents.UploadedByPersonId,Documents.UploadedDateTime From Documents,DocumentTypes " + "WHERE Documents.DocumentTypeId=DocumentTypes.DocumentTypeId AND " + "Documents.DocumentId = " + documentId + ";", connection); @@ -26,16 +26,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadDocumentFromDataReader(reader); + return ReadDocumentFromDataReader (reader); } - throw new ArgumentException("Unknown Document Id"); + throw new ArgumentException ("Unknown Document Id"); } } } - public BasicDocument[] GetDocumentsForForeignObject(DocumentType documentType, int foreignId) + public BasicDocument[] GetDocumentsForForeignObject (DocumentType documentType, int foreignId) { List result = new List(); @@ -44,7 +44,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Documents.DocumentId,Documents.ServerFileName,Documents.ClientFileName,Documents.Description,DocumentTypes.Name AS DocumentType,Documents.ForeignId,Documents.FileSize,Documents.UploadedByPersonId,Documents.UploadedDateTime From Documents,DocumentTypes " + "WHERE Documents.DocumentTypeId=DocumentTypes.DocumentTypeId AND " + "Documents.ForeignId = " + foreignId + " AND " + @@ -54,7 +54,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadDocumentFromDataReader(reader)); + result.Add (ReadDocumentFromDataReader (reader)); } return result.ToArray(); @@ -63,7 +63,7 @@ namespace Swarmops.Database } - public BasicDocument[] GetDocumentsRecentByDescription(string description) + public BasicDocument[] GetDocumentsRecentByDescription (string description) { List result = new List(); @@ -74,16 +74,16 @@ namespace Swarmops.Database string sqlQuery = "SELECT Documents.DocumentId,Documents.ServerFileName,Documents.ClientFileName,Documents.Description,DocumentTypes.Name AS DocumentType,Documents.ForeignId,Documents.FileSize,Documents.UploadedByPersonId,Documents.UploadedDateTime From Documents,DocumentTypes " + "WHERE Documents.DocumentTypeId=DocumentTypes.DocumentTypeId AND " + - "Documents.Description = '" + description.Replace("'", "''") + "' AND " + - "Documents.UploadedDateTime > '" + DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd HH:mm") + "'"; + "Documents.Description = '" + description.Replace ("'", "''") + "' AND " + + "Documents.UploadedDateTime > '" + DateTime.UtcNow.AddDays (-1).ToString ("yyyy-MM-dd HH:mm") + "'"; - DbCommand command = GetDbCommand(sqlQuery, connection); + DbCommand command = GetDbCommand (sqlQuery, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadDocumentFromDataReader(reader)); + result.Add (ReadDocumentFromDataReader (reader)); } return result.ToArray(); @@ -92,45 +92,45 @@ namespace Swarmops.Database } - private BasicDocument ReadDocumentFromDataReader(DbDataReader reader) + private BasicDocument ReadDocumentFromDataReader (DbDataReader reader) { - int documentId = reader.GetInt32(0); - string serverFileName = reader.GetString(1); - string clientFileName = reader.GetString(2); - string description = reader.GetString(3); - DocumentType docType = (DocumentType) Enum.Parse(typeof (DocumentType), reader.GetString(4)); - int foreignId = reader.GetInt32(5); - Int64 fileSize = reader.GetInt64(6); - int uploadedByPersonId = reader.GetInt32(7); - DateTime uploadedDateTime = reader.GetDateTime(8); + int documentId = reader.GetInt32 (0); + string serverFileName = reader.GetString (1); + string clientFileName = reader.GetString (2); + string description = reader.GetString (3); + DocumentType docType = (DocumentType) Enum.Parse (typeof (DocumentType), reader.GetString (4)); + int foreignId = reader.GetInt32 (5); + Int64 fileSize = reader.GetInt64 (6); + int uploadedByPersonId = reader.GetInt32 (7); + DateTime uploadedDateTime = reader.GetDateTime (8); - return new BasicDocument(documentId, serverFileName, clientFileName, description, docType, + return new BasicDocument (documentId, serverFileName, clientFileName, description, docType, foreignId, fileSize, uploadedByPersonId, uploadedDateTime); } - public int CreateDocument(string serverFileName, string clientFileName, long fileSize, string description, + public int CreateDocument (string serverFileName, string clientFileName, long fileSize, string description, DocumentType documentType, int foreignId, int uploadedByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateDocument", connection); + DbCommand command = GetDbCommand ("CreateDocument", connection); command.CommandType = CommandType.StoredProcedure; // HACK - this bypasses the DB abstraction layer -- debug code to find out why // CreateDocument only gets 4 parameters from the DB abstraction layer, when // we give it 8 - command.Parameters.Add(new MySqlParameter("serverFileName", serverFileName)); - command.Parameters.Add(new MySqlParameter("clientFileName", clientFileName)); - command.Parameters.Add(new MySqlParameter("description", description)); - command.Parameters.Add(new MySqlParameter("docTypeString", documentType.ToString())); - command.Parameters.Add(new MySqlParameter("foreignId", foreignId)); - command.Parameters.Add(new MySqlParameter("fileSize", fileSize)); - command.Parameters.Add(new MySqlParameter("uploadedByPersonId", uploadedByPersonId)); - command.Parameters.Add(new MySqlParameter("uploadedDateTime", DateTime.UtcNow)); + command.Parameters.Add (new MySqlParameter ("serverFileName", serverFileName)); + command.Parameters.Add (new MySqlParameter ("clientFileName", clientFileName)); + command.Parameters.Add (new MySqlParameter ("description", description)); + command.Parameters.Add (new MySqlParameter ("docTypeString", documentType.ToString())); + command.Parameters.Add (new MySqlParameter ("foreignId", foreignId)); + command.Parameters.Add (new MySqlParameter ("fileSize", fileSize)); + command.Parameters.Add (new MySqlParameter ("uploadedByPersonId", uploadedByPersonId)); + command.Parameters.Add (new MySqlParameter ("uploadedDateTime", DateTime.UtcNow)); /* AddParameterWithName(command, "serverFileName", serverFileName); @@ -142,57 +142,57 @@ namespace Swarmops.Database AddParameterWithName(command, "uploadedByPersonId", uploadedByPersonId); AddParameterWithName(command, "uploadedDateTime", DateTime.Now);*/ - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetDocumentServerFileName(int documentId, string serverFileName) + public void SetDocumentServerFileName (int documentId, string serverFileName) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetDocumentServerFileName", connection); + DbCommand command = GetDbCommand ("SetDocumentServerFileName", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "documentId", documentId); - AddParameterWithName(command, "newServerFileName", serverFileName); + AddParameterWithName (command, "documentId", documentId); + AddParameterWithName (command, "newServerFileName", serverFileName); command.ExecuteNonQuery(); } } - public void SetDocumentDescription(int documentId, string newDescription) + public void SetDocumentDescription (int documentId, string newDescription) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetDocumentDescription", connection); + DbCommand command = GetDbCommand ("SetDocumentDescription", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "documentId", documentId); - AddParameterWithName(command, "newDescription", newDescription); + AddParameterWithName (command, "documentId", documentId); + AddParameterWithName (command, "newDescription", newDescription); command.ExecuteNonQuery(); } } - public void SetDocumentForeignObject(int documentId, DocumentType newDocumentType, int newForeignId) + public void SetDocumentForeignObject (int documentId, DocumentType newDocumentType, int newForeignId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetDocumentForeignObject", connection); + DbCommand command = GetDbCommand ("SetDocumentForeignObject", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "documentId", documentId); - AddParameterWithName(command, "newDocumentTypeString", newDocumentType.ToString()); - AddParameterWithName(command, "newForeignId", newForeignId); + AddParameterWithName (command, "documentId", documentId); + AddParameterWithName (command, "newDocumentTypeString", newDocumentType.ToString()); + AddParameterWithName (command, "newForeignId", newForeignId); command.ExecuteNonQuery(); } diff --git a/Database/Database-Events.cs b/Database/Database-Events.cs index 443c797d..7a6387e2 100644 --- a/Database/Database-Events.cs +++ b/Database/Database-Events.cs @@ -22,22 +22,22 @@ namespace Swarmops.Database " JOIN PWEventSources ON (PWEvents.EventSourceId=PWEventSources.EventSourceId) "; - private BasicPWEvent ReadPWEventFromDataReader(DbDataReader reader) + private BasicPWEvent ReadPWEventFromDataReader (DbDataReader reader) { - int eventId = reader.GetInt32(0); - EventType eventType = (EventType) Enum.Parse(typeof (EventType), reader.GetString(1)); - EventSource eventSource = (EventSource) Enum.Parse(typeof (EventSource), reader.GetString(2)); - int actingPersonId = reader.GetInt32(3); - int affectedPersonId = reader.GetInt32(4); - DateTime eventDateTime = reader.GetDateTime(5); - DateTime processedDateTime = reader.GetDateTime(6); - bool open = reader.GetBoolean(7); - int organizationId = reader.GetInt32(8); - int geographyId = reader.GetInt32(9); - int parameterInt = reader.GetInt32(10); - string parameterText = reader.GetString(11); + int eventId = reader.GetInt32 (0); + EventType eventType = (EventType) Enum.Parse (typeof (EventType), reader.GetString (1)); + EventSource eventSource = (EventSource) Enum.Parse (typeof (EventSource), reader.GetString (2)); + int actingPersonId = reader.GetInt32 (3); + int affectedPersonId = reader.GetInt32 (4); + DateTime eventDateTime = reader.GetDateTime (5); + DateTime processedDateTime = reader.GetDateTime (6); + bool open = reader.GetBoolean (7); + int organizationId = reader.GetInt32 (8); + int geographyId = reader.GetInt32 (9); + int parameterInt = reader.GetInt32 (10); + string parameterText = reader.GetString (11); - return new BasicPWEvent(eventId, eventDateTime, open, processedDateTime, eventType, eventSource, + return new BasicPWEvent (eventId, eventDateTime, open, processedDateTime, eventType, eventSource, actingPersonId, affectedPersonId, organizationId, geographyId, parameterInt, parameterText); } @@ -53,7 +53,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + pwEventFieldSequence + " WHERE Open=1 AND ProcessDateTime < NOW() LIMIT 10", connection); @@ -61,7 +61,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPWEventFromDataReader(reader)); + result.Add (ReadPWEventFromDataReader (reader)); } return result.ToArray(); @@ -69,7 +69,7 @@ namespace Swarmops.Database } } - public BasicPWEvent[] GetEventsForPerson(int personId) + public BasicPWEvent[] GetEventsForPerson (int personId) { List result = new List(); @@ -78,7 +78,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + pwEventFieldSequence + " WHERE AffectedPersonId=" + personId + " ORDER BY CreatedDateTime", connection); @@ -87,7 +87,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPWEventFromDataReader(reader)); + result.Add (ReadPWEventFromDataReader (reader)); } return result.ToArray(); @@ -95,24 +95,24 @@ namespace Swarmops.Database } } - public Dictionary> GetEventsForPersons(int[] personId, EventType[] eventTypes) + public Dictionary> GetEventsForPersons (int[] personId, EventType[] eventTypes) { Dictionary> result = new Dictionary>(); List eventTypesAsString = new List(); foreach (EventType et in eventTypes) - eventTypesAsString.Add(et.ToString()); + eventTypesAsString.Add (et.ToString()); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + pwEventFieldSequence - + " WHERE AffectedPersonId IN (" + JoinIds(personId) + ") " + + " WHERE AffectedPersonId IN (" + JoinIds (personId) + ") " + (eventTypes.Length > 0 - ? " AND PWEventTypes.Name IN (" + JoinStrings(eventTypesAsString.ToArray()) + ") " + ? " AND PWEventTypes.Name IN (" + JoinStrings (eventTypesAsString.ToArray()) + ") " : "") + " ORDER BY CreatedDateTime desc", connection); @@ -121,10 +121,10 @@ namespace Swarmops.Database { while (reader.Read()) { - BasicPWEvent evt = ReadPWEventFromDataReader(reader); - if (!result.ContainsKey(evt.AffectedPersonId)) + BasicPWEvent evt = ReadPWEventFromDataReader (reader); + if (!result.ContainsKey (evt.AffectedPersonId)) result[evt.AffectedPersonId] = new List(); - result[evt.AffectedPersonId].Add(evt); + result[evt.AffectedPersonId].Add (evt); } return result; @@ -132,7 +132,7 @@ namespace Swarmops.Database } } - public BasicPWEvent[] GetEventsOfType(EventType eventType) + public BasicPWEvent[] GetEventsOfType (EventType eventType) { List result = new List(); @@ -141,7 +141,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + pwEventFieldSequence + " WHERE PWEventTypes.Name='" + eventType + "' ORDER BY CreatedDateTime", connection); @@ -149,7 +149,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPWEventFromDataReader(reader)); + result.Add (ReadPWEventFromDataReader (reader)); } return result.ToArray(); @@ -158,15 +158,15 @@ namespace Swarmops.Database } - public int CreateEvent(EventSource eventSource, EventType eventType, int actingPersonId, + public int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, int organizationId, int geographyId, int affectedPersonId, int parameterInt, string parameterText) { - return CreateEvent(eventSource, eventType, actingPersonId, organizationId, geographyId, affectedPersonId, + return CreateEvent (eventSource, eventType, actingPersonId, organizationId, geographyId, affectedPersonId, parameterInt, parameterText, DateTime.Now); } - public int CreateEvent(EventSource eventSource, EventType eventType, int actingPersonId, + public int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, int organizationId, int geographyId, int affectedPersonId, int parameterInt, string parameterText, DateTime processTime) @@ -175,33 +175,33 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreatePWEvent", connection); + DbCommand command = GetDbCommand ("CreatePWEvent", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "eventSource", eventSource.ToString()); - AddParameterWithName(command, "eventType", eventType.ToString()); - AddParameterWithName(command, "actingPersonId", actingPersonId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "affectedPersonId", affectedPersonId); - AddParameterWithName(command, "parameterInt", parameterInt); - AddParameterWithName(command, "parameterText", parameterText); - AddParameterWithName(command, "processDateTime", processTime); + AddParameterWithName (command, "eventSource", eventSource.ToString()); + AddParameterWithName (command, "eventType", eventType.ToString()); + AddParameterWithName (command, "actingPersonId", actingPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "affectedPersonId", affectedPersonId); + AddParameterWithName (command, "parameterInt", parameterInt); + AddParameterWithName (command, "parameterText", parameterText); + AddParameterWithName (command, "processDateTime", processTime); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetEventProcessed(int eventId) + public void SetEventProcessed (int eventId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CloseEvent", connection); + DbCommand command = GetDbCommand ("CloseEvent", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "eventId", eventId); + AddParameterWithName (command, "eventId", eventId); command.ExecuteNonQuery(); } diff --git a/Database/Database-ExceptionLog.cs b/Database/Database-ExceptionLog.cs index 42d4b955..96ac62f1 100644 --- a/Database/Database-ExceptionLog.cs +++ b/Database/Database-ExceptionLog.cs @@ -11,16 +11,16 @@ namespace Swarmops.Database private const string exceptionLogFieldSequence = " ExceptionID, ExceptionDateTime, Source,ExceptionText FROM ExceptionLog "; - private static BasicExceptionLog ExceptionLogFromDataReader(DbDataReader reader) + private static BasicExceptionLog ExceptionLogFromDataReader (DbDataReader reader) { - int ExceptionId = reader.GetInt32(0); - DateTime ExceptionDateTime = reader.GetDateTime(1); - string Source = reader.GetString(2); - string ExceptionText = reader.GetString(3); - return new BasicExceptionLog(ExceptionId, ExceptionDateTime, Source, ExceptionText); + int ExceptionId = reader.GetInt32 (0); + DateTime ExceptionDateTime = reader.GetDateTime (1); + string Source = reader.GetString (2); + string ExceptionText = reader.GetString (3); + return new BasicExceptionLog (ExceptionId, ExceptionDateTime, Source, ExceptionText); } - public void CreateExceptionLogEntry(DateTime dateTime, string source, Exception e) + public void CreateExceptionLogEntry (DateTime dateTime, string source, Exception e) { try { @@ -28,12 +28,12 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateExceptionLogEntry", connection); + DbCommand command = GetDbCommand ("CreateExceptionLogEntry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "exceptionDateTime", dateTime); - AddParameterWithName(command, "source", source); - AddParameterWithName(command, "exceptionText", e.ToString()); + AddParameterWithName (command, "exceptionDateTime", dateTime); + AddParameterWithName (command, "source", source); + AddParameterWithName (command, "exceptionText", e.ToString()); command.ExecuteNonQuery(); // no primary key for exception log } @@ -46,14 +46,14 @@ namespace Swarmops.Database } - public BasicExceptionLog[] GetExceptionLogTopEntries(int count) + public BasicExceptionLog[] GetExceptionLogTopEntries (int count) { using (DbConnection connection = GetMySqlDbConnection()) { List result = new List(); connection.Open(); - DbCommand command = GetDbCommand(@" + DbCommand command = GetDbCommand (@" SELECT " + exceptionLogFieldSequence + @" order by ExceptionID desc LIMIT " + count, connection); @@ -63,7 +63,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ExceptionLogFromDataReader(reader)); + result.Add (ExceptionLogFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-Expenses.cs b/Database/Database-Expenses.cs index e9714ccf..c61668bf 100644 --- a/Database/Database-Expenses.cs +++ b/Database/Database-Expenses.cs @@ -9,13 +9,13 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicExpenseClaim GetExpenseClaim(int expenseClaimId) + public BasicExpenseClaim GetExpenseClaim (int expenseClaimId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + @@ -26,15 +26,15 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadExpenseFromDataReader(reader); + return ReadExpenseFromDataReader (reader); } - throw new ArgumentException("Unknown ExpenseClaim Id"); + throw new ArgumentException ("Unknown ExpenseClaim Id"); } } } - public BasicExpenseClaim[] GetExpenseClaims(params object[] conditions) + public BasicExpenseClaim[] GetExpenseClaims (params object[] conditions) { List result = new List(); @@ -43,17 +43,17 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + - "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + - "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims " + ConstructWhereClause("ExpenseClaims", conditions), + GetDbCommand ("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims " + ConstructWhereClause ("ExpenseClaims", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExpenseFromDataReader(reader)); + result.Add (ReadExpenseFromDataReader (reader)); } return result.ToArray(); @@ -61,7 +61,7 @@ namespace Swarmops.Database } } - public BasicExpenseClaim[] GetExpenseClaimsByClaimer(int claimingPersonId) + public BasicExpenseClaim[] GetExpenseClaimsByClaimer (int claimingPersonId) { List result = new List(); @@ -70,17 +70,17 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + - "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + - "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims WHERE ClaimingPersonId=" + claimingPersonId, + GetDbCommand ("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE ClaimingPersonId=" + claimingPersonId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExpenseFromDataReader(reader)); + result.Add (ReadExpenseFromDataReader (reader)); } return result.ToArray(); @@ -88,7 +88,7 @@ namespace Swarmops.Database } } - public BasicExpenseClaim[] GetExpenseClaimsByClaimerAndOrganization(int claimingPersonId, int organizationId) + public BasicExpenseClaim[] GetExpenseClaimsByClaimerAndOrganization (int claimingPersonId, int organizationId) { List result = new List(); @@ -97,18 +97,18 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + - "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + - "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims WHERE ClaimingPersonId=" + claimingPersonId + - " AND OrganizationId=" + organizationId, + GetDbCommand ("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE ClaimingPersonId=" + claimingPersonId + + " AND OrganizationId=" + organizationId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExpenseFromDataReader(reader)); + result.Add (ReadExpenseFromDataReader (reader)); } return result.ToArray(); @@ -116,7 +116,7 @@ namespace Swarmops.Database } } - public BasicExpenseClaim[] GetExpenseClaimsByBudgetAndYear(int budgetId, int budgetYear) + public BasicExpenseClaim[] GetExpenseClaimsByBudgetAndYear (int budgetId, int budgetYear) { List result = new List(); @@ -125,17 +125,17 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + - "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + - "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims WHERE BudgetId=" + budgetId + " AND BudgetYear=" + budgetYear, + GetDbCommand ("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE BudgetId=" + budgetId + " AND BudgetYear=" + budgetYear, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExpenseFromDataReader(reader)); + result.Add (ReadExpenseFromDataReader (reader)); } return result.ToArray(); @@ -143,7 +143,7 @@ namespace Swarmops.Database } } - public BasicExpenseClaim[] GetExpenseClaimsByOrganization(int organizationId) + public BasicExpenseClaim[] GetExpenseClaimsByOrganization (int organizationId) { List result = new List(); @@ -152,17 +152,17 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + - "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + - "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims WHERE OrganizationId=" + organizationId, + GetDbCommand ("SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE OrganizationId=" + organizationId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExpenseFromDataReader(reader)); + result.Add (ReadExpenseFromDataReader (reader)); } return result.ToArray(); @@ -171,282 +171,282 @@ namespace Swarmops.Database } - private BasicExpenseClaim ReadExpenseFromDataReader(DbDataReader reader) + private BasicExpenseClaim ReadExpenseFromDataReader (DbDataReader reader) { - int expenseClaimId = reader.GetInt32(0); - int claimingPersonId = reader.GetInt32(1); - DateTime createdDateTime = reader.GetDateTime(2); - bool open = reader.GetBoolean(3); - bool attested = reader.GetBoolean(4); - bool documented = reader.GetBoolean(5); - bool claimed = reader.GetBoolean(6); - int organizationId = reader.GetInt32(7); - int geographyId = reader.GetInt32(8); // obsolete field - int budgetId = reader.GetInt32(9); - DateTime expenseDate = reader.GetDateTime(10); - string description = reader.GetString(11); - double preApprovedAmount = reader.GetDouble(12); - Int64 amountCents = reader.GetInt64(13); - bool repaid = reader.GetBoolean(14); - bool keepSeparate = reader.GetBoolean(15); + int expenseClaimId = reader.GetInt32 (0); + int claimingPersonId = reader.GetInt32 (1); + DateTime createdDateTime = reader.GetDateTime (2); + bool open = reader.GetBoolean (3); + bool attested = reader.GetBoolean (4); + bool documented = reader.GetBoolean (5); + bool claimed = reader.GetBoolean (6); + int organizationId = reader.GetInt32 (7); + int geographyId = reader.GetInt32 (8); // obsolete field + int budgetId = reader.GetInt32 (9); + DateTime expenseDate = reader.GetDateTime (10); + string description = reader.GetString (11); + double preApprovedAmount = reader.GetDouble (12); + Int64 amountCents = reader.GetInt64 (13); + bool repaid = reader.GetBoolean (14); + bool keepSeparate = reader.GetBoolean (15); - return new BasicExpenseClaim(expenseClaimId, claimingPersonId, createdDateTime, + return new BasicExpenseClaim (expenseClaimId, claimingPersonId, createdDateTime, open, attested, documented, claimed, organizationId, geographyId, budgetId, expenseDate, description, preApprovedAmount, amountCents, repaid, keepSeparate); } - public int CreateExpenseClaim(int claimingPersonId, int organizationId, int budgetId, + public int CreateExpenseClaim (int claimingPersonId, int organizationId, int budgetId, DateTime expenseDate, string description, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateExpenseClaim", connection); + DbCommand command = GetDbCommand ("CreateExpenseClaim", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "claimingPersonId", claimingPersonId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "expenseDate", expenseDate); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "claimingPersonId", claimingPersonId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "expenseDate", expenseDate); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "amount", amount); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateExpenseClaim(int claimingPersonId, int organizationId, int budgetId, + public int CreateExpenseClaim (int claimingPersonId, int organizationId, int budgetId, DateTime expenseDate, string description, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateExpenseClaimPrecise", connection); + DbCommand command = GetDbCommand ("CreateExpenseClaimPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "claimingPersonId", claimingPersonId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "budgetId", budgetId); - AddParameterWithName(command, "expenseDate", expenseDate); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "claimingPersonId", claimingPersonId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "budgetId", budgetId); + AddParameterWithName (command, "expenseDate", expenseDate); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "amountCents", amountCents); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimDescription(int expenseClaimId, string description) + public int SetExpenseClaimDescription (int expenseClaimId, string description) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimDescription", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimDescription", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "description", description); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "description", description); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimBudget(int expenseClaimId, int budgetId) + public int SetExpenseClaimBudget (int expenseClaimId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimBudget", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimBudget", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "budgetId", budgetId); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "budgetId", budgetId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimBudgetYear(int expenseClaimId, int budgetYear) + public int SetExpenseClaimBudgetYear (int expenseClaimId, int budgetYear) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimBudgetYear", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimBudgetYear", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "budgetYear", budgetYear); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "budgetYear", budgetYear); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimDate(int expenseClaimId, DateTime expenseDate) + public int SetExpenseClaimDate (int expenseClaimId, DateTime expenseDate) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimDate", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimDate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "expenseDate", expenseDate); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "expenseDate", expenseDate); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimAmount(int expenseClaimId, double amount) + public int SetExpenseClaimAmount (int expenseClaimId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimAmount", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimAmount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "amount", amount); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimAmount(int expenseClaimId, Int64 amountCents) + public int SetExpenseClaimAmount (int expenseClaimId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimAmountPrecise", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimAmountPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "amountCents", amountCents); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimAttested(int expenseClaimId, bool attested) + public int SetExpenseClaimAttested (int expenseClaimId, bool attested) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimAttested", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimAttested", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "attested", attested); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "attested", attested); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimValidated(int expenseClaimId, bool validated) + public int SetExpenseClaimValidated (int expenseClaimId, bool validated) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimValidated", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimValidated", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "validated", validated); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "validated", validated); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimKeepSeparate(int expenseClaimId, bool keepSeparate) + public int SetExpenseClaimKeepSeparate (int expenseClaimId, bool keepSeparate) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimKeepSeparate", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimKeepSeparate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "keepSeparate", keepSeparate); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "keepSeparate", keepSeparate); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimClaimed(int expenseClaimId, bool claimed) + public int SetExpenseClaimClaimed (int expenseClaimId, bool claimed) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimClaimed", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimClaimed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "claimed", claimed); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "claimed", claimed); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimOpen(int expenseClaimId, bool open) + public int SetExpenseClaimOpen (int expenseClaimId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimOpen", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "open", open); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetExpenseClaimRepaid(int expenseClaimId, bool repaid) + public int SetExpenseClaimRepaid (int expenseClaimId, bool repaid) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetExpenseClaimRepaid", connection); + DbCommand command = GetDbCommand ("SetExpenseClaimRepaid", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "expenseClaimId", expenseClaimId); - AddParameterWithName(command, "repaid", repaid); + AddParameterWithName (command, "expenseClaimId", expenseClaimId); + AddParameterWithName (command, "repaid", repaid); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateExpenseEvent(int expenseId, ExpenseEventType eventType, int personId) + public int CreateExpenseEvent (int expenseId, ExpenseEventType eventType, int personId) { - throw new NotImplementedException("Not migrated to version 4"); + throw new NotImplementedException ("Not migrated to version 4"); /* // WARNING: NOT CONVERTED TO V4 YET diff --git a/Database/Database-ExternalActivities.cs b/Database/Database-ExternalActivities.cs index 1b64a7e5..a709906b 100644 --- a/Database/Database-ExternalActivities.cs +++ b/Database/Database-ExternalActivities.cs @@ -16,20 +16,20 @@ namespace Swarmops.Database " Description,CreatedDateTime,CreatedByPersonId,DupeOfActivityId" + " FROM ExternalActivities JOIN ExternalActivityTypes USING (ExternalActivityTypeId) "; - private static BasicExternalActivity ReadExternalActivityFromDataReader(IDataRecord reader) + private static BasicExternalActivity ReadExternalActivityFromDataReader (IDataRecord reader) { - int externalActivityId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - int geographyId = reader.GetInt32(2); - DateTime dateTime = reader.GetDateTime(3); + int externalActivityId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + int geographyId = reader.GetInt32 (2); + DateTime dateTime = reader.GetDateTime (3); ExternalActivityType type = - (ExternalActivityType) Enum.Parse(typeof (ExternalActivityType), reader.GetString(4)); - string description = reader.GetString(5); - DateTime createdDateTime = reader.GetDateTime(6); - int createdByPersonId = reader.GetInt32(7); - int dupeOfActivityId = reader.GetInt32(8); + (ExternalActivityType) Enum.Parse (typeof (ExternalActivityType), reader.GetString (4)); + string description = reader.GetString (5); + DateTime createdDateTime = reader.GetDateTime (6); + int createdByPersonId = reader.GetInt32 (7); + int dupeOfActivityId = reader.GetInt32 (8); - return new BasicExternalActivity(externalActivityId, organizationId, geographyId, type, dateTime, + return new BasicExternalActivity (externalActivityId, organizationId, geographyId, type, dateTime, description, createdByPersonId, createdDateTime, dupeOfActivityId); } @@ -43,14 +43,14 @@ namespace Swarmops.Database /// The external activity database identity. /// The requested external activity. /// Thrown if there is no such identity. - public BasicExternalActivity GetExternalActivity(int externalActivityId) + public BasicExternalActivity GetExternalActivity (int externalActivityId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + externalActivityFieldSequence + "WHERE ExternalActivityId=" + externalActivityId + ";", connection); @@ -58,10 +58,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadExternalActivityFromDataReader(reader); + return ReadExternalActivityFromDataReader (reader); } - throw new ArgumentException("Unknown External Activity Id: " + externalActivityId); + throw new ArgumentException ("Unknown External Activity Id: " + externalActivityId); } } } @@ -74,9 +74,9 @@ namespace Swarmops.Database /// specifiers. /// /// A list of matching ExternalActivities. - public BasicExternalActivity[] GetExternalActivities(params object[] conditions) + public BasicExternalActivity[] GetExternalActivities (params object[] conditions) { - return GetExternalActivitiesSorted("", 0, conditions); + return GetExternalActivitiesSorted ("", 0, conditions); } /// @@ -87,7 +87,7 @@ namespace Swarmops.Database /// specifiers. /// /// A list of matching ExternalActivities. - public BasicExternalActivity[] GetExternalActivitiesSorted(string sortOrder, int limitCount, + public BasicExternalActivity[] GetExternalActivitiesSorted (string sortOrder, int limitCount, params object[] conditions) { List result = new List(); @@ -114,15 +114,15 @@ namespace Swarmops.Database DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + externalActivityFieldSequence + - ConstructWhereClause("ExternalActivities", conditions) + sort + limit, connection); + ConstructWhereClause ("ExternalActivities", conditions) + sort + limit, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadExternalActivityFromDataReader(reader)); + result.Add (ReadExternalActivityFromDataReader (reader)); } return result.ToArray(); @@ -134,30 +134,30 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateExternalActivity(int organizationId, int geographyId, DateTime dateTime, + public int CreateExternalActivity (int organizationId, int geographyId, DateTime dateTime, ExternalActivityType type, string description, int createdByPersonId) { if (description.Length > 256) { - description = description.Substring(0, 250) + "..."; + description = description.Substring (0, 250) + "..."; } using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateExternalActivity", connection); + DbCommand command = GetDbCommand ("CreateExternalActivity", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "dateTime", dateTime); - AddParameterWithName(command, "externalActivityType", type.ToString()); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "dateTime", dateTime); + AddParameterWithName (command, "externalActivityType", type.ToString()); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-ExternalCredentials.cs b/Database/Database-ExternalCredentials.cs index 5433b877..12941d0b 100644 --- a/Database/Database-ExternalCredentials.cs +++ b/Database/Database-ExternalCredentials.cs @@ -6,39 +6,39 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicExternalCredential GetExternalCredential(string serviceName) + public BasicExternalCredential GetExternalCredential (string serviceName) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT ExternalCredentialId,ServiceName,Login,Password From ExternalCredentials WHERE ServiceName='" + - serviceName.Replace("'", "''") + "'", + serviceName.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadExternalCredentialFromDataReader(reader); + return ReadExternalCredentialFromDataReader (reader); } - throw new ArgumentException("Unknown Service Name"); + throw new ArgumentException ("Unknown Service Name"); } } } - private BasicExternalCredential ReadExternalCredentialFromDataReader(DbDataReader reader) + private BasicExternalCredential ReadExternalCredentialFromDataReader (DbDataReader reader) { - int externalCredentialId = reader.GetInt32(0); - string serviceName = reader.GetString(1); - string login = reader.GetString(2); - string password = reader.GetString(3); + int externalCredentialId = reader.GetInt32 (0); + string serviceName = reader.GetString (1); + string login = reader.GetString (2); + string password = reader.GetString (3); - return new BasicExternalCredential(externalCredentialId, serviceName, login, password); + return new BasicExternalCredential (externalCredentialId, serviceName, login, password); } } } \ No newline at end of file diff --git a/Database/Database-ExternalIdentities.cs b/Database/Database-ExternalIdentities.cs index e0e71c93..a7351b3f 100644 --- a/Database/Database-ExternalIdentities.cs +++ b/Database/Database-ExternalIdentities.cs @@ -13,82 +13,82 @@ namespace Swarmops.Database @" ExternalIdentityIdentity, ExternalIdentityTypeName, ExternalSystem, UserID, `Password`, AttachedToPerson FROM ExternalIdentities inner join ExternalIdentityTypes on TypeOfAccount=ExternalIdentityTypeId"; - public BasicExternalIdentity GetExternalIdentity(int identity) + public BasicExternalIdentity GetExternalIdentity (int identity) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + readFieldsSQL + " WHERE ExternalIdentityIdentity=@id", connection); - AddParameterWithName(command, "id", identity); + AddParameterWithName (command, "id", identity); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadExternalIdentityFromDataReader(reader); + return ReadExternalIdentityFromDataReader (reader); } - throw new ArgumentException("Unknown Identity"); + throw new ArgumentException ("Unknown Identity"); } } } - public BasicExternalIdentity GetExternalIdentityFromPersonIdAndType(int persId, ExternalIdentityType type) + public BasicExternalIdentity GetExternalIdentityFromPersonIdAndType (int persId, ExternalIdentityType type) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + readFieldsSQL + " WHERE AttachedToPerson= @persId and ExternalIdentityTypeName = @typeName", connection); - AddParameterWithName(command, "persId", persId); - AddParameterWithName(command, "typeName", type.ToString()); + AddParameterWithName (command, "persId", persId); + AddParameterWithName (command, "typeName", type.ToString()); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadExternalIdentityFromDataReader(reader); + return ReadExternalIdentityFromDataReader (reader); } - throw new ArgumentException("Unknown Identity"); + throw new ArgumentException ("Unknown Identity"); } } } - public BasicExternalIdentity GetExternalIdentityFromUserIdAndType(string userid, ExternalIdentityType type) + public BasicExternalIdentity GetExternalIdentityFromUserIdAndType (string userid, ExternalIdentityType type) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + readFieldsSQL + " WHERE UserID = @userid and ExternalIdentityTypeName = @type", connection); - AddParameterWithName(command, "userid", userid); - AddParameterWithName(command, "type", type.ToString()); + AddParameterWithName (command, "userid", userid); + AddParameterWithName (command, "type", type.ToString()); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadExternalIdentityFromDataReader(reader); + return ReadExternalIdentityFromDataReader (reader); } - throw new ArgumentException("Unknown Identity"); + throw new ArgumentException ("Unknown Identity"); } } } - public List GetExternalIdentities(int persId) + public List GetExternalIdentities (int persId) { List retval = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -96,16 +96,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + readFieldsSQL + " WHERE AttachedToPerson= @persId", connection); - AddParameterWithName(command, "persId", persId); + AddParameterWithName (command, "persId", persId); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - retval.Add(ReadExternalIdentityFromDataReader(reader)); + retval.Add (ReadExternalIdentityFromDataReader (reader)); } return retval; } @@ -122,7 +122,7 @@ namespace Swarmops.Database /// /// /// - public BasicExternalIdentity SetExternalIdentity( + public BasicExternalIdentity SetExternalIdentity ( int externalIdentityIdentity, ExternalIdentityType typeOfAccount, string externalSystem, @@ -134,21 +134,21 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SetExternalIdentity", connection); + DbCommand command = GetDbCommand ("SetExternalIdentity", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "pExternalIdentityIdentity", externalIdentityIdentity); - AddParameterWithName(command, "pTypeOfAccount", typeOfAccount.ToString()); - AddParameterWithName(command, "pExternalSystem", externalSystem); - AddParameterWithName(command, "pUserID", userID); - AddParameterWithName(command, "pPassword", password); - AddParameterWithName(command, "pAttachedToPerson", attachedToPerson); + AddParameterWithName (command, "pExternalIdentityIdentity", externalIdentityIdentity); + AddParameterWithName (command, "pTypeOfAccount", typeOfAccount.ToString()); + AddParameterWithName (command, "pExternalSystem", externalSystem); + AddParameterWithName (command, "pUserID", userID); + AddParameterWithName (command, "pPassword", password); + AddParameterWithName (command, "pAttachedToPerson", attachedToPerson); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadExternalIdentityFromDataReader(reader); + return ReadExternalIdentityFromDataReader (reader); } } } @@ -156,18 +156,18 @@ namespace Swarmops.Database } - private BasicExternalIdentity ReadExternalIdentityFromDataReader(DbDataReader reader) + private BasicExternalIdentity ReadExternalIdentityFromDataReader (DbDataReader reader) { int externalIdentityId = (int) reader["ExternalIdentityIdentity"]; ExternalIdentityType typeOfAccount = (ExternalIdentityType) - Enum.Parse(typeof (ExternalIdentityType), reader["ExternalIdentityTypeName"].ToString()); + Enum.Parse (typeof (ExternalIdentityType), reader["ExternalIdentityTypeName"].ToString()); string externalSystem = (string) reader["ExternalSystem"]; string userID = (string) reader["UserID"]; string password = (string) reader["Password"]; int attachedToPerson = (int) reader["AttachedToPerson"]; - return new BasicExternalIdentity(externalIdentityId, typeOfAccount, externalSystem, userID, password, + return new BasicExternalIdentity (externalIdentityId, typeOfAccount, externalSystem, userID, password, attachedToPerson); } } diff --git a/Database/Database-FinancialTransactionTagSetTypes.cs b/Database/Database-FinancialTransactionTagSetTypes.cs index 06c6d20f..ed82a0b9 100644 --- a/Database/Database-FinancialTransactionTagSetTypes.cs +++ b/Database/Database-FinancialTransactionTagSetTypes.cs @@ -15,20 +15,20 @@ namespace Swarmops.Database " FinancialTransactionTagSetTypeId,ResourceName " + // 0-1 "FROM FinancialTransactionTagSetTypes "; - private static BasicFinancialTransactionTagSetType ReadFinancialTransactionTagSetTypeFromDataReader( + private static BasicFinancialTransactionTagSetType ReadFinancialTransactionTagSetTypeFromDataReader ( IDataRecord reader) { - int financialTransactionTagSetTypeId = reader.GetInt32(0); - string resourceName = reader.GetString(1); + int financialTransactionTagSetTypeId = reader.GetInt32 (0); + string resourceName = reader.GetString (1); - return new BasicFinancialTransactionTagSetType(financialTransactionTagSetTypeId, resourceName); + return new BasicFinancialTransactionTagSetType (financialTransactionTagSetTypeId, resourceName); } #endregion #region Database record reading -- SELECT clauses - public BasicFinancialTransactionTagSetType GetFinancialTransactionTagSetType( + public BasicFinancialTransactionTagSetType GetFinancialTransactionTagSetType ( int financialTransactionTagSetTypeId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -36,20 +36,20 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagSetTypeFieldSequence + " WHERE FinancialTransactionTagSetTypeId=" + - financialTransactionTagSetTypeId.ToString(CultureInfo.InvariantCulture), connection); + financialTransactionTagSetTypeId.ToString (CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadFinancialTransactionTagSetTypeFromDataReader(reader); + return ReadFinancialTransactionTagSetTypeFromDataReader (reader); } - throw new ArgumentException("No such FinancialTransactionSetTypeId: " + - financialTransactionTagSetTypeId.ToString(CultureInfo.InvariantCulture)); + throw new ArgumentException ("No such FinancialTransactionSetTypeId: " + + financialTransactionTagSetTypeId.ToString (CultureInfo.InvariantCulture)); } } } @@ -63,13 +63,13 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT" + financialTransactionTagSetTypeFieldSequence, connection); + DbCommand command = GetDbCommand ("SELECT" + financialTransactionTagSetTypeFieldSequence, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionTagSetTypeFromDataReader(reader)); + result.Add (ReadFinancialTransactionTagSetTypeFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-FinancialTransactionTagSets.cs b/Database/Database-FinancialTransactionTagSets.cs index 53868ec2..9a982484 100644 --- a/Database/Database-FinancialTransactionTagSets.cs +++ b/Database/Database-FinancialTransactionTagSets.cs @@ -17,17 +17,17 @@ namespace Swarmops.Database "VisibilityLevel,ProfitLossType " + // 5-6 "FROM FinancialTransactionTagSets "; - private static BasicFinancialTransactionTagSet ReadFinancialTransactionTagSetFromDataReader(IDataRecord reader) + private static BasicFinancialTransactionTagSet ReadFinancialTransactionTagSetFromDataReader (IDataRecord reader) { - int financialTransactionTagSetId = reader.GetInt32(0); - int financialTransactionTagSetTypeId = reader.GetInt32(1); - int organizationId = reader.GetInt32(2); - int order = reader.GetInt32(3); - bool allowUntagged = reader.GetBoolean(4); - int visibilityLevel = reader.GetInt32(5); - int profitLossType = reader.GetInt32(6); + int financialTransactionTagSetId = reader.GetInt32 (0); + int financialTransactionTagSetTypeId = reader.GetInt32 (1); + int organizationId = reader.GetInt32 (2); + int order = reader.GetInt32 (3); + bool allowUntagged = reader.GetBoolean (4); + int visibilityLevel = reader.GetInt32 (5); + int profitLossType = reader.GetInt32 (6); - return new BasicFinancialTransactionTagSet(financialTransactionTagSetId, financialTransactionTagSetTypeId, + return new BasicFinancialTransactionTagSet (financialTransactionTagSetId, financialTransactionTagSetTypeId, organizationId, order, allowUntagged, visibilityLevel, profitLossType); } @@ -35,32 +35,32 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicFinancialTransactionTagSet GetFinancialTransactionTagSet(int financialTransactionTagSetId) + public BasicFinancialTransactionTagSet GetFinancialTransactionTagSet (int financialTransactionTagSetId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagSetFieldSequence + " WHERE FinancialTransactionTagSetId=" + - financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture), connection); + financialTransactionTagSetId.ToString (CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadFinancialTransactionTagSetFromDataReader(reader); + return ReadFinancialTransactionTagSetFromDataReader (reader); } - throw new ArgumentException("No such FinancialTransactionSetTypeId: " + - financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture)); + throw new ArgumentException ("No such FinancialTransactionSetTypeId: " + + financialTransactionTagSetId.ToString (CultureInfo.InvariantCulture)); } } } - public BasicFinancialTransactionTagSet[] GetFinancialTransactionTagSets(params object[] conditions) + public BasicFinancialTransactionTagSet[] GetFinancialTransactionTagSets (params object[] conditions) { List result = new List(); @@ -69,16 +69,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagSetFieldSequence + - ConstructWhereClause("FinancialTransactionTagSets", conditions) + " ORDER BY DisplayOrder", + ConstructWhereClause ("FinancialTransactionTagSets", conditions) + " ORDER BY DisplayOrder", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionTagSetFromDataReader(reader)); + result.Add (ReadFinancialTransactionTagSetFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-FinancialTransactionTagTypes.cs b/Database/Database-FinancialTransactionTagTypes.cs index 71ee4bef..f0393db1 100644 --- a/Database/Database-FinancialTransactionTagTypes.cs +++ b/Database/Database-FinancialTransactionTagTypes.cs @@ -17,17 +17,18 @@ namespace Swarmops.Database "OpenedYear,ClosedYear " + // 5-6 "FROM FinancialTransactionTagTypes "; - private static BasicFinancialTransactionTagType ReadFinancialTransactionTagTypeFromDataReader(IDataRecord reader) + private static BasicFinancialTransactionTagType ReadFinancialTransactionTagTypeFromDataReader ( + IDataRecord reader) { - int financialTransactionTagTypeId = reader.GetInt32(0); - int parentFinancialTransactionTagTypeId = reader.GetInt32(1); - int financialTransactionTagSetId = reader.GetInt32(2); - string name = reader.GetString(3); - bool active = reader.GetBoolean(4); - int openedYear = reader.GetInt32(5); - int closedYear = reader.GetInt32(6); + int financialTransactionTagTypeId = reader.GetInt32 (0); + int parentFinancialTransactionTagTypeId = reader.GetInt32 (1); + int financialTransactionTagSetId = reader.GetInt32 (2); + string name = reader.GetString (3); + bool active = reader.GetBoolean (4); + int openedYear = reader.GetInt32 (5); + int closedYear = reader.GetInt32 (6); - return new BasicFinancialTransactionTagType(financialTransactionTagTypeId, + return new BasicFinancialTransactionTagType (financialTransactionTagTypeId, parentFinancialTransactionTagTypeId, financialTransactionTagSetId, name, active, openedYear, closedYear); } @@ -35,32 +36,32 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicFinancialTransactionTagType GetFinancialTransactionTagType(int financialTransactionTagTypeId) + public BasicFinancialTransactionTagType GetFinancialTransactionTagType (int financialTransactionTagTypeId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagTypeFieldSequence + " WHERE FinancialTransactionTagTypeId=" + - financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture), connection); + financialTransactionTagTypeId.ToString (CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadFinancialTransactionTagTypeFromDataReader(reader); + return ReadFinancialTransactionTagTypeFromDataReader (reader); } - throw new ArgumentException("No such FinancialTransactionSetTypeId: " + - financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture)); + throw new ArgumentException ("No such FinancialTransactionSetTypeId: " + + financialTransactionTagTypeId.ToString (CultureInfo.InvariantCulture)); } } } - public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypes(params object[] conditions) + public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypes (params object[] conditions) { List result = new List(); @@ -69,15 +70,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagTypeFieldSequence + - ConstructWhereClause("FinancialTransactionTagTypes", conditions), connection); + ConstructWhereClause ("FinancialTransactionTagTypes", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionTagTypeFromDataReader(reader)); + result.Add (ReadFinancialTransactionTagTypeFromDataReader (reader)); } return result.ToArray(); @@ -86,7 +87,7 @@ namespace Swarmops.Database } - public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypesByIdentity(int[] identities) + public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypesByIdentity (int[] identities) { List result = new List(); @@ -95,15 +96,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + financialTransactionTagTypeFieldSequence + - " WHERE FinancialTransactionTagTypeId IN (" + JoinIds(identities) + ")", connection); + " WHERE FinancialTransactionTagTypeId IN (" + JoinIds (identities) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionTagTypeFromDataReader(reader)); + result.Add (ReadFinancialTransactionTagTypeFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-FinancialTransactionTags.cs b/Database/Database-FinancialTransactionTags.cs index eba99104..34fe3904 100644 --- a/Database/Database-FinancialTransactionTags.cs +++ b/Database/Database-FinancialTransactionTags.cs @@ -16,7 +16,7 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public int[] GetFinancialTransactionTagTypes(int financialTransactionId) + public int[] GetFinancialTransactionTagTypes (int financialTransactionId) { List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -24,16 +24,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialTransactionTagTypeId FROM FinancialTransactionTags WHERE FinancialTransactionId=" + - financialTransactionId.ToString(CultureInfo.InvariantCulture), connection); + financialTransactionId.ToString (CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(reader.GetInt32(0)); - // This is a tag type IDENTITY. Need another db call to read the actual tag types. + result.Add (reader.GetInt32 (0)); + // This is a tag type IDENTITY. Need another db call to read the actual tag types. } return result.ToArray(); @@ -45,47 +45,47 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateFinancialTransactionTag(int financialTransactionId, int financialTransactionTagTypeId) + public int CreateFinancialTransactionTag (int financialTransactionId, int financialTransactionTagTypeId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialTransactionTag", connection); + DbCommand command = GetDbCommand ("CreateFinancialTransactionTag", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); - AddParameterWithName(command, "financialTransactionTagTypeId", financialTransactionTagTypeId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialTransactionTagTypeId", financialTransactionTagTypeId); - return Convert.ToInt32(command.ExecuteScalar()); // returns identity, but it's not used - yet, anyway + return Convert.ToInt32 (command.ExecuteScalar()); // returns identity, but it's not used - yet, anyway } } - public void DeleteFinancialTransactionTags(int financialTransactionId) + public void DeleteFinancialTransactionTags (int financialTransactionId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteFinancialTransactionTags", connection); + DbCommand command = GetDbCommand ("DeleteFinancialTransactionTags", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); command.ExecuteNonQuery(); } } - public void DeleteFinancialTransactionTag(int financialTransactionTagId) + public void DeleteFinancialTransactionTag (int financialTransactionTagId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteFinancialTransactionTag", connection); + DbCommand command = GetDbCommand ("DeleteFinancialTransactionTag", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionTagId", financialTransactionTagId); + AddParameterWithName (command, "financialTransactionTagId", financialTransactionTagId); command.ExecuteNonQuery(); } diff --git a/Database/Database-FinancialValidations.cs b/Database/Database-FinancialValidations.cs index a222d37c..69967742 100644 --- a/Database/Database-FinancialValidations.cs +++ b/Database/Database-FinancialValidations.cs @@ -20,19 +20,19 @@ namespace Swarmops.Database private const string financialValidationOrder = " ORDER BY FinancialValidationId "; - private static BasicFinancialValidation ReadFinancialValidationFromDataReader(IDataRecord reader) + private static BasicFinancialValidation ReadFinancialValidationFromDataReader (IDataRecord reader) { - int financialValidationId = reader.GetInt32(0); + int financialValidationId = reader.GetInt32 (0); FinancialValidationType validationType = - (FinancialValidationType) (Enum.Parse(typeof (FinancialValidationType), reader.GetString(1))); + (FinancialValidationType) (Enum.Parse (typeof (FinancialValidationType), reader.GetString (1))); FinancialDependencyType dependencyType = - (FinancialDependencyType) (Enum.Parse(typeof (FinancialDependencyType), reader.GetString(2))); - int foreignId = reader.GetInt32(3); - DateTime dateTime = reader.GetDateTime(4); - int personId = reader.GetInt32(5); - double amount = reader.GetDouble(6); // not yet used + (FinancialDependencyType) (Enum.Parse (typeof (FinancialDependencyType), reader.GetString (2))); + int foreignId = reader.GetInt32 (3); + DateTime dateTime = reader.GetDateTime (4); + int personId = reader.GetInt32 (5); + double amount = reader.GetDouble (6); // not yet used - return new BasicFinancialValidation(financialValidationId, validationType, personId, dateTime, + return new BasicFinancialValidation (financialValidationId, validationType, personId, dateTime, dependencyType, foreignId); } @@ -40,7 +40,7 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicFinancialValidation[] GetFinancialValidations(FinancialDependencyType dependencyType, int foreignId) + public BasicFinancialValidation[] GetFinancialValidations (FinancialDependencyType dependencyType, int foreignId) { List result = new List(); @@ -49,7 +49,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialValidationFieldSequence + " WHERE FinancialDependencyTypes.Name='" + dependencyType + "' AND ForeignId=" + foreignId + " " + financialValidationOrder, connection); @@ -57,7 +57,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialValidationFromDataReader(reader)); + result.Add (ReadFinancialValidationFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-Financials.cs b/Database/Database-Financials.cs index 82565930..f11cb487 100644 --- a/Database/Database-Financials.cs +++ b/Database/Database-Financials.cs @@ -21,34 +21,34 @@ namespace Swarmops.Database " Administrative,Active,LinkBackward,LinkForward " + // 10-13 " FROM FinancialAccounts "; - public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, + public int CreateFinancialAccount (int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialAccount", connection); + DbCommand command = GetDbCommand ("CreateFinancialAccount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "pOrganizationId", pOrganizationId); - AddParameterWithName(command, "pName", pName); - AddParameterWithName(command, "pAccountType", (int) pAccountType); - AddParameterWithName(command, "pParentFinancialAccountId", pParentFinancialAccountId); + AddParameterWithName (command, "pOrganizationId", pOrganizationId); + AddParameterWithName (command, "pName", pName); + AddParameterWithName (command, "pAccountType", (int) pAccountType); + AddParameterWithName (command, "pParentFinancialAccountId", pParentFinancialAccountId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public BasicFinancialAccount GetFinancialAccount(int financialAccountId) + public BasicFinancialAccount GetFinancialAccount (int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialAccountFieldSequence + " WHERE FinancialAccountId=" + financialAccountId + ";", connection); @@ -56,10 +56,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadFinancialAccountFromDataReader(reader); + return ReadFinancialAccountFromDataReader (reader); } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } @@ -68,7 +68,7 @@ namespace Swarmops.Database // this structure, call them GetDatabaseObject and GetDatabaseCollection, and pass the query, // the reader delegate, and the expected type? - public BasicFinancialAccount[] GetFinancialAccountsForOrganization(int organizationId) + public BasicFinancialAccount[] GetFinancialAccountsForOrganization (int organizationId) { List result = new List(); @@ -77,7 +77,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialAccountFieldSequence + " WHERE OrganizationId=" + organizationId + " ORDER BY AccountType, Name;", connection); @@ -85,7 +85,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialAccountFromDataReader(reader)); + result.Add (ReadFinancialAccountFromDataReader (reader)); } return result.ToArray(); @@ -93,7 +93,7 @@ namespace Swarmops.Database } } - public BasicFinancialAccount[] GetFinancialAccountsOwnedByPerson(int ownerPersonId) + public BasicFinancialAccount[] GetFinancialAccountsOwnedByPerson (int ownerPersonId) { List result = new List(); @@ -102,7 +102,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialAccountFieldSequence + " WHERE OwnerPersonId=" + ownerPersonId + " ORDER BY Name;", connection); @@ -110,7 +110,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialAccountFromDataReader(reader)); + result.Add (ReadFinancialAccountFromDataReader (reader)); } return result.ToArray(); @@ -118,7 +118,7 @@ namespace Swarmops.Database } } - public BasicFinancialAccount[] GetFinancialAccounts(int[] financialAccountIds) + public BasicFinancialAccount[] GetFinancialAccounts (int[] financialAccountIds) { List result = new List(); @@ -127,15 +127,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialAccountFieldSequence + " WHERE FinancialAccountId IN (" + - JoinIds(financialAccountIds) + ") ORDER BY AccountType, Name;", connection); + JoinIds (financialAccountIds) + ") ORDER BY AccountType, Name;", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialAccountFromDataReader(reader)); + result.Add (ReadFinancialAccountFromDataReader (reader)); } return result.ToArray(); @@ -143,19 +143,19 @@ namespace Swarmops.Database } } - public BasicFinancialTransaction GetFinancialTransaction(int financialTransactionId) + public BasicFinancialTransaction GetFinancialTransaction (int financialTransactionId) { - BasicFinancialTransaction[] array = GetFinancialTransactions(new[] {financialTransactionId}); + BasicFinancialTransaction[] array = GetFinancialTransactions (new[] {financialTransactionId}); if (array.Length == 0) { - throw new ArgumentException("No such FinancialTransactionId"); + throw new ArgumentException ("No such FinancialTransactionId"); } return array[0]; } - public BasicFinancialTransaction[] GetFinancialTransactions(int[] financialTransactionIds) + public BasicFinancialTransaction[] GetFinancialTransactions (int[] financialTransactionIds) { List result = new List(); @@ -164,15 +164,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialTransactionId,OrganizationId,DateTime,Comment,ImportHash From FinancialTransactions WHERE FinancialTransactionId IN (" + - JoinIds(financialTransactionIds) + ");", connection); + JoinIds (financialTransactionIds) + ");", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionFromDataReader(reader)); + result.Add (ReadFinancialTransactionFromDataReader (reader)); } return result.ToArray(); @@ -180,38 +180,38 @@ namespace Swarmops.Database } } - public BasicFinancialTransaction GetFinancialTransactionFromImportKey(int organizationId, string importKey) + public BasicFinancialTransaction GetFinancialTransactionFromImportKey (int organizationId, string importKey) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialTransactionId,OrganizationId,DateTime,Comment,ImportHash From FinancialTransactions WHERE OrganizationId=" + - organizationId + " AND ImportHash='" + importKey.Replace("'", "''") + "';", connection); + organizationId + " AND ImportHash='" + importKey.Replace ("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadFinancialTransactionFromDataReader(reader); + return ReadFinancialTransactionFromDataReader (reader); } - throw new ArgumentException("No FinancialTransaction with supplied import key"); + throw new ArgumentException ("No FinancialTransaction with supplied import key"); } } } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use.")] - public double GetFinancialAccountBalanceTotal(int financialAccountId) + [Obsolete ("This method uses floating point for financials. Deprecated. Do not use.")] + public double GetFinancialAccountBalanceTotal (int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Sum(AmountCents) FROM FinancialTransactionRows WHERE FinancialAccountId=" + financialAccountId + ";", connection); @@ -219,22 +219,22 @@ namespace Swarmops.Database { if (reader.Read()) { - return reader.GetInt64(0)/100.0; + return reader.GetInt64 (0)/100.0; } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } - public Int64 GetFinancialAccountBalanceTotalCents(int financialAccountId) + public Int64 GetFinancialAccountBalanceTotalCents (int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Sum(AmountCents) FROM FinancialTransactionRows WHERE FinancialAccountId=" + financialAccountId + ";", connection); @@ -242,48 +242,48 @@ namespace Swarmops.Database { if (reader.Read()) { - return reader.GetInt64(0); + return reader.GetInt64 (0); } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } - public Int64 GetFinancialAccountBalanceDeltaCents(int financialAccountId, DateTime startDate, DateTime endDate) + public Int64 GetFinancialAccountBalanceDeltaCents (int financialAccountId, DateTime startDate, DateTime endDate) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select Sum(FinancialTransactionRows.AmountCents),Count(FinancialTransactions.FinancialTransactionId) from FinancialTransactionRows,FinancialTransactions Where FinancialTransactionRows.FinancialAccountId=" + financialAccountId + " AND FinancialTransactionRows.FinancialTransactionId=FinancialTransactions.FinancialTransactionId AND FinancialTransactionRows.Deleted=0 AND FinancialTransactions.DateTime >= '" + - startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND FinancialTransactions.DateTime < '" + - endDate.ToString("yyyy-MM-dd HH:mm:ss") + "';", connection); + startDate.ToString ("yyyy-MM-dd HH:mm:ss") + "' AND FinancialTransactions.DateTime < '" + + endDate.ToString ("yyyy-MM-dd HH:mm:ss") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - if (reader.IsDBNull(0)) + if (reader.IsDBNull (0)) { // No rows, so no delta return 0; } - return reader.GetInt64(0); + return reader.GetInt64 (0); } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } - public Int64 GetFinancialAccountBalanceDeltaCents(int[] financialAccountIds, DateTime startDate, + public Int64 GetFinancialAccountBalanceDeltaCents (int[] financialAccountIds, DateTime startDate, DateTime endDate) { using (DbConnection connection = GetMySqlDbConnection()) @@ -291,45 +291,45 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select Sum(FinancialTransactionRows.AmountCents),Count(FinancialTransactions.FinancialTransactionId) from FinancialTransactionRows,FinancialTransactions Where FinancialTransactionRows.FinancialAccountId IN (" + - JoinIds(financialAccountIds) + + JoinIds (financialAccountIds) + ") AND FinancialTransactionRows.FinancialTransactionId=FinancialTransactions.FinancialTransactionId AND FinancialTransactionRows.Deleted=0 AND FinancialTransactions.DateTime >= '" + - startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND FinancialTransactions.DateTime < '" + - endDate.ToString("yyyy-MM-dd HH:mm:ss") + "';", connection); + startDate.ToString ("yyyy-MM-dd HH:mm:ss") + "' AND FinancialTransactions.DateTime < '" + + endDate.ToString ("yyyy-MM-dd HH:mm:ss") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - if (reader.IsDBNull(0)) + if (reader.IsDBNull (0)) { // No rows, so no delta return 0; } - return reader.GetInt64(0); + return reader.GetInt64 (0); } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use.")] - public decimal GetFinancialAccountBalanceDelta(int financialAccountId, DateTime startDate, DateTime endDate) + [Obsolete ("This method uses floating point for financials. Deprecated. Do not use.")] + public decimal GetFinancialAccountBalanceDelta (int financialAccountId, DateTime startDate, DateTime endDate) { - return GetFinancialAccountBalanceDeltaCents(financialAccountId, startDate, endDate)/100.0m; + return GetFinancialAccountBalanceDeltaCents (financialAccountId, startDate, endDate)/100.0m; } - public BasicFinancialAccountRow[] GetFinancialAccountRows(int financialAccountId, DateTime startDateTime, + public BasicFinancialAccountRow[] GetFinancialAccountRows (int financialAccountId, DateTime startDateTime, DateTime endDateTime, bool selectFar) { - return GetFinancialAccountRows(new[] {financialAccountId}, startDateTime, endDateTime, selectFar); + return GetFinancialAccountRows (new[] {financialAccountId}, startDateTime, endDateTime, selectFar); } - public BasicFinancialAccountRow[] GetFinancialAccountRows(int[] financialAccountIds, DateTime startDateTime, + public BasicFinancialAccountRow[] GetFinancialAccountRows (int[] financialAccountIds, DateTime startDateTime, DateTime endDateTime, bool selectFar) { List result = new List(); @@ -350,11 +350,11 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select FinancialTransactionRows.FinancialAccountId,FinancialTransactionRows.FinancialTransactionId,FinancialTransactions.DateTime,FinancialTransactions.Comment,FinancialTransactionRows.AmountCents,FinancialTransactionRows.CreatedDateTime,FinancialTransactionRows.CreatedByPersonId FROM FinancialTransactions,FinancialTransactionRows WHERE FinancialTransactionRows.Deleted=0 AND FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId AND FinancialTransactionRows.FinancialAccountId IN (" + - JoinIds(financialAccountIds) + ") AND DateTime " + selectorLower + " '" + - startDateTime.ToString("yyyy-MM-dd HH:mm:ss") + - "' AND DateTime " + selectorUpper + " '" + endDateTime.ToString("yyyy-MM-dd HH:mm:ss") + + JoinIds (financialAccountIds) + ") AND DateTime " + selectorLower + " '" + + startDateTime.ToString ("yyyy-MM-dd HH:mm:ss") + + "' AND DateTime " + selectorUpper + " '" + endDateTime.ToString ("yyyy-MM-dd HH:mm:ss") + "' ORDER BY DateTime,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime;", connection); @@ -362,7 +362,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialAccountRowFromDataReader(reader)); + result.Add (ReadFinancialAccountRowFromDataReader (reader)); } return result.ToArray(); @@ -371,12 +371,12 @@ namespace Swarmops.Database } - public BasicFinancialAccountRow[] GetLastFinancialAccountRows(int financialAccountId, int rowCount) + public BasicFinancialAccountRow[] GetLastFinancialAccountRows (int financialAccountId, int rowCount) { - return GetLastFinancialAccountRows(new[] {financialAccountId}, rowCount); + return GetLastFinancialAccountRows (new[] {financialAccountId}, rowCount); } - public BasicFinancialAccountRow[] GetLastFinancialAccountRows(int[] financialAccountIds, int rowCount) + public BasicFinancialAccountRow[] GetLastFinancialAccountRows (int[] financialAccountIds, int rowCount) { List result = new List(); @@ -385,9 +385,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select FinancialTransactionRows.FinancialAccountId,FinancialTransactionRows.FinancialTransactionId,FinancialTransactions.DateTime,FinancialTransactions.Comment,FinancialTransactionRows.AmountCents,FinancialTransactionRows.CreatedDateTime,FinancialTransactionRows.CreatedByPersonId FROM FinancialTransactions,FinancialTransactionRows WHERE FinancialTransactionRows.Deleted=0 AND FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId AND FinancialTransactionRows.FinancialAccountId IN (" + - JoinIds(financialAccountIds) + + JoinIds (financialAccountIds) + ") ORDER BY DateTime DESC,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime LIMIT " + rowCount + ";", connection); @@ -396,7 +396,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialAccountRowFromDataReader(reader)); + result.Add (ReadFinancialAccountRowFromDataReader (reader)); } return result.ToArray(); @@ -405,7 +405,7 @@ namespace Swarmops.Database } - public BasicFinancialTransactionRow[] GetFinancialTransactionRows(int financialTransactionId) + public BasicFinancialTransactionRow[] GetFinancialTransactionRows (int financialTransactionId) { List result = new List(); @@ -414,7 +414,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select FinancialTransactionRowId, FinancialAccountId," + financialTransactionId + " AS FinancialTransactionId,AmountCents,CreatedDateTime,CreatedByPersonId FROM FinancialTransactionRows WHERE FinancialTransactionId=" + financialTransactionId, connection); @@ -423,7 +423,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialTransactionRowFromDataReader(reader)); + result.Add (ReadFinancialTransactionRowFromDataReader (reader)); } return result.ToArray(); @@ -431,14 +431,14 @@ namespace Swarmops.Database } } - public BasicFinancialTransactionRow GetFinancialTransactionRow(int financialTransactionRowId) + public BasicFinancialTransactionRow GetFinancialTransactionRow (int financialTransactionRowId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select FinancialTransactionRowId,FinancialAccountId,FinancialTransactionId,AmountCents,CreatedDateTime,CreatedByPersonId FROM FinancialTransactionRows WHERE FinancialTransactionRowId=" + financialTransactionRowId, connection); @@ -446,16 +446,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadFinancialTransactionRowFromDataReader(reader); + return ReadFinancialTransactionRowFromDataReader (reader); } - throw new ArgumentException("Invalid FinancialTransactionRowId"); + throw new ArgumentException ("Invalid FinancialTransactionRowId"); } } } - public BasicFinancialTransaction[] GetUnbalancedFinancialTransactions(int organizationId) + public BasicFinancialTransaction[] GetUnbalancedFinancialTransactions (int organizationId) { List result = new List(); @@ -474,13 +474,13 @@ namespace Swarmops.Database "GROUP BY FinancialTransactions.FinancialTransactionId HAVING Delta <> 0 " + "ORDER BY FinancialTransactions.DateTime;"; - DbCommand command = GetDbCommand(commandString, connection); + DbCommand command = GetDbCommand (commandString, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionFromDataReader(reader)); + result.Add (ReadFinancialTransactionFromDataReader (reader)); } return result.ToArray(); @@ -489,7 +489,7 @@ namespace Swarmops.Database } - public BasicFinancialTransaction GetFinancialTransactionFromDependency(IHasIdentity foreignObject) + public BasicFinancialTransaction GetFinancialTransactionFromDependency (IHasIdentity foreignObject) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -497,24 +497,24 @@ namespace Swarmops.Database string commandString = "SELECT FinancialTransactionId FROM FinancialTransactionDependencies " + "JOIN FinancialDependencyTypes ON (FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId) " + - "WHERE FinancialDependencyTypes.Name='" + GetForeignTypeString(foreignObject) + + "WHERE FinancialDependencyTypes.Name='" + GetForeignTypeString (foreignObject) + "' AND FinancialTransactionDependencies.ForeignId=" + foreignObject.Identity + ";"; - DbCommand command = GetDbCommand(commandString, connection); + DbCommand command = GetDbCommand (commandString, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return GetFinancialTransaction(reader.GetInt32(0)); - // Warning: opens another datareader before closing both + return GetFinancialTransaction (reader.GetInt32 (0)); + // Warning: opens another datareader before closing both } - throw new ArgumentException( - String.Format("No financial transaction for specified dependency: {0} #{1}", - GetForeignTypeString(foreignObject), foreignObject.Identity)); + throw new ArgumentException ( + String.Format ("No financial transaction for specified dependency: {0} #{1}", + GetForeignTypeString (foreignObject), foreignObject.Identity)); } } } @@ -525,7 +525,7 @@ namespace Swarmops.Database /// /// The organization owning the transactions /// A list of all such transactions - public BasicFinancialTransaction[] GetUndocumentedFinancialTransactions(int organizationId) + public BasicFinancialTransaction[] GetUndocumentedFinancialTransactions (int organizationId) { List result = new List(); @@ -545,13 +545,13 @@ namespace Swarmops.Database "AND NOT EXISTS (SELECT DocumentId FROM Documents JOIN DocumentTypes ON (DocumentTypes.DocumentTypeId=Documents.DocumentTypeId) WHERE Documents.ForeignId=FinancialTransactions.FinancialTransactionId AND DocumentTypes.Name='FinancialTransaction') " + "AND NOT EXISTS (SELECT FinancialTransactionId FROM FinancialTransactionDependencies WHERE FinancialTransactionDependencies.FinancialTransactionId=FinancialTransactions.FinancialTransactionId) " + "GROUP BY FinancialTransactionId HAVING BalanceDelta < 0;"; - DbCommand command = GetDbCommand(commandString, connection); + DbCommand command = GetDbCommand (commandString, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialTransactionFromDataReader(reader)); + result.Add (ReadFinancialTransactionFromDataReader (reader)); } return result.ToArray(); @@ -560,22 +560,22 @@ namespace Swarmops.Database } - public double GetFinancialAccountsBudget(int[] financialAccountIds, int year) + public double GetFinancialAccountsBudget (int[] financialAccountIds, int year) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select SUM(Amount) from FinancialAccountBudgets where Year=" + year + - " AND FinancialAccountId IN (" + JoinIds(financialAccountIds) + ");", connection); + " AND FinancialAccountId IN (" + JoinIds (financialAccountIds) + ");", connection); using (DbDataReader reader = command.ExecuteReader()) { - if (reader.Read() && !reader.IsDBNull(0)) + if (reader.Read() && !reader.IsDBNull (0)) { - return reader.GetDouble(0); + return reader.GetDouble (0); } return 0.0; @@ -583,14 +583,14 @@ namespace Swarmops.Database } } - public double GetFinancialAccountBudget(int financialAccountId, int year) + public double GetFinancialAccountBudget (int financialAccountId, int year) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select Amount from FinancialAccountBudgets where Year=" + year + " AND FinancialAccountId=" + financialAccountId + ";", connection); @@ -598,7 +598,7 @@ namespace Swarmops.Database { if (reader.Read()) { - return reader.GetDouble(0); + return reader.GetDouble (0); } return 0.0; @@ -606,7 +606,7 @@ namespace Swarmops.Database } } - public Int64[] GetFinancialAccountBudgetMonthly(int financialAccountId, int year) + public Int64[] GetFinancialAccountBudgetMonthly (int financialAccountId, int year) { List result = new List(); @@ -615,7 +615,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select AmountCents from FinancialAccountBudgetsMonthly where Year=" + year + " AND FinancialAccountId=" + financialAccountId + " ORDER BY Month;", connection); @@ -623,7 +623,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt64(0)); + result.Add (reader.GetInt64 (0)); } return result.ToArray(); @@ -631,444 +631,445 @@ namespace Swarmops.Database } } - public void SetFinancialAccountBudget(int financialAccountId, int year, double amount) + public void SetFinancialAccountBudget (int financialAccountId, int year, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountBudget", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountBudget", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "year", year); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "year", year); + AddParameterWithName (command, "amount", amount); command.ExecuteNonQuery(); } } - public void SetFinancialAccountBudgetMonthly(int financialAccountId, int year, int month, Int64 amountCents) + public void SetFinancialAccountBudgetMonthly (int financialAccountId, int year, int month, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountBudgetMonthly", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountBudgetMonthly", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "year", year); - AddParameterWithName(command, "month", month); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "year", year); + AddParameterWithName (command, "month", month); + AddParameterWithName (command, "amountCents", amountCents); command.ExecuteNonQuery(); } } - public void SetFinancialAccountOpenedYear(int financialAccountId, int openedYear) + public void SetFinancialAccountOpenedYear (int financialAccountId, int openedYear) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountOpenedYear", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountOpenedYear", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "openedYear", openedYear); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "openedYear", openedYear); command.ExecuteNonQuery(); } } - public void SetFinancialAccountClosedYear(int financialAccountId, int closedYear) + public void SetFinancialAccountClosedYear (int financialAccountId, int closedYear) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountClosedYear", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountClosedYear", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "closedYear", closedYear); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "closedYear", closedYear); command.ExecuteNonQuery(); } } - public void SetFinancialAccountParent(int financialAccountId, int parentFinancialAccountId) + public void SetFinancialAccountParent (int financialAccountId, int parentFinancialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountParent", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountParent", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "parentFinancialAccountId", parentFinancialAccountId); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "parentFinancialAccountId", parentFinancialAccountId); command.ExecuteNonQuery(); } } - public void SetFinancialAccountActive(int financialAccountId, bool active) + public void SetFinancialAccountActive (int financialAccountId, bool active) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountActive", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountActive", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "active", active); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "active", active); command.ExecuteNonQuery(); } } - public void SetFinancialAccountExpensable(int financialAccountId, bool expensable) + public void SetFinancialAccountExpensable (int financialAccountId, bool expensable) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountExpensable", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountExpensable", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "expensable", expensable); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "expensable", expensable); command.ExecuteNonQuery(); } } - public void SetFinancialAccountOpen(int financialAccountId, bool open) + public void SetFinancialAccountOpen (int financialAccountId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountOpen", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetFinancialAccountAdministrative(int financialAccountId, bool administrative) + public void SetFinancialAccountAdministrative (int financialAccountId, bool administrative) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountAdministrative", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountAdministrative", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "administrative", administrative); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "administrative", administrative); command.ExecuteNonQuery(); } } - public void SetFinancialAccountLinkBackward(int financialAccountId, int linkBackward) + public void SetFinancialAccountLinkBackward (int financialAccountId, int linkBackward) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountOwner", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountOwner", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "linkBackward", linkBackward); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "linkBackward", linkBackward); command.ExecuteNonQuery(); } } - public void SetFinancialAccountLinkForward(int financialAccountId, int linkForward) + public void SetFinancialAccountLinkForward (int financialAccountId, int linkForward) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountOwner", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountOwner", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "linkForward", linkForward); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "linkForward", linkForward); command.ExecuteNonQuery(); } } - public void SetFinancialAccountOwner(int financialAccountId, int ownerPersonId) + public void SetFinancialAccountOwner (int financialAccountId, int ownerPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountOwner", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountOwner", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "ownerPersonId", ownerPersonId); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "ownerPersonId", ownerPersonId); command.ExecuteNonQuery(); } } - public void SetFinancialAccountName(int financialAccountId, string name) + public void SetFinancialAccountName (int financialAccountId, string name) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialAccountName", connection); + DbCommand command = GetDbCommand ("SetFinancialAccountName", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "name", name); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "name", name); command.ExecuteNonQuery(); } } - private BasicFinancialTransactionRow ReadFinancialTransactionRowFromDataReader(DbDataReader reader) + private BasicFinancialTransactionRow ReadFinancialTransactionRowFromDataReader (DbDataReader reader) { - int rowId = reader.GetInt32(0); - int accountId = reader.GetInt32(1); - int transactionId = reader.GetInt32(2); - Int64 amountCents = reader.GetInt64(3); - DateTime createdDateTime = reader.GetDateTime(4); - int createdByPersonId = reader.GetInt32(5); + int rowId = reader.GetInt32 (0); + int accountId = reader.GetInt32 (1); + int transactionId = reader.GetInt32 (2); + Int64 amountCents = reader.GetInt64 (3); + DateTime createdDateTime = reader.GetDateTime (4); + int createdByPersonId = reader.GetInt32 (5); - return new BasicFinancialTransactionRow(rowId, accountId, transactionId, amountCents, createdDateTime, + return new BasicFinancialTransactionRow (rowId, accountId, transactionId, amountCents, createdDateTime, createdByPersonId); } - private BasicFinancialAccount ReadFinancialAccountFromDataReader(DbDataReader reader) + private BasicFinancialAccount ReadFinancialAccountFromDataReader (DbDataReader reader) { - int accountId = reader.GetInt32(0); - string name = reader.GetString(1); - int organizationId = reader.GetInt32(2); - FinancialAccountType accountType = (FinancialAccountType) reader.GetInt32(3); - int parentFinancialAccountId = reader.GetInt32(4); - int ownerPersonId = reader.GetInt32(5); - bool open = reader.GetBoolean(6); - int openedYear = reader.GetInt32(7); - int closedYear = reader.GetInt32(8); - bool expensable = reader.GetBoolean(9); - bool administrative = reader.GetBoolean(10); - bool active = reader.GetBoolean(11); - int linkBackward = reader.GetInt32(12); - int linkForward = reader.GetInt32(13); + int accountId = reader.GetInt32 (0); + string name = reader.GetString (1); + int organizationId = reader.GetInt32 (2); + FinancialAccountType accountType = (FinancialAccountType) reader.GetInt32 (3); + int parentFinancialAccountId = reader.GetInt32 (4); + int ownerPersonId = reader.GetInt32 (5); + bool open = reader.GetBoolean (6); + int openedYear = reader.GetInt32 (7); + int closedYear = reader.GetInt32 (8); + bool expensable = reader.GetBoolean (9); + bool administrative = reader.GetBoolean (10); + bool active = reader.GetBoolean (11); + int linkBackward = reader.GetInt32 (12); + int linkForward = reader.GetInt32 (13); - return new BasicFinancialAccount(accountId, name, accountType, organizationId, parentFinancialAccountId, + return new BasicFinancialAccount (accountId, name, accountType, organizationId, parentFinancialAccountId, ownerPersonId, open, openedYear, closedYear, active, expensable, administrative, linkBackward, linkForward); } - private BasicFinancialAccountRow ReadFinancialAccountRowFromDataReader(DbDataReader reader) + private BasicFinancialAccountRow ReadFinancialAccountRowFromDataReader (DbDataReader reader) { - int accountId = reader.GetInt32(0); - int transactionId = reader.GetInt32(1); - DateTime transactionDateTime = reader.GetDateTime(2); - string comment = reader.GetString(3); - Int64 amountCents = reader.GetInt64(4); - DateTime rowDateTime = reader.GetDateTime(5); - int rowCreatedByPersonId = reader.GetInt32(6); + int accountId = reader.GetInt32 (0); + int transactionId = reader.GetInt32 (1); + DateTime transactionDateTime = reader.GetDateTime (2); + string comment = reader.GetString (3); + Int64 amountCents = reader.GetInt64 (4); + DateTime rowDateTime = reader.GetDateTime (5); + int rowCreatedByPersonId = reader.GetInt32 (6); - return new BasicFinancialAccountRow(accountId, transactionId, transactionDateTime, comment, amountCents, + return new BasicFinancialAccountRow (accountId, transactionId, transactionDateTime, comment, amountCents, rowDateTime, rowCreatedByPersonId); } - private BasicFinancialTransaction ReadFinancialTransactionFromDataReader(DbDataReader reader) + private BasicFinancialTransaction ReadFinancialTransactionFromDataReader (DbDataReader reader) { - int transactionId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - DateTime dateTime = reader.GetDateTime(2); - string comment = reader.GetString(3); - string importHash = reader.GetString(4); + int transactionId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + DateTime dateTime = reader.GetDateTime (2); + string comment = reader.GetString (3); + string importHash = reader.GetString (4); - return new BasicFinancialTransaction(transactionId, organizationId, dateTime, comment, importHash); + return new BasicFinancialTransaction (transactionId, organizationId, dateTime, comment, importHash); } - public int CreateFinancialTransaction(int organizationId, DateTime dateTime, string comment) + public int CreateFinancialTransaction (int organizationId, DateTime dateTime, string comment) { if (comment.Length > 127) { - comment = comment.Substring(127); // Dbfield is VARCHAR(128) + comment = comment.Substring (127); // Dbfield is VARCHAR(128) } using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialTransaction", connection); + DbCommand command = GetDbCommand ("CreateFinancialTransaction", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "dateTime", dateTime); - AddParameterWithName(command, "comment", comment); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "dateTime", dateTime); + AddParameterWithName (command, "comment", comment); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateFinancialTransactionStub(int organizationId, DateTime dateTime, int financialAccountId, + public int CreateFinancialTransactionStub (int organizationId, DateTime dateTime, int financialAccountId, Int64 amountCents, string comment, string importHash, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialTransactionStub", connection); + DbCommand command = GetDbCommand ("CreateFinancialTransactionStub", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "dateTime", dateTime); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "comment", comment); - AddParameterWithName(command, "importHash", importHash); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "dateTime", dateTime); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "comment", comment); + AddParameterWithName (command, "importHash", importHash); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "personId", personId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void CreateFinancialTransactionRow(int financialTransactionId, int financialAccountId, double amount, + public void CreateFinancialTransactionRow (int financialTransactionId, int financialAccountId, double amount, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialTransactionRow", connection); + DbCommand command = GetDbCommand ("CreateFinancialTransactionRow", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "amount", amount); - AddParameterWithName(command, "dateTime", DateTime.Now); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "amount", amount); + AddParameterWithName (command, "dateTime", DateTime.Now); + AddParameterWithName (command, "personId", personId); command.ExecuteNonQuery(); } } - public void CreateFinancialTransactionRow(int financialTransactionId, int financialAccountId, Int64 amountCents, + public void CreateFinancialTransactionRow (int financialTransactionId, int financialAccountId, Int64 amountCents, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialTransactionRowPrecise", connection); + DbCommand command = GetDbCommand ("CreateFinancialTransactionRowPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); - AddParameterWithName(command, "financialAccountId", financialAccountId); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "dateTime", DateTime.Now); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "dateTime", DateTime.Now); + AddParameterWithName (command, "personId", personId); command.ExecuteNonQuery(); } } - public void SetFinancialTransactionDescription(int financialTransactionId, string description) + public void SetFinancialTransactionDescription (int financialTransactionId, string description) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialTransactionDescription", connection); + DbCommand command = GetDbCommand ("SetFinancialTransactionDescription", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); - AddParameterWithName(command, "description", description); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "description", description); command.ExecuteNonQuery(); } } - public void SetFinancialTransactionDependency(int financialTransactionId, FinancialDependencyType dependencyType, + public void SetFinancialTransactionDependency (int financialTransactionId, + FinancialDependencyType dependencyType, int foreignId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetFinancialTransactionDependency", connection); + DbCommand command = GetDbCommand ("SetFinancialTransactionDependency", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); - AddParameterWithName(command, "financialDependencyType", dependencyType.ToString()); - AddParameterWithName(command, "foreignId", foreignId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialDependencyType", dependencyType.ToString()); + AddParameterWithName (command, "foreignId", foreignId); command.ExecuteNonQuery(); } } - public void ClearFinancialTransactionDependency(int financialTransactionId) + public void ClearFinancialTransactionDependency (int financialTransactionId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClearFinancialTransactionDependency", connection); + DbCommand command = GetDbCommand ("ClearFinancialTransactionDependency", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "financialTransactionId", financialTransactionId); + AddParameterWithName (command, "financialTransactionId", financialTransactionId); command.ExecuteNonQuery(); } } - public DateTime GetFinancialAccountFirstTransactionDate(int financialAccountId) + public DateTime GetFinancialAccountFirstTransactionDate (int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialTransactions.DateTime FROM FinancialTransactions,FinancialTransactionRows " + "WHERE FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId " + "AND FinancialTransactionRows.FinancialAccountId = " + - financialAccountId.ToString(CultureInfo.InvariantCulture) + " " + + financialAccountId.ToString (CultureInfo.InvariantCulture) + " " + "ORDER BY FinancialTransactions.DateTime LIMIT 1;", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetDateTime(0); + return reader.GetDateTime (0); } - throw new Exception("No transactions for this account yet"); - // need better type here than "Exception" + throw new Exception ("No transactions for this account yet"); + // need better type here than "Exception" ; } } } - public BasicFinancialTransaction[] GetDependentFinancialTransactions(FinancialDependencyType dependencyType, + public BasicFinancialTransaction[] GetDependentFinancialTransactions (FinancialDependencyType dependencyType, int foreignId) { List transactionIds = new List(); @@ -1078,7 +1079,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialTransactionId FROM FinancialTransactionDependencies,FinancialDependencyTypes " + "WHERE FinancialDependencyTypes.Name='" + dependencyType + "' AND " + "FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId AND " + @@ -1088,7 +1089,7 @@ namespace Swarmops.Database { while (reader.Read()) { - transactionIds.Add(reader.GetInt32(0)); + transactionIds.Add (reader.GetInt32 (0)); } } } @@ -1098,7 +1099,7 @@ namespace Swarmops.Database return new BasicFinancialTransaction[0]; } - return GetFinancialTransactions(transactionIds.ToArray()); + return GetFinancialTransactions (transactionIds.ToArray()); } @@ -1106,7 +1107,7 @@ namespace Swarmops.Database // Fix this by introducing the BasicFinancialDependency type in the semi-near future, and // using it as a return type. - public void GetFinancialTransactionDependency(int financialTransactionId, + public void GetFinancialTransactionDependency (int financialTransactionId, out FinancialDependencyType dependencyType, out int foreignId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -1114,7 +1115,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT FinancialDependencyTypes.Name,FinancialTransactionDependencies.ForeignId " + "FROM FinancialTransactionDependencies,FinancialDependencyTypes " + "WHERE FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId " + @@ -1128,8 +1129,9 @@ namespace Swarmops.Database // Set OUT parameters dependencyType = - (FinancialDependencyType) Enum.Parse(typeof (FinancialDependencyType), reader.GetString(0)); - foreignId = reader.GetInt32(1); + (FinancialDependencyType) + Enum.Parse (typeof (FinancialDependencyType), reader.GetString (0)); + foreignId = reader.GetInt32 (1); } else { @@ -1145,7 +1147,7 @@ namespace Swarmops.Database // TODO: Return BasicFinancialValidation object - public void CreateFinancialValidation(FinancialValidationType validationType, + public void CreateFinancialValidation (FinancialValidationType validationType, FinancialDependencyType dependencyType, int foreignId, DateTime validatedDateTime, int personId, double amount) { @@ -1153,15 +1155,15 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateFinancialValidation", connection); + DbCommand command = GetDbCommand ("CreateFinancialValidation", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "validationType", validationType.ToString()); - AddParameterWithName(command, "dependencyType", dependencyType.ToString()); - AddParameterWithName(command, "foreignId", foreignId); - AddParameterWithName(command, "validatedDateTime", validatedDateTime); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "validationType", validationType.ToString()); + AddParameterWithName (command, "dependencyType", dependencyType.ToString()); + AddParameterWithName (command, "foreignId", foreignId); + AddParameterWithName (command, "validatedDateTime", validatedDateTime); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "amount", amount); command.ExecuteNonQuery(); } @@ -1171,7 +1173,7 @@ namespace Swarmops.Database // -- lines and trees and children -- - public BasicFinancialAccount[] GetFinancialAccountChildren(int parentFinancialAccountId) + public BasicFinancialAccount[] GetFinancialAccountChildren (int parentFinancialAccountId) { List result = new List(); @@ -1180,7 +1182,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + financialAccountFieldSequence + " WHERE ParentFinancialAccountId = " + parentFinancialAccountId + " ORDER BY \"Name\"", connection); @@ -1189,7 +1191,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadFinancialAccountFromDataReader(reader)); + result.Add (ReadFinancialAccountFromDataReader (reader)); } return result.ToArray(); @@ -1198,7 +1200,7 @@ namespace Swarmops.Database } - public Dictionary> GetHashedFinancialAccounts(int organizationId) + public Dictionary> GetHashedFinancialAccounts (int organizationId) { // This generates a Dictionary >. // @@ -1210,7 +1212,7 @@ namespace Swarmops.Database Dictionary> result = new Dictionary>(); - BasicFinancialAccount[] nodes = GetFinancialAccountsForOrganization(organizationId); + BasicFinancialAccount[] nodes = GetFinancialAccountsForOrganization (organizationId); // Add the root. @@ -1221,7 +1223,7 @@ namespace Swarmops.Database foreach (BasicFinancialAccount node in nodes) { List newList = new List(); - newList.Add(node); + newList.Add (node); result[node.FinancialAccountId] = newList; } @@ -1230,20 +1232,20 @@ namespace Swarmops.Database foreach (BasicFinancialAccount node in nodes) { - result[node.ParentFinancialAccountId].Add(node); + result[node.ParentFinancialAccountId].Add (node); } return result; } - public BasicFinancialAccount[] GetFinancialAccountLine(int leafFinancialAccountId) + public BasicFinancialAccount[] GetFinancialAccountLine (int leafFinancialAccountId) { - int orgId = GetFinancialAccount(leafFinancialAccountId).OrganizationId; + int orgId = GetFinancialAccount (leafFinancialAccountId).OrganizationId; List result = new List(); - Dictionary> nodes = GetHashedFinancialAccounts(orgId); + Dictionary> nodes = GetHashedFinancialAccounts (orgId); BasicFinancialAccount currentNode = nodes[leafFinancialAccountId][0]; @@ -1251,7 +1253,7 @@ namespace Swarmops.Database while (currentNode != null && currentNode.ParentFinancialAccountId != 0) { - result.Add(currentNode); + result.Add (currentNode); if (currentNode.ParentFinancialAccountId != 0) { @@ -1269,11 +1271,11 @@ namespace Swarmops.Database } - public BasicFinancialAccount[] GetFinancialAccountTreeForOrganization(int organizationId) + public BasicFinancialAccount[] GetFinancialAccountTreeForOrganization (int organizationId) { - Dictionary> nodes = GetHashedFinancialAccounts(organizationId); + Dictionary> nodes = GetHashedFinancialAccounts (organizationId); - return GetFinancialAccountTree(nodes, 0, 0); + return GetFinancialAccountTree (nodes, 0, 0); } /* @@ -1292,7 +1294,7 @@ namespace Swarmops.Database }*/ - private BasicFinancialAccount[] GetFinancialAccountTree( + private BasicFinancialAccount[] GetFinancialAccountTree ( Dictionary> financialAccounts, int startNodeId, int generation) { @@ -1304,18 +1306,18 @@ namespace Swarmops.Database { if (node.FinancialAccountId != startNodeId) { - result.Add(new BasicFinancialAccount(node)); + result.Add (new BasicFinancialAccount (node)); // Add recursively - BasicFinancialAccount[] children = GetFinancialAccountTree(financialAccounts, + BasicFinancialAccount[] children = GetFinancialAccountTree (financialAccounts, node.FinancialAccountId, generation + 1); if (children.Length > 0) { foreach (BasicFinancialAccount child in children) { - result.Add(child); + result.Add (child); } } } @@ -1323,7 +1325,7 @@ namespace Swarmops.Database { // The top parent is special and should be added (unless null); the others shouldn't - result.Add(new BasicFinancialAccount(node)); + result.Add (new BasicFinancialAccount (node)); } } diff --git a/Database/Database-FlatData.cs b/Database/Database-FlatData.cs index 1e9b2d83..b50606b8 100644 --- a/Database/Database-FlatData.cs +++ b/Database/Database-FlatData.cs @@ -6,21 +6,21 @@ namespace Swarmops.Database { public partial class SwarmDb { - public string GetKeyValue(string key) + public string GetKeyValue (string key) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT DataValue FROM FlatData WHERE DataKey='" + key.Replace("'", "''") + "'", + GetDbCommand ("SELECT DataValue FROM FlatData WHERE DataKey='" + key.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetString(0); + return reader.GetString (0); } return string.Empty; @@ -29,17 +29,17 @@ namespace Swarmops.Database } - public void SetKeyValue(string key, string value) + public void SetKeyValue (string key, string value) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetKeyValue", connection); + DbCommand command = GetDbCommand ("SetKeyValue", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "dataKey", key); - AddParameterWithName(command, "dataValue", value); + AddParameterWithName (command, "dataKey", key); + AddParameterWithName (command, "dataValue", value); command.ExecuteNonQuery(); } diff --git a/Database/Database-Geographies.cs b/Database/Database-Geographies.cs index 179a7c4a..18055d56 100644 --- a/Database/Database-Geographies.cs +++ b/Database/Database-Geographies.cs @@ -20,23 +20,23 @@ namespace Swarmops.Database " GeographyId, CountryId, Designation, GeographyLevelId " + // 0-3 " FROM GeographyDesignations "; - private static BasicGeography ReadGeographyFromDataReader(DbDataReader reader) + private static BasicGeography ReadGeographyFromDataReader (DbDataReader reader) { - int geographyId = reader.GetInt32(0); - int parentGeographyId = reader.GetInt32(1); - string name = reader.GetString(2); + int geographyId = reader.GetInt32 (0); + int parentGeographyId = reader.GetInt32 (1); + string name = reader.GetString (2); - return new BasicGeography(geographyId, parentGeographyId, name); + return new BasicGeography (geographyId, parentGeographyId, name); } - private static BasicGeographyDesignation ReadGeographyDesignationFromDataReader(DbDataReader reader) + private static BasicGeographyDesignation ReadGeographyDesignationFromDataReader (DbDataReader reader) { - int geographyId = reader.GetInt32(0); - int countryId = reader.GetInt32(1); - string designation = reader.GetString(2); - GeographyLevel level = (GeographyLevel) reader.GetInt32(3); + int geographyId = reader.GetInt32 (0); + int countryId = reader.GetInt32 (1); + string designation = reader.GetString (2); + GeographyLevel level = (GeographyLevel) reader.GetInt32 (3); - return new BasicGeographyDesignation(geographyId, countryId, designation, level); + return new BasicGeographyDesignation (geographyId, countryId, designation, level); } #endregion @@ -50,7 +50,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 ORDER BY \"Name\"", connection); @@ -58,7 +58,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadGeographyFromDataReader(reader)); + result.Add (ReadGeographyFromDataReader (reader)); } return result.ToArray(); @@ -67,7 +67,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographies(int[] ids) + public BasicGeography[] GetGeographies (int[] ids) { List result = new List(); @@ -76,16 +76,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 AND GeographyId in (" + - JoinIds(ids) + + JoinIds (ids) + ") ORDER BY \"Name\"", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadGeographyFromDataReader(reader)); + result.Add (ReadGeographyFromDataReader (reader)); } return result.ToArray(); @@ -94,7 +94,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographyChildren(int parentGeographyId) + public BasicGeography[] GetGeographyChildren (int parentGeographyId) { List result = new List(); @@ -103,7 +103,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId=" + parentGeographyId + " ORDER BY \"Name\"", connection); @@ -111,7 +111,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadGeographyFromDataReader(reader)); + result.Add (ReadGeographyFromDataReader (reader)); } return result.ToArray(); @@ -139,7 +139,7 @@ namespace Swarmops.Database foreach (BasicGeography node in nodes) { List newList = new List(); - newList.Add(node); + newList.Add (node); result[node.GeographyId] = newList; } @@ -150,7 +150,7 @@ namespace Swarmops.Database { if (node.ParentGeographyId != 0) { - result[node.ParentGeographyId].Add(node); + result[node.ParentGeographyId].Add (node); } } @@ -158,7 +158,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographyLine(int leafGeographyId) + public BasicGeography[] GetGeographyLine (int leafGeographyId) { List result = new List(); @@ -170,7 +170,7 @@ namespace Swarmops.Database while (currentNode.GeographyId != 0) { - result.Add(currentNode); + result.Add (currentNode); if (currentNode.ParentGeographyId != 0) { @@ -178,7 +178,7 @@ namespace Swarmops.Database } else { - currentNode = new BasicGeography(0, 0, string.Empty); + currentNode = new BasicGeography (0, 0, string.Empty); } } @@ -190,21 +190,21 @@ namespace Swarmops.Database public BasicGeography[] GetGeographyTree() { - return GetGeographyTree(1); + return GetGeographyTree (1); } - public BasicGeography[] GetGeographyTree(int startGeographyId) + public BasicGeography[] GetGeographyTree (int startGeographyId) { Dictionary> nodes = GetHashedGeographies(); - return GetGeographyTree(nodes, startGeographyId, 0); + return GetGeographyTree (nodes, startGeographyId, 0); } - public Dictionary GetGeographyHashtable(int startGeographyId) + public Dictionary GetGeographyHashtable (int startGeographyId) { - BasicGeography[] nodes = GetGeographyTree(startGeographyId); + BasicGeography[] nodes = GetGeographyTree (startGeographyId); Dictionary result = new Dictionary(); @@ -217,7 +217,7 @@ namespace Swarmops.Database } - private BasicGeography[] GetGeographyTree(Dictionary> geographies, int startNodeId, + private BasicGeography[] GetGeographyTree (Dictionary> geographies, int startNodeId, int generation) { List result = new List(); @@ -228,17 +228,17 @@ namespace Swarmops.Database { if (node.GeographyId != startNodeId) { - result.Add(new BasicGeography(node.GeographyId, node.ParentGeographyId, node.Name, generation + 1)); + result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation + 1)); // Add recursively - BasicGeography[] children = GetGeographyTree(geographies, node.GeographyId, generation + 1); + BasicGeography[] children = GetGeographyTree (geographies, node.GeographyId, generation + 1); if (children.Length > 0) { foreach (BasicGeography child in children) { - result.Add(child); + result.Add (child); } } } @@ -246,7 +246,7 @@ namespace Swarmops.Database { // The top parent is special and should be added; the others shouldn't - result.Add(new BasicGeography(node.GeographyId, node.ParentGeographyId, node.Name, generation)); + result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation)); } } @@ -254,37 +254,37 @@ namespace Swarmops.Database } - public BasicGeography GetGeography(int geographyId) + public BasicGeography GetGeography (int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "SELECT " + geographyFieldSequence + " WHERE GeographyId=" + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadGeographyFromDataReader(reader); + return ReadGeographyFromDataReader (reader); } - throw new ArgumentException("No such GeographyId: " + geographyId); + throw new ArgumentException ("No such GeographyId: " + geographyId); } } } - public BasicGeography GetGeographyByName(string geographyName) + public BasicGeography GetGeographyByName (string geographyName) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + geographyFieldSequence + " WHERE Name like '" + geographyName.Replace("'", "''") + + GetDbCommand ( + "SELECT " + geographyFieldSequence + " WHERE Name like '" + geographyName.Replace ("'", "''") + "%'", connection); @@ -292,18 +292,18 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadGeographyFromDataReader(reader); + return ReadGeographyFromDataReader (reader); } - throw new ArgumentException("No such Geography: " + geographyName); + throw new ArgumentException ("No such Geography: " + geographyName); } } } - public void SetGeographyName(int geographyId, string name) + public void SetGeographyName (int geographyId, string name) { - throw new NotImplementedException("Renaming geographies is not migrated to MySQL"); + throw new NotImplementedException ("Renaming geographies is not migrated to MySQL"); /* using (DbConnection connection = GetMySqlDbConnection()) { @@ -321,7 +321,7 @@ namespace Swarmops.Database public Dictionary GetGeographyVoterCounts() { - throw new NotImplementedException("Not Migrated to MySQL"); + throw new NotImplementedException ("Not Migrated to MySQL"); /* Dictionary result = new Dictionary(); @@ -346,10 +346,10 @@ namespace Swarmops.Database }*/ } - public void CreateGeographyOfficialDesignation(int geographyId, GeographyLevel level, int countryId, + public void CreateGeographyOfficialDesignation (int geographyId, GeographyLevel level, int countryId, string designation) { - throw new NotImplementedException("Not Migrated to MySQL"); + throw new NotImplementedException ("Not Migrated to MySQL"); /* using (DbConnection connection = GetMySqlDbConnection()) { @@ -367,30 +367,30 @@ namespace Swarmops.Database }*/ } - public int GetGeographyIdFromOfficialDesignation(int countryId, GeographyLevel level, string designation) + public int GetGeographyIdFromOfficialDesignation (int countryId, GeographyLevel level, string designation) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select GeographyId FROM GeographyDesignations WHERE CountryId=" + countryId + " AND GeographyLevelId= " + ((int) level) + " AND Designation='" + - designation.Replace("'", "''") + "'", connection); + designation.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } - throw new ArgumentException("No such designation: " + designation); + throw new ArgumentException ("No such designation: " + designation); } } } - public GeographyLevel[] GetGeographyLevelsAtGeographyId(int geographyId) + public GeographyLevel[] GetGeographyLevelsAtGeographyId (int geographyId) { List result = new List(); @@ -399,7 +399,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select GeographyLevelId FROM GeographyDesignations WHERE GeographyId=" + geographyId, connection); @@ -407,7 +407,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add((GeographyLevel) reader.GetInt32(0)); + result.Add ((GeographyLevel) reader.GetInt32 (0)); } } } @@ -415,7 +415,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicGeographyDesignation[] GetGeographyDesignationsForGeographyId(int geographyId) + public BasicGeographyDesignation[] GetGeographyDesignationsForGeographyId (int geographyId) { List result = new List(); @@ -424,14 +424,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + geographyDesignationFieldSequence + " WHERE GeographyId=" + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadGeographyDesignationFromDataReader(reader)); + result.Add (ReadGeographyDesignationFromDataReader (reader)); } } } @@ -439,7 +439,7 @@ namespace Swarmops.Database return result.ToArray(); } - public int[] GetGeographyIdsFromLevel(int countryId, GeographyLevel level) + public int[] GetGeographyIdsFromLevel (int countryId, GeographyLevel level) { List result = new List(); @@ -448,7 +448,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select GeographyId FROM GeographyDesignations WHERE GeographyLevelId=" + ((int) level) + " AND CountryId=" + countryId, connection); @@ -456,7 +456,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } } } @@ -464,19 +464,19 @@ namespace Swarmops.Database return result.ToArray(); } - public int CreateGeography(string name, int parentGeographyId) + public int CreateGeography (string name, int parentGeographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateGeography", connection); + DbCommand command = GetDbCommand ("CreateGeography", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "parentGeographyId", parentGeographyId); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "parentGeographyId", parentGeographyId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } } diff --git a/Database/Database-InboundInvoices.cs b/Database/Database-InboundInvoices.cs index f60628ca..9791e63d 100644 --- a/Database/Database-InboundInvoices.cs +++ b/Database/Database-InboundInvoices.cs @@ -18,25 +18,25 @@ namespace Swarmops.Database "PayToAccount,Ocr,InvoiceReference,ClosedDateTime,ClosedByPersonId " + "FROM InboundInvoices "; - private BasicInboundInvoice ReadInboundInvoiceFromDataReader(DbDataReader reader) + private BasicInboundInvoice ReadInboundInvoiceFromDataReader (DbDataReader reader) { - int inboundInvoiceId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - DateTime createdDateTime = reader.GetDateTime(2); - int createdByPersonId = reader.GetInt32(3); - DateTime dueDate = reader.GetDateTime(4); - Int64 amountCents = reader.GetInt64(5); - int budgetId = reader.GetInt32(6); - bool attested = reader.GetBoolean(7); - bool open = reader.GetBoolean(8); - string supplier = reader.GetString(9); - string payToAccount = reader.GetString(10); - string ocr = reader.GetString(11); - string invoiceReference = reader.GetString(12); - DateTime closedDateTime = reader.GetDateTime(13); - int closedByPersonId = reader.GetInt32(14); + int inboundInvoiceId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + DateTime createdDateTime = reader.GetDateTime (2); + int createdByPersonId = reader.GetInt32 (3); + DateTime dueDate = reader.GetDateTime (4); + Int64 amountCents = reader.GetInt64 (5); + int budgetId = reader.GetInt32 (6); + bool attested = reader.GetBoolean (7); + bool open = reader.GetBoolean (8); + string supplier = reader.GetString (9); + string payToAccount = reader.GetString (10); + string ocr = reader.GetString (11); + string invoiceReference = reader.GetString (12); + DateTime closedDateTime = reader.GetDateTime (13); + int closedByPersonId = reader.GetInt32 (14); - return new BasicInboundInvoice(inboundInvoiceId, organizationId, createdDateTime, dueDate, + return new BasicInboundInvoice (inboundInvoiceId, organizationId, createdDateTime, dueDate, amountCents, budgetId, supplier, payToAccount, ocr, invoiceReference, attested, open, closedDateTime, closedByPersonId); } @@ -45,14 +45,14 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicInboundInvoice GetInboundInvoice(int inboundInvoiceId) + public BasicInboundInvoice GetInboundInvoice (int inboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + inboundInvoiceFieldSequence + "WHERE InboundInvoiceId=" + inboundInvoiceId + ";", connection); @@ -60,10 +60,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadInboundInvoiceFromDataReader(reader); + return ReadInboundInvoiceFromDataReader (reader); } - throw new ArgumentException("Unknown Account Id"); + throw new ArgumentException ("Unknown Account Id"); } } } @@ -74,7 +74,7 @@ namespace Swarmops.Database /// /// Optional Organization object and/or DatabaseConditions. /// The inbound invoice list. - public BasicInboundInvoice[] GetInboundInvoices(params object[] conditions) + public BasicInboundInvoice[] GetInboundInvoices (params object[] conditions) { List result = new List(); @@ -83,15 +83,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + inboundInvoiceFieldSequence + ConstructWhereClause("InboundInvoices", conditions) + + GetDbCommand ( + "SELECT" + inboundInvoiceFieldSequence + ConstructWhereClause ("InboundInvoices", conditions) + " ORDER BY DueDate;", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadInboundInvoiceFromDataReader(reader)); + result.Add (ReadInboundInvoiceFromDataReader (reader)); } return result.ToArray(); @@ -130,128 +130,128 @@ namespace Swarmops.Database }*/ - public int CreateInboundInvoice(int organizationId, DateTime dueDate, int budgetId, string supplier, + public int CreateInboundInvoice (int organizationId, DateTime dueDate, int budgetId, string supplier, string payToAccount, string ocr, string invoiceReference, Int64 amountCents, int createdByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateInboundInvoicePrecise", connection); + DbCommand command = GetDbCommand ("CreateInboundInvoicePrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "dueDate", dueDate); - AddParameterWithName(command, "budgetId", budgetId); - AddParameterWithName(command, "supplier", supplier); - AddParameterWithName(command, "payToAccount", payToAccount); - AddParameterWithName(command, "ocr", ocr); - AddParameterWithName(command, "invoiceReference", invoiceReference); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "dueDate", dueDate); + AddParameterWithName (command, "budgetId", budgetId); + AddParameterWithName (command, "supplier", supplier); + AddParameterWithName (command, "payToAccount", payToAccount); + AddParameterWithName (command, "ocr", ocr); + AddParameterWithName (command, "invoiceReference", invoiceReference); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetInboundInvoiceOpen(int inboundInvoiceId, bool open) + public void SetInboundInvoiceOpen (int inboundInvoiceId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceOpen", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetInboundInvoiceAttested(int inboundInvoiceId, bool attested) + public void SetInboundInvoiceAttested (int inboundInvoiceId, bool attested) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceAttested", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceAttested", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "attested", attested); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "attested", attested); command.ExecuteNonQuery(); } } - public void SetInboundInvoiceAmount(int inboundInvoiceId, double amount) + public void SetInboundInvoiceAmount (int inboundInvoiceId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceAmount", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceAmount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "amount", amount); command.ExecuteNonQuery(); } } - public void SetInboundInvoiceAmount(int inboundInvoiceId, Int64 amountCents) + public void SetInboundInvoiceAmount (int inboundInvoiceId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceAmountPrecise", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceAmountPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "amountCents", amountCents); command.ExecuteNonQuery(); } } - public void SetInboundInvoiceBudget(int inboundInvoiceId, int budgetId) + public void SetInboundInvoiceBudget (int inboundInvoiceId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceBudget", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceBudget", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "budgetId", budgetId); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "budgetId", budgetId); command.ExecuteNonQuery(); } } - public void SetInboundInvoiceDueDate(int inboundInvoiceId, DateTime dueDate) + public void SetInboundInvoiceDueDate (int inboundInvoiceId, DateTime dueDate) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInboundInvoiceDueDate", connection); + DbCommand command = GetDbCommand ("SetInboundInvoiceDueDate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "inboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "dueDate", dueDate); + AddParameterWithName (command, "inboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "dueDate", dueDate); command.ExecuteNonQuery(); } diff --git a/Database/Database-Initialization.cs b/Database/Database-Initialization.cs index aa9a3f27..f5cac109 100644 --- a/Database/Database-Initialization.cs +++ b/Database/Database-Initialization.cs @@ -8,7 +8,7 @@ namespace Swarmops.Database { // These functions are bloody dangerous, mmmkay? - public void ExecuteAdminCommand(string sqlSequence) + public void ExecuteAdminCommand (string sqlSequence) { // TODO: Verify that we're in admin mode @@ -16,14 +16,14 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand(sqlSequence, connection); + DbCommand command = GetDbCommand (sqlSequence, connection); command.CommandType = CommandType.Text; command.ExecuteNonQuery(); } } - public int ExecuteAdminCommandScalar(string sqlSequence) + public int ExecuteAdminCommandScalar (string sqlSequence) { // TODO: Verify that we're in admin mode @@ -31,7 +31,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand(sqlSequence, connection); + DbCommand command = GetDbCommand (sqlSequence, connection); command.CommandType = CommandType.Text; object result = command.ExecuteScalar(); @@ -41,7 +41,7 @@ namespace Swarmops.Database return 0; } - return Convert.ToInt32(result); + return Convert.ToInt32 (result); } } } diff --git a/Database/Database-InternalPollCandidates.cs b/Database/Database-InternalPollCandidates.cs index 996a4963..759440ab 100644 --- a/Database/Database-InternalPollCandidates.cs +++ b/Database/Database-InternalPollCandidates.cs @@ -14,28 +14,28 @@ namespace Swarmops.Database " InternalPollCandidateId,InternalPollId,PersonId,CandidacyStatement " + // 0-3 "FROM InternalPollCandidates "; - private static BasicInternalPollCandidate ReadInternalPollCandidateFromDataReader(IDataRecord reader) + private static BasicInternalPollCandidate ReadInternalPollCandidateFromDataReader (IDataRecord reader) { - int internalPollCandidateId = reader.GetInt32(0); - int internalPollId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - string candidacyStatement = reader.GetString(3); + int internalPollCandidateId = reader.GetInt32 (0); + int internalPollId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + string candidacyStatement = reader.GetString (3); - return new BasicInternalPollCandidate(internalPollCandidateId, internalPollId, personId, candidacyStatement); + return new BasicInternalPollCandidate (internalPollCandidateId, internalPollId, personId, candidacyStatement); } #endregion #region Record reading - SELECT statements - public BasicInternalPollCandidate GetInternalPollCandidate(int internalPollCandidateId) + public BasicInternalPollCandidate GetInternalPollCandidate (int internalPollCandidateId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + internalPollCandidateFieldSequence + "WHERE InternalPollCandidateId=" + internalPollCandidateId + ";", connection); @@ -43,10 +43,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadInternalPollCandidateFromDataReader(reader); + return ReadInternalPollCandidateFromDataReader (reader); } - throw new ArgumentException("Unknown Id: " + internalPollCandidateId); + throw new ArgumentException ("Unknown Id: " + internalPollCandidateId); } } } @@ -59,7 +59,7 @@ namespace Swarmops.Database /// specifiers. /// /// A list of matching salaries. - public BasicInternalPollCandidate[] GetInternalPollCandidates(params object[] conditions) + public BasicInternalPollCandidate[] GetInternalPollCandidates (params object[] conditions) { List result = new List(); @@ -68,15 +68,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + internalPollCandidateFieldSequence + - ConstructWhereClause("InternalPollCandidates", conditions) + " ORDER BY SortOrder", connection); + ConstructWhereClause ("InternalPollCandidates", conditions) + " ORDER BY SortOrder", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadInternalPollCandidateFromDataReader(reader)); + result.Add (ReadInternalPollCandidateFromDataReader (reader)); } return result.ToArray(); @@ -88,52 +88,52 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateInternalPollCandidate(int internalPollId, int personId, string candidacyStatement) + public int CreateInternalPollCandidate (int internalPollId, int personId, string candidacyStatement) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateInternalPollCandidate", connection); + DbCommand command = GetDbCommand ("CreateInternalPollCandidate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "candidacyStatement", candidacyStatement); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "candidacyStatement", candidacyStatement); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetInternalPollCandidateStatement(int internalPollCandidateId, string candidacyStatement) + public void SetInternalPollCandidateStatement (int internalPollCandidateId, string candidacyStatement) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInternalPollCandidateStatement", connection); + DbCommand command = GetDbCommand ("SetInternalPollCandidateStatement", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollCandidateId", internalPollCandidateId); - AddParameterWithName(command, "candidacyStatement", candidacyStatement); + AddParameterWithName (command, "internalPollCandidateId", internalPollCandidateId); + AddParameterWithName (command, "candidacyStatement", candidacyStatement); command.ExecuteNonQuery(); } } - public int SetInternalPollCandidateSortOrder(int internalPollCandidateId, string sortOrder) + public int SetInternalPollCandidateSortOrder (int internalPollCandidateId, string sortOrder) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInternalPollCandidateSortOrder", connection); + DbCommand command = GetDbCommand ("SetInternalPollCandidateSortOrder", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollCandidateId", internalPollCandidateId); - AddParameterWithName(command, "sortOrder", sortOrder); + AddParameterWithName (command, "internalPollCandidateId", internalPollCandidateId); + AddParameterWithName (command, "sortOrder", sortOrder); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-InternalPollVotes.cs b/Database/Database-InternalPollVotes.cs index 2b46436e..00bc51cc 100644 --- a/Database/Database-InternalPollVotes.cs +++ b/Database/Database-InternalPollVotes.cs @@ -18,37 +18,37 @@ namespace Swarmops.Database " PersonId,InternalPollId,Open,ClosedDateTime " + // 0-3 "FROM InternalPollVoters "; - private static BasicInternalPollVote ReadInternalPollVoteFromDataReader(IDataRecord reader) + private static BasicInternalPollVote ReadInternalPollVoteFromDataReader (IDataRecord reader) { - int internalPollVoteId = reader.GetInt32(0); - int internalPollId = reader.GetInt32(1); - string verificationCode = reader.GetString(2); + int internalPollVoteId = reader.GetInt32 (0); + int internalPollId = reader.GetInt32 (1); + string verificationCode = reader.GetString (2); - return new BasicInternalPollVote(internalPollVoteId, internalPollId, verificationCode); + return new BasicInternalPollVote (internalPollVoteId, internalPollId, verificationCode); } - private static BasicInternalPollVoter ReadInternalPollVoterFromDataReader(IDataRecord reader) + private static BasicInternalPollVoter ReadInternalPollVoterFromDataReader (IDataRecord reader) { - int personId = reader.GetInt32(0); - int internalPollId = reader.GetInt32(1); - bool open = reader.GetBoolean(2); - DateTime closedDateTime = reader.GetDateTime(3); + int personId = reader.GetInt32 (0); + int internalPollId = reader.GetInt32 (1); + bool open = reader.GetBoolean (2); + DateTime closedDateTime = reader.GetDateTime (3); - return new BasicInternalPollVoter(personId, internalPollId, open, closedDateTime); + return new BasicInternalPollVoter (personId, internalPollId, open, closedDateTime); } #endregion #region Record reading - SELECT statements - public BasicInternalPollVote GetInternalPollVote(int internalPollVoteId) + public BasicInternalPollVote GetInternalPollVote (int internalPollVoteId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + internalPollVoteFieldSequence + "WHERE InternalPollVoteId=" + internalPollVoteId + ";", connection); @@ -56,40 +56,40 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadInternalPollVoteFromDataReader(reader); + return ReadInternalPollVoteFromDataReader (reader); } - throw new ArgumentException("Unknown Id: " + internalPollVoteId); + throw new ArgumentException ("Unknown Id: " + internalPollVoteId); } } } - public BasicInternalPollVote GetInternalPollVote(string verificationCode) + public BasicInternalPollVote GetInternalPollVote (string verificationCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + internalPollVoteFieldSequence + "WHERE VerificationCode='" + - verificationCode.Replace("'", "''") + "';", connection); + verificationCode.Replace ("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadInternalPollVoteFromDataReader(reader); + return ReadInternalPollVoteFromDataReader (reader); } - throw new ArgumentException("Unknown Verification Code: " + verificationCode); + throw new ArgumentException ("Unknown Verification Code: " + verificationCode); } } } - public BasicInternalPollVote[] GetInternalPollVotes(params object[] conditions) + public BasicInternalPollVote[] GetInternalPollVotes (params object[] conditions) { List result = new List(); @@ -98,15 +98,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + internalPollVoteFieldSequence + ConstructWhereClause("InternalPollVotes", conditions) + + GetDbCommand ( + "SELECT" + internalPollVoteFieldSequence + + ConstructWhereClause ("InternalPollVotes", conditions) + " ORDER BY VerificationCode", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadInternalPollVoteFromDataReader(reader)); + result.Add (ReadInternalPollVoteFromDataReader (reader)); } return result.ToArray(); @@ -115,14 +116,14 @@ namespace Swarmops.Database } - public InternalPollVoterStatus GetInternalPollVoterStatus(int internalPollId, int personId) + public InternalPollVoterStatus GetInternalPollVoterStatus (int internalPollId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Open FROM InternalPollVoters WHERE InternalPollId=" + internalPollId + " AND PersonId=" + personId, connection); @@ -130,7 +131,7 @@ namespace Swarmops.Database { if (reader.Read()) { - return reader.GetBoolean(0) + return reader.GetBoolean (0) ? InternalPollVoterStatus.CanVote : InternalPollVoterStatus.HasAlreadyVoted; } @@ -141,7 +142,7 @@ namespace Swarmops.Database } - public int[] GetInternalPollVoteDetails(int internalPollVoteId) + public int[] GetInternalPollVoteDetails (int internalPollVoteId) { List result = new List(); @@ -150,7 +151,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT InternalPollCandidateId FROM InternalPollVoteDetails WHERE InternalPollVoteId=" + internalPollVoteId + " ORDER BY Position", connection); @@ -158,7 +159,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -167,7 +168,7 @@ namespace Swarmops.Database } - public BasicInternalPollVoter[] GetInternalPollVoters(params object[] conditions) + public BasicInternalPollVoter[] GetInternalPollVoters (params object[] conditions) { List result = new List(); @@ -175,15 +176,15 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( - "SELECT" + internalPollVoterFieldSequence + ConstructWhereClause("InternalPollVoters", conditions), + DbCommand command = GetDbCommand ( + "SELECT" + internalPollVoterFieldSequence + ConstructWhereClause ("InternalPollVoters", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadInternalPollVoterFromDataReader(reader)); + result.Add (ReadInternalPollVoterFromDataReader (reader)); } return result.ToArray(); @@ -192,7 +193,7 @@ namespace Swarmops.Database } - public Dictionary GetCandidateIdPersonIdMap(int pollId) + public Dictionary GetCandidateIdPersonIdMap (int pollId) { Dictionary result = new Dictionary(); @@ -200,7 +201,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "SELECT InternalPollCandidateId,PersonId FROM InternalPollCandidates WHERE InternalPollId=" + pollId, connection); @@ -208,7 +209,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetInt32(1); + result[reader.GetInt32 (0)] = reader.GetInt32 (1); } return result; @@ -220,90 +221,90 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateInternalPollVote(int internalPollId, int voteGeographyId, string verificationCode) + public int CreateInternalPollVote (int internalPollId, int voteGeographyId, string verificationCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateInternalPollVote", connection); + DbCommand command = GetDbCommand ("CreateInternalPollVote", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "voteGeographyId", voteGeographyId); - AddParameterWithName(command, "verificationCode", verificationCode); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "voteGeographyId", voteGeographyId); + AddParameterWithName (command, "verificationCode", verificationCode); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateInternalPollVoteDetail(int internalPollVoteId, int internalPollCandidateId, int position) + public int CreateInternalPollVoteDetail (int internalPollVoteId, int internalPollCandidateId, int position) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateInternalPollVoteDetail", connection); + DbCommand command = GetDbCommand ("CreateInternalPollVoteDetail", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollVoteId", internalPollVoteId); - AddParameterWithName(command, "internalPollCandidateId", internalPollCandidateId); - AddParameterWithName(command, "position", position); + AddParameterWithName (command, "internalPollVoteId", internalPollVoteId); + AddParameterWithName (command, "internalPollCandidateId", internalPollCandidateId); + AddParameterWithName (command, "position", position); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void ClearInternalPollVote(int internalPollVoteId) + public void ClearInternalPollVote (int internalPollVoteId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClearInternalPollVote", connection); + DbCommand command = GetDbCommand ("ClearInternalPollVote", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollVoteId", internalPollVoteId); + AddParameterWithName (command, "internalPollVoteId", internalPollVoteId); command.ExecuteNonQuery(); } } - public int CreateInternalPollVoter(int internalPollId, int personId) + public int CreateInternalPollVoter (int internalPollId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateInternalPollVoter", connection); + DbCommand command = GetDbCommand ("CreateInternalPollVoter", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "personId", personId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CloseInternalPollVoter(int internalPollId, int personId, string ipAddress) + public int CloseInternalPollVoter (int internalPollId, int personId, string ipAddress) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CloseInternalPollVoter", connection); + DbCommand command = GetDbCommand ("CloseInternalPollVoter", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "closedDateTime", DateTime.Now); - AddParameterWithName(command, "ipAddress", ipAddress); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "closedDateTime", DateTime.Now); + AddParameterWithName (command, "ipAddress", ipAddress); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-InternalPolls.cs b/Database/Database-InternalPolls.cs index da803b9c..082eb036 100644 --- a/Database/Database-InternalPolls.cs +++ b/Database/Database-InternalPolls.cs @@ -16,25 +16,25 @@ namespace Swarmops.Database " VotingOpens,VotingCloses,ResultsTypeId " + // 10-12 " FROM InternalPolls "; - private BasicInternalPoll ReadInternalPollFromDataReader(DbDataReader reader) + private BasicInternalPoll ReadInternalPollFromDataReader (DbDataReader reader) { - int internalPollId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - int geographyId = reader.GetInt32(2); - string name = reader.GetString(3); - bool runningOpen = reader.GetBoolean(4); - bool votingOpen = reader.GetBoolean(5); - int maxVoteLength = reader.GetInt32(6); - int createdByPersonId = reader.GetInt32(7); - DateTime runningOpens = reader.GetDateTime(8); - DateTime runningCloses = reader.GetDateTime(9); - DateTime votingOpens = reader.GetDateTime(10); - DateTime votingCloses = reader.GetDateTime(11); - int resultsTypeId = reader.GetInt32(12); + int internalPollId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + int geographyId = reader.GetInt32 (2); + string name = reader.GetString (3); + bool runningOpen = reader.GetBoolean (4); + bool votingOpen = reader.GetBoolean (5); + int maxVoteLength = reader.GetInt32 (6); + int createdByPersonId = reader.GetInt32 (7); + DateTime runningOpens = reader.GetDateTime (8); + DateTime runningCloses = reader.GetDateTime (9); + DateTime votingOpens = reader.GetDateTime (10); + DateTime votingCloses = reader.GetDateTime (11); + int resultsTypeId = reader.GetInt32 (12); InternalPollResultsType resultsType = (InternalPollResultsType) resultsTypeId; - return new BasicInternalPoll(internalPollId, createdByPersonId, organizationId, geographyId, name, + return new BasicInternalPoll (internalPollId, createdByPersonId, organizationId, geographyId, name, runningOpen, votingOpen, maxVoteLength, runningOpens, runningCloses, votingOpens, votingCloses, resultsType); } @@ -43,14 +43,14 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicInternalPoll GetInternalPoll(int internalPollId) + public BasicInternalPoll GetInternalPoll (int internalPollId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + internalPollFieldSequence + "WHERE InternalPollId=" + internalPollId + ";", connection); @@ -58,10 +58,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadInternalPollFromDataReader(reader); + return ReadInternalPollFromDataReader (reader); } - throw new ArgumentException("Unknown InternalPollId: " + internalPollId); + throw new ArgumentException ("Unknown InternalPollId: " + internalPollId); } } } @@ -72,7 +72,7 @@ namespace Swarmops.Database /// /// Optional Organization object and/or DatabaseConditions. /// The inbound invoice list. - public BasicInternalPoll[] GetInternalPolls(params object[] conditions) + public BasicInternalPoll[] GetInternalPolls (params object[] conditions) { List result = new List(); @@ -81,15 +81,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + internalPollFieldSequence + ConstructWhereClause("InternalPoll", conditions), + GetDbCommand ( + "SELECT " + internalPollFieldSequence + ConstructWhereClause ("InternalPoll", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadInternalPollFromDataReader(reader)); + result.Add (ReadInternalPollFromDataReader (reader)); } return result.ToArray(); @@ -101,7 +101,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateInternalPoll(int organizationId, int geographyId, string name, int maxVoteLength, + public int CreateInternalPoll (int organizationId, int geographyId, string name, int maxVoteLength, InternalPollResultsType resultsType, int createdByPersonId, DateTime runningOpens, DateTime runningCloses, DateTime votingOpens, DateTime votingCloses) @@ -110,52 +110,52 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateInternalPoll", connection); + DbCommand command = GetDbCommand ("CreateInternalPoll", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "maxVoteLength", maxVoteLength); - AddParameterWithName(command, "resultsTypeId", (int) resultsType); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "runningOpens", runningOpens); - AddParameterWithName(command, "runningCloses", runningCloses); - AddParameterWithName(command, "votingOpens", votingOpens); - AddParameterWithName(command, "votingCloses", votingCloses); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "maxVoteLength", maxVoteLength); + AddParameterWithName (command, "resultsTypeId", (int) resultsType); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "runningOpens", runningOpens); + AddParameterWithName (command, "runningCloses", runningCloses); + AddParameterWithName (command, "votingOpens", votingOpens); + AddParameterWithName (command, "votingCloses", votingCloses); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetInternalPollVotingOpen(int internalPollId, bool open) + public void SetInternalPollVotingOpen (int internalPollId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInternalPollVotingOpen", connection); + DbCommand command = GetDbCommand ("SetInternalPollVotingOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetInternalPollRunningOpen(int internalPollId, bool open) + public void SetInternalPollRunningOpen (int internalPollId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetInternalPollRunningOpen", connection); + DbCommand command = GetDbCommand ("SetInternalPollRunningOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "internalPollId", internalPollId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "internalPollId", internalPollId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } diff --git a/Database/Database-MailTemplates.cs b/Database/Database-MailTemplates.cs index 61c249e6..0db5e723 100644 --- a/Database/Database-MailTemplates.cs +++ b/Database/Database-MailTemplates.cs @@ -8,36 +8,36 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicMailTemplate[] GetMailTemplatesByName(string templatename) + public BasicMailTemplate[] GetMailTemplatesByName (string templatename) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - templatename = templatename.Replace("'", "''"); + templatename = templatename.Replace ("'", "''"); - string sql = string.Format("SELECT * FROM MailTemplates WHERE (TemplateName = '{0}')", templatename); + string sql = string.Format ("SELECT * FROM MailTemplates WHERE (TemplateName = '{0}')", templatename); - DbCommand command = GetDbCommand(sql, connection); + DbCommand command = GetDbCommand (sql, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { List retlist = new List(); - retlist.Add(ReadMailTemplate(reader)); + retlist.Add (ReadMailTemplate (reader)); while (reader.Read()) { - retlist.Add(ReadMailTemplate(reader)); + retlist.Add (ReadMailTemplate (reader)); } return retlist.ToArray(); } - throw new ArgumentException("No mailtemplate named: " + templatename + " exists."); + throw new ArgumentException ("No mailtemplate named: " + templatename + " exists."); } } } - public BasicMailTemplate GetMailTemplateById(int templateId) + public BasicMailTemplate GetMailTemplateById (int templateId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -45,17 +45,17 @@ namespace Swarmops.Database string sql = "SELECT * from MailTemplates where TemplateId={0}"; - sql = string.Format(sql, templateId); + sql = string.Format (sql, templateId); - DbCommand command = GetDbCommand(sql, connection); + DbCommand command = GetDbCommand (sql, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadMailTemplate(reader); + return ReadMailTemplate (reader); } - throw new ArgumentException("No mailtemplate with id: " + templateId + " exists."); + throw new ArgumentException ("No mailtemplate with id: " + templateId + " exists."); } } } @@ -69,21 +69,21 @@ namespace Swarmops.Database string sql = "SELECT * from MailTemplates order by templateName, CountryCode, LanguageCode, OrganizationId"; - DbCommand command = GetDbCommand(sql, connection); + DbCommand command = GetDbCommand (sql, connection); using (DbDataReader reader = command.ExecuteReader()) { List retlist = new List(); while (reader.Read()) { - retlist.Add(ReadMailTemplate(reader)); + retlist.Add (ReadMailTemplate (reader)); } return retlist.ToArray(); } } } - private static BasicMailTemplate ReadMailTemplate(DbDataReader reader) + private static BasicMailTemplate ReadMailTemplate (DbDataReader reader) { int templateId = (int) reader["templateId"]; string templateName = reader["templateName"] != DBNull.Value ? (string) reader["templateName"] : ""; @@ -91,10 +91,10 @@ namespace Swarmops.Database string crtyCode = reader["countryCode"] != DBNull.Value ? (string) reader["countryCode"] : ""; int orgId = reader["organizationId"] != DBNull.Value ? (int) reader["organizationId"] : 0; string templateBody = reader["templateBody"] != DBNull.Value ? (string) reader["templateBody"] : ""; - return new BasicMailTemplate(templateId, templateName, langCode, crtyCode, orgId, templateBody); + return new BasicMailTemplate (templateId, templateName, langCode, crtyCode, orgId, templateBody); } - public int SetMailTemplate(int templateId, + public int SetMailTemplate (int templateId, string templateName, string languageCode, string countryCode, @@ -105,24 +105,24 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SetMailTemplate", connection); + DbCommand command = GetDbCommand ("SetMailTemplate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_templateId", templateId); - AddParameterWithName(command, "p_organizationId", organizationId); - AddParameterWithName(command, "p_templateName", templateName); - AddParameterWithName(command, "p_languageCode", languageCode); - AddParameterWithName(command, "p_countryCode", countryCode); - AddParameterWithName(command, "p_templateBody", templateBody); + AddParameterWithName (command, "p_templateId", templateId); + AddParameterWithName (command, "p_organizationId", organizationId); + AddParameterWithName (command, "p_templateName", templateName); + AddParameterWithName (command, "p_languageCode", languageCode); + AddParameterWithName (command, "p_countryCode", countryCode); + AddParameterWithName (command, "p_templateBody", templateBody); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetMailTemplate(BasicMailTemplate mailTemplate) + public int SetMailTemplate (BasicMailTemplate mailTemplate) { - return SetMailTemplate(mailTemplate.TemplateId, + return SetMailTemplate (mailTemplate.TemplateId, mailTemplate.TemplateName, mailTemplate.LanguageCode, mailTemplate.CountryCode, diff --git a/Database/Database-Media.cs b/Database/Database-Media.cs index ac6c9054..c82ee683 100644 --- a/Database/Database-Media.cs +++ b/Database/Database-Media.cs @@ -9,7 +9,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreateMediaEntryFromKeyword(string keyword, string mediaName, bool isBlog, string url, string title, + public int CreateMediaEntryFromKeyword (string keyword, string mediaName, bool isBlog, string url, string title, DateTime dateTime) { using (DbConnection connection = GetMySqlDbConnection()) @@ -17,31 +17,31 @@ namespace Swarmops.Database connection.Open(); try { - DbCommand command = GetDbCommand("CreateMediaKeywordEntry", connection); + DbCommand command = GetDbCommand ("CreateMediaKeywordEntry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "mediaKeyword", keyword); - AddParameterWithName(command, "mediaName", mediaName); - AddParameterWithName(command, "isBlog", isBlog); - AddParameterWithName(command, "mediaEntryTitle", title); - AddParameterWithName(command, "mediaEntryUrl", url); - AddParameterWithName(command, "mediaEntryDateTime", dateTime); + AddParameterWithName (command, "mediaKeyword", keyword); + AddParameterWithName (command, "mediaName", mediaName); + AddParameterWithName (command, "isBlog", isBlog); + AddParameterWithName (command, "mediaEntryTitle", title); + AddParameterWithName (command, "mediaEntryUrl", url); + AddParameterWithName (command, "mediaEntryDateTime", dateTime); - int mediaKeywordEntryId = Convert.ToInt32(command.ExecuteScalar()); + int mediaKeywordEntryId = Convert.ToInt32 (command.ExecuteScalar()); return mediaKeywordEntryId; } catch (Exception e) { - throw new Exception("Failed in sp CreateMediaKeywordEntry:" + e.Message, e); + throw new Exception ("Failed in sp CreateMediaKeywordEntry:" + e.Message, e); } } } - public BasicMediaEntry[] GetBlogEntriesForKeyword(string keyword, DateTime minAge) // NOT ok + public BasicMediaEntry[] GetBlogEntriesForKeyword (string keyword, DateTime minAge) // NOT ok { - throw new NotImplementedException("Not yet migrated to MySQL: GetBlogEntriesForKeyword"); + throw new NotImplementedException ("Not yet migrated to MySQL: GetBlogEntriesForKeyword"); /* return ExecuteMediaDbQuery("SELECT * FROM MediaEntryView WHERE MediaKeyword='" + keyword.Replace("'", "''") + @@ -49,9 +49,9 @@ namespace Swarmops.Database "' AND IsBlog %ISTRUE% ORDER BY MediaEntryDateTime DESC");*/ } - public BasicMediaEntry[] GetOldMediaEntriesForKeyword(string keyword, DateTime minAge) // NOT ok + public BasicMediaEntry[] GetOldMediaEntriesForKeyword (string keyword, DateTime minAge) // NOT ok { - throw new NotImplementedException("Not yet migrated to MySQL: GetOldMediaEntriesForKeyword"); + throw new NotImplementedException ("Not yet migrated to MySQL: GetOldMediaEntriesForKeyword"); /* return @@ -60,7 +60,7 @@ namespace Swarmops.Database "' AND IsBlog %ISFALSE% ORDER BY MediaEntryDateTime DESC");*/ } - private BasicMediaEntry[] ExecuteMediaDbQuery(string commandString) + private BasicMediaEntry[] ExecuteMediaDbQuery (string commandString) { List result = new List(); @@ -68,13 +68,13 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand(commandString, connection); + DbCommand command = GetDbCommand (commandString, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMediaEntryFromReader(reader)); + result.Add (ReadMediaEntryFromReader (reader)); } } } @@ -83,7 +83,7 @@ namespace Swarmops.Database } - public BasicMediaEntry[] GetMediaEntriesForKeywordIdsSimplified(int[] keywordIds) // migrated RF 2010-May-07 + public BasicMediaEntry[] GetMediaEntriesForKeywordIdsSimplified (int[] keywordIds) // migrated RF 2010-May-07 { List result = new List(); @@ -92,16 +92,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT MediaKeywordEntryId, MediaKeywordId, MediaId, MediaEntryDateTime FROM MediaKeywordEntries WHERE MediaKeywordId in (" + - JoinIds(keywordIds) + ") ORDER BY MediaEntryDateTime", connection); + JoinIds (keywordIds) + ") ORDER BY MediaEntryDateTime", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(new BasicMediaEntry(reader.GetInt32(0), reader.GetInt32(1), - reader.GetInt32(2).ToString(), false, "N/A", "N/A", reader.GetDateTime(3))); + result.Add (new BasicMediaEntry (reader.GetInt32 (0), reader.GetInt32 (1), + reader.GetInt32 (2).ToString(), false, "N/A", "N/A", reader.GetDateTime (3))); } } } @@ -110,7 +110,7 @@ namespace Swarmops.Database } - private BasicMediaEntry ReadMediaEntryFromReader(DbDataReader reader) + private BasicMediaEntry ReadMediaEntryFromReader (DbDataReader reader) // NOT ok -- will need to migrate; any dependencies also won't work { int id = (int) reader["MediaKeywordEntryId"]; @@ -133,7 +133,7 @@ namespace Swarmops.Database } } - return new BasicMediaEntry(id, keywordId, mediaName, isBlog, mediaEntryTitle, mediaEntryUrl, + return new BasicMediaEntry (id, keywordId, mediaName, isBlog, mediaEntryTitle, mediaEntryUrl, mediaEntryDateTime); } @@ -146,14 +146,14 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT MediaKeyword From MediaKeywords WHERE SearchBlogs=1", + DbCommand command = GetDbCommand ("SELECT MediaKeyword From MediaKeywords WHERE SearchBlogs=1", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(reader.GetString(0)); + result.Add (reader.GetString (0)); } } } @@ -168,14 +168,14 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT MediaKeyword From MediaKeywords WHERE SearchOldMedia=1", + DbCommand command = GetDbCommand ("SELECT MediaKeyword From MediaKeywords WHERE SearchOldMedia=1", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(reader.GetString(0)); + result.Add (reader.GetString (0)); } } } @@ -191,35 +191,35 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT MediaId,IsBlog From Media", connection); + DbCommand command = GetDbCommand ("SELECT MediaId,IsBlog From Media", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetBoolean(1); + result[reader.GetInt32 (0)] = reader.GetBoolean (1); } } } return result; } - public int GetMediaKeywordId(string keyword) // OK + public int GetMediaKeywordId (string keyword) // OK { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT MediaKeywordId From MediaKeywords WHERE MediaKeyword='" + keyword.Replace("'", "''") + + GetDbCommand ( + "SELECT MediaKeywordId From MediaKeywords WHERE MediaKeyword='" + keyword.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } return 0; } @@ -235,13 +235,13 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT MediaKeywordId,MediaKeyword From MediaKeywords", connection); + DbCommand command = GetDbCommand ("SELECT MediaKeywordId,MediaKeyword From MediaKeywords", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetString(1); + result[reader.GetInt32 (0)] = reader.GetString (1); } } } @@ -249,14 +249,14 @@ namespace Swarmops.Database } - public BasicMediaCategory GetMediaCategory(int mediaCategoryId) // OK + public BasicMediaCategory GetMediaCategory (int mediaCategoryId) // OK { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Name FROM MediaCategories WHERE MediaCategoryId=" + mediaCategoryId, connection); @@ -264,40 +264,40 @@ namespace Swarmops.Database { if (reader.Read()) { - return new BasicMediaCategory(mediaCategoryId, reader.GetString(0)); + return new BasicMediaCategory (mediaCategoryId, reader.GetString (0)); } - throw new ArgumentException("No such MediaCategoryId: " + mediaCategoryId); + throw new ArgumentException ("No such MediaCategoryId: " + mediaCategoryId); } } } - public BasicMediaCategory GetMediaCategoryByName(string mediaCategoryName) // OK + public BasicMediaCategory GetMediaCategoryByName (string mediaCategoryName) // OK { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT MediaCategoryId, Name FROM MediaCategories WHERE Name='" + - mediaCategoryName.Replace("'", "''") + "'", connection); + mediaCategoryName.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return new BasicMediaCategory(reader.GetInt32(0), reader.GetString(1)); + return new BasicMediaCategory (reader.GetInt32 (0), reader.GetString (1)); } - throw new ArgumentException("No such MediaCategory: " + mediaCategoryName); + throw new ArgumentException ("No such MediaCategory: " + mediaCategoryName); } } } - public BasicMediaCategory[] GetMediaCategories(int[] mediaCategoryIds) + public BasicMediaCategory[] GetMediaCategories (int[] mediaCategoryIds) { List result = new List(); @@ -306,15 +306,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT MediaCategoryId, Name FROM MediaCategories WHERE MediaCategoryId in (" + - JoinIds(mediaCategoryIds) + ")", connection); + JoinIds (mediaCategoryIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(new BasicMediaCategory(reader.GetInt32(0), reader.GetString(1))); + result.Add (new BasicMediaCategory (reader.GetInt32 (0), reader.GetString (1))); } return result.ToArray(); @@ -332,14 +332,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT MediaCategoryId, Name FROM MediaCategories WHERE MediaCategoryId", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(new BasicMediaCategory(reader.GetInt32(0), reader.GetString(1))); + result.Add (new BasicMediaCategory (reader.GetInt32 (0), reader.GetString (1))); } return result.ToArray(); @@ -348,7 +348,7 @@ namespace Swarmops.Database } - public BasicMedium[] GetBlogTopList(DateTime date) // OK - migrated + public BasicMedium[] GetBlogTopList (DateTime date) // OK - migrated { using (DbConnection connection = GetMySqlDbConnection()) { @@ -357,15 +357,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT BlogRankingDateId FROM BlogRankingDates WHERE Date='" + date.ToString("yyyy-MM-dd") + + GetDbCommand ( + "SELECT BlogRankingDateId FROM BlogRankingDates WHERE Date='" + date.ToString ("yyyy-MM-dd") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - dateId = reader.GetInt32(0); + dateId = reader.GetInt32 (0); } else { @@ -376,7 +376,7 @@ namespace Swarmops.Database List result = new List(); command = - GetDbCommand( + GetDbCommand ( "select BlogRankings.MediaId,Media.Name from BlogRankings JOIN Media USING (MediaId) WHERE BlogRankings.BlogRankingDateId=" + dateId + " ORDER BY Ranking", connection); @@ -384,11 +384,11 @@ namespace Swarmops.Database { while (reader.Read()) { - int mediaId = reader.GetInt32(0); - string mediaName = reader.GetString(1); + int mediaId = reader.GetInt32 (0); + string mediaName = reader.GetString (1); PoliticalAffiliation politicalAffiliation = PoliticalAffiliation.Unknown; - result.Add(new BasicMedium(mediaId, mediaName, politicalAffiliation)); + result.Add (new BasicMedium (mediaId, mediaName, politicalAffiliation)); } return result.ToArray(); @@ -396,39 +396,39 @@ namespace Swarmops.Database } } - public void StoreBlogTopList(DateTime date, string[] rankedBlogNames) // OK - migrated + public void StoreBlogTopList (DateTime date, string[] rankedBlogNames) // OK - migrated { using (DbConnection connection = GetMySqlDbConnection()) { int dateId = 0; connection.Open(); - DbCommand command = GetDbCommand("CreateBlogRankingDate", connection); + DbCommand command = GetDbCommand ("CreateBlogRankingDate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "date", date); + AddParameterWithName (command, "date", date); - dateId = Convert.ToInt32(command.ExecuteScalar()); + dateId = Convert.ToInt32 (command.ExecuteScalar()); for (int index = 0; index < rankedBlogNames.Length; index++) { - command = GetDbCommand("CreateBlogRankingEntry", connection); + command = GetDbCommand ("CreateBlogRankingEntry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "blogRankingDateId", dateId); - AddParameterWithName(command, "mediaName", LimitStringLength(rankedBlogNames[index], 128)); - AddParameterWithName(command, "ranking", index + 1); + AddParameterWithName (command, "blogRankingDateId", dateId); + AddParameterWithName (command, "mediaName", LimitStringLength (rankedBlogNames[index], 128)); + AddParameterWithName (command, "ranking", index + 1); command.ExecuteNonQuery(); } } } - private string LimitStringLength(string input, int maxLength) + private string LimitStringLength (string input, int maxLength) { if (input.Length > maxLength) { - return input.Substring(0, maxLength - 3) + "..."; + return input.Substring (0, maxLength - 3) + "..."; } return input; diff --git a/Database/Database-Meetings.cs b/Database/Database-Meetings.cs index 35f3b112..178364c1 100644 --- a/Database/Database-Meetings.cs +++ b/Database/Database-Meetings.cs @@ -15,19 +15,19 @@ namespace Swarmops.Database "AmendmentVotingStarts,AmendmentVotingEnds,MotionVotingStarts,MotionVotingEnds " + // 5-8 "FROM Meetings "; - private static BasicMeeting ReadMeetingFromDataReader(IDataRecord reader) + private static BasicMeeting ReadMeetingFromDataReader (IDataRecord reader) { - int meetingId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - string name = reader.GetString(2); - DateTime motionSubmissionEnds = reader.GetDateTime(3); - DateTime amendmentSubmissionEnds = reader.GetDateTime(4); - DateTime amendmentVotingStarts = reader.GetDateTime(5); - DateTime amendmentVotingEnds = reader.GetDateTime(6); - DateTime motionVotingStarts = reader.GetDateTime(7); - DateTime motionVotingEnds = reader.GetDateTime(8); + int meetingId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + string name = reader.GetString (2); + DateTime motionSubmissionEnds = reader.GetDateTime (3); + DateTime amendmentSubmissionEnds = reader.GetDateTime (4); + DateTime amendmentVotingStarts = reader.GetDateTime (5); + DateTime amendmentVotingEnds = reader.GetDateTime (6); + DateTime motionVotingStarts = reader.GetDateTime (7); + DateTime motionVotingEnds = reader.GetDateTime (8); - return new BasicMeeting(meetingId, organizationId, name, motionSubmissionEnds, amendmentSubmissionEnds, + return new BasicMeeting (meetingId, organizationId, name, motionSubmissionEnds, amendmentSubmissionEnds, amendmentVotingStarts, amendmentVotingEnds, motionVotingStarts, motionVotingEnds); } @@ -35,29 +35,29 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicMeeting GetMeeting(int meetingId) + public BasicMeeting GetMeeting (int meetingId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + meetingFieldSequence + "WHERE MeetingId=" + meetingId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadMeetingFromDataReader(reader); + return ReadMeetingFromDataReader (reader); } - throw new ArgumentException("Unknown Meeting Id: " + meetingId); + throw new ArgumentException ("Unknown Meeting Id: " + meetingId); } } } - public BasicMeeting[] GetMeetings(params object[] conditions) + public BasicMeeting[] GetMeetings (params object[] conditions) { List result = new List(); @@ -66,14 +66,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + motionFieldSequence + ConstructWhereClause("Meetings", conditions), connection); + GetDbCommand ( + "SELECT" + motionFieldSequence + ConstructWhereClause ("Meetings", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMeetingFromDataReader(reader)); + result.Add (ReadMeetingFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-Memberships.cs b/Database/Database-Memberships.cs index 82fc0dbc..4fe81d17 100644 --- a/Database/Database-Memberships.cs +++ b/Database/Database-Memberships.cs @@ -39,7 +39,7 @@ namespace Swarmops.Database " MembershipPayments.MembershipId, MembershipPayments.MembershipPaymentStatusId, MembershipPayments.StatusDateTime " + " FROM MembershipPayments "; - public int[] GetMembersForOrganizations(int[] organizationIds) + public int[] GetMembersForOrganizations (int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -51,19 +51,19 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId From Memberships WHERE Active=1 AND OrganizationId IN (" + - JoinIds(organizationIds) + ")", connection); + JoinIds (organizationIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { - return ReadIntegersAtZeroFromDataReader(reader); + return ReadIntegersAtZeroFromDataReader (reader); } } } - public int[] GetMembersForOrganizationsAndGeographies(int[] organizationIds, int[] geographyIds) + public int[] GetMembersForOrganizationsAndGeographies (int[] organizationIds, int[] geographyIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -79,21 +79,21 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "select DISTINCT People.PersonId from Memberships,People WHERE " + "People.PersonId=Memberships.PersonId AND Memberships.Active=1 AND " + - "Memberships.OrganizationId IN (" + JoinIds(organizationIds) + ") AND " + - "People.GeographyId IN (" + JoinIds(geographyIds) + ")", connection); + "Memberships.OrganizationId IN (" + JoinIds (organizationIds) + ") AND " + + "People.GeographyId IN (" + JoinIds (geographyIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { - return ReadIntegersAtZeroFromDataReader(reader); + return ReadIntegersAtZeroFromDataReader (reader); } } } - public BasicMembership[] GetMemberships(params object[] conditions) + public BasicMembership[] GetMemberships (params object[] conditions) { List result = new List(); @@ -102,14 +102,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + membershipFieldSequence + ConstructWhereClause("Memberships", conditions), + GetDbCommand ( + "SELECT " + membershipFieldSequence + ConstructWhereClause ("Memberships", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMembershipFromDataReader(reader)); + result.Add (ReadMembershipFromDataReader (reader)); } return result.ToArray(); @@ -118,7 +119,7 @@ namespace Swarmops.Database } - public BasicMembership[] GetValidMembershipsForOrganizationAndPaymentStatus(int[] organizationIds, + public BasicMembership[] GetValidMembershipsForOrganizationAndPaymentStatus (int[] organizationIds, int paymentStatus) { string sqlCommand = @@ -127,7 +128,7 @@ namespace Swarmops.Database MembershipPayments ON Memberships.MembershipId = MembershipPayments.MembershipId WHERE (Memberships.Active = 1) AND (coalesce(MembershipPayments.MembershipPaymentStatusId, 0) = " + paymentStatus + @") - AND (Memberships.OrganizationId IN (" + JoinIds(organizationIds) + @")) + AND (Memberships.OrganizationId IN (" + JoinIds (organizationIds) + @")) AND (MembershipPayments.StatusDateTime = ( select MAX(StatusDateTime) from MembershipPayments M2 where Memberships.MembershipId = M2.MembershipId ) )"; @@ -137,13 +138,13 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand(sqlCommand, connection); + DbCommand command = GetDbCommand (sqlCommand, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMembershipFromDataReader(reader)); + result.Add (ReadMembershipFromDataReader (reader)); } return result.ToArray(); @@ -152,7 +153,7 @@ namespace Swarmops.Database } - public int GetMembershipCountForOrganizations(int[] organizationIds) + public int GetMembershipCountForOrganizations (int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -164,15 +165,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Count(PersonId) From Memberships WHERE Active=1 AND OrganizationId IN (" + - JoinIds(organizationIds) + ")", connection); + JoinIds (organizationIds) + ")", connection); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int GetMembershipCountForOrganizationsSince(int[] organizationIds, DateTime sinceWhen) + public int GetMembershipCountForOrganizationsSince (int[] organizationIds, DateTime sinceWhen) { if (organizationIds == null || organizationIds.Length == 0) { @@ -184,16 +185,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Count(PersonId) From Memberships WHERE Active=1 AND OrganizationId IN (" + - JoinIds(organizationIds) + ") AND MemberSince > '" + sinceWhen.ToString("yyyy-MM-dd HH:mm") + + JoinIds (organizationIds) + ") AND MemberSince > '" + sinceWhen.ToString ("yyyy-MM-dd HH:mm") + "'", connection); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int GetMemberCountForOrganizations(int[] organizationIds) + public int GetMemberCountForOrganizations (int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -205,15 +206,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Count(DISTINCT PersonId) From Memberships WHERE Active=1 AND OrganizationId IN (" + - JoinIds(organizationIds) + ")", connection); + JoinIds (organizationIds) + ")", connection); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int GetMemberCountForOrganizationsAndGeographies(int[] organizationIds, int[] geographyIds) + public int GetMemberCountForOrganizationsAndGeographies (int[] organizationIds, int[] geographyIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -229,37 +230,37 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "select count(DISTINCT People.PersonId) from Memberships, People WHERE " + "People.PersonId=Memberships.PersonId AND Memberships.Active=1 AND " + - "Memberships.OrganizationId IN (" + JoinIds(organizationIds) + ") AND " + - "People.GeographyId IN (" + JoinIds(geographyIds) + ")", connection); + "Memberships.OrganizationId IN (" + JoinIds (organizationIds) + ") AND " + + "People.GeographyId IN (" + JoinIds (geographyIds) + ")", connection); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - private static int[] ReadIntegersAtZeroFromDataReader(DbDataReader reader) + private static int[] ReadIntegersAtZeroFromDataReader (DbDataReader reader) { List result = new List(); while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); } - public Dictionary> GetMembershipsForPeople(int[] personIds) + public Dictionary> GetMembershipsForPeople (int[] personIds) { - return GetMembershipsForPeople(personIds, 0); + return GetMembershipsForPeople (personIds, 0); } - public Dictionary> GetMembershipsForPeople(int[] personIds, int gracePeriod) + public Dictionary> GetMembershipsForPeople (int[] personIds, int gracePeriod) { Dictionary> result = new Dictionary>(); @@ -273,7 +274,7 @@ namespace Swarmops.Database if (personIds.Length > 64) { - return GetMembershipsForPeopleOptimizedForLargeSets(personIds, gracePeriod); + return GetMembershipsForPeopleOptimizedForLargeSets (personIds, gracePeriod); } using (DbConnection connection = GetMySqlDbConnection()) @@ -285,24 +286,24 @@ namespace Swarmops.Database ? "Active=1" : " (Expires > DATE_ADD(NOW(),INTERVAL -" + gracePeriod + " Day) AND (Expires < DATE_ADD(DateTimeTerminated,INTERVAL 1 Day) OR Active=1))") - + " AND PersonId in (" + JoinIds(personIds) + ")"; + + " AND PersonId in (" + JoinIds (personIds) + ")"; - DbCommand command = GetDbCommand(commandString, connection); + DbCommand command = GetDbCommand (commandString, connection); command.CommandTimeout = 30; // If 30s is too short, something needs optimization. using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - BasicMembership membership = ReadMembershipFromDataReader(reader); + BasicMembership membership = ReadMembershipFromDataReader (reader); int personId = membership.PersonId; - if (!result.ContainsKey(personId)) + if (!result.ContainsKey (personId)) { result[personId] = new List(); } - result[personId].Add(ReadMembershipFromDataReader(reader)); + result[personId].Add (ReadMembershipFromDataReader (reader)); // Add to this person's list of memberships } } @@ -311,7 +312,7 @@ namespace Swarmops.Database return result; } - private Dictionary> GetMembershipsForPeopleOptimizedForLargeSets(int[] personIds, + private Dictionary> GetMembershipsForPeopleOptimizedForLargeSets (int[] personIds, int gracePeriod) { // This version is optimized for larger data sets. Rather than asking the database @@ -337,30 +338,30 @@ namespace Swarmops.Database { if (membership.Active) { - if (personIdLookup.ContainsKey(membership.PersonId)) + if (personIdLookup.ContainsKey (membership.PersonId)) { - if (!result.ContainsKey(membership.PersonId)) + if (!result.ContainsKey (membership.PersonId)) { result[membership.PersonId] = new List(); } - result[membership.PersonId].Add(membership); + result[membership.PersonId].Add (membership); } } else if (gracePeriod != 0) { //Within graceperiod? - if (membership.Expires.AddDays(gracePeriod) > DateTime.Now && - membership.DateTerminated.AddDays(1) > membership.Expires) + if (membership.Expires.AddDays (gracePeriod) > DateTime.Now && + membership.DateTerminated.AddDays (1) > membership.Expires) { - if (personIdLookup.ContainsKey(membership.PersonId)) + if (personIdLookup.ContainsKey (membership.PersonId)) { - if (!result.ContainsKey(membership.PersonId)) + if (!result.ContainsKey (membership.PersonId)) { result[membership.PersonId] = new List(); } - result[membership.PersonId].Add(membership); + result[membership.PersonId].Add (membership); } } } @@ -371,16 +372,16 @@ namespace Swarmops.Database } - public BasicMembership GetActiveMembership(int personId, int organizationId) + public BasicMembership GetActiveMembership (int personId, int organizationId) { if (personId == 0) { - throw new ArgumentOutOfRangeException("PersonId cannot be 0"); + throw new ArgumentOutOfRangeException ("PersonId cannot be 0"); } if (organizationId == 0) { - throw new ArgumentOutOfRangeException("OrganizationId cannot be 0"); + throw new ArgumentOutOfRangeException ("OrganizationId cannot be 0"); } List result = new List(); @@ -390,7 +391,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + membershipFieldSequence + " WHERE Active=1 AND PersonId=" + personId + " AND OrganizationId=" + organizationId, connection); @@ -398,21 +399,21 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadMembershipFromDataReader(reader); + return ReadMembershipFromDataReader (reader); } - throw new ArgumentException("No active membership for personid " + personId + - ", organizationid " + organizationId); + throw new ArgumentException ("No active membership for personid " + personId + + ", organizationid " + organizationId); } } } - public bool IsPersonMember(int personId, int organizationId) + public bool IsPersonMember (int personId, int organizationId) { try { - GetActiveMembership(personId, organizationId); + GetActiveMembership (personId, organizationId); return true; } catch (ArgumentException) @@ -422,52 +423,53 @@ namespace Swarmops.Database } - public BasicMembership GetMembership(int membershipId) + public BasicMembership GetMembership (int membershipId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + membershipFieldSequence + " WHERE MembershipId=" + membershipId, connection); + GetDbCommand ("SELECT " + membershipFieldSequence + " WHERE MembershipId=" + membershipId, + connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadMembershipFromDataReader(reader); + return ReadMembershipFromDataReader (reader); } - throw new ArgumentOutOfRangeException("No such MembershipId: " + membershipId); + throw new ArgumentOutOfRangeException ("No such MembershipId: " + membershipId); } } } - private static BasicMembership ReadMembershipFromDataReader(DbDataReader reader) + private static BasicMembership ReadMembershipFromDataReader (DbDataReader reader) { - int membershipId = reader.GetInt32(0); - int personId = reader.GetInt32(1); - int organizationId = reader.GetInt32(2); - bool active = reader.GetBoolean(3); - DateTime expires = reader.GetDateTime(4); - DateTime memberSince = reader.GetDateTime(5); - DateTime dateTerminated = reader.GetDateTime(6); + int membershipId = reader.GetInt32 (0); + int personId = reader.GetInt32 (1); + int organizationId = reader.GetInt32 (2); + bool active = reader.GetBoolean (3); + DateTime expires = reader.GetDateTime (4); + DateTime memberSince = reader.GetDateTime (5); + DateTime dateTerminated = reader.GetDateTime (6); // bool terminatedAsInvalid = reader.GetBoolean(7); Ignore this field for now - return new BasicMembership(membershipId, personId, organizationId, memberSince, expires, active, + return new BasicMembership (membershipId, personId, organizationId, memberSince, expires, active, dateTerminated); } - public BasicMembershipPaymentStatus GetMembershipPaymentStatus(int membershipId) + public BasicMembershipPaymentStatus GetMembershipPaymentStatus (int membershipId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId=" + membershipId + " ORDER BY StatusDateTime DESC LIMIT 1", connection); @@ -475,18 +477,18 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadMembershipPaymentStatusFromDataReader(reader); + return ReadMembershipPaymentStatusFromDataReader (reader); } // No payment status -- return undefined - return new BasicMembershipPaymentStatus(membershipId, MembershipPaymentStatus.Unknown, - new DateTime(1900, 1, 1)); + return new BasicMembershipPaymentStatus (membershipId, MembershipPaymentStatus.Unknown, + new DateTime (1900, 1, 1)); } } } - public Dictionary GetMembershipPaymentStatuses(int[] membershipIds) + public Dictionary GetMembershipPaymentStatuses (int[] membershipIds) { Dictionary retVal = new Dictionary(); if (membershipIds.Length == 0) @@ -496,21 +498,21 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId IN (" + - JoinIds(membershipIds) + ") ORDER BY StatusDateTime ASC ", connection); + JoinIds (membershipIds) + ") ORDER BY StatusDateTime ASC ", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - BasicMembershipPaymentStatus bms = ReadMembershipPaymentStatusFromDataReader(reader); - retVal[bms.MembershipId] = ReadMembershipPaymentStatusFromDataReader(reader); + BasicMembershipPaymentStatus bms = ReadMembershipPaymentStatusFromDataReader (reader); + retVal[bms.MembershipId] = ReadMembershipPaymentStatusFromDataReader (reader); } foreach (int i in membershipIds) { - if (!retVal.ContainsKey(i)) - retVal[i] = new BasicMembershipPaymentStatus(i, MembershipPaymentStatus.Unknown, - new DateTime(1900, 1, 1)); + if (!retVal.ContainsKey (i)) + retVal[i] = new BasicMembershipPaymentStatus (i, MembershipPaymentStatus.Unknown, + new DateTime (1900, 1, 1)); } return retVal; } @@ -518,122 +520,122 @@ namespace Swarmops.Database } - private BasicMembershipPaymentStatus ReadMembershipPaymentStatusFromDataReader(DbDataReader reader) + private BasicMembershipPaymentStatus ReadMembershipPaymentStatusFromDataReader (DbDataReader reader) { - int membershipId = reader.GetInt32(0); - int membershipPaymentStatusId = reader.GetInt32(1); - DateTime statusDateTime = reader.GetDateTime(2); + int membershipId = reader.GetInt32 (0); + int membershipPaymentStatusId = reader.GetInt32 (1); + DateTime statusDateTime = reader.GetDateTime (2); - return new BasicMembershipPaymentStatus(membershipId, (MembershipPaymentStatus) membershipPaymentStatusId, + return new BasicMembershipPaymentStatus (membershipId, (MembershipPaymentStatus) membershipPaymentStatusId, statusDateTime); } - public void SetMembershipExpires(int membershipId, DateTime newExpiry) + public void SetMembershipExpires (int membershipId, DateTime newExpiry) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetMembershipExpires", connection); + DbCommand command = GetDbCommand ("SetMembershipExpires", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "membershipId", membershipId); - AddParameterWithName(command, "expires", newExpiry); + AddParameterWithName (command, "membershipId", membershipId); + AddParameterWithName (command, "expires", newExpiry); command.ExecuteNonQuery(); } } - public void SetMembershipPaymentStatus(int membershipId, MembershipPaymentStatus paymentStatus, + public void SetMembershipPaymentStatus (int membershipId, MembershipPaymentStatus paymentStatus, DateTime statusDateTime) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetMembershipPaymentStatus", connection); + DbCommand command = GetDbCommand ("SetMembershipPaymentStatus", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "membershipId", membershipId); - AddParameterWithName(command, "paymentStatusId", (int) paymentStatus); - AddParameterWithName(command, "statusDateTime", statusDateTime); + AddParameterWithName (command, "membershipId", membershipId); + AddParameterWithName (command, "paymentStatusId", (int) paymentStatus); + AddParameterWithName (command, "statusDateTime", statusDateTime); command.ExecuteNonQuery(); } } - public int CreateMembership(int personId, int organizationId, DateTime expires) + public int CreateMembership (int personId, int organizationId, DateTime expires) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateMembership", connection); + DbCommand command = GetDbCommand ("CreateMembership", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "expires", expires); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "expires", expires); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int ImportMembership(int personId, int organizationId, DateTime memberSince, DateTime expires) + public int ImportMembership (int personId, int organizationId, DateTime memberSince, DateTime expires) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ImportMembership", connection); + DbCommand command = GetDbCommand ("ImportMembership", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "expires", expires); - AddParameterWithName(command, "membersince", expires); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "expires", expires); + AddParameterWithName (command, "membersince", expires); - int retval = Convert.ToInt32(command.ExecuteScalar()); + int retval = Convert.ToInt32 (command.ExecuteScalar()); return retval; } } - public void TerminateMembership(int membershipId) + public void TerminateMembership (int membershipId) { - TerminateMembership(membershipId, false); + TerminateMembership (membershipId, false); } - public void TerminateMembership(int membershipId, bool asInvalid) + public void TerminateMembership (int membershipId, bool asInvalid) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("TerminateMembership", connection); + DbCommand command = GetDbCommand ("TerminateMembership", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "membershipId", membershipId); - AddParameterWithName(command, "terminatedAsInvalid", asInvalid); + AddParameterWithName (command, "membershipId", membershipId); + AddParameterWithName (command, "terminatedAsInvalid", asInvalid); command.ExecuteNonQuery(); } } - public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime expiry) + public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime expiry) { - return GetExpiringMemberships(organization, expiry, expiry); + return GetExpiringMemberships (organization, expiry, expiry); } - public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime lowerBound, + public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound) { - return GetExpiringMemberships(organization, lowerBound, upperBound, DatabaseCondition.ActiveTrue); + return GetExpiringMemberships (organization, lowerBound, upperBound, DatabaseCondition.ActiveTrue); } - public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime lowerBound, + public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound, DatabaseCondition condition) { // Since I don't trust SQL Server to make correct date comparisons, especially given @@ -641,10 +643,10 @@ namespace Swarmops.Database // the comparison in code instead. This is a run-seldom function, anyway, and getting // some 50k records with four short unlinked fields isn't that expensive. - BasicMembership[] memberships = GetMemberships(organization, condition); + BasicMembership[] memberships = GetMemberships (organization, condition); DateTime minimumDateTime = lowerBound.Date; - DateTime maximumDateTime = upperBound.Date.AddDays(1); + DateTime maximumDateTime = upperBound.Date.AddDays (1); List result = new List(); @@ -655,7 +657,7 @@ namespace Swarmops.Database if (membership.Expires >= minimumDateTime && membership.Expires < maximumDateTime) { - result.Add(membership); + result.Add (membership); } } diff --git a/Database/Database-MotionAmendments.cs b/Database/Database-MotionAmendments.cs index abd876c0..27df793b 100644 --- a/Database/Database-MotionAmendments.cs +++ b/Database/Database-MotionAmendments.cs @@ -18,21 +18,21 @@ namespace Swarmops.Database "MotionAmendments.Carried " + // 10 "FROM MotionAmendments "; - private static BasicMotionAmendment ReadMotionAmendmentFromDataReader(IDataRecord reader) + private static BasicMotionAmendment ReadMotionAmendmentFromDataReader (IDataRecord reader) { - int motionAmendmentId = reader.GetInt32(0); - int motionId = reader.GetInt32(1); - int sequenceNumber = reader.GetInt32(2); - int submittedByPersonId = reader.GetInt32(3); - int createdByPersonId = reader.GetInt32(4); - DateTime createdDateTime = reader.GetDateTime(5); - string title = reader.GetString(6); - string text = reader.GetString(7); - string decisionPoint = reader.GetString(8); - bool open = reader.GetBoolean(9); - bool carried = reader.GetBoolean(10); + int motionAmendmentId = reader.GetInt32 (0); + int motionId = reader.GetInt32 (1); + int sequenceNumber = reader.GetInt32 (2); + int submittedByPersonId = reader.GetInt32 (3); + int createdByPersonId = reader.GetInt32 (4); + DateTime createdDateTime = reader.GetDateTime (5); + string title = reader.GetString (6); + string text = reader.GetString (7); + string decisionPoint = reader.GetString (8); + bool open = reader.GetBoolean (9); + bool carried = reader.GetBoolean (10); - return new BasicMotionAmendment(motionAmendmentId, motionId, sequenceNumber, submittedByPersonId, + return new BasicMotionAmendment (motionAmendmentId, motionId, sequenceNumber, submittedByPersonId, createdByPersonId, createdDateTime, title, text, decisionPoint, open, carried); } @@ -40,14 +40,14 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicMotionAmendment GetMotionAmendment(int motionAmendmentId) + public BasicMotionAmendment GetMotionAmendment (int motionAmendmentId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + motionAmendmentFieldSequence + "WHERE MotionAmendmentId=" + motionAmendmentId + ";", connection); @@ -55,15 +55,15 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadMotionAmendmentFromDataReader(reader); + return ReadMotionAmendmentFromDataReader (reader); } - throw new ArgumentException("Unknown MotionAmendment Id: " + motionAmendmentId); + throw new ArgumentException ("Unknown MotionAmendment Id: " + motionAmendmentId); } } } - public BasicMotionAmendment[] GetMotionAmendments(params object[] conditions) + public BasicMotionAmendment[] GetMotionAmendments (params object[] conditions) { List result = new List(); @@ -72,15 +72,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + motionAmendmentFieldSequence + ConstructWhereClause("MotionAmendments", conditions), + GetDbCommand ( + "SELECT" + motionAmendmentFieldSequence + ConstructWhereClause ("MotionAmendments", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMotionAmendmentFromDataReader(reader)); + result.Add (ReadMotionAmendmentFromDataReader (reader)); } return result.ToArray(); @@ -89,7 +89,7 @@ namespace Swarmops.Database } - public BasicMotionAmendment[] GetMotionAmendmentsForMeeting(int meetingId) + public BasicMotionAmendment[] GetMotionAmendmentsForMeeting (int meetingId) { List result = new List(); @@ -98,7 +98,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + motionAmendmentFieldSequence + " JOIN Motions ON (Motions.MotionId=MotionAmendments.MotionId) WHERE Motions.MeetingId=" + meetingId, connection); @@ -107,7 +107,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadMotionAmendmentFromDataReader(reader)); + result.Add (ReadMotionAmendmentFromDataReader (reader)); } return result.ToArray(); @@ -119,7 +119,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateMotionAmendment(int motionId, int submittingPersonId, int createdByPersonId, string title, + public int CreateMotionAmendment (int motionId, int submittingPersonId, int createdByPersonId, string title, string text, string decisionPoint) { DateTime now = DateTime.Now; @@ -128,18 +128,18 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateMotionAmendment", connection); + DbCommand command = GetDbCommand ("CreateMotionAmendment", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "motionId", motionId); - AddParameterWithName(command, "title", title); - AddParameterWithName(command, "text", text); - AddParameterWithName(command, "decisionPoint", decisionPoint); - AddParameterWithName(command, "submittingPersonId", submittingPersonId); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "createdDateTime", now); + AddParameterWithName (command, "motionId", motionId); + AddParameterWithName (command, "title", title); + AddParameterWithName (command, "text", text); + AddParameterWithName (command, "decisionPoint", decisionPoint); + AddParameterWithName (command, "submittingPersonId", submittingPersonId); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "createdDateTime", now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-Motions.cs b/Database/Database-Motions.cs index c3789fdf..04a3ca2e 100644 --- a/Database/Database-Motions.cs +++ b/Database/Database-Motions.cs @@ -17,28 +17,28 @@ namespace Swarmops.Database "ThreadUrl,Amended,SequenceNumber " + // 15-17 "FROM Motions "; - private static BasicMotion ReadMotionFromDataReader(IDataRecord reader) + private static BasicMotion ReadMotionFromDataReader (IDataRecord reader) { - int motionId = reader.GetInt32(0); - int meetingId = reader.GetInt32(1); - string designation = reader.GetString(2); - int submittedByPersonId = reader.GetInt32(3); - int createdByPersonId = reader.GetInt32(4); - DateTime createdDateTime = reader.GetDateTime(5); - int amendedByPersonId = reader.GetInt32(6); - DateTime amendedDateTime = reader.GetDateTime(7); - string title = reader.GetString(8); - string text = reader.GetString(9); - string amendedText = reader.GetString(10); - string decisionPoints = reader.GetString(11); - string amendedDecisionPoints = reader.GetString(12); - bool open = reader.GetBoolean(13); - bool passed = reader.GetBoolean(14); - string threadUrl = reader.GetString(15); - bool amended = reader.GetBoolean(16); - int sequenceNumber = reader.GetInt32(17); + int motionId = reader.GetInt32 (0); + int meetingId = reader.GetInt32 (1); + string designation = reader.GetString (2); + int submittedByPersonId = reader.GetInt32 (3); + int createdByPersonId = reader.GetInt32 (4); + DateTime createdDateTime = reader.GetDateTime (5); + int amendedByPersonId = reader.GetInt32 (6); + DateTime amendedDateTime = reader.GetDateTime (7); + string title = reader.GetString (8); + string text = reader.GetString (9); + string amendedText = reader.GetString (10); + string decisionPoints = reader.GetString (11); + string amendedDecisionPoints = reader.GetString (12); + bool open = reader.GetBoolean (13); + bool passed = reader.GetBoolean (14); + string threadUrl = reader.GetString (15); + bool amended = reader.GetBoolean (16); + int sequenceNumber = reader.GetInt32 (17); - return new BasicMotion(motionId, meetingId, sequenceNumber, designation, submittedByPersonId, + return new BasicMotion (motionId, meetingId, sequenceNumber, designation, submittedByPersonId, createdByPersonId, createdDateTime, amended, amendedByPersonId, amendedDateTime, title, text, amendedText, decisionPoints, amendedDecisionPoints, threadUrl, open, passed); } @@ -47,29 +47,29 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicMotion GetMotion(int motionId) + public BasicMotion GetMotion (int motionId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + motionFieldSequence + "WHERE MotionId=" + motionId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadMotionFromDataReader(reader); + return ReadMotionFromDataReader (reader); } - throw new ArgumentException("Unknown Motion Id: " + motionId); + throw new ArgumentException ("Unknown Motion Id: " + motionId); } } } - public BasicMotion[] GetMotions(params object[] conditions) + public BasicMotion[] GetMotions (params object[] conditions) { List result = new List(); @@ -78,14 +78,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + motionFieldSequence + ConstructWhereClause("Motions", conditions), connection); + GetDbCommand ( + "SELECT" + motionFieldSequence + ConstructWhereClause ("Motions", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadMotionFromDataReader(reader)); + result.Add (ReadMotionFromDataReader (reader)); } return result.ToArray(); @@ -97,7 +97,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateMotion(int meetingId, int submittingPersonId, int creatingPersonId, string title, string text, + public int CreateMotion (int meetingId, int submittingPersonId, int creatingPersonId, string title, string text, string decisionPoints) { DateTime now = DateTime.Now; @@ -106,18 +106,18 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateMotion", connection); + DbCommand command = GetDbCommand ("CreateMotion", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "meetingId", meetingId); - AddParameterWithName(command, "submittingPersonId", submittingPersonId); - AddParameterWithName(command, "creatingPersonId", creatingPersonId); - AddParameterWithName(command, "createdDateTime", now); - AddParameterWithName(command, "title", title); - AddParameterWithName(command, "text", text); - AddParameterWithName(command, "decisionPoints", decisionPoints); + AddParameterWithName (command, "meetingId", meetingId); + AddParameterWithName (command, "submittingPersonId", submittingPersonId); + AddParameterWithName (command, "creatingPersonId", creatingPersonId); + AddParameterWithName (command, "createdDateTime", now); + AddParameterWithName (command, "title", title); + AddParameterWithName (command, "text", text); + AddParameterWithName (command, "decisionPoints", decisionPoints); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-Newsletters.cs b/Database/Database-Newsletters.cs index e3613220..b94c6861 100644 --- a/Database/Database-Newsletters.cs +++ b/Database/Database-Newsletters.cs @@ -13,13 +13,13 @@ namespace Swarmops.Database /// /// The Report Id. /// An int array of PersonId. - public int[] GetSubscribersForNewsletterFeed(int newsletterFeedId) + public int[] GetSubscribersForNewsletterFeed (int newsletterFeedId) { Dictionary hash = new Dictionary(); // First, we get the newsletter feed we're working with. - BasicNewsletterFeed newsletterFeed = GetNewsletterFeed(newsletterFeedId); + BasicNewsletterFeed newsletterFeed = GetNewsletterFeed (newsletterFeedId); if (newsletterFeed.DefaultSubscribed) { @@ -31,16 +31,16 @@ namespace Swarmops.Database // Note that the individual preferences may have people not in the organization, // and so the final list may include subscribers that are nonmembers. - BasicOrganization[] orgTree = GetOrganizationTree(newsletterFeed.OrganizationId); + BasicOrganization[] orgTree = GetOrganizationTree (newsletterFeed.OrganizationId); List organizationIds = new List(); foreach (BasicOrganization org in orgTree) { - organizationIds.Add(org.Identity); + organizationIds.Add (org.Identity); } - int[] personIds = GetMembersForOrganizations(organizationIds.ToArray()); + int[] personIds = GetMembersForOrganizations (organizationIds.ToArray()); foreach (int personId in personIds) { @@ -55,7 +55,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId,Subscribed FROM NewsletterSubscriptions WHERE NewsletterFeedId=" + newsletterFeedId.ToString(), connection); @@ -63,8 +63,8 @@ namespace Swarmops.Database { while (reader.Read()) { - int personId = reader.GetInt32(0); - bool subscribed = reader.GetBoolean(1); + int personId = reader.GetInt32 (0); + bool subscribed = reader.GetBoolean (1); if (personId > 0) { @@ -83,7 +83,7 @@ namespace Swarmops.Database { if (hash[key]) { - result.Add(key); + result.Add (key); } } @@ -96,14 +96,14 @@ namespace Swarmops.Database /// /// The newsletter id. /// A Newsletter instance. - public BasicNewsletterFeed GetNewsletterFeed(int newsletterFeedId) + public BasicNewsletterFeed GetNewsletterFeed (int newsletterFeedId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT OrganizationId,DefaultSubscribed,Name FROM NewsletterFeeds WHERE NewsletterFeedId=" + newsletterFeedId.ToString(), connection); @@ -112,15 +112,15 @@ namespace Swarmops.Database { if (reader.Read()) { - int organizationId = reader.GetInt32(0); - bool defaultSubscribed = reader.GetBoolean(1); - string reportName = reader.GetString(2); + int organizationId = reader.GetInt32 (0); + bool defaultSubscribed = reader.GetBoolean (1); + string reportName = reader.GetString (2); - return new BasicNewsletterFeed(newsletterFeedId, organizationId, defaultSubscribed, reportName); + return new BasicNewsletterFeed (newsletterFeedId, organizationId, defaultSubscribed, reportName); } else { - throw new ArgumentException("No such newsletter feed id: " + newsletterFeedId.ToString()); + throw new ArgumentException ("No such newsletter feed id: " + newsletterFeedId.ToString()); } } } @@ -131,7 +131,7 @@ namespace Swarmops.Database /// /// /// - public BasicNewsletterFeed[] GetNewsletterFeedsForOrganization(int organizationId) + public BasicNewsletterFeed[] GetNewsletterFeedsForOrganization (int organizationId) { List feeds = new List(); @@ -140,7 +140,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT NewsletterFeedId, Name, DefaultSubscribed FROM NewsletterFeeds WHERE OrganizationId =" + organizationId.ToString(), connection); @@ -148,10 +148,10 @@ namespace Swarmops.Database { while (reader.Read()) { - int newsletterFeedId = reader.GetInt32(0); - string reportName = reader.GetString(1); - bool defaultSubscribed = reader.GetBoolean(2); - feeds.Add(new BasicNewsletterFeed(newsletterFeedId, organizationId, defaultSubscribed, + int newsletterFeedId = reader.GetInt32 (0); + string reportName = reader.GetString (1); + bool defaultSubscribed = reader.GetBoolean (2); + feeds.Add (new BasicNewsletterFeed (newsletterFeedId, organizationId, defaultSubscribed, reportName)); } } @@ -160,7 +160,7 @@ namespace Swarmops.Database return feeds.ToArray(); } - public Dictionary GetNewsletterFeedsForSubscriber(int personId) + public Dictionary GetNewsletterFeedsForSubscriber (int personId) { Dictionary subs = new Dictionary(); @@ -170,7 +170,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT NewsletterFeedId, Subscribed FROM NewsletterSubscriptions WHERE PersonId=" + personId.ToString(), connection); @@ -178,8 +178,8 @@ namespace Swarmops.Database { while (reader.Read()) { - int newsletterFeedId = reader.GetInt32(0); - bool subscribed = reader.GetBoolean(1); + int newsletterFeedId = reader.GetInt32 (0); + bool subscribed = reader.GetBoolean (1); subs[newsletterFeedId] = subscribed; } } @@ -188,33 +188,33 @@ namespace Swarmops.Database return subs; } - public void SetNewsletterSubscription(int personId, int newsletterFeedId, bool subscribed) + public void SetNewsletterSubscription (int personId, int newsletterFeedId, bool subscribed) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPersonNewsletterSubscription", connection); + DbCommand command = GetDbCommand ("SetPersonNewsletterSubscription", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "newsletterFeedId", newsletterFeedId); - AddParameterWithName(command, "subscribed", subscribed); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "newsletterFeedId", newsletterFeedId); + AddParameterWithName (command, "subscribed", subscribed); command.ExecuteNonQuery(); } } - public void DeletePersonNewsletterSubscriptions(int personId) // reverts to default + public void DeletePersonNewsletterSubscriptions (int personId) // reverts to default { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeletePersonNewsletterSubscriptions", connection); + DbCommand command = GetDbCommand ("DeletePersonNewsletterSubscriptions", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "personId", personId); command.ExecuteNonQuery(); } diff --git a/Database/Database-Optimizations.cs b/Database/Database-Optimizations.cs index d0e5faae..7c9bb9af 100644 --- a/Database/Database-Optimizations.cs +++ b/Database/Database-Optimizations.cs @@ -13,9 +13,9 @@ namespace Swarmops.Database /// /// Optimization function. /// - public Dictionary GetPeopleWhoDeclineLocalMail(int[] personIds) + public Dictionary GetPeopleWhoDeclineLocalMail (int[] personIds) { - Array.Sort(personIds); + Array.Sort (personIds); Dictionary result = new Dictionary(); // Step 0 - build a lookup table of the personIds @@ -39,7 +39,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId FROM NewsletterSubscriptions WHERE NewsletterFeedId=2 AND Subscribed=0", connection); @@ -47,9 +47,9 @@ namespace Swarmops.Database { while (reader.Read()) { - int personId = reader.GetInt32(0); + int personId = reader.GetInt32 (0); - if (lookup.ContainsKey(personId)) + if (lookup.ContainsKey (personId)) { result[personId] = false; } @@ -59,14 +59,15 @@ namespace Swarmops.Database // Step 2 - find people who have "NeverMail" set - int[] neverMailPersonIds = GetObjectsByOptionalData(ObjectType.Person, ObjectOptionalDataType.NeverMail, "1"); + int[] neverMailPersonIds = GetObjectsByOptionalData (ObjectType.Person, ObjectOptionalDataType.NeverMail, + "1"); // BasicPerson[] neverMailPeople = this.GetPeopleFromOptionalData(PersonOptionalDataKey.NeverMail, "1"); // For each of these people (they're not that many), if they are present in the personIds array, add them to the dictionary foreach (int neverMailPersonId in neverMailPersonIds) { - if (lookup.ContainsKey(neverMailPersonId)) + if (lookup.ContainsKey (neverMailPersonId)) { result[neverMailPersonId] = false; } @@ -85,7 +86,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PersonId,GeographyId FROM People", connection); @@ -93,8 +94,8 @@ namespace Swarmops.Database { while (reader.Read()) { - int personId = reader.GetInt32(0); - int geographyId = reader.GetInt32(1); + int personId = reader.GetInt32 (0); + int geographyId = reader.GetInt32 (1); result[personId] = geographyId; } @@ -105,7 +106,7 @@ namespace Swarmops.Database } - public Dictionary GetInternalPollVoteCountsPerGeography(int pollId) + public Dictionary GetInternalPollVoteCountsPerGeography (int pollId) { Dictionary result = new Dictionary(); @@ -114,7 +115,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select count(*) AS VoteCount,VoteGeographyId from InternalPollVotes where InternalPollId=" + pollId + " GROUP BY VoteGeographyId", connection); @@ -123,8 +124,8 @@ namespace Swarmops.Database { while (reader.Read()) { - int voteCount = reader.GetInt32(0); - int geographyId = reader.GetInt32(1); + int voteCount = reader.GetInt32 (0); + int geographyId = reader.GetInt32 (1); result[geographyId] = voteCount; } diff --git a/Database/Database-OptionalData.cs b/Database/Database-OptionalData.cs index 73c3daa9..36dc8d9c 100644 --- a/Database/Database-OptionalData.cs +++ b/Database/Database-OptionalData.cs @@ -17,10 +17,10 @@ namespace Swarmops.Database #region Select statements - reading data - public BasicObjectOptionalData GetObjectOptionalData(IHasIdentity forObject) + public BasicObjectOptionalData GetObjectOptionalData (IHasIdentity forObject) { Dictionary initialData = new Dictionary(); - ObjectType objectType = GetObjectTypeForObject(forObject); + ObjectType objectType = GetObjectTypeForObject (forObject); int objectId = forObject.Identity; using (DbConnection connection = GetMySqlDbConnection()) @@ -28,7 +28,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType + "' " + "AND ObjectOptionalData.ObjectId=" + objectId + ";", connection); @@ -36,14 +36,14 @@ namespace Swarmops.Database { while (reader.Read()) { - string objectOptionalDataTypeString = reader.GetString(2); - string data = reader.GetString(3); + string objectOptionalDataTypeString = reader.GetString (2); + string data = reader.GetString (3); try { ObjectOptionalDataType objectOptionalDataType = (ObjectOptionalDataType) - Enum.Parse(typeof (ObjectOptionalDataType), objectOptionalDataTypeString); + Enum.Parse (typeof (ObjectOptionalDataType), objectOptionalDataTypeString); initialData[objectOptionalDataType] = data; } @@ -53,13 +53,13 @@ namespace Swarmops.Database } } - return new BasicObjectOptionalData(objectType, objectId, initialData); + return new BasicObjectOptionalData (objectType, objectId, initialData); } } } - public int[] GetObjectsByOptionalData(ObjectType objectType, ObjectOptionalDataType dataType, string data) + public int[] GetObjectsByOptionalData (ObjectType objectType, ObjectOptionalDataType dataType, string data) { List objectIds = new List(); @@ -68,16 +68,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType + "' " + "AND ObjectOptionalDataTypes.Name='" + dataType + "' " + - "AND ObjectOptionalData.Data='" + data.Replace("'", "''") + "';", connection); + "AND ObjectOptionalData.Data='" + data.Replace ("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - objectIds.Add(reader.GetInt32(1)); + objectIds.Add (reader.GetInt32 (1)); } return objectIds.ToArray(); @@ -86,7 +86,7 @@ namespace Swarmops.Database } - private static ObjectType GetObjectTypeForObject(IHasIdentity objectToIdentify) + private static ObjectType GetObjectTypeForObject (IHasIdentity objectToIdentify) { //string objectTypeString = objectToIdentify.GetType().ToString(); @@ -100,7 +100,7 @@ namespace Swarmops.Database // At this point, we should be able to cast the string to an ObjectType enum try { - return (ObjectType) Enum.Parse(typeof (ObjectType), objectTypeString); + return (ObjectType) Enum.Parse (typeof (ObjectType), objectTypeString); } catch { @@ -110,7 +110,7 @@ namespace Swarmops.Database { try { - return (ObjectType) Enum.Parse(typeof (ObjectType), parentType.Name); + return (ObjectType) Enum.Parse (typeof (ObjectType), parentType.Name); } catch { @@ -118,27 +118,27 @@ namespace Swarmops.Database } } } - throw new InvalidCastException("GetObjectTypeForObject could not identify object of type " + - objectToIdentify.GetType().Name); + throw new InvalidCastException ("GetObjectTypeForObject could not identify object of type " + + objectToIdentify.GetType().Name); } #endregion #region Stored procedures for modifying data - public void SetObjectOptionalData(IHasIdentity thisObject, ObjectOptionalDataType dataType, string data) + public void SetObjectOptionalData (IHasIdentity thisObject, ObjectOptionalDataType dataType, string data) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetObjectOptionalData", connection); + DbCommand command = GetDbCommand ("SetObjectOptionalData", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "objectType", GetObjectTypeForObject(thisObject).ToString()); - AddParameterWithName(command, "objectId", thisObject.Identity); - AddParameterWithName(command, "objectOptionalDataType", dataType.ToString()); - AddParameterWithName(command, "data", data); + AddParameterWithName (command, "objectType", GetObjectTypeForObject (thisObject).ToString()); + AddParameterWithName (command, "objectId", thisObject.Identity); + AddParameterWithName (command, "objectOptionalDataType", dataType.ToString()); + AddParameterWithName (command, "data", data); command.ExecuteNonQuery(); } diff --git a/Database/Database-OrganizationFinancialAccounts.cs b/Database/Database-OrganizationFinancialAccounts.cs index a737c431..ed30a499 100644 --- a/Database/Database-OrganizationFinancialAccounts.cs +++ b/Database/Database-OrganizationFinancialAccounts.cs @@ -12,7 +12,7 @@ namespace Swarmops.Database #region Select statements - reading data - public int GetOrganizationFinancialAccountId(int organizationId, + public int GetOrganizationFinancialAccountId (int organizationId, OrganizationFinancialAccountType organizationFinancialAccountType) { using (DbConnection connection = GetMySqlDbConnection()) @@ -20,7 +20,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + organizationFinancialAccountsDataFieldSequence + "WHERE OrganizationFinancialAccountTypes.Name='" + organizationFinancialAccountType + "' " + "AND OrganizationFinancialAccounts.Organizationid=" + organizationId + ";", connection); @@ -31,7 +31,7 @@ namespace Swarmops.Database { // account Id is third in select list, just return it - return reader.GetInt32(2); + return reader.GetInt32 (2); } // TODO: Throw instead if requested account not found? @@ -109,19 +109,19 @@ namespace Swarmops.Database #region Stored procedures for modifying data - public void SetOrganizationFinancialAccountId(int organizationId, OrganizationFinancialAccountType accountType, + public void SetOrganizationFinancialAccountId (int organizationId, OrganizationFinancialAccountType accountType, int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOrganizationFinancialAccount", connection); + DbCommand command = GetDbCommand ("SetOrganizationFinancialAccount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "organizationFinancialAccountTypeName", accountType.ToString()); - AddParameterWithName(command, "financialAccountId", financialAccountId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "organizationFinancialAccountTypeName", accountType.ToString()); + AddParameterWithName (command, "financialAccountId", financialAccountId); command.ExecuteNonQuery(); } diff --git a/Database/Database-Organizations.cs b/Database/Database-Organizations.cs index 795a8c08..2f6ac50c 100644 --- a/Database/Database-Organizations.cs +++ b/Database/Database-Organizations.cs @@ -16,28 +16,28 @@ namespace Swarmops.Database "DefaultCountryId " + // 10 "FROM Organizations "; - private static BasicOrganization ReadOrganizationFromDataReader(DbDataReader reader) + private static BasicOrganization ReadOrganizationFromDataReader (DbDataReader reader) { - int organizationId = reader.GetInt32(0); - int parentOrganizationId = reader.GetInt32(1); - string name = reader.GetString(2); - string nameInternational = reader.GetString(3); - string nameShort = reader.GetString(4); - string domain = reader.GetString(5); - string mailPrefix = reader.GetString(6); - int anchorGeographyId = reader.GetInt32(7); - bool acceptsMembers = reader.GetBoolean(8); - bool autoAssignNewMembers = reader.GetBoolean(9); - int defaultCountryId = reader.GetInt32(10); + int organizationId = reader.GetInt32 (0); + int parentOrganizationId = reader.GetInt32 (1); + string name = reader.GetString (2); + string nameInternational = reader.GetString (3); + string nameShort = reader.GetString (4); + string domain = reader.GetString (5); + string mailPrefix = reader.GetString (6); + int anchorGeographyId = reader.GetInt32 (7); + bool acceptsMembers = reader.GetBoolean (8); + bool autoAssignNewMembers = reader.GetBoolean (9); + int defaultCountryId = reader.GetInt32 (10); - return new BasicOrganization(organizationId, parentOrganizationId, name, nameInternational, nameShort, + return new BasicOrganization (organizationId, parentOrganizationId, name, nameInternational, nameShort, domain, mailPrefix, anchorGeographyId, acceptsMembers, autoAssignNewMembers, defaultCountryId); } #endregion - public int CreateOrganization(int ParentOrganizationId, string NameInternational, string Name, string NameShort, + public int CreateOrganization (int ParentOrganizationId, string NameInternational, string Name, string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId) { @@ -45,30 +45,30 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateOrganization", connection); + DbCommand command = GetDbCommand ("CreateOrganization", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "pParentOrganizationId", ParentOrganizationId); - AddParameterWithName(command, "pNameInternational", NameInternational); - AddParameterWithName(command, "pName", Name); - AddParameterWithName(command, "pNameShort", NameShort); - AddParameterWithName(command, "pDomain", Domain); - AddParameterWithName(command, "pMailPrefix", MailPrefix); - AddParameterWithName(command, "pAnchorGeographyId", AnchorGeographyId); - AddParameterWithName(command, "pAcceptsMembers", AcceptsMembers); - AddParameterWithName(command, "pAutoAssignNewMembers", AutoAssignNewMembers); - AddParameterWithName(command, "pDefaultCountryId", DefaultCountryId); + AddParameterWithName (command, "pParentOrganizationId", ParentOrganizationId); + AddParameterWithName (command, "pNameInternational", NameInternational); + AddParameterWithName (command, "pName", Name); + AddParameterWithName (command, "pNameShort", NameShort); + AddParameterWithName (command, "pDomain", Domain); + AddParameterWithName (command, "pMailPrefix", MailPrefix); + AddParameterWithName (command, "pAnchorGeographyId", AnchorGeographyId); + AddParameterWithName (command, "pAcceptsMembers", AcceptsMembers); + AddParameterWithName (command, "pAutoAssignNewMembers", AutoAssignNewMembers); + AddParameterWithName (command, "pDefaultCountryId", DefaultCountryId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void DeleteOrganization(int OrganizationId) + public void DeleteOrganization (int OrganizationId) { int deletedOrganizationsID = 98; - BasicOrganization org = GetOrganization(OrganizationId); + BasicOrganization org = GetOrganization (OrganizationId); //Delete is done by setting parent ID to deletedOrganizationsID - UpdateOrganization( + UpdateOrganization ( deletedOrganizationsID, org.NameInternational, org.Name, @@ -82,7 +82,8 @@ namespace Swarmops.Database OrganizationId); } - public void UpdateOrganization(int ParentOrganizationId, string NameInternational, string Name, string NameShort, + public void UpdateOrganization (int ParentOrganizationId, string NameInternational, string Name, + string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId, int OrganizationId) { @@ -90,33 +91,33 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("UpdateOrganization", connection); + DbCommand command = GetDbCommand ("UpdateOrganization", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_ParentOrganizationId", ParentOrganizationId); - AddParameterWithName(command, "p_NameIntl", NameInternational == null ? "" : NameInternational); - AddParameterWithName(command, "p_Name", Name == null ? "" : Name); - AddParameterWithName(command, "p_NameShort", NameShort == null ? "" : NameShort); - AddParameterWithName(command, "p_Domain", Domain == null ? "" : Domain); - AddParameterWithName(command, "p_MailPrefix", MailPrefix == null ? "" : MailPrefix); - AddParameterWithName(command, "p_AnchorGeographyId", AnchorGeographyId); - AddParameterWithName(command, "p_AcceptsMembers", AcceptsMembers); - AddParameterWithName(command, "p_AutoAssignNewMembers", AutoAssignNewMembers); - AddParameterWithName(command, "p_DefaultCountryId", DefaultCountryId); - AddParameterWithName(command, "p_OrganizationId", OrganizationId); + AddParameterWithName (command, "p_ParentOrganizationId", ParentOrganizationId); + AddParameterWithName (command, "p_NameIntl", NameInternational == null ? "" : NameInternational); + AddParameterWithName (command, "p_Name", Name == null ? "" : Name); + AddParameterWithName (command, "p_NameShort", NameShort == null ? "" : NameShort); + AddParameterWithName (command, "p_Domain", Domain == null ? "" : Domain); + AddParameterWithName (command, "p_MailPrefix", MailPrefix == null ? "" : MailPrefix); + AddParameterWithName (command, "p_AnchorGeographyId", AnchorGeographyId); + AddParameterWithName (command, "p_AcceptsMembers", AcceptsMembers); + AddParameterWithName (command, "p_AutoAssignNewMembers", AutoAssignNewMembers); + AddParameterWithName (command, "p_DefaultCountryId", DefaultCountryId); + AddParameterWithName (command, "p_OrganizationId", OrganizationId); command.ExecuteNonQuery(); } } - public BasicOrganization GetOrganization(int organizationId) + public BasicOrganization GetOrganization (int organizationId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId=" + organizationId, connection); @@ -124,16 +125,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadOrganizationFromDataReader(reader); + return ReadOrganizationFromDataReader (reader); } - throw new ArgumentException("No such OrganizationId: " + organizationId); + throw new ArgumentException ("No such OrganizationId: " + organizationId); } } } - public int[] GetOrganizationsIdsInGeographies(BasicGeography[] nodes) + public int[] GetOrganizationsIdsInGeographies (BasicGeography[] nodes) { if (nodes == null || nodes.Length == 0) { @@ -144,14 +145,14 @@ namespace Swarmops.Database foreach (BasicGeography node in nodes) { - nodeIdList.Add(node.GeographyId); + nodeIdList.Add (node.GeographyId); } - return GetOrganizationIdsInGeographies(nodeIdList.ToArray()); + return GetOrganizationIdsInGeographies (nodeIdList.ToArray()); } - public int[] GetOrganizationIdsInGeographies(int[] nodeIds) + public int[] GetOrganizationIdsInGeographies (int[] nodeIds) { if (nodeIds == null || nodeIds.Length == 0) { @@ -165,35 +166,35 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT OrganizationId FROM Organizations Where Active=1 AND AnchorGeographyId in (" + - JoinIds(nodeIds) + + JoinIds (nodeIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - resultKeys[reader.GetInt32(0)] = true; + resultKeys[reader.GetInt32 (0)] = true; } } command = - GetDbCommand( + GetDbCommand ( "SELECT OrganizationId FROM OrganizationUptakeGeographies where GeographyId in (" + - JoinIds(nodeIds) + ")", connection); + JoinIds (nodeIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - resultKeys[reader.GetInt32(0)] = true; + resultKeys[reader.GetInt32 (0)] = true; } } } int[] resultArray = new int[resultKeys.Keys.Count]; - resultKeys.Keys.CopyTo(resultArray, 0); + resultKeys.Keys.CopyTo (resultArray, 0); return resultArray; } @@ -207,7 +208,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT OrganizationId,GeographyId FROM OrganizationUptakeGeographies", connection); @@ -215,13 +216,13 @@ namespace Swarmops.Database { while (reader.Read()) { - int uptakeOrgId = reader.GetInt32(0); - int uptakeGeoId = reader.GetInt32(1); - if (!result.ContainsKey(uptakeOrgId)) + int uptakeOrgId = reader.GetInt32 (0); + int uptakeGeoId = reader.GetInt32 (1); + if (!result.ContainsKey (uptakeOrgId)) { result[uptakeOrgId] = new List(); } - result[uptakeOrgId].Add(uptakeGeoId); + result[uptakeOrgId].Add (uptakeGeoId); } } } @@ -229,19 +230,19 @@ namespace Swarmops.Database return result; } - public int[] GetOrganizationUptakeGeographyIds(int organizationId) + public int[] GetOrganizationUptakeGeographyIds (int organizationId) { List result = new List(); - BasicOrganization basicOrg = GetOrganization(organizationId); - result.Add(basicOrg.AnchorGeographyId); + BasicOrganization basicOrg = GetOrganization (organizationId); + result.Add (basicOrg.AnchorGeographyId); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT GeographyId FROM OrganizationUptakeGeographies WHERE OrganizationId=" + organizationId, connection); @@ -249,11 +250,11 @@ namespace Swarmops.Database { while (reader.Read()) { - int uptakeGeoId = reader.GetInt32(0); + int uptakeGeoId = reader.GetInt32 (0); if (uptakeGeoId != basicOrg.AnchorGeographyId) { - result.Add(uptakeGeoId); + result.Add (uptakeGeoId); } } } @@ -262,7 +263,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicUptakeGeography[] GetOrganizationUptakeGeographies(int organizationId, bool others) + public BasicUptakeGeography[] GetOrganizationUptakeGeographies (int organizationId, bool others) { List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -270,7 +271,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT OrganizationId, GeographyId FROM OrganizationUptakeGeographies WHERE OrganizationId" + (others ? "<>" : "=") + organizationId, connection); @@ -279,7 +280,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(new BasicUptakeGeography(reader.GetInt32(0), reader.GetInt32(1))); + result.Add (new BasicUptakeGeography (reader.GetInt32 (0), reader.GetInt32 (1))); } } } @@ -287,32 +288,32 @@ namespace Swarmops.Database return result.ToArray(); } - public void AddOrgUptakeGeography(int OrganizationId, int GeographyId) + public void AddOrgUptakeGeography (int OrganizationId, int GeographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateUptakeGeography", connection); + DbCommand command = GetDbCommand ("CreateUptakeGeography", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_OrganizationId", OrganizationId); - AddParameterWithName(command, "p_GeographyId", GeographyId); + AddParameterWithName (command, "p_OrganizationId", OrganizationId); + AddParameterWithName (command, "p_GeographyId", GeographyId); command.ExecuteNonQuery(); } } - public void DeleteOrgUptakeGeography(int OrganizationId, int GeographyId) + public void DeleteOrgUptakeGeography (int OrganizationId, int GeographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteUptakeGeography", connection); + DbCommand command = GetDbCommand ("DeleteUptakeGeography", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_OrganizationId", OrganizationId); - AddParameterWithName(command, "p_GeographyId", GeographyId); + AddParameterWithName (command, "p_OrganizationId", OrganizationId); + AddParameterWithName (command, "p_GeographyId", GeographyId); command.ExecuteNonQuery(); } } @@ -326,7 +327,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + organizationFieldSequence + " WHERE Active=1 AND ParentOrganizationId >= 0", connection); @@ -334,7 +335,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadOrganizationFromDataReader(reader)); + result.Add (ReadOrganizationFromDataReader (reader)); } } } @@ -343,7 +344,7 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizations(int[] organizationIds) + public BasicOrganization[] GetOrganizations (int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -357,16 +358,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId IN (" + - JoinIds(organizationIds) + + JoinIds (organizationIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadOrganizationFromDataReader(reader)); + result.Add (ReadOrganizationFromDataReader (reader)); } } } @@ -396,7 +397,7 @@ namespace Swarmops.Database if (organization.ParentOrganizationId >= 0) { List newList = new List(); - newList.Add(organization); + newList.Add (organization); result[organization.OrganizationId] = newList; } @@ -408,7 +409,7 @@ namespace Swarmops.Database { if (organization.ParentOrganizationId > 0) { - result[organization.ParentOrganizationId].Add(organization); + result[organization.ParentOrganizationId].Add (organization); } } @@ -416,17 +417,17 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizationTree(int startOrganizationId) + public BasicOrganization[] GetOrganizationTree (int startOrganizationId) { Dictionary> organizations = GetHashedOrganizations(); - return GetOrganizationTree(organizations, startOrganizationId, 0); + return GetOrganizationTree (organizations, startOrganizationId, 0); } - public Dictionary GetOrganizationHashtable(int startOrganizationId) + public Dictionary GetOrganizationHashtable (int startOrganizationId) { - BasicOrganization[] organizations = GetOrganizationTree(startOrganizationId); + BasicOrganization[] organizations = GetOrganizationTree (startOrganizationId); Dictionary result = new Dictionary(); @@ -439,7 +440,7 @@ namespace Swarmops.Database } - private BasicOrganization[] GetOrganizationTree(Dictionary> organizations, + private BasicOrganization[] GetOrganizationTree (Dictionary> organizations, int startOrganizationId, int generation) { List result = new List(); @@ -450,19 +451,19 @@ namespace Swarmops.Database { if (organization.OrganizationId != startOrganizationId) { - result.Add(organization); + result.Add (organization); // new Organization(organization.OrganizationId, organization.ParentOrganizationId, organization.Name, generation + 1)); // Add recursively - BasicOrganization[] children = GetOrganizationTree(organizations, organization.OrganizationId, + BasicOrganization[] children = GetOrganizationTree (organizations, organization.OrganizationId, generation + 1); if (children.Length > 0) { foreach (BasicOrganization child in children) { - result.Add(child); + result.Add (child); } } } @@ -470,7 +471,7 @@ namespace Swarmops.Database { // The top parent is special and should be added; the others shouldn't - result.Add(organization); + result.Add (organization); // (new Organization(organization.OrganizationId, organization.ParentOrganizationId, organization.Name, generation)); } } @@ -479,7 +480,7 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizationLine(int leafOrganizationId) + public BasicOrganization[] GetOrganizationLine (int leafOrganizationId) { List result = new List(); @@ -491,7 +492,7 @@ namespace Swarmops.Database while (currentOrganization.OrganizationId > 0) { - result.Add(currentOrganization); + result.Add (currentOrganization); if (currentOrganization.ParentOrganizationId > 0) { diff --git a/Database/Database-OutboundCommRecipients.cs b/Database/Database-OutboundCommRecipients.cs index e7c37bb6..3e92545f 100644 --- a/Database/Database-OutboundCommRecipients.cs +++ b/Database/Database-OutboundCommRecipients.cs @@ -15,19 +15,19 @@ namespace Swarmops.Database "FailReasonId " + // 5 "FROM OutboundCommRecipients "; - private BasicOutboundCommRecipient ReadOutboundCommRecipientFromDataReader(IDataRecord reader) + private BasicOutboundCommRecipient ReadOutboundCommRecipientFromDataReader (IDataRecord reader) // Not static -- accesses cache, requiring connection strings { - int outboundCommRecipientId = reader.GetInt32(0); - int outboundCommId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - bool open = reader.GetBoolean(3); - bool success = reader.GetBoolean(4); - int failReasonId = reader.GetInt32(5); + int outboundCommRecipientId = reader.GetInt32 (0); + int outboundCommId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + bool open = reader.GetBoolean (3); + bool success = reader.GetBoolean (4); + int failReasonId = reader.GetInt32 (5); - string failReason = GetCachedFailReasonName(failReasonId); + string failReason = GetCachedFailReasonName (failReasonId); - return new BasicOutboundCommRecipient(outboundCommRecipientId, outboundCommId, personId, open, success, + return new BasicOutboundCommRecipient (outboundCommRecipientId, outboundCommId, personId, open, success, failReason); } @@ -35,31 +35,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicOutboundCommRecipient GetOutboundCommRecipient(int outboundCommRecipientId) + public BasicOutboundCommRecipient GetOutboundCommRecipient (int outboundCommRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + outboundCommRecipientFieldSequence + - "WHERE OutboundCommRecipientId=" + outboundCommRecipientId, + GetDbCommand ("SELECT" + outboundCommRecipientFieldSequence + + "WHERE OutboundCommRecipientId=" + outboundCommRecipientId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadOutboundCommRecipientFromDataReader(reader); + return ReadOutboundCommRecipientFromDataReader (reader); } - throw new ArgumentException("No such OutboundCommRecipientId:" + outboundCommRecipientId); + throw new ArgumentException ("No such OutboundCommRecipientId:" + outboundCommRecipientId); } } } - public BasicOutboundCommRecipient[] GetOutboundCommRecipients(params object[] conditions) + public BasicOutboundCommRecipient[] GetOutboundCommRecipients (params object[] conditions) { List result = new List(); @@ -68,15 +68,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + outboundCommRecipientFieldSequence + - ConstructWhereClause("OutboundCommRecipients", conditions), connection); + ConstructWhereClause ("OutboundCommRecipients", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadOutboundCommRecipientFromDataReader(reader)); + result.Add (ReadOutboundCommRecipientFromDataReader (reader)); } return result.ToArray(); @@ -90,7 +90,7 @@ namespace Swarmops.Database private static Dictionary _failReasonCache; - protected string GetCachedFailReasonName(int failReasonId) + protected string GetCachedFailReasonName (int failReasonId) { if (_failReasonCache == null) { @@ -98,7 +98,7 @@ namespace Swarmops.Database _failReasonCache[0] = null; // special case - no error } - if (_failReasonCache.ContainsKey(failReasonId)) + if (_failReasonCache.ContainsKey (failReasonId)) { return _failReasonCache[failReasonId]; } @@ -108,18 +108,18 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM FailReasons WHERE FailReasonId=" + failReasonId, + GetDbCommand ("SELECT Name FROM FailReasons WHERE FailReasonId=" + failReasonId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - _failReasonCache[failReasonId] = reader.GetString(0); + _failReasonCache[failReasonId] = reader.GetString (0); return _failReasonCache[failReasonId]; } - throw new ArgumentException("No such FailReasonId:" + failReasonId); + throw new ArgumentException ("No such FailReasonId:" + failReasonId); } } } @@ -128,53 +128,53 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateOutboundCommRecipient(int outboundCommId, int personId) + public int CreateOutboundCommRecipient (int outboundCommId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundCommRecipient", connection); + DbCommand command = GetDbCommand ("CreateOutboundCommRecipient", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommId", outboundCommId); - AddParameterWithName(command, "personId", personId); + AddParameterWithName (command, "outboundCommId", outboundCommId); + AddParameterWithName (command, "personId", personId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetOutboundCommRecipientClosed(int outboundCommRecipientId) + public void SetOutboundCommRecipientClosed (int outboundCommRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundCommRecipientClosed", connection); + DbCommand command = GetDbCommand ("SetOutboundCommRecipientClosed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommRecipientId", outboundCommRecipientId); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "outboundCommRecipientId", outboundCommRecipientId); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); command.ExecuteNonQuery(); } } - public int SetOutboundCommRecipientFailed(int outboundCommRecipientId, string failReason) + public int SetOutboundCommRecipientFailed (int outboundCommRecipientId, string failReason) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundCommRecipientFailed", connection); + DbCommand command = GetDbCommand ("SetOutboundCommRecipientFailed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommRecipientId", outboundCommRecipientId); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); - AddParameterWithName(command, "failReason", failReason); + AddParameterWithName (command, "outboundCommRecipientId", outboundCommRecipientId); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "failReason", failReason); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-OutboundComms.cs b/Database/Database-OutboundComms.cs index 00c23b39..d51a2ad4 100644 --- a/Database/Database-OutboundComms.cs +++ b/Database/Database-OutboundComms.cs @@ -18,37 +18,37 @@ namespace Swarmops.Database "RecipientCount,RecipientsSuccess,RecipientsFail " + // 15-17 "FROM OutboundComms "; - private BasicOutboundComm ReadOutboundCommFromDataReader(IDataRecord reader) + private BasicOutboundComm ReadOutboundCommFromDataReader (IDataRecord reader) // Not static -- accesses cache, requiring connection strings { - int outboundCommId = reader.GetInt32(0); - int senderPersonId = reader.GetInt32(1); - int fromPersonId = reader.GetInt32(2); - int organizationId = reader.GetInt32(3); - DateTime createdDateTime = reader.GetDateTime(4); + int outboundCommId = reader.GetInt32 (0); + int senderPersonId = reader.GetInt32 (1); + int fromPersonId = reader.GetInt32 (2); + int organizationId = reader.GetInt32 (3); + DateTime createdDateTime = reader.GetDateTime (4); - int resolverClassId = reader.GetInt32(5); - // Resolve to class name -- cached call more efficient than Join in Select - string recipientDataXml = reader.GetString(6); // Interpreted by ResolverClass - bool resolved = reader.GetBoolean(7); - DateTime resolvedDateTime = reader.GetDateTime(8); - OutboundCommPriority priority = (OutboundCommPriority) reader.GetInt32(9); + int resolverClassId = reader.GetInt32 (5); + // Resolve to class name -- cached call more efficient than Join in Select + string recipientDataXml = reader.GetString (6); // Interpreted by ResolverClass + bool resolved = reader.GetBoolean (7); + DateTime resolvedDateTime = reader.GetDateTime (8); + OutboundCommPriority priority = (OutboundCommPriority) reader.GetInt32 (9); - int transmitterClassId = reader.GetInt32(10); - // Resolve to class name -- cached call more efficient than Join in Select - string payloadXml = reader.GetString(11); // Interpreted by TransmitterClass - bool open = reader.GetBoolean(12); - DateTime startTransmitDateTime = reader.GetDateTime(13); - DateTime closedDateTime = reader.GetDateTime(14); + int transmitterClassId = reader.GetInt32 (10); + // Resolve to class name -- cached call more efficient than Join in Select + string payloadXml = reader.GetString (11); // Interpreted by TransmitterClass + bool open = reader.GetBoolean (12); + DateTime startTransmitDateTime = reader.GetDateTime (13); + DateTime closedDateTime = reader.GetDateTime (14); - int recipientCount = reader.GetInt32(15); // Set by resolver - int recipientSuccessCount = reader.GetInt32(16); - int recipientFailCount = reader.GetInt32(17); + int recipientCount = reader.GetInt32 (15); // Set by resolver + int recipientSuccessCount = reader.GetInt32 (16); + int recipientFailCount = reader.GetInt32 (17); // TODO: resolve resolverClass, transmitterClass - string resolverClass = GetCachedResolverClassName(resolverClassId); - string transmitterClass = GetCachedTransmitterClassName(transmitterClassId); + string resolverClass = GetCachedResolverClassName (resolverClassId); + string transmitterClass = GetCachedTransmitterClassName (transmitterClassId); return new BasicOutboundComm (outboundCommId, senderPersonId, fromPersonId, organizationId, createdDateTime, @@ -61,31 +61,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicOutboundComm GetOutboundComm(int outboundCommId) + public BasicOutboundComm GetOutboundComm (int outboundCommId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + outboundCommFieldSequence + - "WHERE OutboundCommId=" + outboundCommId, + GetDbCommand ("SELECT" + outboundCommFieldSequence + + "WHERE OutboundCommId=" + outboundCommId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadOutboundCommFromDataReader(reader); + return ReadOutboundCommFromDataReader (reader); } - throw new ArgumentException("No such OutboundCommId:" + outboundCommId); + throw new ArgumentException ("No such OutboundCommId:" + outboundCommId); } } } - public BasicOutboundComm[] GetOutboundComms(params object[] conditions) + public BasicOutboundComm[] GetOutboundComms (params object[] conditions) { List result = new List(); @@ -94,15 +94,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + outboundCommFieldSequence + ConstructWhereClause("OutboundComms", conditions) + + GetDbCommand ( + "SELECT" + outboundCommFieldSequence + ConstructWhereClause ("OutboundComms", conditions) + " ORDER BY Priority ASC", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadOutboundCommFromDataReader(reader)); + result.Add (ReadOutboundCommFromDataReader (reader)); } return result.ToArray(); @@ -117,7 +117,7 @@ namespace Swarmops.Database private static Dictionary _resolverClassCache; private static Dictionary _transmitterClassCache; - protected string GetCachedResolverClassName(int resolverClassId) + protected string GetCachedResolverClassName (int resolverClassId) { if (_resolverClassCache == null) { @@ -125,7 +125,7 @@ namespace Swarmops.Database _resolverClassCache[0] = null; // special case for resolvers } - if (_resolverClassCache.ContainsKey(resolverClassId)) + if (_resolverClassCache.ContainsKey (resolverClassId)) { return _resolverClassCache[resolverClassId]; } @@ -135,30 +135,30 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM ResolverClasses WHERE ResolverClassId=" + resolverClassId, + GetDbCommand ("SELECT Name FROM ResolverClasses WHERE ResolverClassId=" + resolverClassId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - _resolverClassCache[resolverClassId] = reader.GetString(0); + _resolverClassCache[resolverClassId] = reader.GetString (0); return _resolverClassCache[resolverClassId]; } - throw new ArgumentException("No such ResolverClassId:" + resolverClassId); + throw new ArgumentException ("No such ResolverClassId:" + resolverClassId); } } } - protected string GetCachedTransmitterClassName(int transmitterClassId) + protected string GetCachedTransmitterClassName (int transmitterClassId) { if (_transmitterClassCache == null) { _transmitterClassCache = new Dictionary(); } - if (_transmitterClassCache.ContainsKey(transmitterClassId)) + if (_transmitterClassCache.ContainsKey (transmitterClassId)) { return _transmitterClassCache[transmitterClassId]; } @@ -168,18 +168,18 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM TransmitterClasses WHERE TransmitterClassId=" + transmitterClassId, + GetDbCommand ("SELECT Name FROM TransmitterClasses WHERE TransmitterClassId=" + transmitterClassId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - _transmitterClassCache[transmitterClassId] = reader.GetString(0); + _transmitterClassCache[transmitterClassId] = reader.GetString (0); return _transmitterClassCache[transmitterClassId]; } - throw new ArgumentException("No such TransmitterClassId:" + transmitterClassId); + throw new ArgumentException ("No such TransmitterClassId:" + transmitterClassId); } } } @@ -188,77 +188,78 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateOutboundComm(int senderPersonId, int fromPersonId, int organizationId, string resolverClass, + public int CreateOutboundComm (int senderPersonId, int fromPersonId, int organizationId, string resolverClass, string recipientDataXml, string transmitterClass, string payloadXml, OutboundCommPriority priority) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundComm", connection); + DbCommand command = GetDbCommand ("CreateOutboundComm", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "senderPersonId", senderPersonId); - AddParameterWithName(command, "fromPersonId", fromPersonId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "resolverClass", String.IsNullOrEmpty(resolverClass) ? "0" : resolverClass); - // Will be turned into ID by stored procedure - AddParameterWithName(command, "recipientDataXml", - String.IsNullOrEmpty(recipientDataXml) ? string.Empty : recipientDataXml); - AddParameterWithName(command, "transmitterClass", transmitterClass); - // Will be turned into ID by stored procedure - AddParameterWithName(command, "payloadXml", payloadXml); - AddParameterWithName(command, "priority", (int) priority); - // convert enum to integerized priority; convert back on field read - AddParameterWithName(command, "createdDateTime", DateTime.UtcNow); + AddParameterWithName (command, "senderPersonId", senderPersonId); + AddParameterWithName (command, "fromPersonId", fromPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "resolverClass", + String.IsNullOrEmpty (resolverClass) ? "0" : resolverClass); + // Will be turned into ID by stored procedure + AddParameterWithName (command, "recipientDataXml", + String.IsNullOrEmpty (recipientDataXml) ? string.Empty : recipientDataXml); + AddParameterWithName (command, "transmitterClass", transmitterClass); + // Will be turned into ID by stored procedure + AddParameterWithName (command, "payloadXml", payloadXml); + AddParameterWithName (command, "priority", (int) priority); + // convert enum to integerized priority; convert back on field read + AddParameterWithName (command, "createdDateTime", DateTime.UtcNow); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetOutboundCommResolved(int outboundCommId) + public void SetOutboundCommResolved (int outboundCommId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundCommResolved", connection); + DbCommand command = GetDbCommand ("SetOutboundCommResolved", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommId", outboundCommId); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "outboundCommId", outboundCommId); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); command.ExecuteNonQuery(); } } - public void SetOutboundCommTransmissionStart(int outboundCommId) + public void SetOutboundCommTransmissionStart (int outboundCommId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundCommTransmissionStart", connection); + DbCommand command = GetDbCommand ("SetOutboundCommTransmissionStart", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommId", outboundCommId); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "outboundCommId", outboundCommId); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); command.ExecuteNonQuery(); } } - public void SetOutboundCommClosed(int outboundCommId) + public void SetOutboundCommClosed (int outboundCommId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundCommClosed", connection); + DbCommand command = GetDbCommand ("SetOutboundCommClosed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundCommId", outboundCommId); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "outboundCommId", outboundCommId); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); command.ExecuteNonQuery(); } diff --git a/Database/Database-OutboundInvoices.cs b/Database/Database-OutboundInvoices.cs index f0f8e715..0fdf2465 100644 --- a/Database/Database-OutboundInvoices.cs +++ b/Database/Database-OutboundInvoices.cs @@ -24,54 +24,54 @@ namespace Swarmops.Database private const string outboundInvoiceItemSortOrder = " ORDER BY SortOrder,OutboundInvoiceItemId "; - private BasicOutboundInvoice ReadOutboundInvoiceFromDataReader(DbDataReader reader) + private BasicOutboundInvoice ReadOutboundInvoiceFromDataReader (DbDataReader reader) { - int outboundInvoiceId = reader.GetInt32(0); - string customerName = reader.GetString(1); - string invoiceAddressPaper = reader.GetString(2); - string invoiceAddressMail = reader.GetString(3); - int currencyId = reader.GetInt32(4); + int outboundInvoiceId = reader.GetInt32 (0); + string customerName = reader.GetString (1); + string invoiceAddressPaper = reader.GetString (2); + string invoiceAddressMail = reader.GetString (3); + int currencyId = reader.GetInt32 (4); // double amount = reader.GetDouble(5); - int organizationId = reader.GetInt32(6); - int budgetId = reader.GetInt32(7); - DateTime createdDateTime = reader.GetDateTime(8); - int createdByPersonId = reader.GetInt32(9); - DateTime dueDate = reader.GetDateTime(10); - int reminderCount = reader.GetInt32(11); - string reference = reader.GetString(12); - bool domestic = reader.GetBoolean(13); - bool open = reader.GetBoolean(14); - bool sent = reader.GetBoolean(15); - string securityCode = reader.GetString(16); - string theirReference = reader.GetString(17); + int organizationId = reader.GetInt32 (6); + int budgetId = reader.GetInt32 (7); + DateTime createdDateTime = reader.GetDateTime (8); + int createdByPersonId = reader.GetInt32 (9); + DateTime dueDate = reader.GetDateTime (10); + int reminderCount = reader.GetInt32 (11); + string reference = reader.GetString (12); + bool domestic = reader.GetBoolean (13); + bool open = reader.GetBoolean (14); + bool sent = reader.GetBoolean (15); + string securityCode = reader.GetString (16); + string theirReference = reader.GetString (17); - return new BasicOutboundInvoice(outboundInvoiceId, customerName, invoiceAddressPaper, invoiceAddressMail, + return new BasicOutboundInvoice (outboundInvoiceId, customerName, invoiceAddressPaper, invoiceAddressMail, currencyId, organizationId, budgetId, createdDateTime, createdByPersonId, dueDate, reminderCount, reference, domestic, open, sent, securityCode, theirReference); } - private BasicOutboundInvoiceItem ReadOutboundInvoiceItemFromDataReader(DbDataReader reader) + private BasicOutboundInvoiceItem ReadOutboundInvoiceItemFromDataReader (DbDataReader reader) { - int outboundInvoiceItemId = reader.GetInt32(0); - int outboundInvoiceId = reader.GetInt32(1); - string description = reader.GetString(2); - Int64 amountCents = reader.GetInt64(3); + int outboundInvoiceItemId = reader.GetInt32 (0); + int outboundInvoiceId = reader.GetInt32 (1); + string description = reader.GetString (2); + Int64 amountCents = reader.GetInt64 (3); - return new BasicOutboundInvoiceItem(outboundInvoiceItemId, outboundInvoiceId, description, amountCents); + return new BasicOutboundInvoiceItem (outboundInvoiceItemId, outboundInvoiceId, description, amountCents); } #endregion #region Record reading - SELECT statements - public BasicOutboundInvoice GetOutboundInvoice(int outboundInvoiceId) + public BasicOutboundInvoice GetOutboundInvoice (int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + outboundInvoiceFieldSequence + "WHERE OutboundInvoiceId=" + outboundInvoiceId + ";", connection); @@ -79,10 +79,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadOutboundInvoiceFromDataReader(reader); + return ReadOutboundInvoiceFromDataReader (reader); } - throw new ArgumentException("Unknown OutboundInvoiceId"); + throw new ArgumentException ("Unknown OutboundInvoiceId"); } } } @@ -93,7 +93,7 @@ namespace Swarmops.Database /// /// Optional Organization object and/or DatabaseConditions. /// The inbound invoice list. - public BasicOutboundInvoice[] GetOutboundInvoices(params object[] conditions) + public BasicOutboundInvoice[] GetOutboundInvoices (params object[] conditions) { List result = new List(); @@ -102,15 +102,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + outboundInvoiceFieldSequence + ConstructWhereClause("OutboundInvoices", conditions) + + GetDbCommand ( + "SELECT" + outboundInvoiceFieldSequence + ConstructWhereClause ("OutboundInvoices", conditions) + " ORDER BY DueDate;", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadOutboundInvoiceFromDataReader(reader)); + result.Add (ReadOutboundInvoiceFromDataReader (reader)); } return result.ToArray(); @@ -119,14 +119,14 @@ namespace Swarmops.Database } - public BasicOutboundInvoiceItem GetOutboundInvoiceItem(int outboundInvoiceItemId) + public BasicOutboundInvoiceItem GetOutboundInvoiceItem (int outboundInvoiceItemId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + outboundInvoiceItemFieldSequence + "WHERE OutboundInvoiceItemId=" + outboundInvoiceItemId + ";", connection); @@ -134,10 +134,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadOutboundInvoiceItemFromDataReader(reader); + return ReadOutboundInvoiceItemFromDataReader (reader); } - throw new ArgumentException("Unknown OutboundInvoiceId"); + throw new ArgumentException ("Unknown OutboundInvoiceId"); } } } @@ -148,7 +148,7 @@ namespace Swarmops.Database /// /// OutboundInvoice object. /// The inbound invoice list. - public BasicOutboundInvoiceItem[] GetOutboundInvoiceItems(params object[] conditions) + public BasicOutboundInvoiceItem[] GetOutboundInvoiceItems (params object[] conditions) { List result = new List(); @@ -157,16 +157,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + outboundInvoiceItemFieldSequence + - ConstructWhereClause("OutboundInvoiceItems", conditions) + outboundInvoiceItemSortOrder + ";", + ConstructWhereClause ("OutboundInvoiceItems", conditions) + outboundInvoiceItemSortOrder + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadOutboundInvoiceItemFromDataReader(reader)); + result.Add (ReadOutboundInvoiceItemFromDataReader (reader)); } return result.ToArray(); @@ -178,7 +178,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateOutboundInvoice(int organizationId, int createdByPersonId, DateTime dueDate, + public int CreateOutboundInvoice (int organizationId, int createdByPersonId, DateTime dueDate, int budgetId, string customerName, string invoiceAddressPaper, string invoiceAddressMail, int currencyId, string reference, bool domestic, string securityCode, string theirReference) @@ -187,128 +187,128 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundInvoice", connection); + DbCommand command = GetDbCommand ("CreateOutboundInvoice", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "dueDate", dueDate); - AddParameterWithName(command, "budgetId", budgetId); - AddParameterWithName(command, "customerName", customerName); - AddParameterWithName(command, "invoiceAddressPaper", invoiceAddressPaper); - AddParameterWithName(command, "invoiceAddressMail", invoiceAddressMail); - AddParameterWithName(command, "currencyId", currencyId); - AddParameterWithName(command, "reference", reference); - AddParameterWithName(command, "domestic", domestic); - AddParameterWithName(command, "securityCode", securityCode); - AddParameterWithName(command, "TheirReference", theirReference); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "dueDate", dueDate); + AddParameterWithName (command, "budgetId", budgetId); + AddParameterWithName (command, "customerName", customerName); + AddParameterWithName (command, "invoiceAddressPaper", invoiceAddressPaper); + AddParameterWithName (command, "invoiceAddressMail", invoiceAddressMail); + AddParameterWithName (command, "currencyId", currencyId); + AddParameterWithName (command, "reference", reference); + AddParameterWithName (command, "domestic", domestic); + AddParameterWithName (command, "securityCode", securityCode); + AddParameterWithName (command, "TheirReference", theirReference); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateOutboundInvoiceItem(int outboundInvoiceId, string description, double amount) + public int CreateOutboundInvoiceItem (int outboundInvoiceId, string description, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundInvoiceItem", connection); + DbCommand command = GetDbCommand ("CreateOutboundInvoiceItem", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "amount", amount); - AddParameterWithName(command, "sortOrder", 1); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "amount", amount); + AddParameterWithName (command, "sortOrder", 1); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateOutboundInvoiceItem(int outboundInvoiceId, string description, Int64 amountCents) + public int CreateOutboundInvoiceItem (int outboundInvoiceId, string description, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundInvoiceItemPrecise", connection); + DbCommand command = GetDbCommand ("CreateOutboundInvoiceItemPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "sortOrder", 1); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "sortOrder", 1); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetOutboundInvoiceOpen(int outboundInvoiceId, bool open) + public void SetOutboundInvoiceOpen (int outboundInvoiceId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundInvoiceOpen", connection); + DbCommand command = GetDbCommand ("SetOutboundInvoiceOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetOutboundInvoiceSent(int inboundInvoiceId, bool sent) + public void SetOutboundInvoiceSent (int inboundInvoiceId, bool sent) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundInvoiceSent", connection); + DbCommand command = GetDbCommand ("SetOutboundInvoiceSent", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "sent", sent); + AddParameterWithName (command, "outboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "sent", sent); command.ExecuteNonQuery(); } } - public void SetOutboundInvoiceReference(int inboundInvoiceId, string reference) + public void SetOutboundInvoiceReference (int inboundInvoiceId, string reference) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundInvoiceReference", connection); + DbCommand command = GetDbCommand ("SetOutboundInvoiceReference", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", inboundInvoiceId); - AddParameterWithName(command, "reference", reference); + AddParameterWithName (command, "outboundInvoiceId", inboundInvoiceId); + AddParameterWithName (command, "reference", reference); command.ExecuteNonQuery(); } } - public void SetOutboundInvoiceBudget(int outboundInvoiceId, int budgetId) + public void SetOutboundInvoiceBudget (int outboundInvoiceId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundInvoiceBudget", connection); + DbCommand command = GetDbCommand ("SetOutboundInvoiceBudget", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); - AddParameterWithName(command, "budgetId", budgetId); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "budgetId", budgetId); command.ExecuteNonQuery(); } diff --git a/Database/Database-OutboundMailRecipients.cs b/Database/Database-OutboundMailRecipients.cs index 6a7fba58..723840a2 100644 --- a/Database/Database-OutboundMailRecipients.cs +++ b/Database/Database-OutboundMailRecipients.cs @@ -12,20 +12,20 @@ namespace Swarmops.Database " FROM OutboundMailRecipients "; - private BasicOutboundMailRecipient ReadOutboundMailRecipientFromDataReader(DbDataReader reader) + private BasicOutboundMailRecipient ReadOutboundMailRecipientFromDataReader (DbDataReader reader) { - int outboundMailRecipientId = reader.GetInt32(0); - int outboundMailId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - bool asOfficer = reader.GetBoolean(3); - int personType = reader.GetInt32(4); + int outboundMailRecipientId = reader.GetInt32 (0); + int outboundMailId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + bool asOfficer = reader.GetBoolean (3); + int personType = reader.GetInt32 (4); - return new BasicOutboundMailRecipient(outboundMailRecipientId, outboundMailId, personId, asOfficer, + return new BasicOutboundMailRecipient (outboundMailRecipientId, outboundMailId, personId, asOfficer, personType); } - public BasicOutboundMailRecipient[] GetTopOutboundMailRecipients(int outboundMailId, int batchSize) + public BasicOutboundMailRecipient[] GetTopOutboundMailRecipients (int outboundMailId, int batchSize) { List result = new List(); @@ -34,7 +34,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + outboundMailRecipientFieldSequence + " WHERE OutboundMailId=" + outboundMailId + " LIMIT " + batchSize, connection); @@ -42,7 +42,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadOutboundMailRecipientFromDataReader(reader)); + result.Add (ReadOutboundMailRecipientFromDataReader (reader)); } return result.ToArray(); @@ -51,34 +51,34 @@ namespace Swarmops.Database } - public void DeleteOutboundMailRecipient(int outboundMailRecipientId) + public void DeleteOutboundMailRecipient (int outboundMailRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteOutboundMailRecipient", connection); + DbCommand command = GetDbCommand ("DeleteOutboundMailRecipient", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailRecipientId", outboundMailRecipientId); + AddParameterWithName (command, "outboundMailRecipientId", outboundMailRecipientId); command.ExecuteNonQuery(); } } - public void CreateOutboundMailRecipient(int outboundMailId, int personId, bool asOfficer, int personType) + public void CreateOutboundMailRecipient (int outboundMailId, int personId, bool asOfficer, int personType) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundMailRecipient", connection); + DbCommand command = GetDbCommand ("CreateOutboundMailRecipient", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "asOfficer", asOfficer); - AddParameterWithName(command, "personType", personType); + AddParameterWithName (command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "asOfficer", asOfficer); + AddParameterWithName (command, "personType", personType); command.ExecuteNonQuery(); } diff --git a/Database/Database-OutboundMails.cs b/Database/Database-OutboundMails.cs index 6a0baf14..aa0f1c61 100644 --- a/Database/Database-OutboundMails.cs +++ b/Database/Database-OutboundMails.cs @@ -16,33 +16,33 @@ namespace Swarmops.Database "StartProcessDateTime,EndProcessDateTime,RecipientCount,RecipientsSuccess,RecipientsFail " + // 15-19 " FROM OutboundMails "; - private static BasicOutboundMail ReadOutboundMailFromDataReader(IDataRecord reader) + private static BasicOutboundMail ReadOutboundMailFromDataReader (IDataRecord reader) { - int outboundMailId = reader.GetInt32(0); - int authorType = reader.GetInt32(1); - int authorPersonId = reader.GetInt32(2); - string title = reader.GetString(3); - string body = reader.GetString(4); + int outboundMailId = reader.GetInt32 (0); + int authorType = reader.GetInt32 (1); + int authorPersonId = reader.GetInt32 (2); + string title = reader.GetString (3); + string body = reader.GetString (4); - int mailPriority = reader.GetInt32(5); - int mailTypeId = reader.GetInt32(6); - int organizationId = reader.GetInt32(7); - int geographyId = reader.GetInt32(8); - DateTime createdDateTime = reader.GetDateTime(9); + int mailPriority = reader.GetInt32 (5); + int mailTypeId = reader.GetInt32 (6); + int organizationId = reader.GetInt32 (7); + int geographyId = reader.GetInt32 (8); + DateTime createdDateTime = reader.GetDateTime (9); - DateTime releaseDateTime = reader.GetDateTime(10); - bool readyForPickup = reader.GetBoolean(11); - bool resolved = reader.GetBoolean(12); - bool processed = reader.GetBoolean(13); - DateTime resolvedDateTime = reader.GetDateTime(14); + DateTime releaseDateTime = reader.GetDateTime (10); + bool readyForPickup = reader.GetBoolean (11); + bool resolved = reader.GetBoolean (12); + bool processed = reader.GetBoolean (13); + DateTime resolvedDateTime = reader.GetDateTime (14); - DateTime startProcessDateTime = reader.GetDateTime(15); - DateTime endProcessDateTime = reader.GetDateTime(16); - int recipientCount = reader.GetInt32(17); - int recipientsSuccess = reader.GetInt32(18); - int recipientsFail = reader.GetInt32(19); + DateTime startProcessDateTime = reader.GetDateTime (15); + DateTime endProcessDateTime = reader.GetDateTime (16); + int recipientCount = reader.GetInt32 (17); + int recipientsSuccess = reader.GetInt32 (18); + int recipientsFail = reader.GetInt32 (19); - return new BasicOutboundMail(outboundMailId, (MailAuthorType) authorType, authorPersonId, title, body, + return new BasicOutboundMail (outboundMailId, (MailAuthorType) authorType, authorPersonId, title, body, mailPriority, mailTypeId, organizationId, geographyId, createdDateTime, releaseDateTime, readyForPickup, resolved, processed, resolvedDateTime, startProcessDateTime, endProcessDateTime, @@ -50,14 +50,14 @@ namespace Swarmops.Database } - public BasicOutboundMail GetOutboundMail(int outboundMailId) + public BasicOutboundMail GetOutboundMail (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + outboundMailFieldSequence + " WHERE OutboundMailId=" + outboundMailId.ToString(), connection); @@ -65,17 +65,17 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadOutboundMailFromDataReader(reader); + return ReadOutboundMailFromDataReader (reader); } else { - throw new ArgumentException("No such OutboundMailId: " + outboundMailId.ToString()); + throw new ArgumentException ("No such OutboundMailId: " + outboundMailId.ToString()); } } } } - public BasicOutboundMail[] GetTopUnresolvedOutboundMail(int count) + public BasicOutboundMail[] GetTopUnresolvedOutboundMail (int count) { if (count == 0) { @@ -89,7 +89,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + outboundMailFieldSequence + " WHERE ReadyForPickup=1 AND Resolved=0 AND Processed=0 ORDER BY MailPriority, OutboundMailId DESC LIMIT " + count.ToString(), @@ -99,7 +99,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadOutboundMailFromDataReader(reader)); + result.Add (ReadOutboundMailFromDataReader (reader)); } return result.ToArray(); @@ -107,7 +107,7 @@ namespace Swarmops.Database } } - public BasicOutboundMail[] GetTopUnprocessedOutboundMail(int count) + public BasicOutboundMail[] GetTopUnprocessedOutboundMail (int count) { if (count == 0) { @@ -121,7 +121,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + outboundMailFieldSequence + " WHERE ReadyForPickup=1 AND Resolved=1 AND Processed=0 " + " AND ReleaseDateTime < NOW() " + @@ -132,7 +132,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadOutboundMailFromDataReader(reader)); + result.Add (ReadOutboundMailFromDataReader (reader)); } return result.ToArray(); @@ -140,7 +140,7 @@ namespace Swarmops.Database } } - public BasicOutboundMail[] GetOutboundMailQueue(int count) + public BasicOutboundMail[] GetOutboundMailQueue (int count) { // This may not survive the migration. SQL Syntax, etc. @@ -156,8 +156,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - String.Format(@" + GetDbCommand ( + String.Format (@" SELECT " + outboundMailFieldSequence + @" where OutboundMailId in ( @@ -179,7 +179,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC { while (reader.Read()) { - result.Add(ReadOutboundMailFromDataReader(reader)); + result.Add (ReadOutboundMailFromDataReader (reader)); } return result.ToArray(); @@ -188,7 +188,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } - public int CreateOutboundMail(MailAuthorType authorType, int authorPersonId, string title, + public int CreateOutboundMail (MailAuthorType authorType, int authorPersonId, string title, string body, int mailPriority, int mailType, int geographyId, int organizationId, DateTime releaseDateTime) { @@ -196,144 +196,144 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC { connection.Open(); - DbCommand command = GetDbCommand("CreateOutboundMail", connection); + DbCommand command = GetDbCommand ("CreateOutboundMail", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "authorType", (int) authorType); - AddParameterWithName(command, "authorPersonId", authorPersonId); - AddParameterWithName(command, "title", title); - AddParameterWithName(command, "body", body); - AddParameterWithName(command, "mailPriority", mailPriority); - AddParameterWithName(command, "mailType", mailType); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "releaseDateTime", releaseDateTime); + AddParameterWithName (command, "authorType", (int) authorType); + AddParameterWithName (command, "authorPersonId", authorPersonId); + AddParameterWithName (command, "title", title); + AddParameterWithName (command, "body", body); + AddParameterWithName (command, "mailPriority", mailPriority); + AddParameterWithName (command, "mailType", mailType); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "releaseDateTime", releaseDateTime); - int result = Convert.ToInt32(command.ExecuteScalar()); + int result = Convert.ToInt32 (command.ExecuteScalar()); if (result == 0) { - throw new Exception("Unable to create outbound mail"); + throw new Exception ("Unable to create outbound mail"); } return result; } } - public void SetOutboundMailProcessed(int outboundMailId) + public void SetOutboundMailProcessed (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundMailProcessed", connection); + DbCommand command = GetDbCommand ("SetOutboundMailProcessed", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); - AddParameterWithName(command, "datetime", DateTime.Now); + AddParameterWithName (command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "datetime", DateTime.Now); command.ExecuteNonQuery(); } } - public void SetOutboundMailStartProcess(int outboundMailId) + public void SetOutboundMailStartProcess (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundMailStartProcess", connection); + DbCommand command = GetDbCommand ("SetOutboundMailStartProcess", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); - AddParameterWithName(command, "datetime", DateTime.Now); + AddParameterWithName (command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "datetime", DateTime.Now); command.ExecuteNonQuery(); } } - public void SetOutboundMailResolved(int outboundMailId) + public void SetOutboundMailResolved (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundMailResolved", connection); + DbCommand command = GetDbCommand ("SetOutboundMailResolved", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); - AddParameterWithName(command, "datetime", DateTime.Now); + AddParameterWithName (command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "datetime", DateTime.Now); command.ExecuteNonQuery(); } } - public void SetOutboundMailReadyForPickup(int outboundMailId) + public void SetOutboundMailReadyForPickup (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundMailReadyForPickup", connection); + DbCommand command = GetDbCommand ("SetOutboundMailReadyForPickup", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "outboundMailId", outboundMailId); command.ExecuteNonQuery(); } } - public void SetOutboundMailRecipientCount(int outboundMailId, int recipientCount) + public void SetOutboundMailRecipientCount (int outboundMailId, int recipientCount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetOutboundMailRecipientCount", connection); + DbCommand command = GetDbCommand ("SetOutboundMailRecipientCount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); - AddParameterWithName(command, "recipientCount", recipientCount); + AddParameterWithName (command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "recipientCount", recipientCount); command.ExecuteNonQuery(); } } - public void IncrementOutboundMailSuccesses(int outboundMailId) + public void IncrementOutboundMailSuccesses (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("IncrementOutboundMailSuccesses", connection); + DbCommand command = GetDbCommand ("IncrementOutboundMailSuccesses", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "outboundMailId", outboundMailId); command.ExecuteNonQuery(); } } - public void IncrementOutboundMailFailures(int outboundMailId) + public void IncrementOutboundMailFailures (int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("IncrementOutboundMailFailures", connection); + DbCommand command = GetDbCommand ("IncrementOutboundMailFailures", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "outboundMailId", outboundMailId); + AddParameterWithName (command, "outboundMailId", outboundMailId); command.ExecuteNonQuery(); } } - public BasicOutboundMail[] GetDuplicateOutboundMail(MailAuthorType authorType, int authorPersonId, string title, + public BasicOutboundMail[] GetDuplicateOutboundMail (MailAuthorType authorType, int authorPersonId, string title, string body, int mailPriority, int mailType, int geographyId, int organizationId, DateTime createDateTime, int recieverId) { @@ -343,7 +343,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + outboundMailFieldSequence + @" INNER JOIN OutboundMailRecipients ON OutboundMailRecipients.OutboundMailId = OutboundMails.OutboundMailId WHERE (OutboundMailRecipients.PersonId = " + recieverId + @") @@ -356,7 +356,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC AND (OutboundMails.OrganizationId = " + organizationId + @") AND (OutboundMails.GeographyId = " + geographyId + @") AND (OutboundMails.CreatedDateTime > TO_DATE('" + - createDateTime.ToString("yyyy-MM-dd HH:mm:ss") + @"'))", connection); + createDateTime.ToString ("yyyy-MM-dd HH:mm:ss") + @"'))", connection); command.CommandType = CommandType.Text; @@ -364,7 +364,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC { while (reader.Read()) { - result.Add(ReadOutboundMailFromDataReader(reader)); + result.Add (ReadOutboundMailFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-PaperLetters.cs b/Database/Database-PaperLetters.cs index 6e8c6449..2470aebb 100644 --- a/Database/Database-PaperLetters.cs +++ b/Database/Database-PaperLetters.cs @@ -11,39 +11,39 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreatePaperLetter(int organizationId, string fromName, string replyAddress, DateTime receivedDate, + public int CreatePaperLetter (int organizationId, string fromName, string replyAddress, DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePaperLetter", connection); + DbCommand command = GetDbCommand ("CreatePaperLetter", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "fromName", fromName); - AddParameterWithName(command, "replyAddress", replyAddress); - AddParameterWithName(command, "receivedDate", receivedDate); - AddParameterWithName(command, "toPersonId", toPersonId); - AddParameterWithName(command, "toPersonInRoleId", (int) toPersonInRole); - AddParameterWithName(command, "personal", personal); - AddParameterWithName(command, "uploadedByPersonId", uploadedByPersonId); - AddParameterWithName(command, "uploadedDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "fromName", fromName); + AddParameterWithName (command, "replyAddress", replyAddress); + AddParameterWithName (command, "receivedDate", receivedDate); + AddParameterWithName (command, "toPersonId", toPersonId); + AddParameterWithName (command, "toPersonInRoleId", (int) toPersonInRole); + AddParameterWithName (command, "personal", personal); + AddParameterWithName (command, "uploadedByPersonId", uploadedByPersonId); + AddParameterWithName (command, "uploadedDateTime", DateTime.Now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public BasicPaperLetter GetPaperLetter(int paperLetterId) + public BasicPaperLetter GetPaperLetter (int paperLetterId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PaperLetterId,OrganizationId,FromName,ReplyAddress,ReceivedDate,ToPersonId," + "ToPersonInRoleId,Personal,UploadedByPersonId,UploadedDateTime " + "From PaperLetters WHERE PaperLetterId=" + paperLetterId + ";", connection); @@ -52,16 +52,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadPaperLetterFromDataReader(reader); + return ReadPaperLetterFromDataReader (reader); } - throw new ArgumentException("Unknown PaperLetter Id"); + throw new ArgumentException ("Unknown PaperLetter Id"); } } } - public BasicPaperLetter[] GetPaperLettersForOrganization(int organizationId) + public BasicPaperLetter[] GetPaperLettersForOrganization (int organizationId) { List result = new List(); @@ -70,7 +70,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PaperLetterId,OrganizationId,FromName,ReplyAddress,ReceivedDate,ToPersonId," + "ToPersonInRoleId,Personal,UploadedByPersonId,UploadedDateTime " + "From PaperLetters WHERE OrganizationId=" + organizationId + ";", connection); @@ -79,7 +79,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPaperLetterFromDataReader(reader)); + result.Add (ReadPaperLetterFromDataReader (reader)); } return result.ToArray(); @@ -88,7 +88,7 @@ namespace Swarmops.Database } - public BasicPaperLetter[] GetPaperLettersForPerson(int personId) + public BasicPaperLetter[] GetPaperLettersForPerson (int personId) { List result = new List(); @@ -97,7 +97,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT PaperLetterId,OrganizationId,FromName,ReplyAddress,ReceivedDate,ToPersonId," + "ToPersonInRoleId,Personal,UploadedByPersonId,UploadedDateTime " + "From PaperLetters WHERE ToPersonId=" + personId + ";", connection); @@ -106,7 +106,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPaperLetterFromDataReader(reader)); + result.Add (ReadPaperLetterFromDataReader (reader)); } return result.ToArray(); @@ -115,20 +115,20 @@ namespace Swarmops.Database } - private BasicPaperLetter ReadPaperLetterFromDataReader(DbDataReader reader) + private BasicPaperLetter ReadPaperLetterFromDataReader (DbDataReader reader) { - int paperLetterId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - string fromName = reader.GetString(2); - string replyAddress = reader.GetString(3); - DateTime receivedDate = reader.GetDateTime(4); - int toPersonId = reader.GetInt32(5); - int toPersonInRoleId = reader.GetInt32(6); - bool personal = reader.GetBoolean(7); - int uploadedByPersonId = reader.GetInt32(8); - DateTime uploadedDateTime = reader.GetDateTime(9); + int paperLetterId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + string fromName = reader.GetString (2); + string replyAddress = reader.GetString (3); + DateTime receivedDate = reader.GetDateTime (4); + int toPersonId = reader.GetInt32 (5); + int toPersonInRoleId = reader.GetInt32 (6); + bool personal = reader.GetBoolean (7); + int uploadedByPersonId = reader.GetInt32 (8); + DateTime uploadedDateTime = reader.GetDateTime (9); - return new BasicPaperLetter(paperLetterId, organizationId, fromName, replyAddress, receivedDate, + return new BasicPaperLetter (paperLetterId, organizationId, fromName, replyAddress, receivedDate, toPersonId, (RoleType) toPersonInRoleId, personal, uploadedByPersonId, uploadedDateTime); } diff --git a/Database/Database-ParleyAttendees.cs b/Database/Database-ParleyAttendees.cs index 0ff93010..57aa95b4 100644 --- a/Database/Database-ParleyAttendees.cs +++ b/Database/Database-ParleyAttendees.cs @@ -15,20 +15,20 @@ namespace Swarmops.Database "CancelDateTime, Invoiced, OutboundInvoiceId, IsGuest" + // 5-8 " FROM ParleyAttendees "; - private static BasicParleyAttendee ReadParleyAttendeeFromDataReader(IDataRecord reader) + private static BasicParleyAttendee ReadParleyAttendeeFromDataReader (IDataRecord reader) { - int parleyAttendeeId = reader.GetInt32(0); - int parleyId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - DateTime signupDateTime = reader.GetDateTime(3); - bool active = reader.GetBoolean(4); + int parleyAttendeeId = reader.GetInt32 (0); + int parleyId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + DateTime signupDateTime = reader.GetDateTime (3); + bool active = reader.GetBoolean (4); - DateTime cancelDateTime = reader.GetDateTime(5); - bool invoiced = reader.GetBoolean(6); - int outboundInvoiceId = reader.GetInt32(7); - bool isGuest = reader.GetBoolean(8); + DateTime cancelDateTime = reader.GetDateTime (5); + bool invoiced = reader.GetBoolean (6); + int outboundInvoiceId = reader.GetInt32 (7); + bool isGuest = reader.GetBoolean (8); - return new BasicParleyAttendee(parleyAttendeeId, parleyId, personId, signupDateTime, active, cancelDateTime, + return new BasicParleyAttendee (parleyAttendeeId, parleyId, personId, signupDateTime, active, cancelDateTime, invoiced, outboundInvoiceId, isGuest); } @@ -36,31 +36,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicParleyAttendee GetParleyAttendee(int parleyAttendeeId) + public BasicParleyAttendee GetParleyAttendee (int parleyAttendeeId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + parleyAttendeeFieldSequence + - "WHERE ParleyAttendeeId=" + parleyAttendeeId, + GetDbCommand ("SELECT" + parleyAttendeeFieldSequence + + "WHERE ParleyAttendeeId=" + parleyAttendeeId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadParleyAttendeeFromDataReader(reader); + return ReadParleyAttendeeFromDataReader (reader); } - throw new ArgumentException("No such ParleyAttendeeId:" + parleyAttendeeId); + throw new ArgumentException ("No such ParleyAttendeeId:" + parleyAttendeeId); } } } - public BasicParleyAttendee[] GetParleyAttendees(params object[] conditions) + public BasicParleyAttendee[] GetParleyAttendees (params object[] conditions) { List result = new List(); @@ -69,15 +69,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + parleyAttendeeFieldSequence + ConstructWhereClause("ParleyAttendees", conditions), + GetDbCommand ( + "SELECT" + parleyAttendeeFieldSequence + ConstructWhereClause ("ParleyAttendees", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadParleyAttendeeFromDataReader(reader)); + result.Add (ReadParleyAttendeeFromDataReader (reader)); } return result.ToArray(); @@ -86,7 +86,7 @@ namespace Swarmops.Database } - public int[] GetParleyAttendeeOptions(int parleyAttendeeId) + public int[] GetParleyAttendeeOptions (int parleyAttendeeId) { List result = new List(); @@ -95,7 +95,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT ParleyOptionId FROM ParleyAttendeeOptions WHERE ParleyAttendeeId=" + parleyAttendeeId, connection); @@ -103,7 +103,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -115,72 +115,72 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateParleyAttendee(int parleyId, int personId, bool isGuest) // ok + public int CreateParleyAttendee (int parleyId, int personId, bool isGuest) // ok { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateParleyAttendee", connection); + DbCommand command = GetDbCommand ("CreateParleyAttendee", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyId", parleyId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "signupDateTime", DateTime.Now); - AddParameterWithName(command, "isGuest", isGuest); + AddParameterWithName (command, "parleyId", parleyId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "signupDateTime", DateTime.Now); + AddParameterWithName (command, "isGuest", isGuest); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyAttendeeActive(int parleyAttendeeId, bool active) + public int SetParleyAttendeeActive (int parleyAttendeeId, bool active) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyAttendeeActive", connection); + DbCommand command = GetDbCommand ("SetParleyAttendeeActive", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyAttendeeId", parleyAttendeeId); - AddParameterWithName(command, "active", active); - AddParameterWithName(command, "cancelDateTime", DateTime.Now); - // if active=false, set to cancellation time. if active=true, ignored + AddParameterWithName (command, "parleyAttendeeId", parleyAttendeeId); + AddParameterWithName (command, "active", active); + AddParameterWithName (command, "cancelDateTime", DateTime.Now); + // if active=false, set to cancellation time. if active=true, ignored - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyAttendeeInvoiced(int parleyAttendeeId, int outboundInvoiceId) + public int SetParleyAttendeeInvoiced (int parleyAttendeeId, int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyAttendeeInvoiced", connection); + DbCommand command = GetDbCommand ("SetParleyAttendeeInvoiced", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyAttendeeId", parleyAttendeeId); - AddParameterWithName(command, "invoiced", (outboundInvoiceId > 0 ? true : false)); - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "parleyAttendeeId", parleyAttendeeId); + AddParameterWithName (command, "invoiced", (outboundInvoiceId > 0 ? true : false)); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int AddParleyAttendeeOption(int parleyAttendeeId, int parleyOptionId) + public int AddParleyAttendeeOption (int parleyAttendeeId, int parleyOptionId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("AddParleyAttendeeOption", connection); + DbCommand command = GetDbCommand ("AddParleyAttendeeOption", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyAttendeeId", parleyAttendeeId); - AddParameterWithName(command, "parleyOptionId", parleyOptionId); + AddParameterWithName (command, "parleyAttendeeId", parleyAttendeeId); + AddParameterWithName (command, "parleyOptionId", parleyOptionId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-ParleyOptions.cs b/Database/Database-ParleyOptions.cs index 51a6e641..c28c2525 100644 --- a/Database/Database-ParleyOptions.cs +++ b/Database/Database-ParleyOptions.cs @@ -14,46 +14,46 @@ namespace Swarmops.Database " ParleyId, ParleyOptionId, Description, AmountCents, Active" + // 0-4 " FROM ParleyOptions "; - private static BasicParleyOption ReadParleyOptionFromDataReader(IDataRecord reader) + private static BasicParleyOption ReadParleyOptionFromDataReader (IDataRecord reader) { - int parleyId = reader.GetInt32(0); - int parleyOptionId = reader.GetInt32(1); - string description = reader.GetString(2); - Int64 amountCents = reader.GetInt64(3); - bool active = reader.GetBoolean(4); + int parleyId = reader.GetInt32 (0); + int parleyOptionId = reader.GetInt32 (1); + string description = reader.GetString (2); + Int64 amountCents = reader.GetInt64 (3); + bool active = reader.GetBoolean (4); - return new BasicParleyOption(parleyOptionId, parleyId, description, amountCents, active); + return new BasicParleyOption (parleyOptionId, parleyId, description, amountCents, active); } #endregion #region Database record reading -- SELECT clauses - public BasicParleyOption GetParleyOption(int parleyOptionId) + public BasicParleyOption GetParleyOption (int parleyOptionId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + parleyOptionFieldSequence + - "WHERE ParleyOptionId=" + parleyOptionId, + GetDbCommand ("SELECT" + parleyOptionFieldSequence + + "WHERE ParleyOptionId=" + parleyOptionId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadParleyOptionFromDataReader(reader); + return ReadParleyOptionFromDataReader (reader); } - throw new ArgumentException("No such ParleyOptionId:" + parleyOptionId); + throw new ArgumentException ("No such ParleyOptionId:" + parleyOptionId); } } } - public BasicParleyOption[] GetParleyOptions(params object[] conditions) + public BasicParleyOption[] GetParleyOptions (params object[] conditions) { List result = new List(); @@ -62,15 +62,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + parleyOptionFieldSequence + ConstructWhereClause("ParleyOptions", conditions), + GetDbCommand ( + "SELECT" + parleyOptionFieldSequence + ConstructWhereClause ("ParleyOptions", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadParleyOptionFromDataReader(reader)); + result.Add (ReadParleyOptionFromDataReader (reader)); } return result.ToArray(); @@ -82,36 +82,36 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateParleyOption(int parleyId, string description, Int64 amountCents) + public int CreateParleyOption (int parleyId, string description, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateParleyOption", connection); + DbCommand command = GetDbCommand ("CreateParleyOption", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyId", parleyId); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "parleyId", parleyId); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "amountCents", amountCents); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyOptionActive(int parleyOptionId, bool active) + public int SetParleyOptionActive (int parleyOptionId, bool active) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyOptionActive", connection); + DbCommand command = GetDbCommand ("SetParleyOptionActive", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyOptionId", parleyOptionId); - AddParameterWithName(command, "active", active); + AddParameterWithName (command, "parleyOptionId", parleyOptionId); + AddParameterWithName (command, "active", active); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-Parleys.cs b/Database/Database-Parleys.cs index 8c410b18..fbf78154 100644 --- a/Database/Database-Parleys.cs +++ b/Database/Database-Parleys.cs @@ -17,30 +17,30 @@ namespace Swarmops.Database "AttendanceFeeCents, ClosedDateTime" + // 15-16 " FROM Parleys "; - private static BasicParley ReadParleyFromDataReader(IDataRecord reader) + private static BasicParley ReadParleyFromDataReader (IDataRecord reader) { - int parleyId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - int budgetId = reader.GetInt32(3); - DateTime createdDateTime = reader.GetDateTime(4); + int parleyId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + int budgetId = reader.GetInt32 (3); + DateTime createdDateTime = reader.GetDateTime (4); - bool open = reader.GetBoolean(5); - bool attested = reader.GetBoolean(6); - string name = reader.GetString(7); - int geographyId = reader.GetInt32(8); - string description = reader.GetString(9); + bool open = reader.GetBoolean (5); + bool attested = reader.GetBoolean (6); + string name = reader.GetString (7); + int geographyId = reader.GetInt32 (8); + string description = reader.GetString (9); - string informationUrl = reader.GetString(10); - DateTime startDate = reader.GetDateTime(11); - DateTime endDate = reader.GetDateTime(12); - Int64 budgetCents = reader.GetInt64(13); - Int64 guaranteeCents = reader.GetInt64(14); + string informationUrl = reader.GetString (10); + DateTime startDate = reader.GetDateTime (11); + DateTime endDate = reader.GetDateTime (12); + Int64 budgetCents = reader.GetInt64 (13); + Int64 guaranteeCents = reader.GetInt64 (14); - Int64 attendanceFeeCents = reader.GetInt64(15); - DateTime closedDateTime = reader.GetDateTime(16); + Int64 attendanceFeeCents = reader.GetInt64 (15); + DateTime closedDateTime = reader.GetDateTime (16); - return new BasicParley( + return new BasicParley ( parleyId, organizationId, personId, budgetId, createdDateTime, open, attested, name, geographyId, description, informationUrl, startDate, endDate, budgetCents, guaranteeCents, @@ -51,31 +51,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicParley GetParley(int parleyId) + public BasicParley GetParley (int parleyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + parleyFieldSequence + - "WHERE ParleyId=" + parleyId, + GetDbCommand ("SELECT" + parleyFieldSequence + + "WHERE ParleyId=" + parleyId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadParleyFromDataReader(reader); + return ReadParleyFromDataReader (reader); } - throw new ArgumentException("No such ParleyId:" + parleyId); + throw new ArgumentException ("No such ParleyId:" + parleyId); } } } - public BasicParley[] GetParleys(params object[] conditions) + public BasicParley[] GetParleys (params object[] conditions) { List result = new List(); @@ -84,14 +84,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + parleyFieldSequence + ConstructWhereClause("Parleys", conditions), connection); + GetDbCommand ( + "SELECT" + parleyFieldSequence + ConstructWhereClause ("Parleys", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadParleyFromDataReader(reader)); + result.Add (ReadParleyFromDataReader (reader)); } return result.ToArray(); @@ -103,7 +103,7 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateParley(int organizationId, int personId, int budgetId, string name, int geographyId, + public int CreateParley (int organizationId, int personId, int budgetId, string name, int geographyId, string description, string informationUrl, DateTime startDate, DateTime endDate, Int64 budgetCents, Int64 guaranteeCents, Int64 attendanceFeeCents) { @@ -111,73 +111,73 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateParley", connection); + DbCommand command = GetDbCommand ("CreateParley", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "budgetId", budgetId); - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "description", description); - AddParameterWithName(command, "informationUrl", informationUrl); - AddParameterWithName(command, "startDate", startDate); - AddParameterWithName(command, "endDate", endDate); - AddParameterWithName(command, "budgetCents", budgetCents); - AddParameterWithName(command, "guaranteeCents", guaranteeCents); - AddParameterWithName(command, "attendanceFeeCents", attendanceFeeCents); - AddParameterWithName(command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "budgetId", budgetId); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "description", description); + AddParameterWithName (command, "informationUrl", informationUrl); + AddParameterWithName (command, "startDate", startDate); + AddParameterWithName (command, "endDate", endDate); + AddParameterWithName (command, "budgetCents", budgetCents); + AddParameterWithName (command, "guaranteeCents", guaranteeCents); + AddParameterWithName (command, "attendanceFeeCents", attendanceFeeCents); + AddParameterWithName (command, "createdDateTime", DateTime.Now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyAttested(int parleyId, bool attested) + public int SetParleyAttested (int parleyId, bool attested) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyAttested", connection); + DbCommand command = GetDbCommand ("SetParleyAttested", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyId", parleyId); - AddParameterWithName(command, "attested", attested); + AddParameterWithName (command, "parleyId", parleyId); + AddParameterWithName (command, "attested", attested); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyBudget(int parleyId, int budgetId) + public int SetParleyBudget (int parleyId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyBudget", connection); + DbCommand command = GetDbCommand ("SetParleyBudget", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyId", parleyId); - AddParameterWithName(command, "budgetId", budgetId); + AddParameterWithName (command, "parleyId", parleyId); + AddParameterWithName (command, "budgetId", budgetId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int SetParleyOpen(int parleyId, bool open) + public int SetParleyOpen (int parleyId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetParleyOpen", connection); + DbCommand command = GetDbCommand ("SetParleyOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "parleyId", parleyId); - AddParameterWithName(command, "open", open); - AddParameterWithName(command, "closedDateTime", DateTime.Now); // ignored if open=true + AddParameterWithName (command, "parleyId", parleyId); + AddParameterWithName (command, "open", open); + AddParameterWithName (command, "closedDateTime", DateTime.Now); // ignored if open=true - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } diff --git a/Database/Database-PaymentCodes.cs b/Database/Database-PaymentCodes.cs index 37d7e68c..bb727b9f 100644 --- a/Database/Database-PaymentCodes.cs +++ b/Database/Database-PaymentCodes.cs @@ -7,31 +7,31 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicPaymentCode GetPaymentCode(string paymentCode) + public BasicPaymentCode GetPaymentCode (string paymentCode) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "select PaymentCodes.*, PhoneNumbers.PhoneNumber AS IssuedToPhoneNumber FROM PaymentCodes, PhoneNumbers where PaymentCodes.IssuedToPhoneId=PhoneNumbers.PhoneNumberId AND PaymentCodes.PaymentCode='" + - paymentCode.Replace("'", "''") + "'", connection); + paymentCode.Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPaymentCodeFromDataReader(reader); + return ReadPaymentCodeFromDataReader (reader); } - throw new ArgumentException("No such payment code"); + throw new ArgumentException ("No such payment code"); } } } - private BasicPaymentCode ReadPaymentCodeFromDataReader(DbDataReader reader) + private BasicPaymentCode ReadPaymentCodeFromDataReader (DbDataReader reader) { int issuedToPersonId = (int) reader["IssuedToPersonId"]; string issuedToPhoneNumber = (string) reader["IssuedToPhoneNumber"]; @@ -39,40 +39,40 @@ namespace Swarmops.Database string paymentCode = (string) reader["PaymentCode"]; bool claimed = (bool) reader["Claimed"]; - return new BasicPaymentCode(paymentCodeId, paymentCode, issuedToPhoneNumber, issuedToPersonId, claimed); + return new BasicPaymentCode (paymentCodeId, paymentCode, issuedToPhoneNumber, issuedToPersonId, claimed); } - public int CreatePaymentCode(string paymentCode, string issuingPhoneNumber, int issuingPersonId) + public int CreatePaymentCode (string paymentCode, string issuingPhoneNumber, int issuingPersonId) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePaymentCode", connection); + DbCommand command = GetDbCommand ("CreatePaymentCode", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", issuingPersonId); - AddParameterWithName(command, "phoneNumber", issuingPhoneNumber); - AddParameterWithName(command, "paymentCode", paymentCode); + AddParameterWithName (command, "personId", issuingPersonId); + AddParameterWithName (command, "phoneNumber", issuingPhoneNumber); + AddParameterWithName (command, "paymentCode", paymentCode); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int ClaimPaymentCode(int paymentCodeId, int claimingPersonId) + public int ClaimPaymentCode (int paymentCodeId, int claimingPersonId) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClaimPaymentCode", connection); + DbCommand command = GetDbCommand ("ClaimPaymentCode", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentCodeId", paymentCodeId); - AddParameterWithName(command, "personId", claimingPersonId); + AddParameterWithName (command, "paymentCodeId", paymentCodeId); + AddParameterWithName (command, "personId", claimingPersonId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } } diff --git a/Database/Database-PaymentGroups.cs b/Database/Database-PaymentGroups.cs index d6e8181f..cb587a3f 100644 --- a/Database/Database-PaymentGroups.cs +++ b/Database/Database-PaymentGroups.cs @@ -15,19 +15,19 @@ namespace Swarmops.Database "Tag,CreatedDateTime,CreatedByPersonId,Open " + // 5-9 "FROM PaymentGroups "; - private static BasicPaymentGroup ReadPaymentGroupFromDataReader(IDataRecord reader) + private static BasicPaymentGroup ReadPaymentGroupFromDataReader (IDataRecord reader) { - int paymentGroupId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - int currencyId = reader.GetInt32(2); - Int64 amountCents = reader.GetInt64(3); - DateTime dateTime = reader.GetDateTime(4); - string tag = reader.GetString(5); - DateTime createdDateTime = reader.GetDateTime(6); - int createdByPersonId = reader.GetInt32(7); - bool open = reader.GetBoolean(8); + int paymentGroupId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + int currencyId = reader.GetInt32 (2); + Int64 amountCents = reader.GetInt64 (3); + DateTime dateTime = reader.GetDateTime (4); + string tag = reader.GetString (5); + DateTime createdDateTime = reader.GetDateTime (6); + int createdByPersonId = reader.GetInt32 (7); + bool open = reader.GetBoolean (8); - return new BasicPaymentGroup(paymentGroupId, organizationId, dateTime, currencyId, amountCents, tag, + return new BasicPaymentGroup (paymentGroupId, organizationId, dateTime, currencyId, amountCents, tag, createdByPersonId, createdDateTime, open); } @@ -35,22 +35,23 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicPaymentGroup GetPaymentGroupByTag(int organizationId, string tag) + public BasicPaymentGroup GetPaymentGroupByTag (int organizationId, string tag) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + paymentGroupFieldSequence + - "WHERE OrganizationId=" + organizationId + " AND Tag='" + tag.Replace("'", "''") + "'", + GetDbCommand ("SELECT" + paymentGroupFieldSequence + + "WHERE OrganizationId=" + organizationId + " AND Tag='" + tag.Replace ("'", "''") + + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPaymentGroupFromDataReader(reader); + return ReadPaymentGroupFromDataReader (reader); } return null; @@ -59,31 +60,31 @@ namespace Swarmops.Database } - public BasicPaymentGroup GetPaymentGroup(int paymentGroupId) + public BasicPaymentGroup GetPaymentGroup (int paymentGroupId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + paymentGroupFieldSequence + - "WHERE PaymentGroupId=" + paymentGroupId, + GetDbCommand ("SELECT" + paymentGroupFieldSequence + + "WHERE PaymentGroupId=" + paymentGroupId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPaymentGroupFromDataReader(reader); + return ReadPaymentGroupFromDataReader (reader); } - throw new ArgumentException("No such PaymentGroupId:" + paymentGroupId); + throw new ArgumentException ("No such PaymentGroupId:" + paymentGroupId); } } } - public BasicPaymentGroup[] GetPaymentGroups(params object[] conditions) + public BasicPaymentGroup[] GetPaymentGroups (params object[] conditions) { List result = new List(); @@ -92,15 +93,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + paymentGroupFieldSequence + ConstructWhereClause("PaymentGroups", conditions), + GetDbCommand ( + "SELECT" + paymentGroupFieldSequence + ConstructWhereClause ("PaymentGroups", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPaymentGroupFromDataReader(reader)); + result.Add (ReadPaymentGroupFromDataReader (reader)); } return result.ToArray(); @@ -112,89 +113,89 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreatePaymentGroup(int organizationId, DateTime dateTime, int currencyId, DateTime createdDateTime, + public int CreatePaymentGroup (int organizationId, DateTime dateTime, int currencyId, DateTime createdDateTime, int createdByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePaymentGroup", connection); + DbCommand command = GetDbCommand ("CreatePaymentGroup", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "dateTime", dateTime); - AddParameterWithName(command, "currencyId", currencyId); - AddParameterWithName(command, "createdDateTime", createdDateTime); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "dateTime", dateTime); + AddParameterWithName (command, "currencyId", currencyId); + AddParameterWithName (command, "createdDateTime", createdDateTime); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetPaymentGroupOpen(int paymentGroupId, bool open) + public void SetPaymentGroupOpen (int paymentGroupId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPaymentGroupOpen", connection); + DbCommand command = GetDbCommand ("SetPaymentGroupOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetPaymentGroupAmount(int paymentGroupId, double amount) + public void SetPaymentGroupAmount (int paymentGroupId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPaymentGroupAmount", connection); + DbCommand command = GetDbCommand ("SetPaymentGroupAmount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "amount", amount); command.ExecuteNonQuery(); } } - public void SetPaymentGroupAmount(int paymentGroupId, Int64 amountCents) + public void SetPaymentGroupAmount (int paymentGroupId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPaymentGroupAmountPrecise", connection); + DbCommand command = GetDbCommand ("SetPaymentGroupAmountPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "amountCents", amountCents); command.ExecuteNonQuery(); } } - public void SetPaymentGroupTag(int paymentGroupId, string reference) + public void SetPaymentGroupTag (int paymentGroupId, string reference) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPaymentGroupTag", connection); + DbCommand command = GetDbCommand ("SetPaymentGroupTag", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "tag", reference); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "tag", reference); command.ExecuteNonQuery(); } diff --git a/Database/Database-Payments.cs b/Database/Database-Payments.cs index 97cba898..0c8dc108 100644 --- a/Database/Database-Payments.cs +++ b/Database/Database-Payments.cs @@ -19,61 +19,61 @@ namespace Swarmops.Database " PaymentInformationId,PaymentId,PaymentInformationTypes.Name,Data " + // 0-4 " FROM PaymentInformation JOIN PaymentInformationTypes USING (PaymentInformationTypeId) "; - private static BasicPayment ReadPaymentFromDataReader(IDataRecord reader) + private static BasicPayment ReadPaymentFromDataReader (IDataRecord reader) { - int paymentId = reader.GetInt32(0); - int paymentGroupId = reader.GetInt32(1); - Int64 amountCents = reader.GetInt64(2); - string reference = reader.GetString(3); - string fromAccount = reader.GetString(4); - string key = reader.GetString(5); - bool hasImage = reader.GetBoolean(6); - int outboundInvoiceId = reader.GetInt32(7); + int paymentId = reader.GetInt32 (0); + int paymentGroupId = reader.GetInt32 (1); + Int64 amountCents = reader.GetInt64 (2); + string reference = reader.GetString (3); + string fromAccount = reader.GetString (4); + string key = reader.GetString (5); + bool hasImage = reader.GetBoolean (6); + int outboundInvoiceId = reader.GetInt32 (7); - return new BasicPayment(paymentId, paymentGroupId, amountCents, reference, fromAccount, key, hasImage, + return new BasicPayment (paymentId, paymentGroupId, amountCents, reference, fromAccount, key, hasImage, outboundInvoiceId); } - private static BasicPaymentInformation ReadPaymentInformationFromDataReader(IDataRecord reader) + private static BasicPaymentInformation ReadPaymentInformationFromDataReader (IDataRecord reader) { - string dataTypeString = reader.GetString(2); - string data = reader.GetString(3); + string dataTypeString = reader.GetString (2); + string data = reader.GetString (3); PaymentInformationType dataType = - (PaymentInformationType) Enum.Parse(typeof (PaymentInformationType), dataTypeString, true); + (PaymentInformationType) Enum.Parse (typeof (PaymentInformationType), dataTypeString, true); - return new BasicPaymentInformation(dataType, data); + return new BasicPaymentInformation (dataType, data); } #endregion #region Database record reading -- SELECT clauses - public BasicPayment GetPayment(int paymentId) + public BasicPayment GetPayment (int paymentId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + paymentFieldSequence + - "WHERE PaymentId=" + paymentId, + GetDbCommand ("SELECT" + paymentFieldSequence + + "WHERE PaymentId=" + paymentId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPaymentFromDataReader(reader); + return ReadPaymentFromDataReader (reader); } - throw new ArgumentException("No such PaymentId:" + paymentId); + throw new ArgumentException ("No such PaymentId:" + paymentId); } } } - public BasicPayment[] GetPayments(params object[] conditions) + public BasicPayment[] GetPayments (params object[] conditions) { List result = new List(); @@ -82,14 +82,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + paymentFieldSequence + ConstructWhereClause("Payments", conditions), connection); + GetDbCommand ( + "SELECT" + paymentFieldSequence + ConstructWhereClause ("Payments", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPaymentFromDataReader(reader)); + result.Add (ReadPaymentFromDataReader (reader)); } return result.ToArray(); @@ -98,7 +98,7 @@ namespace Swarmops.Database } - public BasicPaymentInformation[] GetPaymentInformation(int paymentId) + public BasicPaymentInformation[] GetPaymentInformation (int paymentId) { List result = new List(); @@ -107,14 +107,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + paymentInformationFieldSequence + " WHERE PaymentId=" + paymentId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPaymentInformationFromDataReader(reader)); + result.Add (ReadPaymentInformationFromDataReader (reader)); } return result.ToArray(); @@ -126,71 +126,72 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreatePayment(int paymentGroupId, double amount, string reference, string fromAccount, string key, + public int CreatePayment (int paymentGroupId, double amount, string reference, string fromAccount, string key, bool hasImage, int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayment", connection); + DbCommand command = GetDbCommand ("CreatePayment", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "amount", amount); - AddParameterWithName(command, "reference", reference); - AddParameterWithName(command, "fromAccount", fromAccount); - AddParameterWithName(command, "paymentKey", key); - AddParameterWithName(command, "hasImage", hasImage); - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "amount", amount); + AddParameterWithName (command, "reference", reference); + AddParameterWithName (command, "fromAccount", fromAccount); + AddParameterWithName (command, "paymentKey", key); + AddParameterWithName (command, "hasImage", hasImage); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreatePayment(int paymentGroupId, Int64 amountCents, string reference, string fromAccount, string key, + public int CreatePayment (int paymentGroupId, Int64 amountCents, string reference, string fromAccount, + string key, bool hasImage, int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePaymentPrecise", connection); + DbCommand command = GetDbCommand ("CreatePaymentPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentGroupId", paymentGroupId); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "reference", reference); - AddParameterWithName(command, "fromAccount", fromAccount); - AddParameterWithName(command, "paymentKey", key); - AddParameterWithName(command, "hasImage", hasImage); - AddParameterWithName(command, "outboundInvoiceId", outboundInvoiceId); + AddParameterWithName (command, "paymentGroupId", paymentGroupId); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "reference", reference); + AddParameterWithName (command, "fromAccount", fromAccount); + AddParameterWithName (command, "paymentKey", key); + AddParameterWithName (command, "hasImage", hasImage); + AddParameterWithName (command, "outboundInvoiceId", outboundInvoiceId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreatePaymentInformation(int paymentId, PaymentInformationType type, string data) + public int CreatePaymentInformation (int paymentId, PaymentInformationType type, string data) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePaymentInformation", connection); + DbCommand command = GetDbCommand ("CreatePaymentInformation", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentId", paymentId); - AddParameterWithName(command, "dataTypeString", type.ToString()); - AddParameterWithName(command, "data", data); + AddParameterWithName (command, "paymentId", paymentId); + AddParameterWithName (command, "dataTypeString", type.ToString()); + AddParameterWithName (command, "data", data); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - [Obsolete("This should never be called, ever: it ruins trackability.")] - public void DeletePayment(int paymentId) + [Obsolete ("This should never be called, ever: it ruins trackability.")] + public void DeletePayment (int paymentId) { // This function is necessary since the Swedish bank system only allows for a dupe check AFTER all payments // have been communicated, so they are created as data is received. If the data was a dupe, it is therefore @@ -202,10 +203,10 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("DeletePayment", connection); + DbCommand command = GetDbCommand ("DeletePayment", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentId", paymentId); + AddParameterWithName (command, "paymentId", paymentId); command.ExecuteNonQuery(); } diff --git a/Database/Database-Payouts.cs b/Database/Database-Payouts.cs index 287a798b..76c426b1 100644 --- a/Database/Database-Payouts.cs +++ b/Database/Database-Payouts.cs @@ -26,31 +26,31 @@ namespace Swarmops.Database private const string payoutDependencyTableJoin = " FinancialDependencyTypes.FinancialDependencyTypeId=PayoutDependencies.FinancialDependencyTypeId "; - private static BasicPayout ReadPayoutFromDataReader(IDataRecord reader) + private static BasicPayout ReadPayoutFromDataReader (IDataRecord reader) { - int payoutId = reader.GetInt32(0); - int organizationId = reader.GetInt32(1); - string bank = reader.GetString(2); - string account = reader.GetString(3); - string reference = reader.GetString(4); - Int64 amountCents = reader.GetInt64(5); - DateTime expectedTransactionDate = reader.GetDateTime(6); - bool open = reader.GetBoolean(7); - DateTime createdDateTime = reader.GetDateTime(8); - int createdByPersonId = reader.GetInt32(9); + int payoutId = reader.GetInt32 (0); + int organizationId = reader.GetInt32 (1); + string bank = reader.GetString (2); + string account = reader.GetString (3); + string reference = reader.GetString (4); + Int64 amountCents = reader.GetInt64 (5); + DateTime expectedTransactionDate = reader.GetDateTime (6); + bool open = reader.GetBoolean (7); + DateTime createdDateTime = reader.GetDateTime (8); + int createdByPersonId = reader.GetInt32 (9); - return new BasicPayout(payoutId, organizationId, bank, account, reference, amountCents, + return new BasicPayout (payoutId, organizationId, bank, account, reference, amountCents, expectedTransactionDate, open, createdDateTime, createdByPersonId); } - private static BasicFinancialDependency ReadPayoutDependencyFromDataReader(IDataRecord reader) + private static BasicFinancialDependency ReadPayoutDependencyFromDataReader (IDataRecord reader) { - int payoutId = reader.GetInt32(0); - string financialDependencyTypeString = reader.GetString(1); - int foreignId = reader.GetInt32(2); + int payoutId = reader.GetInt32 (0); + string financialDependencyTypeString = reader.GetString (1); + int foreignId = reader.GetInt32 (2); - return new BasicFinancialDependency(payoutId, - (FinancialDependencyType) Enum.Parse(typeof (FinancialDependencyType), financialDependencyTypeString), + return new BasicFinancialDependency (payoutId, + (FinancialDependencyType) Enum.Parse (typeof (FinancialDependencyType), financialDependencyTypeString), foreignId); } @@ -58,31 +58,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicPayout GetPayout(int payoutId) + public BasicPayout GetPayout (int payoutId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + payoutFieldSequence + - "WHERE PayoutId=" + payoutId, + GetDbCommand ("SELECT" + payoutFieldSequence + + "WHERE PayoutId=" + payoutId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPayoutFromDataReader(reader); + return ReadPayoutFromDataReader (reader); } - throw new ArgumentException("No such PayoutId:" + payoutId); + throw new ArgumentException ("No such PayoutId:" + payoutId); } } } - public BasicFinancialDependency[] GetPayoutDependencies(int payoutId) + public BasicFinancialDependency[] GetPayoutDependencies (int payoutId) { List result = new List(); @@ -91,15 +91,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT" + payoutDependencyFieldSequence + - "WHERE PayoutDependencies.PayoutId=" + payoutId + " AND " + payoutDependencyTableJoin, + GetDbCommand ("SELECT" + payoutDependencyFieldSequence + + "WHERE PayoutDependencies.PayoutId=" + payoutId + " AND " + payoutDependencyTableJoin, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPayoutDependencyFromDataReader(reader)); + result.Add (ReadPayoutDependencyFromDataReader (reader)); } } } @@ -108,31 +108,31 @@ namespace Swarmops.Database } - public int GetPayoutIdFromDependency(IHasIdentity foreignObject, FinancialDependencyType typeName) + public int GetPayoutIdFromDependency (IHasIdentity foreignObject, FinancialDependencyType typeName) { - return GetPayoutIdFromDependency(foreignObject.Identity, typeName.ToString()); + return GetPayoutIdFromDependency (foreignObject.Identity, typeName.ToString()); } - private int GetPayoutIdFromDependency(int foreignObjectId, string financialDependencyTypeName) + private int GetPayoutIdFromDependency (int foreignObjectId, string financialDependencyTypeName) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + payoutDependencyFieldSequence + - "WHERE PayoutDependencies.ForeignId=" + - foreignObjectId.ToString(CultureInfo.InvariantCulture) + - " AND FinancialDependencyTypes.Name='" + financialDependencyTypeName + "'" + - // enum - no sanitation necessary - " AND " + payoutDependencyTableJoin, + GetDbCommand ("SELECT" + payoutDependencyFieldSequence + + "WHERE PayoutDependencies.ForeignId=" + + foreignObjectId.ToString (CultureInfo.InvariantCulture) + + " AND FinancialDependencyTypes.Name='" + financialDependencyTypeName + "'" + + // enum - no sanitation necessary + " AND " + payoutDependencyTableJoin, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } return 0; } @@ -140,13 +140,13 @@ namespace Swarmops.Database } - public int GetPayoutIdFromDependency(IHasIdentity foreignObject) + public int GetPayoutIdFromDependency (IHasIdentity foreignObject) { - return GetPayoutIdFromDependency(foreignObject.Identity, GetForeignTypeString(foreignObject)); + return GetPayoutIdFromDependency (foreignObject.Identity, GetForeignTypeString (foreignObject)); } - public BasicPayout[] GetPayouts(params object[] conditions) + public BasicPayout[] GetPayouts (params object[] conditions) { List result = new List(); @@ -155,14 +155,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + payoutFieldSequence + ConstructWhereClause("Payouts", conditions), connection); + GetDbCommand ( + "SELECT" + payoutFieldSequence + ConstructWhereClause ("Payouts", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPayoutFromDataReader(reader)); + result.Add (ReadPayoutFromDataReader (reader)); } return result.ToArray(); @@ -174,167 +174,167 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreatePayout(int organizationId, string bank, string account, string reference, + public int CreatePayout (int organizationId, string bank, string account, string reference, double amount, DateTime expectedTransactionDate, int createdByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayout", connection); + DbCommand command = GetDbCommand ("CreatePayout", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "bank", bank); - AddParameterWithName(command, "account", account); - AddParameterWithName(command, "reference", reference); - AddParameterWithName(command, "amount", amount); - AddParameterWithName(command, "expectedTransactionDate", expectedTransactionDate); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "bank", bank); + AddParameterWithName (command, "account", account); + AddParameterWithName (command, "reference", reference); + AddParameterWithName (command, "amount", amount); + AddParameterWithName (command, "expectedTransactionDate", expectedTransactionDate); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreatePayout(int organizationId, string bank, string account, string reference, + public int CreatePayout (int organizationId, string bank, string account, string reference, Int64 amountCents, DateTime expectedTransactionDate, int createdByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayoutPrecise", connection); + DbCommand command = GetDbCommand ("CreatePayoutPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "bank", bank); - AddParameterWithName(command, "account", account); - AddParameterWithName(command, "reference", reference); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "expectedTransactionDate", expectedTransactionDate); - AddParameterWithName(command, "createdDateTime", DateTime.Now); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "bank", bank); + AddParameterWithName (command, "account", account); + AddParameterWithName (command, "reference", reference); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "expectedTransactionDate", expectedTransactionDate); + AddParameterWithName (command, "createdDateTime", DateTime.Now); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void CreatePayoutDependency(int payoutId, FinancialDependencyType dependencyType, int foreignId) + public void CreatePayoutDependency (int payoutId, FinancialDependencyType dependencyType, int foreignId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayoutDependency", connection); + DbCommand command = GetDbCommand ("CreatePayoutDependency", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); - AddParameterWithName(command, "financialDependencyType", dependencyType.ToString()); - AddParameterWithName(command, "foreignId", foreignId); + AddParameterWithName (command, "payoutId", payoutId); + AddParameterWithName (command, "financialDependencyType", dependencyType.ToString()); + AddParameterWithName (command, "foreignId", foreignId); command.ExecuteNonQuery(); } } - public void MovePayoutDependencies(int fromPayoutId, int toPayoutId) + public void MovePayoutDependencies (int fromPayoutId, int toPayoutId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("MovePayoutDependencies", connection); + DbCommand command = GetDbCommand ("MovePayoutDependencies", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "fromPayoutId", fromPayoutId); - AddParameterWithName(command, "toPayoutId", toPayoutId); + AddParameterWithName (command, "fromPayoutId", fromPayoutId); + AddParameterWithName (command, "toPayoutId", toPayoutId); command.ExecuteNonQuery(); } } - public void ClearPayoutDependencies(int payoutId) + public void ClearPayoutDependencies (int payoutId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClearPayoutDependencies", connection); + DbCommand command = GetDbCommand ("ClearPayoutDependencies", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); + AddParameterWithName (command, "payoutId", payoutId); command.ExecuteNonQuery(); } } - public void SetPayoutOpen(int payoutId, bool open) + public void SetPayoutOpen (int payoutId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayoutOpen", connection); + DbCommand command = GetDbCommand ("SetPayoutOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "payoutId", payoutId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetPayoutAmount(int payoutId, double amount) + public void SetPayoutAmount (int payoutId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayoutAmount", connection); + DbCommand command = GetDbCommand ("SetPayoutAmount", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); - AddParameterWithName(command, "amount", amount); + AddParameterWithName (command, "payoutId", payoutId); + AddParameterWithName (command, "amount", amount); command.ExecuteNonQuery(); } } - public void SetPayoutAmount(int payoutId, Int64 amountCents) + public void SetPayoutAmount (int payoutId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayoutAmountPrecise", connection); + DbCommand command = GetDbCommand ("SetPayoutAmountPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); - AddParameterWithName(command, "amountCents", amountCents); + AddParameterWithName (command, "payoutId", payoutId); + AddParameterWithName (command, "amountCents", amountCents); command.ExecuteNonQuery(); } } - public void SetPayoutReference(int payoutId, string reference) + public void SetPayoutReference (int payoutId, string reference) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayoutReference", connection); + DbCommand command = GetDbCommand ("SetPayoutReference", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payoutId", payoutId); - AddParameterWithName(command, "reference", reference); + AddParameterWithName (command, "payoutId", payoutId); + AddParameterWithName (command, "reference", reference); command.ExecuteNonQuery(); } diff --git a/Database/Database-Payroll.cs b/Database/Database-Payroll.cs index c1f22336..88a3d6d1 100644 --- a/Database/Database-Payroll.cs +++ b/Database/Database-Payroll.cs @@ -16,22 +16,22 @@ namespace Swarmops.Database "SubtractiveTaxLevelId,AdditiveTaxLevel " + // 10-11 "FROM Payroll "; - private BasicPayrollItem ReadPayrollItemFromDataReader(DbDataReader reader) + private BasicPayrollItem ReadPayrollItemFromDataReader (DbDataReader reader) { - int payrollItemId = reader.GetInt32(0); - int personId = reader.GetInt32(1); - int organizationId = reader.GetInt32(2); - int countryId = reader.GetInt32(3); - DateTime employedDate = reader.GetDateTime(4); - int reportsToPersonId = reader.GetInt32(5); - Int64 baseSalaryCents = reader.GetInt64(6); - int budgetId = reader.GetInt32(7); - bool open = reader.GetBoolean(8); - DateTime terminatedDate = reader.GetDateTime(9); - int subtractiveTaxLevelId = reader.GetInt32(10); - double additiveTaxLevel = reader.GetDouble(11); + int payrollItemId = reader.GetInt32 (0); + int personId = reader.GetInt32 (1); + int organizationId = reader.GetInt32 (2); + int countryId = reader.GetInt32 (3); + DateTime employedDate = reader.GetDateTime (4); + int reportsToPersonId = reader.GetInt32 (5); + Int64 baseSalaryCents = reader.GetInt64 (6); + int budgetId = reader.GetInt32 (7); + bool open = reader.GetBoolean (8); + DateTime terminatedDate = reader.GetDateTime (9); + int subtractiveTaxLevelId = reader.GetInt32 (10); + double additiveTaxLevel = reader.GetDouble (11); - return new BasicPayrollItem(payrollItemId, personId, organizationId, countryId, employedDate, + return new BasicPayrollItem (payrollItemId, personId, organizationId, countryId, employedDate, reportsToPersonId, baseSalaryCents, budgetId, open, terminatedDate, subtractiveTaxLevelId, additiveTaxLevel); } @@ -40,24 +40,24 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicPayrollItem GetPayrollItem(int payrollItemId) + public BasicPayrollItem GetPayrollItem (int payrollItemId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + payrollFieldSequence + "WHERE PayrollItemId=" + payrollItemId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPayrollItemFromDataReader(reader); + return ReadPayrollItemFromDataReader (reader); } - throw new ArgumentException("Unknown Payroll Item Id"); + throw new ArgumentException ("Unknown Payroll Item Id"); } } } @@ -70,7 +70,7 @@ namespace Swarmops.Database /// specifiers. /// /// The list of matching payroll items. - public BasicPayrollItem[] GetPayroll(params object[] conditions) + public BasicPayrollItem[] GetPayroll (params object[] conditions) { List result = new List(); @@ -79,14 +79,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + payrollFieldSequence + ConstructWhereClause("Payroll", conditions), connection); + GetDbCommand ( + "SELECT" + payrollFieldSequence + ConstructWhereClause ("Payroll", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPayrollItemFromDataReader(reader)); + result.Add (ReadPayrollItemFromDataReader (reader)); } return result.ToArray(); @@ -98,7 +98,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreatePayrollItem(int personId, int organizationId, DateTime employedDate, int reportsToPersonId, + public int CreatePayrollItem (int personId, int organizationId, DateTime employedDate, int reportsToPersonId, int countryId, Int64 baseSalaryCents, int subtractiveTaxLevelId, double additiveTaxLevel, int budgetId) { @@ -106,69 +106,69 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreatePayrollItemPrecise", connection); + DbCommand command = GetDbCommand ("CreatePayrollItemPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "employedDate", DateTime.Now); - AddParameterWithName(command, "reportsToPersonId", reportsToPersonId); - AddParameterWithName(command, "countryId", countryId); - AddParameterWithName(command, "baseSalaryCents", baseSalaryCents); - AddParameterWithName(command, "subtractiveTaxLevelId", subtractiveTaxLevelId); - AddParameterWithName(command, "additiveTaxLevel", additiveTaxLevel); - AddParameterWithName(command, "budgetId", budgetId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "employedDate", DateTime.Now); + AddParameterWithName (command, "reportsToPersonId", reportsToPersonId); + AddParameterWithName (command, "countryId", countryId); + AddParameterWithName (command, "baseSalaryCents", baseSalaryCents); + AddParameterWithName (command, "subtractiveTaxLevelId", subtractiveTaxLevelId); + AddParameterWithName (command, "additiveTaxLevel", additiveTaxLevel); + AddParameterWithName (command, "budgetId", budgetId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetPayrollItemOpen(int payrollItemId, bool open) + public void SetPayrollItemOpen (int payrollItemId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayrollItemOpen", connection); + DbCommand command = GetDbCommand ("SetPayrollItemOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "open", open); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "open", open); command.ExecuteNonQuery(); } } - public void SetPayrollItemTerminatedDate(int payrollItemId, DateTime dateTimeTerminated) + public void SetPayrollItemTerminatedDate (int payrollItemId, DateTime dateTimeTerminated) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayrollItemOpen", connection); + DbCommand command = GetDbCommand ("SetPayrollItemOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "dateTimeTerminated", dateTimeTerminated); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "dateTimeTerminated", dateTimeTerminated); command.ExecuteNonQuery(); } } - public void SetPayrollItemBaseSalary(int payrollItemId, Int64 baseSalaryCents) + public void SetPayrollItemBaseSalary (int payrollItemId, Int64 baseSalaryCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPayrollItemBaseSalaryPrecise", connection); + DbCommand command = GetDbCommand ("SetPayrollItemBaseSalaryPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "baseSalaryCents", baseSalaryCents); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "baseSalaryCents", baseSalaryCents); command.ExecuteNonQuery(); } diff --git a/Database/Database-PayrollAdjustments.cs b/Database/Database-PayrollAdjustments.cs index 42823f54..0081cd19 100644 --- a/Database/Database-PayrollAdjustments.cs +++ b/Database/Database-PayrollAdjustments.cs @@ -15,17 +15,17 @@ namespace Swarmops.Database "Open,SalaryId " + // 5-6 "FROM PayrollAdjustments "; - private BasicPayrollAdjustment ReadPayrollAdjustmentFromDataReader(DbDataReader reader) + private BasicPayrollAdjustment ReadPayrollAdjustmentFromDataReader (DbDataReader reader) { - int payrollAdjustmentId = reader.GetInt32(0); - int payrollAdjustmentTypeId = reader.GetInt32(1); - int payrollItemId = reader.GetInt32(2); - Int64 amountCents = reader.GetInt64(3); - string description = reader.GetString(4); - bool open = reader.GetBoolean(5); - int salaryId = reader.GetInt32(6); + int payrollAdjustmentId = reader.GetInt32 (0); + int payrollAdjustmentTypeId = reader.GetInt32 (1); + int payrollItemId = reader.GetInt32 (2); + Int64 amountCents = reader.GetInt64 (3); + string description = reader.GetString (4); + bool open = reader.GetBoolean (5); + int salaryId = reader.GetInt32 (6); - return new BasicPayrollAdjustment(payrollAdjustmentId, payrollItemId, + return new BasicPayrollAdjustment (payrollAdjustmentId, payrollItemId, (PayrollAdjustmentType) payrollAdjustmentTypeId, amountCents, description, open, salaryId); } @@ -34,14 +34,14 @@ namespace Swarmops.Database #region Record reading - SELECT statements - public BasicPayrollAdjustment GetPayrollAdjustment(int payrollAdjustmentId) + public BasicPayrollAdjustment GetPayrollAdjustment (int payrollAdjustmentId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + payrollAdjustmentFieldSequence + "WHERE PayrollAdjustmentId=" + payrollAdjustmentId + ";", connection); @@ -49,10 +49,10 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadPayrollAdjustmentFromDataReader(reader); + return ReadPayrollAdjustmentFromDataReader (reader); } - throw new ArgumentException("Unknown Payroll Adjustment Id"); + throw new ArgumentException ("Unknown Payroll Adjustment Id"); } } } @@ -65,7 +65,7 @@ namespace Swarmops.Database /// specifiers. /// /// The list of matching payroll items. - public BasicPayrollAdjustment[] GetPayrollAdjustments(params object[] conditions) + public BasicPayrollAdjustment[] GetPayrollAdjustments (params object[] conditions) { List result = new List(); @@ -74,15 +74,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + payrollAdjustmentFieldSequence + - ConstructWhereClause("PayrollAdjustments", conditions), connection); + ConstructWhereClause ("PayrollAdjustments", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPayrollAdjustmentFromDataReader(reader)); + result.Add (ReadPayrollAdjustmentFromDataReader (reader)); } return result.ToArray(); @@ -94,67 +94,67 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, double amount, + public int CreatePayrollAdjustment (int payrollItemId, PayrollAdjustmentType type, double amount, string description) { if (description.Length > 128) { - description = description.Substring(0, 128); + description = description.Substring (0, 128); } using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayrollAdjustment", connection); + DbCommand command = GetDbCommand ("CreatePayrollAdjustment", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "payrollAdjustmentTypeId", (int) type); - AddParameterWithName(command, "amount", amount); - AddParameterWithName(command, "description", description); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "payrollAdjustmentTypeId", (int) type); + AddParameterWithName (command, "amount", amount); + AddParameterWithName (command, "description", description); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, + public int CreatePayrollAdjustment (int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, string description) { if (description.Length > 128) { - description = description.Substring(0, 128); + description = description.Substring (0, 128); } using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePayrollAdjustmentPrecise", connection); + DbCommand command = GetDbCommand ("CreatePayrollAdjustmentPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "payrollAdjustmentTypeId", (int) type); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "description", description); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "payrollAdjustmentTypeId", (int) type); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "description", description); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void ClosePayrollAdjustment(int payrollAdjustmentId, int salaryId) + public void ClosePayrollAdjustment (int payrollAdjustmentId, int salaryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("ClosePayrollAdjustment", connection); + DbCommand command = GetDbCommand ("ClosePayrollAdjustment", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollAdjustmentId", payrollAdjustmentId); - AddParameterWithName(command, "salaryId", salaryId); + AddParameterWithName (command, "payrollAdjustmentId", payrollAdjustmentId); + AddParameterWithName (command, "salaryId", salaryId); command.ExecuteNonQuery(); } diff --git a/Database/Database-People.cs b/Database/Database-People.cs index 88a54994..7faec35e 100644 --- a/Database/Database-People.cs +++ b/Database/Database-People.cs @@ -18,20 +18,20 @@ namespace Swarmops.Database " Birthdate, GenderId " + // 10-11 " FROM People "; - private static BasicPerson ReadPersonFromDataReader(DbDataReader reader) + private static BasicPerson ReadPersonFromDataReader (DbDataReader reader) { - int personId = reader.GetInt32(0); - string passwordHash = reader.GetString(1); - string name = reader.GetString(2); - string email = reader.GetString(3); - string street = reader.GetString(4); - string postalCode = reader.GetString(5); - string cityName = reader.GetString(6); - int countryId = reader.GetInt32(7); - string phone = reader.GetString(8); - int geographyId = reader.GetInt32(9); - DateTime birthdate = reader.GetDateTime(10); - int genderId = reader.GetInt32(11); + int personId = reader.GetInt32 (0); + string passwordHash = reader.GetString (1); + string name = reader.GetString (2); + string email = reader.GetString (3); + string street = reader.GetString (4); + string postalCode = reader.GetString (5); + string cityName = reader.GetString (6); + int countryId = reader.GetInt32 (7); + string phone = reader.GetString (8); + int geographyId = reader.GetInt32 (9); + DateTime birthdate = reader.GetDateTime (10); + int genderId = reader.GetInt32 (11); // Fix broken names, emails @@ -39,13 +39,13 @@ namespace Swarmops.Database email = email.ToLower().Trim(); name = name.Trim(); - while (name.Contains(" ")) + while (name.Contains (" ")) { - name = name.Replace(" ", " "); + name = name.Replace (" ", " "); } - return new BasicPerson(personId, passwordHash, name, email, street, postalCode, cityName, countryId, phone, + return new BasicPerson (personId, passwordHash, name, email, street, postalCode, cityName, countryId, phone, geographyId, birthdate, (PersonGender) genderId); } @@ -53,7 +53,7 @@ namespace Swarmops.Database #region Retrieving lists of people based on wildcards or partial data - public BasicPerson[] GetPeopleFromNamePattern(string namePattern) + public BasicPerson[] GetPeopleFromNamePattern (string namePattern) { List result = new List(); @@ -62,9 +62,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + personFieldSequence + " WHERE Name like '" + - GetSqlPatternFromNamePattern(namePattern).Replace("'", "''") + "'", + GetSqlPatternFromNamePattern (namePattern).Replace ("'", "''") + "'", connection); command.CommandTimeout = 120; @@ -72,7 +72,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -80,21 +80,21 @@ namespace Swarmops.Database return result.ToArray(); } - private string GetSqlPatternFromNamePattern(string namePattern) + private string GetSqlPatternFromNamePattern (string namePattern) { // Remove any injection codes - namePattern = SqlSanitize(namePattern).Replace("%", String.Empty).Trim(); + namePattern = SqlSanitize (namePattern).Replace ("%", String.Empty).Trim(); - while (namePattern.Contains(" ")) + while (namePattern.Contains (" ")) { - namePattern = namePattern.Replace(" ", " "); + namePattern = namePattern.Replace (" ", " "); } if (namePattern.Length > 0) { - namePattern = namePattern.Replace(" ", "% ") + "%"; + namePattern = namePattern.Replace (" ", "% ") + "%"; - if (!namePattern.Contains(" ")) + if (!namePattern.Contains (" ")) { namePattern = "%" + namePattern; } @@ -105,7 +105,7 @@ namespace Swarmops.Database return string.Empty; // If no valid search string was supplied } - public BasicPerson[] GetPeopleFromBirthdate(DateTime fromdate, DateTime todate) + public BasicPerson[] GetPeopleFromBirthdate (DateTime fromdate, DateTime todate) { // Is this really valid for MySQL? Yes .net connector makes @parameter substitutions @@ -116,12 +116,12 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + personFieldSequence + " WHERE BirthDate >= @fromdate AND BirthDate < @todate", connection); - AddParameterWithName(command, "fromdate", fromdate); - AddParameterWithName(command, "todate", todate); + AddParameterWithName (command, "fromdate", fromdate); + AddParameterWithName (command, "todate", todate); command.CommandTimeout = 120; @@ -129,7 +129,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -137,7 +137,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromEmailPattern(string emailPattern) + public BasicPerson[] GetPeopleFromEmailPattern (string emailPattern) { List result = new List(); @@ -146,8 +146,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE Email LIKE '" + emailPattern.Replace("'", "''") + "'", + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE Email LIKE '" + emailPattern.Replace ("'", "''") + "'", connection); command.CommandTimeout = 120; @@ -155,7 +155,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -163,7 +163,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromCityPattern(string cityPattern) + public BasicPerson[] GetPeopleFromCityPattern (string cityPattern) { List result = new List(); @@ -172,8 +172,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE City like '" + cityPattern.Replace("'", "''") + "'", + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE City like '" + cityPattern.Replace ("'", "''") + "'", connection); command.CommandTimeout = 120; @@ -181,7 +181,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -189,7 +189,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromPostalCodePattern(string pcPattern) + public BasicPerson[] GetPeopleFromPostalCodePattern (string pcPattern) { List result = new List(); @@ -198,8 +198,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE PostalCode like '" + pcPattern.Replace("'", "''") + + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE PostalCode like '" + pcPattern.Replace ("'", "''") + "'", connection); command.CommandTimeout = 120; @@ -208,7 +208,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -216,19 +216,19 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromPostalCodes(string[] postalCodes) + public BasicPerson[] GetPeopleFromPostalCodes (string[] postalCodes) { List result = new List(); for (int i = 0; i < postalCodes.Length; ++i) - postalCodes[i] = postalCodes[i].Replace("'", "''"); + postalCodes[i] = postalCodes[i].Replace ("'", "''"); - string postalCodesString = ("'" + string.Join("','", postalCodes) + "'").Replace(" ", ""); + string postalCodesString = ("'" + string.Join ("','", postalCodes) + "'").Replace (" ", ""); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + personFieldSequence + " WHERE TRIM(PostalCode) In (" + postalCodesString + ")", connection); command.CommandTimeout = 120; @@ -237,7 +237,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -245,7 +245,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromEmail(string email) + public BasicPerson[] GetPeopleFromEmail (string email) { List result = new List(); @@ -254,8 +254,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE Email='" + email.Replace("'", "''").Trim() + "'", + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE Email='" + email.Replace ("'", "''").Trim() + "'", connection); command.CommandTimeout = 120; @@ -263,7 +263,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -272,7 +272,7 @@ namespace Swarmops.Database } - public BasicPerson[] GetPeopleFromPhoneNumber(int countryId, string phoneNumber) + public BasicPerson[] GetPeopleFromPhoneNumber (int countryId, string phoneNumber) { List result = new List(); @@ -281,17 +281,17 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT " + personFieldSequence + " WHERE CountryId=" + countryId.ToString() + " AND PhoneNumber='" + - phoneNumber.Replace("'", "''") + "'", connection); + phoneNumber.Replace ("'", "''") + "'", connection); command.CommandTimeout = 300; using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -299,18 +299,18 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromPhoneNumber(string countryCode, string phoneNumber) + public BasicPerson[] GetPeopleFromPhoneNumber (string countryCode, string phoneNumber) { - BasicCountry country = GetCountry(countryCode); + BasicCountry country = GetCountry (countryCode); - return GetPeopleFromPhoneNumber(country.Identity, phoneNumber); + return GetPeopleFromPhoneNumber (country.Identity, phoneNumber); } #endregion #region Retrieving specific people or lists of people - public BasicPerson[] GetPeople(int[] personIds) + public BasicPerson[] GetPeople (int[] personIds) { if (personIds == null || personIds.Length == 0) { @@ -325,7 +325,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personFieldSequence + " WHERE PersonId in (" + JoinIds(personIds) + ")", + GetDbCommand ("SELECT " + personFieldSequence + " WHERE PersonId in (" + JoinIds (personIds) + ")", connection); command.CommandTimeout = 120; @@ -333,7 +333,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -350,14 +350,14 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + personFieldSequence, connection); + DbCommand command = GetDbCommand ("SELECT " + personFieldSequence, connection); command.CommandTimeout = 120; using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } } } @@ -366,13 +366,13 @@ namespace Swarmops.Database } - public BasicPerson GetPerson(int personId) + public BasicPerson GetPerson (int personId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + personFieldSequence + " WHERE PersonId=" + personId, + DbCommand command = GetDbCommand ("SELECT " + personFieldSequence + " WHERE PersonId=" + personId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -381,7 +381,7 @@ namespace Swarmops.Database { // Parse the person - BasicPerson person = ReadPersonFromDataReader(reader); + BasicPerson person = ReadPersonFromDataReader (reader); return person; } @@ -391,11 +391,11 @@ namespace Swarmops.Database if (Debugger.IsAttached) { - return new BasicPerson(personId, string.Empty, + return new BasicPerson (personId, string.Empty, "PERSON #" + personId.ToString() + " NOT IN DEV DB", "noreply@example.com", "Foobar 12", - "12345", "Duckville", 1, "", 1, new DateTime(1972, 1, 21), PersonGender.Unknown); + "12345", "Duckville", 1, "", 1, new DateTime (1972, 1, 21), PersonGender.Unknown); } - throw new ArgumentException("No such PersonId: " + personId.ToString()); + throw new ArgumentException ("No such PersonId: " + personId.ToString()); } } } @@ -403,7 +403,7 @@ namespace Swarmops.Database #endregion - public Dictionary GetPeopleGeographies(int[] personIds) + public Dictionary GetPeopleGeographies (int[] personIds) { Dictionary result = new Dictionary(); @@ -417,8 +417,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT PersonId, GeographyId From People WHERE PersonId in (" + JoinIds(personIds) + ")", + GetDbCommand ( + "SELECT PersonId, GeographyId From People WHERE PersonId in (" + JoinIds (personIds) + ")", connection); command.CommandTimeout = 120; @@ -426,7 +426,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetInt32(0), reader.GetInt32(1)); + result.Add (reader.GetInt32 (0), reader.GetInt32 (1)); } } } @@ -435,7 +435,7 @@ namespace Swarmops.Database } - public BasicPerson[] GetPeopleInGeographies(int[] geographyIds) + public BasicPerson[] GetPeopleInGeographies (int[] geographyIds) { if (geographyIds.Length == 0) { @@ -448,15 +448,15 @@ namespace Swarmops.Database { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + ")", + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds (geographyIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } return result.ToArray(); @@ -465,7 +465,7 @@ namespace Swarmops.Database } - public BasicPerson[] GetPeopleInGeographiesWithPattern(int[] geographyIds, string pattern) + public BasicPerson[] GetPeopleInGeographiesWithPattern (int[] geographyIds, string pattern) { if (geographyIds.Length == 0) { @@ -476,18 +476,18 @@ namespace Swarmops.Database if (pattern.Length == 0) { - return GetPeopleInGeographies(geographyIds); // no pattern => fall back to just geography + return GetPeopleInGeographies (geographyIds); // no pattern => fall back to just geography } - string sqlPattern = GetSqlPatternFromNamePattern(pattern); + string sqlPattern = GetSqlPatternFromNamePattern (pattern); List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + + GetDbCommand ( + "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds (geographyIds) + ") AND (Name like '" + sqlPattern + "' OR Email like '" + sqlPattern + "')", connection); @@ -495,7 +495,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadPersonFromDataReader(reader)); + result.Add (ReadPersonFromDataReader (reader)); } return result.ToArray(); @@ -504,87 +504,87 @@ namespace Swarmops.Database } - public void SetPersonName(int personId, string name) + public void SetPersonName (int personId, string name) { - SetPersonBasicStringValue(personId, "Name", name); + SetPersonBasicStringValue (personId, "Name", name); } - public void SetPersonPasswordHash(int personId, string passwordHash) + public void SetPersonPasswordHash (int personId, string passwordHash) { - SetPersonBasicStringValue(personId, "PasswordHash", passwordHash); + SetPersonBasicStringValue (personId, "PasswordHash", passwordHash); } - public void SetPersonStreet(int personId, string street) + public void SetPersonStreet (int personId, string street) { - SetPersonBasicStringValue(personId, "Street", street); + SetPersonBasicStringValue (personId, "Street", street); } - public void SetPersonPostalCode(int personId, string postalCode) + public void SetPersonPostalCode (int personId, string postalCode) { - SetPersonBasicStringValue(personId, "PostalCode", postalCode); + SetPersonBasicStringValue (personId, "PostalCode", postalCode); } - public void SetPersonCity(int personId, string city) + public void SetPersonCity (int personId, string city) { - SetPersonBasicStringValue(personId, "City", city); + SetPersonBasicStringValue (personId, "City", city); } - public void SetPersonPhone(int personId, string phone) + public void SetPersonPhone (int personId, string phone) { - SetPersonBasicStringValue(personId, "PhoneNumber", phone); + SetPersonBasicStringValue (personId, "PhoneNumber", phone); } - public void SetPersonEmail(int personId, string email) + public void SetPersonEmail (int personId, string email) { - SetPersonBasicStringValue(personId, "Email", email); + SetPersonBasicStringValue (personId, "Email", email); } - public int CreatePerson(string name, string email) + public int CreatePerson (string name, string email) { - return CreatePerson(name, email, string.Empty, string.Empty, string.Empty, string.Empty, 0, + return CreatePerson (name, email, string.Empty, string.Empty, string.Empty, string.Empty, 0, DateTime.MinValue, PersonGender.Unknown); } - protected void SetPersonBasicStringValue(int personId, string key, string newValue) + protected void SetPersonBasicStringValue (int personId, string key, string newValue) { - string parameterName = Char.ToLower(key[0]) + key.Substring(1); + string parameterName = Char.ToLower (key[0]) + key.Substring (1); string storedProcedureName = "SetPerson" + key; using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand(storedProcedureName, connection); + DbCommand command = GetDbCommand (storedProcedureName, connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, parameterName, newValue); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, parameterName, newValue); command.ExecuteNonQuery(); } } - public int CreatePerson(string name, string email, string phone, string street, string postalCode, string city, + public int CreatePerson (string name, string email, string phone, string street, string postalCode, string city, int countryId, DateTime birthDate, PersonGender gender) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePerson", connection); + DbCommand command = GetDbCommand ("CreatePerson", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "email", email); - AddParameterWithName(command, "passwordHash", string.Empty); - AddParameterWithName(command, "phoneNumber", phone); - AddParameterWithName(command, "street", street); - AddParameterWithName(command, "postalCode", postalCode); - AddParameterWithName(command, "city", city); - AddParameterWithName(command, "countryId", countryId); - AddParameterWithName(command, "birthdate", birthDate); - AddParameterWithName(command, "genderId", (int) gender); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "email", email); + AddParameterWithName (command, "passwordHash", string.Empty); + AddParameterWithName (command, "phoneNumber", phone); + AddParameterWithName (command, "street", street); + AddParameterWithName (command, "postalCode", postalCode); + AddParameterWithName (command, "city", city); + AddParameterWithName (command, "countryId", countryId); + AddParameterWithName (command, "birthdate", birthDate); + AddParameterWithName (command, "genderId", (int) gender); - int personId = Convert.ToInt32(command.ExecuteScalar()); + int personId = Convert.ToInt32 (command.ExecuteScalar()); return personId; } @@ -605,63 +605,63 @@ namespace Swarmops.Database } }*/ - public void SetPersonGeography(int personId, int geographyId) + public void SetPersonGeography (int personId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPersonGeography", connection); + DbCommand command = GetDbCommand ("SetPersonGeography", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "geographyId", geographyId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "geographyId", geographyId); command.ExecuteNonQuery(); } } - public void SetPersonCountry(int personId, int countryId) + public void SetPersonCountry (int personId, int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPersonCountry", connection); + DbCommand command = GetDbCommand ("SetPersonCountry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "countryId", countryId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "countryId", countryId); command.ExecuteNonQuery(); } } - public void SetPersonGender(int personId, PersonGender gender) + public void SetPersonGender (int personId, PersonGender gender) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPersonGender", connection); + DbCommand command = GetDbCommand ("SetPersonGender", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "genderId", (int) gender); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "genderId", (int) gender); command.ExecuteNonQuery(); } } - public void SetPersonBirthdate(int personId, DateTime birthdate) + public void SetPersonBirthdate (int personId, DateTime birthdate) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetPersonBirthdate", connection); + DbCommand command = GetDbCommand ("SetPersonBirthdate", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "birthdate", birthdate); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "birthdate", birthdate); command.ExecuteNonQuery(); } } diff --git a/Database/Database-Permissions.cs b/Database/Database-Permissions.cs index 072ac8da..68961c31 100644 --- a/Database/Database-Permissions.cs +++ b/Database/Database-Permissions.cs @@ -17,7 +17,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("Select RoleType, PermissionType from PermissionSpecifications", + DbCommand command = GetDbCommand ("Select RoleType, PermissionType from PermissionSpecifications", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -26,9 +26,9 @@ namespace Swarmops.Database { try { - result.Add(new BasicPermission( - (RoleType) (Enum.Parse(typeof (RoleType), reader.GetString(0), true)), - (Permission) (Enum.Parse(typeof (Permission), reader.GetString(1), true)) + result.Add (new BasicPermission ( + (RoleType) (Enum.Parse (typeof (RoleType), reader.GetString (0), true)), + (Permission) (Enum.Parse (typeof (Permission), reader.GetString (1), true)) ) ); } @@ -44,18 +44,18 @@ namespace Swarmops.Database return result.ToArray(); } - public void StoreOnePermission(int RoleTypeId, int PermissionId, bool allow) + public void StoreOnePermission (int RoleTypeId, int PermissionId, bool allow) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("StoreOnePermission", connection); + DbCommand command = GetDbCommand ("StoreOnePermission", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_RoleType", ((RoleType) RoleTypeId).ToString()); - AddParameterWithName(command, "p_PermissionType", ((Permission) PermissionId).ToString()); - AddParameterWithName(command, "p_allow", allow ? 1 : 0); + AddParameterWithName (command, "p_RoleType", ((RoleType) RoleTypeId).ToString()); + AddParameterWithName (command, "p_PermissionType", ((Permission) PermissionId).ToString()); + AddParameterWithName (command, "p_allow", allow ? 1 : 0); command.ExecuteNonQuery(); } diff --git a/Database/Database-PirateWebLog.cs b/Database/Database-PirateWebLog.cs index 7bbd4116..59d7f0f6 100644 --- a/Database/Database-PirateWebLog.cs +++ b/Database/Database-PirateWebLog.cs @@ -8,7 +8,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreatePWLogEntry(DateTime dateTimeUtc, int actingPersonId, string affectedItemType, + public int CreatePWLogEntry (DateTime dateTimeUtc, int actingPersonId, string affectedItemType, int affectedItemId, string actionType, string actionDescription, string changedField, string valueBefore, string valueAfter, string comment, string ipAddress) @@ -16,34 +16,34 @@ namespace Swarmops.Database using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePWLogEntry2", connection); + DbCommand command = GetDbCommand ("CreatePWLogEntry2", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "dateTimeUtc", dateTimeUtc); - AddParameterWithName(command, "actingPersonId", actingPersonId); - AddParameterWithName(command, "affectedItemType", affectedItemType); - AddParameterWithName(command, "affectedItemId", affectedItemId); - AddParameterWithName(command, "actionType", actionType); - AddParameterWithName(command, "actionDescription", actionDescription); - AddParameterWithName(command, "changedField", changedField); - AddParameterWithName(command, "valueBefore", valueBefore); - AddParameterWithName(command, "valueAfter", valueAfter); - AddParameterWithName(command, "comment", comment); - AddParameterWithName(command, "ipAddress", ipAddress); + AddParameterWithName (command, "dateTimeUtc", dateTimeUtc); + AddParameterWithName (command, "actingPersonId", actingPersonId); + AddParameterWithName (command, "affectedItemType", affectedItemType); + AddParameterWithName (command, "affectedItemId", affectedItemId); + AddParameterWithName (command, "actionType", actionType); + AddParameterWithName (command, "actionDescription", actionDescription); + AddParameterWithName (command, "changedField", changedField); + AddParameterWithName (command, "valueBefore", valueBefore); + AddParameterWithName (command, "valueAfter", valueAfter); + AddParameterWithName (command, "comment", comment); + AddParameterWithName (command, "ipAddress", ipAddress); - int logEntryId = Convert.ToInt32(command.ExecuteScalar()); + int logEntryId = Convert.ToInt32 (command.ExecuteScalar()); return logEntryId; } } - public DateTime CheckLogEntry(string affectedItemType, int affectedItemId, string actionType) + public DateTime CheckLogEntry (string affectedItemType, int affectedItemId, string actionType) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT Max(DateTimeUtc) from PWLog WHERE AffectedItemId=" + affectedItemId + " AND AffectedItemType='" + affectedItemType + "' AND ActionType='" + actionType + "'", connection); @@ -51,9 +51,9 @@ namespace Swarmops.Database { if (reader.Read()) { - if (!reader.IsDBNull(0)) + if (!reader.IsDBNull (0)) { - return reader.GetDateTime(0); + return reader.GetDateTime (0); } } return DateTime.MinValue; @@ -61,7 +61,7 @@ namespace Swarmops.Database } } - public BasicPWLog[] GetLatestEvents(string affectedItemType, DateTime beforeDate, int[] affectedIds, + public BasicPWLog[] GetLatestEvents (string affectedItemType, DateTime beforeDate, int[] affectedIds, string[] actionTypes) { List retlist = new List(); @@ -70,31 +70,31 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT DateTimeUtc, ActingPersonId, AffectedItemType, AffectedItemId, ActionType, " + - " ActionDescription, ChangedField, ValueBefore, ValueAfter, Comment, IpAddress " + - " FROM PWLog " + - " WHERE AffectedItemId in (" + JoinIds(affectedIds) + " ) " + - " AND AffectedItemType='" + affectedItemType + "' " + - " AND ActionType in (" + JoinStrings(actionTypes) + ")" + - " AND DateTimeUtc < " + MySqlDate(beforeDate) + " order by DateTimeUtc desc", + GetDbCommand ("SELECT DateTimeUtc, ActingPersonId, AffectedItemType, AffectedItemId, ActionType, " + + " ActionDescription, ChangedField, ValueBefore, ValueAfter, Comment, IpAddress " + + " FROM PWLog " + + " WHERE AffectedItemId in (" + JoinIds (affectedIds) + " ) " + + " AND AffectedItemType='" + affectedItemType + "' " + + " AND ActionType in (" + JoinStrings (actionTypes) + ")" + + " AND DateTimeUtc < " + MySqlDate (beforeDate) + " order by DateTimeUtc desc", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - DateTime dateTimeUtc = reader.GetDateTime(0); - int actingPersonId = reader.GetInt32(1); - string affectedItemTyp = reader.GetString(2); - int affectedItemId = reader.GetInt32(3); - string actionType = reader.GetString(4); - string actionDescription = reader.IsDBNull(5) ? "" : reader.GetString(5); - string changedField = reader.IsDBNull(6) ? "" : reader.GetString(6); - string valueBefore = reader.IsDBNull(7) ? "" : reader.GetString(7); - string valueAfter = reader.IsDBNull(8) ? "" : reader.GetString(8); - string comment = reader.IsDBNull(9) ? "" : reader.GetString(9); - string ipAddress = reader.IsDBNull(10) ? "" : reader.GetString(10); + DateTime dateTimeUtc = reader.GetDateTime (0); + int actingPersonId = reader.GetInt32 (1); + string affectedItemTyp = reader.GetString (2); + int affectedItemId = reader.GetInt32 (3); + string actionType = reader.GetString (4); + string actionDescription = reader.IsDBNull (5) ? "" : reader.GetString (5); + string changedField = reader.IsDBNull (6) ? "" : reader.GetString (6); + string valueBefore = reader.IsDBNull (7) ? "" : reader.GetString (7); + string valueAfter = reader.IsDBNull (8) ? "" : reader.GetString (8); + string comment = reader.IsDBNull (9) ? "" : reader.GetString (9); + string ipAddress = reader.IsDBNull (10) ? "" : reader.GetString (10); - retlist.Add(new BasicPWLog(dateTimeUtc, + retlist.Add (new BasicPWLog (dateTimeUtc, actingPersonId, affectedItemType, affectedItemId, diff --git a/Database/Database-PostalCodes.cs b/Database/Database-PostalCodes.cs index 87be9b38..42f692a4 100644 --- a/Database/Database-PostalCodes.cs +++ b/Database/Database-PostalCodes.cs @@ -13,28 +13,28 @@ namespace Swarmops.Database private const string postalCodeFieldSequence = " PostalCodeId,PostalCode,CityId,CountryId FROM PostalCodes "; - private BasicPostalCode ReadPostalCodeFromDataReader(DbDataReader reader) + private BasicPostalCode ReadPostalCodeFromDataReader (DbDataReader reader) { - int postalCodeId = reader.GetInt32(0); - string postalCode = reader.GetString(1); - int cityId = reader.GetInt32(2); - int countryId = reader.GetInt32(3); + int postalCodeId = reader.GetInt32 (0); + string postalCode = reader.GetString (1); + int cityId = reader.GetInt32 (2); + int countryId = reader.GetInt32 (3); - return new BasicPostalCode(postalCodeId, postalCode, cityId, countryId); + return new BasicPostalCode (postalCodeId, postalCode, cityId, countryId); } #endregion #region Record reading - SELECT statements - public BasicPostalCode[] GetPostalCodesForCountry(int countryId) + public BasicPostalCode[] GetPostalCodesForCountry (int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + postalCodeFieldSequence + "WHERE CountryId=" + countryId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -43,7 +43,7 @@ namespace Swarmops.Database while (reader.Read()) { - result.Add(ReadPostalCodeFromDataReader(reader)); + result.Add (ReadPostalCodeFromDataReader (reader)); } return result.ToArray(); diff --git a/Database/Database-PostalCodesCities.cs b/Database/Database-PostalCodesCities.cs index 517e7804..fbb44852 100644 --- a/Database/Database-PostalCodesCities.cs +++ b/Database/Database-PostalCodesCities.cs @@ -13,18 +13,18 @@ namespace Swarmops.Database " FROM Cities "; - private static BasicCity ReadCityFromDataReader(DbDataReader reader) + private static BasicCity ReadCityFromDataReader (DbDataReader reader) { - int cityId = reader.GetInt32(0); - int countryId = reader.GetInt32(1); - string cityName = reader.GetString(2); - int geographyId = reader.GetInt32(3); + int cityId = reader.GetInt32 (0); + int countryId = reader.GetInt32 (1); + string cityName = reader.GetString (2); + int geographyId = reader.GetInt32 (3); - return new BasicCity(cityId, cityName, countryId, geographyId); + return new BasicCity (cityId, cityName, countryId, geographyId); } - public BasicCity[] GetCitiesByCountryAndPostalCode(int countryId, string postalCode) + public BasicCity[] GetCitiesByCountryAndPostalCode (int countryId, string postalCode) { List cityIdList = new List(); @@ -33,23 +33,23 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT CityId FROM PostalCodes WHERE PostalCode='" + postalCode.Replace("'", "''") + + GetDbCommand ( + "SELECT CityId FROM PostalCodes WHERE PostalCode='" + postalCode.Replace ("'", "''") + "' AND CountryId=" + countryId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - cityIdList.Add(reader.GetInt32(0)); + cityIdList.Add (reader.GetInt32 (0)); } } } - return GetCities(cityIdList.ToArray()); + return GetCities (cityIdList.ToArray()); } - public Dictionary GetCitiesPerPostalCode(int countryId) + public Dictionary GetCitiesPerPostalCode (int countryId) { Dictionary postalList = new Dictionary(); Dictionary cityIdList = new Dictionary(); @@ -59,22 +59,22 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT CityId, PostalCode FROM PostalCodes WHERE CountryId=" + countryId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - postalList[reader.GetString(1)] = reader.GetInt32(0); - cityIdList[reader.GetInt32(0)] = true; + postalList[reader.GetString (1)] = reader.GetInt32 (0); + cityIdList[reader.GetInt32 (0)] = true; } } } int[] cityIds = new int[cityIdList.Count]; - cityIdList.Keys.CopyTo(cityIds, 0); - BasicCity[] cityArr = GetCities(cityIds); + cityIdList.Keys.CopyTo (cityIds, 0); + BasicCity[] cityArr = GetCities (cityIds); Dictionary cities = new Dictionary(); foreach (BasicCity bc in cityArr) cities[bc.Identity] = bc; @@ -87,7 +87,7 @@ namespace Swarmops.Database } - public BasicCity[] GetCities(int[] cityIds) + public BasicCity[] GetCities (int[] cityIds) { if (cityIds.Length == 0) { @@ -101,14 +101,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityId in (" + JoinIds(cityIds) + ")", + GetDbCommand ("SELECT " + cityFieldSequence + " WHERE CityId in (" + JoinIds (cityIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadCityFromDataReader(reader)); + result.Add (ReadCityFromDataReader (reader)); } return result.ToArray(); @@ -117,37 +117,37 @@ namespace Swarmops.Database } - public BasicCity GetCity(int cityId) + public BasicCity GetCity (int cityId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityId=" + cityId, + DbCommand command = GetDbCommand ("SELECT " + cityFieldSequence + " WHERE CityId=" + cityId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCityFromDataReader(reader); + return ReadCityFromDataReader (reader); } - throw new ArgumentException("No such CityId: " + cityId); + throw new ArgumentException ("No such CityId: " + cityId); } } } - public BasicCity GetCityByName(string cityName, int countryId) + public BasicCity GetCityByName (string cityName, int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + + GetDbCommand ( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace ("'", "''") + "' AND CountryId=" + countryId, connection); @@ -155,47 +155,47 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadCityFromDataReader(reader); + return ReadCityFromDataReader (reader); } - throw new ArgumentException("No such CityName: " + cityName); + throw new ArgumentException ("No such CityName: " + cityName); } } } - public BasicCity GetCityByName(string cityName, string countryCode) + public BasicCity GetCityByName (string cityName, string countryCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + - "' AND CountryCode='" + countryCode.ToUpperInvariant().Replace("'", "''") + "'", + GetDbCommand ( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace ("'", "''") + + "' AND CountryCode='" + countryCode.ToUpperInvariant().Replace ("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadCityFromDataReader(reader); + return ReadCityFromDataReader (reader); } - throw new ArgumentException("No such CityName: " + cityName); + throw new ArgumentException ("No such CityName: " + cityName); } } } - public BasicCity[] GetCitiesByName(string cityName, int countryId) + public BasicCity[] GetCitiesByName (string cityName, int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + + GetDbCommand ( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace ("'", "''") + "' AND CountryId=" + countryId, connection); List resList = new List(); @@ -203,27 +203,27 @@ namespace Swarmops.Database { if (reader.Read()) { - resList.Add(ReadCityFromDataReader(reader)); + resList.Add (ReadCityFromDataReader (reader)); while (reader.Read()) { - resList.Add(ReadCityFromDataReader(reader)); + resList.Add (ReadCityFromDataReader (reader)); } return resList.ToArray(); } - throw new ArgumentException("No such CityName: " + cityName); + throw new ArgumentException ("No such CityName: " + cityName); } } } - public BasicCity[] GetCitiesByCountry(string countryCode) + public BasicCity[] GetCitiesByCountry (string countryCode) { - BasicCountry country = GetCountry(countryCode); + BasicCountry country = GetCountry (countryCode); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "SELECT " + cityFieldSequence + " WHERE CountryId=" + country.CountryId, connection); List result = new List(); @@ -231,10 +231,10 @@ namespace Swarmops.Database { if (reader.Read()) { - result.Add(ReadCityFromDataReader(reader)); + result.Add (ReadCityFromDataReader (reader)); while (reader.Read()) { - result.Add(ReadCityFromDataReader(reader)); + result.Add (ReadCityFromDataReader (reader)); } } @@ -243,39 +243,39 @@ namespace Swarmops.Database } } - public int CreateCity(string cityName, int countryId, int geographyId) + public int CreateCity (string cityName, int countryId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateCity", connection); + DbCommand command = GetDbCommand ("CreateCity", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "cityName", cityName); - AddParameterWithName(command, "countryId", countryId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "comment", string.Empty); + AddParameterWithName (command, "cityName", cityName); + AddParameterWithName (command, "countryId", countryId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "comment", string.Empty); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreatePostalCode(string postalCode, int cityId, int countryId) + public int CreatePostalCode (string postalCode, int cityId, int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePostalCode", connection); + DbCommand command = GetDbCommand ("CreatePostalCode", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "postalCode", postalCode); - AddParameterWithName(command, "cityId", cityId); - AddParameterWithName(command, "countryId", countryId); + AddParameterWithName (command, "postalCode", postalCode); + AddParameterWithName (command, "cityId", cityId); + AddParameterWithName (command, "countryId", countryId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } } diff --git a/Database/Database-Refunds.cs b/Database/Database-Refunds.cs index 1ecc2369..76e0777f 100644 --- a/Database/Database-Refunds.cs +++ b/Database/Database-Refunds.cs @@ -15,17 +15,17 @@ namespace Swarmops.Database "ClosedDateTime,CreatedByPersonId" + " FROM Refunds "; - private static BasicRefund ReadRefundFromDataReader(IDataRecord reader) + private static BasicRefund ReadRefundFromDataReader (IDataRecord reader) { - int refundId = reader.GetInt32(0); - int paymentId = reader.GetInt32(1); - bool open = reader.GetBoolean(2); - Int64 amountCents = reader.GetInt64(3); - DateTime createdDateTime = reader.GetDateTime(4); - DateTime closedDateTime = reader.GetDateTime(5); - int createdByPersonId = reader.GetInt32(6); + int refundId = reader.GetInt32 (0); + int paymentId = reader.GetInt32 (1); + bool open = reader.GetBoolean (2); + Int64 amountCents = reader.GetInt64 (3); + DateTime createdDateTime = reader.GetDateTime (4); + DateTime closedDateTime = reader.GetDateTime (5); + int createdByPersonId = reader.GetInt32 (6); - return new BasicRefund(refundId, paymentId, open, amountCents, createdByPersonId, createdDateTime, + return new BasicRefund (refundId, paymentId, open, amountCents, createdByPersonId, createdDateTime, closedDateTime); } @@ -33,31 +33,31 @@ namespace Swarmops.Database #region Database record reading -- SELECT clauses - public BasicRefund GetRefund(int refundId) + public BasicRefund GetRefund (int refundId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + refundFieldSequence + - "WHERE RefundId=" + refundId, + GetDbCommand ("SELECT" + refundFieldSequence + + "WHERE RefundId=" + refundId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadRefundFromDataReader(reader); + return ReadRefundFromDataReader (reader); } - throw new ArgumentException("No such RefundId:" + refundId); + throw new ArgumentException ("No such RefundId:" + refundId); } } } - public BasicRefund[] GetRefunds(params object[] conditions) + public BasicRefund[] GetRefunds (params object[] conditions) { List result = new List(); @@ -66,14 +66,14 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - "SELECT" + refundFieldSequence + ConstructWhereClause("Refunds", conditions), connection); + GetDbCommand ( + "SELECT" + refundFieldSequence + ConstructWhereClause ("Refunds", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadRefundFromDataReader(reader)); + result.Add (ReadRefundFromDataReader (reader)); } return result.ToArray(); @@ -85,13 +85,13 @@ namespace Swarmops.Database #region Creation and manipulation -- stored procedures - public int CreateRefund(int paymentId, int createdByPersonId) + public int CreateRefund (int paymentId, int createdByPersonId) { - return CreateRefund(paymentId, createdByPersonId, 0L); // zero is default; it means refund entire payment + return CreateRefund (paymentId, createdByPersonId, 0L); // zero is default; it means refund entire payment } - public int CreateRefund(int paymentId, int createdByPersonId, Int64 amountCents) + public int CreateRefund (int paymentId, int createdByPersonId, Int64 amountCents) { DateTime now = DateTime.Now; @@ -99,20 +99,20 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateRefund", connection); + DbCommand command = GetDbCommand ("CreateRefund", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "paymentId", paymentId); - AddParameterWithName(command, "amountCents", amountCents); - AddParameterWithName(command, "createdByPersonId", createdByPersonId); - AddParameterWithName(command, "createdDateTime", now); + AddParameterWithName (command, "paymentId", paymentId); + AddParameterWithName (command, "amountCents", amountCents); + AddParameterWithName (command, "createdByPersonId", createdByPersonId); + AddParameterWithName (command, "createdDateTime", now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetRefundOpen(int refundId, bool open) + public void SetRefundOpen (int refundId, bool open) { DateTime now = DateTime.Now; @@ -120,12 +120,12 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SetRefundOpen", connection); + DbCommand command = GetDbCommand ("SetRefundOpen", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "refundId", refundId); - AddParameterWithName(command, "open", open); - AddParameterWithName(command, "closedDateTime", now); // always set, but only valid if open=false + AddParameterWithName (command, "refundId", refundId); + AddParameterWithName (command, "open", open); + AddParameterWithName (command, "closedDateTime", now); // always set, but only valid if open=false command.ExecuteNonQuery(); } diff --git a/Database/Database-Reporters.cs b/Database/Database-Reporters.cs index 95ec8741..d6776a8b 100644 --- a/Database/Database-Reporters.cs +++ b/Database/Database-Reporters.cs @@ -12,85 +12,85 @@ namespace Swarmops.Database " ReporterId,Name,Email " + // 0-2 " FROM Reporters "; - public int CreateReporter(string name, string email) + public int CreateReporter (string name, string email) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateReporter", connection); + DbCommand command = GetDbCommand ("CreateReporter", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "name", name); - AddParameterWithName(command, "email", email); + AddParameterWithName (command, "name", name); + AddParameterWithName (command, "email", email); - int reporterId = Convert.ToInt32(command.ExecuteScalar()); + int reporterId = Convert.ToInt32 (command.ExecuteScalar()); return reporterId; } } - public void DeleteReporter(int reporterId) + public void DeleteReporter (int reporterId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteReporter", connection); + DbCommand command = GetDbCommand ("DeleteReporter", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "reporterId", reporterId); + AddParameterWithName (command, "reporterId", reporterId); command.ExecuteNonQuery(); } } - public void CreateReporterMediaCategory(int reporterId, string mediaCategory) + public void CreateReporterMediaCategory (int reporterId, string mediaCategory) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateReporterMediaCategory", connection); + DbCommand command = GetDbCommand ("CreateReporterMediaCategory", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "reporterId", reporterId); - AddParameterWithName(command, "mediaCategoryName", mediaCategory); + AddParameterWithName (command, "reporterId", reporterId); + AddParameterWithName (command, "mediaCategoryName", mediaCategory); command.ExecuteNonQuery(); } } - public BasicReporter GetReporter(int reporterId) + public BasicReporter GetReporter (int reporterId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + reporterFieldSequence + " WHERE ReporterId=" + reporterId, + DbCommand command = GetDbCommand ("SELECT " + reporterFieldSequence + " WHERE ReporterId=" + reporterId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadReporterFromReader(reader); + return ReadReporterFromReader (reader); } - throw new ArgumentException("No such ReporterId: " + reporterId); + throw new ArgumentException ("No such ReporterId: " + reporterId); } } } - public BasicReporter[] GetReporters(params object[] conditions) + public BasicReporter[] GetReporters (params object[] conditions) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + reporterFieldSequence + ConstructWhereClause("Reporters", conditions), + GetDbCommand ("SELECT " + reporterFieldSequence + ConstructWhereClause ("Reporters", conditions), connection); List result = new List(); @@ -98,7 +98,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadReporterFromReader(reader)); + result.Add (ReadReporterFromReader (reader)); } return result.ToArray(); @@ -107,7 +107,7 @@ namespace Swarmops.Database } - public BasicReporter[] GetReportersFromMediaCategories(int[] mediaCategoryIds) + public BasicReporter[] GetReportersFromMediaCategories (int[] mediaCategoryIds) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -115,15 +115,15 @@ namespace Swarmops.Database List reporterIds = new List(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT ReporterId From ReportersMediaCategories WHERE MediaCategoryId in (" + - JoinIds(mediaCategoryIds) + ")", connection); + JoinIds (mediaCategoryIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - reporterIds.Add(reader.GetInt32(0)); + reporterIds.Add (reader.GetInt32 (0)); } } @@ -131,16 +131,16 @@ namespace Swarmops.Database if (reporterIds.Count > 0) { command = - GetDbCommand( + GetDbCommand ( "SELECT " + reporterFieldSequence + " WHERE ReporterId in (" + - JoinIds(reporterIds.ToArray()) + ")", + JoinIds (reporterIds.ToArray()) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadReporterFromReader(reader)); + result.Add (ReadReporterFromReader (reader)); } return result.ToArray(); @@ -151,7 +151,7 @@ namespace Swarmops.Database } - public int[] GetReporterMediaCategories(int reporterId) + public int[] GetReporterMediaCategories (int reporterId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -159,7 +159,7 @@ namespace Swarmops.Database List categoryIds = new List(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT MediaCategoryId From ReportersMediaCategories WHERE ReporterId=" + reporterId, connection); @@ -167,7 +167,7 @@ namespace Swarmops.Database { while (reader.Read()) { - categoryIds.Add(reader.GetInt32(0)); + categoryIds.Add (reader.GetInt32 (0)); } } @@ -176,13 +176,13 @@ namespace Swarmops.Database } - private static BasicReporter ReadReporterFromReader(DbDataReader reader) + private static BasicReporter ReadReporterFromReader (DbDataReader reader) { - int id = reader.GetInt32(0); - string name = reader.GetString(1); - string email = reader.GetString(2); + int id = reader.GetInt32 (0); + string name = reader.GetString (1); + string email = reader.GetString (2); - return new BasicReporter(id, name, email, null); + return new BasicReporter (id, name, email, null); } } } \ No newline at end of file diff --git a/Database/Database-Roles.cs b/Database/Database-Roles.cs index 986871e9..73f9cd52 100644 --- a/Database/Database-Roles.cs +++ b/Database/Database-Roles.cs @@ -18,22 +18,22 @@ namespace Swarmops.Database // 0-4 " FROM PeopleRoles JOIN PersonRoleTypes ON (PeopleRoles.PersonRoleTypeId=PersonRoleTypes.PersonRoleTypeId) "; - private static BasicPersonRole ReadPersonRoleFromDataReader(DbDataReader reader) + private static BasicPersonRole ReadPersonRoleFromDataReader (DbDataReader reader) { - int personRoleId = reader.GetInt32(0); - string personRoleTypeName = reader.GetString(1); - int personId = reader.GetInt32(2); - int organizationId = reader.GetInt32(3); - int geographyId = reader.GetInt32(4); + int personRoleId = reader.GetInt32 (0); + string personRoleTypeName = reader.GetString (1); + int personId = reader.GetInt32 (2); + int organizationId = reader.GetInt32 (3); + int geographyId = reader.GetInt32 (4); - RoleType roleType = (RoleType) Enum.Parse(typeof (RoleType), personRoleTypeName); + RoleType roleType = (RoleType) Enum.Parse (typeof (RoleType), personRoleTypeName); - return new BasicPersonRole(personRoleId, personId, roleType, organizationId, geographyId); + return new BasicPersonRole (personRoleId, personId, roleType, organizationId, geographyId); } #endregion - public BasicAuthority GetPersonAuthority(IHasIdentity person) + public BasicAuthority GetPersonAuthority (IHasIdentity person) { List systemRoles = new List(); List organizationRoles = new List(); @@ -44,66 +44,66 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personRoleFieldSequence + ConstructWhereClause("PersonRoles", person), + GetDbCommand ("SELECT " + personRoleFieldSequence + ConstructWhereClause ("PersonRoles", person), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - BasicPersonRole newPersonRole = ReadPersonRoleFromDataReader(reader); + BasicPersonRole newPersonRole = ReadPersonRoleFromDataReader (reader); - switch (RoleTypes.ClassOfRole(newPersonRole.Type)) + switch (RoleTypes.ClassOfRole (newPersonRole.Type)) { case RoleClass.System: - systemRoles.Add(newPersonRole); + systemRoles.Add (newPersonRole); break; case RoleClass.Organization: - organizationRoles.Add(newPersonRole); + organizationRoles.Add (newPersonRole); break; case RoleClass.Local: - localRoles.Add(newPersonRole); + localRoles.Add (newPersonRole); break; default: - throw new InvalidOperationException("Invalid RoleTypeId (" + newPersonRole.Type + - ") in database for PersonId " + - person.Identity.ToString()); + throw new InvalidOperationException ("Invalid RoleTypeId (" + newPersonRole.Type + + ") in database for PersonId " + + person.Identity.ToString()); } } - return new BasicAuthority(person.Identity, systemRoles.ToArray(), organizationRoles.ToArray(), + return new BasicAuthority (person.Identity, systemRoles.ToArray(), organizationRoles.ToArray(), localRoles.ToArray()); } } } - public BasicPersonRole GetRole(int roleId) + public BasicPersonRole GetRole (int roleId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + personRoleFieldSequence + " WHERE PersonRoleId=" + roleId, + DbCommand command = GetDbCommand ("SELECT " + personRoleFieldSequence + " WHERE PersonRoleId=" + roleId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadPersonRoleFromDataReader(reader); + return ReadPersonRoleFromDataReader (reader); } else { - throw new ArgumentException("No such RoleId: " + roleId.ToString()); + throw new ArgumentException ("No such RoleId: " + roleId.ToString()); } } } } - public BasicPersonRole[] GetPeopleWithRoleType(RoleType r, int[] orgId, int[] geoId) + public BasicPersonRole[] GetPeopleWithRoleType (RoleType r, int[] orgId, int[] geoId) // TODO: Refactor to use ConstructWhereClause { List retlist = new List(); @@ -112,17 +112,17 @@ namespace Swarmops.Database connection.Open(); string cmd = "SELECT " + personRoleFieldSequence + " WHERE Name= '" + r.ToString() + "'"; if (orgId.Length > 0) - cmd += " AND OrganzationId IN (" + JoinIds(orgId) + ")"; + cmd += " AND OrganzationId IN (" + JoinIds (orgId) + ")"; if (geoId.Length > 0) - cmd += " AND GeographyId IN (" + JoinIds(geoId) + ")"; + cmd += " AND GeographyId IN (" + JoinIds (geoId) + ")"; - DbCommand command = GetDbCommand(cmd, connection); + DbCommand command = GetDbCommand (cmd, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - retlist.Add(ReadPersonRoleFromDataReader(reader)); + retlist.Add (ReadPersonRoleFromDataReader (reader)); } } } @@ -132,26 +132,26 @@ namespace Swarmops.Database public BasicPersonRole[] GetRoles() { - return GetRolesForOrganizationsGeographies(new int[] {}, new int[] {}); + return GetRolesForOrganizationsGeographies (new int[] {}, new int[] {}); } - public BasicPersonRole[] GetRolesForOrganization(int organizationId) + public BasicPersonRole[] GetRolesForOrganization (int organizationId) { - return GetRolesForOrganizationsGeographies(new int[] {organizationId}, new int[0]); + return GetRolesForOrganizationsGeographies (new int[] {organizationId}, new int[0]); } - public BasicPersonRole[] GetRolesForOrganizationGeography(int organizationId, int geographyId) + public BasicPersonRole[] GetRolesForOrganizationGeography (int organizationId, int geographyId) { - return GetRolesForOrganizationGeographies(organizationId, new int[] {geographyId}); + return GetRolesForOrganizationGeographies (organizationId, new int[] {geographyId}); } - public BasicPersonRole[] GetRolesForOrganizationGeographies(int organizationId, int[] geographyIds) + public BasicPersonRole[] GetRolesForOrganizationGeographies (int organizationId, int[] geographyIds) { - return GetRolesForOrganizationsGeographies(new int[] {organizationId}, geographyIds); + return GetRolesForOrganizationsGeographies (new int[] {organizationId}, geographyIds); } - public BasicPersonRole[] GetRolesForOrganizationsGeographies(int[] organizationIds, int[] geographyIds) + public BasicPersonRole[] GetRolesForOrganizationsGeographies (int[] organizationIds, int[] geographyIds) // TODO: Refactor to use ConstructWhereClause { List result = new List(); @@ -162,25 +162,25 @@ namespace Swarmops.Database string selectString = "SELECT " + personRoleFieldSequence; if (organizationIds.Length > 0) - selectString += " WHERE OrganizationId IN (" + JoinIds(organizationIds) + ")"; + selectString += " WHERE OrganizationId IN (" + JoinIds (organizationIds) + ")"; if (geographyIds.Length > 0) { selectString += (organizationIds.Length > 0) ? " AND " : " WHERE "; - selectString += " GeographyId IN ( " + JoinIds(geographyIds) + ")"; + selectString += " GeographyId IN ( " + JoinIds (geographyIds) + ")"; } selectString += " ORDER BY PersonId"; DbCommand command = - GetDbCommand(selectString, connection); + GetDbCommand (selectString, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadPersonRoleFromDataReader(reader)); + result.Add (ReadPersonRoleFromDataReader (reader)); } return result.ToArray(); @@ -189,34 +189,34 @@ namespace Swarmops.Database } - public int CreateRole(int personId, RoleType roleType, int organizationId, int nodeId) + public int CreateRole (int personId, RoleType roleType, int organizationId, int nodeId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreatePersonRole", connection); + DbCommand command = GetDbCommand ("CreatePersonRole", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "personRoleType", roleType.ToString()); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", nodeId); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "personRoleType", roleType.ToString()); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", nodeId); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void DeleteRole(int roleId) + public void DeleteRole (int roleId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeletePersonRole", connection); + DbCommand command = GetDbCommand ("DeletePersonRole", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personRoleId", roleId); + AddParameterWithName (command, "personRoleId", roleId); command.ExecuteNonQuery(); } } diff --git a/Database/Database-Salaries.cs b/Database/Database-Salaries.cs index d5afa6a1..b0c3fe76 100644 --- a/Database/Database-Salaries.cs +++ b/Database/Database-Salaries.cs @@ -16,21 +16,21 @@ namespace Swarmops.Database "Salaries.Open " + // 10 "FROM Salaries "; - private static BasicSalary ReadSalaryFromDataReader(IDataRecord reader) + private static BasicSalary ReadSalaryFromDataReader (IDataRecord reader) { - int salaryId = reader.GetInt32(0); - int payrollItemId = reader.GetInt32(1); - DateTime payoutDate = reader.GetDateTime(2); - Int64 baseSalaryCents = reader.GetInt64(3); - Int64 netSalaryCents = reader.GetInt64(4); - Int64 subtractiveTaxCents = reader.GetInt64(5); - Int64 additiveTaxCents = reader.GetInt64(6); - bool attested = reader.GetBoolean(7); - bool netPaid = reader.GetBoolean(8); - bool taxPaid = reader.GetBoolean(9); - bool open = reader.GetBoolean(10); + int salaryId = reader.GetInt32 (0); + int payrollItemId = reader.GetInt32 (1); + DateTime payoutDate = reader.GetDateTime (2); + Int64 baseSalaryCents = reader.GetInt64 (3); + Int64 netSalaryCents = reader.GetInt64 (4); + Int64 subtractiveTaxCents = reader.GetInt64 (5); + Int64 additiveTaxCents = reader.GetInt64 (6); + bool attested = reader.GetBoolean (7); + bool netPaid = reader.GetBoolean (8); + bool taxPaid = reader.GetBoolean (9); + bool open = reader.GetBoolean (10); - return new BasicSalary(salaryId, payrollItemId, payoutDate, baseSalaryCents, netSalaryCents, + return new BasicSalary (salaryId, payrollItemId, payoutDate, baseSalaryCents, netSalaryCents, subtractiveTaxCents, additiveTaxCents, attested, netPaid, taxPaid, open); } @@ -45,24 +45,24 @@ namespace Swarmops.Database /// The salary database identity. /// The requested salary. /// Thrown if there is no such identity. - public BasicSalary GetSalary(int salaryId) + public BasicSalary GetSalary (int salaryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + salaryFieldSequence + "WHERE SalaryId=" + salaryId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadSalaryFromDataReader(reader); + return ReadSalaryFromDataReader (reader); } - throw new ArgumentException("Unknown Salary Id: " + salaryId); + throw new ArgumentException ("Unknown Salary Id: " + salaryId); } } } @@ -75,7 +75,7 @@ namespace Swarmops.Database /// specifiers. /// /// A list of matching salaries. - public BasicSalary[] GetSalaries(params object[] conditions) + public BasicSalary[] GetSalaries (params object[] conditions) { List result = new List(); @@ -84,15 +84,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + salaryFieldSequence + "JOIN Payroll USING (PayrollItemId)" + - ConstructWhereClause("Salaries", conditions), connection); + ConstructWhereClause ("Salaries", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadSalaryFromDataReader(reader)); + result.Add (ReadSalaryFromDataReader (reader)); } return result.ToArray(); @@ -104,39 +104,39 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateSalary(int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, + public int CreateSalary (int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateSalaryPrecise", connection); + DbCommand command = GetDbCommand ("CreateSalaryPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "payoutDate", payoutDate); - AddParameterWithName(command, "baseSalaryCents", baseSalaryCents); - AddParameterWithName(command, "netSalaryCents", netSalaryCents); - AddParameterWithName(command, "subtractiveTaxCents", subtractiveTaxCents); - AddParameterWithName(command, "additiveTaxCents", additiveTaxCents); + AddParameterWithName (command, "payrollItemId", payrollItemId); + AddParameterWithName (command, "payoutDate", payoutDate); + AddParameterWithName (command, "baseSalaryCents", baseSalaryCents); + AddParameterWithName (command, "netSalaryCents", netSalaryCents); + AddParameterWithName (command, "subtractiveTaxCents", subtractiveTaxCents); + AddParameterWithName (command, "additiveTaxCents", additiveTaxCents); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetSalaryNetPaid(int salaryId, bool netPaid) + public void SetSalaryNetPaid (int salaryId, bool netPaid) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetSalaryNetPaid", connection); + DbCommand command = GetDbCommand ("SetSalaryNetPaid", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "salaryId", salaryId); - AddParameterWithName(command, "netPaid", netPaid); + AddParameterWithName (command, "salaryId", salaryId); + AddParameterWithName (command, "netPaid", netPaid); command.ExecuteNonQuery(); @@ -146,34 +146,34 @@ namespace Swarmops.Database } - public void SetSalaryNetSalary(int salaryId, Int64 netSalaryCents) + public void SetSalaryNetSalary (int salaryId, Int64 netSalaryCents) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetSalaryNetSalaryPrecise", connection); + DbCommand command = GetDbCommand ("SetSalaryNetSalaryPrecise", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "salaryId", salaryId); - AddParameterWithName(command, "netSalaryCents", netSalaryCents); + AddParameterWithName (command, "salaryId", salaryId); + AddParameterWithName (command, "netSalaryCents", netSalaryCents); command.ExecuteNonQuery(); } } - public void SetSalaryTaxPaid(int salaryId, bool taxPaid) + public void SetSalaryTaxPaid (int salaryId, bool taxPaid) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetSalaryTaxPaid", connection); + DbCommand command = GetDbCommand ("SetSalaryTaxPaid", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "salaryId", salaryId); - AddParameterWithName(command, "taxPaid", taxPaid); + AddParameterWithName (command, "salaryId", salaryId); + AddParameterWithName (command, "taxPaid", taxPaid); command.ExecuteNonQuery(); @@ -183,17 +183,17 @@ namespace Swarmops.Database } - public void SetSalaryAttested(int salaryId, bool attested) + public void SetSalaryAttested (int salaryId, bool attested) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetSalaryAttested", connection); + DbCommand command = GetDbCommand ("SetSalaryAttested", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "salaryId", salaryId); - AddParameterWithName(command, "attested", attested); + AddParameterWithName (command, "salaryId", salaryId); + AddParameterWithName (command, "attested", attested); command.ExecuteNonQuery(); } diff --git a/Database/Database-SwarmopsLog.cs b/Database/Database-SwarmopsLog.cs index 55251b85..d5736b38 100644 --- a/Database/Database-SwarmopsLog.cs +++ b/Database/Database-SwarmopsLog.cs @@ -14,29 +14,29 @@ namespace Swarmops.Database " SwarmopsLogEntryId,DateTime,PersonId,EntryTypeId,EntryXml " + // 0-4 "FROM SwarmopsLog "; - private static BasicSwarmopsLogEntry ReadSwarmopsLogEntryFromDataReader(IDataRecord reader) + private static BasicSwarmopsLogEntry ReadSwarmopsLogEntryFromDataReader (IDataRecord reader) { - int swarmopsLogEntryId = reader.GetInt32(0); - DateTime dateTime = reader.GetDateTime(1); - int personId = reader.GetInt32(2); - int entryTypeId = reader.GetInt32(3); - string entryXml = reader.GetString(4); + int swarmopsLogEntryId = reader.GetInt32 (0); + DateTime dateTime = reader.GetDateTime (1); + int personId = reader.GetInt32 (2); + int entryTypeId = reader.GetInt32 (3); + string entryXml = reader.GetString (4); - return new BasicSwarmopsLogEntry(swarmopsLogEntryId, personId, dateTime, entryTypeId, entryXml); + return new BasicSwarmopsLogEntry (swarmopsLogEntryId, personId, dateTime, entryTypeId, entryXml); } #endregion #region Record reading - SELECT statements - public BasicSwarmopsLogEntry GetSwarmopsLogEntry(int swarmopsLogEntryId) + public BasicSwarmopsLogEntry GetSwarmopsLogEntry (int swarmopsLogEntryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + swarmopsLogFieldSequence + "WHERE SwarmopsLogEntryId=" + swarmopsLogEntryId + ";", connection); @@ -44,15 +44,15 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadSwarmopsLogEntryFromDataReader(reader); + return ReadSwarmopsLogEntryFromDataReader (reader); } - throw new ArgumentException("Unknown SwarmopsLogEntryId: " + swarmopsLogEntryId); + throw new ArgumentException ("Unknown SwarmopsLogEntryId: " + swarmopsLogEntryId); } } } - public BasicSwarmopsLogEntry[] GetSwarmopsLogEntries(DateTime startDate, DateTime endDate) + public BasicSwarmopsLogEntry[] GetSwarmopsLogEntries (DateTime startDate, DateTime endDate) { List result = new List(); @@ -61,16 +61,16 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT" + swarmopsLogFieldSequence + " WHERE DateTime >= '" + - startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND DateTime < '" + - endDate.ToString("yyyy-MM-dd HH:mm:ss") + "' ORDER BY DateTime", connection); + startDate.ToString ("yyyy-MM-dd HH:mm:ss") + "' AND DateTime < '" + + endDate.ToString ("yyyy-MM-dd HH:mm:ss") + "' ORDER BY DateTime", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadSwarmopsLogEntryFromDataReader(reader)); + result.Add (ReadSwarmopsLogEntryFromDataReader (reader)); } return result.ToArray(); @@ -82,7 +82,7 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public int CreateSwarmopsLogEntry(int personId, string entryType, string entryXml) + public int CreateSwarmopsLogEntry (int personId, string entryType, string entryXml) { DateTime now = DateTime.UtcNow; @@ -90,31 +90,31 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateSwarmopsLogEntry", connection); + DbCommand command = GetDbCommand ("CreateSwarmopsLogEntry", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "entryType", entryType); - AddParameterWithName(command, "entryXml", entryXml); - AddParameterWithName(command, "dateTime", DateTime.UtcNow); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "entryType", entryType); + AddParameterWithName (command, "entryXml", entryXml); + AddParameterWithName (command, "dateTime", DateTime.UtcNow); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void CreateSwarmopsLogEntryAffectedObject(int swarmopsLogEntryId, string affectedObjectType, + public void CreateSwarmopsLogEntryAffectedObject (int swarmopsLogEntryId, string affectedObjectType, int affectedObjectId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateSwarmopsLogEntryAffectedObject", connection); + DbCommand command = GetDbCommand ("CreateSwarmopsLogEntryAffectedObject", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "swarmopsLogEntryId", swarmopsLogEntryId); - AddParameterWithName(command, "affectedObjectType", affectedObjectType); - AddParameterWithName(command, "affectedObjectId", affectedObjectId); + AddParameterWithName (command, "swarmopsLogEntryId", swarmopsLogEntryId); + AddParameterWithName (command, "affectedObjectType", affectedObjectType); + AddParameterWithName (command, "affectedObjectId", affectedObjectId); command.ExecuteNonQuery(); // no return value - table has no identity } diff --git a/Database/Database-TaxLevels.cs b/Database/Database-TaxLevels.cs index ebbcba09..58a34ca5 100644 --- a/Database/Database-TaxLevels.cs +++ b/Database/Database-TaxLevels.cs @@ -8,7 +8,7 @@ namespace Swarmops.Database { #region Record reading - SELECT statements - public double GetSalaryTaxLevel(int countryId, int taxLevelId, int grossSalary) + public double GetSalaryTaxLevel (int countryId, int taxLevelId, int grossSalary) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -19,8 +19,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( - String.Format( + GetDbCommand ( + String.Format ( "SELECT Tax,Year FROM SalaryTaxLevels WHERE CountryId={0} AND TaxLevelId={1} AND BracketLow<={2} AND Year<={3} ORDER BY BracketLow Desc LIMIT 1", countryId, taxLevelId, grossSalary, thisYear), connection); @@ -28,7 +28,7 @@ namespace Swarmops.Database { if (reader.Read()) { - int year = reader.GetInt32(1); + int year = reader.GetInt32 (1); if (thisYear != year) { @@ -36,7 +36,7 @@ namespace Swarmops.Database // TODO: a very limited time, but not in a sustained situation } - int taxLevel = reader.GetInt32(0); + int taxLevel = reader.GetInt32 (0); if (taxLevel < 0) { @@ -46,7 +46,8 @@ namespace Swarmops.Database return taxLevel; } - throw new ArgumentException("Can't find tax rate for level/country: " + taxLevelId + "/" + countryId); + throw new ArgumentException ("Can't find tax rate for level/country: " + taxLevelId + "/" + + countryId); } } } @@ -55,37 +56,37 @@ namespace Swarmops.Database #region Creation and manipulation - stored procedures - public void CreateSalaryTaxLevel(int countryId, int taxLevelId, int bracketLow, int year, double tax) + public void CreateSalaryTaxLevel (int countryId, int taxLevelId, int bracketLow, int year, double tax) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateSalaryTaxLevel", connection); + DbCommand command = GetDbCommand ("CreateSalaryTaxLevel", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "countryId", countryId); - AddParameterWithName(command, "taxLevelId", taxLevelId); - AddParameterWithName(command, "bracketLow", bracketLow); - AddParameterWithName(command, "year", year); - AddParameterWithName(command, "tax", tax < 1.0 ? (int) (-tax*10000) : (int) tax); + AddParameterWithName (command, "countryId", countryId); + AddParameterWithName (command, "taxLevelId", taxLevelId); + AddParameterWithName (command, "bracketLow", bracketLow); + AddParameterWithName (command, "year", year); + AddParameterWithName (command, "tax", tax < 1.0 ? (int) (-tax*10000) : (int) tax); command.ExecuteNonQuery(); } } - [Obsolete("We're using a new Year column rather than deleting obsolete tax data", false)] - public void DeleteTaxLevels(int countryId) + [Obsolete ("We're using a new Year column rather than deleting obsolete tax data", false)] + public void DeleteTaxLevels (int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("DeleteTaxLevels", connection); + DbCommand command = GetDbCommand ("DeleteTaxLevels", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "countryId", countryId); + AddParameterWithName (command, "countryId", countryId); command.ExecuteNonQuery(); } diff --git a/Database/Database-TemporaryIdentities.cs b/Database/Database-TemporaryIdentities.cs index 75e4efe8..2b316e6a 100644 --- a/Database/Database-TemporaryIdentities.cs +++ b/Database/Database-TemporaryIdentities.cs @@ -12,10 +12,10 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("CreateTemporaryIdentity", connection); + DbCommand command = GetDbCommand ("CreateTemporaryIdentity", connection); command.CommandType = CommandType.StoredProcedure; - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } } diff --git a/Database/Database-Tests.cs b/Database/Database-Tests.cs index ea66f9ae..e59e80df 100644 --- a/Database/Database-Tests.cs +++ b/Database/Database-Tests.cs @@ -31,7 +31,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "CREATE TABLE `CredentialsTests` (" + " `TestId` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT," + " `Description` VARCHAR(256) NOT NULL," + @@ -46,7 +46,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } @@ -59,7 +59,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "ALTER TABLE `CredentialsTests` ADD COLUMN `AppendedColumn` INT AFTER `DateTimeCreated`", connection); @@ -69,7 +69,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } @@ -83,7 +83,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "DROP TABLE `CredentialsTests`", connection); command.ExecuteNonQuery(); @@ -92,7 +92,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } @@ -105,7 +105,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "CREATE PROCEDURE `CreateCredentialsTest`(" + " description VARCHAR(128)" + ")" + @@ -122,7 +122,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } @@ -135,7 +135,7 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand( + DbCommand command = GetDbCommand ( "DROP PROCEDURE `CreateCredentialsTest`", connection); command.ExecuteNonQuery(); @@ -144,22 +144,22 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } - public bool TestExecute(string testDescription) + public bool TestExecute (string testDescription) { try { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateCredentialsTest", connection); + DbCommand command = GetDbCommand ("CreateCredentialsTest", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "description", testDescription); + AddParameterWithName (command, "description", testDescription); command.ExecuteNonQuery(); return true; @@ -167,7 +167,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } @@ -181,7 +181,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT * FROM CredentialsTests", connection); DbDataReader reader = command.ExecuteReader(); @@ -190,7 +190,7 @@ namespace Swarmops.Database } catch (Exception debug) { - Debug.WriteLine(debug.ToString()); + Debug.WriteLine (debug.ToString()); return false; } } diff --git a/Database/Database-UrlTranslations.cs b/Database/Database-UrlTranslations.cs index 58e0e16f..d2f3f62d 100644 --- a/Database/Database-UrlTranslations.cs +++ b/Database/Database-UrlTranslations.cs @@ -7,42 +7,42 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreateUrlTranslation(string url) + public int CreateUrlTranslation (string url) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateUrlTranslation", connection); + DbCommand command = GetDbCommand ("CreateUrlTranslation", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "originalUrl", url); + AddParameterWithName (command, "originalUrl", url); - int urlTranslationId = Convert.ToInt32(command.ExecuteScalar()); + int urlTranslationId = Convert.ToInt32 (command.ExecuteScalar()); return urlTranslationId; } } - public void SetUrlTranslation(string originalUrl, string translatedUrl) + public void SetUrlTranslation (string originalUrl, string translatedUrl) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetUrlTranslation", connection); + DbCommand command = GetDbCommand ("SetUrlTranslation", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "originalUrl", originalUrl); - AddParameterWithName(command, "translatedUrl", translatedUrl); + AddParameterWithName (command, "originalUrl", originalUrl); + AddParameterWithName (command, "translatedUrl", translatedUrl); command.ExecuteNonQuery(); } } - public string[] GetUntranslatedUrls(int max) + public string[] GetUntranslatedUrls (int max) { List result = new List(); @@ -51,7 +51,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT TOP " + max + " OriginalUrl FROM UrlTranslations WHERE Translated=0", connection); @@ -59,7 +59,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(reader.GetString(0)); + result.Add (reader.GetString (0)); } return result.ToArray(); @@ -68,22 +68,22 @@ namespace Swarmops.Database } - public string GetUrlTranslation(string url) + public string GetUrlTranslation (string url) { using (DbConnection connection = GetSqlServerDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( - "SELECT TranslatedUrl FROM UrlTranslations WHERE OriginalUrl='" + url.Replace("'", "''") + + GetDbCommand ( + "SELECT TranslatedUrl FROM UrlTranslations WHERE OriginalUrl='" + url.Replace ("'", "''") + "' AND Translated=1", connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetString(0); + return reader.GetString (0); } return null; diff --git a/Database/Database-Volunteers.cs b/Database/Database-Volunteers.cs index 70521a5a..fb45fe0e 100644 --- a/Database/Database-Volunteers.cs +++ b/Database/Database-Volunteers.cs @@ -18,7 +18,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT VolunteerId,PersonId,OwnerPersonId,OpenedDateTime,Open,ClosedDateTime,ClosingComments FROM Volunteers WHERE Open=1;", connection); @@ -26,7 +26,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadVolunteerFromDataReader(reader)); + result.Add (ReadVolunteerFromDataReader (reader)); } return result.ToArray(); @@ -34,14 +34,14 @@ namespace Swarmops.Database } } - public BasicVolunteer GetVolunteer(int volunteerId) + public BasicVolunteer GetVolunteer (int volunteerId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT VolunteerId,PersonId,OwnerPersonId,OpenedDateTime,Open,ClosedDateTime,ClosingComments FROM Volunteers WHERE VolunteerId=" + volunteerId + ";", connection); @@ -49,22 +49,22 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadVolunteerFromDataReader(reader); + return ReadVolunteerFromDataReader (reader); } - throw new ArgumentException("Unknown VolunteerId"); + throw new ArgumentException ("Unknown VolunteerId"); } } } - public BasicVolunteerRole GetVolunteerRole(int volunteerRoleId) + public BasicVolunteerRole GetVolunteerRole (int volunteerRoleId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT VolunteerRoleId,VolunteerId,OrganizationId,GeographyId,RoleTypeId,Open,Assigned FROM VolunteerRoles WHERE VolunteerRoleId=" + volunteerRoleId + ";", connection); @@ -72,16 +72,16 @@ namespace Swarmops.Database { if (reader.Read()) { - return ReadVolunteerRoleFromDataReader(reader); + return ReadVolunteerRoleFromDataReader (reader); } - throw new ArgumentException("Unknown VolunteerId"); + throw new ArgumentException ("Unknown VolunteerId"); } } } - public BasicVolunteerRole[] GetVolunteerRolesByVolunteer(int volunteerId) + public BasicVolunteerRole[] GetVolunteerRolesByVolunteer (int volunteerId) { List result = new List(); @@ -90,7 +90,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand( + GetDbCommand ( "SELECT VolunteerRoleId,VolunteerId,OrganizationId,GeographyId,RoleTypeId,Open,Assigned FROM VolunteerRoles WHERE VolunteerId=" + volunteerId + ";", connection); @@ -98,7 +98,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add(ReadVolunteerRoleFromDataReader(reader)); + result.Add (ReadVolunteerRoleFromDataReader (reader)); } } } @@ -107,115 +107,115 @@ namespace Swarmops.Database } - private BasicVolunteer ReadVolunteerFromDataReader(DbDataReader reader) + private BasicVolunteer ReadVolunteerFromDataReader (DbDataReader reader) { - int volunteerId = reader.GetInt32(0); - int personId = reader.GetInt32(1); - int ownerPersonId = reader.GetInt32(2); - DateTime openedDateTime = reader.GetDateTime(3); - bool open = reader.GetBoolean(4); - DateTime closedDateTime = reader.GetDateTime(5); - string closingComments = reader.GetString(6); + int volunteerId = reader.GetInt32 (0); + int personId = reader.GetInt32 (1); + int ownerPersonId = reader.GetInt32 (2); + DateTime openedDateTime = reader.GetDateTime (3); + bool open = reader.GetBoolean (4); + DateTime closedDateTime = reader.GetDateTime (5); + string closingComments = reader.GetString (6); - return new BasicVolunteer(volunteerId, personId, ownerPersonId, openedDateTime, open, closedDateTime, + return new BasicVolunteer (volunteerId, personId, ownerPersonId, openedDateTime, open, closedDateTime, closingComments); } - private BasicVolunteerRole ReadVolunteerRoleFromDataReader(DbDataReader reader) + private BasicVolunteerRole ReadVolunteerRoleFromDataReader (DbDataReader reader) { - int volunteerRoleId = reader.GetInt32(0); - int volunteerId = reader.GetInt32(1); - int organizationId = reader.GetInt32(2); - int geographyId = reader.GetInt32(3); - int roleTypeId = reader.GetInt32(4); - bool open = reader.GetBoolean(5); - bool assigned = reader.GetBoolean(6); + int volunteerRoleId = reader.GetInt32 (0); + int volunteerId = reader.GetInt32 (1); + int organizationId = reader.GetInt32 (2); + int geographyId = reader.GetInt32 (3); + int roleTypeId = reader.GetInt32 (4); + bool open = reader.GetBoolean (5); + bool assigned = reader.GetBoolean (6); - return new BasicVolunteerRole(volunteerRoleId, volunteerId, organizationId, geographyId, + return new BasicVolunteerRole (volunteerRoleId, volunteerId, organizationId, geographyId, (RoleType) roleTypeId, open, assigned); } - public int CreateVolunteer(int personId, int ownerPersonId) + public int CreateVolunteer (int personId, int ownerPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateVolunteer", connection); + DbCommand command = GetDbCommand ("CreateVolunteer", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "ownerPersonId", ownerPersonId); - AddParameterWithName(command, "openedDateTime", DateTime.Now); + AddParameterWithName (command, "personId", personId); + AddParameterWithName (command, "ownerPersonId", ownerPersonId); + AddParameterWithName (command, "openedDateTime", DateTime.Now); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public int CreateVolunteerRole(int volunteerId, int organizationId, int geographyId, RoleType roleType) + public int CreateVolunteerRole (int volunteerId, int organizationId, int geographyId, RoleType roleType) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CreateVolunteerRole", connection); + DbCommand command = GetDbCommand ("CreateVolunteerRole", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "volunteerId", volunteerId); - AddParameterWithName(command, "organizationId", organizationId); - AddParameterWithName(command, "geographyId", geographyId); - AddParameterWithName(command, "roleTypeId", (int) roleType); + AddParameterWithName (command, "volunteerId", volunteerId); + AddParameterWithName (command, "organizationId", organizationId); + AddParameterWithName (command, "geographyId", geographyId); + AddParameterWithName (command, "roleTypeId", (int) roleType); - return Convert.ToInt32(command.ExecuteScalar()); + return Convert.ToInt32 (command.ExecuteScalar()); } } - public void SetVolunteerOwnerPersonId(int volunteerId, int ownerPersonId) + public void SetVolunteerOwnerPersonId (int volunteerId, int ownerPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SetVolunteerOwnerPersonId", connection); + DbCommand command = GetDbCommand ("SetVolunteerOwnerPersonId", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "volunteerId", volunteerId); - AddParameterWithName(command, "ownerPersonId", ownerPersonId); + AddParameterWithName (command, "volunteerId", volunteerId); + AddParameterWithName (command, "ownerPersonId", ownerPersonId); command.ExecuteNonQuery(); } } - public void CloseVolunteer(int volunteerId, string closingComments) + public void CloseVolunteer (int volunteerId, string closingComments) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CloseVolunteer", connection); + DbCommand command = GetDbCommand ("CloseVolunteer", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "volunteerId", volunteerId); - AddParameterWithName(command, "closedDateTime", DateTime.Now); - AddParameterWithName(command, "closingComments", closingComments); + AddParameterWithName (command, "volunteerId", volunteerId); + AddParameterWithName (command, "closedDateTime", DateTime.Now); + AddParameterWithName (command, "closingComments", closingComments); command.ExecuteNonQuery(); } } - public void CloseVolunteerRole(int volunteerRoleId, bool wasAssigned) + public void CloseVolunteerRole (int volunteerRoleId, bool wasAssigned) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("CloseVolunteerRole", connection); + DbCommand command = GetDbCommand ("CloseVolunteerRole", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "volunteerRoleId", volunteerRoleId); - AddParameterWithName(command, "assigned", wasAssigned); + AddParameterWithName (command, "volunteerRoleId", volunteerRoleId); + AddParameterWithName (command, "assigned", wasAssigned); command.ExecuteNonQuery(); } diff --git a/Database/Properties/AssemblyInfo.cs b/Database/Properties/AssemblyInfo.cs index 37f2ab4b..b6bb9154 100644 --- a/Database/Properties/AssemblyInfo.cs +++ b/Database/Properties/AssemblyInfo.cs @@ -6,14 +6,14 @@ using System.Reflection; // associated with an assembly. // -[assembly: AssemblyTitle("PirateWeb Database Assembly")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("PirateWeb Database Assembly")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // // Version information for an assembly consists of the following four values: @@ -26,7 +26,7 @@ using System.Reflection; // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion ("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the @@ -54,6 +54,6 @@ using System.Reflection; // documentation for more information on this. // -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] \ No newline at end of file +[assembly: AssemblyDelaySign (false)] +[assembly: AssemblyKeyFile ("")] +[assembly: AssemblyKeyName ("")] \ No newline at end of file diff --git a/Logic/AssemblyInfo.cs b/Logic/AssemblyInfo.cs index 7636e892..0baa771a 100644 --- a/Logic/AssemblyInfo.cs +++ b/Logic/AssemblyInfo.cs @@ -6,14 +6,14 @@ using System.Reflection; // associated with an assembly. // -[assembly: AssemblyTitle("")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // // Version information for an assembly consists of the following four values: @@ -26,7 +26,7 @@ using System.Reflection; // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion ("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the @@ -54,6 +54,6 @@ using System.Reflection; // documentation for more information on this. // -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] \ No newline at end of file +[assembly: AssemblyDelaySign (false)] +[assembly: AssemblyKeyFile ("")] +[assembly: AssemblyKeyName ("")] \ No newline at end of file diff --git a/Logic/Cache/GeographyCache.cs b/Logic/Cache/GeographyCache.cs index b4f2f749..87023b88 100644 --- a/Logic/Cache/GeographyCache.cs +++ b/Logic/Cache/GeographyCache.cs @@ -23,7 +23,7 @@ namespace Swarmops.Logic.Cache { lock (loadCacheLock) { - if (loadCache || lastRefresh.AddMinutes(cacheLifeSpanMinutes) < DateTime.Now) + if (loadCache || lastRefresh.AddMinutes (cacheLifeSpanMinutes) < DateTime.Now) { __geographyCache = SwarmDb.GetDatabaseForReading().GetHashedGeographies(); lastRefresh = DateTime.Now; @@ -34,11 +34,11 @@ namespace Swarmops.Logic.Cache } - public static Geography FromCache(int geographyId) + public static Geography FromCache (int geographyId) { lock (loadCacheLock) { - return Geography.FromBasic(GetGeography(geographyId)); + return Geography.FromBasic (GetGeography (geographyId)); } } @@ -50,7 +50,7 @@ namespace Swarmops.Logic.Cache Dictionary> hashedGeographies = GetHashedGeographies(); foreach (int entry in hashedGeographies.Keys) { - result.Add(hashedGeographies[entry][0]); + result.Add (hashedGeographies[entry][0]); } return result.ToArray(); @@ -58,27 +58,27 @@ namespace Swarmops.Logic.Cache } - public static BasicGeography[] GetGeographies(int[] ids) + public static BasicGeography[] GetGeographies (int[] ids) { List result = new List(); lock (loadCacheLock) { foreach (int i in ids) { - result.Add(GetGeography(i)); + result.Add (GetGeography (i)); } return result.ToArray(); } } - public static BasicGeography[] GetGeographyChildren(int parentGeographyId) + public static BasicGeography[] GetGeographyChildren (int parentGeographyId) { List result = new List(); lock (loadCacheLock) { // Prime the cache - BasicGeography partent = GetGeography(parentGeographyId); + BasicGeography partent = GetGeography (parentGeographyId); //TODO: Possible to miss a child geography here if it was added since last cache reload. @@ -86,45 +86,45 @@ namespace Swarmops.Logic.Cache foreach (BasicGeography b in hashedGeographies[parentGeographyId]) { if (b.Identity != parentGeographyId) - result.Add(b); + result.Add (b); } return result.ToArray(); } } - public static int CountGeographyChildren(int parentGeographyId) + public static int CountGeographyChildren (int parentGeographyId) { lock (loadCacheLock) { // Prime the cache - BasicGeography partent = GetGeography(parentGeographyId); + BasicGeography partent = GetGeography (parentGeographyId); return GetHashedGeographies()[parentGeographyId].Count - 1; } } - public static BasicGeography[] GetGeographyLine(int leafGeographyId) + public static BasicGeography[] GetGeographyLine (int leafGeographyId) { List result = new List(); - BasicGeography currentNode = GetGeography(leafGeographyId); + BasicGeography currentNode = GetGeography (leafGeographyId); // This iterates until the zero-parentid root node is found while (currentNode.GeographyId != 0) { - result.Add(currentNode); + result.Add (currentNode); if (currentNode.ParentGeographyId != 0) { - currentNode = GetGeography(currentNode.ParentGeographyId); + currentNode = GetGeography (currentNode.ParentGeographyId); } else { - currentNode = new BasicGeography(0, 0, string.Empty); + currentNode = new BasicGeography (0, 0, string.Empty); } } @@ -136,13 +136,13 @@ namespace Swarmops.Logic.Cache public static BasicGeography[] GetGeographyTree() { - return GetGeographyTree(1); + return GetGeographyTree (1); } - public static Dictionary GetGeographyHashtable(int startGeographyId) + public static Dictionary GetGeographyHashtable (int startGeographyId) { - BasicGeography[] nodes = GetGeographyTree(startGeographyId); + BasicGeography[] nodes = GetGeographyTree (startGeographyId); Dictionary result = new Dictionary(); @@ -154,15 +154,15 @@ namespace Swarmops.Logic.Cache return result; } - public static BasicGeography[] GetGeographyTree(int startGeographyId) + public static BasicGeography[] GetGeographyTree (int startGeographyId) { Dictionary> nodes = GetHashedGeographies(); - return GetGeographyTree(nodes, startGeographyId, 0); + return GetGeographyTree (nodes, startGeographyId, 0); } - private static BasicGeography[] GetGeographyTree(Dictionary> geographies, + private static BasicGeography[] GetGeographyTree (Dictionary> geographies, int startNodeId, int generation) { @@ -174,17 +174,17 @@ namespace Swarmops.Logic.Cache { if (node.GeographyId != startNodeId) { - result.Add(new BasicGeography(node.GeographyId, node.ParentGeographyId, node.Name, generation + 1)); + result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation + 1)); // Add recursively - BasicGeography[] children = GetGeographyTree(geographies, node.GeographyId, generation + 1); + BasicGeography[] children = GetGeographyTree (geographies, node.GeographyId, generation + 1); if (children.Length > 0) { foreach (BasicGeography child in children) { - result.Add(child); + result.Add (child); } } } @@ -192,7 +192,7 @@ namespace Swarmops.Logic.Cache { // The top parent is special and should be added; the others shouldn't - result.Add(new BasicGeography(node.GeographyId, node.ParentGeographyId, node.Name, generation)); + result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation)); } } @@ -200,46 +200,46 @@ namespace Swarmops.Logic.Cache } - public static BasicGeography GetGeography(int geographyId) + public static BasicGeography GetGeography (int geographyId) { lock (loadCacheLock) { Dictionary> hashedGeographies = GetHashedGeographies(); - if (hashedGeographies.ContainsKey(geographyId)) + if (hashedGeographies.ContainsKey (geographyId)) return hashedGeographies[geographyId][0]; else { loadCache = true; hashedGeographies = GetHashedGeographies(); - if (hashedGeographies.ContainsKey(geographyId)) + if (hashedGeographies.ContainsKey (geographyId)) return hashedGeographies[geographyId][0]; else { - throw new ArgumentException("No such GeographyId: " + geographyId.ToString()); + throw new ArgumentException ("No such GeographyId: " + geographyId.ToString()); } } } } - public static BasicGeography GetGeographyByName(string geographyName) + public static BasicGeography GetGeographyByName (string geographyName) { string cmpName = geographyName.ToLower().Trim(); Dictionary> hashedGeographies = GetHashedGeographies(); foreach (int entry in hashedGeographies.Keys) { - if (hashedGeographies[entry][0].Name.ToLower().Trim().StartsWith(cmpName)) + if (hashedGeographies[entry][0].Name.ToLower().Trim().StartsWith (cmpName)) return hashedGeographies[entry][0]; } //TODO: This can miss due to that the geography was added after last cache reload - throw new ArgumentException("No such GeographyName: " + geographyName); + throw new ArgumentException ("No such GeographyName: " + geographyName); } - public static void SetGeographyName(int geographyId, string name) + public static void SetGeographyName (int geographyId, string name) { - SwarmDb.GetDatabaseForWriting().SetGeographyName(geographyId, name); - BasicGeography geo = SwarmDb.GetDatabaseForReading().GetGeography(geographyId); + SwarmDb.GetDatabaseForWriting().SetGeographyName (geographyId, name); + BasicGeography geo = SwarmDb.GetDatabaseForReading().GetGeography (geographyId); Dictionary> hashedGeographies = GetHashedGeographies(); hashedGeographies[geographyId][0] = geo; } diff --git a/Logic/Cache/GuidCache.cs b/Logic/Cache/GuidCache.cs index 414a353d..9786ad06 100644 --- a/Logic/Cache/GuidCache.cs +++ b/Logic/Cache/GuidCache.cs @@ -24,27 +24,27 @@ namespace Swarmops.Logic.Cache _nextGarbageCollect = DateTime.MinValue; } - public static void Set(string guidString, object objectToCache) + public static void Set (string guidString, object objectToCache) { ConditionalGarbageCollect(); _cache[guidString] = new CachedObject {StoredDateTime = DateTime.UtcNow, Object = objectToCache}; } - public static object Get(string guidString) + public static object Get (string guidString) { - if (!_cache.ContainsKey(guidString)) + if (!_cache.ContainsKey (guidString)) { return null; } return _cache[guidString].Object; } - public static void Delete(string guidString) + public static void Delete (string guidString) { - if (_cache.ContainsKey(guidString)) + if (_cache.ContainsKey (guidString)) { - _cache.Remove(guidString); + _cache.Remove (guidString); } } @@ -59,17 +59,17 @@ namespace Swarmops.Logic.Cache // Do a garbage collect and set the next one for, say, an hour out - _nextGarbageCollect = DateTime.UtcNow.AddHours(1); // do this first for thread reasons + _nextGarbageCollect = DateTime.UtcNow.AddHours (1); // do this first for thread reasons } - DateTime expired = DateTime.UtcNow.AddHours(-24); + DateTime expired = DateTime.UtcNow.AddHours (-24); foreach (string key in _cache.Keys.ToList()) // ToList() is crucial - it takes a copy of the list, which may be modified in-loop { if (_cache[key].StoredDateTime < expired) { - _cache.Remove(key); + _cache.Remove (key); } } } diff --git a/Logic/Cache/MailTemplateCache.cs b/Logic/Cache/MailTemplateCache.cs index c1027948..e7a8caa5 100644 --- a/Logic/Cache/MailTemplateCache.cs +++ b/Logic/Cache/MailTemplateCache.cs @@ -22,21 +22,21 @@ namespace Swarmops.Logic.Cache lastAccess = DateTime.MinValue; } - private static List GetCachedTemplates(string templateName) + private static List GetCachedTemplates (string templateName) { lock (loadCacheLock) { - if (loadCache || lastAccess.AddMinutes(cacheLifeSpanMinutes) < DateTime.Now) + if (loadCache || lastAccess.AddMinutes (cacheLifeSpanMinutes) < DateTime.Now) { __MailTemplateCache = new Dictionary>(); loadCache = false; } - if (!__MailTemplateCache.ContainsKey(templateName)) + if (!__MailTemplateCache.ContainsKey (templateName)) { BasicMailTemplate[] basicTemplates = - SwarmDb.GetDatabaseForReading().GetMailTemplatesByName(templateName); - List tmplList = new List(basicTemplates); + SwarmDb.GetDatabaseForReading().GetMailTemplatesByName (templateName); + List tmplList = new List (basicTemplates); __MailTemplateCache[templateName] = tmplList; } @@ -45,15 +45,15 @@ namespace Swarmops.Logic.Cache } } - public static BasicMailTemplate GetBestMatch(string templateName, string language, string country, + public static BasicMailTemplate GetBestMatch (string templateName, string language, string country, Organization org) { - List tmplList = GetCachedTemplates(templateName); + List tmplList = GetCachedTemplates (templateName); Organizations orgLine = (org != null) ? org.GetLine() : new Organizations(); int[] lineIDs = orgLine.Identities; - List idlist = new List(lineIDs); + List idlist = new List (lineIDs); BasicMailTemplate templateDefault = null; BasicMailTemplate countryDefault = null; @@ -62,7 +62,7 @@ namespace Swarmops.Logic.Cache foreach (BasicMailTemplate bmt in tmplList) { - int thisIndex = idlist.IndexOf(bmt.OrganizationId); + int thisIndex = idlist.IndexOf (bmt.OrganizationId); if (thisIndex > bestIndex) { bestIndex = thisIndex; diff --git a/Logic/Cache/OrganizationCache.cs b/Logic/Cache/OrganizationCache.cs index e5744684..10f047e8 100644 --- a/Logic/Cache/OrganizationCache.cs +++ b/Logic/Cache/OrganizationCache.cs @@ -26,7 +26,7 @@ namespace Swarmops.Logic.Cache { lock (loadCacheLock) { - return (__loadCache || lastRefresh.AddMinutes(cacheLifeSpanMinutes) < DateTime.Now); + return (__loadCache || lastRefresh.AddMinutes (cacheLifeSpanMinutes) < DateTime.Now); } } private set @@ -56,21 +56,21 @@ namespace Swarmops.Logic.Cache return __organizationCache; } - public static Organization FromCache(int OrganizationId) + public static Organization FromCache (int OrganizationId) { lock (loadCacheLock) { - return Organization.FromBasic(GetOrganization(OrganizationId)); + return Organization.FromBasic (GetOrganization (OrganizationId)); } } - internal static int CreateOrganization(int ParentOrganizationId, string NameInternational, string Name, + internal static int CreateOrganization (int ParentOrganizationId, string NameInternational, string Name, string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId) { - int Identity = SwarmDb.GetDatabaseForWriting().CreateOrganization(ParentOrganizationId, + int Identity = SwarmDb.GetDatabaseForWriting().CreateOrganization (ParentOrganizationId, NameInternational, Name, NameShort, @@ -84,19 +84,19 @@ namespace Swarmops.Logic.Cache return Identity; } - public static void UpdateOrganization(int ParentOrganizationId, string NameInternational, string Name, + public static void UpdateOrganization (int ParentOrganizationId, string NameInternational, string Name, string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId, int OrganizationId) { SwarmDb.GetDatabaseForWriting() - .UpdateOrganization(ParentOrganizationId, NameInternational, Name, NameShort, Domain, + .UpdateOrganization (ParentOrganizationId, NameInternational, Name, NameShort, Domain, MailPrefix, AnchorGeographyId, AcceptsMembers, AutoAssignNewMembers, DefaultCountryId, OrganizationId); needsReload = true; } - internal static void Reload(int objectId) + internal static void Reload (int objectId) { __loadCache = true; @@ -115,18 +115,18 @@ namespace Swarmops.Logic.Cache List returnList = new List(); foreach (int id in hashedOrganisations.Keys) { - returnList.Add(hashedOrganisations[id][0]); + returnList.Add (hashedOrganisations[id][0]); } return returnList.ToArray(); } } - public static BasicOrganization GetOrganization(int OrganizationId) + public static BasicOrganization GetOrganization (int OrganizationId) { lock (loadCacheLock) { Dictionary> hashedOrganisations = GetHashedOrganizations(); - if (hashedOrganisations.ContainsKey(OrganizationId)) + if (hashedOrganisations.ContainsKey (OrganizationId)) return hashedOrganisations[OrganizationId][0]; else { @@ -134,31 +134,31 @@ namespace Swarmops.Logic.Cache needsReload = true; hashedOrganisations = GetHashedOrganizations(); - if (hashedOrganisations.ContainsKey(OrganizationId)) + if (hashedOrganisations.ContainsKey (OrganizationId)) return hashedOrganisations[OrganizationId][0]; else { - throw new ArgumentException("No such OrganizationId: " + OrganizationId.ToString()); + throw new ArgumentException ("No such OrganizationId: " + OrganizationId.ToString()); } } ; } } - public static BasicOrganization[] GetOrganizationTree(int startOrganizationId) + public static BasicOrganization[] GetOrganizationTree (int startOrganizationId) { lock (loadCacheLock) { Dictionary> organizations = GetHashedOrganizations(); - return GetOrganizationTree(organizations, startOrganizationId, 0); + return GetOrganizationTree (organizations, startOrganizationId, 0); } } - public static Dictionary GetOrganizationHashtable(int startOrganizationId) + public static Dictionary GetOrganizationHashtable (int startOrganizationId) { - BasicOrganization[] organizations = GetOrganizationTree(startOrganizationId); + BasicOrganization[] organizations = GetOrganizationTree (startOrganizationId); Dictionary result = new Dictionary(); @@ -171,13 +171,13 @@ namespace Swarmops.Logic.Cache } - private static BasicOrganization[] GetOrganizationTree(Dictionary> organizations, + private static BasicOrganization[] GetOrganizationTree (Dictionary> organizations, int startOrganizationId, int generation) { List result = new List(); //Prime the cache - BasicOrganization start = GetOrganization(startOrganizationId); + BasicOrganization start = GetOrganization (startOrganizationId); List thisList = organizations[startOrganizationId]; @@ -185,19 +185,19 @@ namespace Swarmops.Logic.Cache { if (organization.OrganizationId != startOrganizationId) { - result.Add(organization); + result.Add (organization); // new Organization(organization.OrganizationId, organization.ParentOrganizationId, organization.Name, generation + 1)); // Add recursively - BasicOrganization[] children = GetOrganizationTree(organizations, organization.OrganizationId, + BasicOrganization[] children = GetOrganizationTree (organizations, organization.OrganizationId, generation + 1); if (children.Length > 0) { foreach (BasicOrganization child in children) { - result.Add(child); + result.Add (child); } } } @@ -205,7 +205,7 @@ namespace Swarmops.Logic.Cache { // The top parent is special and should be added; the others shouldn't - result.Add(organization); + result.Add (organization); // (new Organization(organization.OrganizationId, organization.ParentOrganizationId, organization.Name, generation)); } } @@ -213,41 +213,41 @@ namespace Swarmops.Logic.Cache return result.ToArray(); } - public static BasicOrganization[] GetOrganizationChildren(int parentOrgId) + public static BasicOrganization[] GetOrganizationChildren (int parentOrgId) { List result = new List(); lock (loadCacheLock) { - BasicOrganization parent = GetOrganization(parentOrgId); + BasicOrganization parent = GetOrganization (parentOrgId); //TODO: It is possible to miss a child here if that child was added after the last cache load. Dictionary> hashedOrganizations = GetHashedOrganizations(); foreach (BasicOrganization b in hashedOrganizations[parentOrgId]) { if (b.Identity != parentOrgId) - result.Add(b); + result.Add (b); } return result.ToArray(); } } - public static BasicOrganization[] GetOrganizationLine(int leafOrganizationId) + public static BasicOrganization[] GetOrganizationLine (int leafOrganizationId) { lock (loadCacheLock) { List result = new List(); - BasicOrganization currentOrganization = GetOrganization(leafOrganizationId); + BasicOrganization currentOrganization = GetOrganization (leafOrganizationId); // This iterates until the zero-parentid root Organization is found while (currentOrganization.OrganizationId > 0) { - result.Add(currentOrganization); + result.Add (currentOrganization); if (currentOrganization.ParentOrganizationId > 0) { - currentOrganization = GetOrganization(currentOrganization.ParentOrganizationId); + currentOrganization = GetOrganization (currentOrganization.ParentOrganizationId); } else { @@ -261,11 +261,11 @@ namespace Swarmops.Logic.Cache } } - [Obsolete("Never use this function. Mark the org as unused, deleted. Records are needed for historic reasons.", + [Obsolete ("Never use this function. Mark the org as unused, deleted. Records are needed for historic reasons.", true)] - internal static void DeleteOrganization(int p) + internal static void DeleteOrganization (int p) { - SwarmDb.GetDatabaseForWriting().DeleteOrganization(p); + SwarmDb.GetDatabaseForWriting().DeleteOrganization (p); needsReload = true; } @@ -291,7 +291,7 @@ namespace Swarmops.Logic.Cache return __cachedUptakeGeographies; } - internal static int[] GetOrganizationsIdsInGeographies(BasicGeography[] nodes) + internal static int[] GetOrganizationsIdsInGeographies (BasicGeography[] nodes) { if (nodes == null || nodes.Length == 0) { @@ -302,14 +302,14 @@ namespace Swarmops.Logic.Cache foreach (BasicGeography node in nodes) { - nodeIdList.Add(node.GeographyId); + nodeIdList.Add (node.GeographyId); } - return GetOrganizationIdsInGeographies(nodeIdList.ToArray()); + return GetOrganizationIdsInGeographies (nodeIdList.ToArray()); } - public static int[] GetOrganizationIdsInGeographies(int[] nodeIds) + public static int[] GetOrganizationIdsInGeographies (int[] nodeIds) { if (nodeIds == null || nodeIds.Length == 0) { @@ -327,7 +327,7 @@ namespace Swarmops.Logic.Cache foreach (int id in hashedOrgs.Keys) { BasicOrganization bo = hashedOrgs[id][0]; - if (idsToFind.ContainsKey(bo.AnchorGeographyId)) + if (idsToFind.ContainsKey (bo.AnchorGeographyId)) { resultKeys[bo.Identity] = true; } @@ -339,11 +339,11 @@ namespace Swarmops.Logic.Cache foreach (int orgId in allUptakes.Keys) { //connected to valid org? - if (hashedOrgs.ContainsKey(orgId)) + if (hashedOrgs.ContainsKey (orgId)) { foreach (int geoId in allUptakes[orgId]) { - if (idsToFind.ContainsKey(geoId)) + if (idsToFind.ContainsKey (geoId)) { resultKeys[orgId] = true; } @@ -353,22 +353,22 @@ namespace Swarmops.Logic.Cache } - return (new List(resultKeys.Keys)).ToArray(); + return (new List (resultKeys.Keys)).ToArray(); ; } - internal static void AddOrgUptakeGeography(int p, int geoId) + internal static void AddOrgUptakeGeography (int p, int geoId) { - SwarmDb.GetDatabaseForWriting().AddOrgUptakeGeography(p, geoId); + SwarmDb.GetDatabaseForWriting().AddOrgUptakeGeography (p, geoId); lock (loadCacheLock) { __cachedUptakeGeographies = null; } } - internal static void DeleteOrgUptakeGeography(int p, int geoId) + internal static void DeleteOrgUptakeGeography (int p, int geoId) { - SwarmDb.GetDatabaseForWriting().DeleteOrgUptakeGeography(p, geoId); + SwarmDb.GetDatabaseForWriting().DeleteOrgUptakeGeography (p, geoId); lock (loadCacheLock) { __cachedUptakeGeographies = null; diff --git a/Logic/Communications/AutoMail.cs b/Logic/Communications/AutoMail.cs index 2c8dfd4e..40300170 100644 --- a/Logic/Communications/AutoMail.cs +++ b/Logic/Communications/AutoMail.cs @@ -8,11 +8,11 @@ namespace Swarmops.Logic.Communications { public class AutoMail : BasicAutoMail { - private AutoMail() : base(null) + private AutoMail() : base (null) { } // Private constructor - private AutoMail(BasicAutoMail basic) : base(basic) + private AutoMail (BasicAutoMail basic) : base (basic) { } @@ -23,20 +23,20 @@ namespace Swarmops.Logic.Communications set { base.Body = value; - SwarmDb.GetDatabaseForWriting().SetAutoMail(this); // saves changes + SwarmDb.GetDatabaseForWriting().SetAutoMail (this); // saves changes } } - internal static AutoMail FromBasic(BasicAutoMail basic) + internal static AutoMail FromBasic (BasicAutoMail basic) { - return new AutoMail(basic); + return new AutoMail (basic); } - public static AutoMail FromTypeOrganizationAndGeography(AutoMailType type, Organization org, Geography geo) + public static AutoMail FromTypeOrganizationAndGeography (AutoMailType type, Organization org, Geography geo) { - BasicAutoMail basic = SwarmDb.GetDatabaseForReading().GetAutoMail(type, org.Identity, geo.Identity); + BasicAutoMail basic = SwarmDb.GetDatabaseForReading().GetAutoMail (type, org.Identity, geo.Identity); if (basic == null) { @@ -48,16 +48,16 @@ namespace Swarmops.Logic.Communications return null; // If there is no body, there is no mail } - return FromBasic(basic); + return FromBasic (basic); } - public static AutoMail Create(AutoMailType type, Organization org, Geography geo, + public static AutoMail Create (AutoMailType type, Organization org, Geography geo, Person author, string title, string body) { - SwarmDb.GetDatabaseForWriting().SetAutoMail(type, org.Identity, geo.Identity, + SwarmDb.GetDatabaseForWriting().SetAutoMail (type, org.Identity, geo.Identity, author == null ? 0 : author.Identity, title, body); - return FromTypeOrganizationAndGeography(type, org, geo); + return FromTypeOrganizationAndGeography (type, org, geo); } diff --git a/Logic/Communications/CommunicationTurnaround.cs b/Logic/Communications/CommunicationTurnaround.cs index d01b2cb2..7e48f3a6 100644 --- a/Logic/Communications/CommunicationTurnaround.cs +++ b/Logic/Communications/CommunicationTurnaround.cs @@ -8,34 +8,34 @@ namespace Swarmops.Logic.Communications { public class CommunicationTurnaround : BasicCommunicationTurnaround { - private CommunicationTurnaround(BasicCommunicationTurnaround basic) : base(basic) + private CommunicationTurnaround (BasicCommunicationTurnaround basic) : base (basic) { // private ctor } - public static CommunicationTurnaround FromBasic(BasicCommunicationTurnaround basic) + public static CommunicationTurnaround FromBasic (BasicCommunicationTurnaround basic) { - return new CommunicationTurnaround(basic); + return new CommunicationTurnaround (basic); } - public static CommunicationTurnaround FromIdentity(Organization organization, int communicationTypeId, + public static CommunicationTurnaround FromIdentity (Organization organization, int communicationTypeId, int communicationId) { return - FromBasic(SwarmDb.GetDatabaseForReading() - .GetCommunicationTurnaround(organization.Identity, communicationTypeId, + FromBasic (SwarmDb.GetDatabaseForReading() + .GetCommunicationTurnaround (organization.Identity, communicationTypeId, communicationId)); } - public static CommunicationTurnaround Create(Organization organization, int communicationId, + public static CommunicationTurnaround Create (Organization organization, int communicationId, DateTime dateTimeOpened) { SwarmDb.GetDatabaseForWriting() - .CreateCommunicationTurnaround(organization.Identity, 1, communicationId, dateTimeOpened); - return FromIdentity(organization, 1, communicationId); + .CreateCommunicationTurnaround (organization.Identity, 1, communicationId, dateTimeOpened); + return FromIdentity (organization, 1, communicationId); } - public void SetResponded(DateTime dateTime, Person person) + public void SetResponded (DateTime dateTime, Person person) { if (!Open) { @@ -55,13 +55,13 @@ namespace Swarmops.Logic.Communications } SwarmDb.GetDatabaseForWriting() - .SetCommunicationTurnaroundResponded(OrganizationId, CommunicationTypeId, CommunicationId, dateTime, + .SetCommunicationTurnaroundResponded (OrganizationId, CommunicationTypeId, CommunicationId, dateTime, personId); base.Responded = true; } - public void Close(DateTime dateTime, Person person) + public void Close (DateTime dateTime, Person person) { if (!Open) { @@ -76,7 +76,7 @@ namespace Swarmops.Logic.Communications } SwarmDb.GetDatabaseForWriting() - .SetCommunicationTurnaroundClosed(OrganizationId, CommunicationTypeId, CommunicationId, dateTime, + .SetCommunicationTurnaroundClosed (OrganizationId, CommunicationTypeId, CommunicationId, dateTime, personId); base.Open = false; diff --git a/Logic/Communications/CommunicationTurnarounds.cs b/Logic/Communications/CommunicationTurnarounds.cs index c16d4e7a..45b0dc70 100644 --- a/Logic/Communications/CommunicationTurnarounds.cs +++ b/Logic/Communications/CommunicationTurnarounds.cs @@ -8,19 +8,19 @@ namespace Swarmops.Logic.Communications public class CommunicationTurnarounds : PluralBase { - public static CommunicationTurnarounds ForOrganization(Organization organization) + public static CommunicationTurnarounds ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static CommunicationTurnarounds ForOrganization(Organization organization, bool includeClosed) + public static CommunicationTurnarounds ForOrganization (Organization organization, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds (organization)); } return - FromArray(SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds(organization, + FromArray (SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds (organization, DatabaseCondition.OpenTrue)); } } diff --git a/Logic/Communications/ICommsRenderer.cs b/Logic/Communications/ICommsRenderer.cs index 35c0f9b7..461aeea5 100644 --- a/Logic/Communications/ICommsRenderer.cs +++ b/Logic/Communications/ICommsRenderer.cs @@ -8,7 +8,7 @@ namespace Swarmops.Logic.Communications /// public interface ICommsRenderer { - RenderedComm RenderComm(Person person); + RenderedComm RenderComm (Person person); } public class RenderedComm : Dictionary diff --git a/Logic/Communications/ICommsTransmitter.cs b/Logic/Communications/ICommsTransmitter.cs index faa8195a..7d3bee7b 100644 --- a/Logic/Communications/ICommsTransmitter.cs +++ b/Logic/Communications/ICommsTransmitter.cs @@ -11,6 +11,6 @@ namespace Swarmops.Logic.Communications /// /// The piece of communications to send. /// The person to send to. - void Transmit(PayloadEnvelope envelope, Person person); + void Transmit (PayloadEnvelope envelope, Person person); } } \ No newline at end of file diff --git a/Logic/Communications/MailTemplate.cs b/Logic/Communications/MailTemplate.cs index cfceca10..62e3efb2 100644 --- a/Logic/Communications/MailTemplate.cs +++ b/Logic/Communications/MailTemplate.cs @@ -16,12 +16,12 @@ namespace Swarmops.Logic.Communications private HtmlDocument htmlDoc; internal MailTemplate() - : base(0, "", "", "", 0, "") + : base (0, "", "", "", 0, "") { } - public MailTemplate(BasicMailTemplate basic) - : base(basic) + public MailTemplate (BasicMailTemplate basic) + : base (basic) { this.originallyLoadedContent = basic.TemplateBody; } @@ -44,7 +44,7 @@ namespace Swarmops.Logic.Communications if (this.htmlDoc != null) { this.htmlDoc = new HtmlDocument(); - this.htmlDoc.LoadHtml(value); + this.htmlDoc.LoadHtml (value); } } catch @@ -60,11 +60,11 @@ namespace Swarmops.Logic.Communications get { if (HtmlDoc.DocumentNode == null - || HtmlDoc.DocumentNode.SelectSingleNode("//body") == null) + || HtmlDoc.DocumentNode.SelectSingleNode ("//body") == null) { NormalizeHtml(); } - return HtmlDoc.DocumentNode.SelectSingleNode("//body"); + return HtmlDoc.DocumentNode.SelectSingleNode ("//body"); } } @@ -78,111 +78,112 @@ namespace Swarmops.Logic.Communications get { string htmlText = HtmlDoc.DocumentNode.OuterHtml; - Regex re = new Regex(@"\r{0,1}\n +"); + Regex re = new Regex (@"\r{0,1}\n +"); //Templates for plain text are supposedly already in a reasonable
 format
-                if (TemplateName.EndsWith("Plain"))
-                    htmlText = re.Replace(htmlText, "\r\n");
+                if (TemplateName.EndsWith ("Plain"))
+                    htmlText = re.Replace (htmlText, "\r\n");
                 else
-                    htmlText = re.Replace(htmlText, " ");
+                    htmlText = re.Replace (htmlText, " ");
 
                 HtmlDocument htmlDoc = new HtmlDocument();
-                htmlDoc.LoadHtml(htmlText);
+                htmlDoc.LoadHtml (htmlText);
 
                 if (htmlDoc.DocumentNode == null)
                 {
-                    throw new Exception("MailTemplate.PlainText detected htmlDoc.DocumentNode== null:\nHTML:" + htmlText);
+                    throw new Exception ("MailTemplate.PlainText detected htmlDoc.DocumentNode== null:\nHTML:" +
+                                         htmlText);
                 }
 
-                HtmlNodeCollection tagsArray = htmlDoc.DocumentNode.SelectNodes("//a");
+                HtmlNodeCollection tagsArray = htmlDoc.DocumentNode.SelectNodes ("//a");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        if (n.InnerText.Trim().ToLower() != n.GetAttributeValue("href", "").Trim().ToLower())
-                            n.AppendChild(htmlDoc.CreateTextNode(" (" + n.GetAttributeValue("href", "") + ")"));
+                        if (n.InnerText.Trim().ToLower() != n.GetAttributeValue ("href", "").Trim().ToLower())
+                            n.AppendChild (htmlDoc.CreateTextNode (" (" + n.GetAttributeValue ("href", "") + ")"));
                     }
                 }
 
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//h1");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//h1");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n\r\n"), null);
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n\r\n"), null);
                     }
                 }
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//h2");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//h2");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n\r\n"), null);
-                        n.AppendChild(htmlDoc.CreateTextNode("\r\n\r\n"));
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n\r\n"), null);
+                        n.AppendChild (htmlDoc.CreateTextNode ("\r\n\r\n"));
                     }
                 }
 
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//h3");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//h3");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n\r\n"), null);
-                        n.AppendChild(htmlDoc.CreateTextNode("\r\n\r\n"));
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n\r\n"), null);
+                        n.AppendChild (htmlDoc.CreateTextNode ("\r\n\r\n"));
                     }
                 }
 
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//li");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//li");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n\r\n- "), null);
-                        n.AppendChild(htmlDoc.CreateTextNode("\r\n"));
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n\r\n- "), null);
+                        n.AppendChild (htmlDoc.CreateTextNode ("\r\n"));
                     }
                 }
 
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//tr");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//tr");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n"), null);
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n"), null);
                     }
                 }
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//p");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//p");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.InsertAfter(htmlDoc.CreateTextNode("\r\n\r\n"), null);
-                        n.AppendChild(htmlDoc.CreateTextNode("\r\n"));
+                        n.InsertAfter (htmlDoc.CreateTextNode ("\r\n\r\n"), null);
+                        n.AppendChild (htmlDoc.CreateTextNode ("\r\n"));
                     }
                 }
-                tagsArray = htmlDoc.DocumentNode.SelectNodes("//br");
+                tagsArray = htmlDoc.DocumentNode.SelectNodes ("//br");
                 if (tagsArray != null)
                 {
                     foreach (HtmlNode n in tagsArray)
                     {
-                        n.AppendChild(htmlDoc.CreateTextNode("\r\n"));
+                        n.AppendChild (htmlDoc.CreateTextNode ("\r\n"));
                     }
                 }
-                HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
+                HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode ("//body");
                 string retval = "";
 
                 if (bodyNode != null)
-                    retval = htmlDoc.DocumentNode.SelectSingleNode("//body").InnerText;
+                    retval = htmlDoc.DocumentNode.SelectSingleNode ("//body").InnerText;
                 else
-                    throw new Exception("ERROR: No body in document in MailTemplate.PlainText");
+                    throw new Exception ("ERROR: No body in document in MailTemplate.PlainText");
 
 
-                re = new Regex(@"\r\n\s+(?=\r\n)"); //replace rows with only whitespace with empty
-                retval = re.Replace(retval, "\r\n");
+                re = new Regex (@"\r\n\s+(?=\r\n)"); //replace rows with only whitespace with empty
+                retval = re.Replace (retval, "\r\n");
 
-                re = new Regex(@"\r\n\r\n(\r\n)+"); //replace three or more linefeeds with two.
-                retval = re.Replace(retval, "\r\n\r\n");
+                re = new Regex (@"\r\n\r\n(\r\n)+"); //replace three or more linefeeds with two.
+                retval = re.Replace (retval, "\r\n\r\n");
 
-                return HttpUtility.HtmlDecode(retval);
+                return HttpUtility.HtmlDecode (retval);
             }
         }
 
@@ -195,11 +196,11 @@ namespace Swarmops.Logic.Communications
                     this.htmlDoc = new HtmlDocument();
                     try
                     {
-                        this.htmlDoc.LoadHtml(base.TemplateBody);
+                        this.htmlDoc.LoadHtml (base.TemplateBody);
                     }
                     catch (Exception ex)
                     {
-                        throw new Exception("Failed to load Html in MailTemplate", ex);
+                        throw new Exception ("Failed to load Html in MailTemplate", ex);
                     }
                 }
                 return this.htmlDoc;
@@ -229,7 +230,7 @@ namespace Swarmops.Logic.Communications
             {
                 HtmlNode titleNode = TitleNode();
                 if (titleNode != null)
-                    return HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(titleNode.InnerText));
+                    return HttpUtility.HtmlDecode (HttpUtility.HtmlDecode (titleNode.InnerText));
                 return "";
             }
         }
@@ -243,15 +244,15 @@ namespace Swarmops.Logic.Communications
 
         #region Data layer access
 
-        public static MailTemplate FromIdentity(int templateId)
+        public static MailTemplate FromIdentity (int templateId)
         {
-            BasicMailTemplate basic = SwarmDb.GetDatabaseForReading().GetMailTemplateById(templateId);
-            return FromBasic(basic);
+            BasicMailTemplate basic = SwarmDb.GetDatabaseForReading().GetMailTemplateById (templateId);
+            return FromBasic (basic);
         }
 
-        internal static MailTemplate FromBasic(BasicMailTemplate basic)
+        internal static MailTemplate FromBasic (BasicMailTemplate basic)
         {
-            MailTemplate templ = new MailTemplate(basic);
+            MailTemplate templ = new MailTemplate (basic);
             return templ;
         }
 
@@ -261,21 +262,21 @@ namespace Swarmops.Logic.Communications
             List resultlist = new List();
             foreach (BasicMailTemplate bt in basic)
             {
-                resultlist.Add(FromBasic(bt));
+                resultlist.Add (FromBasic (bt));
             }
 
             return resultlist;
         }
 
 
-        public static MailTemplate Create(
+        public static MailTemplate Create (
             string templateName,
             string languageCode,
             string countryCode,
             int organizationId,
             string templateBody)
         {
-            int retId = SwarmDb.GetDatabaseForWriting().SetMailTemplate(0,
+            int retId = SwarmDb.GetDatabaseForWriting().SetMailTemplate (0,
                 templateName,
                 languageCode,
                 countryCode,
@@ -283,13 +284,13 @@ namespace Swarmops.Logic.Communications
                 templateBody);
             MailTemplateCache.loadCache = true;
 
-            return FromIdentity(retId);
+            return FromIdentity (retId);
         }
 
         public void Update()
         {
             TemplateBody = TemplateBody; //to make sure the HTMlDoc is taken into account
-            SwarmDb.GetDatabaseForWriting().SetMailTemplate(this); // saves changes
+            SwarmDb.GetDatabaseForWriting().SetMailTemplate (this); // saves changes
             MailTemplateCache.loadCache = true;
         }
 
@@ -297,32 +298,32 @@ namespace Swarmops.Logic.Communications
         //----------------------------------------------//
         // Cached retreval
 
-        public static MailTemplate FromNameCountryAndOrg(string name, string countrycode, int orgId)
+        public static MailTemplate FromNameCountryAndOrg (string name, string countrycode, int orgId)
         {
             if (name == "")
                 return None;
 
-            Country country = Country.FromCode(countrycode);
-            string lang = country.Culture.Substring(0, 2);
-            Organization org = Organization.FromIdentity(orgId);
+            Country country = Country.FromCode (countrycode);
+            string lang = country.Culture.Substring (0, 2);
+            Organization org = Organization.FromIdentity (orgId);
 
-            BasicMailTemplate basic = MailTemplateCache.GetBestMatch(name, lang, countrycode, org);
+            BasicMailTemplate basic = MailTemplateCache.GetBestMatch (name, lang, countrycode, org);
 
-            return FromBasic(basic);
+            return FromBasic (basic);
         }
 
 
-        public static MailTemplate FromNameAndOrg(string name, Organization sender)
+        public static MailTemplate FromNameAndOrg (string name, Organization sender)
         {
             if (name == "")
                 return None;
 
             Country country = sender.DefaultCountry;
             string countrycode = country.Code;
-            string lang = country.Culture.Substring(0, 2);
+            string lang = country.Culture.Substring (0, 2);
 
-            BasicMailTemplate basic = MailTemplateCache.GetBestMatch(name, lang, countrycode, sender);
-            return FromBasic(basic);
+            BasicMailTemplate basic = MailTemplateCache.GetBestMatch (name, lang, countrycode, sender);
+            return FromBasic (basic);
         }
 
         #endregion
@@ -336,29 +337,29 @@ namespace Swarmops.Logic.Communications
         public void NormalizeHtml()
         {
             //Make sure there is a full html document defined
-            this.htmlDoc = NormalizeHtmlExtracted(HtmlDoc, TemplateName.EndsWith("Plain"));
+            this.htmlDoc = NormalizeHtmlExtracted (HtmlDoc, TemplateName.EndsWith ("Plain"));
         }
 
-        private HtmlDocument NormalizeHtmlExtracted(HtmlDocument htDoc, bool forPlainText)
+        private HtmlDocument NormalizeHtmlExtracted (HtmlDocument htDoc, bool forPlainText)
         {
             if (htDoc == null)
             {
-                throw new Exception("NormalizeHtmlExtracted was called with null document:\nTemplateBody:" +
-                                    TemplateBody);
+                throw new Exception ("NormalizeHtmlExtracted was called with null document:\nTemplateBody:" +
+                                     TemplateBody);
             }
 
             if (htDoc.DocumentNode == null)
             {
-                throw new Exception("NormalizeHtmlExtracted was called with null DocumentNode:\nTemplateBody:" +
-                                    TemplateBody);
+                throw new Exception ("NormalizeHtmlExtracted was called with null DocumentNode:\nTemplateBody:" +
+                                     TemplateBody);
             }
 
             string newHtml = "";
 
-            HtmlNode headNode = htDoc.DocumentNode.SelectSingleNode("//head");
-            HtmlNode bodyNode = htDoc.DocumentNode.SelectSingleNode("//body");
-            HtmlNode htmlNode = htDoc.DocumentNode.SelectSingleNode("//html");
-            HtmlNode titleNode = htDoc.DocumentNode.SelectSingleNode("//head/title");
+            HtmlNode headNode = htDoc.DocumentNode.SelectSingleNode ("//head");
+            HtmlNode bodyNode = htDoc.DocumentNode.SelectSingleNode ("//body");
+            HtmlNode htmlNode = htDoc.DocumentNode.SelectSingleNode ("//html");
+            HtmlNode titleNode = htDoc.DocumentNode.SelectSingleNode ("//head/title");
             if (bodyNode == null && headNode == null && htmlNode == null)
                 newHtml = "Untitled" + htDoc.DocumentNode.OuterHtml +
                           "";
@@ -368,36 +369,36 @@ namespace Swarmops.Logic.Communications
                 newHtml = "" + bodyNode.OuterHtml + "";
             else if (headNode == null && htmlNode != null)
             {
-                headNode = htDoc.CreateElement("head");
-                htmlNode.InsertAfter(headNode, null);
-                titleNode = htDoc.CreateElement("title");
+                headNode = htDoc.CreateElement ("head");
+                htmlNode.InsertAfter (headNode, null);
+                titleNode = htDoc.CreateElement ("title");
                 titleNode.InnerHtml = "Untitled";
-                headNode.AppendChild(titleNode);
+                headNode.AppendChild (titleNode);
             }
             else if (titleNode == null && headNode != null)
             {
-                titleNode = htDoc.CreateElement("title");
+                titleNode = htDoc.CreateElement ("title");
                 titleNode.InnerHtml = "Untitled";
-                headNode.AppendChild(titleNode);
+                headNode.AppendChild (titleNode);
             }
 
             if (newHtml != "")
             {
                 htDoc = new HtmlDocument();
-                htDoc.LoadHtml(newHtml);
+                htDoc.LoadHtml (newHtml);
             }
 
             if (htDoc.DocumentNode == null)
             {
-                throw new Exception("NormalizeHtmlExtracted Document Node is null for " + newHtml);
+                throw new Exception ("NormalizeHtmlExtracted Document Node is null for " + newHtml);
             }
 
             //"Plain" templates should have the whole body in a pre tag
-            HtmlNode bodyNode2 = htDoc.DocumentNode.SelectSingleNode("//body");
+            HtmlNode bodyNode2 = htDoc.DocumentNode.SelectSingleNode ("//body");
 
             if (bodyNode2 == null)
             {
-                throw new Exception("NormalizeHtmlExtracted bodyNode2 is null for " + newHtml);
+                throw new Exception ("NormalizeHtmlExtracted bodyNode2 is null for " + newHtml);
             }
 
             int preIx = 0;
@@ -408,16 +409,16 @@ namespace Swarmops.Logic.Communications
 
             if (forPlainText && preIx == bodyNode2.ChildNodes.Count)
             {
-                bodyNode2.InsertAfter(htDoc.CreateElement("pre"), null);
+                bodyNode2.InsertAfter (htDoc.CreateElement ("pre"), null);
                 for (int i = bodyNode2.ChildNodes.Count - 1; i > 0; --i)
                 {
                     HtmlNode nodeToMove = bodyNode2.ChildNodes[i];
-                    bodyNode2.RemoveChild(nodeToMove);
-                    bodyNode2.FirstChild.InsertAfter(nodeToMove, null);
+                    bodyNode2.RemoveChild (nodeToMove);
+                    bodyNode2.FirstChild.InsertAfter (nodeToMove, null);
                 }
                 string html = htDoc.DocumentNode.OuterHtml;
                 htDoc = new HtmlDocument();
-                htDoc.LoadHtml(html);
+                htDoc.LoadHtml (html);
             }
 
             return htDoc;
@@ -425,25 +426,25 @@ namespace Swarmops.Logic.Communications
 
         public void MarkPlaceholderSpans()
         {
-            MarkPlaceholderSpans(HtmlDoc);
+            MarkPlaceholderSpans (HtmlDoc);
         }
 
-        public void MarkPlaceholderSpans(Dictionary allowedPlaceholders)
+        public void MarkPlaceholderSpans (Dictionary allowedPlaceholders)
         {
             MarkPlaceholderSpans();
-            HtmlNodeCollection allTags = HtmlBody.SelectNodes("//*[@class='placeholder2']");
-            Regex reCleanup = new Regex(@"[\s%]");
+            HtmlNodeCollection allTags = HtmlBody.SelectNodes ("//*[@class='placeholder2']");
+            Regex reCleanup = new Regex (@"[\s%]");
             if (allTags != null)
             {
                 foreach (HtmlNode n in allTags)
                 {
-                    string key = reCleanup.Replace(n.InnerText, "");
+                    string key = reCleanup.Replace (n.InnerText, "");
                     string keyLow = key.ToLower();
-                    if (!allowedPlaceholders.ContainsKey(keyLow))
+                    if (!allowedPlaceholders.ContainsKey (keyLow))
                     {
-                        string classname = n.GetAttributeValue("class", "");
-                        classname = classname.Replace("placeholder2", "placeholderUnkn");
-                        n.SetAttributeValue("class", classname);
+                        string classname = n.GetAttributeValue ("class", "");
+                        classname = classname.Replace ("placeholder2", "placeholderUnkn");
+                        n.SetAttributeValue ("class", classname);
                     }
                     else if (allowedPlaceholders[keyLow] != key
                              && allowedPlaceholders[keyLow].ToUpper() != key
@@ -455,19 +456,19 @@ namespace Swarmops.Logic.Communications
             }
         }
 
-        public static void MarkPlaceholderSpans(HtmlDocument htDoc)
+        public static void MarkPlaceholderSpans (HtmlDocument htDoc)
         {
             //Code below is for inserting span's around %tag% placeholders so they can be redered with bg-color in editor
             //(It is a bit hairy, because it is meddling with the same structure it is looping on
             //and that gives some strange effects...)
-            Regex reTags = new Regex(@"(%[a-zåäö0-9]+%)", RegexOptions.IgnoreCase);
-            HtmlNodeCollection allWithTextNodes = htDoc.DocumentNode.SelectNodes("//body//text()/..");
-                //select nodes that have text below them
+            Regex reTags = new Regex (@"(%[a-zåäö0-9]+%)", RegexOptions.IgnoreCase);
+            HtmlNodeCollection allWithTextNodes = htDoc.DocumentNode.SelectNodes ("//body//text()/..");
+            //select nodes that have text below them
             if (allWithTextNodes != null)
             {
                 foreach (HtmlNode n in allWithTextNodes)
                 {
-                    HtmlNodeCollection allTextNodes = n.SelectNodes("./text()"); //select the #text children
+                    HtmlNodeCollection allTextNodes = n.SelectNodes ("./text()"); //select the #text children
                     if (allTextNodes != null)
                     {
                         foreach (HtmlNode tn in allTextNodes)
@@ -480,10 +481,10 @@ namespace Swarmops.Logic.Communications
                             }
 
                             //insert span tags around %tag%, trying to avoid doing it twice.
-                            if (reTags.IsMatch(tn.InnerText) && !n.OuterHtml.Contains("placeholder2") &&
-                                !tn.OuterHtml.Contains("placeholder2"))
+                            if (reTags.IsMatch (tn.InnerText) && !n.OuterHtml.Contains ("placeholder2") &&
+                                !tn.OuterHtml.Contains ("placeholder2"))
                             {
-                                tn.InnerHtml = reTags.Replace(tn.InnerHtml, "$1");
+                                tn.InnerHtml = reTags.Replace (tn.InnerHtml, "$1");
                             }
                         }
                     }
@@ -493,83 +494,83 @@ namespace Swarmops.Logic.Communications
 
         public void RemovePlaceholderSpans()
         {
-            RemovePlaceholderSpans(HtmlDoc);
+            RemovePlaceholderSpans (HtmlDoc);
         }
 
-        public static void RemovePlaceholderSpans(HtmlDocument htDoc)
+        public static void RemovePlaceholderSpans (HtmlDocument htDoc)
         {
-            HtmlNodeCollection placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholder2']");
+            HtmlNodeCollection placeholder2Spans = htDoc.DocumentNode.SelectNodes ("//*[@class='placeholder2']");
             if (placeholder2Spans != null)
             {
                 foreach (HtmlNode n in placeholder2Spans)
                 {
-                    n.ParentNode.RemoveChild(n, true);
+                    n.ParentNode.RemoveChild (n, true);
                 }
             }
-            placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholderUnkn']");
+            placeholder2Spans = htDoc.DocumentNode.SelectNodes ("//*[@class='placeholderUnkn']");
             if (placeholder2Spans != null)
             {
                 foreach (HtmlNode n in placeholder2Spans)
                 {
-                    n.ParentNode.RemoveChild(n, true);
+                    n.ParentNode.RemoveChild (n, true);
                 }
             }
         }
 
-        public HtmlNode GetElementById(string id)
+        public HtmlNode GetElementById (string id)
         {
-            return HtmlDoc.DocumentNode.SelectSingleNode("//*[@id='" + id + "']");
+            return HtmlDoc.DocumentNode.SelectSingleNode ("//*[@id='" + id + "']");
         }
 
-        public HtmlNodeCollection GetElementsById(string id)
+        public HtmlNodeCollection GetElementsById (string id)
         {
-            return HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            return HtmlDoc.DocumentNode.SelectNodes ("//*[@id='" + id + "']");
         }
 
-        public void RemoveElementById(string id)
+        public void RemoveElementById (string id)
         {
-            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes ("//*[@id='" + id + "']");
             if (nodes != null)
                 foreach (HtmlNode node in nodes)
                 {
-                    node.ParentNode.RemoveChild(node);
+                    node.ParentNode.RemoveChild (node);
                 }
         }
 
-        public void RemoveEnclosingTag(string id)
+        public void RemoveEnclosingTag (string id)
         {
-            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes ("//*[@id='" + id + "']");
             if (nodes != null)
                 foreach (HtmlNode node in nodes)
                 {
-                    node.ParentNode.RemoveChild(node, true);
+                    node.ParentNode.RemoveChild (node, true);
                 }
         }
 
-        public bool ReplaceContentById(string id, string InnerHtml)
+        public bool ReplaceContentById (string id, string InnerHtml)
         {
-            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes ("//*[@id='" + id + "']");
             bool retval = false;
             if (nodes != null)
                 foreach (HtmlNode node in nodes)
                 {
                     node.InnerHtml = InnerHtml;
-                    node.ParentNode.RemoveChild(node, true);
+                    node.ParentNode.RemoveChild (node, true);
                     retval = true;
                 }
 
             return retval;
         }
 
-        public void ReplaceContentByPattern(string pattern, string InnerHtml)
+        public void ReplaceContentByPattern (string pattern, string InnerHtml)
         {
             // Replace pattern tags taking case into account.
-            Regex UpperPattern = new Regex("%" + pattern.ToUpper() + "%");
-            Regex LowerPattern = new Regex("%" + pattern.ToLower() + "%");
-            Regex JustPattern = new Regex("%" + pattern + "%", RegexOptions.IgnoreCase);
-            string content = UpperPattern.Replace(TemplateBody, InnerHtml.ToUpper());
-            content = LowerPattern.Replace(content, InnerHtml.ToLower());
-            TemplateBody = JustPattern.Replace(content, InnerHtml);
+            Regex UpperPattern = new Regex ("%" + pattern.ToUpper() + "%");
+            Regex LowerPattern = new Regex ("%" + pattern.ToLower() + "%");
+            Regex JustPattern = new Regex ("%" + pattern + "%", RegexOptions.IgnoreCase);
+            string content = UpperPattern.Replace (TemplateBody, InnerHtml.ToUpper());
+            content = LowerPattern.Replace (content, InnerHtml.ToLower());
+            TemplateBody = JustPattern.Replace (content, InnerHtml);
         }
 
         private HtmlNode TitleNode()
@@ -577,19 +578,19 @@ namespace Swarmops.Logic.Communications
             //Since NormalizeHtml is expensive try without first
             HtmlNode titlenode = null;
             if (HtmlDoc != null && HtmlDoc.DocumentNode != null)
-                titlenode = HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
+                titlenode = HtmlDoc.DocumentNode.SelectSingleNode ("//head/title");
 
             if (titlenode == null)
             {
                 NormalizeHtml();
-                titlenode = HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
+                titlenode = HtmlDoc.DocumentNode.SelectSingleNode ("//head/title");
                 if (titlenode == null)
                 {
                     return null;
                 }
             }
 
-            titlenode.InnerHtml = titlenode.InnerHtml.Replace("<", "<").Replace(">", ">");
+            titlenode.InnerHtml = titlenode.InnerHtml.Replace ("<", "<").Replace (">", ">");
             return titlenode;
         }
     }
diff --git a/Logic/Communications/NewsletterFeed.cs b/Logic/Communications/NewsletterFeed.cs
index 240dca62..d42c14f5 100644
--- a/Logic/Communications/NewsletterFeed.cs
+++ b/Logic/Communications/NewsletterFeed.cs
@@ -20,19 +20,19 @@ namespace Swarmops.Logic.Communications
 
         #region Creation and Construction
 
-        private NewsletterFeed(BasicNewsletterFeed basic)
-            : base(basic)
+        private NewsletterFeed (BasicNewsletterFeed basic)
+            : base (basic)
         {
         }
 
-        public static NewsletterFeed FromIdentity(int identity)
+        public static NewsletterFeed FromIdentity (int identity)
         {
-            return FromBasic(SwarmDb.GetDatabaseForReading().GetNewsletterFeed(identity));
+            return FromBasic (SwarmDb.GetDatabaseForReading().GetNewsletterFeed (identity));
         }
 
-        public static NewsletterFeed FromBasic(BasicNewsletterFeed basic)
+        public static NewsletterFeed FromBasic (BasicNewsletterFeed basic)
         {
-            return new NewsletterFeed(basic);
+            return new NewsletterFeed (basic);
         }
 
         #endregion
diff --git a/Logic/Communications/NewsletterFeeds.cs b/Logic/Communications/NewsletterFeeds.cs
index 92d53982..245f984f 100644
--- a/Logic/Communications/NewsletterFeeds.cs
+++ b/Logic/Communications/NewsletterFeeds.cs
@@ -5,20 +5,20 @@ namespace Swarmops.Logic.Communications
 {
     public class NewsletterFeeds : List
     {
-        public static NewsletterFeeds FromArray(BasicNewsletterFeed[] basicArray)
+        public static NewsletterFeeds FromArray (BasicNewsletterFeed[] basicArray)
         {
             NewsletterFeeds result = new NewsletterFeeds();
 
             result.Capacity = basicArray.Length*11/10;
             foreach (BasicNewsletterFeed basic in basicArray)
             {
-                result.Add(NewsletterFeed.FromBasic(basic));
+                result.Add (NewsletterFeed.FromBasic (basic));
             }
 
             return result;
         }
 
-        public NewsletterFeed Find(int newsletterFeedId)
+        public NewsletterFeed Find (int newsletterFeedId)
         {
             NewsletterFeed result = null;
             foreach (NewsletterFeed feed in this)
diff --git a/Logic/Communications/OutboundComm.cs b/Logic/Communications/OutboundComm.cs
index 7e8433ac..51c2a405 100644
--- a/Logic/Communications/OutboundComm.cs
+++ b/Logic/Communications/OutboundComm.cs
@@ -13,7 +13,7 @@ namespace Swarmops.Logic.Communications
 {
     public class OutboundComm : BasicOutboundComm
     {
-        private OutboundComm(BasicOutboundComm basic) : base(basic)
+        private OutboundComm (BasicOutboundComm basic) : base (basic)
         {
             // private ctor
         }
@@ -25,19 +25,19 @@ namespace Swarmops.Logic.Communications
             {
                 if (!base.Resolved && value)
                 {
-                    SwarmDb.GetDatabaseForWriting().SetOutboundCommResolved(Identity);
+                    SwarmDb.GetDatabaseForWriting().SetOutboundCommResolved (Identity);
                     base.Resolved = true;
                 }
                 else
                 {
-                    throw new InvalidOperationException("Can only set OutboundComms.Resolved from false to true");
+                    throw new InvalidOperationException ("Can only set OutboundComms.Resolved from false to true");
                 }
             }
         }
 
         public OutboundCommRecipients Recipients
         {
-            get { return OutboundCommRecipients.ForOutboundComm(this); }
+            get { return OutboundCommRecipients.ForOutboundComm (this); }
         }
 
         public new bool Open
@@ -47,32 +47,32 @@ namespace Swarmops.Logic.Communications
             {
                 if (base.Open && value == false)
                 {
-                    SwarmDb.GetDatabaseForWriting().SetOutboundCommClosed(Identity);
+                    SwarmDb.GetDatabaseForWriting().SetOutboundCommClosed (Identity);
                     base.Open = false;
                 }
                 else
                 {
-                    throw new InvalidOperationException("Can only change OutboundComms.Open from true to false");
+                    throw new InvalidOperationException ("Can only change OutboundComms.Open from true to false");
                 }
             }
         }
 
-        public static OutboundComm FromBasic(BasicOutboundComm basic)
+        public static OutboundComm FromBasic (BasicOutboundComm basic)
         {
-            return new OutboundComm(basic);
+            return new OutboundComm (basic);
         }
 
-        public static OutboundComm FromIdentity(int outboundCommId)
+        public static OutboundComm FromIdentity (int outboundCommId)
         {
-            return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundComm(outboundCommId));
+            return FromBasic (SwarmDb.GetDatabaseForReading().GetOutboundComm (outboundCommId));
         }
 
-        public static OutboundComm FromIdentityAggressive(int outboundCommId)
+        public static OutboundComm FromIdentityAggressive (int outboundCommId)
         {
-            return FromBasic(SwarmDb.GetDatabaseForWriting().GetOutboundComm(outboundCommId));
+            return FromBasic (SwarmDb.GetDatabaseForWriting().GetOutboundComm (outboundCommId));
         }
 
-        public static OutboundComm Create(Person sender, Person from, Organization organization,
+        public static OutboundComm Create (Person sender, Person from, Organization organization,
             CommResolverClass resolverClass, string recipientDataXml, CommTransmitterClass transmitterClass,
             string payloadXml, OutboundCommPriority priority)
         {
@@ -88,47 +88,47 @@ namespace Swarmops.Logic.Communications
                 transmitterClassString = "Swarmops.Utility.Communications." + transmitterClass;
             }
 
-            return Create(sender, from, organization, resolverClassString, recipientDataXml, transmitterClassString,
+            return Create (sender, from, organization, resolverClassString, recipientDataXml, transmitterClassString,
                 payloadXml, priority);
         }
 
-        public static OutboundComm Create(Person sender, Person from, Organization organization,
+        public static OutboundComm Create (Person sender, Person from, Organization organization,
             string resolverClassString, string recipientDataXml, string transmitterClassString, string payloadXml,
             OutboundCommPriority priority)
         {
             int newId = SwarmDb.GetDatabaseForWriting()
-                .CreateOutboundComm(sender != null ? sender.Identity : 0, from != null ? from.Identity : 0,
+                .CreateOutboundComm (sender != null ? sender.Identity : 0, from != null ? from.Identity : 0,
                     organization != null ? organization.Identity : 0, resolverClassString,
                     recipientDataXml ?? string.Empty, transmitterClassString,
                     payloadXml, priority);
 
-            return FromIdentityAggressive(newId);
+            return FromIdentityAggressive (newId);
         }
 
 
-        public static OutboundComm CreateNotification(Organization organization, NotificationResource notification)
+        public static OutboundComm CreateNotification (Organization organization, NotificationResource notification)
         {
-            return CreateNotification(organization, notification.ToString());
+            return CreateNotification (organization, notification.ToString());
         }
 
 
-        public static OutboundComm CreateNotification(Organization organization, string notificationResourceString)
+        public static OutboundComm CreateNotification (Organization organization, string notificationResourceString)
         {
-            List recipients = People.FromSingle(Person.FromIdentity(1)); // Initial Admin recipient
+            List recipients = People.FromSingle (Person.FromIdentity (1)); // Initial Admin recipient
 
             if (organization != null)
             {
                 // TODO: Change to org admins
             }
 
-            OutboundComm comm = OutboundComm.Create(null, null, organization, CommResolverClass.Unknown, null,
+            OutboundComm comm = OutboundComm.Create (null, null, organization, CommResolverClass.Unknown, null,
                 CommTransmitterClass.CommsTransmitterMail,
-                new PayloadEnvelope(new NotificationPayload(notificationResourceString)).ToXml(),
+                new PayloadEnvelope (new NotificationPayload (notificationResourceString)).ToXml(),
                 OutboundCommPriority.Low);
 
             foreach (Person person in recipients)
             {
-                comm.AddRecipient(person);
+                comm.AddRecipient (person);
             }
 
             comm.Resolved = true;
@@ -137,32 +137,33 @@ namespace Swarmops.Logic.Communications
         }
 
 
-        public static OutboundComm CreateNotificationAttestationNeeded(FinancialAccount budget, Person concernedPerson,
+        public static OutboundComm CreateNotificationAttestationNeeded (FinancialAccount budget, Person concernedPerson,
             string supplier, double amountRequested, string purpose, NotificationResource notification)
         {
-            NotificationPayload payload = new NotificationPayload(notification.ToString());
+            NotificationPayload payload = new NotificationPayload (notification.ToString());
             payload.Strings[NotificationString.CurrencyCode] = budget.Organization.Currency.DisplayCode;
             payload.Strings[NotificationString.OrganizationName] = budget.Organization.Name;
             payload.Strings[NotificationString.BudgetAmountFloat] =
-                amountRequested.ToString(CultureInfo.InvariantCulture);
+                amountRequested.ToString (CultureInfo.InvariantCulture);
             payload.Strings[NotificationString.RequestPurpose] = purpose;
             payload.Strings[NotificationString.Description] = purpose;
             payload.Strings[NotificationString.Supplier] = supplier;
             payload.Strings[NotificationString.BudgetName] = budget.Name;
             payload.Strings[NotificationString.ConcernedPersonName] = concernedPerson.Canonical;
 
-            OutboundComm comm = OutboundComm.Create(null, null, budget.Organization, CommResolverClass.Unknown, null,
+            OutboundComm comm = OutboundComm.Create (null, null, budget.Organization, CommResolverClass.Unknown, null,
                 CommTransmitterClass.CommsTransmitterMail,
-                new PayloadEnvelope(payload).ToXml(),
+                new PayloadEnvelope (payload).ToXml(),
                 OutboundCommPriority.Low);
 
             if (budget.OwnerPersonId == 0)
             {
-                comm.AddRecipient(Person.FromIdentity(1)); // Add admin - not good, should be org admins // HACK // TODO
+                comm.AddRecipient (Person.FromIdentity (1));
+                    // Add admin - not good, should be org admins // HACK // TODO
             }
             else
             {
-                comm.AddRecipient(budget.Owner);
+                comm.AddRecipient (budget.Owner);
             }
 
             comm.Resolved = true;
@@ -171,25 +172,25 @@ namespace Swarmops.Logic.Communications
         }
 
 
-        public static OutboundComm CreateNotificationFinancialValidationNeeded(Organization organization,
+        public static OutboundComm CreateNotificationFinancialValidationNeeded (Organization organization,
             double amountRequested, NotificationResource notification)
         {
-            NotificationPayload payload = new NotificationPayload(notification.ToString());
+            NotificationPayload payload = new NotificationPayload (notification.ToString());
             payload.Strings[NotificationString.CurrencyCode] = organization.Currency.DisplayCode;
             payload.Strings[NotificationString.OrganizationName] = organization.Name;
             payload.Strings[NotificationString.BudgetAmountFloat] =
-                amountRequested.ToString(CultureInfo.InvariantCulture);
+                amountRequested.ToString (CultureInfo.InvariantCulture);
 
-            OutboundComm comm = OutboundComm.Create(null, null, organization, CommResolverClass.Unknown, null,
+            OutboundComm comm = OutboundComm.Create (null, null, organization, CommResolverClass.Unknown, null,
                 CommTransmitterClass.CommsTransmitterMail,
-                new PayloadEnvelope(payload).ToXml(),
+                new PayloadEnvelope (payload).ToXml(),
                 OutboundCommPriority.Low);
 
             People validators = organization.ValidatingPeople;
 
             foreach (Person validator in validators)
             {
-                comm.AddRecipient(validator);
+                comm.AddRecipient (validator);
             }
 
             comm.Resolved = true;
@@ -198,24 +199,24 @@ namespace Swarmops.Logic.Communications
         }
 
 
-        public static OutboundComm CreateNotificationOfFinancialValidation(FinancialAccount budget,
+        public static OutboundComm CreateNotificationOfFinancialValidation (FinancialAccount budget,
             Person concernedPerson, double amountRequested, string purpose, NotificationResource notification)
         {
-            NotificationPayload payload = new NotificationPayload(notification.ToString());
+            NotificationPayload payload = new NotificationPayload (notification.ToString());
             payload.Strings[NotificationString.CurrencyCode] = budget.Organization.Currency.DisplayCode;
             payload.Strings[NotificationString.OrganizationName] = budget.Organization.Name;
             payload.Strings[NotificationString.BudgetAmountFloat] =
-                amountRequested.ToString(CultureInfo.InvariantCulture);
+                amountRequested.ToString (CultureInfo.InvariantCulture);
             payload.Strings[NotificationString.RequestPurpose] = purpose;
             payload.Strings[NotificationString.BudgetName] = budget.Name;
             payload.Strings[NotificationString.ConcernedPersonName] = concernedPerson.Canonical;
 
-            OutboundComm comm = OutboundComm.Create(null, null, budget.Organization, CommResolverClass.Unknown, null,
+            OutboundComm comm = OutboundComm.Create (null, null, budget.Organization, CommResolverClass.Unknown, null,
                 CommTransmitterClass.CommsTransmitterMail,
-                new PayloadEnvelope(payload).ToXml(),
+                new PayloadEnvelope (payload).ToXml(),
                 OutboundCommPriority.Low);
 
-            comm.AddRecipient(concernedPerson);
+            comm.AddRecipient (concernedPerson);
 
             comm.Resolved = true;
 
@@ -223,19 +224,19 @@ namespace Swarmops.Logic.Communications
         }
 
 
-        public void AddRecipient(Person person)
+        public void AddRecipient (Person person)
         {
             if (person == null)
             {
-                throw new ArgumentNullException("Recipient cannot be null.");
+                throw new ArgumentNullException ("Recipient cannot be null.");
             }
 
-            SwarmDb.GetDatabaseForWriting().CreateOutboundCommRecipient(Identity, person.Identity);
+            SwarmDb.GetDatabaseForWriting().CreateOutboundCommRecipient (Identity, person.Identity);
         }
 
         public void StartTransmission()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommTransmissionStart(Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommTransmissionStart (Identity);
         }
     }
 
diff --git a/Logic/Communications/OutboundCommRecipient.cs b/Logic/Communications/OutboundCommRecipient.cs
index de98f6e8..36a47d6e 100644
--- a/Logic/Communications/OutboundCommRecipient.cs
+++ b/Logic/Communications/OutboundCommRecipient.cs
@@ -6,32 +6,32 @@ namespace Swarmops.Logic.Communications
 {
     public class OutboundCommRecipient : BasicOutboundCommRecipient
     {
-        private OutboundCommRecipient(BasicOutboundCommRecipient basic) : base(basic)
+        private OutboundCommRecipient (BasicOutboundCommRecipient basic) : base (basic)
         {
             // private ctor
         }
 
         public Person Person
         {
-            get { return Person.FromIdentity(base.PersonId); }
+            get { return Person.FromIdentity (base.PersonId); }
         }
 
-        public static OutboundCommRecipient FromBasic(BasicOutboundCommRecipient basic)
+        public static OutboundCommRecipient FromBasic (BasicOutboundCommRecipient basic)
         {
-            return new OutboundCommRecipient(basic);
+            return new OutboundCommRecipient (basic);
         }
 
         public void CloseSuccess()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientClosed(Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientClosed (Identity);
 
             base.Success = true;
             base.Open = false;
         }
 
-        public void CloseFailed(string failReason)
+        public void CloseFailed (string failReason)
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientFailed(Identity, failReason);
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientFailed (Identity, failReason);
 
             base.Success = false;
             base.Open = false;
diff --git a/Logic/Communications/OutboundCommRecipients.cs b/Logic/Communications/OutboundCommRecipients.cs
index 5d19eda6..4c954c9d 100644
--- a/Logic/Communications/OutboundCommRecipients.cs
+++ b/Logic/Communications/OutboundCommRecipients.cs
@@ -7,9 +7,9 @@ namespace Swarmops.Logic.Communications
     public class OutboundCommRecipients :
         PluralBase
     {
-        public static OutboundCommRecipients ForOutboundComm(OutboundComm comm)
+        public static OutboundCommRecipients ForOutboundComm (OutboundComm comm)
         {
-            return FromArray(SwarmDb.GetDatabaseForReading().GetOutboundCommRecipients(comm));
+            return FromArray (SwarmDb.GetDatabaseForReading().GetOutboundCommRecipients (comm));
         }
     }
 }
\ No newline at end of file
diff --git a/Logic/Communications/OutboundCommTransmitException.cs b/Logic/Communications/OutboundCommTransmitException.cs
index fff06e74..9031a997 100644
--- a/Logic/Communications/OutboundCommTransmitException.cs
+++ b/Logic/Communications/OutboundCommTransmitException.cs
@@ -8,13 +8,13 @@ namespace Swarmops.Logic.Communications
     /// 
     public class OutboundCommTransmitException : Exception
     {
-        public OutboundCommTransmitException(string description) : base(description)
+        public OutboundCommTransmitException (string description) : base (description)
         {
             Description = description;
         }
 
-        public OutboundCommTransmitException(string description, Exception innerException)
-            : base(description, innerException)
+        public OutboundCommTransmitException (string description, Exception innerException)
+            : base (description, innerException)
         {
             Description = description;
         }
diff --git a/Logic/Communications/OutboundComms.cs b/Logic/Communications/OutboundComms.cs
index c98e03f3..f15d6cce 100644
--- a/Logic/Communications/OutboundComms.cs
+++ b/Logic/Communications/OutboundComms.cs
@@ -8,7 +8,7 @@ namespace Swarmops.Logic.Communications
     {
         public static OutboundComms GetOpen()
         {
-            return FromArray(SwarmDb.GetDatabaseForReading().GetOutboundComms(DatabaseCondition.OpenTrue));
+            return FromArray (SwarmDb.GetDatabaseForReading().GetOutboundComms (DatabaseCondition.OpenTrue));
         }
     }
 }
\ No newline at end of file
diff --git a/Logic/Communications/OutboundMail.cs b/Logic/Communications/OutboundMail.cs
index 8f65870a..b6068889 100644
--- a/Logic/Communications/OutboundMail.cs
+++ b/Logic/Communications/OutboundMail.cs
@@ -23,8 +23,8 @@ namespace Swarmops.Logic.Communications
         /// 
         ///     Private constructor from basic object
         /// 
-        private OutboundMail(BasicOutboundMail basic)
-            : base(basic)
+        private OutboundMail (BasicOutboundMail basic)
+            : base (basic)
         {
             // remember titel for templated mail, it is the name of the template.
             if (MailType > 0)
@@ -34,14 +34,14 @@ namespace Swarmops.Logic.Communications
         /// 
         ///     Creation from basic object - internal to PirateWeb.Logic
         /// 
-        internal static OutboundMail FromBasic(BasicOutboundMail basic)
+        internal static OutboundMail FromBasic (BasicOutboundMail basic)
         {
             if (basic == null)
             {
                 return null;
             }
 
-            return new OutboundMail(basic);
+            return new OutboundMail (basic);
         }
 
 
@@ -50,27 +50,27 @@ namespace Swarmops.Logic.Communications
         /// 
         /// The Identity of the OutboundMail
         /// An OutboundMail from the database
-        public static OutboundMail FromIdentity(int outboundMailId)
+        public static OutboundMail FromIdentity (int outboundMailId)
         {
-            return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundMail(outboundMailId));
+            return FromBasic (SwarmDb.GetDatabaseForReading().GetOutboundMail (outboundMailId));
         }
 
 
-        public static OutboundMail Create(Person author, string title,
+        public static OutboundMail Create (Person author, string title,
             string body, int mailPriority, int mailType,
             Organization organization, Geography geography)
         {
-            return Create(author, title, body, mailPriority, mailType, organization,
+            return Create (author, title, body, mailPriority, mailType, organization,
                 geography, DateTime.Now);
         }
 
-        public static OutboundMail Create(Person author, string title,
+        public static OutboundMail Create (Person author, string title,
             string body, int mailPriority, int mailType,
             Organization organization, Geography geography, DateTime releaseDateTime)
         {
             return
-                FromIdentity(SwarmDb.GetDatabaseForWriting()
-                    .CreateOutboundMail(MailAuthorType.Person, author.Identity, title,
+                FromIdentity (SwarmDb.GetDatabaseForWriting()
+                    .CreateOutboundMail (MailAuthorType.Person, author.Identity, title,
                         body, mailPriority, mailType,
                         geography.Identity, organization.Identity,
                         releaseDateTime));
@@ -81,22 +81,22 @@ namespace Swarmops.Logic.Communications
         ///     Creates an unusable OutboundMail. Used for rendering previews - ONLY.
         ///     (this version, with the ignored priority param is for backward compability)
         /// 
-        public static OutboundMail CreateFake(Person author, string title, string body, int ignoredPriority,
+        public static OutboundMail CreateFake (Person author, string title, string body, int ignoredPriority,
             int mailType,
             Organization organization, Geography geography)
         {
-            return CreateFake(author, title, body, mailType, organization, geography);
+            return CreateFake (author, title, body, mailType, organization, geography);
         }
 
 
         /// 
         ///     Creates an unusable OutboundMail. Used for rendering previews - ONLY.
         /// 
-        public static OutboundMail CreateFake(Person author, string title,
+        public static OutboundMail CreateFake (Person author, string title,
             string body, int mailType,
             Organization organization, Geography geography)
         {
-            return FromBasic(new BasicOutboundMail(0, MailAuthorType.Person, author.PersonId, title,
+            return FromBasic (new BasicOutboundMail (0, MailAuthorType.Person, author.PersonId, title,
                 body, 99, mailType, organization.Identity,
                 geography.Identity, DateTime.Now,
                 DateTime.Now, false, false, false, DateTime.MinValue,
@@ -106,30 +106,30 @@ namespace Swarmops.Logic.Communications
         /// 
         ///     Creates an OutboundMail with a "functional" author.
         /// 
-        public static OutboundMail CreateFunctional(MailAuthorType authorType, string title,
+        public static OutboundMail CreateFunctional (MailAuthorType authorType, string title,
             string body, int mailPriority, int mailType,
             int organizationId, int geographyId, DateTime releaseDateTime)
         {
-            int mailID = SwarmDb.GetDatabaseForWriting().CreateOutboundMail(authorType, 0, title,
+            int mailID = SwarmDb.GetDatabaseForWriting().CreateOutboundMail (authorType, 0, title,
                 body, mailPriority, mailType, geographyId,
                 organizationId, releaseDateTime);
 
             //Constructing instead of reading back from DB, saves time but..., Don't know if it is a good idea./JL
-            return FromBasic(new BasicOutboundMail(mailID, authorType, 0, title,
+            return FromBasic (new BasicOutboundMail (mailID, authorType, 0, title,
                 body, mailPriority, mailType, organizationId,
                 geographyId, DateTime.Now,
                 releaseDateTime));
         }
 
-        public List GetDuplicates(DateTime afterTime, int recipientId)
+        public List GetDuplicates (DateTime afterTime, int recipientId)
         {
             List retList = new List();
             BasicOutboundMail[] mails
-                = SwarmDb.GetDatabaseForReading().GetDuplicateOutboundMail(AuthorType, AuthorPersonId, Title,
+                = SwarmDb.GetDatabaseForReading().GetDuplicateOutboundMail (AuthorType, AuthorPersonId, Title,
                     Body, MailPriority, MailType, GeographyId, OrganizationId, afterTime, recipientId);
             foreach (BasicOutboundMail mail in mails)
             {
-                retList.Add(FromBasic(mail));
+                retList.Add (FromBasic (mail));
             }
 
             return retList;
@@ -138,11 +138,11 @@ namespace Swarmops.Logic.Communications
 
         public static OutboundMail GetFirstUnresolved()
         {
-            BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnresolvedOutboundMail(1);
+            BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnresolvedOutboundMail (1);
 
             if (mails.Length > 0)
             {
-                return FromBasic(mails[0]);
+                return FromBasic (mails[0]);
             }
 
             return null;
@@ -150,11 +150,11 @@ namespace Swarmops.Logic.Communications
 
         public static OutboundMail GetFirstUnprocessed()
         {
-            BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnprocessedOutboundMail(1);
+            BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnprocessedOutboundMail (1);
 
             if (mails.Length > 0)
             {
-                return FromBasic(mails[0]);
+                return FromBasic (mails[0]);
             }
 
             return null;
@@ -169,7 +169,7 @@ namespace Swarmops.Logic.Communications
             get { return base.StartProcessDateTime; }
             set
             {
-                SwarmDb.GetDatabaseForWriting().SetOutboundMailStartProcess(Identity);
+                SwarmDb.GetDatabaseForWriting().SetOutboundMailStartProcess (Identity);
                 base.StartProcessDateTime = DateTime.Now;
             }
         }
@@ -180,13 +180,13 @@ namespace Swarmops.Logic.Communications
             {
                 if (AuthorType != MailAuthorType.Person)
                 {
-                    throw new InvalidOperationException(
+                    throw new InvalidOperationException (
                         "OutboundMail.Author is not a valid property when OutboundMail.AuthorType isn't MailAuthorType.Person.");
                 }
 
                 if (this.author == null)
                 {
-                    this.author = Person.FromIdentity(AuthorPersonId);
+                    this.author = Person.FromIdentity (AuthorPersonId);
                 }
 
                 return this.author;
@@ -199,7 +199,7 @@ namespace Swarmops.Logic.Communications
             {
                 if (this.organization == null)
                 {
-                    this.organization = Organization.FromIdentity(OrganizationId);
+                    this.organization = Organization.FromIdentity (OrganizationId);
                 }
 
                 return this.organization;
@@ -212,7 +212,7 @@ namespace Swarmops.Logic.Communications
             {
                 if (this.geography == null)
                 {
-                    this.geography = Geography.FromIdentity(GeographyId);
+                    this.geography = Geography.FromIdentity (GeographyId);
                 }
 
                 return this.geography;
@@ -228,50 +228,50 @@ namespace Swarmops.Logic.Communications
 
         #region Recipient access and manipulation
 
-        public OutboundMailRecipients GetNextRecipientBatch(int batchSize)
+        public OutboundMailRecipients GetNextRecipientBatch (int batchSize)
         {
             return
-                OutboundMailRecipients.FromArray(
-                    SwarmDb.GetDatabaseForReading().GetTopOutboundMailRecipients(Identity, batchSize), this);
+                OutboundMailRecipients.FromArray (
+                    SwarmDb.GetDatabaseForReading().GetTopOutboundMailRecipients (Identity, batchSize), this);
         }
 
-        public void AddRecipient(Person person, bool asOfficer)
+        public void AddRecipient (Person person, bool asOfficer)
         {
-            AddRecipient(person.Identity, asOfficer);
+            AddRecipient (person.Identity, asOfficer);
         }
 
-        public void AddRecipient(Reporter person)
+        public void AddRecipient (Reporter person)
         {
-            AddReporterRecipient(person.Identity);
+            AddReporterRecipient (person.Identity);
         }
 
-        public void AddRecipients(int[] personIds, bool asOfficers)
+        public void AddRecipients (int[] personIds, bool asOfficers)
         {
             foreach (int personId in personIds)
             {
-                AddRecipient(personId, asOfficers);
+                AddRecipient (personId, asOfficers);
             }
         }
 
-        public void AddReporterRecipients(int[] personIds)
+        public void AddReporterRecipients (int[] personIds)
         {
             foreach (int personId in personIds)
             {
-                AddReporterRecipient(personId);
+                AddReporterRecipient (personId);
             }
         }
 
-        public void AddRecipient(int personId, bool asOfficer)
+        public void AddRecipient (int personId, bool asOfficer)
         {
             SwarmDb.GetDatabaseForWriting()
-                .CreateOutboundMailRecipient(Identity, personId, asOfficer,
+                .CreateOutboundMailRecipient (Identity, personId, asOfficer,
                     (int) OutboundMailRecipient.RecipientType.Person);
         }
 
-        private void AddReporterRecipient(int identity)
+        private void AddReporterRecipient (int identity)
         {
             SwarmDb.GetDatabaseForWriting()
-                .CreateOutboundMailRecipient(Identity, identity, false,
+                .CreateOutboundMailRecipient (Identity, identity, false,
                     (int) OutboundMailRecipient.RecipientType.Reporter);
         }
 
@@ -281,37 +281,37 @@ namespace Swarmops.Logic.Communications
 
         public void SetReadyForPickup()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup(Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup (Identity);
             base.ReadyForPickup = true;
         }
 
         public void SetResolved()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved(Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved (Identity);
             base.Resolved = true;
         }
 
         public void SetProcessed()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundMailProcessed(Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundMailProcessed (Identity);
             base.Processed = true;
         }
 
-        public void SetRecipientCount(int recipientCount)
+        public void SetRecipientCount (int recipientCount)
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount(Identity, recipientCount);
+            SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount (Identity, recipientCount);
             base.RecipientCount = recipientCount;
         }
 
         public void IncrementSuccesses()
         {
-            SwarmDb.GetDatabaseForWriting().IncrementOutboundMailSuccesses(Identity);
+            SwarmDb.GetDatabaseForWriting().IncrementOutboundMailSuccesses (Identity);
             base.RecipientsSuccess++;
         }
 
         public void IncrementFailures()
         {
-            SwarmDb.GetDatabaseForWriting().IncrementOutboundMailFailures(Identity);
+            SwarmDb.GetDatabaseForWriting().IncrementOutboundMailFailures (Identity);
             base.RecipientsFail++;
         }
 
@@ -324,7 +324,7 @@ namespace Swarmops.Logic.Communications
         /// 
         /// The person to render for.
         /// Text with proper replacements done
-        public string RenderText(IEmailPerson recipient, string culture)
+        public string RenderText (IEmailPerson recipient, string culture)
         {
             // First, check if there is a mail template AT ALL. If not, return the raw text.
             if (MailType == (int) TypedMailTemplate.TemplateType.None)
@@ -333,7 +333,7 @@ namespace Swarmops.Logic.Communications
             }
 
             // (If there is a template, the body contains the serialized placeholder values)
-            return Render(recipient, culture, true).PlainText;
+            return Render (recipient, culture, true).PlainText;
         }
 
 
@@ -342,22 +342,22 @@ namespace Swarmops.Logic.Communications
         /// 
         /// The person to render for.
         /// HTML with proper replacements done
-        public string RenderHtml(IEmailPerson recipient, string culture)
+        public string RenderHtml (IEmailPerson recipient, string culture)
         {
             // First, check if there is a mail template AT ALL. If not, return the raw text,
             // within 
 if not already html
 
             if (MailType == (int) TypedMailTemplate.TemplateType.None)
             {
-                Regex reHtmlType = new Regex(@"()", RegexOptions.IgnoreCase);
+                Regex reHtmlType = new Regex (@"()", RegexOptions.IgnoreCase);
 
-                if (reHtmlType.IsMatch(Body))
+                if (reHtmlType.IsMatch (Body))
                     return Body;
                 return "
" + Body + "
"; } // (If there is a template, the body contains the serialized placeholder values) - return Render(recipient, culture, false).Html; + return Render (recipient, culture, false).Html; } /// @@ -367,23 +367,23 @@ namespace Swarmops.Logic.Communications /// The culture to render for. /// True if "Plain" template should be used (if available) /// MailTemplate with proper replacements done - public MailTemplate Render(IEmailPerson recipient, string culture, bool renderText) + public MailTemplate Render (IEmailPerson recipient, string culture, bool renderText) { lock (lockTemplates) { //Locking is needed since this is used in a multithreading scenario and the template is cached for efficiency - TypedMailTemplate template = PrepareTemplate(culture, renderText); - // Setup template and load serialized replacements - template.FillIndividualPlaceholders(recipient); // Add recipient data + TypedMailTemplate template = PrepareTemplate (culture, renderText); + // Setup template and load serialized replacements + template.FillIndividualPlaceholders (recipient); // Add recipient data template.InsertAllPlaceHoldersToTemplate(); // Make all replacements Title = template.Template.TemplateTitleText; // Get the resulting title template.Template.TemplateBody = template.Template.TemplateBody; // Force it to save Html - return new MailTemplate(template.Template); + return new MailTemplate (template.Template); } } - private TypedMailTemplate PrepareTemplate(string culture, bool renderText) + private TypedMailTemplate PrepareTemplate (string culture, bool renderText) { TypedMailTemplate template = null; if (renderText) @@ -391,8 +391,8 @@ namespace Swarmops.Logic.Communications if (this.templatePlain == null) { this.templatePlain = - TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType(MailType) + "Plain"); - this.templatePlain.Initialize(culture.Substring(3), Organization.Identity, this, + TypedMailTemplate.FromName (TypedMailTemplate.GetNameFromMailType (MailType) + "Plain"); + this.templatePlain.Initialize (culture.Substring (3), Organization.Identity, this, (renderText ? "Plain" : "")); this.templatePlain.PreparePlaceholders(); } @@ -407,8 +407,8 @@ namespace Swarmops.Logic.Communications { if (this.templateHtml == null) { - this.templateHtml = TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType(MailType)); - this.templateHtml.Initialize(culture.Substring(3), Organization.Identity, this, + this.templateHtml = TypedMailTemplate.FromName (TypedMailTemplate.GetNameFromMailType (MailType)); + this.templateHtml.Initialize (culture.Substring (3), Organization.Identity, this, (renderText ? "Plain" : "")); this.templateHtml.PreparePlaceholders(); } diff --git a/Logic/Communications/OutboundMailRecipient.cs b/Logic/Communications/OutboundMailRecipient.cs index bd151f1d..4d8d8338 100644 --- a/Logic/Communications/OutboundMailRecipient.cs +++ b/Logic/Communications/OutboundMailRecipient.cs @@ -18,13 +18,13 @@ namespace Swarmops.Logic.Communications private IEmailPerson person; private OutboundMailRecipient() - : base(null) + : base (null) { // Never construct this way } - private OutboundMailRecipient(BasicOutboundMailRecipient basic, OutboundMail outboundMail) - : base(basic) + private OutboundMailRecipient (BasicOutboundMailRecipient basic, OutboundMail outboundMail) + : base (basic) { this.outboundMail = outboundMail; } @@ -88,38 +88,39 @@ namespace Swarmops.Logic.Communications RecipientType type = (RecipientType) base.PersonType; if (type == RecipientType.Person) { - this.person = Person.FromIdentity(base.PersonId); + this.person = Person.FromIdentity (base.PersonId); } else if (type == RecipientType.Reporter) { - this.person = Reporter.FromIdentity(base.PersonId); + this.person = Reporter.FromIdentity (base.PersonId); } } } - internal static OutboundMailRecipient FromBasic(BasicOutboundMailRecipient basic, OutboundMail outboundMail) + internal static OutboundMailRecipient FromBasic (BasicOutboundMailRecipient basic, OutboundMail outboundMail) { - return new OutboundMailRecipient(basic, outboundMail); + return new OutboundMailRecipient (basic, outboundMail); } - public static void Create(OutboundMail outboundMail, Person person, bool asOfficer) + public static void Create (OutboundMail outboundMail, Person person, bool asOfficer) { - Create(outboundMail.Identity, person.Identity, asOfficer, (int) RecipientType.Person); + Create (outboundMail.Identity, person.Identity, asOfficer, (int) RecipientType.Person); } - public static void Create(OutboundMail outboundMail, Reporter person, bool asOfficer) + public static void Create (OutboundMail outboundMail, Reporter person, bool asOfficer) { - Create(outboundMail.Identity, person.Identity, asOfficer, (int) RecipientType.Reporter); + Create (outboundMail.Identity, person.Identity, asOfficer, (int) RecipientType.Reporter); } - public static void Create(int outboundMailId, int personId, bool asOfficer, int personType) + public static void Create (int outboundMailId, int personId, bool asOfficer, int personType) { - SwarmDb.GetDatabaseForWriting().CreateOutboundMailRecipient(outboundMailId, personId, asOfficer, personType); + SwarmDb.GetDatabaseForWriting() + .CreateOutboundMailRecipient (outboundMailId, personId, asOfficer, personType); } public void Delete() { - SwarmDb.GetDatabaseForWriting().DeleteOutboundMailRecipient(Identity); + SwarmDb.GetDatabaseForWriting().DeleteOutboundMailRecipient (Identity); } } } \ No newline at end of file diff --git a/Logic/Communications/OutboundMailRecipients.cs b/Logic/Communications/OutboundMailRecipients.cs index fe45b416..5035eaf7 100644 --- a/Logic/Communications/OutboundMailRecipients.cs +++ b/Logic/Communications/OutboundMailRecipients.cs @@ -5,14 +5,14 @@ namespace Swarmops.Logic.Communications { public class OutboundMailRecipients : List { - public static OutboundMailRecipients FromArray(BasicOutboundMailRecipient[] basicArray, OutboundMail mail) + public static OutboundMailRecipients FromArray (BasicOutboundMailRecipient[] basicArray, OutboundMail mail) { OutboundMailRecipients result = new OutboundMailRecipients(); result.Capacity = basicArray.Length*11/10; foreach (BasicOutboundMailRecipient basic in basicArray) { - result.Add(OutboundMailRecipient.FromBasic(basic, mail)); + result.Add (OutboundMailRecipient.FromBasic (basic, mail)); } return result; diff --git a/Logic/Communications/OutboundMails.cs b/Logic/Communications/OutboundMails.cs index ba5b59d8..a1854ed5 100644 --- a/Logic/Communications/OutboundMails.cs +++ b/Logic/Communications/OutboundMails.cs @@ -6,25 +6,25 @@ namespace Swarmops.Logic.Communications { public class OutboundMails : List { - public static OutboundMails FromArray(BasicOutboundMail[] basicArray) + public static OutboundMails FromArray (BasicOutboundMail[] basicArray) { OutboundMails result = new OutboundMails(); result.Capacity = basicArray.Length*11/10; foreach (BasicOutboundMail basic in basicArray) { - result.Add(OutboundMail.FromBasic(basic)); + result.Add (OutboundMail.FromBasic (basic)); } return result; } - public static OutboundMails GetTopUnprocessed(int count) + public static OutboundMails GetTopUnprocessed (int count) { - BasicOutboundMail[] basicMails = SwarmDb.GetDatabaseForReading().GetTopUnprocessedOutboundMail(count); + BasicOutboundMail[] basicMails = SwarmDb.GetDatabaseForReading().GetTopUnprocessedOutboundMail (count); - return FromArray(basicMails); + return FromArray (basicMails); } } } \ No newline at end of file diff --git a/Logic/Communications/PaperLetter.cs b/Logic/Communications/PaperLetter.cs index fab2d1ad..fb27ba13 100644 --- a/Logic/Communications/PaperLetter.cs +++ b/Logic/Communications/PaperLetter.cs @@ -10,41 +10,41 @@ namespace Swarmops.Logic.Communications { public class PaperLetter : BasicPaperLetter { - public static PaperLetter Create(Person creator, Organization organization, string fromName, + public static PaperLetter Create (Person creator, Organization organization, string fromName, string[] replyAddressLines, DateTime receivedDate, Person recipient, RoleType recipientRole, bool personal) { - return Create(creator.Identity, organization.Identity, fromName, replyAddressLines, receivedDate, + return Create (creator.Identity, organization.Identity, fromName, replyAddressLines, receivedDate, recipient.Identity, recipientRole, personal); } - public static PaperLetter Create(int creatingPersonId, int organizationId, string fromName, + public static PaperLetter Create (int creatingPersonId, int organizationId, string fromName, string[] replyAddressLines, DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal) { - return FromIdentity(SwarmDb.GetDatabaseForWriting(). - CreatePaperLetter(organizationId, fromName, String.Join("|", replyAddressLines), + return FromIdentity (SwarmDb.GetDatabaseForWriting(). + CreatePaperLetter (organizationId, fromName, String.Join ("|", replyAddressLines), receivedDate, toPersonId, toPersonInRole, personal, creatingPersonId)); } - public static PaperLetter FromIdentity(int paperLetterId) + public static PaperLetter FromIdentity (int paperLetterId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPaperLetter(paperLetterId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPaperLetter (paperLetterId)); } - public static PaperLetter FromBasic(BasicPaperLetter basic) + public static PaperLetter FromBasic (BasicPaperLetter basic) { - return new PaperLetter(basic); + return new PaperLetter (basic); } - private PaperLetter(BasicPaperLetter basic) : base(basic) + private PaperLetter (BasicPaperLetter basic) : base (basic) { // empty private constructor } public Documents Documents { - get { return Documents.ForObject(this); } + get { return Documents.ForObject (this); } } #pragma warning disable 169 @@ -55,7 +55,7 @@ namespace Swarmops.Logic.Communications public string[] ReplyAddressLines { - get { return base.ReplyAddress.Split('|'); } + get { return base.ReplyAddress.Split ('|'); } } public Person Recipient @@ -67,7 +67,7 @@ namespace Swarmops.Logic.Communications return null; } - return Person.FromIdentity(base.ToPersonId); + return Person.FromIdentity (base.ToPersonId); } } } diff --git a/Logic/Communications/PaperLetters.cs b/Logic/Communications/PaperLetters.cs index b179a98d..641713f7 100644 --- a/Logic/Communications/PaperLetters.cs +++ b/Logic/Communications/PaperLetters.cs @@ -8,7 +8,7 @@ namespace Swarmops.Logic.Communications { public class PaperLetters : List { - internal static PaperLetters FromArray(BasicPaperLetter[] basicArray) + internal static PaperLetters FromArray (BasicPaperLetter[] basicArray) { // TODO: This function exists in too many places. It's GOT to be possible to make it generic, // through an interface or something like that. @@ -17,30 +17,30 @@ namespace Swarmops.Logic.Communications foreach (BasicPaperLetter basic in basicArray) { - result.Add(PaperLetter.FromBasic(basic)); + result.Add (PaperLetter.FromBasic (basic)); } return result; } - public static PaperLetters ForOrganization(Organization organization) + public static PaperLetters ForOrganization (Organization organization) { - return ForOrganization(organization.Identity); + return ForOrganization (organization.Identity); } - public static PaperLetters ForOrganization(int organizationId) + public static PaperLetters ForOrganization (int organizationId) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPaperLettersForOrganization(organizationId)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPaperLettersForOrganization (organizationId)); } - public static PaperLetters ForPerson(Person person) + public static PaperLetters ForPerson (Person person) { - return ForPerson(person.Identity); + return ForPerson (person.Identity); } - public static PaperLetters ForPerson(int personId) + public static PaperLetters ForPerson (int personId) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPaperLettersForPerson(personId)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPaperLettersForPerson (personId)); } } } \ No newline at end of file diff --git a/Logic/Communications/PhoneMessageReceiver.cs b/Logic/Communications/PhoneMessageReceiver.cs index dae2ce35..03ba2d75 100644 --- a/Logic/Communications/PhoneMessageReceiver.cs +++ b/Logic/Communications/PhoneMessageReceiver.cs @@ -18,12 +18,12 @@ namespace Swarmops.Logic.Communications private string message = ""; private Dictionary people = new Dictionary(); - //people matching the set number + //people matching the set number private string replyMessage = ""; private DateTime sentAt; - public PhoneMessage(string fromNumber, string message, DateTime sentAt) + public PhoneMessage (string fromNumber, string message, DateTime sentAt) { FromNumber = fromNumber; Message = message; @@ -58,8 +58,8 @@ namespace Swarmops.Logic.Communications // The phone number should come from SMS host as +46 // But it can be saved in different formats in the DB, so try the most common // ways to format the number. - string[] phoneNumbers = PhoneMessageTransmitter.DeNormalizedPhoneNumber(FromNumber); - this.people = PhoneMessageReceiver.GetPeopleFromPhoneNumbers(phoneNumbers); + string[] phoneNumbers = PhoneMessageTransmitter.DeNormalizedPhoneNumber (FromNumber); + this.people = PhoneMessageReceiver.GetPeopleFromPhoneNumbers (phoneNumbers); } } @@ -78,37 +78,37 @@ namespace Swarmops.Logic.Communications internal interface IPhoneMessageHandler { - bool Filter(PhoneMessage msg); - bool Handle(PhoneMessage msg); + bool Filter (PhoneMessage msg); + bool Handle (PhoneMessage msg); } internal abstract class PhoneMessageHandler : IPhoneMessageHandler { - public virtual bool Filter(PhoneMessage message) + public virtual bool Filter (PhoneMessage message) { return (message.People.Count > 0); } - public virtual bool Handle(PhoneMessage message) + public virtual bool Handle (PhoneMessage message) { return false; } - protected virtual void ForwardMessage(string from, string to, string subject, string body) + protected virtual void ForwardMessage (string from, string to, string subject, string body) { - PhoneMessageReceiver.SendMail(from, to, subject, body); + PhoneMessageReceiver.SendMail (from, to, subject, body); } } internal class DefaultMessageHandler : PhoneMessageHandler { - public override bool Filter(PhoneMessage message) + public override bool Filter (PhoneMessage message) { return true; //Catch all } - public override bool Handle(PhoneMessage msg) + public override bool Handle (PhoneMessage msg) { string from = "sms-noreply@piratpartiet.se"; string to = "smsreplies@piratpartiet.se"; @@ -123,7 +123,7 @@ namespace Swarmops.Logic.Communications foreach (BasicPerson bp in msg.People.Values) { body += "Det telefonnumret tillhör medlem/aktivistnummer: "; - Person person = Person.FromBasic(bp); + Person person = Person.FromBasic (bp); body += person.Identity + " ("; if (!person.IsActivist) body += "ej "; @@ -134,7 +134,7 @@ namespace Swarmops.Logic.Communications { numbers += "," + bp.PersonId; } - body += "\r\n\r\n" + numbers.Substring(1); + body += "\r\n\r\n" + numbers.Substring (1); } else body += "Hittade ingen medlem/aktivist i databasen med det numret.\r\n\r\n"; @@ -144,10 +144,10 @@ namespace Swarmops.Logic.Communications body += "\r\nComment from SMS processing: " + msg.ErrorMessage; } - ForwardMessage(from, to, subject, body); + ForwardMessage (from, to, subject, body); msg.ReplyMessage += "\r\nDitt meddelande har vidarebefordrats till medlemsservice@piratpartiet.se. Kontakta oss om du undrar över något."; - PWLog.Write(PWLogItem.None, 0, PWLogAction.SMSHandled, "Forwarded SMS from " + msg.FromNumber + " to " + to, + PWLog.Write (PWLogItem.None, 0, PWLogAction.SMSHandled, "Forwarded SMS from " + msg.FromNumber + " to " + to, msg.Message + "\r\n" + msg.ErrorMessage); return true; @@ -156,28 +156,28 @@ namespace Swarmops.Logic.Communications internal class UnregisterActivistHandler : PhoneMessageHandler { - public override bool Filter(PhoneMessage msg) + public override bool Filter (PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + string[] smsParts = msg.Message.ToLower().Trim().Split (new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if ((smsParts[0] == "stopp" || smsParts[0] == "stop") && (smsParts[1] == "aktivist" || smsParts[1] == "activist")) { - return base.Filter(msg); + return base.Filter (msg); } return false; } - public override bool Handle(PhoneMessage msg) + public override bool Handle (PhoneMessage msg) { //TODO: Decide if more than one hit is OK if (msg.People.Count > 0) { foreach (BasicPerson bPerson in msg.People.Values) { - Person person = Person.FromBasic(bPerson); + Person person = Person.FromBasic (bPerson); if (person.IsActivist) { - ActivistEvents.TerminateActivistWithLogging(person, EventSource.SMS); + ActivistEvents.TerminateActivistWithLogging (person, EventSource.SMS); return true; } } @@ -192,9 +192,9 @@ namespace Swarmops.Logic.Communications internal class RegisterActivistHandler : PhoneMessageHandler { - public override bool Filter(PhoneMessage msg) + public override bool Filter (PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + string[] smsParts = msg.Message.ToLower().Trim().Split (new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (smsParts[0] == "start" && (smsParts[1] == "aktivist" || smsParts[1] == "activist")) { return true; @@ -203,9 +203,9 @@ namespace Swarmops.Logic.Communications } - public override bool Handle(PhoneMessage msg) + public override bool Handle (PhoneMessage msg) { - Trace.WriteLine(msg); // use parameter to suppress warning + Trace.WriteLine (msg); // use parameter to suppress warning /* -- all of the phone message handling need to move to app or plugin @@ -254,9 +254,9 @@ namespace Swarmops.Logic.Communications internal class RenewMembershipHandler : PhoneMessageHandler { - public override bool Filter(PhoneMessage msg) + public override bool Filter (PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + string[] smsParts = msg.Message.ToLower().Trim().Split (new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (smsParts[0] == "pp" && smsParts[1] == "igen") { return true; @@ -265,7 +265,7 @@ namespace Swarmops.Logic.Communications } - public override bool Handle(PhoneMessage msg) + public override bool Handle (PhoneMessage msg) { /* This needs to move to a plugin. */ @@ -339,7 +339,7 @@ namespace Swarmops.Logic.Communications // use parameters to suppress warnings - Trace.WriteLine(msg); + Trace.WriteLine (msg); return false; } } @@ -356,9 +356,9 @@ namespace Swarmops.Logic.Communications if (_handlers.Count == 0) { //set up list of handlers - _handlers.Add(new UnregisterActivistHandler()); - _handlers.Add(new RegisterActivistHandler()); - _handlers.Add(new DefaultMessageHandler()); // Always last + _handlers.Add (new UnregisterActivistHandler()); + _handlers.Add (new RegisterActivistHandler()); + _handlers.Add (new DefaultMessageHandler()); // Always last } return _handlers; @@ -372,10 +372,10 @@ namespace Swarmops.Logic.Communications /// /// /// - public static void Handle(string fromNumber, string message, DateTime sentAt) + public static void Handle (string fromNumber, string message, DateTime sentAt) { // create a message object - PhoneMessage msg = new PhoneMessage(fromNumber, message, sentAt); + PhoneMessage msg = new PhoneMessage (fromNumber, message, sentAt); //Ask all handlers if they want to handle the message object foreach (IPhoneMessageHandler handler in Handlers) @@ -383,10 +383,10 @@ namespace Swarmops.Logic.Communications try { // Want to handle this message ? - if (handler.Filter(msg)) + if (handler.Filter (msg)) { // if Handle() returns true do not call the following handlers - if (handler.Handle(msg)) + if (handler.Handle (msg)) break; } } @@ -396,7 +396,7 @@ namespace Swarmops.Logic.Communications } if (msg.ReplyMessage != "") { - PhoneMessageTransmitter.Send(msg.FromNumber, msg.ReplyMessage); + PhoneMessageTransmitter.Send (msg.FromNumber, msg.ReplyMessage); } } @@ -407,7 +407,7 @@ namespace Swarmops.Logic.Communications /// i /// /// - public static Dictionary GetPeopleFromPhoneNumbers(string[] phoneNumbers) + public static Dictionary GetPeopleFromPhoneNumbers (string[] phoneNumbers) { Dictionary peopleDict = new Dictionary(); @@ -416,11 +416,11 @@ namespace Swarmops.Logic.Communications for (int i = 0; i < phoneNumbers.Length; i++) { BasicPerson[] people = SwarmDb.GetDatabaseForReading() - .GetPeopleFromPhoneNumber("SE", phoneNumbers[i]); + .GetPeopleFromPhoneNumber ("SE", phoneNumbers[i]); foreach (BasicPerson bp in people) { //Only add if not seen. - if (!peopleDict.ContainsKey(bp.PersonId)) + if (!peopleDict.ContainsKey (bp.PersonId)) { peopleDict[bp.PersonId] = bp; } @@ -434,23 +434,23 @@ namespace Swarmops.Logic.Communications return peopleDict; } - internal static void SendMail(string from, string to, string subject, string body) + internal static void SendMail (string from, string to, string subject, string body) { MailMessage mail = new MailMessage(); mail.IsBodyHtml = false; mail.Subject = subject; mail.Body = body; - mail.From = new MailAddress(from, from, Encoding.UTF8); - mail.To.Add(to); + mail.From = new MailAddress (from, from, Encoding.UTF8); + mail.To.Add (to); - SmtpClient mailserver = new SmtpClient("mail.piratpartiet.se", 587); + SmtpClient mailserver = new SmtpClient ("mail.piratpartiet.se", 587); try { - mailserver.Send(mail); + mailserver.Send (mail); } catch (Exception e) { - throw new Exception(e.Message + "

" + mail.Body); + throw new Exception (e.Message + "

" + mail.Body); } } } diff --git a/Logic/Communications/PhoneMessageTransmitter.cs b/Logic/Communications/PhoneMessageTransmitter.cs index 19ea5f0c..188ee945 100644 --- a/Logic/Communications/PhoneMessageTransmitter.cs +++ b/Logic/Communications/PhoneMessageTransmitter.cs @@ -23,15 +23,15 @@ namespace Swarmops.Logic.Communications { lock (locker) { - if (credential == null || DateTime.Now.Subtract(lastLoad).TotalSeconds > 30) + if (credential == null || DateTime.Now.Subtract (lastLoad).TotalSeconds > 30) { lastLoad = DateTime.Now; String serviceName = Persistence.Key["SMSService"]; BasicExternalCredential basicCredential = - SwarmDb.GetDatabaseForReading().GetExternalCredential(serviceName); - Encoding enc = Encoding.GetEncoding(28591); //ISO encoding (latin1) + SwarmDb.GetDatabaseForReading().GetExternalCredential (serviceName); + Encoding enc = Encoding.GetEncoding (28591); //ISO encoding (latin1) - credential = new ServiceCredential(basicCredential.Login, basicCredential.Password, + credential = new ServiceCredential (basicCredential.Login, basicCredential.Password, basicCredential.ServiceName, enc); } @@ -51,23 +51,23 @@ namespace Swarmops.Logic.Communications case "SwedishKannel": return 0.03; //Guess default: - throw new Exception("Error on SMSCost. Unknown SMS service: " + Credential.ServiceName); + throw new Exception ("Error on SMSCost. Unknown SMS service: " + Credential.ServiceName); } } } - internal static void Send(string phoneNumber, string message) + internal static void Send (string phoneNumber, string message) { switch (Credential.ServiceName) { case "SwedishSms": - SendMoSMS(phoneNumber, message); + SendMoSMS (phoneNumber, message); break; case "SwedishKannel": - SendKannel(phoneNumber, message); + SendKannel (phoneNumber, message); break; default: - throw new Exception("Error on SMS transmit. Unknown SMS service: " + Credential.ServiceName); + throw new Exception ("Error on SMS transmit. Unknown SMS service: " + Credential.ServiceName); } } @@ -89,8 +89,8 @@ namespace Swarmops.Logic.Communications HttpWebResponse responseOut = null; try { - result = HTTPSender.Send(url, enc, 1500, out responseOut); - if (((int) responseOut.StatusCode).ToString().StartsWith("2")) + result = HTTPSender.Send (url, enc, 1500, out responseOut); + if (((int) responseOut.StatusCode).ToString().StartsWith ("2")) return true; return false; } @@ -100,15 +100,15 @@ namespace Swarmops.Logic.Communications } } default: - throw new Exception("Error on SMS transmit. Unknown SMS service: " + Credential.ServiceName); + throw new Exception ("Error on SMS transmit. Unknown SMS service: " + Credential.ServiceName); } } - public static void SendKannel(string phoneNumber, string message) + public static void SendKannel (string phoneNumber, string message) { //This is the swedish HOMEGROWN SMS sending mechanisma - String encodedMessage = HttpUtility.UrlEncode(message, Credential.Encoding); - String encodedPhone = NormalizePhoneNumber(phoneNumber, Credential.Encoding); + String encodedMessage = HttpUtility.UrlEncode (message, Credential.Encoding); + String encodedPhone = NormalizePhoneNumber (phoneNumber, Credential.Encoding); String username = Credential.Login; String password = Credential.Password; @@ -124,15 +124,15 @@ namespace Swarmops.Logic.Communications "&text=" + encodedMessage + "&charset=latin1"; - result = HTTPSender.Send(call_string, enc); + result = HTTPSender.Send (call_string, enc); if (result != "0: Accepted for delivery") { - throw new Exception("Error on SMS transmit: phone number " + phoneNumber + ", error code " + result); + throw new Exception ("Error on SMS transmit: phone number " + phoneNumber + ", error code " + result); } } - internal static void SendMoSMS(string phone, string message) + internal static void SendMoSMS (string phone, string message) { // This is the SWEDISH sms transmission mechanism. @@ -150,11 +150,11 @@ namespace Swarmops.Logic.Communications // Sätt vilken typ av SMS som skall skickas. String mosms_type = "text"; - String encodedMessage = HttpUtility.UrlEncode(message, Credential.Encoding); + String encodedMessage = HttpUtility.UrlEncode (message, Credential.Encoding); // Sätt SMS-meddelandet som skall skickas String mosms_data = encodedMessage; - mosms_data = HttpUtility.UrlEncode(mosms_data, enc); + mosms_data = HttpUtility.UrlEncode (mosms_data, enc); call_string = mosms_url + "?username=" + mosms_username + @@ -163,30 +163,30 @@ namespace Swarmops.Logic.Communications "&type=" + mosms_type + "&data=" + mosms_data; - result = HTTPSender.Send(call_string, enc); - result = HttpUtility.UrlDecode(result, enc); + result = HTTPSender.Send (call_string, enc); + result = HttpUtility.UrlDecode (result, enc); if (result != "0") { - throw new Exception("Error on SMS transmit: phone number " + phone + ", error code " + result); + throw new Exception ("Error on SMS transmit: phone number " + phone + ", error code " + result); } } // A phone number should be in the format: // + // Also URL encode as the + is treated as a space if not encoded - internal static string NormalizePhoneNumber(string phoneNumber, Encoding enc) + internal static string NormalizePhoneNumber (string phoneNumber, Encoding enc) { phoneNumber = phoneNumber.Trim(); - if (phoneNumber.Length > 4 && !phoneNumber.StartsWith("+")) + if (phoneNumber.Length > 4 && !phoneNumber.StartsWith ("+")) { - if (phoneNumber.StartsWith("00")) + if (phoneNumber.StartsWith ("00")) { - phoneNumber = "+" + phoneNumber.Substring(2); + phoneNumber = "+" + phoneNumber.Substring (2); } - else if (phoneNumber.StartsWith("0")) + else if (phoneNumber.StartsWith ("0")) { - phoneNumber = "+46" + phoneNumber.Substring(1); + phoneNumber = "+46" + phoneNumber.Substring (1); } else { @@ -194,16 +194,16 @@ namespace Swarmops.Logic.Communications } } - phoneNumber = HttpUtility.UrlEncode(phoneNumber, enc); + phoneNumber = HttpUtility.UrlEncode (phoneNumber, enc); return phoneNumber; } - public static string[] DeNormalizedPhoneNumber(string phoneNumber) + public static string[] DeNormalizedPhoneNumber (string phoneNumber) { string[] phoneNumbers = new string[3]; - Match match = Regex.Match(phoneNumber, @"^(((00|\+)46)|0)(7[0236]\d+)$"); + Match match = Regex.Match (phoneNumber, @"^(((00|\+)46)|0)(7[0236]\d+)$"); if (match.Success) { GroupCollection groups = match.Groups; @@ -222,21 +222,21 @@ namespace Swarmops.Logic.Communications private class HTTPSender : ICertificatePolicy { - public bool CheckValidationResult(ServicePoint sp, X509Certificate certificate, WebRequest request, + public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error) { return true; } - public static string Send(string http_payload, Encoding enc) + public static string Send (string http_payload, Encoding enc) { HttpWebResponse responseOut = null; - return Send(http_payload, enc, -1, out responseOut); + return Send (http_payload, enc, -1, out responseOut); } - public static string Send(string http_payload, Encoding enc, int timeout, out HttpWebResponse responseOut) + public static string Send (string http_payload, Encoding enc, int timeout, out HttpWebResponse responseOut) { // variabel för indata StringBuilder sb = new StringBuilder(); @@ -252,7 +252,7 @@ namespace Swarmops.Logic.Communications ServicePointManager.CertificatePolicy = new HTTPSender(); // anropa websidan med aktuella data - HttpWebRequest request = (HttpWebRequest) WebRequest.Create(http_payload); + HttpWebRequest request = (HttpWebRequest) WebRequest.Create (http_payload); if (timeout > -1) { @@ -273,15 +273,15 @@ namespace Swarmops.Logic.Communications do { // fyll bufferten - count = resStream.Read(buf, 0, buf.Length); + count = resStream.Read (buf, 0, buf.Length); // kontrollera att data finns att läsa if (count != 0) { // koda som ISO text - tempString = enc.GetString(buf, 0, count); + tempString = enc.GetString (buf, 0, count); // bygg upp svarssträngen - sb.Append(tempString); + sb.Append (tempString); } } while (count > 0); // finns mer data att läsa? @@ -300,7 +300,7 @@ namespace Swarmops.Logic.Communications internal readonly string Password; internal readonly string ServiceName; - internal ServiceCredential(string login, string password, string serviceName, Encoding enc) + internal ServiceCredential (string login, string password, string serviceName, Encoding enc) { this.Login = login; this.Password = password; diff --git a/Logic/Communications/Transmission/NotificationPayload.cs b/Logic/Communications/Transmission/NotificationPayload.cs index fd925217..1a761e02 100644 --- a/Logic/Communications/Transmission/NotificationPayload.cs +++ b/Logic/Communications/Transmission/NotificationPayload.cs @@ -8,7 +8,7 @@ namespace Swarmops.Logic.Communications.Transmission [Serializable] public class NotificationPayload : PayloadBase, ICommsRenderer { - [Obsolete( + [Obsolete ( "Do not use this direct constructor. It is intended for XML serialization only. Therefore, you're getting a compile-time error.", true)] public NotificationPayload() @@ -16,12 +16,13 @@ namespace Swarmops.Logic.Communications.Transmission // empty ctor, for XML reflection. Do not use. } - public NotificationPayload(string notificationResource) : this(notificationResource, new NotificationStrings()) + public NotificationPayload (string notificationResource) + : this (notificationResource, new NotificationStrings()) { // redirect to main ctor } - public NotificationPayload(string notificationResource, NotificationStrings strings) + public NotificationPayload (string notificationResource, NotificationStrings strings) { SubjectResource = notificationResource + "_Subject"; BodyResource = notificationResource + "_Body"; @@ -37,8 +38,8 @@ namespace Swarmops.Logic.Communications.Transmission // TODO: Pick culture return - ExpandMacros( - Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString(SubjectResource)); + ExpandMacros ( + Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString (SubjectResource)); } public string GetBody() @@ -46,15 +47,15 @@ namespace Swarmops.Logic.Communications.Transmission // TODO: Pick culture return - ExpandMacros( - Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString(BodyResource)); + ExpandMacros ( + Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString (BodyResource)); } - public string ExpandMacros(string input) + public string ExpandMacros (string input) { // TODO: Replace all, of course - input = input.Replace("[HostName]", Dns.GetHostName()); + input = input.Replace ("[HostName]", Dns.GetHostName()); // Loop through supplied strings and replace them in the resource. Not very efficient but who cares @@ -62,7 +63,7 @@ namespace Swarmops.Logic.Communications.Transmission { // TODO: Check if string ends in Float, and if so, parse and culturize it - input = input.Replace("[" + notificationString + "]", Strings[notificationString]); + input = input.Replace ("[" + notificationString + "]", Strings[notificationString]); } return input; @@ -70,7 +71,7 @@ namespace Swarmops.Logic.Communications.Transmission #region Implementation of ICommsRenderer - public RenderedComm RenderComm(Person person) + public RenderedComm RenderComm (Person person) { RenderedComm result = new RenderedComm(); diff --git a/Logic/Communications/Transmission/PayloadBase.cs b/Logic/Communications/Transmission/PayloadBase.cs index 1ba6b175..3b7411fd 100644 --- a/Logic/Communications/Transmission/PayloadBase.cs +++ b/Logic/Communications/Transmission/PayloadBase.cs @@ -11,35 +11,35 @@ namespace Swarmops.Logic.Communications.Transmission { public string ToXml() { - XmlSerializer serializer = new XmlSerializer(typeof (T)); + XmlSerializer serializer = new XmlSerializer (typeof (T)); MemoryStream stream = new MemoryStream(); - serializer.Serialize(stream, this); + serializer.Serialize (stream, this); byte[] xmlBytes = stream.GetBuffer(); - return Encoding.UTF8.GetString(xmlBytes); + return Encoding.UTF8.GetString (xmlBytes); } - public static T FromXml(string xml) + public static T FromXml (string xml) { // Compensate for stupid Mono encoding bugs - if (xml.StartsWith("?")) + if (xml.StartsWith ("?")) { - xml = xml.Substring(1); + xml = xml.Substring (1); } - xml = xml.Replace("�", ""); - xml = xml.Replace("\x00", ""); + xml = xml.Replace ("�", ""); + xml = xml.Replace ("\x00", ""); - XmlSerializer serializer = new XmlSerializer(typeof (T)); + XmlSerializer serializer = new XmlSerializer (typeof (T)); MemoryStream stream = new MemoryStream(); - byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); - stream.Write(xmlBytes, 0, xmlBytes.Length); + byte[] xmlBytes = Encoding.UTF8.GetBytes (xml); + stream.Write (xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - T result = (T) serializer.Deserialize(stream); + T result = (T) serializer.Deserialize (stream); stream.Close(); return result; diff --git a/Logic/Communications/Transmission/PayloadEnvelope.cs b/Logic/Communications/Transmission/PayloadEnvelope.cs index f4d4a79c..dcf36c8a 100644 --- a/Logic/Communications/Transmission/PayloadEnvelope.cs +++ b/Logic/Communications/Transmission/PayloadEnvelope.cs @@ -11,7 +11,7 @@ namespace Swarmops.Logic.Communications.Transmission // default public ctor for serializability } - public PayloadEnvelope(IXmlPayload payload) + public PayloadEnvelope (IXmlPayload payload) { PayloadClass = payload.GetType().ToString(); PayloadXml = payload.ToXml(); diff --git a/Logic/Communications/TypedMailTemplate.cs b/Logic/Communications/TypedMailTemplate.cs index 1261c993..2e5fd807 100644 --- a/Logic/Communications/TypedMailTemplate.cs +++ b/Logic/Communications/TypedMailTemplate.cs @@ -51,12 +51,12 @@ namespace Swarmops.Logic.Communications List retval = new List(); foreach (TemplateType t in templateTypes.Keys) { - retval.Add(templateTypes[t].BaseName); + retval.Add (templateTypes[t].BaseName); } return retval; } - public static string GetNameFromMailType(int mailType) + public static string GetNameFromMailType (int mailType) { try { @@ -64,15 +64,15 @@ namespace Swarmops.Logic.Communications } catch (Exception ex) { - throw new Exception("Can't translate mailtype(" + mailType + ") to template name", ex); + throw new Exception ("Can't translate mailtype(" + mailType + ") to template name", ex); } } - public static TemplateType TypeFromName(string className) + public static TemplateType TypeFromName (string className) { - if (className.ToLower().EndsWith("plain")) - className = className.Substring(0, className.Length - 5); + if (className.ToLower().EndsWith ("plain")) + className = className.Substring (0, className.Length - 5); foreach (TemplateType t in templateTypes.Keys) { if (templateTypes[t].BaseName.ToLower() == className.ToLower()) @@ -86,16 +86,16 @@ namespace Swarmops.Logic.Communications private static Dictionary initTemplateTypes() { Dictionary retval = new Dictionary(); - retval.Add(TemplateType.None, new TypedMailTemplate()); - retval.Add(TemplateType.ActivistMail, new ActivistMail()); - retval.Add(TemplateType.ExpiredMail, new ExpiredMail()); - retval.Add(TemplateType.MemberMail, new MemberMail()); - retval.Add(TemplateType.NewsletterMail, new NewsletterMail()); - retval.Add(TemplateType.OfficerMail, new OfficerMail()); - retval.Add(TemplateType.PressReleaseMail, new PressReleaseMail()); - retval.Add(TemplateType.ReminderMail, new ReminderMail()); - retval.Add(TemplateType.WelcomeMail, new WelcomeMail()); - retval.Add(TemplateType.ChangeOrgMail, new ChangeOrgMail()); + retval.Add (TemplateType.None, new TypedMailTemplate()); + retval.Add (TemplateType.ActivistMail, new ActivistMail()); + retval.Add (TemplateType.ExpiredMail, new ExpiredMail()); + retval.Add (TemplateType.MemberMail, new MemberMail()); + retval.Add (TemplateType.NewsletterMail, new NewsletterMail()); + retval.Add (TemplateType.OfficerMail, new OfficerMail()); + retval.Add (TemplateType.PressReleaseMail, new PressReleaseMail()); + retval.Add (TemplateType.ReminderMail, new ReminderMail()); + retval.Add (TemplateType.WelcomeMail, new WelcomeMail()); + retval.Add (TemplateType.ChangeOrgMail, new ChangeOrgMail()); return retval; } @@ -106,62 +106,62 @@ namespace Swarmops.Logic.Communications public TypedMailTemplate() { this.template = new MailTemplate(); - AddPlaceHolder(new PlaceHolder("RecieverIds", "RecieverIds", PlaceholderType.NoTag)); + AddPlaceHolder (new PlaceHolder ("RecieverIds", "RecieverIds", PlaceholderType.NoTag)); } /// /// Create TypedMailTemplate object from name /// - public static TypedMailTemplate FromName(string className) + public static TypedMailTemplate FromName (string className) { try { - if (className.EndsWith("Plain")) - className = className.Substring(0, className.Length - 5); + if (className.EndsWith ("Plain")) + className = className.Substring (0, className.Length - 5); //Get the current assembly object Assembly assembly = Assembly.GetExecutingAssembly(); //Get the name of the assembly (this will include the public token and version number AssemblyName assemblyName = assembly.GetName(); //Use just the name concat to the class chosen to get the type of the object - Type t = assembly.GetType(assemblyName.Name + ".Communications." + className, false, true); + Type t = assembly.GetType (assemblyName.Name + ".Communications." + className, false, true); if (t == null) { //Fail, no such class - throw new ArgumentException("There is no defined class for a TypedMailTemplate named:" + className); + throw new ArgumentException ("There is no defined class for a TypedMailTemplate named:" + className); } //Create the object, cast it and return it to the caller - return (TypedMailTemplate) Activator.CreateInstance(t); + return (TypedMailTemplate) Activator.CreateInstance (t); } catch (Exception e) { - throw new Exception("Failed to create TypedMailTemplate " + className, e); + throw new Exception ("Failed to create TypedMailTemplate " + className, e); } } - protected virtual void Initialize(MailTemplate templ) + protected virtual void Initialize (MailTemplate templ) { this.template = templ; } - protected virtual void Initialize(string countryCode, int orgId, string variant) + protected virtual void Initialize (string countryCode, int orgId, string variant) { try { - this.template = MailTemplate.FromNameCountryAndOrg(BaseName + variant, countryCode, orgId); + this.template = MailTemplate.FromNameCountryAndOrg (BaseName + variant, countryCode, orgId); } catch { string name = BaseName + variant; - if (name.EndsWith("Plain")) + if (name.EndsWith ("Plain")) { try { - name = name.Substring(0, name.Length - 5); - this.template = MailTemplate.FromNameCountryAndOrg(name, countryCode, orgId); + name = name.Substring (0, name.Length - 5); + this.template = MailTemplate.FromNameCountryAndOrg (name, countryCode, orgId); } catch (Exception e) { - throw new Exception( + throw new Exception ( "Failed to create MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + "," + orgId + ")", e); } @@ -170,11 +170,11 @@ namespace Swarmops.Logic.Communications { try { - this.template = MailTemplate.FromNameCountryAndOrg(name + "Plain", countryCode, orgId); + this.template = MailTemplate.FromNameCountryAndOrg (name + "Plain", countryCode, orgId); } catch (Exception e) { - throw new Exception( + throw new Exception ( "Failed to create (plain) MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + "," + orgId + ")", e); } @@ -186,27 +186,27 @@ namespace Swarmops.Logic.Communications /// /// Initialize a TypedMailTemplate subclass for rendering /// - public virtual void Initialize(string countryCode, int orgId, OutboundMail mail, string variant) + public virtual void Initialize (string countryCode, int orgId, OutboundMail mail, string variant) { - Initialize(countryCode, orgId, variant); + Initialize (countryCode, orgId, variant); try { - DeserializePlaceHolders(mail.Body); + DeserializePlaceHolders (mail.Body); } catch (Exception ex) { try { //try to handle old mail format... just in case. - SetPlaceHolder("BodyContent", mail.Body); - SetPlaceHolder("IntroContent", string.Empty); - SetPlaceHolder("GeographyName", mail.Geography.Name); - SetPlaceHolder("OrgName", mail.Organization.Name); + SetPlaceHolder ("BodyContent", mail.Body); + SetPlaceHolder ("IntroContent", string.Empty); + SetPlaceHolder ("GeographyName", mail.Geography.Name); + SetPlaceHolder ("OrgName", mail.Organization.Name); } catch (Exception) { //didnt't work, throw the original error - throw new Exception("Failed to deserialize placeholders:", ex); + throw new Exception ("Failed to deserialize placeholders:", ex); } } } @@ -237,7 +237,7 @@ namespace Swarmops.Logic.Communications get { if (this.templatetype == TemplateType.None) - this.templatetype = TypeFromName(BaseName); + this.templatetype = TypeFromName (BaseName); return this.templatetype; } } @@ -311,15 +311,15 @@ namespace Swarmops.Logic.Communications { } - internal PlaceHolder(string name, string label, PlaceholderType tagOrId) + internal PlaceHolder (string name, string label, PlaceholderType tagOrId) { this.name = name; this.label = label; this.tagOrId = tagOrId; } - internal PlaceHolder(string name, string label, PlaceholderType tagOrId, Type dataType, string formatString) - : this(name, label, tagOrId) + internal PlaceHolder (string name, string label, PlaceholderType tagOrId, Type dataType, string formatString) + : this (name, label, tagOrId) { this.dataType = dataType; this.formatString = formatString; @@ -361,29 +361,29 @@ namespace Swarmops.Logic.Communications /// /// Used to add placeholder in constructor of subclasses /// - protected void AddPlaceHolder(PlaceHolder ph) + protected void AddPlaceHolder (PlaceHolder ph) { ph.seq = this.placeholders.Count; - this.placeholders.Add(ph.Name, ph); + this.placeholders.Add (ph.Name, ph); } - protected void SetPlaceHolder(string name, string value) + protected void SetPlaceHolder (string name, string value) { this.placeholders[name].value = value; } - protected void SetPlaceHolder(string name, DateTime value) + protected void SetPlaceHolder (string name, DateTime value) { if (Template != null && Template.LanguageCode != "" && Template.CountryCode != "") { - CultureInfo cult = new CultureInfo(Template.LanguageCode + "-" + Template.CountryCode); - string formattedDate = value.ToString(this.placeholders[name].formatString, cult); - SetPlaceHolder(name, formattedDate); + CultureInfo cult = new CultureInfo (Template.LanguageCode + "-" + Template.CountryCode); + string formattedDate = value.ToString (this.placeholders[name].formatString, cult); + SetPlaceHolder (name, formattedDate); } else { string formattedDate = value.Ticks.ToString(); - SetPlaceHolder(name, formattedDate); + SetPlaceHolder (name, formattedDate); } } @@ -394,7 +394,7 @@ namespace Swarmops.Logic.Communications /// Used to serialize the values from the placeholder dictionary wich are then placed in the body of the /// OutboundMail record. from where they later are deserialized when the actual rendering takes place. /// - public virtual void FillIndividualPlaceholders(IEmailPerson personObject) + public virtual void FillIndividualPlaceholders (IEmailPerson personObject) { } @@ -404,84 +404,84 @@ namespace Swarmops.Logic.Communications public void InsertAllPlaceHoldersToTemplate() { if (Template == null) - throw new ArgumentException("There is no template loaded into the TypedMailTemplate"); + throw new ArgumentException ("There is no template loaded into the TypedMailTemplate"); // sort the placeholders according to the order they were defined in to guarantee that substitutions are in expected order. // "Inside" substitutions are done if the placeholder containing the substitution is defined before the substitutet one. - List sortedPlaceholders = new List(Placeholders.Values); - sortedPlaceholders.Sort( - delegate(PlaceHolder ph1, PlaceHolder ph2) { return ph1.seq.CompareTo(ph2.seq); }); + List sortedPlaceholders = new List (Placeholders.Values); + sortedPlaceholders.Sort ( + delegate (PlaceHolder ph1, PlaceHolder ph2) { return ph1.seq.CompareTo (ph2.seq); }); foreach (PlaceHolder ph in sortedPlaceholders) { - InsertOnePlaceholderToTemplate(ph); + InsertOnePlaceholderToTemplate (ph); } } - private void InsertOnePlaceholderToTemplate(PlaceHolder ph) + private void InsertOnePlaceholderToTemplate (PlaceHolder ph) { if (ph.TagOrId == PlaceholderType.Tag) { // .Tag is cleared if it isnt set - if (HttpUtility.HtmlDecode(ph.value) != "") - Template.ReplaceContentByPattern(ph.Name, ph.value); + if (HttpUtility.HtmlDecode (ph.value) != "") + Template.ReplaceContentByPattern (ph.Name, ph.value); else - Template.ReplaceContentByPattern(ph.Name, ""); + Template.ReplaceContentByPattern (ph.Name, ""); } else if (ph.TagOrId == PlaceholderType.Id) { // .Id is left as is if it isn't set - if (HttpUtility.HtmlDecode(ph.value) != "") - Template.ReplaceContentById(ph.Name, ph.value); + if (HttpUtility.HtmlDecode (ph.value) != "") + Template.ReplaceContentById (ph.Name, ph.value); } else if (ph.TagOrId == PlaceholderType.TagInSpan) { // .TagInSpan if not set: All tags are emptied and all elements are removed - if (ph.value != "" && HttpUtility.HtmlDecode(ph.value) != "") + if (ph.value != "" && HttpUtility.HtmlDecode (ph.value) != "") { - Template.ReplaceContentByPattern(ph.Name, ph.value); - Template.RemoveEnclosingTag(ph.Name); + Template.ReplaceContentByPattern (ph.Name, ph.value); + Template.RemoveEnclosingTag (ph.Name); } else { //Replace tags - if (HttpUtility.HtmlDecode(ph.value) != "") - Template.ReplaceContentByPattern(ph.Name, ph.value); + if (HttpUtility.HtmlDecode (ph.value) != "") + Template.ReplaceContentByPattern (ph.Name, ph.value); else - Template.ReplaceContentByPattern(ph.Name, ""); + Template.ReplaceContentByPattern (ph.Name, ""); //and remove id-elements - Template.RemoveElementById(ph.Name); + Template.RemoveElementById (ph.Name); } } } protected string SerializePlaceHolders() { - XmlSerializer s = new XmlSerializer(Placeholders.GetType()); + XmlSerializer s = new XmlSerializer (Placeholders.GetType()); StringBuilder retSb = new StringBuilder(); - TextWriter w = new StringWriter(retSb); - s.Serialize(w, Placeholders); + TextWriter w = new StringWriter (retSb); + s.Serialize (w, Placeholders); w.Close(); - return retSb.ToString().Replace("%IntroContent%", string.Empty); - // EXTREMELY UGLY HACK to empty %IntroContent% + return retSb.ToString().Replace ("%IntroContent%", string.Empty); + // EXTREMELY UGLY HACK to empty %IntroContent% } /// /// Load placeholders dictionary with serialized values /// - protected void DeserializePlaceHolders(string content) + protected void DeserializePlaceHolders (string content) { - XmlSerializer s = new XmlSerializer(Placeholders.GetType()); + XmlSerializer s = new XmlSerializer (Placeholders.GetType()); SerializableDictionary tempPlaceHolders = new SerializableDictionary(); - TextReader r = new StringReader(content); - tempPlaceHolders = (SerializableDictionary) s.Deserialize(r); + TextReader r = new StringReader (content); + tempPlaceHolders = (SerializableDictionary) s.Deserialize (r); r.Close(); foreach (PlaceHolder ph in Placeholders.Values) { - if (tempPlaceHolders.ContainsKey(ph.Name)) + if (tempPlaceHolders.ContainsKey (ph.Name)) { PlaceHolder phI = tempPlaceHolders[ph.name]; try @@ -489,14 +489,14 @@ namespace Swarmops.Logic.Communications long ticks = 0; // If it is a date and it was saved when no template was present it will be in ticks // SetPlaceHolder will format it according to templates culture. - if (Placeholders[ph.Name].DataType == typeof (DateTime) && long.TryParse(phI.Value, out ticks)) - SetPlaceHolder(ph.Name, new DateTime(ticks)); + if (Placeholders[ph.Name].DataType == typeof (DateTime) && long.TryParse (phI.Value, out ticks)) + SetPlaceHolder (ph.Name, new DateTime (ticks)); else - SetPlaceHolder(ph.Name, phI.Value); + SetPlaceHolder (ph.Name, phI.Value); } catch (Exception) { - SetPlaceHolder(ph.Name, "[*Invalid Value*]"); + SetPlaceHolder (ph.Name, "[*Invalid Value*]"); } } } @@ -504,41 +504,41 @@ namespace Swarmops.Logic.Communications #endregion - public OutboundMail CreateOutboundMail(Person author, int mailPriority, Organization organization, + public OutboundMail CreateOutboundMail (Person author, int mailPriority, Organization organization, Geography geography) { - return CreateOutboundMail(author, mailPriority, organization, geography, DateTime.Now); + return CreateOutboundMail (author, mailPriority, organization, geography, DateTime.Now); } /// /// Create OutboundMail with personal sender /// - public OutboundMail CreateOutboundMail(Person author, int mailPriority, + public OutboundMail CreateOutboundMail (Person author, int mailPriority, Organization organization, Geography geography, DateTime releaseDateTime) { - return OutboundMail.Create(author, BaseName, SerializePlaceHolders(), + return OutboundMail.Create (author, BaseName, SerializePlaceHolders(), mailPriority, MailType, organization, geography, releaseDateTime); } /// /// Create OutboundMail mail with "functional" sender /// - public OutboundMail CreateFunctionalOutboundMail(MailAuthorType authorType, int mailPriority, + public OutboundMail CreateFunctionalOutboundMail (MailAuthorType authorType, int mailPriority, Organization organization, Geography geography) { - return CreateFunctionalOutboundMail(authorType, mailPriority, organization, geography, DateTime.Now); + return CreateFunctionalOutboundMail (authorType, mailPriority, organization, geography, DateTime.Now); } - public OutboundMail CreateFunctionalOutboundMail(MailAuthorType authorType, int mailPriority, + public OutboundMail CreateFunctionalOutboundMail (MailAuthorType authorType, int mailPriority, Organization organization, Geography geography, DateTime releaseDateTime) { - return OutboundMail.CreateFunctional(authorType, BaseName, SerializePlaceHolders(), + return OutboundMail.CreateFunctional (authorType, BaseName, SerializePlaceHolders(), mailPriority, MailType, organization.Identity, geography.Identity, releaseDateTime); } - public OutboundMail CreateOutboundFake(Person author, Organization organization, Geography geography) + public OutboundMail CreateOutboundFake (Person author, Organization organization, Geography geography) { - return OutboundMail.CreateFake(author, BaseName, SerializePlaceHolders(), 0, + return OutboundMail.CreateFake (author, BaseName, SerializePlaceHolders(), 0, MailType, organization, geography); } @@ -547,20 +547,20 @@ namespace Swarmops.Logic.Communications public void PreparePlaceholders() { TypedMailTemplate template = this; - Regex reForumType = new Regex(@"(\[h.\])|(\[b\])|(\[i\])|(\[i\])|(\[blockquote\])|(\[br\])|(\[\/a\])", + Regex reForumType = new Regex (@"(\[h.\])|(\[b\])|(\[i\])|(\[i\])|(\[blockquote\])|(\[br\])|(\[\/a\])", RegexOptions.IgnoreCase); - Regex reHtmlType = new Regex(@"()|(<[^>]+?/>)", RegexOptions.IgnoreCase); + Regex reHtmlType = new Regex (@"()|(<[^>]+?/>)", RegexOptions.IgnoreCase); foreach (PlaceHolder ph in template.Placeholders.Values) { - if (reHtmlType.IsMatch(ph.value)) + if (reHtmlType.IsMatch (ph.value)) { //contains HTML, try to strip dangerous features try { HtmlDocument tempDoc = new HtmlDocument(); - tempDoc.LoadHtml(ph.value); - HtmlNodeCollection scriptNodes = tempDoc.DocumentNode.SelectNodes("//script"); + tempDoc.LoadHtml (ph.value); + HtmlNodeCollection scriptNodes = tempDoc.DocumentNode.SelectNodes ("//script"); if (scriptNodes != null) { foreach (HtmlNode n in scriptNodes) @@ -568,23 +568,23 @@ namespace Swarmops.Logic.Communications n.InnerHtml = ""; } } - HtmlNodeCollection iframeNodes = tempDoc.DocumentNode.SelectNodes("//iframe"); + HtmlNodeCollection iframeNodes = tempDoc.DocumentNode.SelectNodes ("//iframe"); if (iframeNodes != null) { foreach (HtmlNode n in iframeNodes) { - n.SetAttributeValue("src", ""); + n.SetAttributeValue ("src", ""); } } HtmlNodeCollection onhandlers = - tempDoc.DocumentNode.SelectNodes("//*[starts-with(local-name(@*),'on')]"); + tempDoc.DocumentNode.SelectNodes ("//*[starts-with(local-name(@*),'on')]"); if (onhandlers != null) { foreach (HtmlNode n in onhandlers) { foreach (HtmlAttribute att in n.Attributes) { - if (att.Name.ToLower().StartsWith("on")) + if (att.Name.ToLower().StartsWith ("on")) { att.Value = ""; } @@ -598,14 +598,14 @@ namespace Swarmops.Logic.Communications } } - if (reForumType.IsMatch(ph.value)) + if (reForumType.IsMatch (ph.value)) { //Is Forum type formatting - ph.value = ConvertForumToHtml(ph.value); + ph.value = ConvertForumToHtml (ph.value); } - if (!reHtmlType.IsMatch(ph.value)) + if (!reHtmlType.IsMatch (ph.value)) { - ph.value = ConvertPlainToHtml(ph.value); + ph.value = ConvertPlainToHtml (ph.value); } } } @@ -613,14 +613,14 @@ namespace Swarmops.Logic.Communications /// /// Convert plain text to reasonable html /// - private string ConvertPlainToHtml(string phvalue) + private string ConvertPlainToHtml (string phvalue) { - phvalue = HttpUtility.HtmlEncode(phvalue); + phvalue = HttpUtility.HtmlEncode (phvalue); phvalue = phvalue. - Replace("\r\n", "\n"). - Replace("\n", "
\n"). - Replace("\n", "\r\n"); + Replace ("\r\n", "\n"). + Replace ("\n", "
\n"). + Replace ("\n", "\r\n"); return phvalue; } @@ -628,46 +628,46 @@ namespace Swarmops.Logic.Communications /// /// Convert a sring with "forum" tags to html /// - private static string ConvertForumToHtml(string phvalue) + private static string ConvertForumToHtml (string phvalue) { - phvalue = HttpUtility.HtmlEncode(phvalue); + phvalue = HttpUtility.HtmlEncode (phvalue); phvalue = phvalue. - Replace("\r\n", "\n"). - Replace("\n", "
\n"). - Replace("[br]
\n", "
\n"). - Replace("
\n
\n", "

\n\n

"). - Replace("\n", "\r\n"). - Replace(""", "\""). - Replace("&", "&") + + Replace ("\r\n", "\n"). + Replace ("\n", "
\n"). + Replace ("[br]
\n", "
\n"). + Replace ("
\n
\n", "

\n\n

"). + Replace ("\n", "\r\n"). + Replace (""", "\""). + Replace ("&", "&") + "

"; // Encode approved HTML codes: h1, h2, h3, blockquote, a, b, i Regex regexLinks = - new Regex("(?s)\\[a\\s+href=\\\"(?[^\\\"]+)\\\"\\](?.+?)\\[/a\\]", + new Regex ("(?s)\\[a\\s+href=\\\"(?[^\\\"]+)\\\"\\](?.+?)\\[/a\\]", RegexOptions.Multiline); - phvalue = regexLinks.Replace(phvalue, RewriteUrlsInHtml); + phvalue = regexLinks.Replace (phvalue, RewriteUrlsInHtml); phvalue = phvalue. - Replace("[h1]", "

"). - Replace("[/h1]", "

"). - Replace("[h2]", "

"). - Replace("[/h2]", "

"). - Replace("[h3]", "

"). - Replace("[/h3]", "

"). - Replace("[b]", ""). - Replace("[/b]", ""). - Replace("[blockquote]", "
"). - Replace("[/blockquote]", "
"). - Replace("[i]", ""). - Replace("[/i]", ""). - Replace("[br]", "
"); + Replace ("[h1]", "

"). + Replace ("[/h1]", "

"). + Replace ("[h2]", "

"). + Replace ("[/h2]", "

"). + Replace ("[h3]", "

"). + Replace ("[/h3]", "

"). + Replace ("[b]", ""). + Replace ("[/b]", ""). + Replace ("[blockquote]", "
"). + Replace ("[/blockquote]", "
"). + Replace ("[i]", ""). + Replace ("[/i]", ""). + Replace ("[br]", "
"); return phvalue; } - private static string RewriteUrlsInHtml(Match match) + private static string RewriteUrlsInHtml (Match match) { return "" + match.Groups["description"].Value + ""; } @@ -689,57 +689,57 @@ namespace Swarmops.Logic.Communications { public MemberMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("GeographyName", "GeographyName", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("BodyContent", "BodyContent", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OrgName", "OrgName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("GeographyName", "GeographyName", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumber", "MemberNumber", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public string pBodyContent { - set { SetPlaceHolder("BodyContent", value); } + set { SetPlaceHolder ("BodyContent", value); } } public string pOrgName { - set { SetPlaceHolder("OrgName", value); } + set { SetPlaceHolder ("OrgName", value); } } public string pGeographyName { - set { SetPlaceHolder("GeographyName", value); } + set { SetPlaceHolder ("GeographyName", value); } } private string MemberNumberWithCheck { - set { SetPlaceHolder("MemberNumberWithCheck", value); } + set { SetPlaceHolder ("MemberNumberWithCheck", value); } } private string MemberNumber { - set { SetPlaceHolder("MemberNumber", value); } + set { SetPlaceHolder ("MemberNumber", value); } } private string HexIdentifier { - set { SetPlaceHolder("HexIdentifier", value); } + set { SetPlaceHolder ("HexIdentifier", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); Person person = (Person) personObject; - MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + MemberNumberWithCheck = CheckDigit.AppendCheckDigit (person.Identity).ToString(); HexIdentifier = person.HexIdentifier(); MemberNumber = person.PersonId.ToString(); } @@ -761,75 +761,75 @@ namespace Swarmops.Logic.Communications { public ExpiredMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("Memberships", "Memberships", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("MemberPhoneNumber", "MemberPhoneNumber", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Memberships", "Memberships", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("MemberPhoneNumber", "MemberPhoneNumber", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("OrgName", "OrgName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumber", "MemberNumber", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public string pMemberships { - set { SetPlaceHolder("Memberships", value); } + set { SetPlaceHolder ("Memberships", value); } } public string pOrgName { - set { SetPlaceHolder("OrgName", value); } + set { SetPlaceHolder ("OrgName", value); } } public string pStdRenewLink { - set { SetPlaceHolder("StdRenewLink", value); } + set { SetPlaceHolder ("StdRenewLink", value); } } private string MemberPhoneNumber { - set { SetPlaceHolder("MemberPhoneNumber", value); } + set { SetPlaceHolder ("MemberPhoneNumber", value); } } private string MemberNumberWithCheck { - set { SetPlaceHolder("MemberNumberWithCheck", value); } + set { SetPlaceHolder ("MemberNumberWithCheck", value); } } private string MemberNumber { - set { SetPlaceHolder("MemberNumber", value); } + set { SetPlaceHolder ("MemberNumber", value); } } private string HexIdentifier { - set { SetPlaceHolder("HexIdentifier", value); } + set { SetPlaceHolder ("HexIdentifier", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { try { if (!(personObject is Person)) - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); Person person = (Person) personObject; - MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + MemberNumberWithCheck = CheckDigit.AppendCheckDigit (person.Identity).ToString(); HexIdentifier = person.HexIdentifier(); MemberNumber = person.PersonId.ToString(); - if (People.FromPhoneNumber(person.Country.Code, person.Phone).Count == 1) + if (People.FromPhoneNumber (person.Country.Code, person.Phone).Count == 1) { MemberPhoneNumber = person.Phone; } } catch (Exception e) { - throw new Exception( + throw new Exception ( "Failed in FillIndividualPlaceholders person is " + personObject == null ? "null" : personObject.Identity.ToString(), e); @@ -841,121 +841,121 @@ namespace Swarmops.Logic.Communications { public ReminderMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("Preamble", "Preamble", PlaceholderType.Id)); - AddPlaceHolder(new PlaceHolder("ExpirationDate", "ExpirationDate", PlaceholderType.Tag, typeof (DateTime), + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Preamble", "Preamble", PlaceholderType.Id)); + AddPlaceHolder (new PlaceHolder ("ExpirationDate", "ExpirationDate", PlaceholderType.Tag, typeof (DateTime), "d")); - AddPlaceHolder(new PlaceHolder("NextDate", "NextDate", PlaceholderType.Tag, typeof (DateTime), "d")); + AddPlaceHolder (new PlaceHolder ("NextDate", "NextDate", PlaceholderType.Tag, typeof (DateTime), "d")); - AddPlaceHolder(new PlaceHolder("TooOldForYouthOrgSpan", "TooOldForYouthOrgSpan(SPAN)", PlaceholderType.Id)); - AddPlaceHolder(new PlaceHolder("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OtherOrg", "OtherOrg", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("CurrentAge", "Age this year", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OtherRenewLink", "OtherOrgRenewLink", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("TooOldForYouthOrgSpan", "TooOldForYouthOrgSpan(SPAN)", PlaceholderType.Id)); + AddPlaceHolder (new PlaceHolder ("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OtherOrg", "OtherOrg", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("CurrentAge", "Age this year", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OtherRenewLink", "OtherOrgRenewLink", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("WrongOrgSpan", "WrongOrgSpan(SPAN)", PlaceholderType.Id)); - AddPlaceHolder(new PlaceHolder("GeographyName", "GeographyName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("WrongOrgSpan", "WrongOrgSpan(SPAN)", PlaceholderType.Id)); + AddPlaceHolder (new PlaceHolder ("GeographyName", "GeographyName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("TerminateLink", "TerminateLink(Tag in SPAN)", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumber", "MemberNumber", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OrgName", "OrgName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("TerminateLink", "TerminateLink(Tag in SPAN)", PlaceholderType.TagInSpan)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public DateTime pExpirationDate { - set { SetPlaceHolder("ExpirationDate", value); } + set { SetPlaceHolder ("ExpirationDate", value); } } public DateTime pNextDate { - set { SetPlaceHolder("NextDate", value); } + set { SetPlaceHolder ("NextDate", value); } } public string pTooOldForYouthOrgSpan { - set { SetPlaceHolder("TooOldForYouthOrgSpan", value); } + set { SetPlaceHolder ("TooOldForYouthOrgSpan", value); } } public string pCurrentOrg { - set { SetPlaceHolder("CurrentOrg", value); } + set { SetPlaceHolder ("CurrentOrg", value); } } public string pOtherOrg { - set { SetPlaceHolder("OtherOrg", value); } + set { SetPlaceHolder ("OtherOrg", value); } } public string pCurrentAge { - set { SetPlaceHolder("CurrentAge", value); } + set { SetPlaceHolder ("CurrentAge", value); } } public string pOtherRenewLink { - set { SetPlaceHolder("OtherRenewLink", value); } + set { SetPlaceHolder ("OtherRenewLink", value); } } public string pWrongOrgSpan { - set { SetPlaceHolder("WrongOrgSpan", value); } + set { SetPlaceHolder ("WrongOrgSpan", value); } } public string pGeographyName { - set { SetPlaceHolder("GeographyName", value); } + set { SetPlaceHolder ("GeographyName", value); } } public string pStdRenewLink { - set { SetPlaceHolder("StdRenewLink", value); } + set { SetPlaceHolder ("StdRenewLink", value); } } public string pOrgName { - set { SetPlaceHolder("OrgName", value); } + set { SetPlaceHolder ("OrgName", value); } } public string pPreamble { - set { SetPlaceHolder("Preamble", value); } + set { SetPlaceHolder ("Preamble", value); } } public string pTerminateLink { - set { SetPlaceHolder("TerminateLink", value); } + set { SetPlaceHolder ("TerminateLink", value); } } private string MemberNumberWithCheck { - set { SetPlaceHolder("MemberNumberWithCheck", value); } + set { SetPlaceHolder ("MemberNumberWithCheck", value); } } private string MemberNumber { - set { SetPlaceHolder("MemberNumber", value); } + set { SetPlaceHolder ("MemberNumber", value); } } private string HexIdentifier { - set { SetPlaceHolder("HexIdentifier", value); } + set { SetPlaceHolder ("HexIdentifier", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); Person person = (Person) personObject; - MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + MemberNumberWithCheck = CheckDigit.AppendCheckDigit (person.Identity).ToString(); HexIdentifier = person.HexIdentifier(); MemberNumber = person.PersonId.ToString(); } @@ -965,69 +965,69 @@ namespace Swarmops.Logic.Communications { public PressReleaseMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("Date", "Date", PlaceholderType.Tag, typeof (DateTime), "d")); - AddPlaceHolder(new PlaceHolder("Time", "Time", PlaceholderType.Tag, typeof (DateTime), "t")); - AddPlaceHolder(new PlaceHolder("PostedToCategories", "PostedToCategories", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("ReporterName", "ReporterName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("ReporterEmail", "ReporterEmail", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("ReporterCategories", "ReporterCategories", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("BodyContent", "BodyContent", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Date", "Date", PlaceholderType.Tag, typeof (DateTime), "d")); + AddPlaceHolder (new PlaceHolder ("Time", "Time", PlaceholderType.Tag, typeof (DateTime), "t")); + AddPlaceHolder (new PlaceHolder ("PostedToCategories", "PostedToCategories", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("ReporterName", "ReporterName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("ReporterEmail", "ReporterEmail", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("ReporterCategories", "ReporterCategories", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OrgName", "OrgName", PlaceholderType.Tag)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public string pBodyContent { - set { SetPlaceHolder("BodyContent", value); } + set { SetPlaceHolder ("BodyContent", value); } } public DateTime pDate { set { - SetPlaceHolder("Date", value); - SetPlaceHolder("Time", value); + SetPlaceHolder ("Date", value); + SetPlaceHolder ("Time", value); } } public string pPostedToCategories { - set { SetPlaceHolder("PostedToCategories", value); } + set { SetPlaceHolder ("PostedToCategories", value); } } public string pOrgName { - set { SetPlaceHolder("OrgName", value); } + set { SetPlaceHolder ("OrgName", value); } } private string ReporterName { - set { SetPlaceHolder("ReporterName", value); } + set { SetPlaceHolder ("ReporterName", value); } } private string ReporterEmail { - set { SetPlaceHolder("ReporterEmail", value); } + set { SetPlaceHolder ("ReporterEmail", value); } } private string ReporterCategories { - set { SetPlaceHolder("ReporterCategories", value); } + set { SetPlaceHolder ("ReporterCategories", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { if (personObject is Reporter) { Reporter person = (Reporter) personObject; ReporterEmail = person.Email; ReporterName = person.Name; - ReporterCategories = GetConcatenatedCategoryString(person.MediaCategories); + ReporterCategories = GetConcatenatedCategoryString (person.MediaCategories); } else if (personObject is Person) { @@ -1037,11 +1037,11 @@ namespace Swarmops.Logic.Communications ReporterCategories = "Piratpartiet/Funktionär"; } else - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); } - public static string GetConcatenatedCategoryString(MediaCategories categories) + public static string GetConcatenatedCategoryString (MediaCategories categories) { if (categories.Count == 0) return ""; @@ -1066,93 +1066,93 @@ namespace Swarmops.Logic.Communications { public NewsletterMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("Date", "Date", PlaceholderType.Tag, typeof (DateTime), "d MMMM yyyy")); - AddPlaceHolder(new PlaceHolder("ForumPostUrl", "ForumPostUrl", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("Name", "Name", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("NameUrl", "NameUrl", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("EmailBase64Url", "EmailBase64Url", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("PhoneBase64Url", "PhoneBase64Url", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("BodyContent", "BodyContent", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Date", "Date", PlaceholderType.Tag, typeof (DateTime), "d MMMM yyyy")); + AddPlaceHolder (new PlaceHolder ("ForumPostUrl", "ForumPostUrl", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("OrgName", "OrgName", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumber", "MemberNumber", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("Name", "Name", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("NameUrl", "NameUrl", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("EmailBase64Url", "EmailBase64Url", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("PhoneBase64Url", "PhoneBase64Url", PlaceholderType.Tag)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public string pBodyContent { - set { SetPlaceHolder("BodyContent", value); } + set { SetPlaceHolder ("BodyContent", value); } } public DateTime pDate { - set { SetPlaceHolder("Date", value); } + set { SetPlaceHolder ("Date", value); } } public string pForumPostUrl { - set { SetPlaceHolder("ForumPostUrl", value); } + set { SetPlaceHolder ("ForumPostUrl", value); } } public string pOrgName { - set { SetPlaceHolder("OrgName", value); } + set { SetPlaceHolder ("OrgName", value); } } private string MemberNumberWithCheck { - set { SetPlaceHolder("MemberNumberWithCheck", value); } + set { SetPlaceHolder ("MemberNumberWithCheck", value); } } private string MemberNumber { - set { SetPlaceHolder("MemberNumber", value); } + set { SetPlaceHolder ("MemberNumber", value); } } private string HexIdentifier { - set { SetPlaceHolder("HexIdentifier", value); } + set { SetPlaceHolder ("HexIdentifier", value); } } private string Name { - set { SetPlaceHolder("Name", value); } + set { SetPlaceHolder ("Name", value); } } private string NameUrl { - set { SetPlaceHolder("NameUrl", value); } + set { SetPlaceHolder ("NameUrl", value); } } private string EmailBase64Url { - set { SetPlaceHolder("EmailBase64Url", value); } + set { SetPlaceHolder ("EmailBase64Url", value); } } private string PhoneBase64Url { - set { SetPlaceHolder("PhoneBase64Url", value); } + set { SetPlaceHolder ("PhoneBase64Url", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); Person person = (Person) personObject; - MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + MemberNumberWithCheck = CheckDigit.AppendCheckDigit (person.Identity).ToString(); HexIdentifier = person.HexIdentifier(); MemberNumber = person.PersonId.ToString(); Name = person.Name; - NameUrl = HttpUtility.UrlEncode(person.Name); - EmailBase64Url = HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(person.Mail))); - PhoneBase64Url = HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(person.Phone))); + NameUrl = HttpUtility.UrlEncode (person.Name); + EmailBase64Url = HttpUtility.UrlEncode (Convert.ToBase64String (Encoding.UTF8.GetBytes (person.Mail))); + PhoneBase64Url = HttpUtility.UrlEncode (Convert.ToBase64String (Encoding.UTF8.GetBytes (person.Phone))); } } @@ -1195,88 +1195,88 @@ namespace Swarmops.Logic.Communications public ChangeOrgMail() { - AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("InactiveOrg", "InactiveOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("ChangeOrg", "ChangeOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("NoLocalOrg", "NoLocalOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - AddPlaceHolder(new PlaceHolder("NextDate", "NextDate", PlaceholderType.Tag, typeof (DateTime), "d")); - AddPlaceHolder(new PlaceHolder("CurrentGeo", "CurrentGeo", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("InactiveEnding", "InactiveEnding(SPAN)", PlaceholderType.Id)); + AddPlaceHolder (new PlaceHolder ("Subject", "Subject", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("InactiveOrg", "InactiveOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("ChangeOrg", "ChangeOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("NoLocalOrg", "NoLocalOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); + AddPlaceHolder (new PlaceHolder ("NextDate", "NextDate", PlaceholderType.Tag, typeof (DateTime), "d")); + AddPlaceHolder (new PlaceHolder ("CurrentGeo", "CurrentGeo", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("InactiveEnding", "InactiveEnding(SPAN)", PlaceholderType.Id)); - AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("MemberNumber", "MemberNumber", PlaceholderType.Tag)); + AddPlaceHolder (new PlaceHolder ("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); } public string pSubject { - set { SetPlaceHolder("Subject", value); } + set { SetPlaceHolder ("Subject", value); } } public string pCurrentOrg { - set { SetPlaceHolder("CurrentOrg", value); } + set { SetPlaceHolder ("CurrentOrg", value); } } public string pInactiveOrg { - set { SetPlaceHolder("InactiveOrg", value); } + set { SetPlaceHolder ("InactiveOrg", value); } } public string pChangeOrg { - set { SetPlaceHolder("ChangeOrg", value); } + set { SetPlaceHolder ("ChangeOrg", value); } } public string pNoLocalOrg { - set { SetPlaceHolder("NoLocalOrg", value); } + set { SetPlaceHolder ("NoLocalOrg", value); } } public DateTime pNextDate { - set { SetPlaceHolder("NextDate", value); } + set { SetPlaceHolder ("NextDate", value); } } public string pCurrentGeo { - set { SetPlaceHolder("CurrentGeo", value); } + set { SetPlaceHolder ("CurrentGeo", value); } } public string pStdRenewLink { - set { SetPlaceHolder("StdRenewLink", value); } + set { SetPlaceHolder ("StdRenewLink", value); } } public string pInactiveEnding { - set { SetPlaceHolder("InactiveEnding", value); } + set { SetPlaceHolder ("InactiveEnding", value); } } private string MemberNumberWithCheck { - set { SetPlaceHolder("MemberNumberWithCheck", value); } + set { SetPlaceHolder ("MemberNumberWithCheck", value); } } private string MemberNumber { - set { SetPlaceHolder("MemberNumber", value); } + set { SetPlaceHolder ("MemberNumber", value); } } private string HexIdentifier { - set { SetPlaceHolder("HexIdentifier", value); } + set { SetPlaceHolder ("HexIdentifier", value); } } - public override void FillIndividualPlaceholders(IEmailPerson personObject) + public override void FillIndividualPlaceholders (IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(BaseName + - ".MakeIndividualReplacements called with wrong type of person object"); + throw new ArgumentException (BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); Person person = (Person) personObject; - MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + MemberNumberWithCheck = CheckDigit.AppendCheckDigit (person.Identity).ToString(); HexIdentifier = person.HexIdentifier(); MemberNumber = person.PersonId.ToString(); } diff --git a/Logic/DashboardTasks/TaskAdvanceDebt.cs b/Logic/DashboardTasks/TaskAdvanceDebt.cs index 833256a1..bbe375e3 100644 --- a/Logic/DashboardTasks/TaskAdvanceDebt.cs +++ b/Logic/DashboardTasks/TaskAdvanceDebt.cs @@ -5,10 +5,10 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskAdvanceDebt : TaskBase { - public TaskAdvanceDebt(decimal debt) - : base( - 0, debt.ToString("N2", CultureInfo.InvariantCulture), DateTime.Now, - DateTime.Now.AddDays(28)) + public TaskAdvanceDebt (decimal debt) + : base ( + 0, debt.ToString ("N2", CultureInfo.InvariantCulture), DateTime.Now, + DateTime.Now.AddDays (28)) { // empty ctor } diff --git a/Logic/DashboardTasks/TaskAttestationLate.cs b/Logic/DashboardTasks/TaskAttestationLate.cs index 21ee1b33..2fc3f1f8 100644 --- a/Logic/DashboardTasks/TaskAttestationLate.cs +++ b/Logic/DashboardTasks/TaskAttestationLate.cs @@ -4,8 +4,8 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskAttestationLate : TaskBase { - public TaskAttestationLate(InboundInvoice invoice) - : base(invoice.Identity, "Invoice #" + invoice.Identity, invoice.CreatedDateTime, invoice.DueDate) + public TaskAttestationLate (InboundInvoice invoice) + : base (invoice.Identity, "Invoice #" + invoice.Identity, invoice.CreatedDateTime, invoice.DueDate) { } } diff --git a/Logic/DashboardTasks/TaskBase.cs b/Logic/DashboardTasks/TaskBase.cs index 11abdb07..fa81d44c 100644 --- a/Logic/DashboardTasks/TaskBase.cs +++ b/Logic/DashboardTasks/TaskBase.cs @@ -4,7 +4,7 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskBase { - public TaskBase(int identity, string description, DateTime opened, DateTime expires) + public TaskBase (int identity, string description, DateTime opened, DateTime expires) { Identity = identity; Description = description; diff --git a/Logic/DashboardTasks/TaskExpenseClaim.cs b/Logic/DashboardTasks/TaskExpenseClaim.cs index 08ae6f56..c5a31f91 100644 --- a/Logic/DashboardTasks/TaskExpenseClaim.cs +++ b/Logic/DashboardTasks/TaskExpenseClaim.cs @@ -4,10 +4,10 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskExpenseClaim : TaskBase { - public TaskExpenseClaim(ExpenseClaim claim) - : base( + public TaskExpenseClaim (ExpenseClaim claim) + : base ( claim.Identity, "Expense Claim #" + claim.Identity, claim.CreatedDateTime, - claim.CreatedDateTime.AddDays(14)) + claim.CreatedDateTime.AddDays (14)) { // empty ctor } diff --git a/Logic/DashboardTasks/TaskGroup.cs b/Logic/DashboardTasks/TaskGroup.cs index 6dd57b48..44672e11 100644 --- a/Logic/DashboardTasks/TaskGroup.cs +++ b/Logic/DashboardTasks/TaskGroup.cs @@ -79,7 +79,7 @@ namespace Swarmops.Logic.DashboardTasks lookupDescriptionMany[TaskGroupType.AttestationWarning] = "Attestations for invoices {0} are running late"; } - public TaskGroup(TaskGroupType type) + public TaskGroup (TaskGroupType type) { Type = type; Tasks = new List(); @@ -104,16 +104,16 @@ namespace Swarmops.Logic.DashboardTasks { if (Type == TaskGroupType.DeclareAdvanceDebts) { - return String.Format(lookupDescriptionSingle[TaskGroupType.DeclareAdvanceDebts], + return String.Format (lookupDescriptionSingle[TaskGroupType.DeclareAdvanceDebts], Tasks[0].Description); } - if (this.Type == TaskGroupType.AttestationWarning) + if (Type == TaskGroupType.AttestationWarning) { List identities = new List(); - foreach (TaskBase item in this.Tasks) + foreach (TaskBase item in Tasks) { - identities.Add(item.Identity); + identities.Add (item.Identity); } identities.Sort(); @@ -122,13 +122,13 @@ namespace Swarmops.Logic.DashboardTasks ? lookupDescriptionMany[TaskGroupType.AttestationWarning] : lookupDescriptionSingle[TaskGroupType.AttestationWarning]; - return String.Format(baseString, Formatting.GenerateRangeString(identities)); + return String.Format (baseString, Formatting.GenerateRangeString (identities)); } - if (this.Tasks.Count > 1) + if (Tasks.Count > 1) { - return String.Format(lookupDescriptionMany[this.Type], this.Tasks.Count); + return String.Format (lookupDescriptionMany[Type], Tasks.Count); } - return lookupDescriptionSingle[this.Type]; + return lookupDescriptionSingle[Type]; } } } diff --git a/Logic/DashboardTasks/TaskInboundInvoice.cs b/Logic/DashboardTasks/TaskInboundInvoice.cs index ec814efa..16d3cbf0 100644 --- a/Logic/DashboardTasks/TaskInboundInvoice.cs +++ b/Logic/DashboardTasks/TaskInboundInvoice.cs @@ -4,10 +4,10 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskInboundInvoice : TaskBase { - public TaskInboundInvoice(InboundInvoice invoice) - : base( + public TaskInboundInvoice (InboundInvoice invoice) + : base ( invoice.Identity, "Inbound Invoice #" + invoice.Identity, invoice.CreatedDateTime, - invoice.DueDate.AddDays(-7)) + invoice.DueDate.AddDays (-7)) { // empty ctor } diff --git a/Logic/DashboardTasks/TaskPayout.cs b/Logic/DashboardTasks/TaskPayout.cs index 06783aa3..31569a68 100644 --- a/Logic/DashboardTasks/TaskPayout.cs +++ b/Logic/DashboardTasks/TaskPayout.cs @@ -5,8 +5,8 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskPayout : TaskBase { - public TaskPayout(Payout payout) - : base(payout.Identity, "Payout #" + payout.Identity, DateTime.Now, payout.ExpectedTransactionDate) + public TaskPayout (Payout payout) + : base (payout.Identity, "Payout #" + payout.Identity, DateTime.Now, payout.ExpectedTransactionDate) { } } diff --git a/Logic/DashboardTasks/TaskReceiptValidation.cs b/Logic/DashboardTasks/TaskReceiptValidation.cs index 14715d16..661031e8 100644 --- a/Logic/DashboardTasks/TaskReceiptValidation.cs +++ b/Logic/DashboardTasks/TaskReceiptValidation.cs @@ -4,10 +4,10 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskReceiptValidation : TaskBase { - public TaskReceiptValidation(ExpenseClaim claim) - : base( + public TaskReceiptValidation (ExpenseClaim claim) + : base ( claim.Identity, "Expense Claim #" + claim.Identity, claim.CreatedDateTime, - claim.CreatedDateTime.AddDays(14)) + claim.CreatedDateTime.AddDays (14)) { // empty ctor } diff --git a/Logic/DashboardTasks/TaskSalary.cs b/Logic/DashboardTasks/TaskSalary.cs index a60efa2c..14297365 100644 --- a/Logic/DashboardTasks/TaskSalary.cs +++ b/Logic/DashboardTasks/TaskSalary.cs @@ -4,11 +4,11 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskSalary : TaskBase { - public TaskSalary(Salary salary) - : base( + public TaskSalary (Salary salary) + : base ( salary.Identity, - salary.PayoutDate.ToString("yyyy-MMM") + " salary for " + salary.PayrollItem.PersonCanonical, - salary.PayoutDate.AddDays(-(salary.PayoutDate.Day - 1)), salary.PayoutDate.AddDays(-7)) + salary.PayoutDate.ToString ("yyyy-MMM") + " salary for " + salary.PayrollItem.PersonCanonical, + salary.PayoutDate.AddDays (-(salary.PayoutDate.Day - 1)), salary.PayoutDate.AddDays (-7)) { // empty ctor } diff --git a/Logic/DashboardTasks/TaskVolunteer.cs b/Logic/DashboardTasks/TaskVolunteer.cs index 9ac2ff8c..6e814938 100644 --- a/Logic/DashboardTasks/TaskVolunteer.cs +++ b/Logic/DashboardTasks/TaskVolunteer.cs @@ -4,10 +4,10 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskVolunteer : TaskBase { - public TaskVolunteer(Volunteer volunteer) - : base( + public TaskVolunteer (Volunteer volunteer) + : base ( volunteer.Identity, "Volunteer " + volunteer.Name, volunteer.OpenedDateTime, - volunteer.OpenedDateTime.AddDays(21)) + volunteer.OpenedDateTime.AddDays (21)) { // empty ctor } diff --git a/Logic/DashboardTasks/Tasks.cs b/Logic/DashboardTasks/Tasks.cs index 62eb7469..2b50c957 100644 --- a/Logic/DashboardTasks/Tasks.cs +++ b/Logic/DashboardTasks/Tasks.cs @@ -10,25 +10,25 @@ namespace Swarmops.Logic.DashboardTasks { public class Tasks : List { - public static Tasks ForPersonOrganization(Person person, Organization organization) + public static Tasks ForPersonOrganization (Person person, Organization organization) { Tasks tasks = new Tasks(); - tasks.AddVolunteers(person, organization); - tasks.AddExpenseClaims(person, organization); - tasks.AddSalaries(person, organization); - tasks.AddInboundInvoices(person, organization); - tasks.AddReceiptValidation(person, organization); - tasks.AddAdvanceDebts(person, organization); - tasks.AddPayouts(person, organization); - tasks.AddAttestationWarnings(person, organization); + tasks.AddVolunteers (person, organization); + tasks.AddExpenseClaims (person, organization); + tasks.AddSalaries (person, organization); + tasks.AddInboundInvoices (person, organization); + tasks.AddReceiptValidation (person, organization); + tasks.AddAdvanceDebts (person, organization); + tasks.AddPayouts (person, organization); + tasks.AddAttestationWarnings (person, organization); return tasks; } - private void AddVolunteers(Person person, Organization organization) + private void AddVolunteers (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.Volunteers); + TaskGroup group = new TaskGroup (TaskGroupType.Volunteers); Volunteers volunteers = Volunteers.GetOpen(); @@ -36,23 +36,23 @@ namespace Swarmops.Logic.DashboardTasks { if (volunteer.Owner.Identity == person.Identity) { - group.Tasks.Add(new TaskVolunteer(volunteer)); + group.Tasks.Add (new TaskVolunteer (volunteer)); } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } - private void AddExpenseClaims(Person person, Organization organization) + private void AddExpenseClaims (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.AttestExpenseClaims); + TaskGroup group = new TaskGroup (TaskGroupType.AttestExpenseClaims); // TODO: Loop over roles, get all open claims for roles where person can attest - ExpenseClaims claims = ExpenseClaims.ForOrganization(organization); + ExpenseClaims claims = ExpenseClaims.ForOrganization (organization); foreach (ExpenseClaim claim in claims) { @@ -60,7 +60,7 @@ namespace Swarmops.Logic.DashboardTasks { if (claim.Budget.OwnerPersonId == person.Identity && !claim.Attested) { - group.Tasks.Add(new TaskExpenseClaim(claim)); + group.Tasks.Add (new TaskExpenseClaim (claim)); } } catch (Exception) @@ -71,93 +71,93 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } - private void AddSalaries(Person person, Organization organization) + private void AddSalaries (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.AttestSalaries); + TaskGroup group = new TaskGroup (TaskGroupType.AttestSalaries); // TODO: Loop over roles, get all open claims for roles where person can attest - Salaries salaries = Salaries.ForOrganization(organization); + Salaries salaries = Salaries.ForOrganization (organization); foreach (Salary salary in salaries) { if (salary.AttestationExpectedBy.Identity == person.Identity && !salary.Attested) { - group.Tasks.Add(new TaskSalary(salary)); + group.Tasks.Add (new TaskSalary (salary)); } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } - private void AddInboundInvoices(Person person, Organization organization) + private void AddInboundInvoices (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.AttestInvoices); + TaskGroup group = new TaskGroup (TaskGroupType.AttestInvoices); // TODO: Loop over roles, get all open claims for roles where person can attest - InboundInvoices invoices = InboundInvoices.ForOrganization(organization); + InboundInvoices invoices = InboundInvoices.ForOrganization (organization); foreach (InboundInvoice invoice in invoices) { if (invoice.Budget.OwnerPersonId == person.Identity && !invoice.Attested) { - group.Tasks.Add(new TaskInboundInvoice(invoice)); + group.Tasks.Add (new TaskInboundInvoice (invoice)); } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } - private void AddReceiptValidation(Person person, Organization organization) + private void AddReceiptValidation (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.ValidateExpenseClaims); + TaskGroup group = new TaskGroup (TaskGroupType.ValidateExpenseClaims); // TODO: Loop over roles, get all open claims for roles where person can attest if ( !person.GetAuthority() - .HasPermission(Permission.CanDoEconomyTransactions, organization.Identity, Geography.RootIdentity, + .HasPermission (Permission.CanDoEconomyTransactions, organization.Identity, Geography.RootIdentity, Authorization.Flag.AnyGeographyExactOrganization)) { // no permission, no tasks return; } - ExpenseClaims claims = ExpenseClaims.ForOrganization(organization); + ExpenseClaims claims = ExpenseClaims.ForOrganization (organization); foreach (ExpenseClaim claim in claims) { if (!claim.Validated) { - group.Tasks.Add(new TaskReceiptValidation(claim)); + group.Tasks.Add (new TaskReceiptValidation (claim)); } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } - private void AddAdvanceDebts(Person person, Organization organization) + private void AddAdvanceDebts (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.DeclareAdvanceDebts); + TaskGroup group = new TaskGroup (TaskGroupType.DeclareAdvanceDebts); // TODO: One task group for each organization, actually - ExpenseClaims claims = ExpenseClaims.FromClaimingPersonAndOrganization(person, organization); + ExpenseClaims claims = ExpenseClaims.FromClaimingPersonAndOrganization (person, organization); decimal debt = 0.0m; @@ -171,89 +171,89 @@ namespace Swarmops.Logic.DashboardTasks if (debt > 0.0m) { - group.Tasks.Add(new TaskAdvanceDebt(debt)); - Add(group); + group.Tasks.Add (new TaskAdvanceDebt (debt)); + Add (group); } } - private void AddPayouts(Person person, Organization organization) + private void AddPayouts (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.Payout); - TaskGroup groupUrgent = new TaskGroup(TaskGroupType.PayoutUrgently); - TaskGroup groupOverdue = new TaskGroup(TaskGroupType.PayoutOverdue); + TaskGroup group = new TaskGroup (TaskGroupType.Payout); + TaskGroup groupUrgent = new TaskGroup (TaskGroupType.PayoutUrgently); + TaskGroup groupOverdue = new TaskGroup (TaskGroupType.PayoutOverdue); if ( !person.GetAuthority() - .HasPermission(Permission.CanPayOutMoney, organization.Identity, 1, + .HasPermission (Permission.CanPayOutMoney, organization.Identity, 1, Authorization.Flag.AnyGeographyExactOrganization)) { return; } - Payouts payouts = Payouts.Construct(organization); + Payouts payouts = Payouts.Construct (organization); foreach (Payout payout in payouts) { - group.Tasks.Add(new TaskPayout(payout)); + group.Tasks.Add (new TaskPayout (payout)); if (payout.DependentInvoices.Count > 0) { if (payout.ExpectedTransactionDate < DateTime.Today) { - groupOverdue.Tasks.Add(new TaskPayout(payout)); + groupOverdue.Tasks.Add (new TaskPayout (payout)); } - else if (payout.ExpectedTransactionDate < DateTime.Today.AddDays(7)) + else if (payout.ExpectedTransactionDate < DateTime.Today.AddDays (7)) { - groupUrgent.Tasks.Add(new TaskPayout(payout)); + groupUrgent.Tasks.Add (new TaskPayout (payout)); } } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } if (groupUrgent.Tasks.Count > 0) { - Add(groupUrgent); + Add (groupUrgent); } if (groupOverdue.Tasks.Count > 0) { - Add(groupOverdue); + Add (groupOverdue); } } - private void AddAttestationWarnings(Person person, Organization organization) + private void AddAttestationWarnings (Person person, Organization organization) { - TaskGroup group = new TaskGroup(TaskGroupType.AttestationWarning); + TaskGroup group = new TaskGroup (TaskGroupType.AttestationWarning); if ( !person.GetAuthority() - .HasPermission(Permission.CanSeeEconomyTransactions, organization.Identity, 1, + .HasPermission (Permission.CanSeeEconomyTransactions, organization.Identity, 1, Authorization.Flag.AnyGeographyExactOrganization)) { return; } - InboundInvoices invoices = InboundInvoices.ForOrganization(organization); + InboundInvoices invoices = InboundInvoices.ForOrganization (organization); - DateTime threshold = DateTime.Today.AddDays(10); + DateTime threshold = DateTime.Today.AddDays (10); foreach (InboundInvoice invoice in invoices) { if (invoice.DueDate < threshold && !invoice.Attested) { - group.Tasks.Add(new TaskAttestationLate(invoice)); + group.Tasks.Add (new TaskAttestationLate (invoice)); } } if (group.Tasks.Count > 0) { - Add(group); + Add (group); } } } diff --git a/Logic/DataObjects/ExpensesDataObject.cs b/Logic/DataObjects/ExpensesDataObject.cs index 51f00222..44c92886 100644 --- a/Logic/DataObjects/ExpensesDataObject.cs +++ b/Logic/DataObjects/ExpensesDataObject.cs @@ -6,63 +6,63 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class ExpensesDataObject { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectByClaimer(int personId) + public static ExpenseClaim[] SelectByClaimer (int personId) { - return ExpenseClaims.FromClaimingPerson(Person.FromIdentity(personId)).ToArray(); + return ExpenseClaims.FromClaimingPerson (Person.FromIdentity (personId)).ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectOpenByClaimer(int personId) + public static ExpenseClaim[] SelectOpenByClaimer (int personId) { - return ExpenseClaims.FromClaimingPerson(Person.FromIdentity(personId)).WhereOpen.ToArray(); + return ExpenseClaims.FromClaimingPerson (Person.FromIdentity (personId)).WhereOpen.ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectByClaimer(Person person) + public static ExpenseClaim[] SelectByClaimer (Person person) { - return SelectByClaimer(person.Identity); + return SelectByClaimer (person.Identity); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectOpenByClaimer(Person person) + public static ExpenseClaim[] SelectOpenByClaimer (Person person) { - return SelectOpenByClaimer(person.Identity); + return SelectOpenByClaimer (person.Identity); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectByOrganization(int organizationId) + public static ExpenseClaim[] SelectByOrganization (int organizationId) { - return ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)).ToArray(); + return ExpenseClaims.FromOrganization (Organization.FromIdentity (organizationId)).ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectUnapprovedByOrganization(int organizationId) + public static ExpenseClaim[] SelectUnapprovedByOrganization (int organizationId) { - return ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)).WhereUnapproved.ToArray(); + return ExpenseClaims.FromOrganization (Organization.FromIdentity (organizationId)).WhereUnapproved.ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static ExpenseClaim[] SelectStatic(ExpenseClaims expenseClaims) + public static ExpenseClaim[] SelectStatic (ExpenseClaims expenseClaims) { return expenseClaims.ToArray(); } diff --git a/Logic/DataObjects/GeographyWithPeopleDataObject.cs b/Logic/DataObjects/GeographyWithPeopleDataObject.cs index 0e7a3a89..a868752d 100644 --- a/Logic/DataObjects/GeographyWithPeopleDataObject.cs +++ b/Logic/DataObjects/GeographyWithPeopleDataObject.cs @@ -6,16 +6,16 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class GeographyWithPeopleDataObject { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static GeographyWithPeople[] SelectSortedStatic(int orgId) + public static GeographyWithPeople[] SelectSortedStatic (int orgId) { - Organizations orgs = Organization.FromIdentity(orgId).GetTree(); + Organizations orgs = Organization.FromIdentity (orgId).GetTree(); List resList = new List(); Geographies tree = Geography.Root.GetTree(); @@ -31,7 +31,7 @@ namespace Swarmops.Logic.DataObjects row.OrgId = orgId; Geographies gTree = geo.GetTree(); int[] members = SwarmDb.GetDatabaseForReading() - .GetMembersForOrganizationsAndGeographies(orgs.Identities, gTree.Identities); + .GetMembersForOrganizationsAndGeographies (orgs.Identities, gTree.Identities); } diff --git a/Logic/DataObjects/MembershipsDataObject.cs b/Logic/DataObjects/MembershipsDataObject.cs index 3cdc2180..b78941e4 100644 --- a/Logic/DataObjects/MembershipsDataObject.cs +++ b/Logic/DataObjects/MembershipsDataObject.cs @@ -5,32 +5,32 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class MembershipsDataObject { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Membership[] Select(int personId) + public static Membership[] Select (int personId) { return - Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(Person.FromIdentity(personId))) + Memberships.FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (Person.FromIdentity (personId))) .ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Membership[] Select(Person person) + public static Membership[] Select (Person person) { - return Select(person.Identity); + return Select (person.Identity); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Membership[] SelectStatic(Memberships memberships) + public static Membership[] SelectStatic (Memberships memberships) { return memberships.ToArray(); } diff --git a/Logic/DataObjects/OrganizationDataObject.cs b/Logic/DataObjects/OrganizationDataObject.cs index a64772f9..bafd8cef 100644 --- a/Logic/DataObjects/OrganizationDataObject.cs +++ b/Logic/DataObjects/OrganizationDataObject.cs @@ -7,7 +7,7 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class OrganizationsDataObject { @@ -19,12 +19,12 @@ namespace Swarmops.Logic.DataObjects { } - public Org(Organization org) - : base(org) + public Org (Organization org) + : base (org) { try { - ParentName = FromIdentity(ParentOrganizationId).Name; + ParentName = FromIdentity (ParentOrganizationId).Name; } catch { @@ -32,7 +32,7 @@ namespace Swarmops.Logic.DataObjects } try { - AnchorName = Geography.FromIdentity(AnchorGeographyId).Name; + AnchorName = Geography.FromIdentity (AnchorGeographyId).Name; } catch { @@ -140,19 +140,19 @@ namespace Swarmops.Logic.DataObjects { } - public UptakeGeography(Structure.UptakeGeography other) - : base(other) + public UptakeGeography (Structure.UptakeGeography other) + : base (other) { } - internal static UptakeGeography fromUptake(Structure.UptakeGeography up) + internal static UptakeGeography fromUptake (Structure.UptakeGeography up) { - return new UptakeGeography(up); + return new UptakeGeography (up); } } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select, true)] + [DataObjectMethod (DataObjectMethodType.Select, true)] #endif public static Org[] Select() { @@ -161,20 +161,20 @@ namespace Swarmops.Logic.DataObjects Organizations orgs = Organizations.GetAll(); foreach (Organization org in orgs) { - res.Add(new Org(org)); + res.Add (new Org (org)); } return res.ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select, true)] + [DataObjectMethod (DataObjectMethodType.Select, true)] #endif - public static Org Select(int orgid) + public static Org Select (int orgid) { try { - return new Org(Organization.FromIdentity(orgid)); + return new Org (Organization.FromIdentity (orgid)); } catch { @@ -183,22 +183,22 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Organization[] Select(int[] OrganizationIds) + public static Organization[] Select (int[] OrganizationIds) { if (OrganizationIds == null) { return new Organization[0]; } - return Organizations.FromIdentities(OrganizationIds).ToArray(); + return Organizations.FromIdentities (OrganizationIds).ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Organization[] SelectStatic(Organization[] OrganizationArray) + public static Organization[] SelectStatic (Organization[] OrganizationArray) { if (OrganizationArray == null) { @@ -209,9 +209,9 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Organization[] SelectStatic(Organizations Organizations) + public static Organization[] SelectStatic (Organizations Organizations) { if (Organizations == null) { @@ -223,9 +223,9 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Organization[] SelectSortedStatic(Organizations Organizations, string sort) + public static Organization[] SelectSortedStatic (Organizations Organizations, string sort) { if (Organizations == null) { @@ -234,16 +234,16 @@ namespace Swarmops.Logic.DataObjects List pList = new List(); - Organization[] foundOrganizations = SelectStatic(Organizations); + Organization[] foundOrganizations = SelectStatic (Organizations); foreach (Organization pers in foundOrganizations) { - pList.Add(pers); + pList.Add (pers); } switch (sort) { case "OrganizationId": - pList.Sort(IdentityComparison); + pList.Sort (IdentityComparison); break; } @@ -252,19 +252,19 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Insert, true)] + [DataObjectMethod (DataObjectMethodType.Insert, true)] #endif - public int AddOrganization(Org org) + public int AddOrganization (Org org) { try { - org.DefaultCountryId = Country.FromCode(org.CountryCode).CountryId; + org.DefaultCountryId = Country.FromCode (org.CountryCode).CountryId; } catch { - org.DefaultCountryId = FindDefaultCountry(org); + org.DefaultCountryId = FindDefaultCountry (org); } - org.Identity = Organization.Create(org.ParentOrganizationId, org.NameInternational, + org.Identity = Organization.Create (org.ParentOrganizationId, org.NameInternational, org.Name, org.NameShort, org.Domain, org.MailPrefix, org.AnchorGeographyId, org.AcceptsMembers, org.AutoAssignNewMembers, org.DefaultCountryId).Identity; // Return true if precisely one row was inserted, otherwise false @@ -272,30 +272,30 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Update, false)] + [DataObjectMethod (DataObjectMethodType.Update, false)] #endif - public int AddDuplicateOrganization(Org org) + public int AddDuplicateOrganization (Org org) { - AddOrganization(org); + AddOrganization (org); return org.Identity; } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Update, true)] + [DataObjectMethod (DataObjectMethodType.Update, true)] #endif - public bool UpdateOrganisation(Org org) + public bool UpdateOrganisation (Org org) { try { try { - org.DefaultCountryId = Country.FromCode(org.CountryCode).CountryId; + org.DefaultCountryId = Country.FromCode (org.CountryCode).CountryId; } catch { - org.DefaultCountryId = FindDefaultCountry(org); + org.DefaultCountryId = FindDefaultCountry (org); } - Organization.UpdateOrganization(org.ParentOrganizationId, org.NameInternational, + Organization.UpdateOrganization (org.ParentOrganizationId, org.NameInternational, org.Name, org.NameShort, org.Domain, org.MailPrefix, org.AnchorGeographyId, org.AcceptsMembers, org.AutoAssignNewMembers, org.DefaultCountryId, org.Identity); @@ -304,17 +304,17 @@ namespace Swarmops.Logic.DataObjects } catch (Exception ex) { - HttpContext.Current.Response.Write("Failed Update:" + ex.Message); - throw new Exception("UpdateOrganisation failed because:" + ex.Message); + HttpContext.Current.Response.Write ("Failed Update:" + ex.Message); + throw new Exception ("UpdateOrganisation failed because:" + ex.Message); } } - private static int FindDefaultCountry(Org org) + private static int FindDefaultCountry (Org org) { //Find default country = Country of anchor. - Geographies line = Geography.FromIdentity(org.AnchorGeographyId).GetLine(); + Geographies line = Geography.FromIdentity (org.AnchorGeographyId).GetLine(); Geography[] arrLine = line.ToArray(); - Array.Reverse(arrLine); + Array.Reverse (arrLine); Countries countries = Countries.GetAll(); int foundCntry = 1; //sweden foreach (Geography geo in arrLine) @@ -335,32 +335,32 @@ namespace Swarmops.Logic.DataObjects public static Comparison IdentityComparison = - delegate(Organization p1, Organization p2) { return p1.OrganizationId.CompareTo(p2.OrganizationId); }; + delegate (Organization p1, Organization p2) { return p1.OrganizationId.CompareTo (p2.OrganizationId); }; ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// - private static UptakeGeography[] UptakeFromArray(Structure.UptakeGeography[] inputArray) + private static UptakeGeography[] UptakeFromArray (Structure.UptakeGeography[] inputArray) { List retlist = new List(); foreach (Structure.UptakeGeography up in inputArray) { - retlist.Add(UptakeGeography.fromUptake(up)); + retlist.Add (UptakeGeography.fromUptake (up)); } return retlist.ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select, false)] + [DataObjectMethod (DataObjectMethodType.Select, false)] #endif - public static UptakeGeography[] SelectOrgMineUptake(int orgid) + public static UptakeGeography[] SelectOrgMineUptake (int orgid) { try { - return UptakeFromArray(Organization.FromIdentity(orgid).GetUptakeGeographies(false)); + return UptakeFromArray (Organization.FromIdentity (orgid).GetUptakeGeographies (false)); } catch { @@ -369,13 +369,13 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select, false)] + [DataObjectMethod (DataObjectMethodType.Select, false)] #endif - public static UptakeGeography[] SelectOrgOthersUptake(int orgid) + public static UptakeGeography[] SelectOrgOthersUptake (int orgid) { try { - return UptakeFromArray(Organization.FromIdentity(orgid).GetUptakeGeographies(true)); + return UptakeFromArray (Organization.FromIdentity (orgid).GetUptakeGeographies (true)); } catch { @@ -384,19 +384,19 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select, false)] + [DataObjectMethod (DataObjectMethodType.Select, false)] #endif - public static UptakeGeography[] SelectOrgOthersUptakeForGeo(int orgid, int geoid) + public static UptakeGeography[] SelectOrgOthersUptakeForGeo (int orgid, int geoid) { try { List filtered = new List(); UptakeGeography[] unfiltered = - UptakeFromArray(Organization.FromIdentity(orgid).GetUptakeGeographies(true)); + UptakeFromArray (Organization.FromIdentity (orgid).GetUptakeGeographies (true)); foreach (UptakeGeography bu in unfiltered) { if (bu.GeoId == geoid) - filtered.Add(bu); + filtered.Add (bu); } return filtered.ToArray(); } @@ -406,28 +406,28 @@ namespace Swarmops.Logic.DataObjects } } - public static void UpdateOrgUptake(int orgid, int[] newUptakeGeos) + public static void UpdateOrgUptake (int orgid, int[] newUptakeGeos) { try { - Organization org = Organization.FromIdentity(orgid); + Organization org = Organization.FromIdentity (orgid); List inOld = new List(); foreach (Geography oldGeo in org.UptakeGeographies) { - if (Array.IndexOf(newUptakeGeos, oldGeo.Identity) > -1) + if (Array.IndexOf (newUptakeGeos, oldGeo.Identity) > -1) { - inOld.Add(oldGeo.Identity); + inOld.Add (oldGeo.Identity); } else { - org.DeleteUptakeGeography(oldGeo.Identity); + org.DeleteUptakeGeography (oldGeo.Identity); } } foreach (int newgeo in newUptakeGeos) { - if (!inOld.Contains(newgeo)) + if (!inOld.Contains (newgeo)) { - org.AddUptakeGeography(newgeo); + org.AddUptakeGeography (newgeo); } } } @@ -438,23 +438,23 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Delete, false)] + [DataObjectMethod (DataObjectMethodType.Delete, false)] #endif - public bool DeleteUptake(UptakeGeography ut) + public bool DeleteUptake (UptakeGeography ut) { - Organization org = Organization.FromIdentity(ut.OrgId); - org.DeleteUptakeGeography(ut.GeoId); + Organization org = Organization.FromIdentity (ut.OrgId); + org.DeleteUptakeGeography (ut.GeoId); return true; } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Insert, false)] + [DataObjectMethod (DataObjectMethodType.Insert, false)] #endif - public bool AddUptake(UptakeGeography ut) + public bool AddUptake (UptakeGeography ut) { - Organization org = Organization.FromIdentity(ut.OrgId); - org.AddUptakeGeography(ut.GeoId); + Organization org = Organization.FromIdentity (ut.OrgId); + org.AddUptakeGeography (ut.GeoId); // Return true if precisely one row was inserted, otherwise false return true; diff --git a/Logic/DataObjects/PeopleDataObject.cs b/Logic/DataObjects/PeopleDataObject.cs index 98f2cac2..fb180108 100644 --- a/Logic/DataObjects/PeopleDataObject.cs +++ b/Logic/DataObjects/PeopleDataObject.cs @@ -6,27 +6,27 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class PeopleDataObject { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Person[] Select(int[] personIds) + public static Person[] Select (int[] personIds) { if (personIds == null) { return new Person[0]; } - return People.FromIdentities(personIds).ToArray(); + return People.FromIdentities (personIds).ToArray(); } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Person[] SelectStatic(Person[] personArray) + public static Person[] SelectStatic (Person[] personArray) { if (personArray == null) { @@ -37,9 +37,9 @@ namespace Swarmops.Logic.DataObjects } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Person[] SelectStatic(People people) + public static Person[] SelectStatic (People people) { if (people == null) { @@ -51,9 +51,9 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static Person[] SelectSortedStatic(People people, string sort) + public static Person[] SelectSortedStatic (People people, string sort) { if (people == null) { @@ -62,36 +62,36 @@ namespace Swarmops.Logic.DataObjects List pList = new List(); - Person[] foundPersons = SelectStatic(people); + Person[] foundPersons = SelectStatic (people); foreach (Person pers in foundPersons) { - pList.Add(pers); + pList.Add (pers); } switch (sort) { case "PersonId": - pList.Sort(PersonIdComparison); + pList.Sort (PersonIdComparison); break; case "Name": - pList.Sort(NameComparison); + pList.Sort (NameComparison); break; case "PostalCode": - pList.Sort(PostalCodeComparison); + pList.Sort (PostalCodeComparison); break; case "CityName": - pList.Sort(CityComparison); + pList.Sort (CityComparison); break; case "Birthdate": - pList.Sort(BirthdateComparison); + pList.Sort (BirthdateComparison); break; // New sortexpressions case "Email": - pList.Sort(EmailComparison); + pList.Sort (EmailComparison); break; case "Phone": - pList.Sort(PhoneComparison); + pList.Sort (PhoneComparison); break; } @@ -99,44 +99,44 @@ namespace Swarmops.Logic.DataObjects } public static Comparison PersonIdComparison = - delegate(Person p1, Person p2) { return p1.PersonId.CompareTo(p2.PersonId); }; + delegate (Person p1, Person p2) { return p1.PersonId.CompareTo (p2.PersonId); }; public static Comparison NameComparison = - delegate(Person p1, Person p2) { return p1.Name.CompareTo(p2.Name); }; + delegate (Person p1, Person p2) { return p1.Name.CompareTo (p2.Name); }; - public static Comparison CityComparison = delegate(Person p1, Person p2) + public static Comparison CityComparison = delegate (Person p1, Person p2) { - int cmpRes = p1.CityName.CompareTo(p2.CityName); + int cmpRes = p1.CityName.CompareTo (p2.CityName); if (cmpRes == 0) - cmpRes = p1.Name.CompareTo(p2.Name); + cmpRes = p1.Name.CompareTo (p2.Name); return cmpRes; }; - public static Comparison PostalCodeComparison = delegate(Person p1, Person p2) + public static Comparison PostalCodeComparison = delegate (Person p1, Person p2) { - int cmpRes = p1.PostalCode.CompareTo(p2.PostalCode); + int cmpRes = p1.PostalCode.CompareTo (p2.PostalCode); if (cmpRes == 0) - cmpRes = p1.Name.CompareTo(p2.Name); + cmpRes = p1.Name.CompareTo (p2.Name); return cmpRes; }; public static Comparison BirthdateComparison = - delegate(Person p1, Person p2) { return p1.Birthdate.CompareTo(p2.Birthdate); }; + delegate (Person p1, Person p2) { return p1.Birthdate.CompareTo (p2.Birthdate); }; // Added for more sorting opportunities - public static Comparison EmailComparison = delegate(Person p1, Person p2) + public static Comparison EmailComparison = delegate (Person p1, Person p2) { - int cmpRes = p1.Mail.CompareTo(p2.Mail); + int cmpRes = p1.Mail.CompareTo (p2.Mail); if (cmpRes == 0) - cmpRes = p1.Name.CompareTo(p2.Name); + cmpRes = p1.Name.CompareTo (p2.Name); return cmpRes; }; - public static Comparison PhoneComparison = delegate(Person p1, Person p2) + public static Comparison PhoneComparison = delegate (Person p1, Person p2) { - int cmpRes = p1.Phone.CompareTo(p2.Phone); + int cmpRes = p1.Phone.CompareTo (p2.Phone); if (cmpRes == 0) - cmpRes = p1.Name.CompareTo(p2.Name); + cmpRes = p1.Name.CompareTo (p2.Name); return cmpRes; }; } diff --git a/Logic/DataObjects/RolesDataObject.cs b/Logic/DataObjects/RolesDataObject.cs index 2b365bd7..1df62497 100644 --- a/Logic/DataObjects/RolesDataObject.cs +++ b/Logic/DataObjects/RolesDataObject.cs @@ -9,16 +9,16 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject (true)] #endif public class RolesDataObject { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static BasicPersonRole[] Select(int personId, RoleClass roleClass) + public static BasicPersonRole[] Select (int personId, RoleClass roleClass) { - BasicAuthority authority = Authorization.GetPersonAuthority(personId); + BasicAuthority authority = Authorization.GetPersonAuthority (personId); switch (roleClass) { @@ -32,16 +32,16 @@ namespace Swarmops.Logic.DataObjects return authority.LocalPersonRoles; default: - throw new InvalidOperationException("Undefined RoleClass in RolesDataObject.Select: " + roleClass); + throw new InvalidOperationException ("Undefined RoleClass in RolesDataObject.Select: " + roleClass); } } #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod (DataObjectMethodType.Select)] #endif - public static BasicPersonRole[] Select(Person person, RoleClass roleClass) + public static BasicPersonRole[] Select (Person person, RoleClass roleClass) { - return Select(person.Identity, roleClass); + return Select (person.Identity, roleClass); } } } \ No newline at end of file diff --git a/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs b/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs index 1ae3471f..fc2d2fe1 100644 --- a/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs +++ b/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial.BankDataReaders { public class TabSeparatedValuesReader : IBankDataAccountStatementReader { - public ImportedBankData ReadData(StreamReader data, FinancialAccount account, ExternalBankDataProfile profile) + public ImportedBankData ReadData (StreamReader data, FinancialAccount account, ExternalBankDataProfile profile) { throw new NotImplementedException(); } diff --git a/Logic/Financial/CashAdvance.cs b/Logic/Financial/CashAdvance.cs index fd28e415..945fdc78 100644 --- a/Logic/Financial/CashAdvance.cs +++ b/Logic/Financial/CashAdvance.cs @@ -16,40 +16,40 @@ namespace Swarmops.Logic.Financial { #region Construction and creation - private CashAdvance(BasicCashAdvance basic) : base(basic) + private CashAdvance (BasicCashAdvance basic) : base (basic) { } - public static CashAdvance FromBasic(BasicCashAdvance basic) + public static CashAdvance FromBasic (BasicCashAdvance basic) { - return new CashAdvance(basic); + return new CashAdvance (basic); } - public static CashAdvance FromIdentity(int cashAdvanceId) + public static CashAdvance FromIdentity (int cashAdvanceId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCashAdvance(cashAdvanceId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCashAdvance (cashAdvanceId)); } - public static CashAdvance FromIdentityAggressive(int cashAdvanceId) + public static CashAdvance FromIdentityAggressive (int cashAdvanceId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetCashAdvance(cashAdvanceId)); + return FromBasic (SwarmDb.GetDatabaseForWriting().GetCashAdvance (cashAdvanceId)); } - public static CashAdvance Create(Organization organization, Person forPerson, Person createdByPerson, + public static CashAdvance Create (Organization organization, Person forPerson, Person createdByPerson, Int64 amountCents, FinancialAccount budget, string description) { CashAdvance newAdvance = - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreateCashAdvance(forPerson.Identity, + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting().CreateCashAdvance (forPerson.Identity, createdByPerson.Identity, organization.Identity, budget.Identity, amountCents, description)); - OutboundComm.CreateNotificationAttestationNeeded(budget, forPerson, string.Empty, amountCents/100.0, + OutboundComm.CreateNotificationAttestationNeeded (budget, forPerson, string.Empty, amountCents/100.0, description, NotificationResource.CashAdvance_Requested); - // Slightly misplaced logic, but failsafer here - SwarmopsLogEntry.Create(forPerson, - new CashAdvanceRequestedLogEntry(createdByPerson, forPerson, amountCents/100.0, budget, description), + // Slightly misplaced logic, but failsafer here + SwarmopsLogEntry.Create (forPerson, + new CashAdvanceRequestedLogEntry (createdByPerson, forPerson, amountCents/100.0, budget, description), newAdvance); return newAdvance; @@ -59,23 +59,23 @@ namespace Swarmops.Logic.Financial #region Implementation of IAttestable - public void Attest(Person attester) + public void Attest (Person attester) { - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.CashAdvance, Identity, DateTime.Now, attester.Identity, AmountCents/100.0); - SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(Identity, true, attester.Identity); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested (Identity, true, attester.Identity); - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Person, AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Person, AmountCents/100.0, Description, NotificationResource.CashAdvance_Attested); } - public void Deattest(Person deattester) + public void Deattest (Person deattester) { - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Deattestation, FinancialDependencyType.CashAdvance, Identity, DateTime.Now, deattester.Identity, AmountCents/100.0); - SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(Identity, false, Person.NobodyId); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested (Identity, false, Person.NobodyId); - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Person, AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Person, AmountCents/100.0, Description, NotificationResource.CashAdvance_Deattested); } @@ -83,7 +83,7 @@ namespace Swarmops.Logic.Financial public Person Person { - get { return Person.FromIdentity(PersonId); } + get { return Person.FromIdentity (PersonId); } } public new bool Open @@ -96,7 +96,7 @@ namespace Swarmops.Logic.Financial return; } - SwarmDb.GetDatabaseForWriting().SetCashAdvanceOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceOpen (Identity, value); base.Open = value; } } @@ -111,7 +111,7 @@ namespace Swarmops.Logic.Financial return; } - SwarmDb.GetDatabaseForWriting().SetCashAdvancePaidOut(Identity, value); + SwarmDb.GetDatabaseForWriting().SetCashAdvancePaidOut (Identity, value); base.PaidOut = value; } } @@ -127,14 +127,15 @@ namespace Swarmops.Logic.Financial } int payoutId = - SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(this, FinancialDependencyType.CashAdvance); + SwarmDb.GetDatabaseForReading() + .GetPayoutIdFromDependency (this, FinancialDependencyType.CashAdvance); if (payoutId == 0) { return null; // or throw? When expense claim system was being phased in, payouts did not exist } - return Payout.FromIdentity(payoutId); + return Payout.FromIdentity (payoutId); } } @@ -149,20 +150,20 @@ namespace Swarmops.Logic.Financial int payoutId = SwarmDb.GetDatabaseForReading() - .GetPayoutIdFromDependency(this, FinancialDependencyType.CashAdvancePayback); + .GetPayoutIdFromDependency (this, FinancialDependencyType.CashAdvancePayback); if (payoutId == 0) { return null; // or throw? When expense claim system was being phased in, payouts did not exist } - return Payout.FromIdentity(payoutId); + return Payout.FromIdentity (payoutId); } } public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(BudgetId); } + get { return FinancialAccount.FromIdentity (BudgetId); } } } } \ No newline at end of file diff --git a/Logic/Financial/CashAdvances.cs b/Logic/Financial/CashAdvances.cs index d1bfbc8a..93b67400 100644 --- a/Logic/Financial/CashAdvances.cs +++ b/Logic/Financial/CashAdvances.cs @@ -14,7 +14,7 @@ namespace Swarmops.Logic.Financial get { CashAdvances result = new CashAdvances(); - result.AddRange(this.Where(cashAdvance => !cashAdvance.Attested)); + result.AddRange (this.Where (cashAdvance => !cashAdvance.Attested)); return result; } @@ -25,7 +25,7 @@ namespace Swarmops.Logic.Financial get { CashAdvances result = new CashAdvances(); - result.AddRange(this.Where(cashAdvance => cashAdvance.Attested)); + result.AddRange (this.Where (cashAdvance => cashAdvance.Attested)); return result; } @@ -36,7 +36,7 @@ namespace Swarmops.Logic.Financial get { CashAdvances result = new CashAdvances(); - result.AddRange(this.Where(cashAdvance => cashAdvance.PaidOut)); + result.AddRange (this.Where (cashAdvance => cashAdvance.PaidOut)); return result; } @@ -47,7 +47,7 @@ namespace Swarmops.Logic.Financial get { CashAdvances result = new CashAdvances(); - result.AddRange(this.Where(cashAdvance => !cashAdvance.PaidOut)); + result.AddRange (this.Where (cashAdvance => !cashAdvance.PaidOut)); return result; } @@ -55,17 +55,17 @@ namespace Swarmops.Logic.Financial public Int64 TotalAmountCents { - get { return this.Sum(cashAdvance => cashAdvance.AmountCents); } + get { return this.Sum (cashAdvance => cashAdvance.AmountCents); } } - public static CashAdvances ForOrganization(Organization organization) + public static CashAdvances ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static CashAdvances ForOrganization(Organization organization, bool includeClosed) + public static CashAdvances ForOrganization (Organization organization, bool includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetCashAdvances(organization, + return FromArray (SwarmDb.GetDatabaseForReading().GetCashAdvances (organization, includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } } diff --git a/Logic/Financial/Currencies.cs b/Logic/Financial/Currencies.cs index be783973..7b62c71f 100644 --- a/Logic/Financial/Currencies.cs +++ b/Logic/Financial/Currencies.cs @@ -8,7 +8,7 @@ namespace Swarmops.Logic.Financial { public static Currencies GetAll() { - return FromArray(SwarmDb.GetDatabaseForReading().GetCurrencies()); + return FromArray (SwarmDb.GetDatabaseForReading().GetCurrencies()); } } } \ No newline at end of file diff --git a/Logic/Financial/Currency.cs b/Logic/Financial/Currency.cs index 2d802ee1..f5312a6b 100644 --- a/Logic/Financial/Currency.cs +++ b/Logic/Financial/Currency.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial { public class Currency : BasicCurrency { - private Currency(BasicCurrency basic) : base(basic) + private Currency (BasicCurrency basic) : base (basic) { // empty ctor } @@ -23,33 +23,33 @@ namespace Swarmops.Logic.Financial } } - public static Currency FromBasic(BasicCurrency basic) + public static Currency FromBasic (BasicCurrency basic) { - return new Currency(basic); + return new Currency (basic); } - public static Currency FromIdentity(int currencyId) + public static Currency FromIdentity (int currencyId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(currencyId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCurrency (currencyId)); } - public static Currency FromIdentityAggressive(int currencyId) + public static Currency FromIdentityAggressive (int currencyId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetCurrency(currencyId)); - // "For writing" is intentional - replication timing issue + return FromBasic (SwarmDb.GetDatabaseForWriting().GetCurrency (currencyId)); + // "For writing" is intentional - replication timing issue } - public static Currency FromCode(string code) + public static Currency FromCode (string code) { code = code.ToUpperInvariant(); - return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(code)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCurrency (code)); } - public static Currency Create(string code, string name, string sign) + public static Currency Create (string code, string name, string sign) { - return FromIdentityAggressive( - SwarmDb.GetDatabaseForWriting().CreateCurrency(code, name, sign)); + return FromIdentityAggressive ( + SwarmDb.GetDatabaseForWriting().CreateCurrency (code, name, sign)); } } } \ No newline at end of file diff --git a/Logic/Financial/ExpenseClaim.cs b/Logic/Financial/ExpenseClaim.cs index b0ec9a42..90ace7aa 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -16,36 +16,36 @@ namespace Swarmops.Logic.Financial { #region Construction and Creation - private ExpenseClaim() : base(null) + private ExpenseClaim() : base (null) { } // Private constructor prevents wanton creation - private ExpenseClaim(BasicExpenseClaim basic) : base(basic) + private ExpenseClaim (BasicExpenseClaim basic) : base (basic) { } // Used by FromBasic() - internal static ExpenseClaim FromBasic(BasicExpenseClaim basic) + internal static ExpenseClaim FromBasic (BasicExpenseClaim basic) { - return new ExpenseClaim(basic); + return new ExpenseClaim (basic); } - public static ExpenseClaim FromIdentity(int expenseId) + public static ExpenseClaim FromIdentity (int expenseId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetExpenseClaim(expenseId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetExpenseClaim (expenseId)); } - public static ExpenseClaim FromIdentityAggressive(int expenseId) + public static ExpenseClaim FromIdentityAggressive (int expenseId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetExpenseClaim(expenseId)); - // ForWriting is intentional - bypass replication lag + return FromBasic (SwarmDb.GetDatabaseForWriting().GetExpenseClaim (expenseId)); + // ForWriting is intentional - bypass replication lag } - public static ExpenseClaim Create(Person claimer, Organization organization, FinancialAccount budget, + public static ExpenseClaim Create (Person claimer, Organization organization, FinancialAccount budget, DateTime expenseDate, string description, Int64 amountCents) { ExpenseClaim newClaim = - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() - .CreateExpenseClaim(claimer.Identity, organization.Identity, + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + .CreateExpenseClaim (claimer.Identity, organization.Identity, budget.Identity, expenseDate, description, amountCents)); // Create the financial transaction with rows @@ -53,15 +53,15 @@ namespace Swarmops.Logic.Financial if (transactionDescription.Length > 64) { - transactionDescription = transactionDescription.Substring(0, 61) + "..."; + transactionDescription = transactionDescription.Substring (0, 61) + "..."; } FinancialTransaction transaction = - FinancialTransaction.Create(organization.Identity, DateTime.Now, + FinancialTransaction.Create (organization.Identity, DateTime.Now, transactionDescription); - transaction.AddRow(organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); - transaction.AddRow(budget, amountCents, claimer); + transaction.AddRow (organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); + transaction.AddRow (budget, amountCents, claimer); // Make the transaction dependent on the expense claim @@ -69,12 +69,12 @@ namespace Swarmops.Logic.Financial // Create notifications - OutboundComm.CreateNotificationAttestationNeeded(budget, claimer, string.Empty, amountCents/100.0, + OutboundComm.CreateNotificationAttestationNeeded (budget, claimer, string.Empty, amountCents/100.0, description, NotificationResource.ExpenseClaim_Created); // Slightly misplaced logic, but failsafer here - OutboundComm.CreateNotificationFinancialValidationNeeded(organization, amountCents/100.0, + OutboundComm.CreateNotificationFinancialValidationNeeded (organization, amountCents/100.0, NotificationResource.Receipts_Filed); - SwarmopsLogEntry.Create(claimer, - new ExpenseClaimFiledLogEntry(claimer /*filing person*/, claimer /*beneficiary*/, amountCents/100.0, + SwarmopsLogEntry.Create (claimer, + new ExpenseClaimFiledLogEntry (claimer /*filing person*/, claimer /*beneficiary*/, amountCents/100.0, budget, description), newClaim); return newClaim; @@ -84,7 +84,7 @@ namespace Swarmops.Logic.Financial public Person Claimer { - get { return Person.FromIdentity(base.ClaimingPersonId); } + get { return Person.FromIdentity (base.ClaimingPersonId); } } public bool Approved @@ -110,14 +110,14 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } public FinancialTransaction FinancialTransaction { get { - FinancialTransactions transactions = FinancialTransactions.ForDependentObject(this); + FinancialTransactions transactions = FinancialTransactions.ForDependentObject (this); if (transactions.Count == 0) { @@ -129,8 +129,8 @@ namespace Swarmops.Logic.Financial return transactions[0]; } - throw new InvalidOperationException("It appears expense claim #" + Identity + - " has multiple dependent financial transactions. This is an invalid state."); + throw new InvalidOperationException ("It appears expense claim #" + Identity + + " has multiple dependent financial transactions. This is an invalid state."); } } @@ -141,7 +141,7 @@ namespace Swarmops.Logic.Financial { if (base.Attested != value) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested (Identity, value); base.Attested = value; } } @@ -154,7 +154,7 @@ namespace Swarmops.Logic.Financial { if (base.Validated != value) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated (Identity, value); base.Validated = value; } } @@ -168,7 +168,7 @@ namespace Swarmops.Logic.Financial if (base.Open != value) { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimOpen (Identity, value); } } } @@ -181,8 +181,8 @@ namespace Swarmops.Logic.Financial if (base.Claimed != value) { base.Claimed = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimClaimed(Identity, value); - UpdateFinancialTransaction(Claimer); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimClaimed (Identity, value); + UpdateFinancialTransaction (Claimer); } } } @@ -195,7 +195,7 @@ namespace Swarmops.Logic.Financial if (base.Repaid != value) { base.Repaid = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimRepaid(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimRepaid (Identity, value); } } } @@ -208,7 +208,7 @@ namespace Swarmops.Logic.Financial if (base.KeepSeparate != value) { base.KeepSeparate = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimKeepSeparate(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimKeepSeparate (Identity, value); } } } @@ -218,7 +218,7 @@ namespace Swarmops.Logic.Financial get { return base.Description; } set { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimDescription(Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimDescription (Identity, value); base.Description = value; } } @@ -254,13 +254,13 @@ namespace Swarmops.Logic.Financial public Documents Documents { - get { return Documents.ForObject(this); } + get { return Documents.ForObject (this); } } public FinancialValidations Validations { - get { return FinancialValidations.ForObject(this); } + get { return FinancialValidations.ForObject (this); } } public Payout Payout @@ -273,40 +273,40 @@ namespace Swarmops.Logic.Financial } int payoutId = - SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(this); + SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency (this); if (payoutId == 0) { return null; // or throw? When expense claim system was being phased in, payouts did not exist } - return Payout.FromIdentity(payoutId); + return Payout.FromIdentity (payoutId); } } #region IValidatable Members - public void Validate(Person validator) + public void Validate (Person validator) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, true); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Validation, + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated (Identity, true); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Validation, FinancialDependencyType.ExpenseClaim, Identity, DateTime.Now, validator.Identity, (double) Amount); base.Validated = true; - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Claimer, AmountCents/100.0, Description, NotificationResource.ExpenseClaim_Validated); } - public void Devalidate(Person devalidator) + public void Devalidate (Person devalidator) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, false); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Devalidation, + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated (Identity, false); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Devalidation, FinancialDependencyType.ExpenseClaim, Identity, DateTime.Now, devalidator.Identity, (double) Amount); base.Validated = false; - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Claimer, AmountCents/100.0, Description, NotificationResource.ExpenseClaim_Devalidated); } @@ -314,27 +314,27 @@ namespace Swarmops.Logic.Financial #region IAttestable Members - public void Attest(Person attester) + public void Attest (Person attester) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, true); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested (Identity, true); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.ExpenseClaim, Identity, DateTime.Now, attester.Identity, (double) Amount); base.Attested = true; - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Claimer, AmountCents/100.0, Description, NotificationResource.ExpenseClaim_Attested); } - public void Deattest(Person deattester) + public void Deattest (Person deattester) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, false); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested (Identity, false); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Deattestation, FinancialDependencyType.ExpenseClaim, Identity, DateTime.Now, deattester.Identity, (double) Amount); base.Attested = false; - OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + OutboundComm.CreateNotificationOfFinancialValidation (Budget, Claimer, AmountCents/100.0, Description, NotificationResource.ExpenseClaim_Deattested); } @@ -342,18 +342,18 @@ namespace Swarmops.Logic.Financial public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(base.BudgetId); } + get { return FinancialAccount.FromIdentity (base.BudgetId); } } - [Obsolete("Obsolete", true)] - public void CreateEvent(ExpenseEventType eventType, Person person) + [Obsolete ("Obsolete", true)] + public void CreateEvent (ExpenseEventType eventType, Person person) { // OBSOLETE // CreateEvent (eventType, person.Identity); } - public void CreateEvent(ExpenseEventType eventType, int personId) + public void CreateEvent (ExpenseEventType eventType, int personId) { // OBSOLETE @@ -367,7 +367,7 @@ namespace Swarmops.Logic.Financial Open = false; } - public void SetAmountCents(Int64 amountCents, Person settingPerson) + public void SetAmountCents (Int64 amountCents, Person settingPerson) { if (base.AmountCents == amountCents) { @@ -375,20 +375,20 @@ namespace Swarmops.Logic.Financial } base.AmountCents = amountCents; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAmount(Identity, amountCents); - UpdateFinancialTransaction(settingPerson); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAmount (Identity, amountCents); + UpdateFinancialTransaction (settingPerson); } - public void SetBudget(FinancialAccount budget, Person settingPerson) + public void SetBudget (FinancialAccount budget, Person settingPerson) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimBudget(Identity, budget.Identity); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimBudget (Identity, budget.Identity); base.BudgetId = budget.Identity; - UpdateFinancialTransaction(settingPerson); + UpdateFinancialTransaction (settingPerson); } - public void Kill(Person killingPerson) + public void Kill (Person killingPerson) { // Set the state to Closed, Unvalidated, Unattested @@ -396,8 +396,8 @@ namespace Swarmops.Logic.Financial Validated = false; Open = false; - UpdateFinancialTransaction(killingPerson); - // will zero out transaction since both Validated and Open are false + UpdateFinancialTransaction (killingPerson); + // will zero out transaction since both Validated and Open are false // Mark transaction as invalid in description @@ -407,11 +407,11 @@ namespace Swarmops.Logic.Financial public void Recalibrate() { - UpdateFinancialTransaction(null); // only to be used for fix-bookkeeping scripts + UpdateFinancialTransaction (null); // only to be used for fix-bookkeeping scripts } - private void UpdateFinancialTransaction(Person updatingPerson) + private void UpdateFinancialTransaction (Person updatingPerson) { Dictionary nominalTransaction = new Dictionary(); @@ -430,7 +430,7 @@ namespace Swarmops.Logic.Financial nominalTransaction[BudgetId] = AmountCents; } - FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); + FinancialTransaction.RecalculateTransaction (nominalTransaction, updatingPerson); } } } \ No newline at end of file diff --git a/Logic/Financial/ExpenseClaims.cs b/Logic/Financial/ExpenseClaims.cs index 5f957dee..eddc01dd 100644 --- a/Logic/Financial/ExpenseClaims.cs +++ b/Logic/Financial/ExpenseClaims.cs @@ -15,7 +15,7 @@ namespace Swarmops.Logic.Financial get { ExpenseClaims result = new ExpenseClaims(); - result.AddRange(this.Where(expense => expense.Open)); + result.AddRange (this.Where (expense => expense.Open)); return result; } @@ -26,7 +26,7 @@ namespace Swarmops.Logic.Financial get { ExpenseClaims result = new ExpenseClaims(); - result.AddRange(this.Where(expense => expense.Approved)); + result.AddRange (this.Where (expense => expense.Approved)); return result; } @@ -37,7 +37,7 @@ namespace Swarmops.Logic.Financial get { ExpenseClaims result = new ExpenseClaims(); - result.AddRange(this.Where(expense => !expense.Approved)); + result.AddRange (this.Where (expense => !expense.Approved)); return result; } @@ -49,7 +49,7 @@ namespace Swarmops.Logic.Financial get { ExpenseClaims result = new ExpenseClaims(); - result.AddRange(this.Where(expenseClaim => !expenseClaim.Attested)); + result.AddRange (this.Where (expenseClaim => !expenseClaim.Attested)); return result; } @@ -61,7 +61,7 @@ namespace Swarmops.Logic.Financial get { ExpenseClaims result = new ExpenseClaims(); - result.AddRange(this.Where(expenseClaim => !expenseClaim.Validated)); + result.AddRange (this.Where (expenseClaim => !expenseClaim.Validated)); return result; } @@ -69,46 +69,46 @@ namespace Swarmops.Logic.Financial public decimal TotalAmount { - get { return this.Sum(claim => claim.Amount); } + get { return this.Sum (claim => claim.Amount); } } public Int64 TotalAmountCents { - get { return this.Sum(claim => claim.AmountCents); } + get { return this.Sum (claim => claim.AmountCents); } } - public static ExpenseClaims FromClaimingPersonAndOrganization(Person person, Organization organization) + public static ExpenseClaims FromClaimingPersonAndOrganization (Person person, Organization organization) { return - FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaimsByClaimerAndOrganization(person.Identity, + FromArray (SwarmDb.GetDatabaseForReading().GetExpenseClaimsByClaimerAndOrganization (person.Identity, organization.Identity)); } - public static ExpenseClaims FromClaimingPerson(Person person) + public static ExpenseClaims FromClaimingPerson (Person person) { - return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaimsByClaimer(person.Identity)); + return FromArray (SwarmDb.GetDatabaseForReading().GetExpenseClaimsByClaimer (person.Identity)); } - public static ExpenseClaims FromOrganization(Organization org) + public static ExpenseClaims FromOrganization (Organization org) { - return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaimsByOrganization(org.Identity)); + return FromArray (SwarmDb.GetDatabaseForReading().GetExpenseClaimsByOrganization (org.Identity)); } - public static ExpenseClaims ForOrganization(Organization org) + public static ExpenseClaims ForOrganization (Organization org) { - return ForOrganization(org, false); + return ForOrganization (org, false); } - public static ExpenseClaims ForOrganization(Organization org, bool includeClosed) + public static ExpenseClaims ForOrganization (Organization org, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaims(org)); + return FromArray (SwarmDb.GetDatabaseForReading().GetExpenseClaims (org)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaims(org, DatabaseCondition.OpenTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetExpenseClaims (org, DatabaseCondition.OpenTrue)); } } } \ No newline at end of file diff --git a/Logic/Financial/ExternalBankData.cs b/Logic/Financial/ExternalBankData.cs index fad2141b..f3d76980 100644 --- a/Logic/Financial/ExternalBankData.cs +++ b/Logic/Financial/ExternalBankData.cs @@ -13,43 +13,43 @@ namespace Swarmops.Logic.Financial public ExternalBankDataProfile Profile { get; set; } public ExternalBankDataRecord[] Records { get; private set; } - public void LoadData(Stream dataStream, Organization organization) + public void LoadData (Stream dataStream, Organization organization) { - using (TextReader reader = new StreamReader(dataStream)) // TODO: Is encoding necessary? + using (TextReader reader = new StreamReader (dataStream)) // TODO: Is encoding necessary? { - LoadData(reader, organization); + LoadData (reader, organization); } } - public void LoadData(TextReader reader, Organization organization) + public void LoadData (TextReader reader, Organization organization) { string data = reader.ReadToEnd(); - LoadData(data, organization); + LoadData (data, organization); } - public void LoadData(string data, Organization organization) + public void LoadData (string data, Organization organization) { List recordList = new List(); if (Profile == null) { - throw new InvalidOperationException("Cannot call LoadData before a profile has been set"); + throw new InvalidOperationException ("Cannot call LoadData before a profile has been set"); } if (Profile.BankDataAccountReader != StockBankDataReaders.TabSeparatedValuesAccountReader) { - throw new NotImplementedException("Only tab separated values are supported at this point"); + throw new NotImplementedException ("Only tab separated values are supported at this point"); } // TODO: Implement bank data reader factory here string organizationCurrencyCode = organization.Currency.Code; - int crlfIndex = data.IndexOfAny(new[] {'\n', '\r'}); + int crlfIndex = data.IndexOfAny (new[] {'\n', '\r'}); - string fieldKeyLine = data.Substring(0, crlfIndex); + string fieldKeyLine = data.Substring (0, crlfIndex); - string[] dataKeyFields = fieldKeyLine.Split('\t'); + string[] dataKeyFields = fieldKeyLine.Split ('\t'); Dictionary fieldNameLookup = new Dictionary(); @@ -67,17 +67,17 @@ namespace Swarmops.Logic.Financial } } - if (!fieldNameLookup.ContainsKey(fieldName)) // wasn't found + if (!fieldNameLookup.ContainsKey (fieldName)) // wasn't found { - throw new InvalidOperationException("Field key \"" + fieldName + - "\" was not supplied or found in data file"); + throw new InvalidOperationException ("Field key \"" + fieldName + + "\" was not supplied or found in data file"); } } - data = data.Substring(crlfIndex).Trim(); + data = data.Substring (crlfIndex).Trim(); - string[] lines = data.Split(new[] {'\r', '\n'}); + string[] lines = data.Split (new[] {'\r', '\n'}); foreach (string lineData in lines) { @@ -88,13 +88,13 @@ namespace Swarmops.Logic.Financial continue; // empty lines may exist due to split on either CR or LF } - string[] lineFields = line.Split('\t'); + string[] lineFields = line.Split ('\t'); // If wrong currency, ignore - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Currency)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.Currency)) { - string currency = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Currency]]); + string currency = StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.Currency]]); if (currency != organizationCurrencyCode) { @@ -104,47 +104,47 @@ namespace Swarmops.Logic.Financial ExternalBankDataRecord newRecord = new ExternalBankDataRecord(); - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Description)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.Description)) { newRecord.Description = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Description]]); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.Description]]); } - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.AccountBalance)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.AccountBalance)) { // Dividing up to step-by-step statements instead of one long statement assists debugging // of culture and other error sources string balanceString = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.AccountBalance]]); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.AccountBalance]]); try { - newRecord.AccountBalanceCents = ParseAmountString(balanceString); + newRecord.AccountBalanceCents = ParseAmountString (balanceString); } catch (Exception innerException) { - throw new FormatException("Couldn't parse account balance string - \"" + balanceString + "\"", + throw new FormatException ("Couldn't parse account balance string - \"" + balanceString + "\"", innerException); } } - if (!fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Date) && - !fieldNameLookup.ContainsKey(ExternalBankDataFieldName.DateTime)) + if (!fieldNameLookup.ContainsKey (ExternalBankDataFieldName.Date) && + !fieldNameLookup.ContainsKey (ExternalBankDataFieldName.DateTime)) { - throw new InvalidOperationException("Cannot parse transactions file without at least a date field"); + throw new InvalidOperationException ("Cannot parse transactions file without at least a date field"); } DateTime dateTime = DateTime.MinValue; - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Date)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.Date)) { - string dateString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Date]]); - dateTime = DateTime.Parse(dateString, new CultureInfo(Profile.Culture)); + string dateString = StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.Date]]); + dateTime = DateTime.Parse (dateString, new CultureInfo (Profile.Culture)); - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Time)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.Time)) { - string timeString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Time]]); - TimeSpan timeOfDay = TimeSpan.Parse(timeString); + string timeString = StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.Time]]); + TimeSpan timeOfDay = TimeSpan.Parse (timeString); dateTime += timeOfDay; } @@ -153,28 +153,28 @@ namespace Swarmops.Logic.Financial // move transaction to like mid-day of the organization's time zone. For now, all orgs are in Europe, so add 12 hours // this is a HACK HACK HACK - dateTime = dateTime.AddHours(12); + dateTime = dateTime.AddHours (12); } } else // no Date field, so by earlier logic, must have a DateTime field { dateTime = - DateTime.Parse(StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.DateTime]]), - new CultureInfo(Profile.Culture)); + DateTime.Parse (StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.DateTime]]), + new CultureInfo (Profile.Culture)); } - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TimeZone)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.TimeZone)) { // Valid time zone formats are "XXX+hh:mm". The XXX are ignored. // Throws exception if this doesn't parse, which is what we want - string timeZoneString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TimeZone]]); - timeZoneString = timeZoneString.Substring(timeZoneString.Length - 6); - TimeSpan timeZone = TimeSpan.Parse(timeZoneString); + string timeZoneString = StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.TimeZone]]); + timeZoneString = timeZoneString.Substring (timeZoneString.Length - 6); + TimeSpan timeZone = TimeSpan.Parse (timeZoneString); dateTime -= timeZone; - // minus, to bring the time to UTC. If time 13:00 is in tz +01:00, the UTC time is 12:00 + // minus, to bring the time to UTC. If time 13:00 is in tz +01:00, the UTC time is 12:00 // Then move from UTC to local time, to match various bookkeeping laws. TODO: local time per organization, perhaps? @@ -184,35 +184,35 @@ namespace Swarmops.Logic.Financial // PILOT SPECIAL CASE: if Paypal and PPSE Pilot program, ignore everything before 2014 if (dateTime.Year < 2014 && organization.Identity == 1 && - fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId) && - PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) + fieldNameLookup.ContainsKey (ExternalBankDataFieldName.UniqueId) && + PilotInstallationIds.IsPilot (PilotInstallationIds.PiratePartySE)) { continue; // Do not import PayPal records from before 2013 } newRecord.DateTime = dateTime; - if (!fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionNet)) + if (!fieldNameLookup.ContainsKey (ExternalBankDataFieldName.TransactionNet)) { - throw new ArgumentException("There must be a transaction amount field in the bank data profile"); + throw new ArgumentException ("There must be a transaction amount field in the bank data profile"); } string amountNetString = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionNet]]); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionNet]]); - newRecord.TransactionNetCents = ParseAmountString(amountNetString); + newRecord.TransactionNetCents = ParseAmountString (amountNetString); - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionGross)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.TransactionGross)) { string amountGrossString = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionGross]]); - newRecord.TransactionGrossCents = ParseAmountString(amountGrossString); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionGross]]); + newRecord.TransactionGrossCents = ParseAmountString (amountGrossString); - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionFee)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.TransactionFee)) { string amountFeeString = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionFee]]); - newRecord.FeeCents = ParseAmountString(amountFeeString); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionFee]]); + newRecord.FeeCents = ParseAmountString (amountFeeString); if (Profile.FeeSignage == FeeSignage.Positive) { @@ -223,28 +223,28 @@ namespace Swarmops.Logic.Financial else { newRecord.TransactionGrossCents = newRecord.TransactionNetCents; - // if no "Gross" field, copy from net + // if no "Gross" field, copy from net } // Check for consistency of gross/net/fee: if (newRecord.TransactionNetCents != newRecord.TransactionGrossCents + newRecord.FeeCents) { - throw new InvalidDataException( + throw new InvalidDataException ( "For a record, the net transaction amount does not match the gross less the fee."); } - if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId)) + if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.UniqueId)) { - newRecord.UniqueId = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.UniqueId]]); + newRecord.UniqueId = StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.UniqueId]]); } - else if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.NotUniqueId)) + else if (fieldNameLookup.ContainsKey (ExternalBankDataFieldName.NotUniqueId)) { newRecord.NotUniqueId = - StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.NotUniqueId]]); + StripQuotes (lineFields[fieldNameLookup[ExternalBankDataFieldName.NotUniqueId]]); } - recordList.Add(newRecord); + recordList.Add (newRecord); } if (Profile.LatestTransactionLocation == LatestTransactionLocation.Top) @@ -257,16 +257,16 @@ namespace Swarmops.Logic.Financial } else { - throw new ArgumentException("LatestTransactionLocation is undefined"); + throw new ArgumentException ("LatestTransactionLocation is undefined"); } - recordList.Sort(new ExternalBankDataRecord()); + recordList.Sort (new ExternalBankDataRecord()); Records = recordList.ToArray(); } - private Int64 ParseAmountString(string input) + private Int64 ParseAmountString (string input) { // This parser deals with a number of different cases and cultures. // It returns cents. @@ -321,14 +321,14 @@ namespace Swarmops.Logic.Financial // remove all known noise from the digit sequence: spaces, thousands accents, commas, periods - input = input.Replace(" ", "").Replace("'", "").Replace(",", "").Replace(".", ""); + input = input.Replace (" ", "").Replace ("'", "").Replace (",", "").Replace (".", ""); // parse what's remaining as cents in Int64 - return Int64.Parse(input); + return Int64.Parse (input); } - private string StripQuotes(string input) + private string StripQuotes (string input) { input = input.Trim(); @@ -336,9 +336,9 @@ namespace Swarmops.Logic.Financial { if (input[0] == '\"') { - if (input.EndsWith("\"")) + if (input.EndsWith ("\"")) { - return input.Trim('\"', ' '); + return input.Trim ('\"', ' '); } } } diff --git a/Logic/Financial/ExternalBankDataProfile.cs b/Logic/Financial/ExternalBankDataProfile.cs index da0cff7d..c4039383 100644 --- a/Logic/Financial/ExternalBankDataProfile.cs +++ b/Logic/Financial/ExternalBankDataProfile.cs @@ -30,7 +30,7 @@ namespace Swarmops.Logic.Financial case ExternalBankDateTimePrecision.Microsecond: return "yyyy-MM-dd HH:mm:ss.ffffff"; default: - throw new NotImplementedException("Unknown ExternalDateTimePrecision: " + this.Precision); + throw new NotImplementedException ("Unknown ExternalDateTimePrecision: " + this.Precision); } } } @@ -54,7 +54,7 @@ namespace Swarmops.Logic.Financial public Dictionary FieldNames { get; private set; } - public static ExternalBankDataProfile FromIdentity(int externalBankDataProfileId) + public static ExternalBankDataProfile FromIdentity (int externalBankDataProfileId) { ExternalBankDataProfile result = new ExternalBankDataProfile(); @@ -63,7 +63,7 @@ namespace Swarmops.Logic.Financial if (externalBankDataProfileId == SESebId) { result.Name = "SEB"; - result.Country = Country.FromCode("SE"); + result.Country = Country.FromCode ("SE"); result.Culture = "sv-SE"; result.FieldNames[ExternalBankDataFieldName.Date] = "Bokföringsdatum"; @@ -109,7 +109,7 @@ namespace Swarmops.Logic.Financial return result; } - throw new ArgumentException("Unrecognized profile Id"); + throw new ArgumentException ("Unrecognized profile Id"); } } diff --git a/Logic/Financial/ExternalBankDataRecord.cs b/Logic/Financial/ExternalBankDataRecord.cs index 50bff7f9..a425cadf 100644 --- a/Logic/Financial/ExternalBankDataRecord.cs +++ b/Logic/Financial/ExternalBankDataRecord.cs @@ -13,7 +13,7 @@ namespace Swarmops.Logic.Financial public long FeeCents; public string NotUniqueId; - // As it says, but something that still assists in creating a hash together w/ other fields + // As it says, but something that still assists in creating a hash together w/ other fields public long TransactionGrossCents; public long TransactionNetCents; @@ -21,11 +21,11 @@ namespace Swarmops.Logic.Financial #region Implementation of IComparer - public int Compare(ExternalBankDataRecord x, ExternalBankDataRecord y) + public int Compare (ExternalBankDataRecord x, ExternalBankDataRecord y) { // Use only DateTime to compare - return x.DateTime.CompareTo(y.DateTime); + return x.DateTime.CompareTo (y.DateTime); } #endregion @@ -36,25 +36,25 @@ namespace Swarmops.Logic.Financial { string importKey = string.Empty; - if (!string.IsNullOrEmpty(this.UniqueId)) + if (!string.IsNullOrEmpty (this.UniqueId)) { importKey = this.UniqueId; } - else if (!string.IsNullOrEmpty(this.NotUniqueId)) + else if (!string.IsNullOrEmpty (this.NotUniqueId)) { string commentKey = this.Description.ToLowerInvariant(); string hashKey = this.NotUniqueId + commentKey + - (this.TransactionNetCents/100.0).ToString(CultureInfo.InvariantCulture) + - (this.AccountBalanceCents/100.0).ToString(CultureInfo.InvariantCulture) + - this.DateTime.ToString("yyyy-MM-dd-HH-mm-ss"); + (this.TransactionNetCents/100.0).ToString (CultureInfo.InvariantCulture) + + (this.AccountBalanceCents/100.0).ToString (CultureInfo.InvariantCulture) + + this.DateTime.ToString ("yyyy-MM-dd-HH-mm-ss"); - importKey = SHA1.Hash(hashKey).Replace(" ", ""); + importKey = SHA1.Hash (hashKey).Replace (" ", ""); } if (importKey.Length > 30) { - importKey = importKey.Substring(0, 30); + importKey = importKey.Substring (0, 30); } return importKey; diff --git a/Logic/Financial/FinancialAccount.cs b/Logic/Financial/FinancialAccount.cs index add568fe..bd340515 100644 --- a/Logic/Financial/FinancialAccount.cs +++ b/Logic/Financial/FinancialAccount.cs @@ -11,29 +11,29 @@ namespace Swarmops.Logic.Financial { public class FinancialAccount : BasicFinancialAccount, ITreeNode, IOwnerSettable { - private FinancialAccount(BasicFinancialAccount basic) - : base(basic) + private FinancialAccount (BasicFinancialAccount basic) + : base (basic) { } - [Obsolete( + [Obsolete ( "This method uses floating point for financials. Deprecated. Do not use; use BalanceTotalCents instead.", true)] public double BalanceTotal { - get { return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceTotal(Identity); } + get { return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceTotal (Identity); } } public Int64 BalanceTotalCents { - get { return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceTotalCents(Identity); } + get { return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceTotalCents (Identity); } } public Organization Organization { get { - return Organization.FromIdentity(OrganizationId); // TODO: Cache + return Organization.FromIdentity (OrganizationId); // TODO: Cache } } @@ -46,9 +46,9 @@ namespace Swarmops.Logic.Financial return null; } - return Person.FromIdentity(OwnerPersonId); + return Person.FromIdentity (OwnerPersonId); } - set { SwarmDb.GetDatabaseForWriting().SetFinancialAccountOwner(Identity, value.Identity); } + set { SwarmDb.GetDatabaseForWriting().SetFinancialAccountOwner (Identity, value.Identity); } } @@ -56,13 +56,14 @@ namespace Swarmops.Logic.Financial { get { - return FinancialAccounts.FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountChildren(Identity)); + return + FinancialAccounts.FromArray (SwarmDb.GetDatabaseForReading().GetFinancialAccountChildren (Identity)); } } public FinancialAccount Parent { - get { return FromIdentity(ParentFinancialAccountId); } + get { return FromIdentity (ParentFinancialAccountId); } set { // We do not change the parent lightly. It cannot be changed if this account has transactions @@ -73,7 +74,7 @@ namespace Swarmops.Logic.Financial int yearClosed = Organization.Parameters.FiscalBooksClosedUntilYear; if (yearClosed > 0 && OpenedYear <= yearClosed) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Can't reparent an account with transactions in closedledger space"); } } @@ -85,7 +86,7 @@ namespace Swarmops.Logic.Financial int newParentId = value != null ? value.Identity : 0; base.ParentFinancialAccountId = newParentId; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountParent(Identity, newParentId); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountParent (Identity, newParentId); } } @@ -95,11 +96,11 @@ namespace Swarmops.Logic.Financial get { return - OptionalData.GetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences); + OptionalData.GetOptionalDataBool (ObjectOptionalDataType.FinancialAccountEnabledForConferences); } set { - OptionalData.SetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences, value); + OptionalData.SetOptionalDataBool (ObjectOptionalDataType.FinancialAccountEnabledForConferences, value); } } @@ -109,22 +110,22 @@ namespace Swarmops.Logic.Financial { // HACK HACK HACK HACK HACK for our pilots; this will be softcoded later TODO - if (OrganizationId == 1 && PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) + if (OrganizationId == 1 && PilotInstallationIds.IsPilot (PilotInstallationIds.PiratePartySE)) { switch (FinancialAccountId) { case 1: - return ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); + return ExternalBankDataProfile.FromIdentity (ExternalBankDataProfile.SESebId); case 2: - return ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.PaypalId); + return ExternalBankDataProfile.FromIdentity (ExternalBankDataProfile.PaypalId); default: return null; } } - if (OrganizationId == 7 && PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && + if (OrganizationId == 7 && PilotInstallationIds.IsPilot (PilotInstallationIds.SwarmopsLive) && FinancialAccountId == 29) { - return ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); + return ExternalBankDataProfile.FromIdentity (ExternalBankDataProfile.SESebId); } return null; @@ -142,7 +143,7 @@ namespace Swarmops.Logic.Financial try { firstTransactionDate = - SwarmDb.GetDatabaseForReading().GetFinancialAccountFirstTransactionDate(Identity); + SwarmDb.GetDatabaseForReading().GetFinancialAccountFirstTransactionDate (Identity); } catch (Exception) { @@ -152,9 +153,9 @@ namespace Swarmops.Logic.Financial if (firstTransactionDate.Year > 1900) { SwarmDb.GetDatabaseForWriting() - .SetFinancialAccountOpenedYear(Identity, firstTransactionDate.Year); + .SetFinancialAccountOpenedYear (Identity, firstTransactionDate.Year); base.OpenedYear = firstTransactionDate.Year; - // TODO: Adapt for non-calendar fiscal years as future expansion? + // TODO: Adapt for non-calendar fiscal years as future expansion? } } @@ -162,7 +163,7 @@ namespace Swarmops.Logic.Financial { return base.OpenedYear; } - throw new ArgumentException("FinancialAccount is not opened yet (no transactions)"); + throw new ArgumentException ("FinancialAccount is not opened yet (no transactions)"); } } @@ -177,7 +178,7 @@ namespace Swarmops.Logic.Financial } base.Active = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountActive(Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountActive (Identity, value); } } @@ -193,7 +194,7 @@ namespace Swarmops.Logic.Financial } base.Expensable = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountExpensable(Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountExpensable (Identity, value); } } @@ -209,7 +210,7 @@ namespace Swarmops.Logic.Financial } base.Administrative = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountAdministrative(Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountAdministrative (Identity, value); } } @@ -221,11 +222,11 @@ namespace Swarmops.Logic.Financial { get { - int geographyId = OptionalData.GetOptionalDataInt(ObjectOptionalDataType.GeographyId); + int geographyId = OptionalData.GetOptionalDataInt (ObjectOptionalDataType.GeographyId); if (geographyId != 0) { - return Geography.FromIdentity(geographyId); + return Geography.FromIdentity (geographyId); } return null; @@ -233,9 +234,9 @@ namespace Swarmops.Logic.Financial set { if (value != null) - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.GeographyId, value.Identity); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.GeographyId, value.Identity); else - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.GeographyId, 0); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.GeographyId, 0); } } @@ -243,14 +244,15 @@ namespace Swarmops.Logic.Financial { get { - if (!String.IsNullOrEmpty(OptionalData.GetOptionalDataString(ObjectOptionalDataType.BankTransactionTag))) + if ( + !String.IsNullOrEmpty (OptionalData.GetOptionalDataString (ObjectOptionalDataType.BankTransactionTag))) { - return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BankTransactionTag); + return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BankTransactionTag); } return null; } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankTransactionTag, value.ToLower()); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BankTransactionTag, value.ToLower()); } } private ObjectOptionalData OptionalData @@ -260,8 +262,8 @@ namespace Swarmops.Logic.Financial if (this._optionalData == null) { FinancialAccount acc = this; - this._optionalData = ObjectOptionalData.ForObject(acc); - //Added cast, otherwise it fails for subclasses + this._optionalData = ObjectOptionalData.ForObject (acc); + //Added cast, otherwise it fails for subclasses } return this._optionalData; } @@ -281,7 +283,7 @@ namespace Swarmops.Logic.Financial #region IOwnerSettable members - public void SetOwner(Person newOwner) + public void SetOwner (Person newOwner) { Owner = newOwner; } @@ -298,7 +300,7 @@ namespace Swarmops.Logic.Financial int yearClosed = Organization.Parameters.FiscalBooksClosedUntilYear; if (yearClosed > 0 && OpenedYear <= yearClosed) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Can't rename an account with transactions in closedledger space"); } } @@ -307,112 +309,113 @@ namespace Swarmops.Logic.Financial // This is ok and can be thrown if OpenedYear throws because there are no transactions yet. } - SwarmDb.GetDatabaseForWriting().SetFinancialAccountName(Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountName (Identity, value); base.Name = value; } } - public static FinancialAccount FromIdentity(int identity) + public static FinancialAccount FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialAccount(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialAccount (identity)); } - public static FinancialAccount FromIdentityAggressive(int identity) + public static FinancialAccount FromIdentityAggressive (int identity) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetFinancialAccount(identity)); - // Note "for writing". Intentional; this bypasses the replication lag from master to slave. + return FromBasic (SwarmDb.GetDatabaseForWriting().GetFinancialAccount (identity)); + // Note "for writing". Intentional; this bypasses the replication lag from master to slave. } - public static FinancialAccount FromBasic(BasicFinancialAccount basic) + public static FinancialAccount FromBasic (BasicFinancialAccount basic) { - return new FinancialAccount(basic); + return new FinancialAccount (basic); } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetDeltaCents instead.", + [Obsolete ("This method uses floating point for financials. Deprecated. Do not use; use GetDeltaCents instead.", true)] - public decimal GetDelta(DateTime start, DateTime end) + public decimal GetDelta (DateTime start, DateTime end) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDelta(Identity, start, end); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDelta (Identity, start, end); } - public Int64 GetDeltaCents(DateTime start, DateTime end) + public Int64 GetDeltaCents (DateTime start, DateTime end) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(Identity, start, end); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents (Identity, start, end); } - public FinancialAccountRows GetLastRows(int rowCount) + public FinancialAccountRows GetLastRows (int rowCount) { BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() - .GetLastFinancialAccountRows(Identity, rowCount); - return FinancialAccountRows.FromArray(basicRows); + .GetLastFinancialAccountRows (Identity, rowCount); + return FinancialAccountRows.FromArray (basicRows); } - public FinancialAccountRows GetRows(DateTime start, DateTime end) + public FinancialAccountRows GetRows (DateTime start, DateTime end) { BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() - .GetFinancialAccountRows(Identity, start, end, false); - return FinancialAccountRows.FromArray(basicRows); + .GetFinancialAccountRows (Identity, start, end, false); + return FinancialAccountRows.FromArray (basicRows); } - public FinancialAccountRows GetRowsFar(DateTime start, DateTime end) // selects lowerbound < x <= upperbound + public FinancialAccountRows GetRowsFar (DateTime start, DateTime end) // selects lowerbound < x <= upperbound { BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() - .GetFinancialAccountRows(Identity, start, end, true); - return FinancialAccountRows.FromArray(basicRows); + .GetFinancialAccountRows (Identity, start, end, true); + return FinancialAccountRows.FromArray (basicRows); } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetBudgetCents instead.") + [Obsolete ("This method uses floating point for financials. Deprecated. Do not use; use GetBudgetCents instead." + ) ] - public double GetBudget(int year) + public double GetBudget (int year) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(Identity, year); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget (Identity, year); } - public Int64 GetBudgetCents(int year) + public Int64 GetBudgetCents (int year) { - return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(Identity, year)*100); + return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget (Identity, year)*100); } - public Int64[] GetBudgetMonthly(int year) + public Int64[] GetBudgetMonthly (int year) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudgetMonthly(Identity, year); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudgetMonthly (Identity, year); } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use.")] - public void SetBudget(int year, double amount) + [Obsolete ("This method uses floating point for financials. Deprecated. Do not use.")] + public void SetBudget (int year, double amount) { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(Identity, year, amount); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget (Identity, year, amount); } - public void SetBudgetCents(int year, Int64 amount) + public void SetBudgetCents (int year, Int64 amount) { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(Identity, year, amount/100.0); - // TODO: Change db structure to use cents + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget (Identity, year, amount/100.0); + // TODO: Change db structure to use cents } - public void SetBudgetMontly(int year, int month, Int64 amountCents) + public void SetBudgetMontly (int year, int month, Int64 amountCents) { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudgetMonthly(Identity, year, month, amountCents); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudgetMonthly (Identity, year, month, amountCents); } - public static FinancialAccount Create(Organization organization, string newAccountName, + public static FinancialAccount Create (Organization organization, string newAccountName, FinancialAccountType accountType, FinancialAccount parentAccount) { - return Create(organization.Identity, newAccountName, accountType, + return Create (organization.Identity, newAccountName, accountType, parentAccount == null ? 0 : parentAccount.Identity); } - protected static FinancialAccount Create(int organizationId, string name, FinancialAccountType accountType, + protected static FinancialAccount Create (int organizationId, string name, FinancialAccountType accountType, int parentFinancialAccountId) { int accountId = SwarmDb.GetDatabaseForWriting() - .CreateFinancialAccount(organizationId, name, accountType, parentFinancialAccountId); - return FromIdentityAggressive(accountId); + .CreateFinancialAccount (organizationId, name, accountType, parentFinancialAccountId); + return FromIdentityAggressive (accountId); } public FinancialAccounts GetTree() { - return FinancialAccounts.GetTree(this); + return FinancialAccounts.GetTree (this); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialAccountRow.cs b/Logic/Financial/FinancialAccountRow.cs index 574cf083..0afb094b 100644 --- a/Logic/Financial/FinancialAccountRow.cs +++ b/Logic/Financial/FinancialAccountRow.cs @@ -6,8 +6,8 @@ namespace Swarmops.Logic.Financial { #region Construction and Creation - private FinancialAccountRow(BasicFinancialAccountRow basic) - : base(basic) + private FinancialAccountRow (BasicFinancialAccountRow basic) + : base (basic) { } @@ -16,16 +16,16 @@ namespace Swarmops.Logic.Financial get { return AmountCents/100.0m; } } - public static FinancialAccountRow FromBasic(BasicFinancialAccountRow basic) + public static FinancialAccountRow FromBasic (BasicFinancialAccountRow basic) { - return new FinancialAccountRow(basic); + return new FinancialAccountRow (basic); } #endregion public FinancialTransaction Transaction { - get { return FinancialTransaction.FromIdentity(FinancialTransactionId); } + get { return FinancialTransaction.FromIdentity (FinancialTransactionId); } } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialAccountRows.cs b/Logic/Financial/FinancialAccountRows.cs index bebd23d4..ba7708a2 100644 --- a/Logic/Financial/FinancialAccountRows.cs +++ b/Logic/Financial/FinancialAccountRows.cs @@ -5,13 +5,13 @@ namespace Swarmops.Logic.Financial { public class FinancialAccountRows : List { - public static FinancialAccountRows FromArray(BasicFinancialAccountRow[] array) + public static FinancialAccountRows FromArray (BasicFinancialAccountRow[] array) { FinancialAccountRows result = new FinancialAccountRows {Capacity = (array.Length*11/10)}; foreach (BasicFinancialAccountRow basic in array) { - result.Add(FinancialAccountRow.FromBasic(basic)); + result.Add (FinancialAccountRow.FromBasic (basic)); } return result; diff --git a/Logic/Financial/FinancialAccounts.cs b/Logic/Financial/FinancialAccounts.cs index fd23885c..1556ecc9 100644 --- a/Logic/Financial/FinancialAccounts.cs +++ b/Logic/Financial/FinancialAccounts.cs @@ -11,21 +11,22 @@ namespace Swarmops.Logic.Financial { public class FinancialAccounts : PluralBase { - public static FinancialAccounts ForOrganization(Organization organization) + public static FinancialAccounts ForOrganization (Organization organization) { return - FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountTreeForOrganization(organization.Identity)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetFinancialAccountTreeForOrganization (organization.Identity)); } - public static FinancialAccounts ForOwner(Person person) + public static FinancialAccounts ForOwner (Person person) { - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountsOwnedByPerson(person.Identity)); + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialAccountsOwnedByPerson (person.Identity)); } - public static FinancialAccounts ForOrganization(Organization organization, FinancialAccountType accountType) + public static FinancialAccounts ForOrganization (Organization organization, FinancialAccountType accountType) { - FinancialAccounts allAccounts = ForOrganization(organization); + FinancialAccounts allAccounts = ForOrganization (organization); if (accountType == FinancialAccountType.All) { @@ -51,75 +52,75 @@ namespace Swarmops.Logic.Financial foreach (FinancialAccount account in allAccounts) { - if (lookup.ContainsKey(account.AccountType)) + if (lookup.ContainsKey (account.AccountType)) { - result.Add(account); + result.Add (account); } } return result; } - public static FinancialAccounts FromBankTransactionTag(string tag) + public static FinancialAccounts FromBankTransactionTag (string tag) { int[] accountIdentities = - SwarmDb.GetDatabaseForReading().GetObjectsByOptionalData(ObjectType.FinancialAccount, + SwarmDb.GetDatabaseForReading().GetObjectsByOptionalData (ObjectType.FinancialAccount, ObjectOptionalDataType. BankTransactionTag, tag.ToLower()); - return FromIdentities(accountIdentities); + return FromIdentities (accountIdentities); } - public static FinancialAccounts FromIdentities(int[] financialAccountIds) + public static FinancialAccounts FromIdentities (int[] financialAccountIds) { if (financialAccountIds.Length == 0) { return new FinancialAccounts(); } - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccounts(financialAccountIds)); + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialAccounts (financialAccountIds)); } - public FinancialAccountRows GetRows(DateTime start, DateTime end) + public FinancialAccountRows GetRows (DateTime start, DateTime end) { BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() - .GetFinancialAccountRows(Identities, start, end, false); - return FinancialAccountRows.FromArray(basicRows); + .GetFinancialAccountRows (Identities, start, end, false); + return FinancialAccountRows.FromArray (basicRows); } - public FinancialAccountRows GetRowsFar(DateTime start, DateTime end) + public FinancialAccountRows GetRowsFar (DateTime start, DateTime end) { BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() - .GetFinancialAccountRows(Identities, start, end, true); - return FinancialAccountRows.FromArray(basicRows); + .GetFinancialAccountRows (Identities, start, end, true); + return FinancialAccountRows.FromArray (basicRows); } - [Obsolete("This function uses double-point variables for money. Use GetBudgetSumCents instead.")] - public double GetBudgetSum(int year) + [Obsolete ("This function uses double-point variables for money. Use GetBudgetSumCents instead.")] + public double GetBudgetSum (int year) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(Identities, year); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget (Identities, year); } - public Int64 GetBudgetSumCents(int year) + public Int64 GetBudgetSumCents (int year) { // TODO: Add support in database - return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(Identities, year)*100); + return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget (Identities, year)*100); } - public Int64 GetDeltaCents(DateTime start, DateTime end) + public Int64 GetDeltaCents (DateTime start, DateTime end) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(Identities, start, end); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents (Identities, start, end); } - public static FinancialAccounts GetTree(FinancialAccount rootAccount) + public static FinancialAccounts GetTree (FinancialAccount rootAccount) { - Dictionary nodes = GetHashedAccounts(rootAccount.Organization); + Dictionary nodes = GetHashedAccounts (rootAccount.Organization); - return GetTree(nodes, rootAccount.Identity, 0); + return GetTree (nodes, rootAccount.Identity, 0); } @@ -139,7 +140,7 @@ namespace Swarmops.Logic.Financial }*/ - private static FinancialAccounts GetTree(Dictionary accounts, int startNodeId, + private static FinancialAccounts GetTree (Dictionary accounts, int startNodeId, int generation) { FinancialAccounts result = new FinancialAccounts(); @@ -150,17 +151,17 @@ namespace Swarmops.Logic.Financial { if (account.Identity != startNodeId) { - result.Add(account); + result.Add (account); // Add recursively - FinancialAccounts children = GetTree(accounts, account.Identity, generation + 1); + FinancialAccounts children = GetTree (accounts, account.Identity, generation + 1); if (children.Count > 0) { foreach (FinancialAccount child in children) { - result.Add(child); + result.Add (child); } } } @@ -168,14 +169,14 @@ namespace Swarmops.Logic.Financial { // The top parent is special and should be added; the others shouldn't - result.Add(account); + result.Add (account); } } return result; } - public static Dictionary GetHashedAccounts(Organization organization) + public static Dictionary GetHashedAccounts (Organization organization) { // This generates a Dictionary >. // @@ -188,14 +189,14 @@ namespace Swarmops.Logic.Financial Dictionary result = new Dictionary(); FinancialAccounts allAccounts = - FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountsForOrganization(organization.Identity)); + FromArray (SwarmDb.GetDatabaseForReading().GetFinancialAccountsForOrganization (organization.Identity)); // Add the nodes. foreach (FinancialAccount account in allAccounts) { FinancialAccounts accounts = new FinancialAccounts(); - accounts.Add(account); + accounts.Add (account); result[account.Identity] = accounts; } @@ -206,7 +207,7 @@ namespace Swarmops.Logic.Financial foreach (FinancialAccount account in allAccounts) { - result[account.ParentIdentity].Add(account); + result[account.ParentIdentity].Add (account); } return result; diff --git a/Logic/Financial/FinancialTransaction.cs b/Logic/Financial/FinancialTransaction.cs index 5a5a160f..61eaeb08 100644 --- a/Logic/Financial/FinancialTransaction.cs +++ b/Logic/Financial/FinancialTransaction.cs @@ -14,62 +14,63 @@ namespace Swarmops.Logic.Financial { #region Construction and Creation - private FinancialTransaction(BasicFinancialTransaction basic) - : base(basic) + private FinancialTransaction (BasicFinancialTransaction basic) + : base (basic) { } - public static FinancialTransaction FromBasic(BasicFinancialTransaction basic) + public static FinancialTransaction FromBasic (BasicFinancialTransaction basic) { - return new FinancialTransaction(basic); + return new FinancialTransaction (basic); } - public static FinancialTransaction FromIdentity(int financialTransactionId) + public static FinancialTransaction FromIdentity (int financialTransactionId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransaction(financialTransactionId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransaction (financialTransactionId)); } - public static FinancialTransaction FromIdentityAggressive(int financialTransactionId) + public static FinancialTransaction FromIdentityAggressive (int financialTransactionId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetFinancialTransaction(financialTransactionId)); - // ForWriting intentional - bypass replication lag + return FromBasic (SwarmDb.GetDatabaseForWriting().GetFinancialTransaction (financialTransactionId)); + // ForWriting intentional - bypass replication lag } - public static FinancialTransaction FromDependency(IHasIdentity dependency) + public static FinancialTransaction FromDependency (IHasIdentity dependency) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionFromDependency(dependency)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransactionFromDependency (dependency)); } - public static FinancialTransaction FromImportKey(Organization organization, string importKey) + public static FinancialTransaction FromImportKey (Organization organization, string importKey) { return - FromBasic(SwarmDb.GetDatabaseForReading() - .GetFinancialTransactionFromImportKey(organization.Identity, importKey)); + FromBasic (SwarmDb.GetDatabaseForReading() + .GetFinancialTransactionFromImportKey (organization.Identity, importKey)); } - public static FinancialTransaction ImportWithStub(int organizationId, DateTime dateTime, int financialAccountId, + public static FinancialTransaction ImportWithStub (int organizationId, DateTime dateTime, int financialAccountId, Int64 amountCents, string description, string importHash, int personId) { - int transactionId = SwarmDb.GetDatabaseForWriting().CreateFinancialTransactionStub(organizationId, dateTime, - financialAccountId, amountCents, - description, importHash, personId); + int transactionId = SwarmDb.GetDatabaseForWriting() + .CreateFinancialTransactionStub (organizationId, dateTime, + financialAccountId, amountCents, + description, importHash, personId); if (transactionId == 0) { return null; // This was a dupe -- already imported, as determined by ImportHash } - return FromIdentityAggressive(transactionId); + return FromIdentityAggressive (transactionId); } - public static FinancialTransaction Create(int organizationId, DateTime dateTime, string description) + public static FinancialTransaction Create (int organizationId, DateTime dateTime, string description) { int transactionId = SwarmDb.GetDatabaseForWriting() - .CreateFinancialTransaction(organizationId, dateTime, description); - return FromIdentityAggressive(transactionId); + .CreateFinancialTransaction (organizationId, dateTime, description); + return FromIdentityAggressive (transactionId); } #endregion @@ -79,17 +80,17 @@ namespace Swarmops.Logic.Financial get { return - FinancialTransactionRows.FromArray( - SwarmDb.GetDatabaseForReading().GetFinancialTransactionRows(Identity)); + FinancialTransactionRows.FromArray ( + SwarmDb.GetDatabaseForReading().GetFinancialTransactionRows (Identity)); } } public Documents Documents { - get { return Documents.ForObject(this); } + get { return Documents.ForObject (this); } } - public Int64 this[FinancialAccount account] + public Int64 this [FinancialAccount account] { get { @@ -115,7 +116,7 @@ namespace Swarmops.Logic.Financial set { base.Description = value; - SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDescription(Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDescription (Identity, value); } } @@ -125,7 +126,7 @@ namespace Swarmops.Logic.Financial { try { - return FromDependency(this); + return FromDependency (this); } catch (ArgumentException) { @@ -138,8 +139,8 @@ namespace Swarmops.Logic.Financial { set { - SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDependency( - Identity, GetFinancialDependencyType(value), value.Identity); + SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDependency ( + Identity, GetFinancialDependencyType (value), value.Identity); } get { @@ -150,7 +151,7 @@ namespace Swarmops.Logic.Financial FinancialDependencyType dependencyType; int foreignId; - SwarmDb.GetDatabaseForReading().GetFinancialTransactionDependency(Identity, out dependencyType, + SwarmDb.GetDatabaseForReading().GetFinancialTransactionDependency (Identity, out dependencyType, out foreignId); if (foreignId == 0) @@ -160,59 +161,59 @@ namespace Swarmops.Logic.Financial if (dependencyType == FinancialDependencyType.ExpenseClaim) { - return ExpenseClaim.FromIdentity(foreignId); + return ExpenseClaim.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.InboundInvoice) { - return InboundInvoice.FromIdentity(foreignId); + return InboundInvoice.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.OutboundInvoice) { - return OutboundInvoice.FromIdentity(foreignId); + return OutboundInvoice.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.Salary) { - return Salary.FromIdentity(foreignId); + return Salary.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.Payout) { - return Payout.FromIdentity(foreignId); + return Payout.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.PaymentGroup) { - return PaymentGroup.FromIdentity(foreignId); + return PaymentGroup.FromIdentity (foreignId); } if (dependencyType == FinancialDependencyType.FinancialTransaction) { - return FromIdentity(foreignId); + return FromIdentity (foreignId); } - throw new NotImplementedException("Unimplemented dependency type: " + dependencyType); + throw new NotImplementedException ("Unimplemented dependency type: " + dependencyType); } } - [Obsolete("Do not use double-precision methods. They leak cents. Use AddRow (FinancialAccount, Int64, Person).", + [Obsolete ("Do not use double-precision methods. They leak cents. Use AddRow (FinancialAccount, Int64, Person).", true)] - public void AddRow(FinancialAccount account, double amount, Person person) + public void AddRow (FinancialAccount account, double amount, Person person) { - AddRow(account, (Int64) (amount*100), person); + AddRow (account, (Int64) (amount*100), person); } - public void AddRow(FinancialAccount account, Int64 amountCents, Person person) + public void AddRow (FinancialAccount account, Int64 amountCents, Person person) { - AddRow(account.Identity, amountCents, person != null ? person.Identity : 0); + AddRow (account.Identity, amountCents, person != null ? person.Identity : 0); } - private void AddRow(int financialAccountId, Int64 amountCents, int personId) + private void AddRow (int financialAccountId, Int64 amountCents, int personId) { if (DateTime.Year <= - FinancialAccount.FromIdentity(financialAccountId).Organization.Parameters.FiscalBooksClosedUntilYear) + FinancialAccount.FromIdentity (financialAccountId).Organization.Parameters.FiscalBooksClosedUntilYear) { // Recurse down into continuation transactions to write row in first nonclosed year @@ -222,42 +223,42 @@ namespace Swarmops.Logic.Financial { // No continuation; create one - transactionContinued = Create(OrganizationId, DateTime.Now, + transactionContinued = Create (OrganizationId, DateTime.Now, "Continued Tx #" + Identity); - transactionContinued.AddRow(financialAccountId, amountCents, personId); + transactionContinued.AddRow (financialAccountId, amountCents, personId); transactionContinued.Dependency = this; } else { // Recurse - transactionContinued.AddRow(financialAccountId, amountCents, personId); + transactionContinued.AddRow (financialAccountId, amountCents, personId); } return; } SwarmDb.GetDatabaseForWriting() - .CreateFinancialTransactionRow(Identity, financialAccountId, amountCents, personId); + .CreateFinancialTransactionRow (Identity, financialAccountId, amountCents, personId); } - public void AddDocument(string serverFileName, string originalFileName, Int64 fileSize, string description, + public void AddDocument (string serverFileName, string originalFileName, Int64 fileSize, string description, Person uploader) { // Determine a new client file name - int indexOfLastPeriod = originalFileName.LastIndexOf('.'); - string extension = originalFileName.Substring(indexOfLastPeriod).ToLower(); + int indexOfLastPeriod = originalFileName.LastIndexOf ('.'); + string extension = originalFileName.Substring (indexOfLastPeriod).ToLower(); string newClientFileName = "transaction_" + Identity + "_document_" + - DateTime.Now.ToString("yyyyMMddHHmmss") + extension; + DateTime.Now.ToString ("yyyyMMddHHmmss") + extension; // Create the document - Document.Create(serverFileName, newClientFileName, fileSize, description, this, uploader); + Document.Create (serverFileName, newClientFileName, fileSize, description, this, uploader); } - private static FinancialDependencyType GetFinancialDependencyType(IHasIdentity foreignObject) + private static FinancialDependencyType GetFinancialDependencyType (IHasIdentity foreignObject) { if (foreignObject is ExpenseClaim) { @@ -288,21 +289,21 @@ namespace Swarmops.Logic.Financial return FinancialDependencyType.FinancialTransaction; } - throw new NotImplementedException("Unidentified dependency encountered in GetFinancialDependencyType:" + - foreignObject.GetType()); + throw new NotImplementedException ("Unidentified dependency encountered in GetFinancialDependencyType:" + + foreignObject.GetType()); } - public void CreateTag(FinancialTransactionTagType tagType, Person creatingPerson) + public void CreateTag (FinancialTransactionTagType tagType, Person creatingPerson) { // TODO: Verify that there isn't already a tag in this set in the transaction, and if so, delete it first - SwarmDb.GetDatabaseForWriting().CreateFinancialTransactionTag(Identity, tagType.Identity); + SwarmDb.GetDatabaseForWriting().CreateFinancialTransactionTag (Identity, tagType.Identity); // TODO: Log that the tag was added (and by whom?) } - public FinancialTransactionTagType GetTag(FinancialTransactionTagSet tagSet) + public FinancialTransactionTagType GetTag (FinancialTransactionTagSet tagSet) { // We're lazy: we're getting ALL tags and picking out the correct one. It's a minimum of overhead given that // there should be at most five records in the most advanced scenarios, and this is cheaper than doing it @@ -310,7 +311,7 @@ namespace Swarmops.Logic.Financial // Possible todo: cache tags (it's likely there are several calls in a row). - FinancialTransactionTagTypes tagTypes = FinancialTransactionTagTypes.ForTransaction(this); + FinancialTransactionTagTypes tagTypes = FinancialTransactionTagTypes.ForTransaction (this); foreach (FinancialTransactionTagType tagType in tagTypes) { @@ -326,7 +327,7 @@ namespace Swarmops.Logic.Financial } - public bool RecalculateTransaction(Dictionary nominalTransaction, Person loggingPerson) + public bool RecalculateTransaction (Dictionary nominalTransaction, Person loggingPerson) { // TODO: Update dimension 2 with dimension 1 P&L accounts as template @@ -343,7 +344,7 @@ namespace Swarmops.Logic.Financial foreach (FinancialTransactionRow row in Rows) { - if (!currentTransaction.ContainsKey(row.FinancialAccountId)) + if (!currentTransaction.ContainsKey (row.FinancialAccountId)) { currentTransaction[row.FinancialAccountId] = 0; } @@ -355,8 +356,8 @@ namespace Swarmops.Logic.Financial if (continuedTransaction != null) { - continuedTransaction.AddContinuedTransactionsToLookup(currentTransaction); - // Recurses to all continued transactions + continuedTransaction.AddContinuedTransactionsToLookup (currentTransaction); + // Recurses to all continued transactions } // Step 2: create an image of what the transaction SHOULD look like with changes. @@ -367,7 +368,7 @@ namespace Swarmops.Logic.Financial foreach (int accountId in currentTransaction.Keys) { - if (!nominalTransaction.ContainsKey(accountId)) + if (!nominalTransaction.ContainsKey (accountId)) { nominalTransaction[accountId] = 0; } @@ -375,7 +376,7 @@ namespace Swarmops.Logic.Financial foreach (int accountId in nominalTransaction.Keys) { - if (!currentTransaction.ContainsKey(accountId)) + if (!currentTransaction.ContainsKey (accountId)) { currentTransaction[accountId] = 0; } @@ -388,7 +389,7 @@ namespace Swarmops.Logic.Financial { if (currentTransaction[accountId] != nominalTransaction[accountId]) { - AddRow(accountId, nominalTransaction[accountId] - currentTransaction[accountId], + AddRow (accountId, nominalTransaction[accountId] - currentTransaction[accountId], loggingPerson == null ? 0 : loggingPerson.Identity); changedTransaction = true; } @@ -400,18 +401,18 @@ namespace Swarmops.Logic.Financial return changedTransaction; } - private void AddContinuedTransactionsToLookup(Dictionary currentTransactionData) + private void AddContinuedTransactionsToLookup (Dictionary currentTransactionData) { FinancialTransaction continuedTransaction = ContinuedTransaction; if (continuedTransaction != null) { - continuedTransaction.AddContinuedTransactionsToLookup(currentTransactionData); + continuedTransaction.AddContinuedTransactionsToLookup (currentTransactionData); } foreach (FinancialTransactionRow row in Rows) { - if (!currentTransactionData.ContainsKey(row.FinancialAccountId)) + if (!currentTransactionData.ContainsKey (row.FinancialAccountId)) { currentTransactionData[row.FinancialAccountId] = 0; } diff --git a/Logic/Financial/FinancialTransactionRow.cs b/Logic/Financial/FinancialTransactionRow.cs index ab04fcd9..d6a97c79 100644 --- a/Logic/Financial/FinancialTransactionRow.cs +++ b/Logic/Financial/FinancialTransactionRow.cs @@ -9,8 +9,8 @@ namespace Swarmops.Logic.Financial private FinancialAccount account; private FinancialTransaction transaction; - private FinancialTransactionRow(BasicFinancialTransactionRow basic) - : base(basic) + private FinancialTransactionRow (BasicFinancialTransactionRow basic) + : base (basic) { } @@ -20,7 +20,7 @@ namespace Swarmops.Logic.Financial { if (this.transaction == null) { - this.transaction = FinancialTransaction.FromIdentity(base.FinancialTransactionId); + this.transaction = FinancialTransaction.FromIdentity (base.FinancialTransactionId); } return this.transaction; @@ -33,7 +33,7 @@ namespace Swarmops.Logic.Financial { if (this.account == null) { - this.account = FinancialAccount.FromIdentity(base.FinancialAccountId); + this.account = FinancialAccount.FromIdentity (base.FinancialAccountId); } return this.account; @@ -45,20 +45,20 @@ namespace Swarmops.Logic.Financial get { return Account.Name; } } - [Obsolete("Do not use. Use Int64 AmountCents.", true)] + [Obsolete ("Do not use. Use Int64 AmountCents.", true)] public decimal Amount { get { return AmountCents/100.0m; } } - public static FinancialTransactionRow FromBasic(BasicFinancialTransactionRow basic) + public static FinancialTransactionRow FromBasic (BasicFinancialTransactionRow basic) { - return new FinancialTransactionRow(basic); + return new FinancialTransactionRow (basic); } - public static FinancialTransactionRow FromIdentity(int identity) + public static FinancialTransactionRow FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionRow(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransactionRow (identity)); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionRows.cs b/Logic/Financial/FinancialTransactionRows.cs index 937ef0d5..19700721 100644 --- a/Logic/Financial/FinancialTransactionRows.cs +++ b/Logic/Financial/FinancialTransactionRows.cs @@ -7,7 +7,7 @@ namespace Swarmops.Logic.Financial { public class FinancialTransactionRows : List { - [Obsolete("Do not use. Use AmountCentsTotal.", true)] + [Obsolete ("Do not use. Use AmountCentsTotal.", true)] public decimal AmountTotal { get @@ -36,7 +36,7 @@ namespace Swarmops.Logic.Financial } } - [Obsolete("Do not use. Use Int64 BalanceCentsDelta.", true)] + [Obsolete ("Do not use. Use Int64 BalanceCentsDelta.", true)] public decimal BalanceDelta { get @@ -73,13 +73,13 @@ namespace Swarmops.Logic.Financial } } - public static FinancialTransactionRows FromArray(BasicFinancialTransactionRow[] basicArray) + public static FinancialTransactionRows FromArray (BasicFinancialTransactionRow[] basicArray) { FinancialTransactionRows result = new FinancialTransactionRows {Capacity = (basicArray.Length*11/10)}; foreach (BasicFinancialTransactionRow basic in basicArray) { - result.Add(FinancialTransactionRow.FromBasic(basic)); + result.Add (FinancialTransactionRow.FromBasic (basic)); } return result; diff --git a/Logic/Financial/FinancialTransactionTagSet.cs b/Logic/Financial/FinancialTransactionTagSet.cs index 20792c76..077f0ecc 100644 --- a/Logic/Financial/FinancialTransactionTagSet.cs +++ b/Logic/Financial/FinancialTransactionTagSet.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial { public class FinancialTransactionTagSet : BasicFinancialTransactionTagSet { - private FinancialTransactionTagSet(BasicFinancialTransactionTagSet basic) : base(basic) + private FinancialTransactionTagSet (BasicFinancialTransactionTagSet basic) : base (basic) { // ctor } @@ -15,14 +15,14 @@ namespace Swarmops.Logic.Financial get { return (TagSetProfitLossType) base.ProfitLossType; } } - public static FinancialTransactionTagSet FromBasic(BasicFinancialTransactionTagSet basic) + public static FinancialTransactionTagSet FromBasic (BasicFinancialTransactionTagSet basic) { - return new FinancialTransactionTagSet(basic); + return new FinancialTransactionTagSet (basic); } - public static FinancialTransactionTagSet FromIdentity(int identity) + public static FinancialTransactionTagSet FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSet(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSet (identity)); } } diff --git a/Logic/Financial/FinancialTransactionTagSetType.cs b/Logic/Financial/FinancialTransactionTagSetType.cs index d40ae92b..30b59dd5 100644 --- a/Logic/Financial/FinancialTransactionTagSetType.cs +++ b/Logic/Financial/FinancialTransactionTagSetType.cs @@ -5,18 +5,18 @@ namespace Swarmops.Logic.Financial { public class FinancialTransactionTagSetType { - public static string GetLocalizedName(int identity) + public static string GetLocalizedName (int identity) { if (identity < 0) { string resource = ((FinancialTransactionTagSetTypesStock) identity).ToString(); return - Logic_Financial_FinancialTransactionTagSetTypesStock.ResourceManager.GetString( + Logic_Financial_FinancialTransactionTagSetTypesStock.ResourceManager.GetString ( resource); } - throw new NotImplementedException("Custom set names are not implemented yet"); + throw new NotImplementedException ("Custom set names are not implemented yet"); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagSets.cs b/Logic/Financial/FinancialTransactionTagSets.cs index d988898b..60cf346b 100644 --- a/Logic/Financial/FinancialTransactionTagSets.cs +++ b/Logic/Financial/FinancialTransactionTagSets.cs @@ -8,9 +8,9 @@ namespace Swarmops.Logic.Financial public class FinancialTransactionTagSets : PluralBase { - public static FinancialTransactionTagSets ForOrganization(Organization organization) + public static FinancialTransactionTagSets ForOrganization (Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSets(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSets (organization)); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagType.cs b/Logic/Financial/FinancialTransactionTagType.cs index e342ca60..39c2392c 100644 --- a/Logic/Financial/FinancialTransactionTagType.cs +++ b/Logic/Financial/FinancialTransactionTagType.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial { public class FinancialTransactionTagType : BasicFinancialTransactionTagType { - private FinancialTransactionTagType(BasicFinancialTransactionTagType basicTagType) : base(basicTagType) + private FinancialTransactionTagType (BasicFinancialTransactionTagType basicTagType) : base (basicTagType) { // private ctor } @@ -15,14 +15,14 @@ namespace Swarmops.Logic.Financial get { return base.ParentFinancialTransactionTagTypeId; } } - public static FinancialTransactionTagType FromBasic(BasicFinancialTransactionTagType basic) + public static FinancialTransactionTagType FromBasic (BasicFinancialTransactionTagType basic) { - return new FinancialTransactionTagType(basic); + return new FinancialTransactionTagType (basic); } - public static FinancialTransactionTagType FromIdentity(int identity) + public static FinancialTransactionTagType FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagType(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagType (identity)); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagTypes.cs b/Logic/Financial/FinancialTransactionTagTypes.cs index 3aba4e68..1164779a 100644 --- a/Logic/Financial/FinancialTransactionTagTypes.cs +++ b/Logic/Financial/FinancialTransactionTagTypes.cs @@ -7,27 +7,27 @@ namespace Swarmops.Logic.Financial public class FinancialTransactionTagTypes : PluralBase { - public static FinancialTransactionTagTypes ForSet(FinancialTransactionTagSet set) + public static FinancialTransactionTagTypes ForSet (FinancialTransactionTagSet set) { - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes(set)); + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes (set)); } - public static FinancialTransactionTagTypes FromIdentities(int[] identities) + public static FinancialTransactionTagTypes FromIdentities (int[] identities) { - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypesByIdentity(identities)); + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypesByIdentity (identities)); } - public static FinancialTransactionTagTypes ForTransaction(FinancialTransaction transaction) + public static FinancialTransactionTagTypes ForTransaction (FinancialTransaction transaction) { int[] tagTypeIdentities = - SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes(transaction.Identity); + SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes (transaction.Identity); if (tagTypeIdentities.Length == 0) { return new FinancialTransactionTagTypes(); // none, so return empty set } - return FromIdentities(tagTypeIdentities); + return FromIdentities (tagTypeIdentities); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactions.cs b/Logic/Financial/FinancialTransactions.cs index 44f9a76e..b79ce2c5 100644 --- a/Logic/Financial/FinancialTransactions.cs +++ b/Logic/Financial/FinancialTransactions.cs @@ -11,25 +11,25 @@ namespace Swarmops.Logic.Financial public class FinancialTransactions : PluralBase { - public static FinancialTransactions GetIncomplete(Organization organization) + public static FinancialTransactions GetIncomplete (Organization organization) { - return GetIncomplete(organization.Identity); + return GetIncomplete (organization.Identity); } - public static FinancialTransactions GetUnbalanced(Organization organization) + public static FinancialTransactions GetUnbalanced (Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetUnbalancedFinancialTransactions(organization.Identity)); + return FromArray (SwarmDb.GetDatabaseForReading().GetUnbalancedFinancialTransactions (organization.Identity)); } - public static FinancialTransactions GetIncomplete(int organizationId) + public static FinancialTransactions GetIncomplete (int organizationId) { FinancialTransactions unbalanced = - FromArray(SwarmDb.GetDatabaseForReading().GetUnbalancedFinancialTransactions(organizationId)); + FromArray (SwarmDb.GetDatabaseForReading().GetUnbalancedFinancialTransactions (organizationId)); FinancialTransactions undocumented = - FromArray(SwarmDb.GetDatabaseForReading().GetUndocumentedFinancialTransactions(organizationId)); + FromArray (SwarmDb.GetDatabaseForReading().GetUndocumentedFinancialTransactions (organizationId)); - FinancialTransactions allIncomplete = LogicalOr(unbalanced, undocumented); + FinancialTransactions allIncomplete = LogicalOr (unbalanced, undocumented); // filter by year, too // HACK: get book-close date from Org object @@ -40,23 +40,24 @@ namespace Swarmops.Logic.Financial { if (transaction.DateTime.Year > 2009) { - result.Add(transaction); + result.Add (transaction); } } return result; } - public static FinancialTransactions ForDependentObject(IHasIdentity foreignObject) + public static FinancialTransactions ForDependentObject (IHasIdentity foreignObject) { return - FromArray( - SwarmDb.GetDatabaseForReading().GetDependentFinancialTransactions(GetDependencyType(foreignObject), - foreignObject.Identity)); + FromArray ( + SwarmDb.GetDatabaseForReading() + .GetDependentFinancialTransactions (GetDependencyType (foreignObject), + foreignObject.Identity)); } - private static FinancialDependencyType GetDependencyType(IHasIdentity foreignObject) + private static FinancialDependencyType GetDependencyType (IHasIdentity foreignObject) { if (foreignObject is ExpenseClaim) { @@ -67,7 +68,7 @@ namespace Swarmops.Logic.Financial return FinancialDependencyType.InboundInvoice; } - throw new NotImplementedException("Unimplemented dependency type:" + foreignObject.GetType()); + throw new NotImplementedException ("Unimplemented dependency type:" + foreignObject.GetType()); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialValidation.cs b/Logic/Financial/FinancialValidation.cs index d41d036e..811eb083 100644 --- a/Logic/Financial/FinancialValidation.cs +++ b/Logic/Financial/FinancialValidation.cs @@ -5,19 +5,19 @@ namespace Swarmops.Logic.Financial { public class FinancialValidation : BasicFinancialValidation { - private FinancialValidation(BasicFinancialValidation basic) - : base(basic) + private FinancialValidation (BasicFinancialValidation basic) + : base (basic) { } public Person Person { - get { return Person.FromIdentity(PersonId); } + get { return Person.FromIdentity (PersonId); } } - public static FinancialValidation FromBasic(BasicFinancialValidation basic) + public static FinancialValidation FromBasic (BasicFinancialValidation basic) { - return new FinancialValidation(basic); + return new FinancialValidation (basic); } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialValidations.cs b/Logic/Financial/FinancialValidations.cs index a8748b7e..c236f320 100644 --- a/Logic/Financial/FinancialValidations.cs +++ b/Logic/Financial/FinancialValidations.cs @@ -10,21 +10,21 @@ namespace Swarmops.Logic.Financial { public class FinancialValidations : PluralBase { - public static void Create(FinancialValidationType validationType, IHasIdentity foreignObject, + public static void Create (FinancialValidationType validationType, IHasIdentity foreignObject, Person actingPerson) { - Create(validationType, foreignObject, actingPerson, 0.0); + Create (validationType, foreignObject, actingPerson, 0.0); } - public static void Create(FinancialValidationType validationType, IHasIdentity foreignObject, + public static void Create (FinancialValidationType validationType, IHasIdentity foreignObject, Person actingPerson, double amount) { SwarmDb.GetDatabaseForWriting() - .CreateFinancialValidation(validationType, GetDependencyType(foreignObject), foreignObject.Identity, + .CreateFinancialValidation (validationType, GetDependencyType (foreignObject), foreignObject.Identity, DateTime.Now, actingPerson.Identity, amount); } - private static FinancialDependencyType GetDependencyType(IHasIdentity foreignObject) + private static FinancialDependencyType GetDependencyType (IHasIdentity foreignObject) { if (foreignObject is ExpenseClaim) { @@ -39,15 +39,15 @@ namespace Swarmops.Logic.Financial return FinancialDependencyType.Salary; } - throw new NotImplementedException("Unknown dependency: " + foreignObject.GetType()); + throw new NotImplementedException ("Unknown dependency: " + foreignObject.GetType()); } - public static FinancialValidations ForObject(IHasIdentity financialDependency) + public static FinancialValidations ForObject (IHasIdentity financialDependency) { return - FromArray(SwarmDb.GetDatabaseForReading() - .GetFinancialValidations(GetDependencyType(financialDependency), + FromArray (SwarmDb.GetDatabaseForReading() + .GetFinancialValidations (GetDependencyType (financialDependency), financialDependency.Identity)); } } diff --git a/Logic/Financial/IAttestable.cs b/Logic/Financial/IAttestable.cs index 5b71079f..b37a3c35 100644 --- a/Logic/Financial/IAttestable.cs +++ b/Logic/Financial/IAttestable.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial public interface IAttestable { FinancialAccount Budget { get; } - void Attest(Person attester); - void Deattest(Person deattester); + void Attest (Person attester); + void Deattest (Person deattester); } } \ No newline at end of file diff --git a/Logic/Financial/IBankDataAccountStatementReader.cs b/Logic/Financial/IBankDataAccountStatementReader.cs index bf3b1161..4c460b99 100644 --- a/Logic/Financial/IBankDataAccountStatementReader.cs +++ b/Logic/Financial/IBankDataAccountStatementReader.cs @@ -4,6 +4,6 @@ namespace Swarmops.Logic.Financial { internal interface IBankDataAccountStatementReader { - ImportedBankData ReadData(StreamReader data, FinancialAccount account, ExternalBankDataProfile profile); + ImportedBankData ReadData (StreamReader data, FinancialAccount account, ExternalBankDataProfile profile); } } \ No newline at end of file diff --git a/Logic/Financial/IValidatable.cs b/Logic/Financial/IValidatable.cs index dc7be721..bd7d1a91 100644 --- a/Logic/Financial/IValidatable.cs +++ b/Logic/Financial/IValidatable.cs @@ -4,7 +4,7 @@ namespace Swarmops.Logic.Financial { public interface IValidatable { - void Validate(Person validator); - void Devalidate(Person devalidator); + void Validate (Person validator); + void Devalidate (Person devalidator); } } \ No newline at end of file diff --git a/Logic/Financial/InboundInvoice.cs b/Logic/Financial/InboundInvoice.cs index 89b1376e..757c1dab 100644 --- a/Logic/Financial/InboundInvoice.cs +++ b/Logic/Financial/InboundInvoice.cs @@ -14,15 +14,15 @@ namespace Swarmops.Logic.Financial { public class InboundInvoice : BasicInboundInvoice, IAttestable { - private InboundInvoice(BasicInboundInvoice basicInstance) : - base(basicInstance) + private InboundInvoice (BasicInboundInvoice basicInstance) : + base (basicInstance) { // constructor from basic type } public Documents Documents { - get { return Documents.ForObject(this); } + get { return Documents.ForObject (this); } } public new bool Open @@ -32,7 +32,7 @@ namespace Swarmops.Logic.Financial { if (base.Open != value) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceOpen (Identity, value); base.Open = value; } } @@ -40,7 +40,7 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } @@ -57,7 +57,7 @@ namespace Swarmops.Logic.Financial { if (value != base.DueDate) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceDueDate(Identity, value); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceDueDate (Identity, value); base.DueDate = value; } } @@ -67,7 +67,7 @@ namespace Swarmops.Logic.Financial { get { - FinancialTransactions transactions = FinancialTransactions.ForDependentObject(this); + FinancialTransactions transactions = FinancialTransactions.ForDependentObject (this); if (transactions.Count == 0) { @@ -79,14 +79,14 @@ namespace Swarmops.Logic.Financial return transactions[0]; } - throw new InvalidOperationException("It appears inbound invoice #" + Identity + - " has multiple dependent financial transactions. This is an invalid state."); + throw new InvalidOperationException ("It appears inbound invoice #" + Identity + + " has multiple dependent financial transactions. This is an invalid state."); } } public FinancialValidations Validations { - get { return FinancialValidations.ForObject(this); } + get { return FinancialValidations.ForObject (this); } } @@ -95,32 +95,32 @@ namespace Swarmops.Logic.Financial get { return - ObjectOptionalData.ForObject(this).GetOptionalDataString( + ObjectOptionalData.ForObject (this).GetOptionalDataString ( ObjectOptionalDataType.InboundInvoiceDescription); } set { - ObjectOptionalData.ForObject(this) - .SetOptionalDataString(ObjectOptionalDataType.InboundInvoiceDescription, value); + ObjectOptionalData.ForObject (this) + .SetOptionalDataString (ObjectOptionalDataType.InboundInvoiceDescription, value); } } #region IAttestable Members - public void Attest(Person attester) + public void Attest (Person attester) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(Identity, true); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested (Identity, true); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.InboundInvoice, Identity, DateTime.Now, attester.Identity, (double) Amount); base.Attested = true; } - public void Deattest(Person deattester) + public void Deattest (Person deattester) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(Identity, false); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested (Identity, false); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Deattestation, FinancialDependencyType.InboundInvoice, Identity, DateTime.Now, deattester.Identity, (double) Amount); base.Attested = false; @@ -137,16 +137,16 @@ namespace Swarmops.Logic.Financial return null; } - return FinancialAccount.FromIdentity(base.BudgetId); + return FinancialAccount.FromIdentity (base.BudgetId); } } - public static InboundInvoice Create(Organization organization, DateTime dueDate, Int64 amountCents, + public static InboundInvoice Create (Organization organization, DateTime dueDate, Int64 amountCents, FinancialAccount budget, string supplier, string description, string payToAccount, string ocr, string invoiceReference, Person creatingPerson) { - InboundInvoice newInvoice = FromIdentity(SwarmDb.GetDatabaseForWriting(). - CreateInboundInvoice(organization.Identity, dueDate, budget.Identity, + InboundInvoice newInvoice = FromIdentity (SwarmDb.GetDatabaseForWriting(). + CreateInboundInvoice (organization.Identity, dueDate, budget.Identity, supplier, payToAccount, ocr, invoiceReference, amountCents, creatingPerson.Identity)); @@ -155,11 +155,11 @@ namespace Swarmops.Logic.Financial // Create a corresponding financial transaction with rows FinancialTransaction transaction = - FinancialTransaction.Create(organization.Identity, DateTime.Now, + FinancialTransaction.Create (organization.Identity, DateTime.Now, "Invoice #" + newInvoice.Identity + " from " + supplier); - transaction.AddRow(organization.FinancialAccounts.DebtsInboundInvoices, -amountCents, creatingPerson); - transaction.AddRow(budget, amountCents, creatingPerson); + transaction.AddRow (organization.FinancialAccounts.DebtsInboundInvoices, -amountCents, creatingPerson); + transaction.AddRow (budget, amountCents, creatingPerson); // Make the transaction dependent on the inbound invoice @@ -167,44 +167,44 @@ namespace Swarmops.Logic.Financial // Create notification (slightly misplaced logic, but this is failsafest place) - OutboundComm.CreateNotificationAttestationNeeded(budget, creatingPerson, supplier, amountCents/100.0, + OutboundComm.CreateNotificationAttestationNeeded (budget, creatingPerson, supplier, amountCents/100.0, description, NotificationResource.InboundInvoice_Created); - // Slightly misplaced logic, but failsafer here - SwarmopsLogEntry.Create(creatingPerson, - new InboundInvoiceCreatedLogEntry(creatingPerson, supplier, description, amountCents/100.0, budget), + // Slightly misplaced logic, but failsafer here + SwarmopsLogEntry.Create (creatingPerson, + new InboundInvoiceCreatedLogEntry (creatingPerson, supplier, description, amountCents/100.0, budget), newInvoice); return newInvoice; } - public static InboundInvoice FromBasic(BasicInboundInvoice basic) + public static InboundInvoice FromBasic (BasicInboundInvoice basic) { - return new InboundInvoice(basic); + return new InboundInvoice (basic); } - public static InboundInvoice FromIdentity(int inboundInvoiceId) + public static InboundInvoice FromIdentity (int inboundInvoiceId) { - return new InboundInvoice(SwarmDb.GetDatabaseForReading().GetInboundInvoice(inboundInvoiceId)); + return new InboundInvoice (SwarmDb.GetDatabaseForReading().GetInboundInvoice (inboundInvoiceId)); } - public void SetBudget(FinancialAccount budget, Person settingPerson) + public void SetBudget (FinancialAccount budget, Person settingPerson) { base.BudgetId = budget.Identity; - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceBudget(Identity, budget.Identity); - UpdateTransaction(settingPerson); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceBudget (Identity, budget.Identity); + UpdateTransaction (settingPerson); } - public void SetAmountCents(Int64 amountCents, Person settingPerson) + public void SetAmountCents (Int64 amountCents, Person settingPerson) { base.AmountCents = amountCents; - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAmount(Identity, amountCents); - UpdateTransaction(settingPerson); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAmount (Identity, amountCents); + UpdateTransaction (settingPerson); } - private void UpdateTransaction(Person updatingPerson) + private void UpdateTransaction (Person updatingPerson) { Dictionary nominalTransaction = new Dictionary(); @@ -218,7 +218,7 @@ namespace Swarmops.Logic.Financial nominalTransaction[BudgetId] = AmountCents; } - FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); + FinancialTransaction.RecalculateTransaction (nominalTransaction, updatingPerson); } } } \ No newline at end of file diff --git a/Logic/Financial/InboundInvoices.cs b/Logic/Financial/InboundInvoices.cs index d93020dc..636457e5 100644 --- a/Logic/Financial/InboundInvoices.cs +++ b/Logic/Financial/InboundInvoices.cs @@ -14,7 +14,7 @@ namespace Swarmops.Logic.Financial get { InboundInvoices result = new InboundInvoices(); - result.AddRange(this.Where(invoice => invoice.Attested)); + result.AddRange (this.Where (invoice => invoice.Attested)); return result; } @@ -26,7 +26,7 @@ namespace Swarmops.Logic.Financial get { InboundInvoices result = new InboundInvoices(); - result.AddRange(this.Where(invoice => invoice.Attested == false)); + result.AddRange (this.Where (invoice => invoice.Attested == false)); return result; } @@ -68,9 +68,9 @@ namespace Swarmops.Logic.Financial ///
/// The organization. /// The list of inbound invoices. - public static InboundInvoices ForOrganization(Organization organization) + public static InboundInvoices ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } /// @@ -79,9 +79,9 @@ namespace Swarmops.Logic.Financial /// The organizations. /// True to include closed records. /// The list of inbound invoices. - public static InboundInvoices ForOrganization(Organization organization, bool includeClosed) + public static InboundInvoices ForOrganization (Organization organization, bool includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInboundInvoices(organization, + return FromArray (SwarmDb.GetDatabaseForReading().GetInboundInvoices (organization, includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); diff --git a/Logic/Financial/OrganizationFinancialAccounts.cs b/Logic/Financial/OrganizationFinancialAccounts.cs index 58d8dcdd..0b8b0337 100644 --- a/Logic/Financial/OrganizationFinancialAccounts.cs +++ b/Logic/Financial/OrganizationFinancialAccounts.cs @@ -11,22 +11,22 @@ namespace Swarmops.Logic.Financial { private readonly int _organizationId; - public OrganizationFinancialAccounts(int organizationId) + public OrganizationFinancialAccounts (int organizationId) { this._organizationId = organizationId; } - public OrganizationFinancialAccounts(Organization organization) - : this(organization.Identity) + public OrganizationFinancialAccounts (Organization organization) + : this (organization.Identity) { } - public FinancialAccount this[OrganizationFinancialAccountType accountType] + public FinancialAccount this [OrganizationFinancialAccountType accountType] { get { - int accountId = SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId(this._organizationId, + int accountId = SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId (this._organizationId, accountType); if (accountId == 0) @@ -34,11 +34,11 @@ namespace Swarmops.Logic.Financial return null; // not set } - return FinancialAccount.FromIdentity(accountId); + return FinancialAccount.FromIdentity (accountId); } set { - SwarmDb.GetDatabaseForWriting().SetOrganizationFinancialAccountId(this._organizationId, accountType, + SwarmDb.GetDatabaseForWriting().SetOrganizationFinancialAccountId (this._organizationId, accountType, value.Identity); } } @@ -192,14 +192,14 @@ namespace Swarmops.Logic.Financial // THIS SERIOUSLY NEEDS OPTIMIZATION, MMMKAY? FinancialAccounts costAccounts = - FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), + FinancialAccounts.ForOrganization (Organization.FromIdentity (this._organizationId), FinancialAccountType.Cost); foreach (FinancialAccount account in costAccounts) { if (account.IsConferenceParent) { - result.Add(account); + result.Add (account); } } @@ -217,7 +217,7 @@ namespace Swarmops.Logic.Financial int yearlyResultId = CostsYearlyResult.Identity; FinancialAccounts costAccounts = - FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), + FinancialAccounts.ForOrganization (Organization.FromIdentity (this._organizationId), FinancialAccountType.Cost); foreach (FinancialAccount account in costAccounts) @@ -225,7 +225,7 @@ namespace Swarmops.Logic.Financial if (account.Identity != yearlyResultId && account.Expensable) // really should be redundant, but still... { - result.Add(account); + result.Add (account); } } @@ -243,7 +243,7 @@ namespace Swarmops.Logic.Financial int yearlyResultId = CostsYearlyResult.Identity; FinancialAccounts costAccounts = - FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), + FinancialAccounts.ForOrganization (Organization.FromIdentity (this._organizationId), FinancialAccountType.Income); foreach (FinancialAccount account in costAccounts) @@ -251,7 +251,7 @@ namespace Swarmops.Logic.Financial if (account.Identity != yearlyResultId && account.Expensable) // really should be redundant, but still... { - result.Add(account); + result.Add (account); } } diff --git a/Logic/Financial/OutboundInvoice.cs b/Logic/Financial/OutboundInvoice.cs index 6e7f0ffc..bbbe2f31 100644 --- a/Logic/Financial/OutboundInvoice.cs +++ b/Logic/Financial/OutboundInvoice.cs @@ -11,14 +11,14 @@ namespace Swarmops.Logic.Financial { public class OutboundInvoice : BasicOutboundInvoice { - private OutboundInvoice(BasicOutboundInvoice basic) : base(basic) + private OutboundInvoice (BasicOutboundInvoice basic) : base (basic) { // empty ctor } public OutboundInvoiceItems Items { - get { return OutboundInvoiceItems.ForInvoice(this); } + get { return OutboundInvoiceItems.ForInvoice (this); } } @@ -60,12 +60,12 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(BudgetId); } + get { return FinancialAccount.FromIdentity (BudgetId); } } public new bool Sent @@ -77,12 +77,12 @@ namespace Swarmops.Logic.Financial { if (value) { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceSent(Identity, true); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceSent (Identity, true); base.Sent = true; } else { - throw new InvalidOperationException("Cannot set a sent invoice to unsent status"); + throw new InvalidOperationException ("Cannot set a sent invoice to unsent status"); } } } @@ -95,7 +95,7 @@ namespace Swarmops.Logic.Financial { if (value != base.Open) { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceOpen (Identity, value); base.Open = value; } } @@ -109,7 +109,7 @@ namespace Swarmops.Logic.Financial try { - payment = Payment.ForOutboundInvoice(this); + payment = Payment.ForOutboundInvoice (this); } catch (Exception) { @@ -124,14 +124,14 @@ namespace Swarmops.Logic.Financial get { return base.Reference; } set { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceReference(Identity, value); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceReference (Identity, value); base.Reference = value; } } public Currency Currency { - get { return Currency.FromIdentity(base.CurrencyId); } + get { return Currency.FromIdentity (base.CurrencyId); } } @@ -139,20 +139,20 @@ namespace Swarmops.Logic.Financial { get { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); - int personId = data.GetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceToPersonId); + int personId = data.GetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceToPersonId); if (personId == 0) { return null; } - return Person.FromIdentity(personId); + return Person.FromIdentity (personId); } set { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); - data.SetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceToPersonId, value.Identity); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); + data.SetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceToPersonId, value.Identity); } } @@ -160,20 +160,20 @@ namespace Swarmops.Logic.Financial { get { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); - int invoiceId = data.GetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceCreditedWithInvoice); + int invoiceId = data.GetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceCreditedWithInvoice); if (invoiceId == 0) { return null; } - return FromIdentity(invoiceId); + return FromIdentity (invoiceId); } set { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); - data.SetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceCreditedWithInvoice, value.Identity); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); + data.SetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceCreditedWithInvoice, value.Identity); } } @@ -181,116 +181,117 @@ namespace Swarmops.Logic.Financial { get { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); - int invoiceId = data.GetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceCreditsInvoice); + int invoiceId = data.GetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceCreditsInvoice); if (invoiceId == 0) { return null; } - return FromIdentity(invoiceId); + return FromIdentity (invoiceId); } set { - ObjectOptionalData data = ObjectOptionalData.ForObject(this); - data.SetOptionalDataInt(ObjectOptionalDataType.OutboundInvoiceCreditsInvoice, value.Identity); + ObjectOptionalData data = ObjectOptionalData.ForObject (this); + data.SetOptionalDataInt (ObjectOptionalDataType.OutboundInvoiceCreditsInvoice, value.Identity); } } - public static OutboundInvoice FromBasic(BasicOutboundInvoice basic) + public static OutboundInvoice FromBasic (BasicOutboundInvoice basic) { - return new OutboundInvoice(basic); + return new OutboundInvoice (basic); } - public static OutboundInvoice FromIdentity(int outboundInvoiceId) + public static OutboundInvoice FromIdentity (int outboundInvoiceId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundInvoice(outboundInvoiceId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetOutboundInvoice (outboundInvoiceId)); } - public static OutboundInvoice FromReference(string reference) + public static OutboundInvoice FromReference (string reference) { // TODO: Verify Luhn // Use identity as drogue chute - string identityString = reference.Substring(12, reference.Length - 13); + string identityString = reference.Substring (12, reference.Length - 13); - OutboundInvoice result = FromIdentity(Int32.Parse(identityString)); + OutboundInvoice result = FromIdentity (Int32.Parse (identityString)); if (result.Reference != reference) { - throw new ArgumentException("No such outbound invoice"); + throw new ArgumentException ("No such outbound invoice"); } return result; } - public static OutboundInvoice Create(Organization organization, Person createdByPerson, DateTime dueDate, + public static OutboundInvoice Create (Organization organization, Person createdByPerson, DateTime dueDate, FinancialAccount budget, string customerName, string invoiceAddressMail, string invoiceAddressPaper, Currency currency, bool domestic, string theirReference) { OutboundInvoice invoice = - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateOutboundInvoice(organization.Identity, createdByPerson != null ? createdByPerson.Identity : 0, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateOutboundInvoice (organization.Identity, + createdByPerson != null ? createdByPerson.Identity : 0, dueDate, budget.Identity, customerName, invoiceAddressPaper, invoiceAddressMail, currency.Identity, string.Empty, domestic, - Authentication.CreateRandomPassword(6), theirReference)); + Authentication.CreateRandomPassword (6), theirReference)); // Set reference invoice.Reference = - Formatting.AddLuhnChecksum(Formatting.ReverseString(DateTime.Now.ToString("yyyyMMddHHmm")) + - invoice.Identity); + Formatting.AddLuhnChecksum (Formatting.ReverseString (DateTime.Now.ToString ("yyyyMMddHHmm")) + + invoice.Identity); return invoice; } - public void AddItem(string description, double amount) + public void AddItem (string description, double amount) { - SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem(Identity, description, amount); + SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem (Identity, description, amount); } - public void AddItem(string description, Int64 amountCents) + public void AddItem (string description, Int64 amountCents) { // NOTE: MUST NOT ADD FINANCIAL TRANSACTION LINES HERE; SURCHARGES ARE ADDED AS LINE ITEMS ON PAYMENT - SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem(Identity, description, amountCents); + SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem (Identity, description, amountCents); } public void SetPaid() { Open = false; - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, OrganizationId, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, OrganizationId, Geography.RootIdentity, 0, Identity, string.Empty); } - public OutboundInvoice Credit(Person creditingPerson) + public OutboundInvoice Credit (Person creditingPerson) { - OutboundInvoice credit = Create(Organization, creditingPerson, DateTime.Now, + OutboundInvoice credit = Create (Organization, creditingPerson, DateTime.Now, Budget, CustomerName, InvoiceAddressMail, InvoiceAddressPaper, Currency, Domestic, TheirReference); if (Domestic) // TODO: LANGUAGE { - credit.AddItem("Kredit för faktura " + Reference, -AmountCents); - credit.AddItem("DETTA ÄR EN KREDITFAKTURA OCH SKA EJ BETALAS", 0.00); + credit.AddItem ("Kredit för faktura " + Reference, -AmountCents); + credit.AddItem ("DETTA ÄR EN KREDITFAKTURA OCH SKA EJ BETALAS", 0.00); - AddItem( - String.Format("KREDITERAD {0:yyyy-MM-dd} i kreditfaktura {1}", DateTime.Today, credit.Reference), + AddItem ( + String.Format ("KREDITERAD {0:yyyy-MM-dd} i kreditfaktura {1}", DateTime.Today, credit.Reference), 0.00); } else { - credit.AddItem("Credit for invoice " + Reference, -AmountCents); - credit.AddItem("THIS IS A CREDIT. DO NOT PAY.", 0.00); + credit.AddItem ("Credit for invoice " + Reference, -AmountCents); + credit.AddItem ("THIS IS A CREDIT. DO NOT PAY.", 0.00); - AddItem( - String.Format("CREDITED {0:yyyy-MM-dd} in credit invoice {1}", DateTime.Today, credit.Reference), + AddItem ( + String.Format ("CREDITED {0:yyyy-MM-dd} in credit invoice {1}", DateTime.Today, credit.Reference), 0.00); } @@ -303,13 +304,13 @@ namespace Swarmops.Logic.Financial // Create the financial transaction with rows FinancialTransaction transaction = - FinancialTransaction.Create(credit.OrganizationId, DateTime.Now, + FinancialTransaction.Create (credit.OrganizationId, DateTime.Now, "Credit Invoice #" + credit.Identity + " to " + credit.CustomerName); - transaction.AddRow( - Organization.FromIdentity(credit.OrganizationId).FinancialAccounts.AssetsOutboundInvoices, + transaction.AddRow ( + Organization.FromIdentity (credit.OrganizationId).FinancialAccounts.AssetsOutboundInvoices, credit.AmountCents, creditingPerson); - transaction.AddRow(credit.Budget, -credit.AmountCents, creditingPerson); + transaction.AddRow (credit.Budget, -credit.AmountCents, creditingPerson); // Make the transaction dependent on the credit @@ -317,7 +318,7 @@ namespace Swarmops.Logic.Financial // Create the event for PirateBot-Mono to send off mails - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoiceCreated, creditingPerson.Identity, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.OutboundInvoiceCreated, creditingPerson.Identity, OrganizationId, Geography.RootIdentity, 0, credit.Identity, string.Empty); // If this invoice was already closed, issue a credit. If not closed, close it. @@ -332,7 +333,7 @@ namespace Swarmops.Logic.Financial if (payment != null) { - payment.Refund(creditingPerson); + payment.Refund (creditingPerson); } } diff --git a/Logic/Financial/OutboundInvoiceItem.cs b/Logic/Financial/OutboundInvoiceItem.cs index 34a53d14..cbd4c1fa 100644 --- a/Logic/Financial/OutboundInvoiceItem.cs +++ b/Logic/Financial/OutboundInvoiceItem.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Financial { public class OutboundInvoiceItem : BasicOutboundInvoiceItem { - private OutboundInvoiceItem(BasicOutboundInvoiceItem basic) : base(basic) + private OutboundInvoiceItem (BasicOutboundInvoiceItem basic) : base (basic) { // empty ctor } @@ -15,14 +15,14 @@ namespace Swarmops.Logic.Financial get { return AmountCents/100.0m; } } - public static OutboundInvoiceItem FromBasic(BasicOutboundInvoiceItem basic) + public static OutboundInvoiceItem FromBasic (BasicOutboundInvoiceItem basic) { - return new OutboundInvoiceItem(basic); + return new OutboundInvoiceItem (basic); } - public static OutboundInvoiceItem FromIdentity(int outboundInvoiceItemId) + public static OutboundInvoiceItem FromIdentity (int outboundInvoiceItemId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundInvoiceItem(outboundInvoiceItemId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetOutboundInvoiceItem (outboundInvoiceItemId)); } } } \ No newline at end of file diff --git a/Logic/Financial/OutboundInvoiceItems.cs b/Logic/Financial/OutboundInvoiceItems.cs index b053d4e2..6f473183 100644 --- a/Logic/Financial/OutboundInvoiceItems.cs +++ b/Logic/Financial/OutboundInvoiceItems.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Financial { public class OutboundInvoiceItems : PluralBase { - public static OutboundInvoiceItems ForInvoice(OutboundInvoice invoice) + public static OutboundInvoiceItems ForInvoice (OutboundInvoice invoice) { - return FromArray(SwarmDb.GetDatabaseForReading().GetOutboundInvoiceItems(invoice)); + return FromArray (SwarmDb.GetDatabaseForReading().GetOutboundInvoiceItems (invoice)); } } } \ No newline at end of file diff --git a/Logic/Financial/OutboundInvoices.cs b/Logic/Financial/OutboundInvoices.cs index 9aaca39b..e4eac112 100644 --- a/Logic/Financial/OutboundInvoices.cs +++ b/Logic/Financial/OutboundInvoices.cs @@ -7,19 +7,20 @@ namespace Swarmops.Logic.Financial { public class OutboundInvoices : PluralBase { - public static OutboundInvoices ForOrganization(Organization organization) + public static OutboundInvoices ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static OutboundInvoices ForOrganization(Organization organization, bool includeClosed) + public static OutboundInvoices ForOrganization (Organization organization, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetOutboundInvoices(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetOutboundInvoices (organization)); } return - FromArray(SwarmDb.GetDatabaseForReading().GetOutboundInvoices(organization, DatabaseCondition.OpenTrue)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetOutboundInvoices (organization, DatabaseCondition.OpenTrue)); } } } \ No newline at end of file diff --git a/Logic/Financial/Payment.cs b/Logic/Financial/Payment.cs index fdb5e18b..6cef3ed3 100644 --- a/Logic/Financial/Payment.cs +++ b/Logic/Financial/Payment.cs @@ -14,8 +14,8 @@ namespace Swarmops.Logic.Financial { private PaymentInformationList informationList; - private Payment(BasicPayment payment) - : base(payment) + private Payment (BasicPayment payment) + : base (payment) { // empty copy ctor } @@ -32,7 +32,7 @@ namespace Swarmops.Logic.Financial { if (infoPiece.Type == PaymentInformationType.Freeform) { - result.Add(infoPiece.Data); + result.Add (infoPiece.Data); } } @@ -42,58 +42,58 @@ namespace Swarmops.Logic.Financial public string PayerName { - get { return GetSinglePaymentInformation(PaymentInformationType.Name); } + get { return GetSinglePaymentInformation (PaymentInformationType.Name); } } public string PayerStreet { - get { return GetSinglePaymentInformation(PaymentInformationType.Street); } + get { return GetSinglePaymentInformation (PaymentInformationType.Street); } } public string PayerPostalCode { - get { return GetSinglePaymentInformation(PaymentInformationType.PostalCode); } + get { return GetSinglePaymentInformation (PaymentInformationType.PostalCode); } } public string PayerCity { - get { return GetSinglePaymentInformation(PaymentInformationType.City); } + get { return GetSinglePaymentInformation (PaymentInformationType.City); } } public string PayerOrganizationNumber { - get { return GetSinglePaymentInformation(PaymentInformationType.OrgNumber); } + get { return GetSinglePaymentInformation (PaymentInformationType.OrgNumber); } } public PaymentGroup Group { - get { return PaymentGroup.FromIdentity(PaymentGroupId); } + get { return PaymentGroup.FromIdentity (PaymentGroupId); } } public OutboundInvoice OutboundInvoice { - get { return OutboundInvoice.FromIdentity(OutboundInvoiceId); } + get { return OutboundInvoice.FromIdentity (OutboundInvoiceId); } } - public static Payment FromBasic(BasicPayment basic) + public static Payment FromBasic (BasicPayment basic) { - return new Payment(basic); + return new Payment (basic); } - public static Payment FromIdentity(int paymentId) + public static Payment FromIdentity (int paymentId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPayment(paymentId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPayment (paymentId)); } - private static Payment FromIdentityAggressive(int paymentId) + private static Payment FromIdentityAggressive (int paymentId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPayment(paymentId)); - // "Writing" intentional - avoid race conditions + return FromBasic (SwarmDb.GetDatabaseForWriting().GetPayment (paymentId)); + // "Writing" intentional - avoid race conditions } - public static Payment ForOutboundInvoice(OutboundInvoice invoice) + public static Payment ForOutboundInvoice (OutboundInvoice invoice) { - BasicPayment[] array = SwarmDb.GetDatabaseForReading().GetPayments(invoice); + BasicPayment[] array = SwarmDb.GetDatabaseForReading().GetPayments (invoice); if (array.Length == 0) { @@ -102,18 +102,19 @@ namespace Swarmops.Logic.Financial if (array.Length > 1) { - throw new InvalidDataException("There can not be two payments for one invoice"); + throw new InvalidDataException ("There can not be two payments for one invoice"); } - return FromBasic(array[0]); + return FromBasic (array[0]); } - public static Payment Create(PaymentGroup group, double amount, string reference, string fromAccount, string key, + public static Payment Create (PaymentGroup group, double amount, string reference, string fromAccount, + string key, bool hasImage) { // Match against outbound invoice, too - OutboundInvoice invoice = OutboundInvoice.FromReference(reference); + OutboundInvoice invoice = OutboundInvoice.FromReference (reference); // TODO: Verify that invoice is not already closed; if so, issue refund @@ -121,17 +122,17 @@ namespace Swarmops.Logic.Financial invoice.Open = false; - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, group.Organization.Identity, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, group.Organization.Identity, Geography.RootIdentity, 0, invoice.Identity, string.Empty); - // TODO: REMOVE PWLOG FOR SWARMOPS in due time + // TODO: REMOVE PWLOG FOR SWARMOPS in due time return - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() - .CreatePayment(group.Identity, amount, reference, fromAccount, key, hasImage, + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + .CreatePayment (group.Identity, amount, reference, fromAccount, key, hasImage, invoice.Identity)); } - public static Payment CreateSingle(Organization organization, DateTime dateTime, Currency currency, + public static Payment CreateSingle (Organization organization, DateTime dateTime, Currency currency, Int64 amountCents, OutboundInvoice invoice, Person createdByPerson) { // TODO: Verify that invoice is not already closed; if so, issue refund @@ -140,10 +141,10 @@ namespace Swarmops.Logic.Financial invoice.SetPaid(); - PaymentGroup group = PaymentGroup.Create(organization, dateTime, currency, createdByPerson); + PaymentGroup group = PaymentGroup.Create (organization, dateTime, currency, createdByPerson); Payment newPayment = - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() - .CreatePayment(group.Identity, amountCents, string.Empty, string.Empty, string.Empty, false, + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + .CreatePayment (group.Identity, amountCents, string.Empty, string.Empty, string.Empty, false, invoice.Identity)); group.AmountCents = amountCents; @@ -154,12 +155,12 @@ namespace Swarmops.Logic.Financial { if (this.informationList == null) { - this.informationList = PaymentInformationList.ForPayment(this); - // caution: assumes the list is static over lifetime of the payment object + this.informationList = PaymentInformationList.ForPayment (this); + // caution: assumes the list is static over lifetime of the payment object } } - private string GetSinglePaymentInformation(PaymentInformationType type) + private string GetSinglePaymentInformation (PaymentInformationType type) { PopulateInformation(); @@ -174,22 +175,22 @@ namespace Swarmops.Logic.Financial return null; } - public void AddInformation(PaymentInformationType type, string data) + public void AddInformation (PaymentInformationType type, string data) { - if (!string.IsNullOrEmpty(data)) + if (!string.IsNullOrEmpty (data)) { - SwarmDb.GetDatabaseForWriting().CreatePaymentInformation(Identity, type, data); + SwarmDb.GetDatabaseForWriting().CreatePaymentInformation (Identity, type, data); } } - public void Refund(Person refundingPerson) + public void Refund (Person refundingPerson) { - Financial.Refund.Create(this, refundingPerson); + Financial.Refund.Create (this, refundingPerson); } - public void Refund(Int64 amountCents, Person refundingPerson) + public void Refund (Int64 amountCents, Person refundingPerson) { - Financial.Refund.Create(this, refundingPerson, amountCents); + Financial.Refund.Create (this, refundingPerson, amountCents); } } } \ No newline at end of file diff --git a/Logic/Financial/PaymentGroup.cs b/Logic/Financial/PaymentGroup.cs index 59295f75..18bf68e8 100644 --- a/Logic/Financial/PaymentGroup.cs +++ b/Logic/Financial/PaymentGroup.cs @@ -10,7 +10,7 @@ namespace Swarmops.Logic.Financial { public class PaymentGroup : BasicPaymentGroup, ISummable { - private PaymentGroup(BasicPaymentGroup basic) : base(basic) + private PaymentGroup (BasicPaymentGroup basic) : base (basic) { // empty ctor } @@ -21,7 +21,7 @@ namespace Swarmops.Logic.Financial set { base.Tag = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupTag(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupTag (Identity, value); } } @@ -31,7 +31,7 @@ namespace Swarmops.Logic.Financial set { base.AmountCents = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupAmount(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupAmount (Identity, value); } } @@ -46,19 +46,19 @@ namespace Swarmops.Logic.Financial set { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupOpen (Identity, value); } } public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } public Payments Payments { - get { return Payments.ForPaymentGroup(this); } + get { return Payments.ForPaymentGroup (this); } } public string Payers @@ -70,13 +70,13 @@ namespace Swarmops.Logic.Financial { string payer = payment.PayerName; - if (!string.IsNullOrEmpty(payer)) + if (!string.IsNullOrEmpty (payer)) { - payerList.Add(payer); + payerList.Add (payer); } } - return String.Join(", ", payerList.ToArray()); + return String.Join (", ", payerList.ToArray()); } } @@ -94,48 +94,48 @@ namespace Swarmops.Logic.Financial #endregion - public static PaymentGroup FromIdentity(int paymentGroupId) + public static PaymentGroup FromIdentity (int paymentGroupId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPaymentGroup(paymentGroupId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPaymentGroup (paymentGroupId)); } - private static PaymentGroup FromIdentityAggressive(int paymentGroupId) + private static PaymentGroup FromIdentityAggressive (int paymentGroupId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPaymentGroup(paymentGroupId)); - // "For writing" intentional - solves race conditions on create + return FromBasic (SwarmDb.GetDatabaseForWriting().GetPaymentGroup (paymentGroupId)); + // "For writing" intentional - solves race conditions on create } - public static PaymentGroup FromBasic(BasicPaymentGroup basic) + public static PaymentGroup FromBasic (BasicPaymentGroup basic) { - return new PaymentGroup(basic); + return new PaymentGroup (basic); } - public static PaymentGroup Create(Organization organization, DateTime timestamp, Currency currency, + public static PaymentGroup Create (Organization organization, DateTime timestamp, Currency currency, Person createdByPerson) { return - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() - .CreatePaymentGroup(organization.Identity, timestamp, + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + .CreatePaymentGroup (organization.Identity, timestamp, currency.Identity, DateTime.Now, createdByPerson == null ? 0 : createdByPerson.Identity)); } - public static PaymentGroup FromTag(Organization organization, string tag) + public static PaymentGroup FromTag (Organization organization, string tag) { BasicPaymentGroup basicGroup = SwarmDb.GetDatabaseForReading() - .GetPaymentGroupByTag(organization.Identity, tag); + .GetPaymentGroupByTag (organization.Identity, tag); if (basicGroup == null) { return null; } - return FromBasic(basicGroup); + return FromBasic (basicGroup); } - public Payment CreatePayment(double amount, string reference, string fromAccount, string key, bool hasImage) + public Payment CreatePayment (double amount, string reference, string fromAccount, string key, bool hasImage) { - return Payment.Create(this, amount, reference, fromAccount, key, hasImage); + return Payment.Create (this, amount, reference, fromAccount, key, hasImage); } @@ -144,18 +144,18 @@ namespace Swarmops.Logic.Financial // This function attempts to find a transaction that matches the payment group, a transaction that is currently unbalanced. // If found, it balances the transaction against accounts receivable and ties it to the payment group. - FinancialTransactions transactions = FinancialTransactions.GetUnbalanced(Organization); + FinancialTransactions transactions = FinancialTransactions.GetUnbalanced (Organization); - return MapTransaction(transactions); + return MapTransaction (transactions); } - public bool MapTransaction(FinancialTransactions transactions) + public bool MapTransaction (FinancialTransactions transactions) { int namespaceLength = 4; - // typically, transactions are tagged to be unique per year, so the year is added to tag to make unique + // typically, transactions are tagged to be unique per year, so the year is added to tag to make unique - switch (Char.ToLowerInvariant(Tag[5])) + switch (Char.ToLowerInvariant (Tag[5])) { case 'm': namespaceLength = 6; // unique per year and month @@ -168,20 +168,20 @@ namespace Swarmops.Logic.Financial break; } - string lookfor = Tag.Substring(5 + namespaceLength).ToLowerInvariant().Trim(); - int year = Int32.Parse(Tag.Substring(5, 4)); + string lookfor = Tag.Substring (5 + namespaceLength).ToLowerInvariant().Trim(); + int year = Int32.Parse (Tag.Substring (5, 4)); - if (Char.IsDigit(Tag[0])) + if (Char.IsDigit (Tag[0])) { - lookfor = Tag.Substring(namespaceLength); // temp - remove after PPSE books closed for 2011 - year = Int32.Parse(Tag.Substring(0, 4)); + lookfor = Tag.Substring (namespaceLength); // temp - remove after PPSE books closed for 2011 + year = Int32.Parse (Tag.Substring (0, 4)); } foreach (FinancialTransaction transaction in transactions) { if (transaction.Description.Length >= Organization.IncomingPaymentTag.Length + lookfor.Length && - transaction.Description.ToLowerInvariant().StartsWith(Organization.IncomingPaymentTag) && - transaction.Description.Trim().ToLowerInvariant().EndsWith(lookfor)) + transaction.Description.ToLowerInvariant().StartsWith (Organization.IncomingPaymentTag) && + transaction.Description.Trim().ToLowerInvariant().EndsWith (lookfor)) { if (transaction.Rows.AmountCentsTotal == AmountCents) { @@ -191,7 +191,8 @@ namespace Swarmops.Logic.Financial // match! - transaction.AddRow(Organization.FinancialAccounts.AssetsOutboundInvoices, -AmountCents, null); + transaction.AddRow (Organization.FinancialAccounts.AssetsOutboundInvoices, -AmountCents, + null); transaction.Dependency = this; Open = false; return true; diff --git a/Logic/Financial/PaymentGroups.cs b/Logic/Financial/PaymentGroups.cs index 637fa9d5..5a5b19c8 100644 --- a/Logic/Financial/PaymentGroups.cs +++ b/Logic/Financial/PaymentGroups.cs @@ -7,18 +7,19 @@ namespace Swarmops.Logic.Financial { public class PaymentGroups : PluralBase { - public static PaymentGroups ForOrganization(Organization organization) + public static PaymentGroups ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static PaymentGroups ForOrganization(Organization organization, bool includeClosed) + public static PaymentGroups ForOrganization (Organization organization, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPaymentGroups(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPaymentGroups (organization)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetPaymentGroups(organization, DatabaseCondition.OpenTrue)); + return + FromArray (SwarmDb.GetDatabaseForReading().GetPaymentGroups (organization, DatabaseCondition.OpenTrue)); } } } \ No newline at end of file diff --git a/Logic/Financial/PaymentInformation.cs b/Logic/Financial/PaymentInformation.cs index 10a2b5f5..abc61f40 100644 --- a/Logic/Financial/PaymentInformation.cs +++ b/Logic/Financial/PaymentInformation.cs @@ -6,38 +6,38 @@ namespace Swarmops.Logic.Financial { public class PaymentInformation : BasicPaymentInformation { - private PaymentInformation(BasicPaymentInformation basic) : base(basic) + private PaymentInformation (BasicPaymentInformation basic) : base (basic) { // empty } - public static PaymentInformation FromBasic(BasicPaymentInformation basic) + public static PaymentInformation FromBasic (BasicPaymentInformation basic) { - return new PaymentInformation(basic); + return new PaymentInformation (basic); } } public class PaymentInformationList : List { - public static PaymentInformationList FromArray(BasicPaymentInformation[] basicArray) + public static PaymentInformationList FromArray (BasicPaymentInformation[] basicArray) { PaymentInformationList result = new PaymentInformationList {Capacity = basicArray.Length*11/10}; foreach (BasicPaymentInformation basic in basicArray) { - result.Add(PaymentInformation.FromBasic(basic)); + result.Add (PaymentInformation.FromBasic (basic)); } return result; } - public static PaymentInformationList ForPayment(Payment payment) + public static PaymentInformationList ForPayment (Payment payment) { BasicPaymentInformation[] basicInfoList = - SwarmDb.GetDatabaseForReading().GetPaymentInformation(payment.Identity); + SwarmDb.GetDatabaseForReading().GetPaymentInformation (payment.Identity); - return FromArray(basicInfoList); + return FromArray (basicInfoList); } } } \ No newline at end of file diff --git a/Logic/Financial/Payments.cs b/Logic/Financial/Payments.cs index e636b461..4907a688 100644 --- a/Logic/Financial/Payments.cs +++ b/Logic/Financial/Payments.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Financial { public class Payments : PluralBase { - public static Payments ForPaymentGroup(PaymentGroup group) + public static Payments ForPaymentGroup (PaymentGroup group) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayments(group)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPayments (group)); } } } \ No newline at end of file diff --git a/Logic/Financial/Payout.cs b/Logic/Financial/Payout.cs index 9bdbe110..4f67ced5 100644 --- a/Logic/Financial/Payout.cs +++ b/Logic/Financial/Payout.cs @@ -18,8 +18,8 @@ namespace Swarmops.Logic.Financial { #region Creation and Construction - private Payout(BasicPayout basic) : - base(basic) + private Payout (BasicPayout basic) : + base (basic) { LoadDependencies(); } @@ -31,7 +31,7 @@ namespace Swarmops.Logic.Financial throw new NotImplementedException(); } - public static Payout Create(Payout payout) + public static Payout Create (Payout payout) { throw new NotImplementedException(); // Seems not to be needed @@ -52,59 +52,59 @@ namespace Swarmops.Logic.Financial this.DependentCashAdvancesPayout = new CashAdvances(); this.DependentCashAdvancesPayback = new CashAdvances(); - BasicFinancialDependency[] dependencies = SwarmDb.GetDatabaseForReading().GetPayoutDependencies(Identity); + BasicFinancialDependency[] dependencies = SwarmDb.GetDatabaseForReading().GetPayoutDependencies (Identity); foreach (BasicFinancialDependency dependency in dependencies) { switch (dependency.DependencyType) { case FinancialDependencyType.ExpenseClaim: - this.DependentExpenseClaims.Add(ExpenseClaim.FromIdentity(dependency.ForeignId)); + this.DependentExpenseClaims.Add (ExpenseClaim.FromIdentity (dependency.ForeignId)); break; case FinancialDependencyType.InboundInvoice: - this.DependentInvoices.Add(InboundInvoice.FromIdentity(dependency.ForeignId)); + this.DependentInvoices.Add (InboundInvoice.FromIdentity (dependency.ForeignId)); break; case FinancialDependencyType.Salary: - Salary salary = Salary.FromIdentity(dependency.ForeignId); + Salary salary = Salary.FromIdentity (dependency.ForeignId); if (salary.NetSalaryCents == AmountCents) // HACK: Assumes that tax total is not identical { - this.DependentSalariesNet.Add(salary); + this.DependentSalariesNet.Add (salary); } else { - this.DependentSalariesTax.Add(salary); + this.DependentSalariesTax.Add (salary); } break; case FinancialDependencyType.CashAdvance: - this.DependentCashAdvancesPayout.Add(CashAdvance.FromIdentity(dependency.ForeignId)); + this.DependentCashAdvancesPayout.Add (CashAdvance.FromIdentity (dependency.ForeignId)); break; case FinancialDependencyType.CashAdvancePayback: - this.DependentCashAdvancesPayback.Add(CashAdvance.FromIdentity(dependency.ForeignId)); + this.DependentCashAdvancesPayback.Add (CashAdvance.FromIdentity (dependency.ForeignId)); break; default: - throw new NotImplementedException( + throw new NotImplementedException ( "Unknown financial dependency type in Payout.LoadDependencies(): " + dependency); } } } - public static Payout FromBasic(BasicPayout basic) + public static Payout FromBasic (BasicPayout basic) { - return new Payout(basic); + return new Payout (basic); } - public static Payout FromIdentity(int payoutId) + public static Payout FromIdentity (int payoutId) { try { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPayout(payoutId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPayout (payoutId)); } catch (ArgumentException e) { - throw new InvalidOperationException(String.Format("Error loading Payout #{0}", payoutId), e); + throw new InvalidOperationException (String.Format ("Error loading Payout #{0}", payoutId), e); } } @@ -123,7 +123,7 @@ namespace Swarmops.Logic.Financial { if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutAmount(Identity, (Int64) (value*100)); + SwarmDb.GetDatabaseForWriting().SetPayoutAmount (Identity, (Int64) (value*100)); } base.AmountCents = (Int64) value*100; } @@ -136,7 +136,7 @@ namespace Swarmops.Logic.Financial { if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutAmount(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutAmount (Identity, value); } base.AmountCents = value; } @@ -149,7 +149,7 @@ namespace Swarmops.Logic.Financial { if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutReference(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutReference (Identity, value); } base.Reference = value; } @@ -162,7 +162,7 @@ namespace Swarmops.Logic.Financial get { return base.Open; } set { - SwarmDb.GetDatabaseForWriting().SetPayoutOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutOpen (Identity, value); base.Open = value; } } @@ -174,7 +174,7 @@ namespace Swarmops.Logic.Financial { if (Identity != 0) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Should never use ProtoIdentity after Identity has been established"); } @@ -184,39 +184,39 @@ namespace Swarmops.Logic.Financial foreach (InboundInvoice invoice in this.DependentInvoices) { - result += "|I" + invoice.Identity.ToString(CultureInfo.InvariantCulture); + result += "|I" + invoice.Identity.ToString (CultureInfo.InvariantCulture); } foreach (ExpenseClaim claim in this.DependentExpenseClaims) { - result += "|C" + claim.Identity.ToString(CultureInfo.InvariantCulture); + result += "|C" + claim.Identity.ToString (CultureInfo.InvariantCulture); } foreach (CashAdvance advancePayback in this.DependentCashAdvancesPayback) { - result += "|a" + advancePayback.Identity.ToString(CultureInfo.InvariantCulture); + result += "|a" + advancePayback.Identity.ToString (CultureInfo.InvariantCulture); } foreach (CashAdvance advance in this.DependentCashAdvancesPayout) { - result += "|A" + advance.Identity.ToString(CultureInfo.InvariantCulture); + result += "|A" + advance.Identity.ToString (CultureInfo.InvariantCulture); } foreach (Salary salary in this.DependentSalariesNet) { - result += "|S" + salary.Identity.ToString(CultureInfo.InvariantCulture); + result += "|S" + salary.Identity.ToString (CultureInfo.InvariantCulture); } foreach (Salary salary in this.DependentSalariesTax) { - result += "|T" + salary.Identity.ToString(CultureInfo.InvariantCulture); + result += "|T" + salary.Identity.ToString (CultureInfo.InvariantCulture); } // ReSharper restore LoopCanBeConvertedToQuery if (result.Length > 0) { - return result.Substring(1); + return result.Substring (1); } return string.Empty; @@ -231,7 +231,7 @@ namespace Swarmops.Logic.Financial { // TODO: read from db instead - throw new InvalidOperationException("Dependencies not initialized"); + throw new InvalidOperationException ("Dependencies not initialized"); } if (this.DependentInvoices.Count > 0) @@ -254,24 +254,24 @@ namespace Swarmops.Logic.Financial { return "The Tax Man"; } - throw new InvalidOperationException("No dependencies for payout #" + Identity); + throw new InvalidOperationException ("No dependencies for payout #" + Identity); } } public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } public FinancialTransaction FinancialTransaction { - get { return FinancialTransaction.FromDependency(this); } + get { return FinancialTransaction.FromDependency (this); } } - public static Payout CreateFromProtoIdentity(Person creator, string protoIdentity) + public static Payout CreateFromProtoIdentity (Person creator, string protoIdentity) { - string[] components = protoIdentity.Split('|'); + string[] components = protoIdentity.Split ('|'); int payoutId = 0; // The components can EITHER be a series of expense claims OR a single invoice. @@ -294,11 +294,11 @@ namespace Swarmops.Logic.Financial foreach (string component in components) { - int advanceId = Int32.Parse(component.Substring(1)); - CashAdvance advance = CashAdvance.FromIdentity(advanceId); - identityList.Add(advanceId); + int advanceId = Int32.Parse (component.Substring (1)); + CashAdvance advance = CashAdvance.FromIdentity (advanceId); + identityList.Add (advanceId); organizationId = advance.OrganizationId; - Organization organization = Organization.FromIdentity(advance.OrganizationId); + Organization organization = Organization.FromIdentity (advance.OrganizationId); if (bank.Length < 1) { @@ -312,14 +312,14 @@ namespace Swarmops.Logic.Financial advance.PaidOut = true; //advance.Open = false; // isn't this closed only when settling the debt? Serious bug here? - SwarmopsLogEntry.Create(creator, - new PayoutCreatedLogEntry(creator, advance.Person, organization, + SwarmopsLogEntry.Create (creator, + new PayoutCreatedLogEntry (creator, advance.Person, organization, organization.Currency, amountCents/100.0, "Cash Advance Paid Out"), advance.Person, advance); - OutboundComm.CreateNotificationOfFinancialValidation(advance.Budget, advance.Person, + OutboundComm.CreateNotificationOfFinancialValidation (advance.Budget, advance.Person, advance.AmountCents/100.0, advance.Description, NotificationResource.CashAdvance_PaidOut); } @@ -327,22 +327,22 @@ namespace Swarmops.Logic.Financial if (identityList.Count == 1) { - referenceString = "Cash Advance #" + identityList[0].ToString(CultureInfo.InvariantCulture); + referenceString = "Cash Advance #" + identityList[0].ToString (CultureInfo.InvariantCulture); } else { identityList.Sort(); - referenceString = "Cash Advances " + Formatting.GenerateRangeString(identityList); + referenceString = "Cash Advances " + Formatting.GenerateRangeString (identityList); } - payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(organizationId, bank, account, - referenceString, amountCents, DateTime.Today.AddDays(1), + payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout (organizationId, bank, account, + referenceString, amountCents, DateTime.Today.AddDays (1), creator.Identity); foreach (int advanceId in identityList) { SwarmDb.GetDatabaseForWriting() - .CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvance, + .CreatePayoutDependency (payoutId, FinancialDependencyType.CashAdvance, advanceId); } } @@ -361,12 +361,12 @@ namespace Swarmops.Logic.Financial foreach (string component in components) { - int foreignId = Int32.Parse(component.Substring(1)); + int foreignId = Int32.Parse (component.Substring (1)); if (component[0] == 'C') { - ExpenseClaim claim = ExpenseClaim.FromIdentity(foreignId); - claimIdentityList.Add(foreignId); + ExpenseClaim claim = ExpenseClaim.FromIdentity (foreignId); + claimIdentityList.Add (foreignId); if (bank.Length < 1) { @@ -383,13 +383,13 @@ namespace Swarmops.Logic.Financial claim.Repaid = true; claim.Close(); - OutboundComm.CreateNotificationOfFinancialValidation(claim.Budget, claim.Claimer, + OutboundComm.CreateNotificationOfFinancialValidation (claim.Budget, claim.Claimer, claim.AmountCents/100.0, claim.Description, NotificationResource.ExpenseClaim_PaidOut); } else if (component[0] == 'a') { - CashAdvance advancePayback = CashAdvance.FromIdentity(foreignId); - advancePaybackIdentityList.Add(foreignId); + CashAdvance advancePayback = CashAdvance.FromIdentity (foreignId); + advancePaybackIdentityList.Add (foreignId); amountCents -= advancePayback.AmountCents; advancePayback.Open = false; @@ -400,35 +400,35 @@ namespace Swarmops.Logic.Financial if (claimIdentityList.Count == 1) { - referenceString = "Expense Claim #" + claimIdentityList[0].ToString(CultureInfo.InvariantCulture); + referenceString = "Expense Claim #" + claimIdentityList[0].ToString (CultureInfo.InvariantCulture); } else { claimIdentityList.Sort(); - referenceString = "Expense Claims " + Formatting.GenerateRangeString(claimIdentityList); + referenceString = "Expense Claims " + Formatting.GenerateRangeString (claimIdentityList); } - SwarmopsLogEntry.Create(creator, - new PayoutCreatedLogEntry(creator, beneficiaryPerson, organization, + SwarmopsLogEntry.Create (creator, + new PayoutCreatedLogEntry (creator, beneficiaryPerson, organization, organization.Currency, amountCents/100.0, referenceString), beneficiaryPerson); - payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(organizationId, bank, account, - referenceString, amountCents, DateTime.Today.AddDays(1), + payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout (organizationId, bank, account, + referenceString, amountCents, DateTime.Today.AddDays (1), creator.Identity); foreach (int claimId in claimIdentityList) { SwarmDb.GetDatabaseForWriting() - .CreatePayoutDependency(payoutId, FinancialDependencyType.ExpenseClaim, + .CreatePayoutDependency (payoutId, FinancialDependencyType.ExpenseClaim, claimId); } foreach (int advancePaybackId in advancePaybackIdentityList) { SwarmDb.GetDatabaseForWriting() - .CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvancePayback, + .CreatePayoutDependency (payoutId, FinancialDependencyType.CashAdvancePayback, advancePaybackId); } } @@ -436,7 +436,7 @@ namespace Swarmops.Logic.Financial { // There is just one invoice per payout - InboundInvoice invoice = InboundInvoice.FromIdentity(Int32.Parse(components[0].Substring(1))); + InboundInvoice invoice = InboundInvoice.FromIdentity (Int32.Parse (components[0].Substring (1))); DateTime expectedPayment = invoice.DueDate; @@ -446,13 +446,14 @@ namespace Swarmops.Logic.Financial } payoutId = SwarmDb.GetDatabaseForWriting() - .CreatePayout(invoice.OrganizationId, string.Empty, invoice.PayToAccount, + .CreatePayout (invoice.OrganizationId, string.Empty, invoice.PayToAccount, invoice.Ocr.Length > 0 ? "OCR " + invoice.Ocr : "Ref# " + invoice.InvoiceReference, invoice.AmountCents, expectedPayment, creator.Identity); - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.InboundInvoice, - invoice.Identity); + SwarmDb.GetDatabaseForWriting() + .CreatePayoutDependency (payoutId, FinancialDependencyType.InboundInvoice, + invoice.Identity); invoice.Open = false; } @@ -460,16 +461,16 @@ namespace Swarmops.Logic.Financial { // Salary, net payment - Salary salary = Salary.FromIdentity(Int32.Parse(components[0].Substring(1))); + Salary salary = Salary.FromIdentity (Int32.Parse (components[0].Substring (1))); payoutId = SwarmDb.GetDatabaseForWriting() - .CreatePayout(salary.PayrollItem.OrganizationId, salary.PayrollItem.Person.BankName, + .CreatePayout (salary.PayrollItem.OrganizationId, salary.PayrollItem.Person.BankName, salary.PayrollItem.Person.BankAccount, - "Salary " + salary.PayoutDate.ToString("yyyy-MMM"), + "Salary " + salary.PayoutDate.ToString ("yyyy-MMM"), salary.NetSalaryCents, salary.PayoutDate, creator.Identity); - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.Salary, + SwarmDb.GetDatabaseForWriting().CreatePayoutDependency (payoutId, FinancialDependencyType.Salary, salary.Identity); salary.NetPaid = true; @@ -481,13 +482,13 @@ namespace Swarmops.Logic.Financial List identityList = new List(); Int64 amountCents = 0; int organizationId = 0; - DateTime payDay = DateTime.Today.AddDays(1); + DateTime payDay = DateTime.Today.AddDays (1); foreach (string component in components) { - int salaryId = Int32.Parse(component.Substring(1)); - Salary salary = Salary.FromIdentity(salaryId); - identityList.Add(salaryId); + int salaryId = Int32.Parse (component.Substring (1)); + Salary salary = Salary.FromIdentity (salaryId); + identityList.Add (salaryId); if (organizationId == 0) { @@ -501,7 +502,7 @@ namespace Swarmops.Logic.Financial } string referenceString = string.Empty; - Organization organization = Organization.FromIdentity(organizationId); + Organization organization = Organization.FromIdentity (organizationId); if (identityList.Count == 1) { @@ -510,17 +511,17 @@ namespace Swarmops.Logic.Financial else { identityList.Sort(); - referenceString = "Tax for salaries " + Formatting.GenerateRangeString(identityList); + referenceString = "Tax for salaries " + Formatting.GenerateRangeString (identityList); } payoutId = SwarmDb.GetDatabaseForWriting() - .CreatePayout(organization.Identity, "The Tax Man", organization.Parameters.TaxAccount, + .CreatePayout (organization.Identity, "The Tax Man", organization.Parameters.TaxAccount, organization.Parameters.TaxOcr, amountCents, payDay, creator.Identity); foreach (int salaryId in identityList) { - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.Salary, + SwarmDb.GetDatabaseForWriting().CreatePayoutDependency (payoutId, FinancialDependencyType.Salary, salaryId); } } @@ -529,10 +530,10 @@ namespace Swarmops.Logic.Financial throw new NotImplementedException(); } - return FromIdentity(payoutId); + return FromIdentity (payoutId); } - public void BindToTransactionAndClose(FinancialTransaction transaction, Person bindingPerson) + public void BindToTransactionAndClose (FinancialTransaction transaction, Person bindingPerson) { Dictionary accountDebitLookup = new Dictionary(); Organization organization = Organization; @@ -579,7 +580,7 @@ namespace Swarmops.Logic.Financial { if (accountDebitLookup[financialAccountId] != 0) { - transaction.AddRow(FinancialAccount.FromIdentity(financialAccountId), + transaction.AddRow (FinancialAccount.FromIdentity (financialAccountId), accountDebitLookup[financialAccountId], bindingPerson); } } @@ -595,9 +596,9 @@ namespace Swarmops.Logic.Financial } - public void MigrateDependenciesTo(Payout migrationTarget) + public void MigrateDependenciesTo (Payout migrationTarget) { - SwarmDb.GetDatabaseForWriting().MovePayoutDependencies(Identity, migrationTarget.Identity); + SwarmDb.GetDatabaseForWriting().MovePayoutDependencies (Identity, migrationTarget.Identity); migrationTarget.RecalculateAmount(); RecalculateAmount(); } @@ -624,7 +625,7 @@ namespace Swarmops.Logic.Financial if (!Open) { - throw new InvalidOperationException("Payout is already closed - cannot undo"); + throw new InvalidOperationException ("Payout is already closed - cannot undo"); } foreach (ExpenseClaim claim in this.DependentExpenseClaims) @@ -654,7 +655,7 @@ namespace Swarmops.Logic.Financial salary.TaxPaid = false; } - SwarmDb.GetDatabaseForWriting().ClearPayoutDependencies(Identity); + SwarmDb.GetDatabaseForWriting().ClearPayoutDependencies (Identity); RecalculateAmount(); Open = false; } diff --git a/Logic/Financial/Payouts.cs b/Logic/Financial/Payouts.cs index a218b354..f97af38f 100644 --- a/Logic/Financial/Payouts.cs +++ b/Logic/Financial/Payouts.cs @@ -41,38 +41,38 @@ namespace Swarmops.Logic.Financial } } - public static Payouts ForOrganization(Organization organization) + public static Payouts ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static Payouts ForOrganization(Organization organization, bool includeClosed) + public static Payouts ForOrganization (Organization organization, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayouts(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPayouts (organization)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetPayouts(organization, DatabaseCondition.OpenTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPayouts (organization, DatabaseCondition.OpenTrue)); } - public static Payouts Construct(Organization organization) + public static Payouts Construct (Organization organization) { // Construct a list of not-yet-created payouts. Basically, these are the things that // Economy hasn't yet filed with the bank. Payouts result = new Payouts(); - AddUnpaidExpenseClaims(result, organization); - AddUnpaidInboundInvoices(result, organization); - AddUnpaidSalaries(result, organization); - AddUnpaidCashAdvances(result, organization); + AddUnpaidExpenseClaims (result, organization); + AddUnpaidInboundInvoices (result, organization); + AddUnpaidSalaries (result, organization); + AddUnpaidCashAdvances (result, organization); return result; } - private static void AddUnpaidExpenseClaims(Payouts payoutList, Organization organization) + private static void AddUnpaidExpenseClaims (Payouts payoutList, Organization organization) { - ExpenseClaims claims = ExpenseClaims.FromOrganization(organization); + ExpenseClaims claims = ExpenseClaims.FromOrganization (organization); Dictionary payoutLookup = new Dictionary(); @@ -87,22 +87,22 @@ namespace Swarmops.Logic.Financial // this should be added to the list. Check if we already have pending payouts // for this person: - if (payoutLookup.ContainsKey(claim.ClaimingPersonId)) + if (payoutLookup.ContainsKey (claim.ClaimingPersonId)) { // Yes. Add claim to list. - payoutLookup[claim.ClaimingPersonId].DependentExpenseClaims.Add(claim); + payoutLookup[claim.ClaimingPersonId].DependentExpenseClaims.Add (claim); } else { // No. Create a new payout for this person. - BasicPayout basicPayout = new BasicPayout(0, organization.Identity, claim.Claimer.BankName, + BasicPayout basicPayout = new BasicPayout (0, organization.Identity, claim.Claimer.BankName, claim.Claimer.BankClearing + " / " + claim.Claimer.BankAccount, string.Empty, 0, DateTime.MinValue, false, DateTime.Now, 0); - Payout payout = Payout.FromBasic(basicPayout); + Payout payout = Payout.FromBasic (basicPayout); - payout.DependentExpenseClaims.Add(claim); + payout.DependentExpenseClaims.Add (claim); payoutLookup[claim.ClaimingPersonId] = payout; } @@ -113,18 +113,18 @@ namespace Swarmops.Logic.Financial // At this point, all the expense claims have been added - but we need to add the open // cash advances and deduct them. - CashAdvances cashAdvances = CashAdvances.ForOrganization(organization); + CashAdvances cashAdvances = CashAdvances.ForOrganization (organization); cashAdvances = cashAdvances.WherePaid; // At this point, only open and paid cash advances are in the list: they're debts to the org foreach (CashAdvance cashAdvance in cashAdvances) { - if (payoutLookup.ContainsKey(cashAdvance.PersonId)) + if (payoutLookup.ContainsKey (cashAdvance.PersonId)) { // there's a payout prepared to this person - we need to deduct the cash advance from it. - payoutLookup[cashAdvance.PersonId].DependentCashAdvancesPayback.Add(cashAdvance); + payoutLookup[cashAdvance.PersonId].DependentCashAdvancesPayback.Add (cashAdvance); } } @@ -139,7 +139,7 @@ namespace Swarmops.Logic.Financial foreach (ExpenseClaim claim in payout.DependentExpenseClaims) { newAmountCents += claim.AmountCents; - claimIds.Add(claim.Identity); + claimIds.Add (claim.Identity); } foreach (CashAdvance previousAdvance in payout.DependentCashAdvancesPayback) @@ -156,26 +156,26 @@ namespace Swarmops.Logic.Financial if (claimIds.Count == 1) { payout.Reference = "[Loc]Financial_ExpenseClaimSpecification" + lessAdvancesIndicator + "|" + - claimIds[0].ToString(CultureInfo.InvariantCulture); + claimIds[0].ToString (CultureInfo.InvariantCulture); } else { claimIds.Sort(); payout.Reference = "[Loc]Financial_ExpenseClaimsSpecification" + lessAdvancesIndicator + "|" + - Formatting.GenerateRangeString(claimIds); + Formatting.GenerateRangeString (claimIds); } if (newAmountCents > 0) { - payoutList.Add(payout); + payoutList.Add (payout); } } } - private static void AddUnpaidCashAdvances(Payouts payoutList, Organization organization) + private static void AddUnpaidCashAdvances (Payouts payoutList, Organization organization) { - CashAdvances advances = CashAdvances.ForOrganization(organization); + CashAdvances advances = CashAdvances.ForOrganization (organization); advances = advances.WhereAttested; advances = advances.WhereUnpaid; @@ -187,26 +187,26 @@ namespace Swarmops.Logic.Financial if (!advance.Open || !advance.Attested || advance.PaidOut) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Got into loop with closed/unattested/paid-out cash advances - this is not a possible state"); } - if (payoutLookup.ContainsKey(advance.PersonId)) + if (payoutLookup.ContainsKey (advance.PersonId)) { // Yes. Add claim to list. - payoutLookup[advance.PersonId].DependentCashAdvancesPayout.Add(advance); + payoutLookup[advance.PersonId].DependentCashAdvancesPayout.Add (advance); } else { // No. Create a new payout for this person. - BasicPayout basicPayout = new BasicPayout(0, organization.Identity, advance.Person.BankName, + BasicPayout basicPayout = new BasicPayout (0, organization.Identity, advance.Person.BankName, advance.Person.BankClearing + " / " + advance.Person.BankAccount, string.Empty, 0, DateTime.MinValue, false, DateTime.Now, 0); - Payout payout = Payout.FromBasic(basicPayout); + Payout payout = Payout.FromBasic (basicPayout); - payout.DependentCashAdvancesPayout.Add(advance); + payout.DependentCashAdvancesPayout.Add (advance); payoutLookup[advance.PersonId] = payout; } @@ -223,7 +223,7 @@ namespace Swarmops.Logic.Financial foreach (CashAdvance advance in payout.DependentCashAdvancesPayout) { newAmountCents += advance.AmountCents; - advanceIds.Add(advance.Identity); + advanceIds.Add (advance.Identity); } payout.AmountCents = newAmountCents; @@ -231,50 +231,50 @@ namespace Swarmops.Logic.Financial if (advanceIds.Count == 1) { payout.Reference = "[Loc]Financial_CashAdvanceSpecification|" + - advanceIds[0].ToString(CultureInfo.InvariantCulture); + advanceIds[0].ToString (CultureInfo.InvariantCulture); } else { advanceIds.Sort(); payout.Reference = "[Loc]Financial_CashAdvancesSpecification|" + - Formatting.GenerateRangeString(advanceIds); + Formatting.GenerateRangeString (advanceIds); } if (newAmountCents > 0) { - payoutList.Add(payout); + payoutList.Add (payout); } } } - private static void AddUnpaidInboundInvoices(Payouts payoutList, Organization organization) + private static void AddUnpaidInboundInvoices (Payouts payoutList, Organization organization) { - InboundInvoices invoices = InboundInvoices.ForOrganization(organization); + InboundInvoices invoices = InboundInvoices.ForOrganization (organization); foreach (InboundInvoice invoice in invoices) { if (invoice.Attested) { - BasicPayout basicPayout = new BasicPayout(0, organization.Identity, string.Empty, + BasicPayout basicPayout = new BasicPayout (0, organization.Identity, string.Empty, invoice.PayToAccount, invoice.Ocr.Length > 0 ? "OCR " + invoice.Ocr : "Ref# " + invoice.InvoiceReference, (Int64) (invoice.Amount*100), invoice.DueDate, false, DateTime.Now, 0); - Payout payout = Payout.FromBasic(basicPayout); + Payout payout = Payout.FromBasic (basicPayout); - payout.DependentInvoices.Add(invoice); + payout.DependentInvoices.Add (invoice); - payoutList.Add(payout); + payoutList.Add (payout); } } } - private static void AddUnpaidSalaries(Payouts payoutList, Organization organization) + private static void AddUnpaidSalaries (Payouts payoutList, Organization organization) { Int64 taxTotalCents = 0; - Salaries salaries = Salaries.ForOrganization(organization); + Salaries salaries = Salaries.ForOrganization (organization); List identityList = new List(); DateTime payDay = DateTime.MaxValue; @@ -290,16 +290,16 @@ namespace Swarmops.Logic.Financial PayrollItem payrollItem = salary.PayrollItem; Person employee = payrollItem.Person; - BasicPayout basicPayout = new BasicPayout(0, organization.Identity, employee.BankName, + BasicPayout basicPayout = new BasicPayout (0, organization.Identity, employee.BankName, employee.BankClearing + " / " + employee.BankAccount, "[Loc]Financial_SalarySpecification|[Date]" + - salary.PayoutDate.ToString(CultureInfo.InvariantCulture), + salary.PayoutDate.ToString (CultureInfo.InvariantCulture), salary.NetSalaryCents, salary.PayoutDate, false, DateTime.Now, 0); - Payout payout = Payout.FromBasic(basicPayout); + Payout payout = Payout.FromBasic (basicPayout); - payout.DependentSalariesNet.Add(salary); + payout.DependentSalariesNet.Add (salary); - payoutList.Add(payout); + payoutList.Add (payout); if (payDay > salary.PayoutDate) { @@ -310,7 +310,7 @@ namespace Swarmops.Logic.Financial if (!salary.TaxPaid) { taxTotalCents += salary.TaxTotalCents; - identityList.Add(salary.Identity); + identityList.Add (salary.Identity); if (payDay > salary.PayoutDate) { @@ -333,34 +333,34 @@ namespace Swarmops.Logic.Financial { identityList.Sort(); referenceString = "[Loc]Financial_TaxesSpecification|" + - Formatting.GenerateRangeString(identityList); + Formatting.GenerateRangeString (identityList); } - BasicPayout basicPayout = new BasicPayout(0, organization.Identity, "[Loc]Financial_TheTaxMan", + BasicPayout basicPayout = new BasicPayout (0, organization.Identity, "[Loc]Financial_TheTaxMan", string.Empty, referenceString, taxTotalCents, payDay, false, DateTime.Now, 0); - Payout payout = Payout.FromBasic(basicPayout); + Payout payout = Payout.FromBasic (basicPayout); foreach (int salaryId in identityList) { - payout.DependentSalariesTax.Add(Salary.FromIdentity(salaryId)); + payout.DependentSalariesTax.Add (Salary.FromIdentity (salaryId)); } - payoutList.Add(payout); + payoutList.Add (payout); } } - public static void AutomatchAgainstUnbalancedTransactions(Organization organization) + public static void AutomatchAgainstUnbalancedTransactions (Organization organization) { // Matches unbalanced financial transactions against unclosed payouts // Should this be in bot? - Payouts payouts = ForOrganization(organization); + Payouts payouts = ForOrganization (organization); - FinancialTransactions transactions = FinancialTransactions.GetUnbalanced(organization); + FinancialTransactions transactions = FinancialTransactions.GetUnbalanced (organization); foreach (FinancialTransaction transaction in transactions) { @@ -368,8 +368,8 @@ namespace Swarmops.Logic.Financial // First, establish that there are no similar transactions within 7 days. N^2 search. - DateTime timeLow = transaction.DateTime.AddDays(-7); - DateTime timeHigh = transaction.DateTime.AddDays(7); + DateTime timeLow = transaction.DateTime.AddDays (-7); + DateTime timeHigh = transaction.DateTime.AddDays (7); bool foundCompeting = false; @@ -411,8 +411,8 @@ namespace Swarmops.Logic.Financial { // HACK: While PW5 doesn't have a manual-debug interface, special case for cash advances - payoutLowerTimeLimit = transaction.DateTime.AddDays(-60); - payoutUpperTimeLimit = transaction.DateTime.AddDays(60); + payoutLowerTimeLimit = transaction.DateTime.AddDays (-60); + payoutUpperTimeLimit = transaction.DateTime.AddDays (60); } if (payout.ExpectedTransactionDate >= payoutLowerTimeLimit && @@ -423,7 +423,7 @@ namespace Swarmops.Logic.Financial try { - FinancialTransaction tiedTransaction = FinancialTransaction.FromDependency(payout); + FinancialTransaction tiedTransaction = FinancialTransaction.FromDependency (payout); // Console.WriteLine(" - - - but is tied to transaction #{0} already", tiedTransaction.Identity); break; @@ -448,8 +448,8 @@ namespace Swarmops.Logic.Financial } else { - Payout payout = Payout.FromIdentity(payoutIdFound); - payout.BindToTransactionAndClose(transaction, null); + Payout payout = Payout.FromIdentity (payoutIdFound); + payout.BindToTransactionAndClose (transaction, null); } } } diff --git a/Logic/Financial/Payroll.cs b/Logic/Financial/Payroll.cs index 5d688312..ed4847dd 100644 --- a/Logic/Financial/Payroll.cs +++ b/Logic/Financial/Payroll.cs @@ -15,9 +15,9 @@ namespace Swarmops.Logic.Financial /// /// The organization. /// The payroll. - public static Payroll ForOrganization(Organization organization) + public static Payroll ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } @@ -27,9 +27,9 @@ namespace Swarmops.Logic.Financial /// The organization to filter for. /// True to include closed records. /// The payroll. - public static Payroll ForOrganization(Organization organization, bool includeClosed) + public static Payroll ForOrganization (Organization organization, bool includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayroll(organization, + return FromArray (SwarmDb.GetDatabaseForReading().GetPayroll (organization, includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } @@ -40,7 +40,7 @@ namespace Swarmops.Logic.Financial /// The payroll. public static Payroll GetAll() { - return GetAll(false); + return GetAll (false); } @@ -49,12 +49,12 @@ namespace Swarmops.Logic.Financial /// /// True to include closed records. /// The payroll. - public static Payroll GetAll(bool includeClosed) + public static Payroll GetAll (bool includeClosed) { return - FromArray( + FromArray ( SwarmDb.GetDatabaseForReading() - .GetPayroll(includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); + .GetPayroll (includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } /// @@ -66,10 +66,10 @@ namespace Swarmops.Logic.Financial 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, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) >= 0) + String.Compare (lastRun, expectedLastRun, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) >= 0) { // nothing to do, return @@ -82,12 +82,12 @@ namespace Swarmops.Logic.Financial // TODO: Different payday per organization? Payroll payroll = GetAll(); - DateTime payday = new DateTime(today.Year, today.Month, 25); + DateTime payday = new DateTime (today.Year, today.Month, 25); foreach (PayrollItem payrollItem in payroll) { - Salary salary = Salary.Create(payrollItem, payday); - SwarmopsLog.CreateEntry(payrollItem.Person, new SalaryCreatedLogEntry(salary)); + Salary salary = Salary.Create (payrollItem, payday); + SwarmopsLog.CreateEntry (payrollItem.Person, new SalaryCreatedLogEntry (salary)); // TODO: CREATE SALARY SPECIFICATION, SEND TO PERSON } diff --git a/Logic/Financial/PayrollAdjustment.cs b/Logic/Financial/PayrollAdjustment.cs index 63ade99e..ae4c222a 100644 --- a/Logic/Financial/PayrollAdjustment.cs +++ b/Logic/Financial/PayrollAdjustment.cs @@ -6,7 +6,7 @@ namespace Swarmops.Logic.Financial { public class PayrollAdjustment : BasicPayrollAdjustment { - private PayrollAdjustment(BasicPayrollAdjustment basic) : base(basic) + private PayrollAdjustment (BasicPayrollAdjustment basic) : base (basic) { // private constructor } @@ -30,36 +30,36 @@ namespace Swarmops.Logic.Financial get { return base.AmountCents/100.0m; } } - public static PayrollAdjustment FromBasic(BasicPayrollAdjustment basic) + public static PayrollAdjustment FromBasic (BasicPayrollAdjustment basic) { - return new PayrollAdjustment(basic); // invoke private ctor + return new PayrollAdjustment (basic); // invoke private ctor } - public static PayrollAdjustment FromIdentity(int payrollAdjustmentId) + public static PayrollAdjustment FromIdentity (int payrollAdjustmentId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPayrollAdjustment(payrollAdjustmentId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPayrollAdjustment (payrollAdjustmentId)); } - public void Close(Salary salary) + public void Close (Salary salary) { if (!Open) { - throw new InvalidOperationException("Payroll adjustment #" + Identity + - " cannot be closed; is already closed"); + throw new InvalidOperationException ("Payroll adjustment #" + Identity + + " cannot be closed; is already closed"); } - SwarmDb.GetDatabaseForWriting().ClosePayrollAdjustment(Identity, salary.Identity); + SwarmDb.GetDatabaseForWriting().ClosePayrollAdjustment (Identity, salary.Identity); base.Open = false; base.SalaryId = salary.Identity; } - public static PayrollAdjustment Create(PayrollItem item, PayrollAdjustmentType type, double amount, + public static PayrollAdjustment Create (PayrollItem item, PayrollAdjustmentType type, double amount, string description) { - int id = SwarmDb.GetDatabaseForWriting().CreatePayrollAdjustment(item.Identity, type, amount, description); - return FromIdentity(id); + int id = SwarmDb.GetDatabaseForWriting().CreatePayrollAdjustment (item.Identity, type, amount, description); + return FromIdentity (id); } } } \ No newline at end of file diff --git a/Logic/Financial/PayrollAdjustments.cs b/Logic/Financial/PayrollAdjustments.cs index 7b541809..455f6a5a 100644 --- a/Logic/Financial/PayrollAdjustments.cs +++ b/Logic/Financial/PayrollAdjustments.cs @@ -6,15 +6,16 @@ namespace Swarmops.Logic.Financial { public class PayrollAdjustments : PluralBase { - public static PayrollAdjustments ForPayrollItem(PayrollItem payrollItem) + public static PayrollAdjustments ForPayrollItem (PayrollItem payrollItem) { return - FromArray(SwarmDb.GetDatabaseForReading().GetPayrollAdjustments(payrollItem, DatabaseCondition.OpenTrue)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetPayrollAdjustments (payrollItem, DatabaseCondition.OpenTrue)); } - public static PayrollAdjustments ForSalary(Salary salary) + public static PayrollAdjustments ForSalary (Salary salary) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayrollAdjustments(salary)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPayrollAdjustments (salary)); } } } \ No newline at end of file diff --git a/Logic/Financial/PayrollItem.cs b/Logic/Financial/PayrollItem.cs index 288803a3..62f94553 100644 --- a/Logic/Financial/PayrollItem.cs +++ b/Logic/Financial/PayrollItem.cs @@ -7,7 +7,7 @@ namespace Swarmops.Logic.Financial { public class PayrollItem : BasicPayrollItem { - private PayrollItem(BasicPayrollItem basic) : base(basic) + private PayrollItem (BasicPayrollItem basic) : base (basic) { // private constructor } @@ -21,12 +21,12 @@ namespace Swarmops.Logic.Financial public Person Person { - get { return Person.FromIdentity(PersonId); } + get { return Person.FromIdentity (PersonId); } } public Person ReportsToPerson { - get { return Person.FromIdentity(ReportsToPersonId); } + get { return Person.FromIdentity (ReportsToPersonId); } } public string PersonCanonical @@ -36,27 +36,27 @@ namespace Swarmops.Logic.Financial public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(BudgetId); } + get { return FinancialAccount.FromIdentity (BudgetId); } } public Country Country { - get { return Country.FromIdentity(CountryId); } + get { return Country.FromIdentity (CountryId); } } public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } - public static PayrollItem FromBasic(BasicPayrollItem basic) + public static PayrollItem FromBasic (BasicPayrollItem basic) { - return new PayrollItem(basic); // invoke private ctor + return new PayrollItem (basic); // invoke private ctor } - public static PayrollItem FromIdentity(int payrollItemId) + public static PayrollItem FromIdentity (int payrollItemId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPayrollItem(payrollItemId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPayrollItem (payrollItemId)); } } } \ No newline at end of file diff --git a/Logic/Financial/Refund.cs b/Logic/Financial/Refund.cs index 5049ff86..372a3b36 100644 --- a/Logic/Financial/Refund.cs +++ b/Logic/Financial/Refund.cs @@ -10,14 +10,14 @@ namespace Swarmops.Logic.Financial { public class Refund : BasicRefund { - private Refund(BasicRefund basic) : base(basic) + private Refund (BasicRefund basic) : base (basic) { // empty pvt ctor } public Payment Payment { - get { return Payment.FromIdentity(PaymentId); } + get { return Payment.FromIdentity (PaymentId); } } public decimal AmountDecimal @@ -35,33 +35,33 @@ namespace Swarmops.Logic.Financial } } - public static Refund FromBasic(BasicRefund basic) + public static Refund FromBasic (BasicRefund basic) { - return new Refund(basic); + return new Refund (basic); } - public static Refund FromIdentity(int refundId) + public static Refund FromIdentity (int refundId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetRefund(refundId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetRefund (refundId)); } - public static Refund Create(Payment payment, Person creatingPerson) + public static Refund Create (Payment payment, Person creatingPerson) { - return Create(payment, creatingPerson, 0L); + return Create (payment, creatingPerson, 0L); } - public static Refund Create(Payment payment, Person creatingPerson, Int64 amountCents) + public static Refund Create (Payment payment, Person creatingPerson, Int64 amountCents) { if (amountCents > payment.AmountCents) { - throw new ArgumentException("Refund amount cannot exceed payment amount"); + throw new ArgumentException ("Refund amount cannot exceed payment amount"); } Refund refund = - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateRefund(payment.Identity, creatingPerson.Identity, amountCents)); + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateRefund (payment.Identity, creatingPerson.Identity, amountCents)); - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.RefundCreated, 0, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.RefundCreated, 0, refund.Payment.OutboundInvoice.Organization.Identity, Geography.RootIdentity, 0, refund.Identity, string.Empty); diff --git a/Logic/Financial/Salaries.cs b/Logic/Financial/Salaries.cs index 5bc06c94..4e3a3587 100644 --- a/Logic/Financial/Salaries.cs +++ b/Logic/Financial/Salaries.cs @@ -14,7 +14,7 @@ namespace Swarmops.Logic.Financial get { Salaries result = new Salaries(); - result.AddRange(this.Where(salary => salary.Attested)); + result.AddRange (this.Where (salary => salary.Attested)); return result; } @@ -26,7 +26,7 @@ namespace Swarmops.Logic.Financial get { Salaries result = new Salaries(); - result.AddRange(this.Where(salary => !salary.Attested)); + result.AddRange (this.Where (salary => !salary.Attested)); return result; } @@ -35,32 +35,32 @@ namespace Swarmops.Logic.Financial public double TotalAmountNet { - get { return this.Sum(salary => salary.NetSalaryCents/100.0); } + get { return this.Sum (salary => salary.NetSalaryCents/100.0); } } public double TotalAmountTax { - get { return this.Sum(salary => salary.TaxTotalCents/100.0); } + get { return this.Sum (salary => salary.TaxTotalCents/100.0); } } public Int64 TotalAmountCentsNet { - get { return this.Sum(salary => salary.NetSalaryCents); } + get { return this.Sum (salary => salary.NetSalaryCents); } } public Int64 TotalAmountCentsTax { - get { return this.Sum(salary => salary.TaxTotalCents); } + get { return this.Sum (salary => salary.TaxTotalCents); } } - public static Salaries ForOrganization(Organization organization) + public static Salaries ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static Salaries ForOrganization(Organization organization, bool includeClosed) + public static Salaries ForOrganization (Organization organization, bool includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetSalaries(organization, + return FromArray (SwarmDb.GetDatabaseForReading().GetSalaries (organization, includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } } diff --git a/Logic/Financial/Salary.cs b/Logic/Financial/Salary.cs index c56bfe37..7f3d943b 100644 --- a/Logic/Financial/Salary.cs +++ b/Logic/Financial/Salary.cs @@ -9,7 +9,7 @@ namespace Swarmops.Logic.Financial { public class Salary : BasicSalary, IAttestable { - internal Salary(BasicSalary basic) : base(basic) + internal Salary (BasicSalary basic) : base (basic) { // private ctor } @@ -17,13 +17,13 @@ namespace Swarmops.Logic.Financial public PayrollItem PayrollItem { - get { return PayrollItem.FromIdentity(PayrollItemId); } + get { return PayrollItem.FromIdentity (PayrollItemId); } } public PayrollAdjustments Adjustments { - get { return PayrollAdjustments.ForSalary(this); } + get { return PayrollAdjustments.ForSalary (this); } } @@ -57,7 +57,7 @@ namespace Swarmops.Logic.Financial { if (value != base.NetSalaryCents) { - SwarmDb.GetDatabaseForWriting().SetSalaryNetSalary(Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryNetSalary (Identity, value); base.NetSalaryCents = value; } } @@ -109,7 +109,7 @@ namespace Swarmops.Logic.Financial get { return base.NetPaid; } set { - SwarmDb.GetDatabaseForWriting().SetSalaryNetPaid(Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryNetPaid (Identity, value); base.NetPaid = value; base.Open = !(base.NetPaid && base.TaxPaid); } @@ -120,7 +120,7 @@ namespace Swarmops.Logic.Financial get { return base.TaxPaid; } set { - SwarmDb.GetDatabaseForWriting().SetSalaryTaxPaid(Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryTaxPaid (Identity, value); base.NetPaid = value; base.Open = !(base.NetPaid && base.TaxPaid); } @@ -129,7 +129,7 @@ namespace Swarmops.Logic.Financial public FinancialValidations Validations { - get { return FinancialValidations.ForObject(this); } + get { return FinancialValidations.ForObject (this); } } // dummy comment to force a build -- remove on sight @@ -153,18 +153,18 @@ namespace Swarmops.Logic.Financial #region IAttestable Members - public void Attest(Person attester) + public void Attest (Person attester) { - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.Salary, Identity, DateTime.Now, attester.Identity, NetSalaryCents/100.0); - SwarmDb.GetDatabaseForWriting().SetSalaryAttested(Identity, true); + SwarmDb.GetDatabaseForWriting().SetSalaryAttested (Identity, true); } - public void Deattest(Person deattester) + public void Deattest (Person deattester) { - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.Salary, Identity, DateTime.Now, deattester.Identity, NetSalaryCents/100.0); - SwarmDb.GetDatabaseForWriting().SetSalaryAttested(Identity, false); + SwarmDb.GetDatabaseForWriting().SetSalaryAttested (Identity, false); } #endregion @@ -174,26 +174,26 @@ namespace Swarmops.Logic.Financial get { return PayrollItem.Budget; } } - public static Salary FromBasic(BasicSalary basic) + public static Salary FromBasic (BasicSalary basic) { - return new Salary(basic); + return new Salary (basic); } - public static Salary FromIdentity(int salaryId) + public static Salary FromIdentity (int salaryId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetSalary(salaryId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetSalary (salaryId)); } - public static Salary Create(int payrollItemId, DateTime payoutDate) + public static Salary Create (int payrollItemId, DateTime payoutDate) { - return Create(PayrollItem.FromIdentity(payrollItemId), payoutDate); + return Create (PayrollItem.FromIdentity (payrollItemId), payoutDate); } - public static Salary Create(PayrollItem payrollItem, DateTime payoutDate) + public static Salary Create (PayrollItem payrollItem, DateTime payoutDate) { // Load the existing adjustments. - PayrollAdjustments adjustments = PayrollAdjustments.ForPayrollItem(payrollItem); + PayrollAdjustments adjustments = PayrollAdjustments.ForPayrollItem (payrollItem); Int64 payCents = payrollItem.BaseSalaryCents; @@ -209,7 +209,7 @@ namespace Swarmops.Logic.Financial // calculate tax - double subtractiveTax = TaxLevels.GetTax(payrollItem.Country, payrollItem.SubtractiveTaxLevelId, + double subtractiveTax = TaxLevels.GetTax (payrollItem.Country, payrollItem.SubtractiveTaxLevelId, payCents/100.0); if (subtractiveTax < 1.0) @@ -236,28 +236,28 @@ namespace Swarmops.Logic.Financial // Create salary, close adjustments - Salary salary = Create(payrollItem, payoutDate, payCents, subtractiveTaxCents, additiveTaxCents); + Salary salary = Create (payrollItem, payoutDate, payCents, subtractiveTaxCents, additiveTaxCents); // For each adjustment, close and bind to salary foreach (PayrollAdjustment adjustment in adjustments) { - adjustment.Close(salary); + adjustment.Close (salary); } // If net is negative, create rollover adjustment if (payCents < 0) { - PayrollAdjustment rollover1 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, + PayrollAdjustment rollover1 = PayrollAdjustment.Create (payrollItem, PayrollAdjustmentType.NetAdjustment, -payCents, "Deficit rolls over to next salary"); - rollover1.Close(salary); + rollover1.Close (salary); - PayrollAdjustment rollover2 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, + PayrollAdjustment rollover2 = PayrollAdjustment.Create (payrollItem, PayrollAdjustmentType.NetAdjustment, payCents, "Deficit rolled over from " + - payoutDate.ToString("yyyy-MM-dd")); + payoutDate.ToString ("yyyy-MM-dd")); // keep rollover2 open, so the deficit from this salary is carried to the next @@ -267,13 +267,13 @@ namespace Swarmops.Logic.Financial // Add the financial transaction FinancialTransaction transaction = - FinancialTransaction.Create(payrollItem.OrganizationId, DateTime.Now, + FinancialTransaction.Create (payrollItem.OrganizationId, DateTime.Now, "Salary #" + salary.Identity + ": " + payrollItem.PersonCanonical + " " + - salary.PayoutDate.ToString("yyyy-MMM", CultureInfo.InvariantCulture)); - transaction.AddRow(payrollItem.Budget, salary.CostTotalCents, null); - transaction.AddRow(payrollItem.Organization.FinancialAccounts.DebtsSalary, -salary.NetSalaryCents, null); - transaction.AddRow(payrollItem.Organization.FinancialAccounts.DebtsTax, -salary.TaxTotalCents, null); + salary.PayoutDate.ToString ("yyyy-MMM", CultureInfo.InvariantCulture)); + transaction.AddRow (payrollItem.Budget, salary.CostTotalCents, null); + transaction.AddRow (payrollItem.Organization.FinancialAccounts.DebtsSalary, -salary.NetSalaryCents, null); + transaction.AddRow (payrollItem.Organization.FinancialAccounts.DebtsTax, -salary.TaxTotalCents, null); transaction.Dependency = salary; // Finally, check if net and/or tax are zero, and if so, mark them as already-paid (i.e. not due for payment) @@ -291,12 +291,12 @@ namespace Swarmops.Logic.Financial return salary; } - private static Salary Create(PayrollItem payrollItem, DateTime payoutDate, Int64 netSalaryCents, + private static Salary Create (PayrollItem payrollItem, DateTime payoutDate, Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateSalary(payrollItem.Identity, payoutDate, payrollItem.BaseSalaryCents, netSalaryCents, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateSalary (payrollItem.Identity, payoutDate, payrollItem.BaseSalaryCents, netSalaryCents, subtractiveTaxCents, additiveTaxCents)); } } diff --git a/Logic/Financial/TaxLevels.cs b/Logic/Financial/TaxLevels.cs index 74bc71d5..03979b85 100644 --- a/Logic/Financial/TaxLevels.cs +++ b/Logic/Financial/TaxLevels.cs @@ -6,21 +6,21 @@ namespace Swarmops.Logic.Financial { public class TaxLevels { - public static double GetTax(Country country, int taxLevelIdentifier, double grossSalary) + public static double GetTax (Country country, int taxLevelIdentifier, double grossSalary) { if (grossSalary < 1.0) // The lowest tax bracket is 1 currency unit { return 0.0; // no tax } - double taxLevel = SwarmDb.GetDatabaseForReading().GetSalaryTaxLevel(country.Identity, taxLevelIdentifier, - (int) Math.Floor(grossSalary)); + double taxLevel = SwarmDb.GetDatabaseForReading().GetSalaryTaxLevel (country.Identity, taxLevelIdentifier, + (int) Math.Floor (grossSalary)); if (taxLevel < 1.0) { // Percentage - return Math.Floor(grossSalary*taxLevel); + return Math.Floor (grossSalary*taxLevel); } // otherwise, absolute number @@ -28,14 +28,14 @@ namespace Swarmops.Logic.Financial return taxLevel; } - public static void ImportTaxLevels(Country country, int year, string data) + public static void ImportTaxLevels (Country country, int year, string data) { if (country.Code != "SE") { - throw new NotImplementedException("Can't import this country's tax levels yet"); + throw new NotImplementedException ("Can't import this country's tax levels yet"); } - string[] lines = data.Split('\n'); // if \r\n is used, the \r will be harmlessly at the end of lines + string[] lines = data.Split ('\n'); // if \r\n is used, the \r will be harmlessly at the end of lines foreach (string line in lines) { @@ -55,9 +55,9 @@ namespace Swarmops.Logic.Financial bool isPercentage = line[2] == '%' ? true : false; - int lowerBracket = Int32.Parse(line.Substring(5, 7)); - double tax = Double.Parse(line.Substring(19, 5)); - int taxLevelId = Int32.Parse(line.Substring(3, 2)); + int lowerBracket = Int32.Parse (line.Substring (5, 7)); + double tax = Double.Parse (line.Substring (19, 5)); + int taxLevelId = Int32.Parse (line.Substring (3, 2)); if (isPercentage) { @@ -65,7 +65,7 @@ namespace Swarmops.Logic.Financial } SwarmDb.GetDatabaseForWriting() - .CreateSalaryTaxLevel(country.Identity, taxLevelId, lowerBracket, year, tax); + .CreateSalaryTaxLevel (country.Identity, taxLevelId, lowerBracket, year, tax); } } } diff --git a/Logic/Financial/YearlyReport.cs b/Logic/Financial/YearlyReport.cs index c0e5e1ba..a6e05e36 100644 --- a/Logic/Financial/YearlyReport.cs +++ b/Logic/Financial/YearlyReport.cs @@ -18,7 +18,7 @@ namespace Swarmops.Logic.Financial private Dictionary[] _treeLookups; private Dictionary> _treeMap; - public static YearlyReport Create(Organization organization, int year, FinancialAccountType accountType) + public static YearlyReport Create (Organization organization, int year, FinancialAccountType accountType) { YearlyReport report = new YearlyReport(); report.Organization = organization; @@ -27,7 +27,7 @@ namespace Swarmops.Logic.Financial // Get accounts - FinancialAccounts accounts = FinancialAccounts.ForOrganization(organization, accountType); + FinancialAccounts accounts = FinancialAccounts.ForOrganization (organization, accountType); // Remove unwanted accounts @@ -39,7 +39,7 @@ namespace Swarmops.Logic.Financial if (account.Identity == resultsAccount.Identity) { - accounts.Remove(account); + accounts.Remove (account); break; } } @@ -50,24 +50,24 @@ namespace Swarmops.Logic.Financial foreach (FinancialAccount account in accounts) { - if (!report._treeMap.ContainsKey(account.ParentIdentity)) + if (!report._treeMap.ContainsKey (account.ParentIdentity)) { report._treeMap[account.ParentIdentity] = new List(); } - report._treeMap[account.ParentIdentity].Add(account); + report._treeMap[account.ParentIdentity].Add (account); } FinancialAccounts orderedList = new FinancialAccounts(); - // This list is guaranteed to have parents before children + // This list is guaranteed to have parents before children - report.PopulateOrderedList(orderedList, 0); // recursively add nodes parents-first - report.PopulateLookups(orderedList); // populate the lookup tables for results per account + report.PopulateOrderedList (orderedList, 0); // recursively add nodes parents-first + report.PopulateLookups (orderedList); // populate the lookup tables for results per account report.PopulateTotals(); report.ReportLines = new List(); - report.RecurseAddLines(report.ReportLines, 0); + report.RecurseAddLines (report.ReportLines, 0); // Aggregate accounts, if appropriate @@ -105,8 +105,8 @@ namespace Swarmops.Logic.Financial remapLookup[FinancialAccountType.Asset] = assetLine; remapLookup[FinancialAccountType.Debt] = debtLine; - newRootLevel.Add(assetLine); - newRootLevel.Add(debtLine); + newRootLevel.Add (assetLine); + newRootLevel.Add (debtLine); } else if (this._accountType == FinancialAccountType.Result) { @@ -117,12 +117,12 @@ namespace Swarmops.Logic.Financial remapLookup[FinancialAccountType.Income] = incomeLine; remapLookup[FinancialAccountType.Cost] = costLine; - newRootLevel.Add(incomeLine); - newRootLevel.Add(costLine); + newRootLevel.Add (incomeLine); + newRootLevel.Add (costLine); } else { - throw new InvalidOperationException( + throw new InvalidOperationException ( "AccountType other than Balance or Result passed to YearlyReport.AggregateAccounts()"); } @@ -130,7 +130,7 @@ namespace Swarmops.Logic.Financial { if (reportLine.AccountId == equityIdentity) { - newRootLevel.Add(reportLine); + newRootLevel.Add (reportLine); } else { @@ -140,7 +140,7 @@ namespace Swarmops.Logic.Financial aggregateLine.Children = new List(); } - aggregateLine.Children.Add(reportLine); + aggregateLine.Children.Add (reportLine); aggregateLine.AccountTreeValues.PreviousYear += reportLine.AccountTreeValues.PreviousYear; for (int quarter = 0; quarter < 4; quarter++) @@ -161,16 +161,16 @@ namespace Swarmops.Logic.Financial { this.Totals = new YearlyReportNode(); - this.Totals.PreviousYear = PopulateOneTotal(this._singleLookups[0]); - this.Totals.ThisYear = PopulateOneTotal(this._singleLookups[5]); + this.Totals.PreviousYear = PopulateOneTotal (this._singleLookups[0]); + this.Totals.ThisYear = PopulateOneTotal (this._singleLookups[5]); for (int quarter = 0; quarter < 4; quarter++) { - this.Totals.Quarters[quarter] = PopulateOneTotal(this._singleLookups[quarter + 1]); + this.Totals.Quarters[quarter] = PopulateOneTotal (this._singleLookups[quarter + 1]); } } - private Int64 PopulateOneTotal(Dictionary lookup) + private Int64 PopulateOneTotal (Dictionary lookup) { Int64[] allValues = lookup.Values.ToArray(); @@ -178,7 +178,7 @@ namespace Swarmops.Logic.Financial } - private void RecurseAddLines(List list, int renderNodeId) + private void RecurseAddLines (List list, int renderNodeId) { foreach (FinancialAccount account in this._treeMap[renderNodeId]) { @@ -186,20 +186,20 @@ namespace Swarmops.Logic.Financial newLine.AccountId = account.Identity; newLine.AccountName = account.Name; newLine.AccountType = account.AccountType; - newLine.AccountValues = CreateYearlyReportNode(account.Identity, this._singleLookups); - newLine.AccountTreeValues = CreateYearlyReportNode(account.Identity, this._treeLookups); + newLine.AccountValues = CreateYearlyReportNode (account.Identity, this._singleLookups); + newLine.AccountTreeValues = CreateYearlyReportNode (account.Identity, this._treeLookups); - if (this._treeMap.ContainsKey(account.Identity)) + if (this._treeMap.ContainsKey (account.Identity)) { - RecurseAddLines(newLine.Children, account.Identity); + RecurseAddLines (newLine.Children, account.Identity); } - list.Add(newLine); + list.Add (newLine); } } - private YearlyReportNode CreateYearlyReportNode(int accountId, Dictionary[] lookup) + private YearlyReportNode CreateYearlyReportNode (int accountId, Dictionary[] lookup) { YearlyReportNode node = new YearlyReportNode(); node.PreviousYear = lookup[0][accountId]; @@ -214,21 +214,21 @@ namespace Swarmops.Logic.Financial } - private void PopulateOrderedList(FinancialAccounts orderedList, int renderNodeId) + private void PopulateOrderedList (FinancialAccounts orderedList, int renderNodeId) { foreach (FinancialAccount account in this._treeMap[renderNodeId]) { - orderedList.Add(account); + orderedList.Add (account); - if (this._treeMap.ContainsKey(account.Identity)) + if (this._treeMap.ContainsKey (account.Identity)) { - PopulateOrderedList(orderedList, account.Identity); // recursive call + PopulateOrderedList (orderedList, account.Identity); // recursive call } } } - private void PopulateLookups(FinancialAccounts accounts) + private void PopulateLookups (FinancialAccounts accounts) { this._singleLookups = new Dictionary[6]; this._treeLookups = new Dictionary[6]; @@ -241,8 +241,8 @@ namespace Swarmops.Logic.Financial DateTime[] quarterBoundaries = { - new DateTime(this.Year, 1, 1), new DateTime(this.Year, 3, 1), new DateTime(this.Year, 6, 1), - new DateTime(this.Year, 9, 1), new DateTime(this.Year + 1, 1, 1) + new DateTime (this.Year, 1, 1), new DateTime (this.Year, 3, 1), new DateTime (this.Year, 6, 1), + new DateTime (this.Year, 9, 1), new DateTime (this.Year + 1, 1, 1) }; // 1) Actually, the accounts are already sorted. Or are supposed to be, anyway, @@ -256,17 +256,18 @@ namespace Swarmops.Logic.Financial if (this._accountType == FinancialAccountType.Result) { - this._singleLookups[0][account.Identity] = account.GetDeltaCents(new DateTime(this.Year - 1, 1, 1), - new DateTime(this.Year, 1, 1)); + this._singleLookups[0][account.Identity] = account.GetDeltaCents ( + new DateTime (this.Year - 1, 1, 1), + new DateTime (this.Year, 1, 1)); } else if (this._accountType == FinancialAccountType.Balance) { - this._singleLookups[0][account.Identity] = account.GetDeltaCents(new DateTime(1900, 1, 1), - new DateTime(this.Year, 1, 1)); + this._singleLookups[0][account.Identity] = account.GetDeltaCents (new DateTime (1900, 1, 1), + new DateTime (this.Year, 1, 1)); } else { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Can only calculate yearly reports for balance or P&L statements"); } @@ -275,7 +276,7 @@ namespace Swarmops.Logic.Financial for (int quarter = 0; quarter < 4; quarter++) { this._singleLookups[quarter + 1][account.Identity] = - account.GetDeltaCents(quarterBoundaries[quarter], + account.GetDeltaCents (quarterBoundaries[quarter], quarterBoundaries[quarter + 1]); } @@ -283,17 +284,17 @@ namespace Swarmops.Logic.Financial if (this._accountType == FinancialAccountType.Result) { - this._singleLookups[5][account.Identity] = account.GetDeltaCents(new DateTime(this.Year, 1, 1), - new DateTime(this.Year + 1, 1, 1)); + this._singleLookups[5][account.Identity] = account.GetDeltaCents (new DateTime (this.Year, 1, 1), + new DateTime (this.Year + 1, 1, 1)); } else if (this._accountType == FinancialAccountType.Balance) { - this._singleLookups[5][account.Identity] = account.GetDeltaCents(new DateTime(1900, 1, 1), - new DateTime(this.Year + 1, 1, 1)); + this._singleLookups[5][account.Identity] = account.GetDeltaCents (new DateTime (1900, 1, 1), + new DateTime (this.Year + 1, 1, 1)); } else { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Can only calculate yearly reports for balance or P&L statements"); } @@ -309,14 +310,14 @@ namespace Swarmops.Logic.Financial for (int index = 0; index < 6; index++) { - AddChildrenValuesToParents(this._treeLookups[index], accounts); + AddChildrenValuesToParents (this._treeLookups[index], accounts); } // Done. } - private void AddChildrenValuesToParents(Dictionary lookup, FinancialAccounts accounts) + private void AddChildrenValuesToParents (Dictionary lookup, FinancialAccounts accounts) { // Iterate backwards and add any value to its parent's value, as they are sorted in tree order. diff --git a/Logic/Governance/Ballot.cs b/Logic/Governance/Ballot.cs index 7492ab92..5da51e10 100644 --- a/Logic/Governance/Ballot.cs +++ b/Logic/Governance/Ballot.cs @@ -7,19 +7,19 @@ namespace Swarmops.Logic.Governance { public class Ballot : BasicBallot { - private Ballot(BasicBallot basic) : base(basic) + private Ballot (BasicBallot basic) : base (basic) { // empty ctor } public People Candidates { - get { return People.FromIdentities(SwarmDb.GetDatabaseForReading().GetBallotCandidates(Identity), true); } + get { return People.FromIdentities (SwarmDb.GetDatabaseForReading().GetBallotCandidates (Identity), true); } } public Geography Geography { - get { return Geography.FromIdentity(GeographyId); } + get { return Geography.FromIdentity (GeographyId); } } public new int Count @@ -29,7 +29,7 @@ namespace Swarmops.Logic.Governance if (value != base.Count) { base.Count = value; - SwarmDb.GetDatabaseForWriting().SetBallotCount(Identity, value); + SwarmDb.GetDatabaseForWriting().SetBallotCount (Identity, value); } } get { return base.Count; } @@ -42,39 +42,39 @@ namespace Swarmops.Logic.Governance if (value != base.DeliveryAddress) { base.DeliveryAddress = value; - SwarmDb.GetDatabaseForWriting().SetBallotDeliveryAddress(Identity, value); + SwarmDb.GetDatabaseForWriting().SetBallotDeliveryAddress (Identity, value); } } get { return base.DeliveryAddress; } } - public static Ballot FromBasic(BasicBallot basic) + public static Ballot FromBasic (BasicBallot basic) { - return new Ballot(basic); + return new Ballot (basic); } - public static Ballot FromIdentity(int ballotId) + public static Ballot FromIdentity (int ballotId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetBallot(ballotId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetBallot (ballotId)); } - public static Ballot Create(Election election, Organization organization, Geography geography, string name, + public static Ballot Create (Election election, Organization organization, Geography geography, string name, int ballotCount, string deliveryAddress) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateBallot(election.Identity, name, organization.Identity, geography.Identity, ballotCount, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateBallot (election.Identity, name, organization.Identity, geography.Identity, ballotCount, deliveryAddress)); } - public void AddCandidate(Person person) + public void AddCandidate (Person person) { - SwarmDb.GetDatabaseForWriting().CreateBallotCandidate(Identity, person.Identity); + SwarmDb.GetDatabaseForWriting().CreateBallotCandidate (Identity, person.Identity); } public void ClearCandidates() { - SwarmDb.GetDatabaseForWriting().ClearBallotCandidates(Identity); + SwarmDb.GetDatabaseForWriting().ClearBallotCandidates (Identity); } } } \ No newline at end of file diff --git a/Logic/Governance/Ballots.cs b/Logic/Governance/Ballots.cs index 909ac8d4..a7124288 100644 --- a/Logic/Governance/Ballots.cs +++ b/Logic/Governance/Ballots.cs @@ -12,14 +12,14 @@ namespace Swarmops.Logic.Governance // nothing much here - public static Ballots ForElection(Election election, Organization organization) + public static Ballots ForElection (Election election, Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetBallots(election, organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetBallots (election, organization)); } - public static Dictionary GetBallotsForPerson(Person person) + public static Dictionary GetBallotsForPerson (Person person) { - return SwarmDb.GetDatabaseForReading().GetBallotsForPerson(person.Identity); + return SwarmDb.GetDatabaseForReading().GetBallotsForPerson (person.Identity); } } } \ No newline at end of file diff --git a/Logic/Governance/Election.cs b/Logic/Governance/Election.cs index 99cb5ef1..686e74a5 100644 --- a/Logic/Governance/Election.cs +++ b/Logic/Governance/Election.cs @@ -8,54 +8,54 @@ namespace Swarmops.Logic.Governance { public class Election : BasicElection { - private Election(BasicElection basic) : base(basic) + private Election (BasicElection basic) : base (basic) { // empty private ctor } public static Election September2010 { - get { return FromIdentity(3); } + get { return FromIdentity (3); } } - public static Election FromBasic(BasicElection basic) + public static Election FromBasic (BasicElection basic) { - return new Election(basic); + return new Election (basic); } - public static Election FromIdentity(int electionId) + public static Election FromIdentity (int electionId) { switch (electionId) { case 1: return - FromBasic(new BasicElection(1, "SE General Elections", Country.FromCode("SE").GeographyId, - new DateTime(2006, 9, 17))); + FromBasic (new BasicElection (1, "SE General Elections", Country.FromCode ("SE").GeographyId, + new DateTime (2006, 9, 17))); case 2: return - FromBasic(new BasicElection(2, "SE European Elections", Country.FromCode("SE").GeographyId, - new DateTime(2009, 6, 7))); + FromBasic (new BasicElection (2, "SE European Elections", Country.FromCode ("SE").GeographyId, + new DateTime (2009, 6, 7))); case 3: return - FromBasic(new BasicElection(3, "SE General Elections", Country.FromCode("SE").GeographyId, - new DateTime(2010, 9, 19))); + FromBasic (new BasicElection (3, "SE General Elections", Country.FromCode ("SE").GeographyId, + new DateTime (2010, 9, 19))); default: - throw new NotImplementedException("Elections are not in the db yet."); + throw new NotImplementedException ("Elections are not in the db yet."); } } - public People GetDocumentedCandidates(Organization organization) + public People GetDocumentedCandidates (Organization organization) { return - People.FromIdentities(SwarmDb.GetDatabaseForReading().GetDocumentedCandidates(Identity, + People.FromIdentities (SwarmDb.GetDatabaseForReading().GetDocumentedCandidates (Identity, organization.Identity)); } - public void SetCandidateDocumented(Organization organization, Person candidate) + public void SetCandidateDocumented (Organization organization, Person candidate) { SwarmDb.GetDatabaseForWriting() - .SetCandidateDocumentationReceived(Identity, organization.Identity, candidate.Identity); + .SetCandidateDocumentationReceived (Identity, organization.Identity, candidate.Identity); } } } \ No newline at end of file diff --git a/Logic/Governance/Meeting.cs b/Logic/Governance/Meeting.cs index 07409256..01563259 100644 --- a/Logic/Governance/Meeting.cs +++ b/Logic/Governance/Meeting.cs @@ -5,19 +5,19 @@ namespace Swarmops.Logic.Governance { public class Meeting : BasicMeeting { - private Meeting(BasicMeeting basic) : base(basic) + private Meeting (BasicMeeting basic) : base (basic) { // empty ctor } - public static Meeting FromBasic(BasicMeeting basicMeeting) + public static Meeting FromBasic (BasicMeeting basicMeeting) { - return new Meeting(basicMeeting); + return new Meeting (basicMeeting); } - public static Meeting FromIdentity(int meetingId) + public static Meeting FromIdentity (int meetingId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMeeting(meetingId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetMeeting (meetingId)); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElection.cs b/Logic/Governance/MeetingElection.cs index 00f775fb..759af7a6 100644 --- a/Logic/Governance/MeetingElection.cs +++ b/Logic/Governance/MeetingElection.cs @@ -10,7 +10,7 @@ namespace Swarmops.Logic.Governance { public class MeetingElection : BasicInternalPoll { - private MeetingElection(BasicInternalPoll basic) : base(basic) + private MeetingElection (BasicInternalPoll basic) : base (basic) { // private ctor } @@ -18,27 +18,27 @@ namespace Swarmops.Logic.Governance public static MeetingElection Primaries2010Simulation { - get { return FromIdentity(1); } + get { return FromIdentity (1); } } public static MeetingElection Primaries2010 { - get { return FromIdentity(2); } + get { return FromIdentity (2); } } public static MeetingElection UpDelegates2010 { - get { return FromIdentity(3); } + get { return FromIdentity (3); } } public MeetingElectionCandidates Candidates { - get { return MeetingElectionCandidates.ForPoll(this); } + get { return MeetingElectionCandidates.ForPoll (this); } } public Organization Organization { - get { return Organization.FromIdentity(base.OrganizationId); } + get { return Organization.FromIdentity (base.OrganizationId); } } public new bool VotingOpen @@ -48,7 +48,7 @@ namespace Swarmops.Logic.Governance { if (value != base.VotingOpen) { - SwarmDb.GetDatabaseForWriting().SetInternalPollVotingOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetInternalPollVotingOpen (Identity, value); base.VotingOpen = value; } } @@ -61,7 +61,7 @@ namespace Swarmops.Logic.Governance { if (value != base.RunningOpen) { - SwarmDb.GetDatabaseForWriting().SetInternalPollRunningOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetInternalPollRunningOpen (Identity, value); base.RunningOpen = value; } } @@ -69,54 +69,54 @@ namespace Swarmops.Logic.Governance public Person Creator { - get { return Person.FromIdentity(base.CreatedByPersonId); } + get { return Person.FromIdentity (base.CreatedByPersonId); } } - public static MeetingElection FromBasic(BasicInternalPoll basic) + public static MeetingElection FromBasic (BasicInternalPoll basic) { - return new MeetingElection(basic); + return new MeetingElection (basic); } - public static MeetingElection Create(Person creator, Organization org, Geography geo, string name, + public static MeetingElection Create (Person creator, Organization org, Geography geo, string name, InternalPollResultsType resultsType, int maxVoteLength, DateTime runningOpens, DateTime runningCloses, DateTime votingOpens, DateTime votingCloses) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateInternalPoll(org.Identity, geo.Identity, name, maxVoteLength, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateInternalPoll (org.Identity, geo.Identity, name, maxVoteLength, resultsType, creator.Identity, runningOpens, runningCloses, votingOpens, votingCloses)); } - public static MeetingElection FromIdentity(int internalPollId) + public static MeetingElection FromIdentity (int internalPollId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPoll(internalPollId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetInternalPoll (internalPollId)); } - public void AddCandidate(Person person, string candidacyStatement) + public void AddCandidate (Person person, string candidacyStatement) { - MeetingElectionCandidate.Create(this, person, candidacyStatement); + MeetingElectionCandidate.Create (this, person, candidacyStatement); } - public void AddVoter(Person person) + public void AddVoter (Person person) { - SwarmDb.GetDatabaseForWriting().CreateInternalPollVoter(Identity, person.Identity); + SwarmDb.GetDatabaseForWriting().CreateInternalPollVoter (Identity, person.Identity); } - public MeetingElectionVote CreateVote(Person person, string ipAddress) + public MeetingElectionVote CreateVote (Person person, string ipAddress) { - if (SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus(Identity, person.Identity) != + if (SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus (Identity, person.Identity) != InternalPollVoterStatus.CanVote) { - throw new InvalidOperationException("Voter status is not open"); + throw new InvalidOperationException ("Voter status is not open"); } Geography voteGeography = person.Geography; // Make sure that the vote geography is not at a lower level than ElectoralCircuit. - while (voteGeography.ParentGeographyId != 0 && !voteGeography.AtLevel(GeographyLevel.ElectoralCircuit)) + while (voteGeography.ParentGeographyId != 0 && !voteGeography.AtLevel (GeographyLevel.ElectoralCircuit)) { voteGeography = voteGeography.Parent; } @@ -126,23 +126,23 @@ namespace Swarmops.Logic.Governance voteGeography = person.Geography; } - SwarmDb.GetDatabaseForWriting().CloseInternalPollVoter(Identity, person.Identity, ipAddress); - return MeetingElectionVote.Create(this, voteGeography); + SwarmDb.GetDatabaseForWriting().CloseInternalPollVoter (Identity, person.Identity, ipAddress); + return MeetingElectionVote.Create (this, voteGeography); } - public InternalPollVoterStatus GetVoterStatus(Person person) + public InternalPollVoterStatus GetVoterStatus (Person person) { - return SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus(Identity, person.Identity); + return SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus (Identity, person.Identity); } public Dictionary GetCandidatePersonMap() { - return SwarmDb.GetDatabaseForReading().GetCandidateIdPersonIdMap(Identity); + return SwarmDb.GetDatabaseForReading().GetCandidateIdPersonIdMap (Identity); } public MeetingElectionVoters GetClosedVoters() { - return MeetingElectionVoters.ForPollClosed(this); + return MeetingElectionVoters.ForPollClosed (this); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionCandidate.cs b/Logic/Governance/MeetingElectionCandidate.cs index 7683350d..7e245901 100644 --- a/Logic/Governance/MeetingElectionCandidate.cs +++ b/Logic/Governance/MeetingElectionCandidate.cs @@ -16,7 +16,7 @@ namespace Swarmops.Logic.Governance cache = new Dictionary(); } - private MeetingElectionCandidate(BasicInternalPollCandidate basic) : base(basic) + private MeetingElectionCandidate (BasicInternalPollCandidate basic) : base (basic) { // private ctor } @@ -33,7 +33,7 @@ namespace Swarmops.Logic.Governance { if (this.personCache == null) { - this.personCache = Person.FromIdentity(PersonId); + this.personCache = Person.FromIdentity (PersonId); } return this.personCache; @@ -44,15 +44,15 @@ namespace Swarmops.Logic.Governance { get { - DateTime referenceDate = new DateTime(2010, 9, 19); + DateTime referenceDate = new DateTime (2010, 9, 19); int age = referenceDate.Year - Person.Birthdate.Year; - if (referenceDate < Person.Birthdate.AddYears(age)) + if (referenceDate < Person.Birthdate.AddYears (age)) { age--; } - return String.Format("{0} år, {1}", age, Person.Geography.Name); + return String.Format ("{0} år, {1}", age, Person.Geography.Name); } } @@ -78,31 +78,31 @@ namespace Swarmops.Logic.Governance { base.CandidacyStatement = value; cache[Identity] = this; // Replace cache instance - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateStatement(Identity, value); + SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateStatement (Identity, value); } } - public static MeetingElectionCandidate FromBasic(BasicInternalPollCandidate basic) + public static MeetingElectionCandidate FromBasic (BasicInternalPollCandidate basic) { - return new MeetingElectionCandidate(basic); + return new MeetingElectionCandidate (basic); } - public static MeetingElectionCandidate FromIdentity(int internalPollCandidateId) + public static MeetingElectionCandidate FromIdentity (int internalPollCandidateId) { - if (!cache.ContainsKey(internalPollCandidateId)) + if (!cache.ContainsKey (internalPollCandidateId)) { cache[internalPollCandidateId] = - FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollCandidate(internalPollCandidateId)); + FromBasic (SwarmDb.GetDatabaseForReading().GetInternalPollCandidate (internalPollCandidateId)); } return cache[internalPollCandidateId]; } - public static MeetingElectionCandidate FromPersonAndPoll(Person person, MeetingElection poll) + public static MeetingElectionCandidate FromPersonAndPoll (Person person, MeetingElection poll) { MeetingElectionCandidates candidates = - MeetingElectionCandidates.FromArray(SwarmDb.GetDatabaseForReading() - .GetInternalPollCandidates(person, poll)); + MeetingElectionCandidates.FromArray (SwarmDb.GetDatabaseForReading() + .GetInternalPollCandidates (person, poll)); if (candidates.Count == 0) { @@ -111,7 +111,7 @@ namespace Swarmops.Logic.Governance if (candidates.Count > 1) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "A specific person can not be a candidate more than once for a specific poll"); } @@ -119,11 +119,11 @@ namespace Swarmops.Logic.Governance } - public static MeetingElectionCandidate Create(MeetingElection poll, Person person, string candidacyStatement) + public static MeetingElectionCandidate Create (MeetingElection poll, Person person, string candidacyStatement) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateInternalPollCandidate(poll.Identity, person.Identity, candidacyStatement)); + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateInternalPollCandidate (poll.Identity, person.Identity, candidacyStatement)); } public override string ToString() @@ -131,14 +131,14 @@ namespace Swarmops.Logic.Governance return Identity.ToString(); } - public void SetSortOrder(string sortOrder) + public void SetSortOrder (string sortOrder) { - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder(Identity, sortOrder); + SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder (Identity, sortOrder); } public void RandomizeSortOrder() { - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder(Identity, Guid.NewGuid().ToString()); + SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder (Identity, Guid.NewGuid().ToString()); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionCandidates.cs b/Logic/Governance/MeetingElectionCandidates.cs index e3d509af..b5c485f1 100644 --- a/Logic/Governance/MeetingElectionCandidates.cs +++ b/Logic/Governance/MeetingElectionCandidates.cs @@ -7,9 +7,9 @@ namespace Swarmops.Logic.Governance public class MeetingElectionCandidates : PluralBase { - public static MeetingElectionCandidates ForPoll(MeetingElection poll) + public static MeetingElectionCandidates ForPoll (MeetingElection poll) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollCandidates(poll)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPollCandidates (poll)); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionVote.cs b/Logic/Governance/MeetingElectionVote.cs index bae6144b..6c5c3990 100644 --- a/Logic/Governance/MeetingElectionVote.cs +++ b/Logic/Governance/MeetingElectionVote.cs @@ -7,48 +7,48 @@ namespace Swarmops.Logic.Governance { public class MeetingElectionVote : BasicInternalPollVote { - private MeetingElectionVote(BasicInternalPollVote basic) : base(basic) + private MeetingElectionVote (BasicInternalPollVote basic) : base (basic) { // empty private ctor } public int[] SelectedCandidateIdsInOrder { - get { return SwarmDb.GetDatabaseForReading().GetInternalPollVoteDetails(Identity); } + get { return SwarmDb.GetDatabaseForReading().GetInternalPollVoteDetails (Identity); } } - public static MeetingElectionVote FromBasic(BasicInternalPollVote basic) + public static MeetingElectionVote FromBasic (BasicInternalPollVote basic) { - return new MeetingElectionVote(basic); + return new MeetingElectionVote (basic); } - public static MeetingElectionVote FromIdentity(int internalPollVoteId) + public static MeetingElectionVote FromIdentity (int internalPollVoteId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollVote(internalPollVoteId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetInternalPollVote (internalPollVoteId)); } - public static MeetingElectionVote FromVerificationCode(string verificationCode) + public static MeetingElectionVote FromVerificationCode (string verificationCode) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollVote(verificationCode)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetInternalPollVote (verificationCode)); } - public static MeetingElectionVote Create(MeetingElection poll, Geography voteGeography) + public static MeetingElectionVote Create (MeetingElection poll, Geography voteGeography) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateInternalPollVote(poll.Identity, voteGeography.Identity, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateInternalPollVote (poll.Identity, voteGeography.Identity, Authentication. - CreateRandomPassword(12))); + CreateRandomPassword (12))); } - public void AddDetail(int position, MeetingElectionCandidate candidate) + public void AddDetail (int position, MeetingElectionCandidate candidate) { - SwarmDb.GetDatabaseForWriting().CreateInternalPollVoteDetail(Identity, candidate.Identity, position); + SwarmDb.GetDatabaseForWriting().CreateInternalPollVoteDetail (Identity, candidate.Identity, position); } public void Clear() { - SwarmDb.GetDatabaseForWriting().ClearInternalPollVote(Identity); + SwarmDb.GetDatabaseForWriting().ClearInternalPollVote (Identity); } /* diff --git a/Logic/Governance/MeetingElectionVoter.cs b/Logic/Governance/MeetingElectionVoter.cs index b2a2b29c..ebf2004e 100644 --- a/Logic/Governance/MeetingElectionVoter.cs +++ b/Logic/Governance/MeetingElectionVoter.cs @@ -5,19 +5,19 @@ namespace Swarmops.Logic.Governance { public class MeetingElectionVoter : BasicInternalPollVoter { - private MeetingElectionVoter(BasicInternalPollVoter basic) : base(basic) + private MeetingElectionVoter (BasicInternalPollVoter basic) : base (basic) { // empty ctor } public Person Person { - get { return Person.FromIdentity(base.PersonId); } + get { return Person.FromIdentity (base.PersonId); } } public MeetingElection Poll { - get { return MeetingElection.FromIdentity(base.InternalPollId); } + get { return MeetingElection.FromIdentity (base.InternalPollId); } } public InternalPollVoterStatus VoterStatus @@ -25,9 +25,9 @@ namespace Swarmops.Logic.Governance get { return base.Open ? InternalPollVoterStatus.CanVote : InternalPollVoterStatus.HasAlreadyVoted; } } - public static MeetingElectionVoter FromBasic(BasicInternalPollVoter basic) + public static MeetingElectionVoter FromBasic (BasicInternalPollVoter basic) { - return new MeetingElectionVoter(basic); + return new MeetingElectionVoter (basic); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionVoters.cs b/Logic/Governance/MeetingElectionVoters.cs index 243995db..de841417 100644 --- a/Logic/Governance/MeetingElectionVoters.cs +++ b/Logic/Governance/MeetingElectionVoters.cs @@ -6,35 +6,35 @@ namespace Swarmops.Logic.Governance { public class MeetingElectionVoters : List { - public static MeetingElectionVoters FromArray(BasicInternalPollVoter[] basicArray) + public static MeetingElectionVoters FromArray (BasicInternalPollVoter[] basicArray) { MeetingElectionVoters result = new MeetingElectionVoters {Capacity = basicArray.Length*11/10}; foreach (BasicInternalPollVoter basic in basicArray) { - result.Add(MeetingElectionVoter.FromBasic(basic)); + result.Add (MeetingElectionVoter.FromBasic (basic)); } return result; } - public static MeetingElectionVoters ForPoll(MeetingElection poll, bool includeClosed) + public static MeetingElectionVoters ForPoll (MeetingElection poll, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPollVoters (poll)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll, DatabaseCondition.OpenTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPollVoters (poll, DatabaseCondition.OpenTrue)); } - public static MeetingElectionVoters ForPoll(MeetingElection poll) + public static MeetingElectionVoters ForPoll (MeetingElection poll) { - return ForPoll(poll, false); + return ForPoll (poll, false); } - public static MeetingElectionVoters ForPollClosed(MeetingElection poll) + public static MeetingElectionVoters ForPollClosed (MeetingElection poll) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll, DatabaseCondition.OpenFalse)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPollVoters (poll, DatabaseCondition.OpenFalse)); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionVotes.cs b/Logic/Governance/MeetingElectionVotes.cs index 12273113..5675bee5 100644 --- a/Logic/Governance/MeetingElectionVotes.cs +++ b/Logic/Governance/MeetingElectionVotes.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Governance { public class MeetingElectionVotes : PluralBase { - public static MeetingElectionVotes ForInternalPoll(MeetingElection poll) + public static MeetingElectionVotes ForInternalPoll (MeetingElection poll) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVotes(poll)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPollVotes (poll)); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElections.cs b/Logic/Governance/MeetingElections.cs index fb5915c6..bbbf4709 100644 --- a/Logic/Governance/MeetingElections.cs +++ b/Logic/Governance/MeetingElections.cs @@ -7,19 +7,19 @@ namespace Swarmops.Logic.Governance { public class MeetingElections : PluralBase { - public static MeetingElections ForOrganization(Organization organization) + public static MeetingElections ForOrganization (Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPolls(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPolls (organization)); } - public static MeetingElections ForOrganizations(Organizations organizations) + public static MeetingElections ForOrganizations (Organizations organizations) { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPolls(organizations)); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPolls (organizations)); } public static MeetingElections GetAll() { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPolls()); + return FromArray (SwarmDb.GetDatabaseForReading().GetInternalPolls()); } } } \ No newline at end of file diff --git a/Logic/Governance/Motion.cs b/Logic/Governance/Motion.cs index 2d3179c8..c06449d8 100644 --- a/Logic/Governance/Motion.cs +++ b/Logic/Governance/Motion.cs @@ -6,49 +6,49 @@ namespace Swarmops.Logic.Governance { public class Motion : BasicMotion { - private Motion(BasicMotion basic) : base(basic) + private Motion (BasicMotion basic) : base (basic) { // empty ctor } public MotionAmendments Amendments { - get { return MotionAmendments.ForMotion(this); } + get { return MotionAmendments.ForMotion (this); } } public Meeting Meeting { - get { return Meeting.FromIdentity(MeetingId); } + get { return Meeting.FromIdentity (MeetingId); } } public Person Submitter { - get { return Person.FromIdentity(SubmittedByPersonId); } + get { return Person.FromIdentity (SubmittedByPersonId); } } - public static Motion FromBasic(BasicMotion basic) + public static Motion FromBasic (BasicMotion basic) { - return new Motion(basic); + return new Motion (basic); } - public static Motion FromIdentity(int motionId) + public static Motion FromIdentity (int motionId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMotion(motionId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetMotion (motionId)); } - public static Motion Create(Meeting meeting, Person submittingPerson, Person creatingPerson, string title, + public static Motion Create (Meeting meeting, Person submittingPerson, Person creatingPerson, string title, string text, string decisionPoints) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateMotion(meeting.Identity, submittingPerson.Identity, creatingPerson.Identity, title, text, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateMotion (meeting.Identity, submittingPerson.Identity, creatingPerson.Identity, title, text, decisionPoints)); } - public MotionAmendment AddAmendment(string title, string text, string decisionPoint, Person submittingPerson, + public MotionAmendment AddAmendment (string title, string text, string decisionPoint, Person submittingPerson, Person createdByPerson) { - return MotionAmendment.Create(this, title, text, decisionPoint, submittingPerson, createdByPerson); + return MotionAmendment.Create (this, title, text, decisionPoint, submittingPerson, createdByPerson); } } } \ No newline at end of file diff --git a/Logic/Governance/MotionAmendment.cs b/Logic/Governance/MotionAmendment.cs index 41d21ba3..1b2c4235 100644 --- a/Logic/Governance/MotionAmendment.cs +++ b/Logic/Governance/MotionAmendment.cs @@ -6,15 +6,15 @@ namespace Swarmops.Logic.Governance { public class MotionAmendment : BasicMotionAmendment { - private MotionAmendment(BasicMotionAmendment basic) : - base(basic) + private MotionAmendment (BasicMotionAmendment basic) : + base (basic) { // empty ctor } public Motion Motion { - get { return Motion.FromIdentity(MotionId); } + get { return Motion.FromIdentity (MotionId); } } public string Designation @@ -25,25 +25,25 @@ namespace Swarmops.Logic.Governance public Person Submitter { - get { return Person.FromIdentity(SubmittedByPersonId); } + get { return Person.FromIdentity (SubmittedByPersonId); } } - public static MotionAmendment FromBasic(BasicMotionAmendment basic) + public static MotionAmendment FromBasic (BasicMotionAmendment basic) { - return new MotionAmendment(basic); + return new MotionAmendment (basic); } - public static MotionAmendment FromIdentity(int motionAmendmentId) + public static MotionAmendment FromIdentity (int motionAmendmentId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMotionAmendment(motionAmendmentId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetMotionAmendment (motionAmendmentId)); } - public static MotionAmendment Create(Motion motion, string title, string text, string decisionPoint, + public static MotionAmendment Create (Motion motion, string title, string text, string decisionPoint, Person submittingPerson, Person creatingPerson) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateMotionAmendment(motion.Identity, submittingPerson.Identity, creatingPerson.Identity, title, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateMotionAmendment (motion.Identity, submittingPerson.Identity, creatingPerson.Identity, title, text, decisionPoint)); } } diff --git a/Logic/Governance/MotionAmendments.cs b/Logic/Governance/MotionAmendments.cs index 737c72d0..dd07a5b0 100644 --- a/Logic/Governance/MotionAmendments.cs +++ b/Logic/Governance/MotionAmendments.cs @@ -6,14 +6,14 @@ namespace Swarmops.Logic.Governance { public class MotionAmendments : PluralBase { - public static MotionAmendments ForMotion(Motion motion) + public static MotionAmendments ForMotion (Motion motion) { - return FromArray(SwarmDb.GetDatabaseForReading().GetMotionAmendments(motion)); + return FromArray (SwarmDb.GetDatabaseForReading().GetMotionAmendments (motion)); } - public static MotionAmendments ForMeeting(Meeting meeting) + public static MotionAmendments ForMeeting (Meeting meeting) { - return FromArray(SwarmDb.GetDatabaseForReading().GetMotionAmendmentsForMeeting(meeting.Identity)); + return FromArray (SwarmDb.GetDatabaseForReading().GetMotionAmendmentsForMeeting (meeting.Identity)); } } } \ No newline at end of file diff --git a/Logic/Governance/Motions.cs b/Logic/Governance/Motions.cs index f328656b..f5bbe9a7 100644 --- a/Logic/Governance/Motions.cs +++ b/Logic/Governance/Motions.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Governance { public class Motions : PluralBase { - public static Motions ForMeeting(Meeting meeting) + public static Motions ForMeeting (Meeting meeting) { - return FromArray(SwarmDb.GetDatabaseForReading().GetMotions(meeting)); + return FromArray (SwarmDb.GetDatabaseForReading().GetMotions (meeting)); } } } \ No newline at end of file diff --git a/Logic/Media/MediaCategories.cs b/Logic/Media/MediaCategories.cs index fa13d501..8e17a5d9 100644 --- a/Logic/Media/MediaCategories.cs +++ b/Logic/Media/MediaCategories.cs @@ -9,30 +9,30 @@ namespace Swarmops.Logic.Media { public int[] Identities { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + get { return LogicServices.ObjectsToIdentifiers (ToArray()); } } - public static MediaCategories FromArray(BasicMediaCategory[] basicArray) + public static MediaCategories FromArray (BasicMediaCategory[] basicArray) { MediaCategories result = new MediaCategories(); result.Capacity = basicArray.Length*11/10; foreach (BasicMediaCategory basic in basicArray) { - result.Add(MediaCategory.FromBasic(basic)); + result.Add (MediaCategory.FromBasic (basic)); } return result; } - public static MediaCategories FromIdentities(int[] identities) + public static MediaCategories FromIdentities (int[] identities) { - return FromArray(SwarmDb.GetDatabaseForReading().GetMediaCategories(identities)); + return FromArray (SwarmDb.GetDatabaseForReading().GetMediaCategories (identities)); } public static MediaCategories GetAll() { - return FromArray(SwarmDb.GetDatabaseForReading().GetMediaCategories()); + return FromArray (SwarmDb.GetDatabaseForReading().GetMediaCategories()); } } } \ No newline at end of file diff --git a/Logic/Media/MediaCategory.cs b/Logic/Media/MediaCategory.cs index 98cbe31b..c6971017 100644 --- a/Logic/Media/MediaCategory.cs +++ b/Logic/Media/MediaCategory.cs @@ -5,18 +5,18 @@ namespace Swarmops.Logic.Media { public class MediaCategory : BasicMediaCategory { - private MediaCategory(BasicMediaCategory original) : base(original) + private MediaCategory (BasicMediaCategory original) : base (original) { } - public static MediaCategory FromName(string name) + public static MediaCategory FromName (string name) { - return new MediaCategory(SwarmDb.GetDatabaseForReading().GetMediaCategoryByName(name)); + return new MediaCategory (SwarmDb.GetDatabaseForReading().GetMediaCategoryByName (name)); } - public static MediaCategory FromBasic(BasicMediaCategory basic) + public static MediaCategory FromBasic (BasicMediaCategory basic) { - return new MediaCategory(basic); + return new MediaCategory (basic); } } } \ No newline at end of file diff --git a/Logic/Media/MediaEntries.cs b/Logic/Media/MediaEntries.cs index 8ab6e4e9..a18af285 100644 --- a/Logic/Media/MediaEntries.cs +++ b/Logic/Media/MediaEntries.cs @@ -7,24 +7,24 @@ namespace Swarmops.Logic.Media { public class MediaEntries : List { - public static MediaEntries FromArray(BasicMediaEntry[] basicArray) + public static MediaEntries FromArray (BasicMediaEntry[] basicArray) { MediaEntries result = new MediaEntries(); result.Capacity = basicArray.Length*11/10; foreach (BasicMediaEntry basic in basicArray) { - result.Add(MediaEntry.FromBasic(basic)); + result.Add (MediaEntry.FromBasic (basic)); } return result; } - public void Add(MediaEntries moreMediaEntries) + public void Add (MediaEntries moreMediaEntries) { foreach (MediaEntry entry in moreMediaEntries) { - Add(entry); + Add (entry); } } @@ -38,14 +38,14 @@ namespace Swarmops.Logic.Media return SwarmDb.GetDatabaseForReading().GetOldMediaKeywords(); } - public static MediaEntries FromBlogKeyword(string keyword, DateTime minimumAge) + public static MediaEntries FromBlogKeyword (string keyword, DateTime minimumAge) { - return FromArray(SwarmDb.GetDatabaseForReading().GetBlogEntriesForKeyword(keyword, minimumAge)); + return FromArray (SwarmDb.GetDatabaseForReading().GetBlogEntriesForKeyword (keyword, minimumAge)); } - public static MediaEntries FromOldMediaKeyword(string keyword, DateTime minimumAge) + public static MediaEntries FromOldMediaKeyword (string keyword, DateTime minimumAge) { - return FromArray(SwarmDb.GetDatabaseForReading().GetOldMediaEntriesForKeyword(keyword, minimumAge)); + return FromArray (SwarmDb.GetDatabaseForReading().GetOldMediaEntriesForKeyword (keyword, minimumAge)); } public static Dictionary GetMediaTypeTable() @@ -58,22 +58,22 @@ namespace Swarmops.Logic.Media return SwarmDb.GetDatabaseForReading().GetMediaKeywordTable(); } - public static MediaEntries FromKeywordsSimplified(string[] keywords) + public static MediaEntries FromKeywordsSimplified (string[] keywords) { List keywordIds = new List(); foreach (string keyword in keywords) { - keywordIds.Add(SwarmDb.GetDatabaseForReading().GetMediaKeywordId(keyword)); + keywordIds.Add (SwarmDb.GetDatabaseForReading().GetMediaKeywordId (keyword)); } return - FromArray(SwarmDb.GetDatabaseForReading().GetMediaEntriesForKeywordIdsSimplified(keywordIds.ToArray())); + FromArray (SwarmDb.GetDatabaseForReading().GetMediaEntriesForKeywordIdsSimplified (keywordIds.ToArray())); } - public static int GetKeywordId(string keyword) + public static int GetKeywordId (string keyword) { - return SwarmDb.GetDatabaseForReading().GetMediaKeywordId(keyword); + return SwarmDb.GetDatabaseForReading().GetMediaKeywordId (keyword); } } } \ No newline at end of file diff --git a/Logic/Media/MediaEntry.cs b/Logic/Media/MediaEntry.cs index 894c299e..2552377e 100644 --- a/Logic/Media/MediaEntry.cs +++ b/Logic/Media/MediaEntry.cs @@ -6,21 +6,22 @@ namespace Swarmops.Logic.Media { public class MediaEntry : BasicMediaEntry { - private MediaEntry(BasicMediaEntry basic) : - base(basic) + private MediaEntry (BasicMediaEntry basic) : + base (basic) { } - public static MediaEntry FromBasic(BasicMediaEntry basic) + public static MediaEntry FromBasic (BasicMediaEntry basic) { - return new MediaEntry(basic); + return new MediaEntry (basic); } - public static bool CreateFromKeyword(string keyword, string mediaName, bool isBlog, string url, string title, + public static bool CreateFromKeyword (string keyword, string mediaName, bool isBlog, string url, string title, DateTime dateTime) { - int id = SwarmDb.GetDatabaseForWriting().CreateMediaEntryFromKeyword(keyword, mediaName, isBlog, url, title, - dateTime); + int id = SwarmDb.GetDatabaseForWriting() + .CreateMediaEntryFromKeyword (keyword, mediaName, isBlog, url, title, + dateTime); if (id != 0) { diff --git a/Logic/Media/Reporter.cs b/Logic/Media/Reporter.cs index 2c6a2a2d..b67735d4 100644 --- a/Logic/Media/Reporter.cs +++ b/Logic/Media/Reporter.cs @@ -8,7 +8,7 @@ namespace Swarmops.Logic.Media { private MediaCategories mediaCategories; - private Reporter(BasicReporter original) : base(original) + private Reporter (BasicReporter original) : base (original) { } @@ -18,14 +18,14 @@ namespace Swarmops.Logic.Media { if (MediaCategoryIds == null) { - MediaCategoryIds = SwarmDb.GetDatabaseForReading().GetReporterMediaCategories(Identity); + MediaCategoryIds = SwarmDb.GetDatabaseForReading().GetReporterMediaCategories (Identity); } if (this.mediaCategories == null) { if (MediaCategoryIds.Length > 0) { - this.mediaCategories = MediaCategories.FromIdentities(MediaCategoryIds); + this.mediaCategories = MediaCategories.FromIdentities (MediaCategoryIds); } else { @@ -37,13 +37,13 @@ namespace Swarmops.Logic.Media } } - public static Reporter Create(string name, string email, string[] categories) + public static Reporter Create (string name, string email, string[] categories) { - Reporter reporter = FromIdentity(SwarmDb.GetDatabaseForWriting().CreateReporter(name, email)); + Reporter reporter = FromIdentity (SwarmDb.GetDatabaseForWriting().CreateReporter (name, email)); foreach (string category in categories) { - SwarmDb.GetDatabaseForWriting().CreateReporterMediaCategory(reporter.Identity, category); + SwarmDb.GetDatabaseForWriting().CreateReporterMediaCategory (reporter.Identity, category); } return reporter; @@ -52,29 +52,29 @@ namespace Swarmops.Logic.Media public void Delete() { - SwarmDb.GetDatabaseForWriting().DeleteReporter(Identity); + SwarmDb.GetDatabaseForWriting().DeleteReporter (Identity); // After this operation, the object is no longer valid. } - public static Reporter FromBasic(BasicReporter basic) + public static Reporter FromBasic (BasicReporter basic) { - return new Reporter(basic); + return new Reporter (basic); } - public static Reporter FromIdentity(int identity) + public static Reporter FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetReporter(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetReporter (identity)); } #region IComparable Members - public int CompareTo(object obj) + public int CompareTo (object obj) { Reporter otherReporter = (Reporter) obj; - return Name.CompareTo(otherReporter.Name); + return Name.CompareTo (otherReporter.Name); } #endregion diff --git a/Logic/Media/Reporters.cs b/Logic/Media/Reporters.cs index d7df2b72..7fed9b0e 100644 --- a/Logic/Media/Reporters.cs +++ b/Logic/Media/Reporters.cs @@ -6,14 +6,14 @@ namespace Swarmops.Logic.Media { public class Reporters : List { - public static Reporters FromArray(BasicReporter[] basicArray) + public static Reporters FromArray (BasicReporter[] basicArray) { Reporters result = new Reporters(); result.Capacity = basicArray.Length*11/10; foreach (BasicReporter basic in basicArray) { - result.Add(Reporter.FromBasic(basic)); + result.Add (Reporter.FromBasic (basic)); } return result; @@ -22,14 +22,14 @@ namespace Swarmops.Logic.Media public static Reporters GetAll() { BasicReporter[] basicReporters = SwarmDb.GetDatabaseForReading().GetReporters(); - return FromArray(basicReporters); + return FromArray (basicReporters); } - public static Reporters FromMediaCategories(MediaCategories categories) + public static Reporters FromMediaCategories (MediaCategories categories) { BasicReporter[] basicReporters = - SwarmDb.GetDatabaseForReading().GetReportersFromMediaCategories(categories.Identities); - return FromArray(basicReporters); + SwarmDb.GetDatabaseForReading().GetReportersFromMediaCategories (categories.Identities); + return FromArray (basicReporters); } } } \ No newline at end of file diff --git a/Logic/Security/Accesses.cs b/Logic/Security/Accesses.cs index be02e310..a341ca0d 100644 --- a/Logic/Security/Accesses.cs +++ b/Logic/Security/Accesses.cs @@ -9,20 +9,20 @@ namespace Swarmops.Logic.Security public readonly Organization Organization; public readonly AccessType Type; - public Access(AccessAspect aspect, AccessType type) + public Access (AccessAspect aspect, AccessType type) { this.Aspect = aspect; this.Type = type; } - public Access(Organization organization, AccessAspect aspect, AccessType type) + public Access (Organization organization, AccessAspect aspect, AccessType type) { this.Organization = organization; this.Aspect = aspect; this.Type = type; } - public Access(Organization organization, Geography geography, AccessAspect aspect, AccessType type) + public Access (Organization organization, Geography geography, AccessAspect aspect, AccessType type) { this.Organization = organization; this.Geography = geography; diff --git a/Logic/Security/Authentication.cs b/Logic/Security/Authentication.cs index 8eea9767..a36316f0 100644 --- a/Logic/Security/Authentication.cs +++ b/Logic/Security/Authentication.cs @@ -22,11 +22,11 @@ namespace Swarmops.Logic.Security /// This function will throw an UnauthorizedAccessException if the user /// cannot be authenticated using the supplied credentials. /// - public static Person Authenticate(string loginToken, string password) + public static Person Authenticate (string loginToken, string password) { // Get the list of people that match the login token. - People candidatePeople = GetPeopleByLoginToken(loginToken); + People candidatePeople = GetPeopleByLoginToken (loginToken); Person authenticatedUser = null; // For every person in the list, test the supplied password against the current and legacy hash schemes. @@ -59,15 +59,15 @@ namespace Swarmops.Logic.Security bool goodCredentials = false; - if (CheckPassword(candidate, password)) + if (CheckPassword (candidate, password)) { goodCredentials = true; } - else if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) + else if (PilotInstallationIds.IsPilot (PilotInstallationIds.PiratePartySE)) { // If the most recent password hash mechanism fails, try legacy hashes IF on pilot installation - string[] legacyHashes = GenerateLegacyPasswordHashes(candidate, password); + string[] legacyHashes = GenerateLegacyPasswordHashes (candidate, password); foreach (string legacyHash in legacyHashes) { @@ -91,7 +91,7 @@ namespace Swarmops.Logic.Security // We have a double credentials hit. This becomes a serious security concern. // TODO: Alert operator about this, it's a serious condition. - throw new UnauthorizedAccessException("Double credentials hit"); + throw new UnauthorizedAccessException ("Double credentials hit"); } // The current candidate has good credentials: @@ -111,7 +111,7 @@ namespace Swarmops.Logic.Security } - public static string CreateRandomPassword(int length) + public static string CreateRandomPassword (int length) { string allowedChars = "ABCDEFHJKMNPQRTUVWXYZ23456789"; char[] chars = new char[length]; @@ -119,10 +119,10 @@ namespace Swarmops.Logic.Security for (int index = 0; index < length; index++) { - chars[index] = allowedChars[randomizer.Next(0, allowedChars.Length)]; + chars[index] = allowedChars[randomizer.Next (0, allowedChars.Length)]; } - return new string(chars); + return new string (chars); } /// @@ -131,39 +131,39 @@ namespace Swarmops.Logic.Security /// The person to generate the hash for. /// The password to hash. /// A hash on the format "C8 5B A2 19 B5..." (29 characters). - internal static string GenerateNewPasswordHash(Person person, string password) + internal static string GenerateNewPasswordHash (Person person, string password) { if (person == null) { - throw new ArgumentNullException("person"); + throw new ArgumentNullException ("person"); } if (person.PersonId == 0) { - throw new ArgumentOutOfRangeException("PersonId on the supplied person cannot be 0"); + throw new ArgumentOutOfRangeException ("PersonId on the supplied person cannot be 0"); } - return GenerateNewPasswordHash(person.PersonId, password); + return GenerateNewPasswordHash (person.PersonId, password); } - internal static string GenerateNewPasswordHash(int personId, string password) + internal static string GenerateNewPasswordHash (int personId, string password) { - string salt = BCrypt.GenerateSalt(12); - // Longer than standard (10) on purpose. Should be good through 2020 or so. - string passwordHash = BCrypt.HashPassword(personId.ToString(CultureInfo.InvariantCulture) + password, salt); + string salt = BCrypt.GenerateSalt (12); + // Longer than standard (10) on purpose. Should be good through 2020 or so. + string passwordHash = BCrypt.HashPassword (personId.ToString (CultureInfo.InvariantCulture) + password, salt); return passwordHash; } - internal static bool CheckPassword(Person person, string password) + internal static bool CheckPassword (Person person, string password) { - if (!person.PasswordHash.StartsWith("$2a$12$")) + if (!person.PasswordHash.StartsWith ("$2a$12$")) { return false; // not a BCrypt hash with work factor 12; fall back to legacy or fail. Caller's problem } - return BCrypt.CheckPassword(person.Identity.ToString(CultureInfo.InvariantCulture) + password, + return BCrypt.CheckPassword (person.Identity.ToString (CultureInfo.InvariantCulture) + password, person.PasswordHash); } @@ -173,7 +173,7 @@ namespace Swarmops.Logic.Security /// The person to generate a hash for. /// The password to hash. /// A list of previously valid password hashes. - private static string[] GenerateLegacyPasswordHashes(Person person, string password) + private static string[] GenerateLegacyPasswordHashes (Person person, string password) { // Calling Obsolete Property is valid here since we are generationg legacy hashes. #pragma warning disable 618 @@ -181,13 +181,13 @@ namespace Swarmops.Logic.Security { return new[] { - SHA1.Hash(password + person.Identity + "Pirate"), - MD5.Hash(password + person.PersonalNumber + "Pirate") + SHA1.Hash (password + person.Identity + "Pirate"), + MD5.Hash (password + person.PersonalNumber + "Pirate") }; } return new[] { - SHA1.Hash(password + person.Identity + "Pirate") + SHA1.Hash (password + person.Identity + "Pirate") }; #pragma warning restore 618 } @@ -198,7 +198,7 @@ namespace Swarmops.Logic.Security /// /// The login token to look for. /// An array of person IDs. - private static People GetPeopleByLoginToken(string loginToken) + private static People GetPeopleByLoginToken (string loginToken) { People result = new People(); @@ -206,16 +206,16 @@ namespace Swarmops.Logic.Security // First, is the login token numeric? If so, add it as is and is a valid person. - if (LogicServices.IsNumber(loginToken)) + if (LogicServices.IsNumber (loginToken)) { try { - int personId = Int32.Parse(loginToken); - Person person = Person.FromIdentity(personId); + int personId = Int32.Parse (loginToken); + Person person = Person.FromIdentity (personId); // If we get here without exception, the login token is a valid person Id - result.Add(person); + result.Add (person); } catch (Exception) { @@ -226,46 +226,46 @@ namespace Swarmops.Logic.Security // Second, is the login token ten digits? If so, look for the person with this personal number. // This is specific to the Swedish PP. - string cleanedNumber = LogicServices.CleanNumber(loginToken); + string cleanedNumber = LogicServices.CleanNumber (loginToken); if (cleanedNumber.Length == 10) { - int[] personIds = database.GetObjectsByOptionalData(ObjectType.Person, + int[] personIds = database.GetObjectsByOptionalData (ObjectType.Person, ObjectOptionalDataType.PersonalNumber, cleanedNumber); foreach (int personId in personIds) { - result.Add(Person.FromIdentity(personId)); + result.Add (Person.FromIdentity (personId)); } } // Third, look for a matching name. Expand the login token so that "R Falkv" will match "Rickard Falkvinge". // Only do this if the login token, excessive whitespace removed, is five characters or more. - result = People.LogicalOr(result, People.FromNamePattern(loginToken)); + result = People.LogicalOr (result, People.FromNamePattern (loginToken)); // Fourth, look for a matching email. Only do an exact match here. - if (loginToken.Contains("@")) + if (loginToken.Contains ("@")) { - result = People.LogicalOr(result, People.FromEmailPattern(loginToken)); + result = People.LogicalOr (result, People.FromEmailPattern (loginToken)); } return result; } - public static Person RequestNewPasswordProcess(string eMail, string URL) + public static Person RequestNewPasswordProcess (string eMail, string URL) { int personID = 0; - int.TryParse(eMail, out personID); + int.TryParse (eMail, out personID); Person authenticatedUser = null; People candidatePeople = null; if (personID == 0) { BasicPerson[] people = - SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern(eMail.ToLower().Replace("%", "").Trim()); - candidatePeople = People.FromArray(people); + SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern (eMail.ToLower().Replace ("%", "").Trim()); + candidatePeople = People.FromArray (people); // if multiple people share same e-mail, suppose the last one registered is the one to change. foreach (Person p in candidatePeople) @@ -278,7 +278,7 @@ namespace Swarmops.Logic.Security } else { - candidatePeople = People.FromIdentities(new[] {personID}); + candidatePeople = People.FromIdentities (new[] {personID}); if (candidatePeople.Count > 0) { authenticatedUser = candidatePeople[0]; @@ -290,12 +290,12 @@ namespace Swarmops.Logic.Security return null; } - string passwordTicket = CreateRandomPassword(EmailVerificationTicketLength); + string passwordTicket = CreateRandomPassword (EmailVerificationTicketLength); foreach (Person p in candidatePeople) { - string encodedPasswordTicket = GenerateNewPasswordHash(p, passwordTicket); - p.ResetPasswordTicket = encodedPasswordTicket + ";" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + string encodedPasswordTicket = GenerateNewPasswordHash (p, passwordTicket); + p.ResetPasswordTicket = encodedPasswordTicket + ";" + DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss"); } //TODO: Localize @@ -305,11 +305,11 @@ namespace Swarmops.Logic.Security if (candidatePeople.Count == 1) { App_LocalResources.Authentication.Culture = - CultureInfo.GetCultureInfo(authenticatedUser.PreferredCulture); + CultureInfo.GetCultureInfo (authenticatedUser.PreferredCulture); mailbody = App_LocalResources.Authentication.RequestNewPassword_Mail_Preamble; mailbody += App_LocalResources.Authentication.RequestNewPassword_Mail_ClickOneLink; - mailbody += "\r\n" + String.Format(URL, authenticatedUser.PersonId, passwordTicket); + mailbody += "\r\n" + String.Format (URL, authenticatedUser.PersonId, passwordTicket); } else { @@ -320,7 +320,7 @@ namespace Swarmops.Logic.Security int membershipCount = 0; if (App_LocalResources.Authentication.Culture == CultureInfo.InvariantCulture) { - App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo(p.PreferredCulture); + App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo (p.PreferredCulture); } links += "\r\n\r\n"; @@ -330,10 +330,10 @@ namespace Swarmops.Logic.Security foreach (Membership ms in msList) { ++membershipCount; - links += " (" + ms.Organization.Name + "," + ms.MemberSince.ToString("yyyy-MM-dd") + ")"; + links += " (" + ms.Organization.Name + "," + ms.MemberSince.ToString ("yyyy-MM-dd") + ")"; } links += "] "; - links += "\r\n" + String.Format(URL, p.PersonId, passwordTicket); + links += "\r\n" + String.Format (URL, p.PersonId, passwordTicket); if (membershipCount > 0) { linksTot += links; @@ -347,80 +347,80 @@ namespace Swarmops.Logic.Security mailbody += App_LocalResources.Authentication.RequestNewPassword_Mail_Ending; - authenticatedUser.SendNotice(App_LocalResources.Authentication.RequestNewPassword_Mail_Subject, mailbody, 1); + authenticatedUser.SendNotice (App_LocalResources.Authentication.RequestNewPassword_Mail_Subject, mailbody, 1); return authenticatedUser; } - public static void RequestMembershipConfirmation(Person p, string URL) + public static void RequestMembershipConfirmation (Person p, string URL) { - string passwordTicket = CreateRandomPassword(EmailVerificationTicketLength); + string passwordTicket = CreateRandomPassword (EmailVerificationTicketLength); - string encodedPasswordTicket = SHA1.Hash(passwordTicket); - p.ResetPasswordTicket = encodedPasswordTicket + ";" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + string encodedPasswordTicket = SHA1.Hash (passwordTicket); + p.ResetPasswordTicket = encodedPasswordTicket + ";" + DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss"); string mailbody = ""; App_LocalResources.Authentication.Culture = - CultureInfo.GetCultureInfo(p.PreferredCulture); + CultureInfo.GetCultureInfo (p.PreferredCulture); mailbody = App_LocalResources.Authentication.MembershipConf_Mail_Preamble; - mailbody += "\r\n" + String.Format(URL, p.PersonId, passwordTicket); + mailbody += "\r\n" + String.Format (URL, p.PersonId, passwordTicket); mailbody += App_LocalResources.Authentication.MembershipConf_Mail_Ending; - p.SendNotice(App_LocalResources.Authentication.MembershipConf_Mail_Subject, mailbody, 1); + p.SendNotice (App_LocalResources.Authentication.MembershipConf_Mail_Subject, mailbody, 1); } - public static void ValidateEmailVerificationTicket(Person pers, string token) + public static void ValidateEmailVerificationTicket (Person pers, string token) { if (token.Length != EmailVerificationTicketLength) { - throw new VerificationTicketLengthException("Wrong length of code, should be " + - EmailVerificationTicketLength + " characters."); + throw new VerificationTicketLengthException ("Wrong length of code, should be " + + EmailVerificationTicketLength + " characters."); } string storedTicket = pers.ResetPasswordTicket; - string[] storedParts = storedTicket.Split(new[] {';'}); + string[] storedParts = storedTicket.Split (new[] {';'}); if (storedParts.Length < 2) { - throw new VerificationTicketWrongException("No such code exists."); + throw new VerificationTicketWrongException ("No such code exists."); } DateTime createdTime = DateTime.MinValue; - DateTime.TryParseExact(storedParts[1].Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, + DateTime.TryParseExact (storedParts[1].Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdTime); - if (DateTime.Now.Subtract(createdTime).TotalHours > 10) + if (DateTime.Now.Subtract (createdTime).TotalHours > 10) { - throw new VerificationTicketTooOldException( + throw new VerificationTicketTooOldException ( "Verification code too old, it must be used within 10 hours."); } - if (SHA1.Hash(token) == storedParts[0]) + if (SHA1.Hash (token) == storedParts[0]) { // Yes, proceed to next step } else { - throw new VerificationTicketWrongException("Wrong verification code."); + throw new VerificationTicketWrongException ("Wrong verification code."); } } - public static void SetPasswordByEmailVerificationTicket(Person pers, string token, string newPassword) + public static void SetPasswordByEmailVerificationTicket (Person pers, string token, string newPassword) { - ValidateEmailVerificationTicket(pers, token); + ValidateEmailVerificationTicket (pers, token); - pers.SetPassword(newPassword); + pers.SetPassword (newPassword); pers.ResetPasswordTicket = ""; } - internal static bool ValidatePassword(Person person, string oldpassword) + internal static bool ValidatePassword (Person person, string oldpassword) { - if (CheckPassword(person, oldpassword)) + if (CheckPassword (person, oldpassword)) { return true; } // If the most recent password hash mechanism fails, try legacy hashes - string[] legacyHashes = GenerateLegacyPasswordHashes(person, oldpassword); + string[] legacyHashes = GenerateLegacyPasswordHashes (person, oldpassword); foreach (string legacyHash in legacyHashes) { @@ -432,18 +432,18 @@ namespace Swarmops.Logic.Security return false; } - public static Person RequestActivistSignoffProcess(string eMail, string URL) + public static Person RequestActivistSignoffProcess (string eMail, string URL) { int personID = 0; - int.TryParse(eMail, out personID); + int.TryParse (eMail, out personID); Person authenticatedUser = null; People candidatePeople = null; bool personIsActivist = false; if (personID == 0) { BasicPerson[] people = - SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern(eMail.ToLower().Replace("%", "").Trim()); - candidatePeople = People.FromArray(people); + SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern (eMail.ToLower().Replace ("%", "").Trim()); + candidatePeople = People.FromArray (people); // if multiple people share same e-mail, suppose the last one registered is the one to change. foreach (Person p in candidatePeople) @@ -456,7 +456,7 @@ namespace Swarmops.Logic.Security } else { - candidatePeople = People.FromIdentities(new[] {personID}); + candidatePeople = People.FromIdentities (new[] {personID}); if (candidatePeople.Count > 0) { authenticatedUser = candidatePeople[0]; @@ -480,19 +480,19 @@ namespace Swarmops.Logic.Security Person p = candidatePeople[0]; if (App_LocalResources.Authentication.Culture == CultureInfo.InvariantCulture) { - App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo(p.PreferredCulture); + App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo (p.PreferredCulture); } string encodedPasswordTicket = - SHA1.Hash(p.Identity.ToString(CultureInfo.InvariantCulture)).Replace(" ", "").Substring(0, 4) + + SHA1.Hash (p.Identity.ToString (CultureInfo.InvariantCulture)).Replace (" ", "").Substring (0, 4) + p.Identity; mailbody = App_LocalResources.Authentication.RequestActivistSignoff_Mail_Preamble; mailbody += App_LocalResources.Authentication.RequestActivistSignoff_Mail_ClickOneLink; - mailbody += "\r\n" + String.Format(URL, encodedPasswordTicket); + mailbody += "\r\n" + String.Format (URL, encodedPasswordTicket); } else { @@ -505,17 +505,17 @@ namespace Swarmops.Logic.Security personIsActivist = true; if (App_LocalResources.Authentication.Culture == CultureInfo.InvariantCulture) { - App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo(p.PreferredCulture); + App_LocalResources.Authentication.Culture = CultureInfo.GetCultureInfo (p.PreferredCulture); } string encodedPasswordTicket = - GenerateNewPasswordHash(p, p.Identity.ToString()).Replace(" ", "").Substring(0, 4) + + GenerateNewPasswordHash (p, p.Identity.ToString()).Replace (" ", "").Substring (0, 4) + p.Identity; links += "\r\n\r\n"; links += "#" + p.PersonId; - links += "\r\n" + String.Format(URL, encodedPasswordTicket); + links += "\r\n" + String.Format (URL, encodedPasswordTicket); } } @@ -528,41 +528,41 @@ namespace Swarmops.Logic.Security if (personIsActivist) { - authenticatedUser.SendNotice(App_LocalResources.Authentication.RequestActivistSignoff_Mail_Subject, + authenticatedUser.SendNotice (App_LocalResources.Authentication.RequestActivistSignoff_Mail_Subject, mailbody, 1); } return authenticatedUser; } - public static void ValidateRequestActivistSignoffProcess(Person p, string code) + public static void ValidateRequestActivistSignoffProcess (Person p, string code) { string encodedPasswordTicket = - SHA1.Hash(p.Identity.ToString(CultureInfo.InvariantCulture)).Replace(" ", "").Substring(0, 4) + + SHA1.Hash (p.Identity.ToString (CultureInfo.InvariantCulture)).Replace (" ", "").Substring (0, 4) + p.Identity; if (code != encodedPasswordTicket) { - throw new VerificationTicketWrongException("No such code exists."); + throw new VerificationTicketWrongException ("No such code exists."); } } public class VerificationTicketLengthException : Exception { - internal VerificationTicketLengthException(string msg) : base(msg) + internal VerificationTicketLengthException (string msg) : base (msg) { } } public class VerificationTicketTooOldException : Exception { - internal VerificationTicketTooOldException(string msg) : base(msg) + internal VerificationTicketTooOldException (string msg) : base (msg) { } } public class VerificationTicketWrongException : Exception { - internal VerificationTicketWrongException(string msg) : base(msg) + internal VerificationTicketWrongException (string msg) : base (msg) { } } diff --git a/Logic/Security/Authority.cs b/Logic/Security/Authority.cs index 9ca01f49..b06e5bcc 100644 --- a/Logic/Security/Authority.cs +++ b/Logic/Security/Authority.cs @@ -13,26 +13,26 @@ namespace Swarmops.Logic.Security #region Construction and Creation private Authority() - : base(0, null, null, null) + : base (0, null, null, null) { } - private Authority(BasicAuthority basic) - : base(basic.PersonId, basic.SystemPersonRoles, basic.OrganizationPersonRoles, basic.LocalPersonRoles) + private Authority (BasicAuthority basic) + : base (basic.PersonId, basic.SystemPersonRoles, basic.OrganizationPersonRoles, basic.LocalPersonRoles) { } - public static Authority FromBasic(BasicAuthority basic) + public static Authority FromBasic (BasicAuthority basic) { - return new Authority(basic); + return new Authority (basic); } #endregion - public Organizations GetOrganizations(RoleType[] forRoles) + public Organizations GetOrganizations (RoleType[] forRoles) { - if (HasRoleType(RoleType.SystemAdmin)) + if (HasRoleType (RoleType.SystemAdmin)) { return Organizations.GetAll(); } @@ -41,25 +41,25 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in OrganizationPersonRoles) { - if (Array.IndexOf(forRoles, role.Type) >= 0) - orgIdentities.Add(role.OrganizationId); + if (Array.IndexOf (forRoles, role.Type) >= 0) + orgIdentities.Add (role.OrganizationId); } foreach (BasicPersonRole role in LocalPersonRoles) { - if (Array.IndexOf(forRoles, role.Type) >= 0) - orgIdentities.Add(role.OrganizationId); + if (Array.IndexOf (forRoles, role.Type) >= 0) + orgIdentities.Add (role.OrganizationId); } - return Organizations.FromIdentities(orgIdentities.ToArray()); + return Organizations.FromIdentities (orgIdentities.ToArray()); } - public bool CanSeePerson(Person person) + public bool CanSeePerson (Person person) { - People initialList = People.FromArray(new[] {person}); + People initialList = People.FromArray (new[] {person}); - People filteredList = Authorization.FilterPeopleToMatchAuthority(initialList, this); + People filteredList = Authorization.FilterPeopleToMatchAuthority (initialList, this); if (filteredList.Count == 0) { @@ -70,36 +70,36 @@ namespace Swarmops.Logic.Security } - public Geographies GetGeographiesForOrganization(Organization organization) + public Geographies GetGeographiesForOrganization (Organization organization) { return - GetGeographiesForOrganization(organization, RoleTypes.AllRoleTypes); + GetGeographiesForOrganization (organization, RoleTypes.AllRoleTypes); } - public Geographies GetGeographiesForOrganization(Organization organization, RoleType[] roleTypes) + public Geographies GetGeographiesForOrganization (Organization organization, RoleType[] roleTypes) { return - Geographies.FromArray(Authorization.GetNodesInAuthorityForOrganization(this, organization.Identity, + Geographies.FromArray (Authorization.GetNodesInAuthorityForOrganization (this, organization.Identity, roleTypes)); } - public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, Authorization.Flag flags) { - return HasLocalRoleAtOrganizationGeography(organization, geography, RoleTypes.AllLocalRoleTypes, flags); + return HasLocalRoleAtOrganizationGeography (organization, geography, RoleTypes.AllLocalRoleTypes, flags); } - public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, RoleType roleType, Authorization.Flag flags) { - return HasLocalRoleAtOrganizationGeography(organization, geography, + return HasLocalRoleAtOrganizationGeography (organization, geography, new[] {roleType}, flags); } - public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, RoleType[] roleTypes, Authorization.Flag flags) { if (organization != null && organization.Identity == Organization.SandboxIdentity) @@ -153,7 +153,7 @@ namespace Swarmops.Logic.Security if (!organizationClear && (flags & Authorization.Flag.ExactOrganization) == 0) { - if (organization != null && organization.Inherits(role.OrganizationId)) + if (organization != null && organization.Inherits (role.OrganizationId)) { organizationClear = true; } @@ -161,7 +161,7 @@ namespace Swarmops.Logic.Security if (!geographyClear && (flags & Authorization.Flag.ExactGeography) == 0) { - if (geography != null && geography.Inherits(role.GeographyId)) + if (geography != null && geography.Inherits (role.GeographyId)) { geographyClear = true; } @@ -180,17 +180,17 @@ namespace Swarmops.Logic.Security return false; } - public bool HasRoleAtOrganization(Organization organization, Authorization.Flag flags) + public bool HasRoleAtOrganization (Organization organization, Authorization.Flag flags) { - return HasRoleAtOrganization(organization, RoleTypes.AllOrganizationalRoleTypes, flags); + return HasRoleAtOrganization (organization, RoleTypes.AllOrganizationalRoleTypes, flags); } - public bool HasRoleAtOrganization(Organization organization, RoleType roleType, Authorization.Flag flags) + public bool HasRoleAtOrganization (Organization organization, RoleType roleType, Authorization.Flag flags) { - return HasRoleAtOrganization(organization, new[] {roleType}, flags); + return HasRoleAtOrganization (organization, new[] {roleType}, flags); } - public bool HasRoleAtOrganization(Organization organization, RoleType[] roleTypes, Authorization.Flag flags) + public bool HasRoleAtOrganization (Organization organization, RoleType[] roleTypes, Authorization.Flag flags) { if (organization == null) { @@ -220,7 +220,7 @@ namespace Swarmops.Logic.Security if ((flags & Authorization.Flag.ExactOrganization) == 0) { - if (organization.Inherits(role.OrganizationId)) + if (organization.Inherits (role.OrganizationId)) { return true; } @@ -233,12 +233,12 @@ namespace Swarmops.Logic.Security } - public bool HasRoleType(RoleType roleType) + public bool HasRoleType (RoleType roleType) { - return HasAnyRoleType(new[] {roleType}); + return HasAnyRoleType (new[] {roleType}); } - public bool HasAnyRoleType(RoleType[] roleTypes) + public bool HasAnyRoleType (RoleType[] roleTypes) { foreach (RoleType r in roleTypes) { @@ -255,19 +255,19 @@ namespace Swarmops.Logic.Security public bool CanEditSystemRoles() { - return HasPermission(Permission.CanEditSystemRoles, -1, -1, + return HasPermission (Permission.CanEditSystemRoles, -1, -1, Authorization.Flag.ExactGeography | Authorization.Flag.ExactOrganization); } - public bool CanEditOrgRolesForOrg(int orgId) + public bool CanEditOrgRolesForOrg (int orgId) { - return HasPermission(Permission.CanEditOrganisationalRoles, orgId, -1, Authorization.Flag.Default); + return HasPermission (Permission.CanEditOrganisationalRoles, orgId, -1, Authorization.Flag.Default); } - public bool HasAnyPermission(Permission perm) + public bool HasAnyPermission (Permission perm) { - return Authorization.CheckAuthorization(new PermissionSet(perm), -1, -1, this, + return Authorization.CheckAuthorization (new PermissionSet (perm), -1, -1, this, Authorization.Flag.AnyGeographyAnyOrganization); } @@ -277,32 +277,33 @@ namespace Swarmops.Logic.Security return Authorization.CheckAuthorization(new PermissionSet(perm), organizationId, Organization.RootIdentity, this, flags); } */ - public bool HasPermission(Permission perm, int organizationId, int geographyId, Authorization.Flag flags) + public bool HasPermission (Permission perm, int organizationId, int geographyId, Authorization.Flag flags) { - return Authorization.CheckAuthorization(new PermissionSet(perm, organizationId, geographyId), organizationId, + return Authorization.CheckAuthorization (new PermissionSet (perm, organizationId, geographyId), + organizationId, geographyId, this, flags); } - public bool HasPermission(PermissionSet perm, Authorization.Flag flags) + public bool HasPermission (PermissionSet perm, Authorization.Flag flags) { - return Authorization.CheckAuthorization(perm, -1, -1, this, flags); + return Authorization.CheckAuthorization (perm, -1, -1, this, flags); } - public bool HasPermission(PermissionSet perm, int organizationId, int geographyId, Authorization.Flag flags) + public bool HasPermission (PermissionSet perm, int organizationId, int geographyId, Authorization.Flag flags) { - return Authorization.CheckAuthorization(perm, organizationId, geographyId, this, flags); + return Authorization.CheckAuthorization (perm, organizationId, geographyId, this, flags); } - public Organizations OrganisationsWithPermission(Permission perm, RoleType[] roles) + public Organizations OrganisationsWithPermission (Permission perm, RoleType[] roles) { - Organizations orgList = GetOrganizations(roles); + Organizations orgList = GetOrganizations (roles); Organizations retList = new Organizations(); foreach (Organization org in orgList) { - if (HasPermission(perm, org.Identity, -1, Authorization.Flag.Default)) - if (!retList.Contains(org)) - retList.Add(org); + if (HasPermission (perm, org.Identity, -1, Authorization.Flag.Default)) + if (!retList.Contains (org)) + retList.Add (org); } return retList; } diff --git a/Logic/Security/Authorization.cs b/Logic/Security/Authorization.cs index 1c4af1bb..f2e2fdc1 100644 --- a/Logic/Security/Authorization.cs +++ b/Logic/Security/Authorization.cs @@ -130,13 +130,13 @@ namespace Swarmops.Logic.Security } } - public static bool RoleTypeHasPermission(RoleType r, Permission p) + public static bool RoleTypeHasPermission (RoleType r, Permission p) { if (flagReload) InitializeStaticData(); - if (_PermissonsPerRoleTypeDict.ContainsKey(r)) + if (_PermissonsPerRoleTypeDict.ContainsKey (r)) { - if (_PermissonsPerRoleTypeDict[r].ContainsKey(p)) + if (_PermissonsPerRoleTypeDict[r].ContainsKey (p)) { return _PermissonsPerRoleTypeDict[r][p]; } @@ -145,19 +145,19 @@ namespace Swarmops.Logic.Security } - public static RoleType[] RoleTypesWithPermission(Permission p) + public static RoleType[] RoleTypesWithPermission (Permission p) { - return RoleTypesWithPermission(p, RoleTypes.AllLocalRoleTypes); + return RoleTypesWithPermission (p, RoleTypes.AllLocalRoleTypes); } - public static RoleType[] RoleTypesWithPermission(Permission p, RoleType[] rt) + public static RoleType[] RoleTypesWithPermission (Permission p, RoleType[] rt) { List resList = new List(); foreach (RoleType r in rt) { - if (RoleTypeHasPermission(r, p)) + if (RoleTypeHasPermission (r, p)) { - resList.Add(r); + resList.Add (r); } } return resList.ToArray(); @@ -179,25 +179,25 @@ namespace Swarmops.Logic.Security { RoleType role = bp.RoleType; Permission perm = bp.PermissionType; - if (!_PermissonsPerRoleTypeDict.ContainsKey(role)) + if (!_PermissonsPerRoleTypeDict.ContainsKey (role)) { _PermissonsPerRoleTypeDict[role] = new Dictionary(); } _PermissonsPerRoleTypeDict[role][perm] = true; - if (!tempDict.ContainsKey(perm)) + if (!tempDict.ContainsKey (perm)) { List tmpList = new List(); - tempDict.Add(perm, tmpList); + tempDict.Add (perm, tmpList); } - tempDict[perm].Add(role); + tempDict[perm].Add (role); } Dictionary newPermissonsDict = new Dictionary(); foreach (Permission p in tempDict.Keys) { RoleType[] roles = tempDict[p].ToArray(); - newPermissonsDict.Add(p, roles); + newPermissonsDict.Add (p, roles); } PermissonsDict = newPermissonsDict; lastReload = DateTime.Now; @@ -206,21 +206,22 @@ namespace Swarmops.Logic.Security } - public static Authority GetPersonAuthority(int personId) + public static Authority GetPersonAuthority (int personId) { - return Authority.FromBasic(SwarmDb.GetDatabaseForReading().GetPersonAuthority(Person.FromIdentity(personId))); + return + Authority.FromBasic (SwarmDb.GetDatabaseForReading().GetPersonAuthority (Person.FromIdentity (personId))); } - public static BasicGeography[] GetNodesInAuthorityForOrganization(BasicAuthority authority, int organizationId) + public static BasicGeography[] GetNodesInAuthorityForOrganization (BasicAuthority authority, int organizationId) { - return GetNodesInAuthorityForOrganization(authority, organizationId, RoleTypes.AllRoleTypes); + return GetNodesInAuthorityForOrganization (authority, organizationId, RoleTypes.AllRoleTypes); } - public static BasicGeography[] GetNodesInAuthorityForOrganization(BasicAuthority authority, int organizationId, + public static BasicGeography[] GetNodesInAuthorityForOrganization (BasicAuthority authority, int organizationId, RoleType[] roleTypes) { - Organizations organizationLine = Organization.FromIdentity(organizationId).GetLine(); + Organizations organizationLine = Organization.FromIdentity (organizationId).GetLine(); // Build lookup tables @@ -242,15 +243,15 @@ namespace Swarmops.Logic.Security if (authority.AllPersonRoles.Length > 0) { - Dictionary geoDict = GeographyCache.GetGeographyHashtable(Geography.RootIdentity); + Dictionary geoDict = GeographyCache.GetGeographyHashtable (Geography.RootIdentity); foreach (BasicPersonRole role in authority.AllPersonRoles) { - if (orgLookup.ContainsKey(role.OrganizationId)) + if (orgLookup.ContainsKey (role.OrganizationId)) { - if (roleLookup.ContainsKey(role.Type)) + if (roleLookup.ContainsKey (role.Type)) { - result.Add(geoDict[role.GeographyId]); + result.Add (geoDict[role.GeographyId]); } } } @@ -285,10 +286,11 @@ namespace Swarmops.Logic.Security /// The node the activity is applied to, or zero for world. /// The person performing the activity (NOT the victim of it). /// True if allowed under current authority. - public static bool CheckAuthorization(PermissionSet permissionsNeeded, int organizationId, int geoNodeId, + public static bool CheckAuthorization (PermissionSet permissionsNeeded, int organizationId, int geoNodeId, int checkedPersonId, Flag flags) { - return CheckAuthorization(permissionsNeeded, organizationId, geoNodeId, GetPersonAuthority(checkedPersonId), + return CheckAuthorization (permissionsNeeded, organizationId, geoNodeId, + GetPersonAuthority (checkedPersonId), flags); } @@ -300,7 +302,7 @@ namespace Swarmops.Logic.Security /// The node the activity is applied to, or zero for world. /// The authority to test against. /// True if allowed under current authority. - public static bool CheckAuthorization(PermissionSet permissionsNeeded, int organizationId, int geoNodeId, + public static bool CheckAuthorization (PermissionSet permissionsNeeded, int organizationId, int geoNodeId, Authority authority, Flag flags) { if (permissionsNeeded == null) @@ -310,7 +312,7 @@ namespace Swarmops.Logic.Security { try { - currentGeo = Geography.FromIdentity(geoNodeId); + currentGeo = Geography.FromIdentity (geoNodeId); } catch { @@ -322,7 +324,7 @@ namespace Swarmops.Logic.Security { try { - currentOrg = Organization.FromIdentity(organizationId); + currentOrg = Organization.FromIdentity (organizationId); } catch { @@ -340,7 +342,7 @@ namespace Swarmops.Logic.Security { try { - innerCurrentGeo = Geography.FromIdentity(perm.geographyId); + innerCurrentGeo = Geography.FromIdentity (perm.geographyId); } catch { @@ -353,7 +355,7 @@ namespace Swarmops.Logic.Security { try { - innerCurrentOrg = Organization.FromIdentity(perm.orgId); + innerCurrentOrg = Organization.FromIdentity (perm.orgId); } catch { @@ -363,13 +365,13 @@ namespace Swarmops.Logic.Security innerCurrentOrg = currentOrg; RoleType[] rolesForPerm = {}; - if (PermissonsDict.ContainsKey(perm.perm)) + if (PermissonsDict.ContainsKey (perm.perm)) rolesForPerm = PermissonsDict[perm.perm]; if (perm.perm == Permission.CanSeeSelf) thisFound = 1; else if (rolesForPerm.Length > 0) - thisFound = CheckSpecificValidRoles(authority, rolesForPerm, innerCurrentGeo, innerCurrentOrg, + thisFound = CheckSpecificValidRoles (authority, rolesForPerm, innerCurrentGeo, innerCurrentOrg, thisFound, flags); @@ -385,26 +387,27 @@ namespace Swarmops.Logic.Security return false; } - private static int CheckSpecificValidRoles(Authority authority, RoleType[] roles, + private static int CheckSpecificValidRoles (Authority authority, RoleType[] roles, Geography currentGeo, Organization currentOrg, int thisFound, Flag flags) { - if (authority.HasAnyRoleType(roles)) + if (authority.HasAnyRoleType (roles)) { //Yes, we have one of the roles foreach (RoleType r in roles) { - if (authority.HasRoleType(r) && (Array.IndexOf(RoleTypes.AllLocalRoleTypes, r) > -1)) + if (authority.HasRoleType (r) && (Array.IndexOf (RoleTypes.AllLocalRoleTypes, r) > -1)) { - thisFound = authority.HasLocalRoleAtOrganizationGeography(currentOrg, currentGeo, r, flags) + thisFound = authority.HasLocalRoleAtOrganizationGeography (currentOrg, currentGeo, r, flags) ? 1 : thisFound; } - else if (authority.HasRoleType(r) && ((Array.IndexOf(RoleTypes.AllOrganizationalRoleTypes, r) > -1))) + else if (authority.HasRoleType (r) && + ((Array.IndexOf (RoleTypes.AllOrganizationalRoleTypes, r) > -1))) { - thisFound = authority.HasRoleAtOrganization(currentOrg, r, flags) ? 1 : thisFound; + thisFound = authority.HasRoleAtOrganization (currentOrg, r, flags) ? 1 : thisFound; } - else if (authority.HasRoleType(r) && ((Array.IndexOf(RoleTypes.AllSystemRoleTypes, r) > -1))) + else if (authority.HasRoleType (r) && ((Array.IndexOf (RoleTypes.AllSystemRoleTypes, r) > -1))) { //System PersonRole thisFound = 1; @@ -424,12 +427,12 @@ namespace Swarmops.Logic.Security } - public static Memberships FilterMembershipsToMatchAuthority(Memberships memberships, Geography personGeography, + public static Memberships FilterMembershipsToMatchAuthority (Memberships memberships, Geography personGeography, Authority authority) { // First: If sysadmin, return the whole list uncensored. - if (IsSystemAdministrator(authority)) + if (IsSystemAdministrator (authority)) { return memberships; } @@ -440,15 +443,15 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.OrganizationPersonRoles) { Dictionary clearedOrganizations = - OrganizationCache.GetOrganizationHashtable(role.OrganizationId); + OrganizationCache.GetOrganizationHashtable (role.OrganizationId); foreach (Membership membership in memberships) { - bool organizationClear = clearedOrganizations.ContainsKey(membership.OrganizationId); + bool organizationClear = clearedOrganizations.ContainsKey (membership.OrganizationId); if (organizationClear && - authority.HasPermission(Permission.CanViewMemberships, membership.OrganizationId, + authority.HasPermission (Permission.CanViewMemberships, membership.OrganizationId, membership.Person.GeographyId, Flag.Default)) { clearedMemberships[membership.Identity] = membership; @@ -460,20 +463,20 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.LocalPersonRoles) { Dictionary clearedGeographies = - GeographyCache.GetGeographyHashtable(role.GeographyId); + GeographyCache.GetGeographyHashtable (role.GeographyId); Dictionary clearedOrganizations = - OrganizationCache.GetOrganizationHashtable(role.OrganizationId); + OrganizationCache.GetOrganizationHashtable (role.OrganizationId); - bool geographyClear = clearedGeographies.ContainsKey(personGeography.Identity); + bool geographyClear = clearedGeographies.ContainsKey (personGeography.Identity); geographyClear = geographyClear && - authority.HasPermission(Permission.CanViewMemberships, role.OrganizationId, + authority.HasPermission (Permission.CanViewMemberships, role.OrganizationId, personGeography.Identity, Flag.Default); if (geographyClear) { foreach (Membership membership in memberships) { - bool organizationClear = clearedOrganizations.ContainsKey(membership.OrganizationId); + bool organizationClear = clearedOrganizations.ContainsKey (membership.OrganizationId); if (organizationClear) { @@ -490,25 +493,25 @@ namespace Swarmops.Logic.Security foreach (Membership membership in clearedMemberships.Values) { - result.Add(membership); + result.Add (membership); } return result; } - public static People FilterPeopleToMatchAuthority(People people, Authority authority) + public static People FilterPeopleToMatchAuthority (People people, Authority authority) { - return FilterPeopleToMatchAuthority(people, authority, -1); + return FilterPeopleToMatchAuthority (people, authority, -1); // -1 indicates to respect grace period } - public static People FilterPeopleToMatchAuthority(People people, Authority authority, int gracePeriod) + public static People FilterPeopleToMatchAuthority (People people, Authority authority, int gracePeriod) { // First: If sysadmin, return the whole list uncensored. - if (IsSystemAdministrator(authority)) + if (IsSystemAdministrator (authority)) { return people; } @@ -519,8 +522,8 @@ namespace Swarmops.Logic.Security gracePeriod = Membership.GracePeriod; Dictionary> membershipTable = - databaseRead.GetMembershipsForPeople(people.Identities, gracePeriod); - Dictionary geographyTable = databaseRead.GetPeopleGeographies(people.Identities); + databaseRead.GetMembershipsForPeople (people.Identities, gracePeriod); + Dictionary geographyTable = databaseRead.GetPeopleGeographies (people.Identities); Dictionary clearedPeople = new Dictionary(); @@ -531,26 +534,26 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.OrganizationPersonRoles) { Dictionary clearedOrganizations = - OrganizationCache.GetOrganizationHashtable(role.OrganizationId); + OrganizationCache.GetOrganizationHashtable (role.OrganizationId); foreach (Person person in people) { // Is the organization cleared in this officer's role for this to-be-viewed member? - if (membershipTable.ContainsKey(person.Identity)) + if (membershipTable.ContainsKey (person.Identity)) { foreach (BasicMembership membership in membershipTable[person.Identity]) { - if (clearedOrganizations.ContainsKey(membership.OrganizationId) + if (clearedOrganizations.ContainsKey (membership.OrganizationId) && - authority.HasPermission(Permission.CanSeePeople, membership.OrganizationId, + authority.HasPermission (Permission.CanSeePeople, membership.OrganizationId, person.GeographyId, Flag.Default)) { if (membership.Active - || (membership.Expires > DateTime.Now.AddDays(-gracePeriod) - && membership.Expires.AddDays(1) > membership.DateTerminated + || (membership.Expires > DateTime.Now.AddDays (-gracePeriod) + && membership.Expires.AddDays (1) > membership.DateTerminated && - authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, + authority.HasPermission (Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default))) { clearedPeople[person.Identity] = person; @@ -559,7 +562,7 @@ namespace Swarmops.Logic.Security } } } - /* -- commented out. This means "does the current authority have Org Admin privileges over Person"? + /* -- commented out. This means "does the current authority have Org Admin privileges over Person"? else if (CanSeeNonMembers) { //person isn't member anywhere clearedPeople[person.Identity] = person; @@ -578,25 +581,25 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.LocalPersonRoles) { Dictionary clearedGeographies = - GeographyCache.GetGeographyHashtable(role.GeographyId); + GeographyCache.GetGeographyHashtable (role.GeographyId); Dictionary clearedOrganizations = - OrganizationCache.GetOrganizationHashtable(role.OrganizationId); + OrganizationCache.GetOrganizationHashtable (role.OrganizationId); foreach (Person person in people) { // Is the node AND the organization cleared in this officer's role for this to-be-viewed member? - if (membershipTable.ContainsKey(person.Identity)) + if (membershipTable.ContainsKey (person.Identity)) { foreach (BasicMembership membership in membershipTable[person.Identity]) { int organizationClear = 0; int geographyClear = 0; - if (clearedOrganizations.ContainsKey(membership.OrganizationId)) + if (clearedOrganizations.ContainsKey (membership.OrganizationId)) { organizationClear = membership.OrganizationId; - if (clearedGeographies.ContainsKey(geographyTable[person.Identity])) + if (clearedGeographies.ContainsKey (geographyTable[person.Identity])) { geographyClear = geographyTable[person.Identity]; } @@ -604,14 +607,14 @@ namespace Swarmops.Logic.Security if (organizationClear > 0 && geographyClear > 0 && - authority.HasPermission(Permission.CanSeePeople, organizationClear, geographyClear, + authority.HasPermission (Permission.CanSeePeople, organizationClear, geographyClear, Flag.Default)) { if (membership.Active - || (membership.Expires > DateTime.Now.AddDays(-gracePeriod) - && membership.Expires.AddDays(1) > membership.DateTerminated + || (membership.Expires > DateTime.Now.AddDays (-gracePeriod) + && membership.Expires.AddDays (1) > membership.DateTerminated && - authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, + authority.HasPermission (Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default))) { clearedPeople[person.Identity] = person; @@ -631,14 +634,14 @@ namespace Swarmops.Logic.Security foreach (Person clearedPerson in clearedPeople.Values) { - result.Add(clearedPerson); + result.Add (clearedPerson); } return result; } - public static BasicPerson[] FilterUnlistedPeople(BasicPerson[] people) + public static BasicPerson[] FilterUnlistedPeople (BasicPerson[] people) { Dictionary unlistedTable = new Dictionary(); List result = new List(); @@ -653,7 +656,7 @@ namespace Swarmops.Logic.Security // Get ALL unlisted people from database. They're not that many. Build a hashtable with them. int[] anonymousPersonIds = SwarmDb.GetDatabaseForReading() - .GetObjectsByOptionalData(ObjectType.Person, ObjectOptionalDataType.Anonymous, "1"); + .GetObjectsByOptionalData (ObjectType.Person, ObjectOptionalDataType.Anonymous, "1"); foreach (int anonymousPersonId in anonymousPersonIds) { @@ -664,9 +667,9 @@ namespace Swarmops.Logic.Security foreach (BasicPerson person in people) { - if (!unlistedTable.ContainsKey(person.Identity)) + if (!unlistedTable.ContainsKey (person.Identity)) { - result.Add(person); + result.Add (person); } } @@ -674,7 +677,7 @@ namespace Swarmops.Logic.Security } - public static BasicPerson[] FilterUniquePeople(BasicPerson[] people) + public static BasicPerson[] FilterUniquePeople (BasicPerson[] people) { // Somewhat crude dupelist, but atleast it can give some hints @@ -690,58 +693,58 @@ namespace Swarmops.Logic.Security if (people == null || people.Length == 0) { - return (new List(result.Values)).ToArray(); + return (new List (result.Values)).ToArray(); } foreach (Person p in people) { - if (uniqueTableName.ContainsKey(p.Name)) + if (uniqueTableName.ContainsKey (p.Name)) { foreach (Person sameperson in uniqueTableName[p.Name]) { - MatchPerson(result, p, sameperson); + MatchPerson (result, p, sameperson); } - uniqueTableName[p.Name].Add(p); + uniqueTableName[p.Name].Add (p); } else { uniqueTableName[p.Name] = new List(); - uniqueTableName[p.Name].Add(p); + uniqueTableName[p.Name].Add (p); } - if (uniqueTablePhone.ContainsKey(p.Phone) && p.Phone.Replace("0", "").Trim() != "") + if (uniqueTablePhone.ContainsKey (p.Phone) && p.Phone.Replace ("0", "").Trim() != "") { foreach (Person sameperson in uniqueTablePhone[p.Phone]) { - MatchPerson(result, p, sameperson); + MatchPerson (result, p, sameperson); } - uniqueTablePhone[p.Phone].Add(p); + uniqueTablePhone[p.Phone].Add (p); } else { uniqueTablePhone[p.Phone] = new List(); - uniqueTablePhone[p.Phone].Add(p); + uniqueTablePhone[p.Phone].Add (p); } - if (uniqueTableEmail.ContainsKey(p.Mail)) + if (uniqueTableEmail.ContainsKey (p.Mail)) { foreach (Person sameperson in uniqueTableEmail[p.Mail]) { - MatchPerson(result, p, sameperson); + MatchPerson (result, p, sameperson); } - uniqueTableEmail[p.Mail].Add(p); + uniqueTableEmail[p.Mail].Add (p); } else { uniqueTableEmail[p.Mail] = new List(); - uniqueTableEmail[p.Mail].Add(p); + uniqueTableEmail[p.Mail].Add (p); } } - return (new List(result.Values)).ToArray(); + return (new List (result.Values)).ToArray(); } - private static void MatchPerson(Dictionary result, Person p, BasicPerson sameperson) + private static void MatchPerson (Dictionary result, Person p, BasicPerson sameperson) { int matches = 0; if (p.Name.Trim().ToLower() == sameperson.Name.Trim().ToLower()) @@ -752,14 +755,14 @@ namespace Swarmops.Logic.Security ++matches; if (matches > 1) { - if (!result.ContainsKey(p.PersonId)) - result.Add(p.PersonId, p); - if (!result.ContainsKey(sameperson.PersonId)) - result.Add(sameperson.PersonId, sameperson); + if (!result.ContainsKey (p.PersonId)) + result.Add (p.PersonId, p); + if (!result.ContainsKey (sameperson.PersonId)) + result.Add (sameperson.PersonId, sameperson); } } - private static bool IsSystemAdministrator(BasicAuthority authority) + private static bool IsSystemAdministrator (BasicAuthority authority) { foreach (BasicPersonRole role in authority.SystemPersonRoles) { @@ -772,21 +775,21 @@ namespace Swarmops.Logic.Security return false; } - public static int[] PersonsWithRoleInOrg(RoleType roleType, int p, bool includeChildOrgs) + public static int[] PersonsWithRoleInOrg (RoleType roleType, int p, bool includeChildOrgs) { Organizations line = new Organizations(); if (includeChildOrgs) - line = Organization.FromIdentity(p).GetLine(); + line = Organization.FromIdentity (p).GetLine(); else - line.Add(Organization.FromIdentity(p)); + line.Add (Organization.FromIdentity (p)); BasicPersonRole[] basPersons - = SwarmDb.GetDatabaseForReading().GetPeopleWithRoleType(roleType, line.Identities, new int[] {}); + = SwarmDb.GetDatabaseForReading().GetPeopleWithRoleType (roleType, line.Identities, new int[] {}); List retList = new List(); foreach (BasicPersonRole b in basPersons) - retList.Add(b.PersonId); + retList.Add (b.PersonId); return retList.ToArray(); } diff --git a/Logic/Security/BCrypt.cs b/Logic/Security/BCrypt.cs index 51cf36dc..46b651af 100644 --- a/Logic/Security/BCrypt.cs +++ b/Logic/Security/BCrypt.cs @@ -393,38 +393,38 @@ namespace Swarmops.Logic.Security /// The byte array to encode /// The number of bytes to encode /// A Base64-encoded string - private static string EncodeBase64(byte[] d, int length) + private static string EncodeBase64 (byte[] d, int length) { if (length <= 0 || length > d.Length) { - throw new ArgumentOutOfRangeException("length", length, null); + throw new ArgumentOutOfRangeException ("length", length, null); } - StringBuilder rs = new StringBuilder(length*2); + StringBuilder rs = new StringBuilder (length*2); for (int offset = 0, c1, c2; offset < length;) { c1 = d[offset++] & 0xff; - rs.Append(base64_code[(c1 >> 2) & 0x3f]); + rs.Append (base64_code[(c1 >> 2) & 0x3f]); c1 = (c1 & 0x03) << 4; if (offset >= length) { - rs.Append(base64_code[c1 & 0x3f]); + rs.Append (base64_code[c1 & 0x3f]); break; } c2 = d[offset++] & 0xff; c1 |= (c2 >> 4) & 0x0f; - rs.Append(base64_code[c1 & 0x3f]); + rs.Append (base64_code[c1 & 0x3f]); c1 = (c2 & 0x0f) << 2; if (offset >= length) { - rs.Append(base64_code[c1 & 0x3f]); + rs.Append (base64_code[c1 & 0x3f]); break; } c2 = d[offset++] & 0xff; c1 |= (c2 >> 6) & 0x03; - rs.Append(base64_code[c1 & 0x3f]); - rs.Append(base64_code[c2 & 0x3f]); + rs.Append (base64_code[c1 & 0x3f]); + rs.Append (base64_code[c2 & 0x3f]); } return rs.ToString(); @@ -437,7 +437,7 @@ namespace Swarmops.Logic.Security /// /// The Base64-encoded value /// The decoded value of x - private static int Char64(char c) + private static int Char64 (char c) { int i = c; return (i < 0 || i > index_64.Length) ? -1 : index_64[i]; @@ -451,44 +451,44 @@ namespace Swarmops.Logic.Security /// The string to decode /// The maximum number of bytes to decode /// An array containing the decoded bytes - private static byte[] DecodeBase64(string s, int maximumLength) + private static byte[] DecodeBase64 (string s, int maximumLength) { - List bytes = new List(Math.Min(maximumLength, s.Length)); + List bytes = new List (Math.Min (maximumLength, s.Length)); if (maximumLength <= 0) { - throw new ArgumentOutOfRangeException("maximumLength", maximumLength, null); + throw new ArgumentOutOfRangeException ("maximumLength", maximumLength, null); } for (int offset = 0, slen = s.Length, length = 0; offset < slen - 1 && length < maximumLength;) { - int c1 = Char64(s[offset++]); - int c2 = Char64(s[offset++]); + int c1 = Char64 (s[offset++]); + int c2 = Char64 (s[offset++]); if (c1 == -1 || c2 == -1) { break; } - bytes.Add((byte) ((c1 << 2) | ((c2 & 0x30) >> 4))); + bytes.Add ((byte) ((c1 << 2) | ((c2 & 0x30) >> 4))); if (++length >= maximumLength || offset >= s.Length) { break; } - int c3 = Char64(s[offset++]); + int c3 = Char64 (s[offset++]); if (c3 == -1) { break; } - bytes.Add((byte) (((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2))); + bytes.Add ((byte) (((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2))); if (++length >= maximumLength || offset >= s.Length) { break; } - int c4 = Char64(s[offset++]); - bytes.Add((byte) (((c3 & 0x03) << 6) | c4)); + int c4 = Char64 (s[offset++]); + bytes.Add ((byte) (((c3 & 0x03) << 6) | c4)); ++length; } @@ -508,7 +508,7 @@ namespace Swarmops.Logic.Security /// The position in the array of the /// blocks. /// - private void Encipher(uint[] block, int offset) + private void Encipher (uint[] block, int offset) { uint i, n, l = block[offset], r = block[offset + 1]; @@ -546,7 +546,7 @@ namespace Swarmops.Logic.Security /// /// The current offset into data. /// The next work of material from data. - private static uint StreamToWord(byte[] data, ref int offset) + private static uint StreamToWord (byte[] data, ref int offset) { uint word = 0; @@ -565,16 +565,16 @@ namespace Swarmops.Logic.Security private void InitKey() { this.p = new uint[p_orig.Length]; - p_orig.CopyTo(this.p, 0); + p_orig.CopyTo (this.p, 0); this.s = new uint[s_orig.Length]; - s_orig.CopyTo(this.s, 0); + s_orig.CopyTo (this.s, 0); } /// /// Key the Blowfish cipher. /// /// An array containing the key. - private void Key(byte[] key) + private void Key (byte[] key) { uint[] lr = {0, 0}; int plen = this.p.Length, slen = this.s.Length; @@ -582,19 +582,19 @@ namespace Swarmops.Logic.Security int offset = 0; for (int i = 0; i < plen; i++) { - this.p[i] = this.p[i] ^ StreamToWord(key, ref offset); + this.p[i] = this.p[i] ^ StreamToWord (key, ref offset); } for (int i = 0; i < plen; i += 2) { - Encipher(lr, 0); + Encipher (lr, 0); this.p[i] = lr[0]; this.p[i + 1] = lr[1]; } for (int i = 0; i < slen; i += 2) { - Encipher(lr, 0); + Encipher (lr, 0); this.s[i] = lr[0]; this.s[i + 1] = lr[1]; } @@ -607,7 +607,7 @@ namespace Swarmops.Logic.Security /// /// Salt information. /// Password information. - private void EksKey(byte[] data, byte[] key) + private void EksKey (byte[] data, byte[] key) { uint[] lr = {0, 0}; int plen = this.p.Length, slen = this.s.Length; @@ -615,24 +615,24 @@ namespace Swarmops.Logic.Security int keyOffset = 0; for (int i = 0; i < plen; i++) { - this.p[i] = this.p[i] ^ StreamToWord(key, ref keyOffset); + this.p[i] = this.p[i] ^ StreamToWord (key, ref keyOffset); } int dataOffset = 0; for (int i = 0; i < plen; i += 2) { - lr[0] ^= StreamToWord(data, ref dataOffset); - lr[1] ^= StreamToWord(data, ref dataOffset); - Encipher(lr, 0); + lr[0] ^= StreamToWord (data, ref dataOffset); + lr[1] ^= StreamToWord (data, ref dataOffset); + Encipher (lr, 0); this.p[i] = lr[0]; this.p[i + 1] = lr[1]; } for (int i = 0; i < slen; i += 2) { - lr[0] ^= StreamToWord(data, ref dataOffset); - lr[1] ^= StreamToWord(data, ref dataOffset); - Encipher(lr, 0); + lr[0] ^= StreamToWord (data, ref dataOffset); + lr[1] ^= StreamToWord (data, ref dataOffset); + Encipher (lr, 0); this.s[i] = lr[0]; this.s[i + 1] = lr[1]; } @@ -652,39 +652,39 @@ namespace Swarmops.Logic.Security /// rounds of hashing to apply. /// /// An array containing the binary hashed password. - private byte[] CryptRaw(byte[] password, byte[] salt, int logRounds) + private byte[] CryptRaw (byte[] password, byte[] salt, int logRounds) { uint[] cdata = new uint[bf_crypt_ciphertext.Length]; - bf_crypt_ciphertext.CopyTo(cdata, 0); + bf_crypt_ciphertext.CopyTo (cdata, 0); int clen = cdata.Length; byte[] ret; if (logRounds < 4 || logRounds > 31) { - throw new ArgumentOutOfRangeException("logRounds", logRounds, null); + throw new ArgumentOutOfRangeException ("logRounds", logRounds, null); } int rounds = 1 << logRounds; if (salt.Length != BCRYPT_SALT_LEN) { - throw new ArgumentException("Invalid salt length.", "salt"); + throw new ArgumentException ("Invalid salt length.", "salt"); } InitKey(); - EksKey(salt, password); + EksKey (salt, password); for (int i = 0; i < rounds; i++) { - Key(password); - Key(salt); + Key (password); + Key (salt); } for (int i = 0; i < 64; i++) { for (int j = 0; j < (clen >> 1); j++) { - Encipher(cdata, j << 1); + Encipher (cdata, j << 1); } } @@ -709,22 +709,22 @@ namespace Swarmops.Logic.Security /// using BCrypt.GenerateSalt). /// /// The hashed password. - public static string HashPassword(string password, string salt) + public static string HashPassword (string password, string salt) { if (password == null) { - throw new ArgumentNullException("password"); + throw new ArgumentNullException ("password"); } if (salt == null) { - throw new ArgumentNullException("salt"); + throw new ArgumentNullException ("salt"); } char minor = (char) 0; if (salt[0] != '$' || salt[1] != '2') { - throw new ArgumentException("Invalid salt version"); + throw new ArgumentException ("Invalid salt version"); } int offset; @@ -733,7 +733,7 @@ namespace Swarmops.Logic.Security minor = salt[2]; if (minor != 'a' || salt[3] != '$') { - throw new ArgumentException("Invalid salt revision"); + throw new ArgumentException ("Invalid salt revision"); } offset = 4; } @@ -745,35 +745,35 @@ namespace Swarmops.Logic.Security // Extract number of rounds if (salt[offset + 2] > '$') { - throw new ArgumentException("Missing salt rounds"); + throw new ArgumentException ("Missing salt rounds"); } - int rounds = Int32.Parse(salt.Substring(offset, 2), NumberFormatInfo.InvariantInfo); + int rounds = Int32.Parse (salt.Substring (offset, 2), NumberFormatInfo.InvariantInfo); - byte[] passwordBytes = Encoding.UTF8.GetBytes(password + (minor >= 'a' ? "\0" : String.Empty)); - byte[] saltBytes = DecodeBase64(salt.Substring(offset + 3, 22), + byte[] passwordBytes = Encoding.UTF8.GetBytes (password + (minor >= 'a' ? "\0" : String.Empty)); + byte[] saltBytes = DecodeBase64 (salt.Substring (offset + 3, 22), BCRYPT_SALT_LEN); BCrypt bcrypt = new BCrypt(); - byte[] hashed = bcrypt.CryptRaw(passwordBytes, saltBytes, rounds); + byte[] hashed = bcrypt.CryptRaw (passwordBytes, saltBytes, rounds); StringBuilder rs = new StringBuilder(); - rs.Append("$2"); + rs.Append ("$2"); if (minor >= 'a') { - rs.Append(minor); + rs.Append (minor); } - rs.Append('$'); + rs.Append ('$'); if (rounds < 10) { - rs.Append('0'); + rs.Append ('0'); } - rs.Append(rounds); - rs.Append('$'); - rs.Append(EncodeBase64(saltBytes, saltBytes.Length)); - rs.Append(EncodeBase64(hashed, + rs.Append (rounds); + rs.Append ('$'); + rs.Append (EncodeBase64 (saltBytes, saltBytes.Length)); + rs.Append (EncodeBase64 (hashed, (bf_crypt_ciphertext.Length*4) - 1)); return rs.ToString(); @@ -788,22 +788,22 @@ namespace Swarmops.Logic.Security /// logRounds). /// /// An encoded salt value. - public static string GenerateSalt(int logRounds) + public static string GenerateSalt (int logRounds) { byte[] randomBytes = new byte[BCRYPT_SALT_LEN]; - RandomNumberGenerator.Create().GetBytes(randomBytes); + RandomNumberGenerator.Create().GetBytes (randomBytes); - StringBuilder rs = new StringBuilder((randomBytes.Length*2) + 8); + StringBuilder rs = new StringBuilder ((randomBytes.Length*2) + 8); - rs.Append("$2a$"); + rs.Append ("$2a$"); if (logRounds < 10) { - rs.Append('0'); + rs.Append ('0'); } - rs.Append(logRounds); - rs.Append('$'); - rs.Append(EncodeBase64(randomBytes, randomBytes.Length)); + rs.Append (logRounds); + rs.Append ('$'); + rs.Append (EncodeBase64 (randomBytes, randomBytes.Length)); return rs.ToString(); } @@ -816,7 +816,7 @@ namespace Swarmops.Logic.Security /// An encoded salt value. public static string GenerateSalt() { - return GenerateSalt(GENSALT_DEFAULT_LOG2_ROUNDS); + return GenerateSalt (GENSALT_DEFAULT_LOG2_ROUNDS); } /// @@ -829,9 +829,9 @@ namespace Swarmops.Logic.Security /// true if the passwords, false /// otherwise. /// - public static bool CheckPassword(string plaintext, string hashed) + public static bool CheckPassword (string plaintext, string hashed) { - return StringComparer.Ordinal.Compare(hashed, HashPassword(plaintext, hashed)) == 0; + return StringComparer.Ordinal.Compare (hashed, HashPassword (plaintext, hashed)) == 0; } } } \ No newline at end of file diff --git a/Logic/Security/MD5.cs b/Logic/Security/MD5.cs index f71a0956..eb57cc13 100644 --- a/Logic/Security/MD5.cs +++ b/Logic/Security/MD5.cs @@ -8,12 +8,12 @@ namespace Swarmops /// public class MD5 { - public static string Hash(string input) + public static string Hash (string input) { - byte[] data = Encoding.GetEncoding(1252).GetBytes(input); + byte[] data = Encoding.GetEncoding (1252).GetBytes (input); System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider(); - byte[] hash = md5.ComputeHash(data); + byte[] hash = md5.ComputeHash (data); // Write the resulting hash to a string of hex values. @@ -21,7 +21,7 @@ namespace Swarmops foreach (byte oneByte in hash) { - result.Append(oneByte.ToString("X02") + " "); + result.Append (oneByte.ToString ("X02") + " "); } return result.ToString().TrimEnd(); diff --git a/Logic/Security/PermissionSet.cs b/Logic/Security/PermissionSet.cs index 5d765442..f7a4295d 100644 --- a/Logic/Security/PermissionSet.cs +++ b/Logic/Security/PermissionSet.cs @@ -12,29 +12,29 @@ namespace Swarmops.Logic.Security public List permsList = new List(); - public PermissionSet(Permission p) + public PermissionSet (Permission p) { - this.permsList.Add(new Item(-1, -1, p)); + this.permsList.Add (new Item (-1, -1, p)); } - public PermissionSet(Permission p, int orgId) + public PermissionSet (Permission p, int orgId) { - this.permsList.Add(new Item(orgId, -1, p)); + this.permsList.Add (new Item (orgId, -1, p)); } - public PermissionSet(Permission p, int orgId, int geoId) + public PermissionSet (Permission p, int orgId, int geoId) { - this.permsList.Add(new Item(orgId, geoId, p)); + this.permsList.Add (new Item (orgId, geoId, p)); } - public PermissionSet(Item pi) + public PermissionSet (Item pi) { - this.permsList.Add(pi); + this.permsList.Add (pi); } - public PermissionSet(string permsString) + public PermissionSet (string permsString) { - Regex re = new Regex( + Regex re = new Regex ( @" # will search Permission(1,1),Permission(1,1),Permission ( # group for each ,Permission(1,1) or ,Permission ( @@ -51,7 +51,7 @@ namespace Swarmops.Logic.Security ) ,* # group could end with comma )", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); - MatchCollection matches = re.Matches(permsString); + MatchCollection matches = re.Matches (permsString); foreach (Match m in matches) { try @@ -62,20 +62,20 @@ namespace Swarmops.Logic.Security try { string pars = m.Groups["params"].Value; - string[] split = pars.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); + string[] split = pars.Split (new[] {','}, StringSplitOptions.RemoveEmptyEntries); if (pars.Length > 0) { - org = int.Parse(split[0]); + org = int.Parse (split[0]); if (pars.Length > 1) - geo = int.Parse(split[1]); + geo = int.Parse (split[1]); } } catch { } - Permission p = (Permission) Enum.Parse(typeof (Permission), hit, true); - Item item = new Item(org, geo, p); - this.permsList.Add(item); + Permission p = (Permission) Enum.Parse (typeof (Permission), hit, true); + Item item = new Item (org, geo, p); + this.permsList.Add (item); } catch { @@ -95,7 +95,7 @@ namespace Swarmops.Logic.Security set { this.needAll = !value; } } - public bool IsInSet(Permission p) + public bool IsInSet (Permission p) { foreach (Item ps in this.permsList) if (ps.perm == p) @@ -103,18 +103,18 @@ namespace Swarmops.Logic.Security return false; } - public bool IsInSet(PermissionSet ps) + public bool IsInSet (PermissionSet ps) { foreach (Permission p in ps) - if (!IsInSet(p)) + if (!IsInSet (p)) return false; return true; } - public bool IsAnyInSet(PermissionSet ps) + public bool IsAnyInSet (PermissionSet ps) { foreach (Permission p in ps) - if (IsInSet(p)) + if (IsInSet (p)) return true; return false; } @@ -124,16 +124,16 @@ namespace Swarmops.Logic.Security List reslist = new List(); foreach (Item itm in this) { - reslist.Add(itm.perm.ToString()); + reslist.Add (itm.perm.ToString()); } string[] resArr = reslist.ToArray(); - string res = string.Join(this.needAll ? " & " : " | ", resArr); + string res = string.Join (this.needAll ? " & " : " | ", resArr); return res; } public Enumerator GetEnumerator() { - return new Enumerator(this); + return new Enumerator (this); } public class Enumerator : IEnumerator @@ -141,7 +141,7 @@ namespace Swarmops.Logic.Security private readonly PermissionSet parent; private int currentIndex = -1; - internal Enumerator(PermissionSet p) + internal Enumerator (PermissionSet p) { this.parent = p; Reset(); @@ -174,21 +174,21 @@ namespace Swarmops.Logic.Security public class Item { - public Item(int pOrgId, int pGeoId, Permission pPerm) + public Item (int pOrgId, int pGeoId, Permission pPerm) { orgId = pOrgId; geographyId = pGeoId; perm = pPerm; } - public Item(int pOrgId, Permission pPerm) + public Item (int pOrgId, Permission pPerm) { orgId = pOrgId; geographyId = -1; perm = pPerm; } - public Item(Permission pPerm) + public Item (Permission pPerm) { orgId = -1; geographyId = -1; diff --git a/Logic/Security/PgpKey.cs b/Logic/Security/PgpKey.cs index a69e0355..adfd8441 100644 --- a/Logic/Security/PgpKey.cs +++ b/Logic/Security/PgpKey.cs @@ -9,12 +9,12 @@ namespace Swarmops.Logic.Security { public string Fingerprint { get; private set; } - public static void Generate(Person person, Organization organization) + public static void Generate (Person person, Organization organization) { GnuPG generatingInstance = new GnuPG(); generatingInstance.Timeout = 120000; - generatingInstance.GenerateKeyPair(person.Name, person.PartyEmail, organization.Name, - new DateTime(DateTime.Today.Year + 2, 12, 31)); + generatingInstance.GenerateKeyPair (person.Name, person.PartyEmail, organization.Name, + new DateTime (DateTime.Today.Year + 2, 12, 31)); GnuPGKeyCollection keys = new GnuPG().GetKeys(); foreach (GnuPGKey key in keys) @@ -22,11 +22,11 @@ namespace Swarmops.Logic.Security if (key.UserId == person.PartyEmail) { // Console.Write(" signing..."); - generatingInstance.SignKey(key.Fingerprint, "system@pirateweb.net"); + generatingInstance.SignKey (key.Fingerprint, "system@pirateweb.net"); // Console.Write(" uploading..."); - generatingInstance.UploadKey(key.Fingerprint.Replace(" ", "")); - string armorSecret = new GnuPG().GetSecretKey(key.Fingerprint.Replace(" ", "")); - string armorPublic = new GnuPG().GetPublicKey(key.Fingerprint.Replace(" ", "")); + generatingInstance.UploadKey (key.Fingerprint.Replace (" ", "")); + string armorSecret = new GnuPG().GetSecretKey (key.Fingerprint.Replace (" ", "")); + string armorPublic = new GnuPG().GetPublicKey (key.Fingerprint.Replace (" ", "")); // Console.Write(" deleting..."); key.Delete(); diff --git a/Logic/Security/SHA1.cs b/Logic/Security/SHA1.cs index 78126bc1..e6caaa8d 100644 --- a/Logic/Security/SHA1.cs +++ b/Logic/Security/SHA1.cs @@ -8,12 +8,12 @@ namespace Swarmops.Logic.Security /// public class SHA1 { - public static string Hash(string input) + public static string Hash (string input) { - byte[] data = Encoding.GetEncoding(1252).GetBytes(input); + byte[] data = Encoding.GetEncoding (1252).GetBytes (input); System.Security.Cryptography.SHA1 SHA1 = new SHA1CryptoServiceProvider(); - byte[] hash = SHA1.ComputeHash(data); + byte[] hash = SHA1.ComputeHash (data); // Write the resulting hash to a string of hex values. @@ -21,7 +21,7 @@ namespace Swarmops.Logic.Security foreach (byte oneByte in hash) { - result.Append(oneByte.ToString("X02") + " "); + result.Append (oneByte.ToString ("X02") + " "); } return result.ToString().TrimEnd(); diff --git a/Logic/Special/DummyBitcoin.cs b/Logic/Special/DummyBitcoin.cs index f52f2b7d..9de59796 100644 --- a/Logic/Special/DummyBitcoin.cs +++ b/Logic/Special/DummyBitcoin.cs @@ -10,7 +10,7 @@ namespace Swarmops.Logic.Special { public DummyBitcoin() { - Address = new BitcoinAddress("abcdefgh"); + Address = new BitcoinAddress ("abcdefgh"); } public static BitcoinAddress Address { get; set; } diff --git a/Logic/Special/Mail/MailServerDatabase.cs b/Logic/Special/Mail/MailServerDatabase.cs index 69715057..bb0eee03 100644 --- a/Logic/Special/Mail/MailServerDatabase.cs +++ b/Logic/Special/Mail/MailServerDatabase.cs @@ -16,17 +16,17 @@ namespace Swarmops.Logic.Special.Mail connectionString = Persistence.Key["MailServerDatabaseConnect"]; } - public static void AddAccount(string email, string initialPassword, int quotaMegabytes) + public static void AddAccount (string email, string initialPassword, int quotaMegabytes) { - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( MySqlCommand command = - new MySqlCommand( - "INSERT INTO users (email, password, quota) VALUES ('" + email.Replace("'", "''") + - "', ENCRYPT('" + initialPassword.Replace("'", "''") + "'), " + + new MySqlCommand ( + "INSERT INTO users (email, password, quota) VALUES ('" + email.Replace ("'", "''") + + "', ENCRYPT('" + initialPassword.Replace ("'", "''") + "'), " + (1048576*quotaMegabytes) + ");", connection)) { command.ExecuteNonQuery(); @@ -34,7 +34,7 @@ namespace Swarmops.Logic.Special.Mail } } - public static List SearchAccount(string email) + public static List SearchAccount (string email) { //temporary test @@ -47,54 +47,54 @@ namespace Swarmops.Logic.Special.Mail ON (users.email = forwardings.source)) LEFT OUTER JOIN forwardings forwardings_1 ON (forwardings_1.destination = users.email) - where email LIKE '" + email.Replace("'", "''") + "%'"; + where email LIKE '" + email.Replace ("'", "''") + "%'"; Dictionary foundAccounts = new Dictionary(); - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); - using (MySqlCommand command = new MySqlCommand(sql, connection)) + using (MySqlCommand command = new MySqlCommand (sql, connection)) { using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - if (!foundAccounts.ContainsKey(reader["email"].ToString().ToLower())) - foundAccounts.Add(reader["email"].ToString().ToLower(), new MailAccount()); + if (!foundAccounts.ContainsKey (reader["email"].ToString().ToLower())) + foundAccounts.Add (reader["email"].ToString().ToLower(), new MailAccount()); MailAccount curr = foundAccounts[reader["email"].ToString().ToLower()]; curr.account = reader["email"].ToString(); if (reader["destination"] != DBNull.Value - && !curr.forwardedTo.Contains(reader["destination"].ToString())) - curr.forwardedTo.Add(reader["destination"].ToString()); + && !curr.forwardedTo.Contains (reader["destination"].ToString())) + curr.forwardedTo.Add (reader["destination"].ToString()); if (reader["source"] != DBNull.Value - && !curr.forwardedFrom.Contains(reader["source"].ToString())) - curr.forwardedFrom.Add(reader["source"].ToString()); + && !curr.forwardedFrom.Contains (reader["source"].ToString())) + curr.forwardedFrom.Add (reader["source"].ToString()); } } } } - return new List(foundAccounts.Values); + return new List (foundAccounts.Values); } - public static string FindFreeAccount(string email) + public static string FindFreeAccount (string email) { email = email.Trim(); - if (email == null || email.IndexOf("@") < 2) + if (email == null || email.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("email too short"); + throw new ArgumentOutOfRangeException ("email too short"); } - email = email.Replace("'", "''"); + email = email.Replace ("'", "''"); // First, try to find the exact address (Because I'm suspicious about performance of regexp searches in mysql.../JL) - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( - MySqlCommand command = new MySqlCommand("select * from users where email = '" + email + "'", + MySqlCommand command = new MySqlCommand ("select * from users where email = '" + email + "'", connection)) { using (DbDataReader reader = command.ExecuteReader()) @@ -106,22 +106,22 @@ namespace Swarmops.Logic.Special.Mail } } } - string[] splitDom = email.Split(new[] {'@'}); + string[] splitDom = email.Split (new[] {'@'}); - string[] splitArr = splitDom[0].Split(new[] {'.'}); + string[] splitArr = splitDom[0].Split (new[] {'.'}); string firstPart = splitArr[0]; splitArr[0] = ""; - string secondPart = string.Join(".", splitArr, 1, splitArr.Length - 1); - string secondPartRegEx = secondPart.Replace(".", "[.period.]"); - string domainRegex = splitDom[1].Replace(".", "[.period.]"); + string secondPart = string.Join (".", splitArr, 1, splitArr.Length - 1); + string secondPartRegEx = secondPart.Replace (".", "[.period.]"); + string domainRegex = splitDom[1].Replace (".", "[.period.]"); // fetch all addresses that start the same as the one we are checking. using ( MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "select * from users where email RLIKE " + "'^" + firstPart + "([.period.][^[.period.]]+){0,1}[.period.]" + secondPartRegEx + "@" + domainRegex + "'", @@ -133,13 +133,13 @@ namespace Swarmops.Logic.Special.Mail { while (reader.Read()) { - foundAddresses.Add(((string) reader["email"]).Trim().ToLowerInvariant()); + foundAddresses.Add (((string) reader["email"]).Trim().ToLowerInvariant()); } } string suggestMail = email; char suggestChar = 'a'; char suggestChar2 = (char) ('a' - 1); - while (foundAddresses.Contains(suggestMail.Trim().ToLowerInvariant())) + while (foundAddresses.Contains (suggestMail.Trim().ToLowerInvariant())) { string suggestString = "" + suggestChar; if (suggestChar > 'z') @@ -160,40 +160,40 @@ namespace Swarmops.Logic.Special.Mail } - public static void SetNewPassword(string email, string newPassword) + public static void SetNewPassword (string email, string newPassword) { - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( MySqlCommand command = - new MySqlCommand( - "UPDATE users SET password=ENCRYPT('" + newPassword.Replace("'", "''") + - "') WHERE email='" + email.Replace("'", "''") + "';", connection)) + new MySqlCommand ( + "UPDATE users SET password=ENCRYPT('" + newPassword.Replace ("'", "''") + + "') WHERE email='" + email.Replace ("'", "''") + "';", connection)) { command.ExecuteNonQuery(); } } } - public static void StartForwarding(string fromEmail, string toEmail) + public static void StartForwarding (string fromEmail, string toEmail) { - fromEmail = fromEmail.Trim().Replace("'", "''"); - toEmail = toEmail.Trim().Replace("'", "''"); + fromEmail = fromEmail.Trim().Replace ("'", "''"); + toEmail = toEmail.Trim().Replace ("'", "''"); - if (fromEmail == null || fromEmail.IndexOf("@") < 2) + if (fromEmail == null || fromEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("fromEmail too short"); + throw new ArgumentOutOfRangeException ("fromEmail too short"); } - if (toEmail == null || toEmail.IndexOf("@") < 2) + if (toEmail == null || toEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("toEmail too short"); + throw new ArgumentOutOfRangeException ("toEmail too short"); } - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); @@ -202,13 +202,13 @@ namespace Swarmops.Logic.Special.Mail // this will be created, if no loop is found, // so test for it when finding loop - loopDict.Add(fromEmail, toEmail); + loopDict.Add (fromEmail, toEmail); string loopEmail = toEmail; - while (loopEmail != "" && !loopDict.ContainsKey(loopEmail)) + while (loopEmail != "" && !loopDict.ContainsKey (loopEmail)) { - using (MySqlCommand command = new MySqlCommand( + using (MySqlCommand command = new MySqlCommand ( "select * from forwardings where source = '" + loopEmail + "'", connection)) { using (DbDataReader reader = command.ExecuteReader()) @@ -216,7 +216,7 @@ namespace Swarmops.Logic.Special.Mail if (reader.Read()) { string tmpDest = ((string) reader["destination"]).Trim().ToLower(); - loopDict.Add(loopEmail, tmpDest); + loopDict.Add (loopEmail, tmpDest); loopEmail = tmpDest; } else @@ -239,11 +239,11 @@ namespace Swarmops.Logic.Special.Mail msg += " -> " + adr; } msg += " -> " + loopDict[lastadr]; - throw new InvalidOperationException(msg); + throw new InvalidOperationException (msg); } - using (MySqlCommand command = new MySqlCommand( + using (MySqlCommand command = new MySqlCommand ( "DELETE FROM forwardings WHERE source='" + fromEmail + "';" + "INSERT INTO forwardings (source, destination) VALUES ('" + fromEmail + "', '" + toEmail + "');", connection)) @@ -253,27 +253,27 @@ namespace Swarmops.Logic.Special.Mail } } - public static void StopSpecificForwarding(string fromEmail, string toEmail) + public static void StopSpecificForwarding (string fromEmail, string toEmail) { - fromEmail = fromEmail.Trim().Replace("'", "''"); - if (fromEmail == null || fromEmail.IndexOf("@") < 2) + fromEmail = fromEmail.Trim().Replace ("'", "''"); + if (fromEmail == null || fromEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("fromEmail too short"); + throw new ArgumentOutOfRangeException ("fromEmail too short"); } - toEmail = toEmail.Trim().Replace("'", "''"); - if (toEmail == null || toEmail.IndexOf("@") < 2) + toEmail = toEmail.Trim().Replace ("'", "''"); + if (toEmail == null || toEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("toEmail too short"); + throw new ArgumentOutOfRangeException ("toEmail too short"); } - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "DELETE FROM forwardings WHERE source='" + fromEmail + "' AND destination='" + toEmail + "';", connection)) { @@ -282,21 +282,21 @@ namespace Swarmops.Logic.Special.Mail } } - public static void StopForwarding(string fromEmail) + public static void StopForwarding (string fromEmail) { - fromEmail = fromEmail.Trim().Replace("'", "''"); - if (fromEmail == null || fromEmail.IndexOf("@") < 2) + fromEmail = fromEmail.Trim().Replace ("'", "''"); + if (fromEmail == null || fromEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("fromEmail too short"); + throw new ArgumentOutOfRangeException ("fromEmail too short"); } - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "DELETE FROM forwardings WHERE source='" + fromEmail + "';", connection)) { command.ExecuteNonQuery(); @@ -304,21 +304,21 @@ namespace Swarmops.Logic.Special.Mail } } - public static void DeleteAccount(string fromEmail) + public static void DeleteAccount (string fromEmail) { - fromEmail = fromEmail.Trim().Replace("'", "''"); - if (fromEmail == null || fromEmail.IndexOf("@") < 2) + fromEmail = fromEmail.Trim().Replace ("'", "''"); + if (fromEmail == null || fromEmail.IndexOf ("@") < 2) { - throw new ArgumentOutOfRangeException("Email too short"); + throw new ArgumentOutOfRangeException ("Email too short"); } - using (MySqlConnection connection = new MySqlConnection(connectionString)) + using (MySqlConnection connection = new MySqlConnection (connectionString)) { connection.Open(); using ( MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( // Shortcut past the account that is to be removed @"Update forwardings INNER JOIN diff --git a/Logic/Special/Sweden/SupportCase.cs b/Logic/Special/Sweden/SupportCase.cs index b573b839..a87f54f7 100644 --- a/Logic/Special/Sweden/SupportCase.cs +++ b/Logic/Special/Sweden/SupportCase.cs @@ -11,7 +11,7 @@ namespace Swarmops.Logic.Special.Sweden public readonly int SupportCaseId; public readonly string Title; - public SupportCase(int identity, string title) + public SupportCase (int identity, string title) { this.SupportCaseId = identity; this.Title = title; @@ -20,17 +20,17 @@ namespace Swarmops.Logic.Special.Sweden this.Email = string.Empty; } - public SupportCase(int identity, string title, string email) + public SupportCase (int identity, string title, string email) { this.SupportCaseId = identity; this.Title = title; this.Email = email; - int indexOfBracket = email.IndexOf('<'); + int indexOfBracket = email.IndexOf ('<'); if (indexOfBracket >= 0) { - this.Email = email.Substring(indexOfBracket + 1, email.IndexOf('>') - indexOfBracket - 1); + this.Email = email.Substring (indexOfBracket + 1, email.IndexOf ('>') - indexOfBracket - 1); } } @@ -39,9 +39,9 @@ namespace Swarmops.Logic.Special.Sweden get { return this.SupportCaseId; } } - public void CloseWithComment(string comment) + public void CloseWithComment (string comment) { - SupportDatabase.CloseWithComment(Identity, comment); + SupportDatabase.CloseWithComment (Identity, comment); } } } \ No newline at end of file diff --git a/Logic/Special/Sweden/SupportCaseDelta.cs b/Logic/Special/Sweden/SupportCaseDelta.cs index 0bc01613..83d7df68 100644 --- a/Logic/Special/Sweden/SupportCaseDelta.cs +++ b/Logic/Special/Sweden/SupportCaseDelta.cs @@ -5,7 +5,7 @@ namespace Swarmops.Logic.Special.Sweden { public class SupportCaseDelta : IHasIdentity { - public SupportCaseDelta(int supportCaseDeltaId, int supportCaseId, int supportPersonId, DateTime dateTime, + public SupportCaseDelta (int supportCaseDeltaId, int supportCaseId, int supportPersonId, DateTime dateTime, string verb, string changes) { SupportCaseDeltaId = supportCaseDeltaId; diff --git a/Logic/Special/Sweden/SupportDatabase.cs b/Logic/Special/Sweden/SupportDatabase.cs index a1e1a5fb..d5c07ad6 100644 --- a/Logic/Special/Sweden/SupportDatabase.cs +++ b/Logic/Special/Sweden/SupportDatabase.cs @@ -16,17 +16,17 @@ namespace Swarmops.Logic.Special.Sweden private static MySqlConnection GetConnection() { string connect = Persistence.Key["SupportDatabaseConnect"]; - return new MySqlConnection(connect); + return new MySqlConnection (connect); } private static SupportCase[] GetUndeliverableCases() { - return GetUndeliverableCases(0, 99999); + return GetUndeliverableCases (0, 99999); } - public static SupportCaseDelta[] GetCaseDeltas(int fromDeltaId) + public static SupportCaseDelta[] GetCaseDeltas (int fromDeltaId) { List result = new List(); @@ -35,7 +35,7 @@ namespace Swarmops.Logic.Special.Sweden connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT ixBugEvent,ixBug,ixPerson,dt,sVerb,sChanges FROM BugEvent WHERE ixBugEvent > " + fromDeltaId + " ORDER BY ixBugEvent", connection); @@ -45,9 +45,9 @@ namespace Swarmops.Logic.Special.Sweden { while (reader.Read()) { - if (!reader.IsDBNull(1)) // Safeguard -- some ixBug are NULL due to data corruption + if (!reader.IsDBNull (1)) // Safeguard -- some ixBug are NULL due to data corruption { - result.Add(ReadSupportCaseDeltaFromReader(reader)); + result.Add (ReadSupportCaseDeltaFromReader (reader)); } } } @@ -66,7 +66,7 @@ namespace Swarmops.Logic.Special.Sweden connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT ixBug,sTitle,sCustomerEmail FROM Bug WHERE fOpen=1", connection); using (MySqlDataReader reader = command.ExecuteReader()) @@ -75,11 +75,11 @@ namespace Swarmops.Logic.Special.Sweden { try { - result.Add(ReadFullSupportCaseFromReader(reader)); + result.Add (ReadFullSupportCaseFromReader (reader)); } catch (SqlNullValueException) { - Console.WriteLine("Exception on bug {0}", reader.GetInt32(0)); + Console.WriteLine ("Exception on bug {0}", reader.GetInt32 (0)); } } } @@ -89,30 +89,30 @@ namespace Swarmops.Logic.Special.Sweden } - public static SupportCase GetCase(int supportCaseId) + public static SupportCase GetCase (int supportCaseId) { using (MySqlConnection connection = GetConnection()) { connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT ixBug,sTitle,sCustomerEmail FROM Bug WHERE ixBug=" + supportCaseId, connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return ReadFullSupportCaseFromReader(reader); + return ReadFullSupportCaseFromReader (reader); } - throw new ArgumentException("No such Support Case Id: " + supportCaseId); + throw new ArgumentException ("No such Support Case Id: " + supportCaseId); } } } - private static SupportCase[] GetUndeliverableCases(int startBugId, int limit) + private static SupportCase[] GetUndeliverableCases (int startBugId, int limit) { List result = new List(); @@ -121,7 +121,7 @@ namespace Swarmops.Logic.Special.Sweden connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT ixBug,sTitle FROM Bug WHERE (sTitle LIKE 'Undeliver%' OR sTitle = 'failure notice' OR sTitle LIKE 'Mail delivery failed: returning message to sender' OR sTitle LIKE 'Delivery Status Notification%' OR sTitle LIKE 'Olevererbart:%' OR sTitle LIKE 'Returned mail:%') AND fOpen=1 and ixBug > " + startBugId + " order by ixBug LIMIT " + limit, connection); @@ -130,7 +130,7 @@ namespace Swarmops.Logic.Special.Sweden { while (reader.Read()) { - result.Add(ReadSupportCaseFromReader(reader)); + result.Add (ReadSupportCaseFromReader (reader)); } } } @@ -147,7 +147,7 @@ namespace Swarmops.Logic.Special.Sweden connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT ixBug,sTitle FROM Bug WHERE (sTitle = 'Delivery Status Notification (Delay)' OR sTitle LIKE 'Warning: could not send message for %' OR sTitle LIKE 'AUTO:%' OR sTitle LIKE 'Out of Office%') AND fOpen=1", connection); @@ -155,7 +155,7 @@ namespace Swarmops.Logic.Special.Sweden { while (reader.Read()) { - result.Add(ReadSupportCaseFromReader(reader)); + result.Add (ReadSupportCaseFromReader (reader)); } } } @@ -164,14 +164,14 @@ namespace Swarmops.Logic.Special.Sweden } - public static bool IsCaseOpen(int caseId) + public static bool IsCaseOpen (int caseId) { using (MySqlConnection connection = GetConnection()) { connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT fOpen FROM Bug WHERE ixBug=" + caseId, connection); @@ -179,7 +179,7 @@ namespace Swarmops.Logic.Special.Sweden { if (reader.Read()) { - if (reader.GetInt32(0) == 1) + if (reader.GetInt32 (0) == 1) { return true; } @@ -191,14 +191,14 @@ namespace Swarmops.Logic.Special.Sweden } - public static DateTime? GetCaseCloseDateTime(int caseId) + public static DateTime? GetCaseCloseDateTime (int caseId) { using (MySqlConnection connection = GetConnection()) { connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT dtClosed FROM Bug WHERE ixBug=" + caseId, connection); @@ -206,9 +206,9 @@ namespace Swarmops.Logic.Special.Sweden { if (reader.Read()) { - if (!reader.IsDBNull(0)) + if (!reader.IsDBNull (0)) { - return reader.GetDateTime(0); + return reader.GetDateTime (0); } } @@ -224,12 +224,12 @@ namespace Swarmops.Logic.Special.Sweden foreach (SupportCase @case in cases) { - CloseWithComment(@case.Identity, "No action taken on delay warnings. Case closed."); + CloseWithComment (@case.Identity, "No action taken on delay warnings. Case closed."); } } - public static SupportEmail[] GetRecentOutgoingEmails(int sinceEventId) + public static SupportEmail[] GetRecentOutgoingEmails (int sinceEventId) { List result = new List(); @@ -238,7 +238,7 @@ namespace Swarmops.Logic.Special.Sweden connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT BugEvent.ixBugEvent AS BugEventId,BugEvent.ixBug AS BugId, Bug.sTitle as BugTitle, Bug.sCustomerEmail AS Recipient, BugEvent.s AS Body,Person.sFullName AS Sender FROM BugEvent,Bug,Person WHERE BugEvent.sVerb='Replied' AND BugEvent.fEmail=1 AND Person.ixPerson=BugEvent.ixPerson AND Bug.ixBug = BugEvent.ixBug AND BugEvent.ixBugEvent > " + sinceEventId, connection); @@ -246,7 +246,7 @@ namespace Swarmops.Logic.Special.Sweden { while (reader.Read()) { - result.Add(ReadSupportEmailFromReader(reader)); + result.Add (ReadSupportEmailFromReader (reader)); } } } @@ -255,14 +255,14 @@ namespace Swarmops.Logic.Special.Sweden } - public static string GetFirstEventText(int bugId) + public static string GetFirstEventText (int bugId) { using (MySqlConnection connection = GetConnection()) { connection.Open(); MySqlCommand command = - new MySqlCommand( + new MySqlCommand ( "SELECT s FROM BugEvent WHERE ixBug = " + bugId + " ORDER BY ixBugEvent LIMIT 1", connection); @@ -279,77 +279,77 @@ namespace Swarmops.Logic.Special.Sweden } - private static SupportEmail ReadSupportEmailFromReader(MySqlDataReader reader) + private static SupportEmail ReadSupportEmailFromReader (MySqlDataReader reader) { SupportEmail email = new SupportEmail(); // BugEvent.ixBugEvent AS BugEventId,BugEvent.ixBug AS BugId, Bug.sTitle as BugTitle, Bug.sCustomerEmail AS Recipient, BugEvent.s AS Body,Person.sFullName AS Sender - email.CaseId = reader.GetInt32(1); - email.Body = Encoding.UTF8.GetString(Encoding.GetEncoding(1252).GetBytes(reader.GetString(4))); - email.EventId = reader.GetInt32(0); - email.From = reader.GetString(5); - email.To = reader.GetString(3); - email.CaseTitle = reader.GetString(2); + email.CaseId = reader.GetInt32 (1); + email.Body = Encoding.UTF8.GetString (Encoding.GetEncoding (1252).GetBytes (reader.GetString (4))); + email.EventId = reader.GetInt32 (0); + email.From = reader.GetString (5); + email.To = reader.GetString (3); + email.CaseTitle = reader.GetString (2); return email; } - private static SupportCase ReadFullSupportCaseFromReader(MySqlDataReader reader) + private static SupportCase ReadFullSupportCaseFromReader (MySqlDataReader reader) { // ixBug,sTitle,sCustomerEmail - int identity = reader.GetInt32(0); - string title = reader.GetString(1); + int identity = reader.GetInt32 (0); + string title = reader.GetString (1); string email = string.Empty; - if (!reader.IsDBNull(2)) + if (!reader.IsDBNull (2)) { - email = reader.GetString(2); + email = reader.GetString (2); } - return new SupportCase(identity, title, email); + return new SupportCase (identity, title, email); } - private static SupportCase ReadSupportCaseFromReader(MySqlDataReader reader) + private static SupportCase ReadSupportCaseFromReader (MySqlDataReader reader) { // ixBug,sTitle - int identity = reader.GetInt32(0); - string title = reader.GetString(1); + int identity = reader.GetInt32 (0); + string title = reader.GetString (1); - return new SupportCase(identity, title); + return new SupportCase (identity, title); } - private static SupportCaseDelta ReadSupportCaseDeltaFromReader(MySqlDataReader reader) + private static SupportCaseDelta ReadSupportCaseDeltaFromReader (MySqlDataReader reader) { // ixBug,sTitle - int deltaId = reader.GetInt32(0); - int caseId = reader.GetInt32(1); - int personId = reader.GetInt32(2); - DateTime dateTime = reader.GetDateTime(3); - string verb = reader.GetString(4); - string changes = reader.GetString(5); + int deltaId = reader.GetInt32 (0); + int caseId = reader.GetInt32 (1); + int personId = reader.GetInt32 (2); + DateTime dateTime = reader.GetDateTime (3); + string verb = reader.GetString (4); + string changes = reader.GetString (5); - return new SupportCaseDelta(deltaId, caseId, personId, dateTime, verb, changes); + return new SupportCaseDelta (deltaId, caseId, personId, dateTime, verb, changes); } - internal static void CloseWithComment(int bugId, string comment) + internal static void CloseWithComment (int bugId, string comment) { using (MySqlConnection connection = GetConnection()) { connection.Open(); - MySqlCommand command = new MySqlCommand("CloseWithComment", connection); - command.Parameters.AddWithValue("bugId", bugId); - command.Parameters.AddWithValue("comment", comment); - command.Parameters.AddWithValue("dateTime", DateTime.Now); + MySqlCommand command = new MySqlCommand ("CloseWithComment", connection); + command.Parameters.AddWithValue ("bugId", bugId); + command.Parameters.AddWithValue ("comment", comment); + command.Parameters.AddWithValue ("dateTime", DateTime.Now); command.CommandType = CommandType.StoredProcedure; @@ -360,12 +360,12 @@ namespace Swarmops.Logic.Special.Sweden public static void NotifyBouncingEmails() { - Regex regex = new Regex(@"(?[a-z_0-9\.\+\-]+\@[a-z_0-9\.\-]+)", + Regex regex = new Regex (@"(?[a-z_0-9\.\+\-]+\@[a-z_0-9\.\-]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); string SMSBouncingEmail = ("" + Persistence.Key["SMSBouncingEmail"]).ToUpper().Trim(); - Regex reIsNo = new Regex(@"(NO)|(N)|(NEJ)", RegexOptions.IgnoreCase); - Boolean dontSendSMS = reIsNo.IsMatch(SMSBouncingEmail); + Regex reIsNo = new Regex (@"(NO)|(N)|(NEJ)", RegexOptions.IgnoreCase); + Boolean dontSendSMS = reIsNo.IsMatch (SMSBouncingEmail); Boolean holdSMS = SMSBouncingEmail == "HOLD"; int lastCaseHandled = 0; @@ -375,7 +375,7 @@ namespace Swarmops.Logic.Special.Sweden SupportCase[] cases = null; while (lastCaseHandled == 0 || (cases != null && cases.Length > 0)) { - cases = GetUndeliverableCases(lastCaseHandled, 100); + cases = GetUndeliverableCases (lastCaseHandled, 100); if (cases.Length == 0) // very very important bugfix { @@ -387,14 +387,14 @@ namespace Swarmops.Logic.Special.Sweden lastCaseHandled = @case.Identity; bool attemptRecovery = true; - if (@case.Title.ToLower().Contains("ditt medlemskap har")) + if (@case.Title.ToLower().Contains ("ditt medlemskap har")) { // "Ditt medlemskap har gått ut" attemptRecovery = false; } - if (@case.Title.ToLower().Contains("press")) + if (@case.Title.ToLower().Contains ("press")) { // Press release @@ -403,30 +403,30 @@ namespace Swarmops.Logic.Special.Sweden if (attemptRecovery) { - string body = GetFirstEventText(@case.Identity); + string body = GetFirstEventText (@case.Identity); // Strip the mail header - int bodySeparator = body.IndexOf("\r\n\r\n"); + int bodySeparator = body.IndexOf ("\r\n\r\n"); if (bodySeparator > 0) { - body = body.Substring(bodySeparator + 4); + body = body.Substring (bodySeparator + 4); } else { body = string.Empty; } - Match match = regex.Match(body); + Match match = regex.Match (body); if (match.Success) { string email = match.Groups["email"].Value; - People people = People.FromEmail(email); + People people = People.FromEmail (email); if (people.Count > 2) { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "Bounced message closed. More than one person matches the email address. Both marked unreachable."); foreach (Person person in people) @@ -437,7 +437,7 @@ namespace Swarmops.Logic.Special.Sweden else if (people.Count < 1) { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "Bounced message closed. No person in the database matches the email address."); } @@ -468,7 +468,7 @@ namespace Swarmops.Logic.Special.Sweden { if (dontSendSMS) { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "The person at phone# " + person.Phone + ", " + person.Name + " (#" + person.Identity + "), was not contacted due to that SMS notification is currently turned off. Bounced message closed."); @@ -477,18 +477,18 @@ namespace Swarmops.Logic.Special.Sweden { try { - person.SendPhoneMessage( + person.SendPhoneMessage ( "Piratpartiet: den mailadress vi har till dig (" + person.Mail + ") studsar. Kontakta medlemsservice@piratpartiet.se med ny adress."); - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "Successfully notified the member at phone# " + person.Phone + ", " + person.Name + " (#" + person.Identity + "), about the bounced email using an SMS message. Case closed."); } catch (Exception) { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "The person at phone# " + person.Phone + ", " + person.Name + " (#" + person.Identity + "), could not be reached over SMS. This member has been marked unreachable. Bounced message closed."); @@ -498,7 +498,7 @@ namespace Swarmops.Logic.Special.Sweden } else { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, person.Name + " (#" + person.Identity + ") does not have a listed phone number. This member has been marked unreachable. Bounced message closed."); person.MailUnreachable = true; @@ -507,7 +507,7 @@ namespace Swarmops.Logic.Special.Sweden } else { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "The person at phone# " + person.Phone + ", " + person.Name + " (#" + person.Identity + ") has no active memberships. Bounced message closed."); @@ -516,13 +516,13 @@ namespace Swarmops.Logic.Special.Sweden } else { - CloseWithComment(@case.Identity, + CloseWithComment (@case.Identity, "Bounced message closed. No email address could be located."); } } else { - CloseWithComment(@case.Identity, "Bounced message closed without attempt of recovery."); + CloseWithComment (@case.Identity, "Bounced message closed without attempt of recovery."); } } } diff --git a/Logic/Special/Sweden/SwedishForumDatabase.cs b/Logic/Special/Sweden/SwedishForumDatabase.cs index 8c5b3a63..5c8f6cf7 100644 --- a/Logic/Special/Sweden/SwedishForumDatabase.cs +++ b/Logic/Special/Sweden/SwedishForumDatabase.cs @@ -20,27 +20,27 @@ namespace Swarmops.Logic.Special.Sweden public interface IForumDatabase { bool TestMode { get; set; } - int CreateNewPost(int forumId, Person poster, string title, string description, string post); - int GetAccountId(string nick); + int CreateNewPost (int forumId, Person poster, string title, string description, string post); + int GetAccountId (string nick); int[] GetAccountList(); - string GetAccountName(int accountId); - int GetPollIdFromTopicId(int topicId); - Dictionary GetPollVotes(int pollId); - bool IsPartyMember(int accountId); - void SetPartyMember(int accountId); - void SetPartyNonmember(int accountId); + string GetAccountName (int accountId); + int GetPollIdFromTopicId (int topicId); + Dictionary GetPollVotes (int pollId); + bool IsPartyMember (int accountId); + void SetPartyMember (int accountId); + void SetPartyNonmember (int accountId); } public class SwedishForumDatabase { - public static IForumDatabase GetDatabase(int type, string connectionstring) + public static IForumDatabase GetDatabase (int type, string connectionstring) { if (type == 1) - return SwedishForumDatabaseInstantForum.GetDatabase(connectionstring); - return SwedishForumDatabaseVBulletin.GetDatabase(connectionstring); + return SwedishForumDatabaseInstantForum.GetDatabase (connectionstring); + return SwedishForumDatabaseVBulletin.GetDatabase (connectionstring); } - public static IForumDatabase GetDatabase(int type) + public static IForumDatabase GetDatabase (int type) { if (type == 1) return SwedishForumDatabaseInstantForum.GetDatabase(); @@ -51,13 +51,13 @@ namespace Swarmops.Logic.Special.Sweden { if (Path.DirectorySeparatorChar == '/') { - if (string.IsNullOrEmpty(Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Bot"])) - return GetDatabase(1); - return GetDatabase(2); + if (string.IsNullOrEmpty (Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Bot"])) + return GetDatabase (1); + return GetDatabase (2); } - if (string.IsNullOrEmpty(Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Web"])) - return GetDatabase(1); - return GetDatabase(2); + if (string.IsNullOrEmpty (Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Web"])) + return GetDatabase (1); + return GetDatabase (2); } } @@ -89,55 +89,55 @@ namespace Swarmops.Logic.Special.Sweden #endregion - public SwedishForumDatabaseInstantForum(string connectString) + public SwedishForumDatabaseInstantForum (string connectString) { this.connectString = connectString; } - public int GetAccountId(string nick) + public int GetAccountId (string nick) { if (nick == null) { - throw new ArgumentNullException("nick"); + throw new ArgumentNullException ("nick"); } - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand( - String.Format("Select UserId from InstantASP_Users Where Username='{0}'", - nick.Replace("'", "''")), connection); + new SqlCommand ( + String.Format ("Select UserId from InstantASP_Users Where Username='{0}'", + nick.Replace ("'", "''")), connection); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } - throw new ArgumentException("No such nick in database"); + throw new ArgumentException ("No such nick in database"); } } } - public string GetAccountName(int accountId) + public string GetAccountName (int accountId) { - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand(String.Format("Select Username from InstantASP_Users Where UserId=" + accountId), + new SqlCommand (String.Format ("Select Username from InstantASP_Users Where UserId=" + accountId), connection); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetString(0); + return reader.GetString (0); } - throw new ArgumentException("No such nick in database"); + throw new ArgumentException ("No such nick in database"); } } } @@ -146,17 +146,17 @@ namespace Swarmops.Logic.Special.Sweden { List result = new List(); - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); - SqlCommand command = new SqlCommand(String.Format("Select UserId from InstantASP_Users"), connection); + SqlCommand command = new SqlCommand (String.Format ("Select UserId from InstantASP_Users"), connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -178,22 +178,22 @@ namespace Swarmops.Logic.Special.Sweden #region Party Membership - public bool IsPartyMember(int accountId) + public bool IsPartyMember (int accountId) { - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand( - String.Format("Select PrimaryRoleID from InstantASP_Users where UserID=" + accountId), + new SqlCommand ( + String.Format ("Select PrimaryRoleID from InstantASP_Users where UserID=" + accountId), connection); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - int roleId = reader.GetInt16(0); + int roleId = reader.GetInt16 (0); if (roleId == 7) { return true; @@ -201,37 +201,37 @@ namespace Swarmops.Logic.Special.Sweden return false; } - throw new Exception("Account Id does not exist"); + throw new Exception ("Account Id does not exist"); } } } - public void SetPartyMember(int accountId) + public void SetPartyMember (int accountId) { - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); - SqlCommand command = new SqlCommand("PirateSetMember", connection); + SqlCommand command = new SqlCommand ("PirateSetMember", connection); command.CommandType = CommandType.StoredProcedure; - command.Parameters.AddWithValue("@accountId", accountId); + command.Parameters.AddWithValue ("@accountId", accountId); command.ExecuteNonQuery(); } } - public void SetPartyNonmember(int accountId) + public void SetPartyNonmember (int accountId) { - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); - SqlCommand command = new SqlCommand("PirateSetNonmember", connection); + SqlCommand command = new SqlCommand ("PirateSetNonmember", connection); command.CommandType = CommandType.StoredProcedure; - command.Parameters.AddWithValue("@accountId", accountId); + command.Parameters.AddWithValue ("@accountId", accountId); command.ExecuteNonQuery(); } } @@ -240,21 +240,21 @@ namespace Swarmops.Logic.Special.Sweden #region Polls - public int GetPollIdFromTopicId(int topicId) + public int GetPollIdFromTopicId (int topicId) { - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand(String.Format("Select PollID from InstantForum_Polls where PostID=" + topicId), + new SqlCommand (String.Format ("Select PollID from InstantForum_Polls where PostID=" + topicId), connection); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } throw new ArgumentOutOfRangeException(); @@ -263,11 +263,11 @@ namespace Swarmops.Logic.Special.Sweden } - public Dictionary GetPollVotes(int pollId) + public Dictionary GetPollVotes (int pollId) { // First, let's get the list of alternatives. - Dictionary pollAlternatives = GetPollAlternatives(pollId); + Dictionary pollAlternatives = GetPollAlternatives (pollId); // Construct a comma-separated list of the answer IDs. @@ -275,20 +275,20 @@ namespace Swarmops.Logic.Special.Sweden foreach (int pollAlternativeId in pollAlternatives.Keys) { - altStringBuilder.Append("," + pollAlternativeId); + altStringBuilder.Append ("," + pollAlternativeId); } - string altString = altStringBuilder.ToString().Substring(1); + string altString = altStringBuilder.ToString().Substring (1); Dictionary result = new Dictionary(); - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand( - String.Format( + new SqlCommand ( + String.Format ( "Select PollAnswerID,UserID from InstantForum_PollVotes WHERE PollAnswerId IN (" + altString + ")"), connection); @@ -299,9 +299,9 @@ namespace Swarmops.Logic.Special.Sweden while (reader.Read()) { voteCount++; - int forumUserId = reader.GetInt32(1); + int forumUserId = reader.GetInt32 (1); - People people = People.FromOptionalData(ObjectOptionalDataType.ForumAccountId, + People people = People.FromOptionalData (ObjectOptionalDataType.ForumAccountId, forumUserId.ToString()); if (people.Count > 1) { @@ -310,14 +310,14 @@ namespace Swarmops.Logic.Special.Sweden { if (testPerson.GetMemberships().Count == 0) { - people.Remove(testPerson); + people.Remove (testPerson); } } if (people.Count > 1) { - throw new Exception("This is not possible -- check userid " + forumUserId + - ", appears to be tied to several personIds"); + throw new Exception ("This is not possible -- check userid " + forumUserId + + ", appears to be tied to several personIds"); } } @@ -328,15 +328,15 @@ namespace Swarmops.Logic.Special.Sweden person = people[0]; } - int pollAnswerId = reader.GetInt32(0); + int pollAnswerId = reader.GetInt32 (0); string pollAnswer = pollAlternatives[pollAnswerId]; - if (!result.ContainsKey(pollAnswer)) + if (!result.ContainsKey (pollAnswer)) { result[pollAnswer] = new People(); } - result[pollAnswer].Add(person); + result[pollAnswer].Add (person); } return result; @@ -345,24 +345,24 @@ namespace Swarmops.Logic.Special.Sweden } - private Dictionary GetPollAlternatives(int pollId) + private Dictionary GetPollAlternatives (int pollId) { Dictionary result = new Dictionary(); - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); SqlCommand command = - new SqlCommand( - String.Format("Select PollAnswerID,AnswerText from InstantForum_PollAnswers WHERE PollId=" + - pollId), connection); + new SqlCommand ( + String.Format ("Select PollAnswerID,AnswerText from InstantForum_PollAnswers WHERE PollId=" + + pollId), connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetString(1); + result[reader.GetInt32 (0)] = reader.GetString (1); } return result; @@ -374,40 +374,40 @@ namespace Swarmops.Logic.Special.Sweden #region Create Post - public int CreateNewPost(int forumId, Person poster, string title, string description, string post) + public int CreateNewPost (int forumId, Person poster, string title, string description, string post) { // Returns the new post id if (this.forceForumId != 0) forumId = this.forceForumId; - using (SqlConnection connection = new SqlConnection(this.connectString)) + using (SqlConnection connection = new SqlConnection (this.connectString)) { connection.Open(); // First, insert the post itself - SqlCommand command = new SqlCommand("if_sp_InsertPost", connection); + SqlCommand command = new SqlCommand ("if_sp_InsertPost", connection); command.CommandType = CommandType.StoredProcedure; - command.Parameters.AddWithValue("@intForumID", forumId); - command.Parameters.AddWithValue("@intTopicID", 0); - command.Parameters.AddWithValue("@intParentID", 0); - command.Parameters.AddWithValue("@intUserID", poster.SwedishForumAccountId); - command.Parameters.AddWithValue("@strMessageIcon", string.Empty); - command.Parameters.AddWithValue("@strTitle", title); - command.Parameters.AddWithValue("@strDescription", description); - command.Parameters.AddWithValue("@bitForumModerated", false); - command.Parameters.AddWithValue("@bitIsPoll", false); - command.Parameters.AddWithValue("@strIPAddress", "127.0.0.1"); + command.Parameters.AddWithValue ("@intForumID", forumId); + command.Parameters.AddWithValue ("@intTopicID", 0); + command.Parameters.AddWithValue ("@intParentID", 0); + command.Parameters.AddWithValue ("@intUserID", poster.SwedishForumAccountId); + command.Parameters.AddWithValue ("@strMessageIcon", string.Empty); + command.Parameters.AddWithValue ("@strTitle", title); + command.Parameters.AddWithValue ("@strDescription", description); + command.Parameters.AddWithValue ("@bitForumModerated", false); + command.Parameters.AddWithValue ("@bitIsPoll", false); + command.Parameters.AddWithValue ("@strIPAddress", "127.0.0.1"); - SqlParameter parameterText = new SqlParameter("@strMessage", SqlDbType.NText, post.Length*2 + 2048); + SqlParameter parameterText = new SqlParameter ("@strMessage", SqlDbType.NText, post.Length*2 + 2048); parameterText.Value = post; - command.Parameters.Add(parameterText); + command.Parameters.Add (parameterText); - SqlParameter parameterResult = new SqlParameter("@intIdentity", SqlDbType.Int, 4); + SqlParameter parameterResult = new SqlParameter ("@intIdentity", SqlDbType.Int, 4); parameterResult.Direction = ParameterDirection.Output; - command.Parameters.Add(parameterResult); + command.Parameters.Add (parameterResult); command.ExecuteNonQuery(); @@ -415,15 +415,15 @@ namespace Swarmops.Logic.Special.Sweden // Then, update the LastRead for this forum - command = new SqlCommand("if_sp_UpdateForumLastPostInformation", connection); + command = new SqlCommand ("if_sp_UpdateForumLastPostInformation", connection); command.CommandType = CommandType.StoredProcedure; - command.Parameters.Add(new SqlParameter("@intForumID", forumId)); - command.Parameters.Add(new SqlParameter("@intLastPosterPostID", postId)); - command.Parameters.Add(new SqlParameter("@intLastPosterUserID", poster.SwedishForumAccountId)); - command.Parameters.Add(new SqlParameter("@strLastPosterUsername", poster.Name)); - command.Parameters.Add(new SqlParameter("@strLastPosterSubject", title)); - command.Parameters.Add(new SqlParameter("@dtLastPosterDate", DateTime.Now)); + command.Parameters.Add (new SqlParameter ("@intForumID", forumId)); + command.Parameters.Add (new SqlParameter ("@intLastPosterPostID", postId)); + command.Parameters.Add (new SqlParameter ("@intLastPosterUserID", poster.SwedishForumAccountId)); + command.Parameters.Add (new SqlParameter ("@strLastPosterUsername", poster.Name)); + command.Parameters.Add (new SqlParameter ("@strLastPosterSubject", title)); + command.Parameters.Add (new SqlParameter ("@dtLastPosterDate", DateTime.Now)); command.ExecuteNonQuery(); @@ -433,9 +433,9 @@ namespace Swarmops.Logic.Special.Sweden #endregion - public static IForumDatabase GetDatabase(string connectionstring) + public static IForumDatabase GetDatabase (string connectionstring) { - return new SwedishForumDatabaseInstantForum(CachedConnectionString); + return new SwedishForumDatabaseInstantForum (CachedConnectionString); } public static IForumDatabase GetDatabase() @@ -450,7 +450,7 @@ namespace Swarmops.Logic.Special.Sweden ConnectionString = ConfigurationManager.ConnectionStrings["PirateWeb"].ConnectionString; ProviderName = ConfigurationManager.ConnectionStrings["PirateWeb"].ProviderName; - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized from Config ConnectionString: [" + ConnectionString + "] / [" + ProviderName + "]"); } @@ -464,12 +464,12 @@ namespace Swarmops.Logic.Special.Sweden { // We are running under mono - using (StreamReader reader = new StreamReader(MonoConfigFile)) + using (StreamReader reader = new StreamReader (MonoConfigFile)) { ConnectionString = reader.ReadLine(); ProviderName = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for Linux: [" + ConnectionString + "] / [" + ProviderName + "]"); } @@ -477,13 +477,14 @@ namespace Swarmops.Logic.Special.Sweden else if (HttpContext.Current != null) { // We are running a web application - using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(WebConfigFile)) + using ( + StreamReader reader = new StreamReader (HttpContext.Current.Server.MapPath (WebConfigFile)) ) { ConnectionString = reader.ReadLine(); ProviderName = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for web: [" + ConnectionString + "] / [" + ProviderName + "]"); } @@ -492,12 +493,12 @@ namespace Swarmops.Logic.Special.Sweden { // We are running an application, presumably directly from Visual Studio. // If so, the current working directory is "PirateWeb/30/Console/bin". - using (StreamReader reader = new StreamReader(AppConfigFile)) + using (StreamReader reader = new StreamReader (AppConfigFile)) { ConnectionString = reader.ReadLine(); ProviderName = reader.ReadLine(); - Logging.LogInformation(LogSource.PirateDb, + Logging.LogInformation (LogSource.PirateDb, "SwarmDb initialized for application: [" + ConnectionString + "] / [" + ProviderName + "]"); } @@ -505,7 +506,7 @@ namespace Swarmops.Logic.Special.Sweden } catch (Exception) { - Logging.LogWarning(LogSource.PirateDb, "Unable to read Database.Config - defaulting"); + Logging.LogWarning (LogSource.PirateDb, "Unable to read Database.Config - defaulting"); // Ignore if we can't read the Database.config } @@ -529,13 +530,13 @@ namespace Swarmops.Logic.Special.Sweden string DataSource = DefaultAppDataSource; if (HttpContext.Current != null) { - DataSource = HttpContext.Current.Server.MapPath(DefaultWebDataSource); + DataSource = HttpContext.Current.Server.MapPath (DefaultWebDataSource); } - ConnectionString = DefaultConnectionString.Replace("%DataSource%", DataSource); + ConnectionString = DefaultConnectionString.Replace ("%DataSource%", DataSource); ProviderName = DefaultProviderName; } - ConnectionString = ConnectionString.Replace("database=pirateweb", "database=pirateforums"); + ConnectionString = ConnectionString.Replace ("database=pirateweb", "database=pirateforums"); // Now write the correct data to the cache, for faster lookup next time. if (CachedConnectionString == null) @@ -544,13 +545,13 @@ namespace Swarmops.Logic.Special.Sweden CachedProviderName = ProviderName; } - return new SwedishForumDatabaseInstantForum(CachedConnectionString); + return new SwedishForumDatabaseInstantForum (CachedConnectionString); } } public class ErrorIgnorerPolicy : ICertificatePolicy { - public bool CheckValidationResult(ServicePoint sp, X509Certificate certificate, WebRequest request, int error) + public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error) { if (error == 0) return true; @@ -573,57 +574,57 @@ namespace Swarmops.Logic.Special.Sweden private readonly string connectString = string.Empty; private int forceForumId; - public SwedishForumDatabaseVBulletin(string connectString) + public SwedishForumDatabaseVBulletin (string connectString) { this.connectString = connectString; } - public int GetAccountId(string nick) + public int GetAccountId (string nick) { if (nick == null) { - throw new ArgumentNullException("nick"); + throw new ArgumentNullException ("nick"); } - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); MySqlCommand command = - new MySqlCommand( - String.Format("Select userid from vb_user Where username='{0}'", - nick.Replace("'", "''")), connection); + new MySqlCommand ( + String.Format ("Select userid from vb_user Where username='{0}'", + nick.Replace ("'", "''")), connection); command.CommandTimeout = 20; using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } - throw new ArgumentException("No such nick in database"); + throw new ArgumentException ("No such nick in database"); } } } - public string GetAccountName(int accountId) + public string GetAccountName (int accountId) { - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); MySqlCommand command = - new MySqlCommand(String.Format("Select username from vb_user Where userid=" + accountId), + new MySqlCommand (String.Format ("Select username from vb_user Where userid=" + accountId), connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetString(0); + return reader.GetString (0); } - throw new ArgumentException("No such nick in database"); + throw new ArgumentException ("No such nick in database"); } } } @@ -632,17 +633,17 @@ namespace Swarmops.Logic.Special.Sweden { List result = new List(); - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); - MySqlCommand command = new MySqlCommand(String.Format("Select userid from vb_user"), connection); + MySqlCommand command = new MySqlCommand (String.Format ("Select userid from vb_user"), connection); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(reader.GetInt32(0)); + result.Add (reader.GetInt32 (0)); } return result.ToArray(); @@ -664,15 +665,15 @@ namespace Swarmops.Logic.Special.Sweden #region Party Membership - public bool IsPartyMember(int accountId) + public bool IsPartyMember (int accountId) { - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); MySqlCommand command = - new MySqlCommand( - String.Format("Select membergroupids from vb_user where userid=" + accountId), + new MySqlCommand ( + String.Format ("Select membergroupids from vb_user where userid=" + accountId), connection); using (MySqlDataReader reader = command.ExecuteReader()) @@ -681,27 +682,27 @@ namespace Swarmops.Logic.Special.Sweden { string allGroups = ","; - if (!reader.IsDBNull(0)) - allGroups += "" + reader.GetString(0) + ","; + if (!reader.IsDBNull (0)) + allGroups += "" + reader.GetString (0) + ","; - allGroups = allGroups.Replace(" ", ""); + allGroups = allGroups.Replace (" ", ""); - if (allGroups.Contains("," + partymembergroupid + ",")) + if (allGroups.Contains ("," + partymembergroupid + ",")) { return true; } return false; } - throw new Exception("Account Id does not exist"); + throw new Exception ("Account Id does not exist"); } } } - public void SetPartyMember(int accountId) + public void SetPartyMember (int accountId) { - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); //TODO: Convert back to stored procedure @@ -713,29 +714,29 @@ namespace Swarmops.Logic.Special.Sweden string allGroups = ","; - MySqlCommand command = new MySqlCommand( - String.Format("Select membergroupids from vb_user where userid=" + accountId), + MySqlCommand command = new MySqlCommand ( + String.Format ("Select membergroupids from vb_user where userid=" + accountId), connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - if (!reader.IsDBNull(0)) - allGroups += "" + reader.GetString(0) + ","; + if (!reader.IsDBNull (0)) + allGroups += "" + reader.GetString (0) + ","; } } - if (!allGroups.Contains("," + partymembergroupid + ",")) + if (!allGroups.Contains ("," + partymembergroupid + ",")) { allGroups = (allGroups - .Replace(" ", "") - .Replace(",,", ",") - .Trim(',') + "," + partymembergroupid).Trim(','); + .Replace (" ", "") + .Replace (",,", ",") + .Trim (',') + "," + partymembergroupid).Trim (','); command = - new MySqlCommand( - String.Format( + new MySqlCommand ( + String.Format ( "Update vb_user set membergroupids='{0}', displaygroupid={1} where userid={2}", allGroups, partymembergroupid, accountId), connection); @@ -746,9 +747,9 @@ namespace Swarmops.Logic.Special.Sweden } - public void SetPartyNonmember(int accountId) + public void SetPartyNonmember (int accountId) { - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); @@ -761,29 +762,30 @@ namespace Swarmops.Logic.Special.Sweden string allGroups = ","; - MySqlCommand command = new MySqlCommand( - String.Format("Select membergroupids from vb_user where userid=" + accountId), + MySqlCommand command = new MySqlCommand ( + String.Format ("Select membergroupids from vb_user where userid=" + accountId), connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - if (!reader.IsDBNull(0)) - allGroups += "" + reader.GetString(0) + ","; + if (!reader.IsDBNull (0)) + allGroups += "" + reader.GetString (0) + ","; } } - if (allGroups.Contains("," + partymembergroupid + ",")) + if (allGroups.Contains ("," + partymembergroupid + ",")) { allGroups = allGroups - .Replace(" ", "") - .Replace("," + partymembergroupid + ",", ",") - .Replace(",,", ",").Trim(','); + .Replace (" ", "") + .Replace ("," + partymembergroupid + ",", ",") + .Replace (",,", ",").Trim (','); command = - new MySqlCommand( - String.Format("Update vb_user set membergroupids='{0}',displaygroupid={1} where userid={2}", + new MySqlCommand ( + String.Format ( + "Update vb_user set membergroupids='{0}',displaygroupid={1} where userid={2}", allGroups, nonmembergroupid, accountId ), connection); @@ -797,21 +799,21 @@ namespace Swarmops.Logic.Special.Sweden #region Get Polls - public int GetPollIdFromTopicId(int threadId) + public int GetPollIdFromTopicId (int threadId) { - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); - MySqlCommand command = new MySqlCommand( - String.Format("Select pollid from vb_thread where threadid=" + threadId), + MySqlCommand command = new MySqlCommand ( + String.Format ("Select pollid from vb_thread where threadid=" + threadId), connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetInt32(0); + return reader.GetInt32 (0); } throw new ArgumentOutOfRangeException(); @@ -820,19 +822,19 @@ namespace Swarmops.Logic.Special.Sweden } - public Dictionary GetPollVotes(int pollId) + public Dictionary GetPollVotes (int pollId) { //// First, let's get the list of alternatives. - Dictionary pollAlternatives = GetPollAlternatives(pollId); + Dictionary pollAlternatives = GetPollAlternatives (pollId); Dictionary result = new Dictionary(); - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); - MySqlCommand command = new MySqlCommand( - String.Format("Select userid, voteoption from pw_pollvote where pollid=" + pollId), + MySqlCommand command = new MySqlCommand ( + String.Format ("Select userid, voteoption from pw_pollvote where pollid=" + pollId), connection); using (MySqlDataReader reader = command.ExecuteReader()) @@ -842,9 +844,9 @@ namespace Swarmops.Logic.Special.Sweden while (reader.Read()) { voteCount++; - int forumUserId = reader.GetInt32(0); + int forumUserId = reader.GetInt32 (0); - People people = People.FromOptionalData(ObjectOptionalDataType.ForumAccountId, + People people = People.FromOptionalData (ObjectOptionalDataType.ForumAccountId, forumUserId.ToString()); if (people.Count > 1) { @@ -853,7 +855,7 @@ namespace Swarmops.Logic.Special.Sweden { if (testPerson.GetMemberships().Count == 0) { - people.Remove(testPerson); + people.Remove (testPerson); } } @@ -862,8 +864,8 @@ namespace Swarmops.Logic.Special.Sweden string ids = ""; foreach (Person p in people) ids += " " + p.Identity; - throw new Exception("This is not possible -- check userid " + forumUserId + - ", appears to be tied to several personIds:" + ids); + throw new Exception ("This is not possible -- check userid " + forumUserId + + ", appears to be tied to several personIds:" + ids); } } @@ -874,19 +876,19 @@ namespace Swarmops.Logic.Special.Sweden person = people[0]; } - int pollAnswerId = reader.GetInt32(1); + int pollAnswerId = reader.GetInt32 (1); pollAnswerId--; //One based - if (!pollAlternatives.ContainsKey(pollAnswerId)) + if (!pollAlternatives.ContainsKey (pollAnswerId)) pollAlternatives[pollAnswerId] = "" + pollAnswerId; string pollAnswer = pollAlternatives[pollAnswerId]; - if (!result.ContainsKey(pollAnswer)) + if (!result.ContainsKey (pollAnswer)) { result[pollAnswer] = new People(); } - result[pollAnswer].Add(person); + result[pollAnswer].Add (person); } return result; @@ -895,30 +897,30 @@ namespace Swarmops.Logic.Special.Sweden } - private Dictionary GetPollAlternatives(int pollId) + private Dictionary GetPollAlternatives (int pollId) { Dictionary result = new Dictionary(); //Förslag A |||Förslag B |||Förslag C |||Förslag D |||Förslag E |||Avstår - using (MySqlConnection connection = new MySqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection (this.connectString)) { connection.Open(); - MySqlCommand command = new MySqlCommand( - String.Format("Select options from pw_poll where pollid=" + pollId), + MySqlCommand command = new MySqlCommand ( + String.Format ("Select options from pw_poll where pollid=" + pollId), connection); string options = ""; using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - options = reader.GetString(0); + options = reader.GetString (0); } else throw new ArgumentOutOfRangeException(); } - string[] results = options.Replace("|||", "\x12").Split('\x12'); + string[] results = options.Replace ("|||", "\x12").Split ('\x12'); for (int i = 0; i < results.Length; ++i) result[i] = results[i].Trim(); } @@ -929,7 +931,7 @@ namespace Swarmops.Logic.Special.Sweden #region Create Post - public int CreateNewPost(int forumId, Person poster, string title, string description, string post) + public int CreateNewPost (int forumId, Person poster, string title, string description, string post) { // call to vBulletin plugin to add post //key = special value secret key / selecting function to perform @@ -952,18 +954,18 @@ namespace Swarmops.Logic.Special.Sweden //Needed to avoid errors from homegrown SSL cert. ServicePointManager.CertificatePolicy = new ErrorIgnorerPolicy(); #pragma warning restore 618 - HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url); + HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url); //string proxy = null; - Encoding recieverEncoding = Encoding.GetEncoding("iso-8859-1"); + Encoding recieverEncoding = Encoding.GetEncoding ("iso-8859-1"); - string data = String.Format("key={0}&forumid={1}&userid={2}&title={3}&pagetext={4}", - HttpUtility.UrlEncode(postTopicKey, recieverEncoding), - HttpUtility.UrlEncode("" + forumId, recieverEncoding), - HttpUtility.UrlEncode("" + personAccountId, recieverEncoding), - HttpUtility.UrlEncode(title + ": " + description, recieverEncoding), - HttpUtility.UrlEncode(post, recieverEncoding)); + string data = String.Format ("key={0}&forumid={1}&userid={2}&title={3}&pagetext={4}", + HttpUtility.UrlEncode (postTopicKey, recieverEncoding), + HttpUtility.UrlEncode ("" + forumId, recieverEncoding), + HttpUtility.UrlEncode ("" + personAccountId, recieverEncoding), + HttpUtility.UrlEncode (title + ": " + description, recieverEncoding), + HttpUtility.UrlEncode (post, recieverEncoding)); - byte[] buffer = recieverEncoding.GetBytes(data); //Forum was set up for Latin-1 + byte[] buffer = recieverEncoding.GetBytes (data); //Forum was set up for Latin-1 req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; @@ -975,11 +977,11 @@ namespace Swarmops.Logic.Special.Sweden req.ServicePoint.Expect100Continue = false; //Disable stupid feature - req.Headers.Add("Pragma", "no-cache"); + req.Headers.Add ("Pragma", "no-cache"); Stream reqst = req.GetRequestStream(); // add form data to request stream - reqst.Write(buffer, 0, buffer.Length); + reqst.Write (buffer, 0, buffer.Length); reqst.Flush(); reqst.Close(); @@ -987,29 +989,29 @@ namespace Swarmops.Logic.Special.Sweden HttpWebResponse res = (HttpWebResponse) req.GetResponse(); Stream resst = res.GetResponseStream(); - StreamReader sr = new StreamReader(resst); + StreamReader sr = new StreamReader (resst); string response = sr.ReadToEnd(); int postId = 0; - if (int.TryParse(response, out postId)) + if (int.TryParse (response, out postId)) { return postId; } - throw new Exception("Error when calling CreateNewPost:" + response); + throw new Exception ("Error when calling CreateNewPost:" + response); } catch (WebException ex) { - throw new Exception("WebException when calling CreateNewPost:" + ex.Message); + throw new Exception ("WebException when calling CreateNewPost:" + ex.Message); } } - private string UrlEncode(string toEncode) + private string UrlEncode (string toEncode) { - return HttpUtility.UrlEncode(toEncode, Encoding.GetEncoding("iso-8859-1")); + return HttpUtility.UrlEncode (toEncode, Encoding.GetEncoding ("iso-8859-1")); } - public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, + public static bool Validator (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; @@ -1017,9 +1019,9 @@ namespace Swarmops.Logic.Special.Sweden #endregion - public static IForumDatabase GetDatabase(string connectionstring) + public static IForumDatabase GetDatabase (string connectionstring) { - return new SwedishForumDatabaseVBulletin(connectionstring); + return new SwedishForumDatabaseVBulletin (connectionstring); } public static IForumDatabase GetDatabase() @@ -1042,7 +1044,7 @@ namespace Swarmops.Logic.Special.Sweden } catch (Exception) { - Logging.LogWarning(LogSource.PirateDb, "Unable to read Forum Connectionstring"); + Logging.LogWarning (LogSource.PirateDb, "Unable to read Forum Connectionstring"); } // To simplify future checks @@ -1058,7 +1060,7 @@ namespace Swarmops.Logic.Special.Sweden CachedConnectionString = ConnectionString; } - return new SwedishForumDatabaseVBulletin(CachedConnectionString); + return new SwedishForumDatabaseVBulletin (CachedConnectionString); } } } \ No newline at end of file diff --git a/Logic/Special/Sweden/SwedishForumHandleProvider.cs b/Logic/Special/Sweden/SwedishForumHandleProvider.cs index c0412f54..40fea2f8 100644 --- a/Logic/Special/Sweden/SwedishForumHandleProvider.cs +++ b/Logic/Special/Sweden/SwedishForumHandleProvider.cs @@ -11,20 +11,20 @@ namespace Swarmops.Logic.Special.Sweden { #region IHandleProvider Members - public string GetPersonHandle(int personId) + public string GetPersonHandle (int personId) { - Person person = Person.FromIdentity(personId); + Person person = Person.FromIdentity (personId); if (person.SwedishForumAccountId == 0) { return null; } - return SwedishForumDatabase.GetDatabase().GetAccountName(person.SwedishForumAccountId); + return SwedishForumDatabase.GetDatabase().GetAccountName (person.SwedishForumAccountId); } - public void SetPersonHandle(int personId, string newHandle) + public void SetPersonHandle (int personId, string newHandle) { /* -- unused in Swarmops @@ -70,18 +70,18 @@ namespace Swarmops.Logic.Special.Sweden // suppress warnings with trace messages - Trace.WriteLine(personId); - Trace.WriteLine(newHandle); + Trace.WriteLine (personId); + Trace.WriteLine (newHandle); } - public HandleErrorType CanSetHandle(string newHandle) + public HandleErrorType CanSetHandle (string newHandle) { - throw new Exception("The method or operation is not implemented."); + throw new Exception ("The method or operation is not implemented."); } - public int GetPersonByHandle(string handle) + public int GetPersonByHandle (string handle) { - throw new Exception("The method or operation is not implemented."); + throw new Exception ("The method or operation is not implemented."); } #endregion diff --git a/Logic/Structure/Cities.cs b/Logic/Structure/Cities.cs index de5dae16..7fbfd9c6 100644 --- a/Logic/Structure/Cities.cs +++ b/Logic/Structure/Cities.cs @@ -6,42 +6,42 @@ namespace Swarmops.Logic.Structure { public class Cities : List { - public static Cities FromArray(BasicCity[] array) + public static Cities FromArray (BasicCity[] array) { Cities result = new Cities {Capacity = (array.Length*11/10)}; foreach (BasicCity basic in array) { - result.Add(City.FromBasic(basic)); + result.Add (City.FromBasic (basic)); } return result; } - public static Cities FromPostalCode(string postalCode, Country country) + public static Cities FromPostalCode (string postalCode, Country country) { - return FromPostalCode(postalCode, country.Identity); + return FromPostalCode (postalCode, country.Identity); } - public static Cities FromPostalCode(string postalCode, string countryCode) + public static Cities FromPostalCode (string postalCode, string countryCode) { - return FromPostalCode(postalCode, Country.FromCode(countryCode).Identity); + return FromPostalCode (postalCode, Country.FromCode (countryCode).Identity); } - public static Cities FromPostalCode(string postalCode, int countryId) + public static Cities FromPostalCode (string postalCode, int countryId) { - return FromArray(SwarmDb.GetDatabaseForReading().GetCitiesByCountryAndPostalCode(countryId, postalCode)); + return FromArray (SwarmDb.GetDatabaseForReading().GetCitiesByCountryAndPostalCode (countryId, postalCode)); } - public static Cities FromName(string cityName, int countryId) + public static Cities FromName (string cityName, int countryId) { - return FromArray(SwarmDb.GetDatabaseForReading().GetCitiesByName(cityName, countryId)); + return FromArray (SwarmDb.GetDatabaseForReading().GetCitiesByName (cityName, countryId)); } - public static Cities ForCountry(string countryCode) + public static Cities ForCountry (string countryCode) { - return FromArray(SwarmDb.GetDatabaseForReading().GetCitiesByCountry(countryCode)); + return FromArray (SwarmDb.GetDatabaseForReading().GetCitiesByCountry (countryCode)); } } } \ No newline at end of file diff --git a/Logic/Structure/City.cs b/Logic/Structure/City.cs index e418e79e..ac7fcdd5 100644 --- a/Logic/Structure/City.cs +++ b/Logic/Structure/City.cs @@ -7,14 +7,14 @@ namespace Swarmops.Logic.Structure [Serializable] public class City : BasicCity { - private City(BasicCity basic) - : base(basic) + private City (BasicCity basic) + : base (basic) { } // public ctor needed for serialization - [Obsolete("Do not call this function directly. It is intended only for use in serialization.", true)] - public City() : base(0, string.Empty, 0, 0) + [Obsolete ("Do not call this function directly. It is intended only for use in serialization.", true)] + public City() : base (0, string.Empty, 0, 0) { // this instance is NOT initalized, and intended to be used only in serialization. } @@ -22,32 +22,32 @@ namespace Swarmops.Logic.Structure public Geography Geography { - get { return Geography.FromIdentity(GeographyId); } // TODO: Cache + get { return Geography.FromIdentity (GeographyId); } // TODO: Cache } - public static City FromIdentity(int cityId) + public static City FromIdentity (int cityId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCity(cityId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCity (cityId)); } - public static City FromBasic(BasicCity basic) + public static City FromBasic (BasicCity basic) { - return new City(basic); + return new City (basic); } - public static City FromName(string cityName, int countryId) + public static City FromName (string cityName, int countryId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCityByName(cityName, countryId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCityByName (cityName, countryId)); } - public static City FromName(string cityName, string countryCode) + public static City FromName (string cityName, string countryCode) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCityByName(cityName, countryCode)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCityByName (cityName, countryCode)); } - public static City Create(string cityName, int countryId, int geographyId) + public static City Create (string cityName, int countryId, int geographyId) { - return FromIdentity(SwarmDb.GetDatabaseForWriting().CreateCity(cityName, countryId, geographyId)); + return FromIdentity (SwarmDb.GetDatabaseForWriting().CreateCity (cityName, countryId, geographyId)); } } } \ No newline at end of file diff --git a/Logic/Structure/Countries.cs b/Logic/Structure/Countries.cs index 689128cc..17bcfcd4 100644 --- a/Logic/Structure/Countries.cs +++ b/Logic/Structure/Countries.cs @@ -8,21 +8,21 @@ namespace Swarmops.Logic.Structure { public static Countries GetAll() { - return FromArray(SwarmDb.GetDatabaseForReading().GetAllCountries()); + return FromArray (SwarmDb.GetDatabaseForReading().GetAllCountries()); } public static Countries GetInUse() { - return FromArray(SwarmDb.GetDatabaseForReading().GetCountriesInUse()); + return FromArray (SwarmDb.GetDatabaseForReading().GetCountriesInUse()); } - public static Countries FromArray(BasicCountry[] basicArray) + public static Countries FromArray (BasicCountry[] basicArray) { Countries result = new Countries {Capacity = (basicArray.Length*11/10)}; foreach (BasicCountry basic in basicArray) { - result.Add(Country.FromBasic(basic)); + result.Add (Country.FromBasic (basic)); } return result; diff --git a/Logic/Structure/Country.cs b/Logic/Structure/Country.cs index fd0001f0..e0ce6bbc 100644 --- a/Logic/Structure/Country.cs +++ b/Logic/Structure/Country.cs @@ -8,42 +8,42 @@ namespace Swarmops.Logic.Structure [Serializable] public class Country : BasicCountry { - private Country(BasicCountry basic) - : base(basic) + private Country (BasicCountry basic) + : base (basic) { } - [Obsolete("Do not call this function directly. It is only intended for use in serialization.", true)] - public Country() : base(0, string.Empty, string.Empty) + [Obsolete ("Do not call this function directly. It is only intended for use in serialization.", true)] + public Country() : base (0, string.Empty, string.Empty) { // this ctor does NOT initialize the instance, but is provided to allow for serialization } public Geography Geography { - get { return Geography.FromIdentity(GeographyId); } + get { return Geography.FromIdentity (GeographyId); } } public Currency Currency { - get { return Currency.FromIdentity(CurrencyId); } + get { return Currency.FromIdentity (CurrencyId); } } - public static Country FromBasic(BasicCountry basic) + public static Country FromBasic (BasicCountry basic) { - return new Country(basic); + return new Country (basic); } // TODO: Cache these two functions, country info doesn't change - public static Country FromIdentity(int identity) + public static Country FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCountry(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCountry (identity)); } - public static Country FromCode(string countryCode) + public static Country FromCode (string countryCode) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCountry(countryCode)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetCountry (countryCode)); } } } \ No newline at end of file diff --git a/Logic/Structure/Geographies.cs b/Logic/Structure/Geographies.cs index a5043203..9bea7c8b 100644 --- a/Logic/Structure/Geographies.cs +++ b/Logic/Structure/Geographies.cs @@ -12,42 +12,42 @@ namespace Swarmops.Logic.Structure { #region Creation and Construction - public static Geographies FromArray(BasicGeography[] basicArray) + public static Geographies FromArray (BasicGeography[] basicArray) { Geographies result = new Geographies(); result.Capacity = basicArray.Length*11/10; foreach (BasicGeography basic in basicArray) { - result.Add(Geography.FromBasic(basic)); + result.Add (Geography.FromBasic (basic)); } return result; } - public static Geographies FromSingle(Geography geography) + public static Geographies FromSingle (Geography geography) { Geographies result = new Geographies(); - result.Add(geography); + result.Add (geography); return result; } - public static Geographies FromIdentities(int[] geoIds) + public static Geographies FromIdentities (int[] geoIds) { - return FromArray(GeographyCache.GetGeographies(geoIds)); + return FromArray (GeographyCache.GetGeographies (geoIds)); // return FromArray(SwarmDb.GetDatabaseForReading().GetGeographies(geoIds)); } - public static Geographies FromLevel(Country country, GeographyLevel level) + public static Geographies FromLevel (Country country, GeographyLevel level) { - return FromLevel(country.Identity, level); + return FromLevel (country.Identity, level); } - public static Geographies FromLevel(int countryId, GeographyLevel level) + public static Geographies FromLevel (int countryId, GeographyLevel level) { - return FromIdentities(SwarmDb.GetDatabaseForReading().GetGeographyIdsFromLevel(countryId, level)); + return FromIdentities (SwarmDb.GetDatabaseForReading().GetGeographyIdsFromLevel (countryId, level)); } #endregion @@ -71,7 +71,7 @@ namespace Swarmops.Logic.Structure public int[] Identities { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + get { return LogicServices.ObjectsToIdentifiers (ToArray()); } } @@ -84,7 +84,7 @@ namespace Swarmops.Logic.Structure /// The list of nodes. /// The highest node to return. /// The filtered list. - public Geographies FilterAbove(Geography topGeography) + public Geographies FilterAbove (Geography topGeography) { Geographies result = new Geographies(); @@ -101,15 +101,15 @@ namespace Swarmops.Logic.Structure foreach (Geography node in this) { - if (lineLookup.ContainsKey(node.Identity)) + if (lineLookup.ContainsKey (node.Identity)) { // Above cutoff point, add filter node - result.Add(topGeography); + result.Add (topGeography); } else { - result.Add(node); + result.Add (node); } } @@ -133,7 +133,7 @@ namespace Swarmops.Logic.Structure foreach (Geography currentNode in this) { - Geographies currentLine = Geography.FromIdentity(currentNode.GeographyId).GetLine(); + Geographies currentLine = Geography.FromIdentity (currentNode.GeographyId).GetLine(); foreach (Geography comparedNode in this) { @@ -154,7 +154,7 @@ namespace Swarmops.Logic.Structure // Therefore, the current node is already present in the collection, // as a child of the compared node. It can be safely removed. - remaining.Remove(currentNode.GeographyId); + remaining.Remove (currentNode.GeographyId); break; } } @@ -167,14 +167,14 @@ namespace Swarmops.Logic.Structure foreach (int nodeId in remaining.Keys) { - result.Add(remaining[nodeId]); + result.Add (remaining[nodeId]); } return result; } - public static Geographies LogicalOr(Geographies set1, Geographies set2) + public static Geographies LogicalOr (Geographies set1, Geographies set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -209,40 +209,40 @@ namespace Swarmops.Logic.Structure foreach (Geography geography in table.Values) { - result.Add(geography); + result.Add (geography); } return result; } - public Geographies LogicalOr(Geographies set2) + public Geographies LogicalOr (Geographies set2) { - return LogicalOr(this, set2); + return LogicalOr (this, set2); } public static Dictionary GetHierarchicalSortOrder() { Dictionary resultDictionary = new Dictionary(); - BuildHierarchicalSortOrder(resultDictionary, Geography.Root, 0); + BuildHierarchicalSortOrder (resultDictionary, Geography.Root, 0); return resultDictionary; } - private static void BuildHierarchicalSortOrder(Dictionary resultDictionary, + private static void BuildHierarchicalSortOrder (Dictionary resultDictionary, Geography currentParent, int level) { if (level > 20) { - throw new Exception("Detected loop in Geographic data at geography id:" + currentParent.Identity + ", " + - currentParent.Name); + throw new Exception ("Detected loop in Geographic data at geography id:" + currentParent.Identity + ", " + + currentParent.Name); } - if (!resultDictionary.ContainsKey(currentParent.Identity)) + if (!resultDictionary.ContainsKey (currentParent.Identity)) { - resultDictionary.Add(currentParent.Identity, new HierSortOrder(resultDictionary.Count, level)); + resultDictionary.Add (currentParent.Identity, new HierSortOrder (resultDictionary.Count, level)); } foreach (Geography subgeo in currentParent.Children) - BuildHierarchicalSortOrder(resultDictionary, subgeo, level + 1); + BuildHierarchicalSortOrder (resultDictionary, subgeo, level + 1); } public class HierSortOrder @@ -250,7 +250,7 @@ namespace Swarmops.Logic.Structure private readonly int level; private readonly int order; - internal HierSortOrder(int pOrder, int pLevel) + internal HierSortOrder (int pOrder, int pLevel) { this.order = pOrder; this.level = pLevel; diff --git a/Logic/Structure/Geography.cs b/Logic/Structure/Geography.cs index 2e501eed..2055a9ce 100644 --- a/Logic/Structure/Geography.cs +++ b/Logic/Structure/Geography.cs @@ -15,46 +15,46 @@ namespace Swarmops.Logic.Structure #region Construction and Creation private Geography() - : base(0, 0, string.Empty) + : base (0, 0, string.Empty) { // private ctor prevents construction } - private Geography(BasicGeography basic) - : base(basic) + private Geography (BasicGeography basic) + : base (basic) { // construction from basic } - public static Geography FromBasic(BasicGeography basic) + public static Geography FromBasic (BasicGeography basic) { - return new Geography(basic); + return new Geography (basic); } - public static Geography FromIdentity(int geographyId) + public static Geography FromIdentity (int geographyId) { - return FromBasic(GeographyCache.GetGeography(geographyId)); + return FromBasic (GeographyCache.GetGeography (geographyId)); //return FromBasic(SwarmDb.GetDatabaseForReading().GetGeography(geographyId)); } - public static Geography FromName(string geographyName) + public static Geography FromName (string geographyName) { // TODO: Possible dupes here, need resolution once we see the extent of the problem - return FromBasic(GeographyCache.GetGeographyByName(geographyName)); + return FromBasic (GeographyCache.GetGeographyByName (geographyName)); //return FromBasic(SwarmDb.GetDatabaseForReading().GetGeographyByName(geographyName)); } - public static Geography FromOfficialDesignation(Country country, GeographyLevel level, string designation) + public static Geography FromOfficialDesignation (Country country, GeographyLevel level, string designation) { - return FromOfficialDesignation(country.Identity, level, designation); + return FromOfficialDesignation (country.Identity, level, designation); } - public static Geography FromOfficialDesignation(int countryId, GeographyLevel level, string designation) + public static Geography FromOfficialDesignation (int countryId, GeographyLevel level, string designation) { return - FromIdentity(SwarmDb.GetDatabaseForReading().GetGeographyIdFromOfficialDesignation(countryId, level, + FromIdentity (SwarmDb.GetDatabaseForReading().GetGeographyIdFromOfficialDesignation (countryId, level, designation)); } @@ -95,7 +95,7 @@ namespace Swarmops.Logic.Structure { List retVal = new List(); foreach (Geography child in Children) - retVal.Add(child); + retVal.Add (child); return retVal; } } @@ -104,43 +104,43 @@ namespace Swarmops.Logic.Structure public Geographies Children { - get { return Geographies.FromArray(GeographyCache.GetGeographyChildren(Identity)); } + get { return Geographies.FromArray (GeographyCache.GetGeographyChildren (Identity)); } } public int ChildrenCount { - get { return GeographyCache.CountGeographyChildren(Identity); } + get { return GeographyCache.CountGeographyChildren (Identity); } } public static Geography Root { - get { return FromIdentity(RootIdentity); } + get { return FromIdentity (RootIdentity); } } public Geography Parent { - get { return FromIdentity(ParentIdentity); } + get { return FromIdentity (ParentIdentity); } } public Geographies GetTree() { - return Geographies.FromArray(GeographyCache.GetGeographyTree(Identity)); + return Geographies.FromArray (GeographyCache.GetGeographyTree (Identity)); // return Geographies.FromArray(SwarmDb.GetDatabaseForReading().GetGeographyTree(Identity)); } public Geographies GetLine() { - return Geographies.FromArray(GeographyCache.GetGeographyLine(Identity)); + return Geographies.FromArray (GeographyCache.GetGeographyLine (Identity)); //return Geographies.FromArray(SwarmDb.GetDatabaseForReading().GetGeographyLine(Identity)); } - public bool Inherits(Geography prospectiveParent) + public bool Inherits (Geography prospectiveParent) { - return Inherits(prospectiveParent.Identity); + return Inherits (prospectiveParent.Identity); } - public bool Inherits(int prospectiveParentGeographyId) + public bool Inherits (int prospectiveParentGeographyId) { // Returns true if prospectiveParent is a parent of ours. @@ -158,9 +158,9 @@ namespace Swarmops.Logic.Structure } - public bool AtLevel(GeographyLevel level) + public bool AtLevel (GeographyLevel level) { - GeographyLevel[] levels = SwarmDb.GetDatabaseForReading().GetGeographyLevelsAtGeographyId(Identity); + GeographyLevel[] levels = SwarmDb.GetDatabaseForReading().GetGeographyLevelsAtGeographyId (Identity); foreach (GeographyLevel potentialMatch in levels) { @@ -175,7 +175,7 @@ namespace Swarmops.Logic.Structure public BasicGeographyDesignation[] GetGeographyDesignations() { - return SwarmDb.GetDatabaseForReading().GetGeographyDesignationsForGeographyId(Identity); + return SwarmDb.GetDatabaseForReading().GetGeographyDesignationsForGeographyId (Identity); } } } \ No newline at end of file diff --git a/Logic/Structure/GeographyBar.cs b/Logic/Structure/GeographyBar.cs index a8c051b2..1fc5b637 100644 --- a/Logic/Structure/GeographyBar.cs +++ b/Logic/Structure/GeographyBar.cs @@ -10,11 +10,11 @@ namespace Swarmops.Logic.Structure #region IComparable Members - public int CompareTo(object obj) + public int CompareTo (object obj) { GeographyBar otherBar = (GeographyBar) obj; - return this.Value.CompareTo(otherBar.Value); + return this.Value.CompareTo (otherBar.Value); } #endregion diff --git a/Logic/Structure/GeographyStatistics.cs b/Logic/Structure/GeographyStatistics.cs index 014b4449..447c8c23 100644 --- a/Logic/Structure/GeographyStatistics.cs +++ b/Logic/Structure/GeographyStatistics.cs @@ -19,7 +19,7 @@ namespace Swarmops.Logic.Structure this.Timestamp = DateTime.Now; } - public static GeographyStatistics GeneratePresent(int[] memberCountForOrganizations) + public static GeographyStatistics GeneratePresent (int[] memberCountForOrganizations) { Dictionary voterCounts = SwarmDb.GetDatabaseForReading().GetGeographyVoterCounts(); GeographyStatistics result = new GeographyStatistics(); @@ -30,7 +30,7 @@ namespace Swarmops.Logic.Structure { GeographyDataPoint dataPoint = new GeographyDataPoint { - GeographyName = Geography.FromIdentity(geographyId).Name, + GeographyName = Geography.FromIdentity (geographyId).Name, GeographyId = geographyId, VoterCount = voterCounts[geographyId] }; @@ -44,8 +44,8 @@ namespace Swarmops.Logic.Structure foreach (int orgId in memberCountForOrganizations) { People members = - People.FromMemberships( - Memberships.ForOrganizations(Organization.FromIdentity(orgId).GetTree())); + People.FromMemberships ( + Memberships.ForOrganizations (Organization.FromIdentity (orgId).GetTree())); foreach (Person person in members) { @@ -54,7 +54,7 @@ namespace Swarmops.Logic.Structure // If we don't have this key, it's because it's too far down. Move up the tree until we're at least // at municipal level. - while (geography.Identity != 1 && !result.ContainsKey(geography.Identity)) + while (geography.Identity != 1 && !result.ContainsKey (geography.Identity)) { geography = geography.Parent; } @@ -102,7 +102,7 @@ namespace Swarmops.Logic.Structure { // Increment our temp values for every geo node below the one we're currently processing. - if (!result.ContainsKey(localNode.Identity)) + if (!result.ContainsKey (localNode.Identity)) { continue; } @@ -127,7 +127,7 @@ namespace Swarmops.Logic.Structure } } - if (!result.ContainsKey(geography.Identity)) + if (!result.ContainsKey (geography.Identity)) { result[geography.Identity] = new GeographyDataPoint { @@ -164,16 +164,16 @@ namespace Swarmops.Logic.Structure return result; } - public static GeographyStatistics FromXml(string xml) + public static GeographyStatistics FromXml (string xml) { - GeographyStatisticsSerializable serializable = GeographyStatisticsSerializable.FromXml(xml); + GeographyStatisticsSerializable serializable = GeographyStatisticsSerializable.FromXml (xml); GeographyStatistics result = new GeographyStatistics(); foreach (GeographyDataPoint dataPoint in serializable) { result[dataPoint.GeographyId] = dataPoint; - result[dataPoint.GeographyId].GeographyName = HttpUtility.HtmlDecode(dataPoint.GeographyName); + result[dataPoint.GeographyId].GeographyName = HttpUtility.HtmlDecode (dataPoint.GeographyName); } return result; @@ -188,8 +188,8 @@ namespace Swarmops.Logic.Structure foreach (GeographyDataPoint dataPoint in Values) { - dataPoint.GeographyName = HttpUtility.HtmlEncode(dataPoint.GeographyName); - serializable.Add(dataPoint); + dataPoint.GeographyName = HttpUtility.HtmlEncode (dataPoint.GeographyName); + serializable.Add (dataPoint); } return serializable.ToXml(); @@ -199,16 +199,16 @@ namespace Swarmops.Logic.Structure [Serializable] public class GeographyStatisticsSerializable : List { - public static GeographyStatisticsSerializable FromXml(string xml) + public static GeographyStatisticsSerializable FromXml (string xml) { - XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); + XmlSerializer serializer = new XmlSerializer (typeof (GeographyStatisticsSerializable)); MemoryStream stream = new MemoryStream(); - byte[] xmlBytes = Encoding.Default.GetBytes(xml); - stream.Write(xmlBytes, 0, xmlBytes.Length); + byte[] xmlBytes = Encoding.Default.GetBytes (xml); + stream.Write (xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - GeographyStatisticsSerializable result = (GeographyStatisticsSerializable) serializer.Deserialize(stream); + GeographyStatisticsSerializable result = (GeographyStatisticsSerializable) serializer.Deserialize (stream); stream.Close(); return result; @@ -217,13 +217,13 @@ namespace Swarmops.Logic.Structure public string ToXml() { - XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); + XmlSerializer serializer = new XmlSerializer (typeof (GeographyStatisticsSerializable)); MemoryStream stream = new MemoryStream(); - serializer.Serialize(stream, this); + serializer.Serialize (stream, this); byte[] xmlBytes = stream.GetBuffer(); - return Encoding.Default.GetString(xmlBytes); + return Encoding.Default.GetString (xmlBytes); } } } \ No newline at end of file diff --git a/Logic/Structure/GeographyStatisticsOverTime.cs b/Logic/Structure/GeographyStatisticsOverTime.cs index cd70504a..0f24e918 100644 --- a/Logic/Structure/GeographyStatisticsOverTime.cs +++ b/Logic/Structure/GeographyStatisticsOverTime.cs @@ -7,16 +7,16 @@ namespace Swarmops.Logic.Structure { internal class GeographyStatisticsOverTime : List { - public static GeographyStatisticsOverTime FromXml(string xml) + public static GeographyStatisticsOverTime FromXml (string xml) { - XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); + XmlSerializer serializer = new XmlSerializer (typeof (GeographyStatisticsOverTime)); MemoryStream stream = new MemoryStream(); - byte[] xmlBytes = Encoding.Default.GetBytes(xml); - stream.Write(xmlBytes, 0, xmlBytes.Length); + byte[] xmlBytes = Encoding.Default.GetBytes (xml); + stream.Write (xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - GeographyStatisticsOverTime result = (GeographyStatisticsOverTime) serializer.Deserialize(stream); + GeographyStatisticsOverTime result = (GeographyStatisticsOverTime) serializer.Deserialize (stream); stream.Close(); return result; @@ -25,13 +25,13 @@ namespace Swarmops.Logic.Structure public string ToXml() { - XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); + XmlSerializer serializer = new XmlSerializer (typeof (GeographyStatisticsOverTime)); MemoryStream stream = new MemoryStream(); - serializer.Serialize(stream, this); + serializer.Serialize (stream, this); byte[] xmlBytes = stream.GetBuffer(); - return Encoding.Default.GetString(xmlBytes); + return Encoding.Default.GetString (xmlBytes); } } } \ No newline at end of file diff --git a/Logic/Structure/Organization.cs b/Logic/Structure/Organization.cs index dcffcfc0..f79387db 100644 --- a/Logic/Structure/Organization.cs +++ b/Logic/Structure/Organization.cs @@ -26,31 +26,31 @@ namespace Swarmops.Logic.Structure { } // disallow public direct construction - private Organization(BasicOrganization basic) - : base(basic) + private Organization (BasicOrganization basic) + : base (basic) { } - protected Organization(Organization org) - : base(org) + protected Organization (Organization org) + : base (org) { } - public static Organization FromIdentity(int identity) + public static Organization FromIdentity (int identity) { - return FromBasic(OrganizationCache.GetOrganization(identity)); + return FromBasic (OrganizationCache.GetOrganization (identity)); //return FromBasic(SwarmDb.GetDatabaseForReading().GetOrganization(identity)); } - public static Organization FromIdentityAggressive(int identity) + public static Organization FromIdentityAggressive (int identity) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetOrganization(identity)); - // Note "for writing". Intentional. Queries master db; bypasses replication lag. + return FromBasic (SwarmDb.GetDatabaseForWriting().GetOrganization (identity)); + // Note "for writing". Intentional. Queries master db; bypasses replication lag. } - public static Organization FromBasic(BasicOrganization basic) + public static Organization FromBasic (BasicOrganization basic) { - return new Organization(basic); + return new Organization (basic); } #endregion @@ -62,49 +62,49 @@ namespace Swarmops.Logic.Structure #region class globals - [Obsolete("This should never be used anymore!", true)] public static readonly int RootIdentity = 5; - [Obsolete("This should never be used anymore!", true)] public static readonly int PPSEid = 1; - [Obsolete("This should never be used anymore!", true)] public static readonly int UPSEid = 2; - [Obsolete("This should never be used anymore!", true)] public static readonly int PPFIid = 49; - [Obsolete("This should never be used anymore!", true)] public static readonly int UPFIid = 95; - [Obsolete("This should never be used anymore!", true)] public static readonly int PPNOid = 48; - [Obsolete("This should never be used anymore!", true)] public static readonly int PPDKid = 82; - [Obsolete("This should never be used anymore!", true)] public static readonly int UPDKid = 83; + [Obsolete ("This should never be used anymore!", true)] public static readonly int RootIdentity = 5; + [Obsolete ("This should never be used anymore!", true)] public static readonly int PPSEid = 1; + [Obsolete ("This should never be used anymore!", true)] public static readonly int UPSEid = 2; + [Obsolete ("This should never be used anymore!", true)] public static readonly int PPFIid = 49; + [Obsolete ("This should never be used anymore!", true)] public static readonly int UPFIid = 95; + [Obsolete ("This should never be used anymore!", true)] public static readonly int PPNOid = 48; + [Obsolete ("This should never be used anymore!", true)] public static readonly int PPDKid = 82; + [Obsolete ("This should never be used anymore!", true)] public static readonly int UPDKid = 83; public static Organization Sandbox { - get { return FromIdentity(SandboxIdentity); } + get { return FromIdentity (SandboxIdentity); } } public static int SandboxIdentity { get { - if (FromIdentity(1).Name.StartsWith("Sandbox")) + if (FromIdentity (1).Name.StartsWith ("Sandbox")) { return 1; } - if (FromIdentity(3).Name.StartsWith("Sandbox")) + if (FromIdentity (3).Name.StartsWith ("Sandbox")) { return 3; } - throw new InvalidOperationException("Cannot locate Sandbox organization's identity"); + throw new InvalidOperationException ("Cannot locate Sandbox organization's identity"); } } - [Obsolete("This should never be used anymore!", true)] + [Obsolete ("This should never be used anymore!", true)] public static Organization PPSE { - get { return FromIdentity(PPSEid); } + get { return FromIdentity (PPSEid); } } #endregion #region IComparable Members - public int CompareTo(object obj) + public int CompareTo (object obj) { Organization org2 = obj as Organization; @@ -125,7 +125,7 @@ namespace Swarmops.Logic.Structure // TODO: Read culture from organization's default country instead of hardcoding like this - return String.Compare(Name, org2.Name, true, new CultureInfo("sv-SE")); + return String.Compare (Name, org2.Name, true, new CultureInfo ("sv-SE")); } #endregion @@ -154,7 +154,7 @@ namespace Swarmops.Logic.Structure { List retVal = new List(); foreach (Organization child in Children) - retVal.Add(child); + retVal.Add (child); return retVal; } } @@ -168,8 +168,8 @@ namespace Swarmops.Logic.Structure if (this._optionalData == null) { Organization o = this; - this._optionalData = ObjectOptionalData.ForObject(o); - //Added cast, otherwise it fails for subclasses + this._optionalData = ObjectOptionalData.ForObject (o); + //Added cast, otherwise it fails for subclasses } return this._optionalData; } @@ -177,18 +177,18 @@ namespace Swarmops.Logic.Structure public Organization Parent { - get { return OrganizationCache.FromCache(ParentIdentity); } + get { return OrganizationCache.FromCache (ParentIdentity); } } public Organizations Children { - get { return Organizations.FromArray(OrganizationCache.GetOrganizationChildren(Identity)); } + get { return Organizations.FromArray (OrganizationCache.GetOrganizationChildren (Identity)); } } public OrganizationFinancialAccounts FinancialAccounts { - get { return new OrganizationFinancialAccounts(Identity); } + get { return new OrganizationFinancialAccounts (Identity); } } public FinancialAccounts FinancialAccountsExternal @@ -198,18 +198,18 @@ namespace Swarmops.Logic.Structure // HACK: MUST FETCH THIS FROM ACTUAL ACCOUNTS // HACK HACK HACK HACK HACK HACK - if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE) && OrganizationId == 1) + if (PilotInstallationIds.IsPilot (PilotInstallationIds.PiratePartySE) && OrganizationId == 1) { FinancialAccounts result = new FinancialAccounts(); - result.Add(FinancialAccount.FromIdentity(1)); - result.Add(FinancialAccount.FromIdentity(2)); + result.Add (FinancialAccount.FromIdentity (1)); + result.Add (FinancialAccount.FromIdentity (2)); return result; } - if (PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && OrganizationId == 7) + if (PilotInstallationIds.IsPilot (PilotInstallationIds.SwarmopsLive) && OrganizationId == 7) { FinancialAccounts result = new FinancialAccounts(); - result.Add(FinancialAccount.FromIdentity(29)); + result.Add (FinancialAccount.FromIdentity (29)); return result; } @@ -221,7 +221,7 @@ namespace Swarmops.Logic.Structure public OrganizationParameters Parameters { - get { return new OrganizationParameters(this); } + get { return new OrganizationParameters (this); } } @@ -241,11 +241,11 @@ namespace Swarmops.Logic.Structure // HACK: this gets the TEMPORARY list string peopleIdstring = Parameters.TemporaryAccessListWrite; - string[] peopleIds = peopleIdstring.Split(' '); + string[] peopleIds = peopleIdstring.Split (' '); foreach (string peopleId in peopleIds) { - result.Add(Person.FromIdentity(Int32.Parse(peopleId))); + result.Add (Person.FromIdentity (Int32.Parse (peopleId))); } return result; @@ -257,13 +257,13 @@ namespace Swarmops.Logic.Structure get { string optionalData = OptionalData[ObjectOptionalDataType.OrgRegularLabel]; - if (string.IsNullOrEmpty(optionalData)) + if (string.IsNullOrEmpty (optionalData)) { RegularLabel = ParticipantTitle.Member; return ParticipantTitle.Member; // Legacy } - return (ParticipantTitle)(Enum.Parse(typeof(ParticipantTitle),optionalData)); + return (ParticipantTitle) (Enum.Parse (typeof (ParticipantTitle), optionalData)); } set { OptionalData[ObjectOptionalDataType.OrgRegularLabel] = value.ToString(); } } @@ -273,7 +273,7 @@ namespace Swarmops.Logic.Structure get { string optionalData = OptionalData[ObjectOptionalDataType.OrgActivistLabel]; - if (string.IsNullOrEmpty(optionalData)) + if (string.IsNullOrEmpty (optionalData)) { ActivistLabel = "Activist"; return "Activist"; @@ -288,7 +288,7 @@ namespace Swarmops.Logic.Structure public bool IsEconomyEnabled { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgEconomyEnabled); } } public int FirstFiscalYear @@ -297,7 +297,7 @@ namespace Swarmops.Logic.Structure { if (!IsEconomyEnabled) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Cannot request first fiscal year; organization is not economy-enabled"); } @@ -305,19 +305,19 @@ namespace Swarmops.Logic.Structure if (year < 2000) { - if (Identity == 1 && Name.StartsWith("Piratpartiet")) + if (Identity == 1 && Name.StartsWith ("Piratpartiet")) { - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2009); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.OrgFirstFiscalYear, 2009); year = 2009; } - else if (Identity == 7 && Name.StartsWith("Europirate Acad")) + else if (Identity == 7 && Name.StartsWith ("Europirate Acad")) { - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2012); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.OrgFirstFiscalYear, 2012); year = 2012; } - else if (Identity == 1 && Name.StartsWith("Sandbox")) + else if (Identity == 1 && Name.StartsWith ("Sandbox")) { - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2012); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.OrgFirstFiscalYear, 2012); year = 2012; } } @@ -332,50 +332,50 @@ namespace Swarmops.Logic.Structure { if (!IsEconomyEnabled) { - throw new InvalidOperationException("Cannot request currency; organization is not economy-enabled"); + throw new InvalidOperationException ("Cannot request currency; organization is not economy-enabled"); } - string currencyCode = OptionalData.GetOptionalDataString(ObjectOptionalDataType.OrgCurrency); + string currencyCode = OptionalData.GetOptionalDataString (ObjectOptionalDataType.OrgCurrency); - if (string.IsNullOrEmpty(currencyCode)) + if (string.IsNullOrEmpty (currencyCode)) { - if (Identity == 1 && (Name.StartsWith("Piratpartiet") || Name.StartsWith("Sandbox"))) + if (Identity == 1 && (Name.StartsWith ("Piratpartiet") || Name.StartsWith ("Sandbox"))) { // This is a one-off to fix the v4 installation. Currency is SEK. - OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgCurrency, "SEK"); + OptionalData.SetOptionalDataString (ObjectOptionalDataType.OrgCurrency, "SEK"); currencyCode = "SEK"; } - if (Identity == 2 && (Name.StartsWith("European"))) + if (Identity == 2 && (Name.StartsWith ("European"))) { - OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgCurrency, "SEK"); + OptionalData.SetOptionalDataString (ObjectOptionalDataType.OrgCurrency, "SEK"); currencyCode = "SEK"; } } - return Currency.FromCode(currencyCode); + return Currency.FromCode (currencyCode); } } - public bool IsOrInherits(Organization prospectiveParent) + public bool IsOrInherits (Organization prospectiveParent) { if (Identity == prospectiveParent.Identity) return true; - return Inherits(prospectiveParent.Identity); + return Inherits (prospectiveParent.Identity); } - public bool Inherits(Organization prospectiveParent) + public bool Inherits (Organization prospectiveParent) { - return Inherits(prospectiveParent.Identity); + return Inherits (prospectiveParent.Identity); } - public bool IsOrInherits(int prospectiveParentOrganizationId) + public bool IsOrInherits (int prospectiveParentOrganizationId) { if (Identity == prospectiveParentOrganizationId) return true; - return Inherits(prospectiveParentOrganizationId); + return Inherits (prospectiveParentOrganizationId); } - public bool Inherits(int prospectiveParentOrganizationId) + public bool Inherits (int prospectiveParentOrganizationId) { // Returns true if prospectiveParent is a parent of ours. @@ -394,33 +394,34 @@ namespace Swarmops.Logic.Structure public Organizations GetLine() { - return Organizations.FromArray(OrganizationCache.GetOrganizationLine(Identity)); + return Organizations.FromArray (OrganizationCache.GetOrganizationLine (Identity)); //return Organizations.FromArray(SwarmDb.GetDatabaseForReading().GetOrganizationLine(Identity)); } public Organizations GetTree() { - return Organizations.FromArray(OrganizationCache.GetOrganizationTree(Identity)); + return Organizations.FromArray (OrganizationCache.GetOrganizationTree (Identity)); //return Organizations.FromArray(SwarmDb.GetDatabaseForReading().GetOrganizationTree(Identity)); } public int GetMemberCount() { - return Memberships.GetMemberCountForOrganization(this); + return Memberships.GetMemberCountForOrganization (this); } public NewsletterFeeds GetNewsletterFeeds() { - return NewsletterFeeds.FromArray(SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForOrganization(Identity)); + return + NewsletterFeeds.FromArray (SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForOrganization (Identity)); } - public void EnableEconomy(Currency currency) + public void EnableEconomy (Currency currency) { if (IsEconomyEnabled) { - throw new InvalidOperationException("Economy data already enabled"); + throw new InvalidOperationException ("Economy data already enabled"); } // First, set hardwired accounts @@ -429,11 +430,11 @@ namespace Swarmops.Logic.Structure // TODO: Set names according to org default culture FinancialAccounts[OrganizationFinancialAccountType.AssetsBankAccountMain] = - FinancialAccount.Create(this, "Bank Account", FinancialAccountType.Asset, null); + FinancialAccount.Create (this, "Bank Account", FinancialAccountType.Asset, null); FinancialAccounts[OrganizationFinancialAccountType.AssetsOutboundInvoices] = - FinancialAccount.Create(this, "Outbound Invoices", FinancialAccountType.Asset, null); + FinancialAccount.Create (this, "Outbound Invoices", FinancialAccountType.Asset, null); FinancialAccounts[OrganizationFinancialAccountType.AssetsOutstandingCashAdvances] = - FinancialAccount.Create(this, "Cash Advances", FinancialAccountType.Asset, null); + FinancialAccount.Create (this, "Cash Advances", FinancialAccountType.Asset, null); //FinancialAccounts[OrganizationFinancialAccountType.AssetsPaypal] = // FinancialAccount.Create(this, "Paypal Account", FinancialAccountType.Asset, null); //FinancialAccounts[OrganizationFinancialAccountType.AssetsBitcoinHot] = @@ -443,59 +444,59 @@ namespace Swarmops.Logic.Structure //FinancialAccounts[OrganizationFinancialAccountType.AssetsVatInbound] = // FinancialAccount.Create(this, "Inbound Value Added Tax", FinancialAccountType.Asset, null); FinancialAccounts[OrganizationFinancialAccountType.CostsAllocatedFunds] = - FinancialAccount.Create(this, "Allocated funds", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Allocated funds", FinancialAccountType.Cost, null); FinancialAccounts[OrganizationFinancialAccountType.CostsBankFees] = - FinancialAccount.Create(this, "Bank Fees", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Bank Fees", FinancialAccountType.Cost, null); FinancialAccounts[OrganizationFinancialAccountType.CostsInfrastructure] = - FinancialAccount.Create(this, "ICT and Infrastructure", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "ICT and Infrastructure", FinancialAccountType.Cost, null); FinancialAccounts[OrganizationFinancialAccountType.CostsYearlyResult] = - FinancialAccount.Create(this, "Yearly result", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Yearly result", FinancialAccountType.Cost, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsEquity] = - FinancialAccount.Create(this, "Equity", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "Equity", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsExpenseClaims] = - FinancialAccount.Create(this, "Expense Claims", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "Expense Claims", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsInboundInvoices] = - FinancialAccount.Create(this, "Inbound Invoices", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "Inbound Invoices", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsOther] = - FinancialAccount.Create(this, "General Debt", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "General Debt", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsSalary] = - FinancialAccount.Create(this, "Salaries Due", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "Salaries Due", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.DebtsTax] = - FinancialAccount.Create(this, "Taxes Due", FinancialAccountType.Debt, null); + FinancialAccount.Create (this, "Taxes Due", FinancialAccountType.Debt, null); //FinancialAccounts[OrganizationFinancialAccountType.DebtsVatOutbound] = // FinancialAccount.Create(this, "Outbound Value Added Tax", FinancialAccountType.Debt, null); FinancialAccounts[OrganizationFinancialAccountType.IncomeDonations] = - FinancialAccount.Create(this, "Donations", FinancialAccountType.Income, null); + FinancialAccount.Create (this, "Donations", FinancialAccountType.Income, null); FinancialAccounts[OrganizationFinancialAccountType.IncomeSales] = - FinancialAccount.Create(this, "Sales", FinancialAccountType.Income, null); + FinancialAccount.Create (this, "Sales", FinancialAccountType.Income, null); // Then, create various cost accounts that are probably needed, or that could be used as a starting point - FinancialAccount.Create(this, "Offices", FinancialAccountType.Cost, null); - FinancialAccount.Create(this, "Unforeseen", FinancialAccountType.Cost, null); - FinancialAccount.Create(this, "Staff", FinancialAccountType.Cost, null); - FinancialAccount.Create(this, "Marketing and Campaigns", FinancialAccountType.Cost, null); - FinancialAccount.Create(this, "Research and Development", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Offices", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Unforeseen", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Staff", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Marketing and Campaigns", FinancialAccountType.Cost, null); + FinancialAccount.Create (this, "Research and Development", FinancialAccountType.Cost, null); // Finally, create the first conference parent - FinancialAccount conferenceBase = FinancialAccount.Create(this, "Conferences", + FinancialAccount conferenceBase = FinancialAccount.Create (this, "Conferences", FinancialAccountType.Cost, null); conferenceBase.IsConferenceParent = true; // Set the currency - OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgCurrency, currency.Code); + OptionalData.SetOptionalDataString (ObjectOptionalDataType.OrgCurrency, currency.Code); // Set current year to first fiscal year - OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, DateTime.Today.Year); + OptionalData.SetOptionalDataInt (ObjectOptionalDataType.OrgFirstFiscalYear, DateTime.Today.Year); // Finally, flag the org as enabled - OptionalData.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); + OptionalData.SetOptionalDataBool (ObjectOptionalDataType.OrgEconomyEnabled, true); } #endregion @@ -522,7 +523,7 @@ namespace Swarmops.Logic.Structure { return null; } - return Country.FromIdentity(DefaultCountryId); + return Country.FromIdentity (DefaultCountryId); } } @@ -557,7 +558,7 @@ namespace Swarmops.Logic.Structure return MailPrefix; } - if (string.IsNullOrEmpty(this.mailPrefixInherited)) + if (string.IsNullOrEmpty (this.mailPrefixInherited)) { Organizations orgLine = GetLine(); @@ -584,7 +585,7 @@ namespace Swarmops.Logic.Structure { if (this.anchorGeography == null) { - this.anchorGeography = Geography.FromIdentity(AnchorGeographyId); + this.anchorGeography = Geography.FromIdentity (AnchorGeographyId); } return this.anchorGeography; @@ -604,46 +605,46 @@ namespace Swarmops.Logic.Structure if (this.uptakeGeographies == null) { this.uptakeGeographies = - Geographies.FromIdentities( - SwarmDb.GetDatabaseForReading().GetOrganizationUptakeGeographyIds(Identity)); + Geographies.FromIdentities ( + SwarmDb.GetDatabaseForReading().GetOrganizationUptakeGeographyIds (Identity)); } return this.uptakeGeographies.AsReadOnly(); } } - public void AddUptakeGeography(Geography geo) + public void AddUptakeGeography (Geography geo) { - AddUptakeGeography(geo.Identity); + AddUptakeGeography (geo.Identity); } - public void DeleteUptakeGeography(Geography geo) + public void DeleteUptakeGeography (Geography geo) { - DeleteUptakeGeography(geo.Identity); + DeleteUptakeGeography (geo.Identity); } - public void AddUptakeGeography(int geoId) + public void AddUptakeGeography (int geoId) { - OrganizationCache.AddOrgUptakeGeography(Identity, geoId); + OrganizationCache.AddOrgUptakeGeography (Identity, geoId); } - public void DeleteUptakeGeography(int geoId) + public void DeleteUptakeGeography (int geoId) { - OrganizationCache.DeleteOrgUptakeGeography(Identity, geoId); + OrganizationCache.DeleteOrgUptakeGeography (Identity, geoId); } - public UptakeGeography[] GetUptakeGeographies(bool others) + public UptakeGeography[] GetUptakeGeographies (bool others) { BasicUptakeGeography[] basics = SwarmDb.GetDatabaseForReading() - .GetOrganizationUptakeGeographies(Identity, others); + .GetOrganizationUptakeGeographies (Identity, others); List retVal = new List(); foreach (BasicUptakeGeography b in basics) { try { - UptakeGeography ug = UptakeGeography.FromBasic(b); + UptakeGeography ug = UptakeGeography.FromBasic (b); if (ug.Organization != null && ug.Geography != null && ug.Organization.ParentIdentity != -1) - retVal.Add(UptakeGeography.FromBasic(b)); + retVal.Add (UptakeGeography.FromBasic (b)); } catch { @@ -653,7 +654,7 @@ namespace Swarmops.Logic.Structure if (others) { - throw new NotImplementedException("Apollo 13. Contact the devs with the Apollo 13."); + throw new NotImplementedException ("Apollo 13. Contact the devs with the Apollo 13."); // When is this code used anyway? One organization setting its geography uptake structure should NEVER interfere with // other organizations' uptake trees ("Organization.RootIdentity"). There is no reason whatsoever to get all @@ -670,9 +671,9 @@ namespace Swarmops.Logic.Structure } }*/ } - BasicUptakeGeography myAnchor = new BasicUptakeGeography(Identity, AnchorGeographyId); - if (retVal.Find(delegate(UptakeGeography ug) { return ug.GeoId == AnchorGeographyId; }) == null) - retVal.Add(UptakeGeography.FromBasic(myAnchor)); + BasicUptakeGeography myAnchor = new BasicUptakeGeography (Identity, AnchorGeographyId); + if (retVal.Find (delegate (UptakeGeography ug) { return ug.GeoId == AnchorGeographyId; }) == null) + retVal.Add (UptakeGeography.FromBasic (myAnchor)); return retVal.ToArray(); } @@ -683,24 +684,24 @@ namespace Swarmops.Logic.Structure private Dictionary functionalMailDict; - public FunctionalMail.AddressItem GetFunctionalMailAddressInh(MailAuthorType authorType) + public FunctionalMail.AddressItem GetFunctionalMailAddressInh (MailAuthorType authorType) { LoadFunctionalMailAddress(); - if (this.functionalMailDict.ContainsKey(authorType)) + if (this.functionalMailDict.ContainsKey (authorType)) return this.functionalMailDict[authorType]; - if (this.ParentIdentity != 0) - return this.Parent.GetFunctionalMailAddressInh(authorType); - if (FunctionalMail.Address.ContainsKey(authorType)) + if (ParentIdentity != 0) + return Parent.GetFunctionalMailAddressInh (authorType); + if (FunctionalMail.Address.ContainsKey (authorType)) return FunctionalMail.Address[authorType]; // Default. return null; } - public FunctionalMail.AddressItem GetFunctionalMailAddress(MailAuthorType authorType) + public FunctionalMail.AddressItem GetFunctionalMailAddress (MailAuthorType authorType) { LoadFunctionalMailAddress(); - if (this.functionalMailDict.ContainsKey(authorType)) + if (this.functionalMailDict.ContainsKey (authorType)) return this.functionalMailDict[authorType]; return null; } @@ -710,23 +711,23 @@ namespace Swarmops.Logic.Structure if (this.functionalMailDict == null) { this.functionalMailDict = new Dictionary(); - string funcMails = OptionalData.GetOptionalDataString(ObjectOptionalDataType.OrgFunctionalMail); - string[] rows = funcMails.Replace("\r", "\n") - .Replace("\n\n", "\n") - .Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries); + string funcMails = OptionalData.GetOptionalDataString (ObjectOptionalDataType.OrgFunctionalMail); + string[] rows = funcMails.Replace ("\r", "\n") + .Replace ("\n\n", "\n") + .Split (new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries); - Regex reSplitAddress = new Regex(@"^(?.+?):(?.+)[,;:]\s*(?
\S+?@\S+?)$", + Regex reSplitAddress = new Regex (@"^(?.+?):(?.+)[,;:]\s*(?
\S+?@\S+?)$", RegexOptions.IgnoreCase); foreach (string row in rows) { - Match match = reSplitAddress.Match(row); + Match match = reSplitAddress.Match (row); try { MailAuthorType maType = - (MailAuthorType) Enum.Parse(typeof (MailAuthorType), match.Groups["Type"].Value); + (MailAuthorType) Enum.Parse (typeof (MailAuthorType), match.Groups["Type"].Value); string name = match.Groups["Name"].Value; string address = match.Groups["Address"].Value; - this.functionalMailDict[maType] = new FunctionalMail.AddressItem(address, name); + this.functionalMailDict[maType] = new FunctionalMail.AddressItem (address, name); } catch { @@ -735,15 +736,15 @@ namespace Swarmops.Logic.Structure } } - public void SetFunctionalMailAddress(MailAuthorType authorType, string name, string email) + public void SetFunctionalMailAddress (MailAuthorType authorType, string name, string email) { - if (string.IsNullOrEmpty(email.Trim())) + if (string.IsNullOrEmpty (email.Trim())) { - this.functionalMailDict.Remove(authorType); + this.functionalMailDict.Remove (authorType); } else { - this.functionalMailDict[authorType] = new FunctionalMail.AddressItem(email, name); + this.functionalMailDict[authorType] = new FunctionalMail.AddressItem (email, name); } SaveFunctionalMailDict(); } @@ -755,10 +756,10 @@ namespace Swarmops.Logic.Structure foreach (MailAuthorType ma in this.functionalMailDict.Keys) { - sb.AppendFormat("{0}:{1};{2}\r\n", ma, this.functionalMailDict[ma].Name, + sb.AppendFormat ("{0}:{1};{2}\r\n", ma, this.functionalMailDict[ma].Name, this.functionalMailDict[ma].Email); } - OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgFunctionalMail, sb.ToString()); + OptionalData.SetOptionalDataString (ObjectOptionalDataType.OrgFunctionalMail, sb.ToString()); } #endregion @@ -769,11 +770,11 @@ namespace Swarmops.Logic.Structure { get { - if (OptionalData.HasData(ObjectOptionalDataType.OrgShowNamesInNotifications)) - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); - if (this.ParentIdentity != 0) - return this.Parent.ShowNamesInNotificationsInh; - return this.OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); + if (OptionalData.HasData (ObjectOptionalDataType.OrgShowNamesInNotifications)) + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgShowNamesInNotifications); + if (ParentIdentity != 0) + return Parent.ShowNamesInNotificationsInh; + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgShowNamesInNotifications); } } @@ -781,19 +782,19 @@ namespace Swarmops.Logic.Structure { get { - if (OptionalData.HasData(ObjectOptionalDataType.OrgShowNamesInNotifications)) - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); + if (OptionalData.HasData (ObjectOptionalDataType.OrgShowNamesInNotifications)) + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgShowNamesInNotifications); return null; } set { if (value.HasValue) { - OptionalData.SetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications, value.Value); + OptionalData.SetOptionalDataBool (ObjectOptionalDataType.OrgShowNamesInNotifications, value.Value); } else { - OptionalData.SetOptionalData(ObjectOptionalDataType.OrgShowNamesInNotifications, null); + OptionalData.SetOptionalData (ObjectOptionalDataType.OrgShowNamesInNotifications, null); } } } @@ -806,11 +807,11 @@ namespace Swarmops.Logic.Structure { get { - if (OptionalData.HasData(ObjectOptionalDataType.OrgUsePaymentStatus)) - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); - if (this.ParentIdentity != 0) - return this.Parent.UsePaymentStatusInh; - return this.OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); + if (OptionalData.HasData (ObjectOptionalDataType.OrgUsePaymentStatus)) + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgUsePaymentStatus); + if (ParentIdentity != 0) + return Parent.UsePaymentStatusInh; + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgUsePaymentStatus); } } @@ -818,19 +819,19 @@ namespace Swarmops.Logic.Structure { get { - if (OptionalData.HasData(ObjectOptionalDataType.OrgUsePaymentStatus)) - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); + if (OptionalData.HasData (ObjectOptionalDataType.OrgUsePaymentStatus)) + return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.OrgUsePaymentStatus); return null; } set { if (value.HasValue) { - OptionalData.SetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus, value.Value); + OptionalData.SetOptionalDataBool (ObjectOptionalDataType.OrgUsePaymentStatus, value.Value); } else { - OptionalData.SetOptionalData(ObjectOptionalDataType.OrgUsePaymentStatus, null); + OptionalData.SetOptionalData (ObjectOptionalDataType.OrgUsePaymentStatus, null); } } } @@ -842,13 +843,13 @@ namespace Swarmops.Logic.Structure Organizations line = GetLine(); BasicPersonRole[] treasurers = SwarmDb.GetDatabaseForReading() - .GetPeopleWithRoleType(RoleType.OrganizationTreasurer, line.Identities, new int[] {}); + .GetPeopleWithRoleType (RoleType.OrganizationTreasurer, line.Identities, new int[] {}); if (treasurers.Length == 0) - throw new Exception("No Treasurer Found"); + throw new Exception ("No Treasurer Found"); if (treasurers.Length == 1) - return Person.FromIdentity(treasurers[0].PersonId); + return Person.FromIdentity (treasurers[0].PersonId); for (int i = line.Count - 1; i >= 0; --i) { @@ -857,29 +858,29 @@ namespace Swarmops.Logic.Structure foreach (BasicPersonRole br in treasurers) { if (org.Identity == br.OrganizationId) - return Person.FromIdentity(br.PersonId); + return Person.FromIdentity (br.PersonId); } } - throw new Exception("No Treasurer Found"); + throw new Exception ("No Treasurer Found"); } - public Memberships GetMemberships(bool includeTerminated) + public Memberships GetMemberships (bool includeTerminated) { - return Memberships.ForOrganization(this, includeTerminated); + return Memberships.ForOrganization (this, includeTerminated); } public Memberships GetMemberships() { - return GetMemberships(false); + return GetMemberships (false); } - public static Organization Create(int parentOrganizationId, string nameInternational, string name, + public static Organization Create (int parentOrganizationId, string nameInternational, string name, string nameShort, string domain, string mailPrefix, int anchorGeographyId, bool acceptsMembers, bool autoAssignNewMembers, int defaultCountryId) { - return FromIdentityAggressive(OrganizationCache.CreateOrganization(parentOrganizationId, + return FromIdentityAggressive (OrganizationCache.CreateOrganization (parentOrganizationId, nameInternational, name, nameShort, @@ -891,13 +892,13 @@ namespace Swarmops.Logic.Structure defaultCountryId)); } - [Obsolete("Never use this function. Mark the organization as unused. Records are needed for history.", true)] + [Obsolete ("Never use this function. Mark the organization as unused. Records are needed for history.", true)] public void Delete() { string problems = ""; int ChildrenCount = Children.Count; - int ActiveMembershipsCount = GetMemberships(false).Count; - int HistoricalMembershipsCount = GetMemberships(true).Count - ActiveMembershipsCount; + int ActiveMembershipsCount = GetMemberships (false).Count; + int HistoricalMembershipsCount = GetMemberships (true).Count - ActiveMembershipsCount; if (ChildrenCount > 0) problems += ChildrenCount + " child organisations\n\r"; @@ -909,26 +910,26 @@ namespace Swarmops.Logic.Structure problems += HistoricalMembershipsCount + " historical memberships\n\r"; if (problems != "") - throw new Exception("Can not delete because:\n\r" + problems); + throw new Exception ("Can not delete because:\n\r" + problems); // OrganizationCache.DeleteOrganization(this.Identity); -- commented out because OrganizationCache.Delete is also marked obsolete } - public static void UpdateOrganization(int ParentOrganizationId, string NameInternational, string Name, + public static void UpdateOrganization (int ParentOrganizationId, string NameInternational, string Name, string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId, int OrganizationId) { - OrganizationCache.UpdateOrganization(ParentOrganizationId, NameInternational, Name, NameShort, Domain, + OrganizationCache.UpdateOrganization (ParentOrganizationId, NameInternational, Name, NameShort, Domain, MailPrefix, AnchorGeographyId, AcceptsMembers, AutoAssignNewMembers, DefaultCountryId, OrganizationId); } - public DateTime GetEndOfFiscalYear(int year) + public DateTime GetEndOfFiscalYear (int year) { // Returns the last millisecond of the fiscal year. For now, this is limited to calendar years; the function // is placed here for future flexibility. - return new DateTime(year, 12, 31, 23, 59, 59, 999); + return new DateTime (year, 12, 31, 23, 59, 59, 999); } } } \ No newline at end of file diff --git a/Logic/Structure/OrganizationParameters.cs b/Logic/Structure/OrganizationParameters.cs index 5436c85a..489fdbb9 100644 --- a/Logic/Structure/OrganizationParameters.cs +++ b/Logic/Structure/OrganizationParameters.cs @@ -8,24 +8,24 @@ namespace Swarmops.Logic.Structure private readonly ObjectOptionalData data; private readonly Organization organization; - public OrganizationParameters(Organization organization) + public OrganizationParameters (Organization organization) { this.organization = organization; - this.data = ObjectOptionalData.ForObject(organization); + this.data = ObjectOptionalData.ForObject (organization); } public bool EconomyEnabled { get { - if (this.data.HasData(ObjectOptionalDataType.OrgEconomyEnabled)) + if (this.data.HasData (ObjectOptionalDataType.OrgEconomyEnabled)) { - return this.data.GetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled); + return this.data.GetOptionalDataBool (ObjectOptionalDataType.OrgEconomyEnabled); } if (this.organization.Identity == 1) // temp { - this.data.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); + this.data.SetOptionalDataBool (ObjectOptionalDataType.OrgEconomyEnabled, true); } return false; @@ -37,7 +37,7 @@ namespace Swarmops.Logic.Structure { get { - int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear); + int year = this.data.GetOptionalDataInt (ObjectOptionalDataType.OrgFirstFiscalYear); return year; } } @@ -47,11 +47,11 @@ namespace Swarmops.Logic.Structure { get { - int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); + int year = this.data.GetOptionalDataInt (ObjectOptionalDataType.OrgBooksClosedForYear); return year; } - set { this.data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, value); } + set { this.data.SetOptionalDataInt (ObjectOptionalDataType.OrgBooksClosedForYear, value); } } @@ -59,11 +59,11 @@ namespace Swarmops.Logic.Structure { get { - int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); + int year = this.data.GetOptionalDataInt (ObjectOptionalDataType.OrgBooksClosedForYear); if (year == 0 && this.organization.Identity == 1) { - this.data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, 2009); + this.data.SetOptionalDataInt (ObjectOptionalDataType.OrgBooksClosedForYear, 2009); return 2009; } @@ -75,12 +75,12 @@ namespace Swarmops.Logic.Structure { get { - string taxAccount = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount); + string taxAccount = this.data.GetOptionalDataString (ObjectOptionalDataType.OrgTaxAccount); - if (string.IsNullOrEmpty(taxAccount) && this.organization.Identity == 1) + if (string.IsNullOrEmpty (taxAccount) && this.organization.Identity == 1) { taxAccount = "Bg 5050-1055"; - this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount, taxAccount); + this.data.SetOptionalDataString (ObjectOptionalDataType.OrgTaxAccount, taxAccount); } return taxAccount; @@ -91,12 +91,12 @@ namespace Swarmops.Logic.Structure { get { - string taxOcr = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr); + string taxOcr = this.data.GetOptionalDataString (ObjectOptionalDataType.OrgTaxOcr); - if (string.IsNullOrEmpty(taxOcr) && this.organization.Identity == 1) + if (string.IsNullOrEmpty (taxOcr) && this.organization.Identity == 1) { taxOcr = "1680243045141"; - this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr, taxOcr); + this.data.SetOptionalDataString (ObjectOptionalDataType.OrgTaxOcr, taxOcr); } return taxOcr; @@ -107,32 +107,32 @@ namespace Swarmops.Logic.Structure { get { - string accessList = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead); + string accessList = this.data.GetOptionalDataString (ObjectOptionalDataType.OrgTemporaryAccessListRead); - if (string.IsNullOrEmpty(accessList)) + if (string.IsNullOrEmpty (accessList)) { accessList = string.Empty; } return accessList; } - set { this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead, value); } + set { this.data.SetOptionalDataString (ObjectOptionalDataType.OrgTemporaryAccessListRead, value); } } public string TemporaryAccessListWrite { get { - string accessList = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite); + string accessList = this.data.GetOptionalDataString (ObjectOptionalDataType.OrgTemporaryAccessListWrite); - if (string.IsNullOrEmpty(accessList)) + if (string.IsNullOrEmpty (accessList)) { accessList = "1"; // Priming new organizations with the sysadmin account } return accessList; } - set { this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite, value); } + set { this.data.SetOptionalDataString (ObjectOptionalDataType.OrgTemporaryAccessListWrite, value); } } } } \ No newline at end of file diff --git a/Logic/Structure/Organizations.cs b/Logic/Structure/Organizations.cs index 74a3ced1..254e2add 100644 --- a/Logic/Structure/Organizations.cs +++ b/Logic/Structure/Organizations.cs @@ -12,32 +12,32 @@ namespace Swarmops.Logic.Structure { #region Creation and Construction - public static Organizations FromSingle(Organization organization) + public static Organizations FromSingle (Organization organization) { Organizations result = new Organizations {organization}; return result; } - public static Organizations FromArray(Organization[] organizationArray) + public static Organizations FromArray (Organization[] organizationArray) { Organizations result = new Organizations {Capacity = (organizationArray.Length*11/10)}; foreach (Organization organization in organizationArray) { - result.Add(organization); + result.Add (organization); } return result; } - public static Organizations FromArray(BasicOrganization[] organizationArray) + public static Organizations FromArray (BasicOrganization[] organizationArray) { Organizations result = new Organizations {Capacity = (organizationArray.Length*11/10)}; foreach (BasicOrganization basic in organizationArray) { - result.Add(Organization.FromBasic(basic)); + result.Add (Organization.FromBasic (basic)); } return result; @@ -45,32 +45,32 @@ namespace Swarmops.Logic.Structure public static Organizations GetAll() { - return FromArray(OrganizationCache.GetAll()); + return FromArray (OrganizationCache.GetAll()); } - public static Organizations FromIdentities(int[] organizationIds) + public static Organizations FromIdentities (int[] organizationIds) { List foundOrgs = new List(); foreach (int id in organizationIds) { - foundOrgs.Add(Organization.FromIdentity(id)); + foundOrgs.Add (Organization.FromIdentity (id)); } - return FromArray(foundOrgs.ToArray()); + return FromArray (foundOrgs.ToArray()); } - public static Organizations GetOrganizationsAvailableAtGeography(int geographyId) + public static Organizations GetOrganizationsAvailableAtGeography (int geographyId) { - BasicGeography[] nodeLine = GeographyCache.GetGeographyLine(geographyId); - return FromIdentities(OrganizationCache.GetOrganizationsIdsInGeographies(nodeLine)); + BasicGeography[] nodeLine = GeographyCache.GetGeographyLine (geographyId); + return FromIdentities (OrganizationCache.GetOrganizationsIdsInGeographies (nodeLine)); } - public static Organizations GetAllOrganizationsAvailableAtGeography(int geographyId) + public static Organizations GetAllOrganizationsAvailableAtGeography (int geographyId) { List nodeList = new List(); - nodeList.AddRange(GeographyCache.GetGeographyLine(geographyId)); - nodeList.AddRange(GeographyCache.GetGeographyTree(geographyId)); + nodeList.AddRange (GeographyCache.GetGeographyLine (geographyId)); + nodeList.AddRange (GeographyCache.GetGeographyTree (geographyId)); - return FromIdentities(OrganizationCache.GetOrganizationsIdsInGeographies(nodeList.ToArray())); + return FromIdentities (OrganizationCache.GetOrganizationsIdsInGeographies (nodeList.ToArray())); } #endregion @@ -114,7 +114,7 @@ namespace Swarmops.Logic.Structure // Therefore, the current organization is already present in the collection, // as a child of the compared organization. It can be safely removed. - remaining.Remove(currentOrg.Identity); + remaining.Remove (currentOrg.Identity); break; } } @@ -127,7 +127,7 @@ namespace Swarmops.Logic.Structure foreach (int organizationId in remaining.Keys) { - result.Add(remaining[organizationId]); + result.Add (remaining[organizationId]); } return result; @@ -155,7 +155,7 @@ namespace Swarmops.Logic.Structure foreach (Organization org in table.Values) { - result.Add(org); + result.Add (org); } return result; @@ -165,7 +165,7 @@ namespace Swarmops.Logic.Structure #region Logical Operators (And, Or) - public static Organizations LogicalOr(Organizations set1, Organizations set2) + public static Organizations LogicalOr (Organizations set1, Organizations set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -200,13 +200,13 @@ namespace Swarmops.Logic.Structure foreach (Organization org in table.Values) { - result.Add(org); + result.Add (org); } return result; } - public static Organizations LogicalAnd(Organizations set1, Organizations set2) + public static Organizations LogicalAnd (Organizations set1, Organizations set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -235,23 +235,23 @@ namespace Swarmops.Logic.Structure Organizations result = new Organizations(); foreach (Organization org in set1) { - if (set2Lookup.ContainsKey(org.Identity)) + if (set2Lookup.ContainsKey (org.Identity)) { - result.Add(org); + result.Add (org); } } return result; } - public Organizations LogicalAnd(Organizations set2) + public Organizations LogicalAnd (Organizations set2) { - return LogicalAnd(this, set2); + return LogicalAnd (this, set2); } - public Organizations LogicalOr(Organizations set2) + public Organizations LogicalOr (Organizations set2) { - return LogicalOr(this, set2); + return LogicalOr (this, set2); } #endregion @@ -272,7 +272,7 @@ namespace Swarmops.Logic.Structure { if (organization.IsEconomyEnabled) { - result.Add(organization); + result.Add (organization); } } @@ -282,32 +282,32 @@ namespace Swarmops.Logic.Structure public int[] Identities { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + get { return LogicServices.ObjectsToIdentifiers (ToArray()); } } public int GetMembershipCount() { - return Memberships.GetMemberCountForOrganizations(this); + return Memberships.GetMemberCountForOrganizations (this); } public int GetMemberCount() { - return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizations(Identities); + return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizations (Identities); } - public int GetMemberCountForGeographies(Geographies geographies) + public int GetMemberCountForGeographies (Geographies geographies) { - return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizationsAndGeographies(Identities, + return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizationsAndGeographies (Identities, geographies.Identities); } - public int GetRoleHolderCountForGeographies(Geographies geographies) + public int GetRoleHolderCountForGeographies (Geographies geographies) { Dictionary result = new Dictionary(); BasicPersonRole[] personRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies (Identities, geographies.Identities); foreach (BasicPersonRole role in personRoles) @@ -319,12 +319,12 @@ namespace Swarmops.Logic.Structure } - public People GetRoleHoldersForGeographies(Geographies geographies) + public People GetRoleHoldersForGeographies (Geographies geographies) { Dictionary result = new Dictionary(); BasicPersonRole[] personRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies (Identities, geographies.Identities); foreach (BasicPersonRole role in personRoles) @@ -336,10 +336,10 @@ namespace Swarmops.Logic.Structure foreach (int key in result.Keys) { - list.Add(key); + list.Add (key); } - return People.FromIdentities(list.ToArray()); + return People.FromIdentities (list.ToArray()); } #endregion @@ -349,13 +349,13 @@ namespace Swarmops.Logic.Structure // -------------------------------------------- - public static Organization GetMostLocalOrganization(int geographyId, int rootOrganizationId) + public static Organization GetMostLocalOrganization (int geographyId, int rootOrganizationId) { // This function returns the most local organization in a tree under "rootOrganizationId". // First, find all possible organizations at the particular geography: - Organizations orgList = GetOrganizationsAvailableAtGeography(geographyId); + Organizations orgList = GetOrganizationsAvailableAtGeography (geographyId); // Second, only note those that inherit from the supplied root: @@ -363,7 +363,7 @@ namespace Swarmops.Logic.Structure foreach (Organization org in orgList) { - if (org.IsOrInherits(rootOrganizationId)) + if (org.IsOrInherits (rootOrganizationId)) { table[org.OrganizationId] = org; } @@ -376,8 +376,8 @@ namespace Swarmops.Logic.Structure { // No organizations! - throw new ArgumentException( - string.Format( + throw new ArgumentException ( + string.Format ( "No organizations eligible under supplied organization ({0}) for supplied geography({1})", rootOrganizationId, geographyId)); } @@ -389,7 +389,7 @@ namespace Swarmops.Logic.Structure { foreach (Geography uptakeGeo in org.UptakeGeographies) { - Geographies geoLine = Geography.FromIdentity(org.AnchorGeographyId).GetLine(); + Geographies geoLine = Geography.FromIdentity (org.AnchorGeographyId).GetLine(); if (geoLine.Count > maxLength && org.AutoAssignNewMembers) { bestFit = org; diff --git a/Logic/Structure/PostalCode.cs b/Logic/Structure/PostalCode.cs index 78bbb441..32c2ced0 100644 --- a/Logic/Structure/PostalCode.cs +++ b/Logic/Structure/PostalCode.cs @@ -6,26 +6,26 @@ namespace Swarmops.Logic.Structure [Serializable] public class PostalCode : BasicPostalCode { - private PostalCode(BasicPostalCode basic) : - base(basic) + private PostalCode (BasicPostalCode basic) : + base (basic) { // constructor } - [Obsolete("Do not call this constructor directly. It is intended only for serialization.", true)] - public PostalCode() : base(0, string.Empty, 0, 0) + [Obsolete ("Do not call this constructor directly. It is intended only for serialization.", true)] + public PostalCode() : base (0, string.Empty, 0, 0) { // this ctor does NOT initialize the instance. It is provided to allow for serialization. } public Country Country { - get { return Country.FromIdentity(CountryId); } + get { return Country.FromIdentity (CountryId); } } public City City { - get { return City.FromIdentity(CityId); } + get { return City.FromIdentity (CityId); } } public string CityName @@ -33,9 +33,9 @@ namespace Swarmops.Logic.Structure get { return City.Name; } } - public static PostalCode FromBasic(BasicPostalCode basic) + public static PostalCode FromBasic (BasicPostalCode basic) { - return new PostalCode(basic); + return new PostalCode (basic); } } } \ No newline at end of file diff --git a/Logic/Structure/PostalCodes.cs b/Logic/Structure/PostalCodes.cs index d30e6190..e15d6dfe 100644 --- a/Logic/Structure/PostalCodes.cs +++ b/Logic/Structure/PostalCodes.cs @@ -8,26 +8,26 @@ namespace Swarmops.Logic.Structure [Serializable] public class PostalCodes : List { - public static PostalCodes FromArray(BasicPostalCode[] array) + public static PostalCodes FromArray (BasicPostalCode[] array) { PostalCodes result = new PostalCodes {Capacity = (array.Length*11/10)}; foreach (BasicPostalCode basic in array) { - result.Add(PostalCode.FromBasic(basic)); + result.Add (PostalCode.FromBasic (basic)); } return result; } - public static PostalCodes ForCountry(string countryCode) + public static PostalCodes ForCountry (string countryCode) { - return ForCountry(Country.FromCode(countryCode).Identity); + return ForCountry (Country.FromCode (countryCode).Identity); } - public static PostalCodes ForCountry(int countryId) + public static PostalCodes ForCountry (int countryId) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPostalCodesForCountry(countryId)); + return FromArray (SwarmDb.GetDatabaseForReading().GetPostalCodesForCountry (countryId)); } } } \ No newline at end of file diff --git a/Logic/Structure/UptakeGeography.cs b/Logic/Structure/UptakeGeography.cs index 369de96a..5c4266c9 100644 --- a/Logic/Structure/UptakeGeography.cs +++ b/Logic/Structure/UptakeGeography.cs @@ -12,20 +12,20 @@ namespace Swarmops.Logic.Structure { } // disallow public direct construction - private UptakeGeography(BasicUptakeGeography basic) - : base(basic) + private UptakeGeography (BasicUptakeGeography basic) + : base (basic) { } - protected UptakeGeography(UptakeGeography other) - : base(other) + protected UptakeGeography (UptakeGeography other) + : base (other) { } - public static UptakeGeography FromBasic(BasicUptakeGeography basic) + public static UptakeGeography FromBasic (BasicUptakeGeography basic) { - return new UptakeGeography(basic); + return new UptakeGeography (basic); } #endregion @@ -51,16 +51,16 @@ namespace Swarmops.Logic.Structure get { if (this.geography == null) - this.geography = Geography.FromIdentity(GeoId); + this.geography = Geography.FromIdentity (GeoId); return this.geography; } protected set { if (Organization != null) - Organization.DeleteUptakeGeography(GeoId); + Organization.DeleteUptakeGeography (GeoId); if (value != null && Organization != null) - Organization.AddUptakeGeography(value.GeographyId); + Organization.AddUptakeGeography (value.GeographyId); this.geography = value; } @@ -71,16 +71,16 @@ namespace Swarmops.Logic.Structure get { if (this.organization == null) - this.organization = Organization.FromIdentity(OrgId); + this.organization = Organization.FromIdentity (OrgId); return this.organization; } protected set { if (Organization != null) - Organization.DeleteUptakeGeography(GeoId); + Organization.DeleteUptakeGeography (GeoId); if (value != null) - value.AddUptakeGeography(GeoId); + value.AddUptakeGeography (GeoId); this.organization = value; } } diff --git a/Logic/Support/ActivistEvents.cs b/Logic/Support/ActivistEvents.cs index 8bcbde3e..a8e98a19 100644 --- a/Logic/Support/ActivistEvents.cs +++ b/Logic/Support/ActivistEvents.cs @@ -6,10 +6,10 @@ namespace Swarmops.Logic.Support { public class ActivistEvents { - public static void TerminateActivistWithLogging(Person p, EventSource eventSourceSignupPage) + public static void TerminateActivistWithLogging (Person p, EventSource eventSourceSignupPage) { int orgId = 1; - PWEvents.CreateEvent(eventSourceSignupPage, + PWEvents.CreateEvent (eventSourceSignupPage, EventType.LostActivist, p.Identity, orgId, @@ -18,14 +18,14 @@ namespace Swarmops.Logic.Support 0, string.Empty); p.TerminateActivist(); - PWLog.Write(PWLogItem.Person, p.Identity, PWLogAction.ActivistLost, "Lost as activist", string.Empty); + PWLog.Write (PWLogItem.Person, p.Identity, PWLogAction.ActivistLost, "Lost as activist", string.Empty); } - public static void CreateActivistWithLogging(Geography geo, Person newActivist, string logMessage, + public static void CreateActivistWithLogging (Geography geo, Person newActivist, string logMessage, EventSource evtSrc, bool isPublic, bool isConfirmed, int orgId) { - PWEvents.CreateEvent(evtSrc, + PWEvents.CreateEvent (evtSrc, EventType.NewActivist, newActivist.Identity, orgId, @@ -33,8 +33,8 @@ namespace Swarmops.Logic.Support newActivist.Identity, 0, string.Empty); - newActivist.CreateActivist(isPublic, isConfirmed); - PWLog.Write(newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, + newActivist.CreateActivist (isPublic, isConfirmed); + PWLog.Write (newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, "New activist joined.", logMessage); } } diff --git a/Logic/Support/CheckDigit.cs b/Logic/Support/CheckDigit.cs index c35e537e..fdddf4d7 100644 --- a/Logic/Support/CheckDigit.cs +++ b/Logic/Support/CheckDigit.cs @@ -73,15 +73,15 @@ namespace Swarmops.Logic.Support /// /// The string for which the check digit is to be calculated. /// The input with the calculated check digit appended. - public static string AppendCheckDigit(string input) + public static string AppendCheckDigit (string input) { - int[] resultArray = Instance._AppendCheckDigit(_ConvertToIntArray(input)); + int[] resultArray = Instance._AppendCheckDigit (_ConvertToIntArray (input)); StringBuilder resultString = new StringBuilder(); for (int i = 0; i < resultArray.Length; i++) { - resultString.Append(resultArray[i]); + resultString.Append (resultArray[i]); } return resultString.ToString(); @@ -93,10 +93,10 @@ namespace Swarmops.Logic.Support /// /// The long integer for which the check digit is to be calculated. /// The input with the calculated check digit appended. - public static long AppendCheckDigit(long input) + public static long AppendCheckDigit (long input) { - int[] resultArray = Instance._AppendCheckDigit(_ConvertToIntArray(input)); - return _ConvertToLong(resultArray); + int[] resultArray = Instance._AppendCheckDigit (_ConvertToIntArray (input)); + return _ConvertToLong (resultArray); } /// @@ -105,10 +105,10 @@ namespace Swarmops.Logic.Support /// /// The integer for which the check digit is to be calculated. /// The input with the calculated check digit appended. - public static int AppendCheckDigit(int input) + public static int AppendCheckDigit (int input) { - int[] resultArray = Instance._AppendCheckDigit(_ConvertToIntArray(input)); - long resultLong = _ConvertToLong(resultArray); + int[] resultArray = Instance._AppendCheckDigit (_ConvertToIntArray (input)); + long resultLong = _ConvertToLong (resultArray); return (int) resultLong; } @@ -118,9 +118,9 @@ namespace Swarmops.Logic.Support /// /// The integer array for which the check digit is to be calculated. /// The input with the calculated check digit appended. - public static int[] AppendCheckDigit(int[] input) + public static int[] AppendCheckDigit (int[] input) { - return Instance._AppendCheckDigit(input); + return Instance._AppendCheckDigit (input); } //----------------------------------------------------------------------------------------------- @@ -135,9 +135,9 @@ namespace Swarmops.Logic.Support /// /// The string for which the check digit is to be calculated. /// The check digit for the input. - public static int CalculateCheckDigit(string input) + public static int CalculateCheckDigit (string input) { - return Instance._CalculateCheckDigit(_ConvertToIntArray(input)); + return Instance._CalculateCheckDigit (_ConvertToIntArray (input)); } /// @@ -145,9 +145,9 @@ namespace Swarmops.Logic.Support /// /// The long integer for which the check digit is to be calculated. /// The check digit for the input. - public static int CalculateCheckDigit(long input) + public static int CalculateCheckDigit (long input) { - return Instance._CalculateCheckDigit(_ConvertToIntArray(input)); + return Instance._CalculateCheckDigit (_ConvertToIntArray (input)); } /// @@ -155,9 +155,9 @@ namespace Swarmops.Logic.Support /// /// The integer for which the check digit is to be calculated. /// The check digit for the input. - public static int CalculateCheckDigit(int input) + public static int CalculateCheckDigit (int input) { - return Instance._CalculateCheckDigit(_ConvertToIntArray(input)); + return Instance._CalculateCheckDigit (_ConvertToIntArray (input)); } /// @@ -165,9 +165,9 @@ namespace Swarmops.Logic.Support /// /// The integer array for which the check digit is to be calculated. /// The check digit for the input. - public static int CalculateCheckDigit(int[] input) + public static int CalculateCheckDigit (int[] input) { - return Instance._CalculateCheckDigit(input); + return Instance._CalculateCheckDigit (input); } //----------------------------------------------------------------------------------------------- @@ -188,9 +188,9 @@ namespace Swarmops.Logic.Support /// Returns true if the last digit of the input is the valid check digit for /// the input. Otherwise returns false. /// - public static bool Check(string input) + public static bool Check (string input) { - return Instance._Check(_ConvertToIntArray(input)); + return Instance._Check (_ConvertToIntArray (input)); } /// @@ -204,9 +204,9 @@ namespace Swarmops.Logic.Support /// Returns true if the last digit of the input is the valid check digit for /// the input. Otherwise returns false. /// - public static bool Check(long input) + public static bool Check (long input) { - return Instance._Check(_ConvertToIntArray(input)); + return Instance._Check (_ConvertToIntArray (input)); } /// @@ -220,9 +220,9 @@ namespace Swarmops.Logic.Support /// Returns true if the last digit of the input is the valid check digit for /// the input. Otherwise returns false. /// - public static bool Check(int input) + public static bool Check (int input) { - return Instance._Check(_ConvertToIntArray(input)); + return Instance._Check (_ConvertToIntArray (input)); } /// @@ -237,9 +237,9 @@ namespace Swarmops.Logic.Support /// Returns true if the last digit of the input is the valid check digit for /// the input. Otherwise returns false. /// - public static bool Check(int[] input) + public static bool Check (int[] input) { - return Instance._Check(input); + return Instance._Check (input); } /// @@ -254,9 +254,9 @@ namespace Swarmops.Logic.Support /// Returns true if the check digit is valid for /// the input. Otherwise returns false. /// - public static bool Check(string input, int checkDigit) + public static bool Check (string input, int checkDigit) { - return Instance._Check(_ConvertToIntArray(input), checkDigit); + return Instance._Check (_ConvertToIntArray (input), checkDigit); } /// @@ -271,9 +271,9 @@ namespace Swarmops.Logic.Support /// Returns true if the check digit is valid for /// the input. Otherwise returns false. /// - public static bool Check(long input, int checkDigit) + public static bool Check (long input, int checkDigit) { - return Instance._Check(_ConvertToIntArray(input), checkDigit); + return Instance._Check (_ConvertToIntArray (input), checkDigit); } /// @@ -288,9 +288,9 @@ namespace Swarmops.Logic.Support /// Returns true if the check digit is valid for /// the input. Otherwise returns false. /// - public static bool Check(int input, int checkDigit) + public static bool Check (int input, int checkDigit) { - return Instance._Check(_ConvertToIntArray(input), checkDigit); + return Instance._Check (_ConvertToIntArray (input), checkDigit); } /// @@ -305,9 +305,9 @@ namespace Swarmops.Logic.Support /// Returns true if the check digit is valid for /// the input. Otherwise returns false. /// - public static bool Check(int[] input, int checkDigit) + public static bool Check (int[] input, int checkDigit) { - return Instance._Check(input, checkDigit); + return Instance._Check (input, checkDigit); } //----------------------------------------------------------------------------------------------- @@ -340,27 +340,27 @@ namespace Swarmops.Logic.Support #region Private Static Methods //----------------------------------------------------------------------------------------------- - private static int[] _ConvertToIntArray(string input) + private static int[] _ConvertToIntArray (string input) { int[] inputArray = new int[input.Length]; for (int i = 0; i < input.Length; i++) - inputArray[i] = Convert.ToInt32(input.Substring(i, 1)); + inputArray[i] = Convert.ToInt32 (input.Substring (i, 1)); return inputArray; } - private static int[] _ConvertToIntArray(long input) + private static int[] _ConvertToIntArray (long input) { - return _ConvertToIntArray(input.ToString()); + return _ConvertToIntArray (input.ToString()); } - private static int[] _ConvertToIntArray(int input) + private static int[] _ConvertToIntArray (int input) { - return _ConvertToIntArray(input.ToString()); + return _ConvertToIntArray (input.ToString()); } - private static long _ConvertToLong(int[] input) + private static long _ConvertToLong (int[] input) { long result = 0; long power = 1; @@ -381,17 +381,17 @@ namespace Swarmops.Logic.Support #region Private Instance Methods //----------------------------------------------------------------------------------------------- - private int[] _AppendCheckDigit(int[] input) + private int[] _AppendCheckDigit (int[] input) { - int checkDigit = _CalculateCheckDigit(input); + int checkDigit = _CalculateCheckDigit (input); int[] result = new int[input.Length + 1]; - input.CopyTo(result, 0); + input.CopyTo (result, 0); result[result.Length - 1] = checkDigit; return result; } - private int _CalculateCheckDigit(int[] input) + private int _CalculateCheckDigit (int[] input) { // First we need to reverse the order of the input digits int[] reversedInput = new int[input.Length]; @@ -406,7 +406,7 @@ namespace Swarmops.Logic.Support return checkDigit; } - private bool _Check(int[] input) + private bool _Check (int[] input) { // First we need to reverse the order of the input digits int[] reversedInput = new int[input.Length]; @@ -420,12 +420,12 @@ namespace Swarmops.Logic.Support return (check == 0); } - private bool _Check(int[] input, int checkDigit) + private bool _Check (int[] input, int checkDigit) { int[] newInput = new int[input.Length + 1]; - input.CopyTo(newInput, 0); + input.CopyTo (newInput, 0); newInput[newInput.Length - 1] = checkDigit; - return _Check(newInput); + return _Check (newInput); } //----------------------------------------------------------------------------------------------- diff --git a/Logic/Support/DatabaseMaintenance.cs b/Logic/Support/DatabaseMaintenance.cs index d8e090c1..dc884efc 100644 --- a/Logic/Support/DatabaseMaintenance.cs +++ b/Logic/Support/DatabaseMaintenance.cs @@ -25,7 +25,7 @@ namespace Swarmops.Logic.Support try { - personOne = Person.FromIdentity(1); + personOne = Person.FromIdentity (1); initialized = true; } catch (Exception) @@ -36,25 +36,25 @@ namespace Swarmops.Logic.Support if (initialized && personOne != null) // double checks in case Database behavior should change to return null rather than throw later { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Cannot run Genesis Device style initalization on already-populated database"); } using (WebClient client = new WebClient()) { - sql = client.DownloadString("http://packages.swarmops.com/schemata/initialize.sql"); - // Hardcoded as security measure - don't want to pass arbitrary sql in from web layer + sql = client.DownloadString ("http://packages.swarmops.com/schemata/initialize.sql"); + // Hardcoded as security measure - don't want to pass arbitrary sql in from web layer } - string[] sqlCommands = sql.Split('#'); - // in the file, the commands are split by a single # sign. (Semicolons are an integral part of storedprocs, so they can't be used.) + string[] sqlCommands = sql.Split ('#'); + // in the file, the commands are split by a single # sign. (Semicolons are an integral part of storedprocs, so they can't be used.) foreach (string sqlCommand in sqlCommands) { - SwarmDb.GetDatabaseForAdmin().ExecuteAdminCommand(sqlCommand.Trim()); + SwarmDb.GetDatabaseForAdmin().ExecuteAdminCommand (sqlCommand.Trim()); } - SwarmDb.GetDatabaseForWriting().SetKeyValue("DbVersion", "1"); // We're at baseline + SwarmDb.GetDatabaseForWriting().SetKeyValue ("DbVersion", "1"); // We're at baseline } public static void UpgradeSchemata() @@ -68,27 +68,27 @@ namespace Swarmops.Logic.Support { currentDbVersion++; - string fileName = String.Format("http://packages.swarmops.com/schemata/upgrade-{0:D4}.sql", + string fileName = String.Format ("http://packages.swarmops.com/schemata/upgrade-{0:D4}.sql", currentDbVersion); using (WebClient client = new WebClient()) { - sql = client.DownloadString(fileName); + sql = client.DownloadString (fileName); } - string[] sqlCommands = sql.Split('#'); - // in the file, the commands are split by a single # sign. (Semicolons are an integral part of storedprocs, so they can't be used.) + string[] sqlCommands = sql.Split ('#'); + // in the file, the commands are split by a single # sign. (Semicolons are an integral part of storedprocs, so they can't be used.) foreach (string sqlCommand in sqlCommands) { try { - SwarmDb.GetDatabaseForAdmin().ExecuteAdminCommand(sqlCommand.Trim()); + SwarmDb.GetDatabaseForAdmin().ExecuteAdminCommand (sqlCommand.Trim()); } catch (MySqlException exception) { SwarmDb.GetDatabaseForWriting() - .CreateExceptionLogEntry(DateTime.UtcNow, "DatabaseUpgrade", exception); + .CreateExceptionLogEntry (DateTime.UtcNow, "DatabaseUpgrade", exception); // Continue processing after logging error. // TODO: Throw and abort? Tricky decision @@ -97,15 +97,15 @@ namespace Swarmops.Logic.Support upgraded = true; SwarmDb.GetDatabaseForWriting() - .SetKeyValue("DbVersion", currentDbVersion.ToString(CultureInfo.InvariantCulture)); - // Increment after each successful run + .SetKeyValue ("DbVersion", currentDbVersion.ToString (CultureInfo.InvariantCulture)); + // Increment after each successful run } if (upgraded) { try { - OutboundComm.CreateNotification(null, NotificationResource.System_DatabaseSchemaUpgraded); + OutboundComm.CreateNotification (null, NotificationResource.System_DatabaseSchemaUpgraded); } catch (ArgumentException) { diff --git a/Logic/Support/Document.cs b/Logic/Support/Document.cs index a7d79cd4..c4aea074 100644 --- a/Logic/Support/Document.cs +++ b/Logic/Support/Document.cs @@ -14,7 +14,7 @@ namespace Swarmops.Logic.Support { public class Document : BasicDocument { - private Document(BasicDocument document) : base(document) + private Document (BasicDocument document) : base (document) { } @@ -23,7 +23,7 @@ namespace Swarmops.Logic.Support get { return base.ServerFileName; } set { - SwarmDb.GetDatabaseForWriting().SetDocumentServerFileName(Identity, value); + SwarmDb.GetDatabaseForWriting().SetDocumentServerFileName (Identity, value); base.ServerFileName = value; } } @@ -35,23 +35,23 @@ namespace Swarmops.Logic.Support switch (DocumentType) { case DocumentType.ExpenseClaim: - return ExpenseClaim.FromIdentity(ForeignId); + return ExpenseClaim.FromIdentity (ForeignId); case DocumentType.FinancialTransaction: - return FinancialTransaction.FromIdentity(ForeignId); + return FinancialTransaction.FromIdentity (ForeignId); case DocumentType.InboundInvoice: - return InboundInvoice.FromIdentity(ForeignId); + return InboundInvoice.FromIdentity (ForeignId); case DocumentType.PaperLetter: - return PaperLetter.FromIdentity(ForeignId); + return PaperLetter.FromIdentity (ForeignId); case DocumentType.PayrollItem: - return PayrollItem.FromIdentity(ForeignId); + return PayrollItem.FromIdentity (ForeignId); default: - throw new NotImplementedException("DocumentType needs implementation: " + - DocumentType.ToString()); + throw new NotImplementedException ("DocumentType needs implementation: " + + DocumentType.ToString()); } } } @@ -71,34 +71,34 @@ namespace Swarmops.Logic.Support } } - public static Document FromIdentity(int documentId) + public static Document FromIdentity (int documentId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetDocument(documentId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetDocument (documentId)); } - public static Document FromIdentityAggressive(int documentId) + public static Document FromIdentityAggressive (int documentId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetDocument(documentId)); - // "For writing" is intentional - bypasses a race condition in replication + return FromBasic (SwarmDb.GetDatabaseForWriting().GetDocument (documentId)); + // "For writing" is intentional - bypasses a race condition in replication } - public static Document FromBasic(BasicDocument basicDocument) + public static Document FromBasic (BasicDocument basicDocument) { - return new Document(basicDocument); + return new Document (basicDocument); } - public static Document Create(string serverFileName, string clientFileName, Int64 fileSize, + public static Document Create (string serverFileName, string clientFileName, Int64 fileSize, string description, IHasIdentity identifiableObject, Person uploader) { int newDocumentId = SwarmDb.GetDatabaseForWriting(). - CreateDocument(serverFileName, clientFileName, fileSize, description, - GetDocumentTypeForObject(identifiableObject), + CreateDocument (serverFileName, clientFileName, fileSize, description, + GetDocumentTypeForObject (identifiableObject), identifiableObject == null ? 0 : identifiableObject.Identity, uploader.Identity); - return FromIdentityAggressive(newDocumentId); + return FromIdentityAggressive (newDocumentId); } - public static DocumentType GetDocumentTypeForObject(IHasIdentity foreignObject) + public static DocumentType GetDocumentTypeForObject (IHasIdentity foreignObject) { if (foreignObject == null) { @@ -136,14 +136,14 @@ namespace Swarmops.Logic.Support } else { - throw new ArgumentException("Unrecognized foreign object type:" + foreignObject.GetType().ToString()); + throw new ArgumentException ("Unrecognized foreign object type:" + foreignObject.GetType().ToString()); } } - public void SetForeignObject(IHasIdentity foreignObject) + public void SetForeignObject (IHasIdentity foreignObject) { SwarmDb.GetDatabaseForWriting() - .SetDocumentForeignObject(Identity, GetDocumentTypeForObject(foreignObject), foreignObject.Identity); + .SetDocumentForeignObject (Identity, GetDocumentTypeForObject (foreignObject), foreignObject.Identity); } @@ -151,19 +151,19 @@ namespace Swarmops.Logic.Support { // Unlink, actually - SetForeignObject(new TemporaryIdentity(0)); - File.Delete(StorageRoot + ServerFileName); - SwarmDb.GetDatabaseForWriting().SetDocumentDescription(Identity, "Deleted"); + SetForeignObject (new TemporaryIdentity (0)); + File.Delete (StorageRoot + ServerFileName); + SwarmDb.GetDatabaseForWriting().SetDocumentDescription (Identity, "Deleted"); } - public StreamReader GetReader(Encoding encoding) + public StreamReader GetReader (Encoding encoding) { - return new StreamReader(StorageRoot + ServerFileName, encoding); + return new StreamReader (StorageRoot + ServerFileName, encoding); } - public StreamReader GetReader(int encodingCodePage) + public StreamReader GetReader (int encodingCodePage) { - return GetReader(Encoding.GetEncoding(encodingCodePage)); + return GetReader (Encoding.GetEncoding (encodingCodePage)); } } } \ No newline at end of file diff --git a/Logic/Support/Documents.cs b/Logic/Support/Documents.cs index 6f0ca8f8..654496fd 100644 --- a/Logic/Support/Documents.cs +++ b/Logic/Support/Documents.cs @@ -11,32 +11,32 @@ namespace Swarmops.Logic.Support { private IHasIdentity sourceObject; - public static Documents ForObject(IHasIdentity identifiableObject) + public static Documents ForObject (IHasIdentity identifiableObject) { Documents newInstance = - FromArray( - SwarmDb.GetDatabaseForReading().GetDocumentsForForeignObject( - Document.GetDocumentTypeForObject(identifiableObject), identifiableObject.Identity)); + FromArray ( + SwarmDb.GetDatabaseForReading().GetDocumentsForForeignObject ( + Document.GetDocumentTypeForObject (identifiableObject), identifiableObject.Identity)); newInstance.sourceObject = identifiableObject; return newInstance; } - public static Documents FromArray(BasicDocument[] basicArray) + public static Documents FromArray (BasicDocument[] basicArray) { Documents result = new Documents {Capacity = (basicArray.Length*11/10)}; foreach (BasicDocument basic in basicArray) { - result.Add(Document.FromBasic(basic)); + result.Add (Document.FromBasic (basic)); } return result; } - public Document Add(string serverFileName, string clientFileName, Int64 fileSize, + public Document Add (string serverFileName, string clientFileName, Int64 fileSize, string description, Person uploader) { // This is kind of experimental. Is it a good idea to be able to write @@ -45,31 +45,31 @@ namespace Swarmops.Logic.Support if (this.sourceObject == null) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Cannot add documents to a Documents instance that was not created from an object."); } Document newDocument = - Document.Create(serverFileName, clientFileName, fileSize, description, + Document.Create (serverFileName, clientFileName, fileSize, description, this.sourceObject, uploader); - base.Add(newDocument); + base.Add (newDocument); return newDocument; } - public static Documents RecentFromDescription(string description) + public static Documents RecentFromDescription (string description) { - return FromArray(SwarmDb.GetDatabaseForReading().GetDocumentsRecentByDescription(description)); + return FromArray (SwarmDb.GetDatabaseForReading().GetDocumentsRecentByDescription (description)); } - public void SetForeignObjectForAll(IHasIdentity foreignObject) + public void SetForeignObjectForAll (IHasIdentity foreignObject) { foreach (Document doc in this) { - doc.SetForeignObject(foreignObject); + doc.SetForeignObject (foreignObject); } } } diff --git a/Logic/Support/ExtensionMethods.cs b/Logic/Support/ExtensionMethods.cs index 8ebb949c..07ed6575 100644 --- a/Logic/Support/ExtensionMethods.cs +++ b/Logic/Support/ExtensionMethods.cs @@ -12,12 +12,12 @@ namespace System.Web.ExtensionMethods /// Set the response to be JSON format, and add appropriate headers. /// /// None. - public static void SetJson(this HttpResponse response) + public static void SetJson (this HttpResponse response) { response.ContentType = "application/json"; response.CacheControl = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"; // IE dumbfixes - response.AddHeader("Last-Modified", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)); - response.AddHeader("Pragma", "no-cache"); + response.AddHeader ("Last-Modified", DateTime.UtcNow.ToString (CultureInfo.InvariantCulture)); + response.AddHeader ("Pragma", "no-cache"); } } @@ -36,54 +36,54 @@ namespace System.Web.ExtensionMethods /// /// The that should be dumped. /// The raw HTTP request. - public static string ToRaw(this HttpRequest request) + public static string ToRaw (this HttpRequest request) { StringWriter writer = new StringWriter(); - WriteStartLine(request, writer); - WriteHeaders(request, writer); - WriteBody(request, writer); + WriteStartLine (request, writer); + WriteHeaders (request, writer); + WriteBody (request, writer); return writer.ToString(); } - public static string GetBody(this HttpRequest request) + public static string GetBody (this HttpRequest request) { StringWriter writer = new StringWriter(); - WriteBody(request, writer); + WriteBody (request, writer); return writer.ToString(); } - private static void WriteStartLine(HttpRequest request, StringWriter writer) + private static void WriteStartLine (HttpRequest request, StringWriter writer) { const string SPACE = " "; - writer.Write(request.HttpMethod); - writer.Write(SPACE + request.Url); - writer.WriteLine(SPACE + request.ServerVariables["SERVER_PROTOCOL"]); + writer.Write (request.HttpMethod); + writer.Write (SPACE + request.Url); + writer.WriteLine (SPACE + request.ServerVariables["SERVER_PROTOCOL"]); } - private static void WriteHeaders(HttpRequest request, StringWriter writer) + private static void WriteHeaders (HttpRequest request, StringWriter writer) { foreach (string key in request.Headers.AllKeys) { - writer.WriteLine("{0}: {1}", key, request.Headers[key]); + writer.WriteLine ("{0}: {1}", key, request.Headers[key]); } writer.WriteLine(); } - private static void WriteBody(HttpRequest request, StringWriter writer) + private static void WriteBody (HttpRequest request, StringWriter writer) { - StreamReader reader = new StreamReader(request.InputStream); + StreamReader reader = new StreamReader (request.InputStream); try { string body = reader.ReadToEnd(); - writer.WriteLine(body); + writer.WriteLine (body); } finally { diff --git a/Logic/Support/Formatting.cs b/Logic/Support/Formatting.cs index 916dda41..74fa380e 100644 --- a/Logic/Support/Formatting.cs +++ b/Logic/Support/Formatting.cs @@ -8,19 +8,19 @@ namespace Swarmops.Logic.Support { public static class Formatting { - public static string CleanNumber(string input) + public static string CleanNumber (string input) { - return LogicServices.CleanNumber(input); + return LogicServices.CleanNumber (input); } - public static string GeneratePassword(int length) + public static string GeneratePassword (int length) { - return Authentication.CreateRandomPassword(length); + return Authentication.CreateRandomPassword (length); } - public static bool ValidateEmailFormat(string email) + public static bool ValidateEmailFormat (string email) { string gTLD = "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|" + "mobi|museum|name|net|org|pro|tel|travel"; @@ -46,20 +46,20 @@ namespace Swarmops.Logic.Support + "va|vc|ve|vg|vi|vn|vu|" + "wf|ws|ye|yt|yu|za|zm|zw"; Regex re = - new Regex( + new Regex ( @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:" + ccTLD + "|" + gTLD + ")$", RegexOptions.IgnoreCase); - return re.IsMatch(email); + return re.IsMatch (email); } - public static string GenerateRangeString(List ids) + public static string GenerateRangeString (List ids) { - return GenerateRangeString(ids.ToArray()); + return GenerateRangeString (ids.ToArray()); } - public static string GenerateRangeString(int[] ids) + public static string GenerateRangeString (int[] ids) { if (ids.Length == 0) { @@ -99,10 +99,10 @@ namespace Swarmops.Logic.Support } } - return result.Substring(2); + return result.Substring (2); } - public static string AddLuhnChecksum(string number) + public static string AddLuhnChecksum (string number) { int sum = 0; for (int i = 0; i < number.Length; i++) @@ -116,20 +116,20 @@ namespace Swarmops.Logic.Support } - public static string ReverseString(string input) + public static string ReverseString (string input) { char[] charArray = input.ToCharArray(); - Array.Reverse(charArray); - return new string(charArray); + Array.Reverse (charArray); + return new string (charArray); } - public static string JoinIdentities(List ids) + public static string JoinIdentities (List ids) { - return JoinIdentities(ids.ToArray()); + return JoinIdentities (ids.ToArray()); } - public static string JoinIdentities(int[] ids) + public static string JoinIdentities (int[] ids) { if (ids.Length == 0) { @@ -138,12 +138,12 @@ namespace Swarmops.Logic.Support StringBuilder builder = new StringBuilder(); - builder.Append(ids[0].ToString()); + builder.Append (ids[0].ToString()); for (int index = 1; index < ids.Length; index++) { - builder.Append(","); - builder.Append(ids[index].ToString()); + builder.Append (","); + builder.Append (ids[index].ToString()); } return builder.ToString(); diff --git a/Logic/Support/Imagery.cs b/Logic/Support/Imagery.cs index da43f07e..98ae89d6 100644 --- a/Logic/Support/Imagery.cs +++ b/Logic/Support/Imagery.cs @@ -7,7 +7,7 @@ namespace Swarmops.Logic.Support { public class Imagery { - public static Image Resize(Image sourceImage, int width, int height) + public static Image Resize (Image sourceImage, int width, int height) { // Code copied from CodeProject, http://www.codeproject.com/KB/GDI-plus/imageresize.aspx @@ -27,32 +27,32 @@ namespace Swarmops.Logic.Support if (nPercentH > nPercentW) // modified: crop, don't pad { nPercent = nPercentH; - destX = Convert.ToInt16((width - - (sourceWidth*nPercent))/2); + destX = Convert.ToInt16 ((width - + (sourceWidth*nPercent))/2); } else { nPercent = nPercentW; - destY = Convert.ToInt16((height - - (sourceHeight*nPercent))/2); + destY = Convert.ToInt16 ((height - + (sourceHeight*nPercent))/2); } int destWidth = (int) (sourceWidth*nPercent); int destHeight = (int) (sourceHeight*nPercent); - Bitmap bmPhoto = new Bitmap(width, height, + Bitmap bmPhoto = new Bitmap (width, height, PixelFormat.Format24bppRgb); - bmPhoto.SetResolution(sourceImage.HorizontalResolution, + bmPhoto.SetResolution (sourceImage.HorizontalResolution, sourceImage.VerticalResolution); - Graphics grPhoto = Graphics.FromImage(bmPhoto); - grPhoto.Clear(Color.Red); + Graphics grPhoto = Graphics.FromImage (bmPhoto); + grPhoto.Clear (Color.Red); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; - grPhoto.DrawImage(sourceImage, - new Rectangle(destX, destY, destWidth, destHeight), - new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), + grPhoto.DrawImage (sourceImage, + new Rectangle (destX, destY, destWidth, destHeight), + new Rectangle (sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); diff --git a/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs b/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs index 915abd15..05af4f1c 100644 --- a/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs +++ b/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs @@ -12,7 +12,7 @@ namespace Swarmops.Logic.Support.LogEntries // empty ctor needed for serialize } - public CashAdvanceRequestedLogEntry(Person actingPerson, Person beneficiaryPerson, double amount, + public CashAdvanceRequestedLogEntry (Person actingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason) { Amount = amount; diff --git a/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs b/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs index 9a5ad3dd..1493c0f6 100644 --- a/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs +++ b/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs @@ -12,7 +12,7 @@ namespace Swarmops.Logic.Support.LogEntries // empty ctor needed for serialize } - public ExpenseClaimFiledLogEntry(Person filingPerson, Person beneficiaryPerson, double amount, + public ExpenseClaimFiledLogEntry (Person filingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason) { Amount = amount; diff --git a/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs b/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs index 492d0985..bd5c93d1 100644 --- a/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs @@ -12,7 +12,7 @@ namespace Swarmops.Logic.Support.LogEntries // empty ctor needed for serialize } - public InboundInvoiceCreatedLogEntry(Person creatingPerson, string supplier, string description, double amount, + public InboundInvoiceCreatedLogEntry (Person creatingPerson, string supplier, string description, double amount, FinancialAccount budget) { Amount = amount; diff --git a/Logic/Support/LogEntries/LogEntryBase.cs b/Logic/Support/LogEntries/LogEntryBase.cs index 643f6403..31a37b71 100644 --- a/Logic/Support/LogEntries/LogEntryBase.cs +++ b/Logic/Support/LogEntries/LogEntryBase.cs @@ -10,35 +10,35 @@ namespace Swarmops.Logic.Support.LogEntries { public virtual string ToXml() { - XmlSerializer serializer = new XmlSerializer(GetType()); + XmlSerializer serializer = new XmlSerializer (GetType()); MemoryStream stream = new MemoryStream(); - serializer.Serialize(stream, this); + serializer.Serialize (stream, this); byte[] xmlBytes = stream.GetBuffer(); - return Encoding.UTF8.GetString(xmlBytes); + return Encoding.UTF8.GetString (xmlBytes); } - public static T FromXml(string xml) // 'T' might not work here, like it didn't in ToXml() + public static T FromXml (string xml) // 'T' might not work here, like it didn't in ToXml() { // Compensate for stupid Mono encoding bugs - if (xml.StartsWith("?")) + if (xml.StartsWith ("?")) { - xml = xml.Substring(1); + xml = xml.Substring (1); } - xml = xml.Replace("�", ""); - xml = xml.Replace("\x00", ""); + xml = xml.Replace ("�", ""); + xml = xml.Replace ("\x00", ""); - XmlSerializer serializer = new XmlSerializer(typeof (T)); + XmlSerializer serializer = new XmlSerializer (typeof (T)); MemoryStream stream = new MemoryStream(); - byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); - stream.Write(xmlBytes, 0, xmlBytes.Length); + byte[] xmlBytes = Encoding.UTF8.GetBytes (xml); + stream.Write (xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - T result = (T) serializer.Deserialize(stream); + T result = (T) serializer.Deserialize (stream); stream.Close(); return result; diff --git a/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs b/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs index c9238758..a86fc959 100644 --- a/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs @@ -13,7 +13,7 @@ namespace Swarmops.Logic.Support.LogEntries // public ctor required for serializability } - public PayoutCreatedLogEntry(Person payingPerson, Person beneficiaryPerson, Organization organization, + public PayoutCreatedLogEntry (Person payingPerson, Person beneficiaryPerson, Organization organization, Currency currency, double amount, string reason) { Amount = amount; diff --git a/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs b/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs index 68f57859..2b4fe6d5 100644 --- a/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs @@ -6,13 +6,13 @@ namespace Swarmops.Logic.Support.LogEntries [Serializable] public class SalaryCreatedLogEntry : FinancialActionBase { - [Obsolete("Do not call this constructor directly.", true)] + [Obsolete ("Do not call this constructor directly.", true)] public SalaryCreatedLogEntry() { // empty ctor needed for serializability; should not be called } - public SalaryCreatedLogEntry(Salary salary) + public SalaryCreatedLogEntry (Salary salary) { ActingPersonId = 0; BeneficiaryPersonId = salary.PayrollItem.PersonId; diff --git a/Logic/Support/LogicServices.cs b/Logic/Support/LogicServices.cs index 29d04cc5..5a712fa3 100644 --- a/Logic/Support/LogicServices.cs +++ b/Logic/Support/LogicServices.cs @@ -12,11 +12,11 @@ namespace Swarmops.Logic.Support /// /// String to test. /// True if safely parsable by Int32.Parse. - internal static bool IsNumber(string input) + internal static bool IsNumber (string input) { try { - Int32.Parse(input); + Int32.Parse (input); return true; } catch (Exception) @@ -31,7 +31,7 @@ namespace Swarmops.Logic.Support /// The string to clean. /// The sanitized result. /// This means that an input string of "abc153ûû" would come back as "153". - internal static string CleanNumber(string input) + internal static string CleanNumber (string input) { if (input == null) { @@ -44,21 +44,21 @@ namespace Swarmops.Logic.Support { if (acter >= '0' && acter <= '9') { - result.Append(acter); + result.Append (acter); } } return result.ToString(); } - internal static int[] ObjectsToIdentifiers(IHasIdentity[] identifiables) + internal static int[] ObjectsToIdentifiers (IHasIdentity[] identifiables) { List result = new List(); result.Capacity = identifiables.Length*11/10; foreach (IHasIdentity identifiable in identifiables) { - result.Add(identifiable.Identity); + result.Add (identifiable.Identity); } return result.ToArray(); diff --git a/Logic/Support/ObjectOptionalData.cs b/Logic/Support/ObjectOptionalData.cs index 72df2b8e..71aefa5c 100644 --- a/Logic/Support/ObjectOptionalData.cs +++ b/Logic/Support/ObjectOptionalData.cs @@ -11,17 +11,17 @@ namespace Swarmops.Logic.Support { private IHasIdentity forObject; - private ObjectOptionalData(BasicObjectOptionalData basic) - : base(basic) + private ObjectOptionalData (BasicObjectOptionalData basic) + : base (basic) { // empty ctor } - public string this[ObjectOptionalDataType dataType] + public string this [ObjectOptionalDataType dataType] { get { - if (OptionalData.ContainsKey(dataType)) + if (OptionalData.ContainsKey (dataType)) { return OptionalData[dataType]; } @@ -30,27 +30,27 @@ namespace Swarmops.Logic.Support } set { - SwarmDb.GetDatabaseForWriting().SetObjectOptionalData(this.forObject, dataType, value); + SwarmDb.GetDatabaseForWriting().SetObjectOptionalData (this.forObject, dataType, value); OptionalData[dataType] = value; } } - public static ObjectOptionalData FromBasic(BasicObjectOptionalData basic) + public static ObjectOptionalData FromBasic (BasicObjectOptionalData basic) { - return new ObjectOptionalData(basic); + return new ObjectOptionalData (basic); } - public static ObjectOptionalData ForObject(IHasIdentity identifiableObject) + public static ObjectOptionalData ForObject (IHasIdentity identifiableObject) { ObjectOptionalData thisObject = - FromBasic(SwarmDb.GetDatabaseForReading().GetObjectOptionalData(identifiableObject)); + FromBasic (SwarmDb.GetDatabaseForReading().GetObjectOptionalData (identifiableObject)); thisObject.forObject = identifiableObject; return thisObject; } - public bool HasData(ObjectOptionalDataType dataType) + public bool HasData (ObjectOptionalDataType dataType) { - if (OptionalData.ContainsKey(dataType)) + if (OptionalData.ContainsKey (dataType)) { return true; } @@ -74,9 +74,9 @@ namespace Swarmops.Logic.Support // Optional data support - public string GetOptionalDataString(ObjectOptionalDataType key) + public string GetOptionalDataString (ObjectOptionalDataType key) { - if (HasData(key)) + if (HasData (key)) { return this[key]; } @@ -84,33 +84,33 @@ namespace Swarmops.Logic.Support return string.Empty; } - public void SetOptionalDataString(ObjectOptionalDataType key, string value) + public void SetOptionalDataString (ObjectOptionalDataType key, string value) { - SetOptionalData(key, value); + SetOptionalData (key, value); } // All ints default to 0 - public int GetOptionalDataInt(ObjectOptionalDataType key) + public int GetOptionalDataInt (ObjectOptionalDataType key) { - if (HasData(key)) + if (HasData (key)) { - return Int32.Parse(this[key]); + return Int32.Parse (this[key]); } return 0; } - public void SetOptionalDataInt(ObjectOptionalDataType key, int value) + public void SetOptionalDataInt (ObjectOptionalDataType key, int value) { - SetOptionalData(key, value.ToString()); + SetOptionalData (key, value.ToString()); } // All bools default to false - public bool GetOptionalDataBool(ObjectOptionalDataType key) + public bool GetOptionalDataBool (ObjectOptionalDataType key) { - if (HasData(key)) + if (HasData (key)) { return (this[key] == "1" ? true : false); } @@ -118,18 +118,18 @@ namespace Swarmops.Logic.Support return false; } - public void SetOptionalDataBool(ObjectOptionalDataType key, bool value) + public void SetOptionalDataBool (ObjectOptionalDataType key, bool value) { - SetOptionalData(key, value ? "1" : "0"); + SetOptionalData (key, value ? "1" : "0"); } - public void SetOptionalData(ObjectOptionalDataType dataType, string data) + public void SetOptionalData (ObjectOptionalDataType dataType, string data) { - SwarmDb.GetDatabaseForWriting().SetObjectOptionalData(this.forObject, dataType, data); + SwarmDb.GetDatabaseForWriting().SetObjectOptionalData (this.forObject, dataType, data); - if (data == null && OptionalData.ContainsKey(dataType)) - OptionalData.Remove(dataType); + if (data == null && OptionalData.ContainsKey (dataType)) + OptionalData.Remove (dataType); else this[dataType] = data; } diff --git a/Logic/Support/Optimizations.cs b/Logic/Support/Optimizations.cs index 0885f134..95dc1f57 100644 --- a/Logic/Support/Optimizations.cs +++ b/Logic/Support/Optimizations.cs @@ -8,9 +8,9 @@ namespace Swarmops.Logic.Support /// public class Optimizations { - public static Dictionary GetPeopleWhoDeclineLocalMail(int[] personIds) + public static Dictionary GetPeopleWhoDeclineLocalMail (int[] personIds) { - return SwarmDb.GetDatabaseForReading().GetPeopleWhoDeclineLocalMail(personIds); + return SwarmDb.GetDatabaseForReading().GetPeopleWhoDeclineLocalMail (personIds); } public static Dictionary GetGeographyVoterCounts() @@ -18,9 +18,9 @@ namespace Swarmops.Logic.Support return SwarmDb.GetDatabaseForReading().GetGeographyVoterCounts(); } - public static Dictionary GetInternalPollVoteCountsPerGeography(int pollId) + public static Dictionary GetInternalPollVoteCountsPerGeography (int pollId) { - return SwarmDb.GetDatabaseForReading().GetInternalPollVoteCountsPerGeography(pollId); + return SwarmDb.GetDatabaseForReading().GetInternalPollVoteCountsPerGeography (pollId); } } } \ No newline at end of file diff --git a/Logic/Support/PWEvents.cs b/Logic/Support/PWEvents.cs index 95cc442c..ee9d4b15 100644 --- a/Logic/Support/PWEvents.cs +++ b/Logic/Support/PWEvents.cs @@ -7,14 +7,14 @@ namespace Swarmops.Logic.Support { public class PWEvents { - public static int CreateEvent(EventSource eventSource, EventType eventType, int actingPersonId, + public static int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, int organizationId, int geographyId, int affectedPersonId, int parameterInt, string parameterText) { //TODO: organizationId comes in hardcoded as 1 from a lot of places, should probably be changed based on affected person // to the party for that country if not swedish. - return SwarmDb.GetDatabaseForWriting().CreateEvent(eventSource, eventType, actingPersonId, organizationId, + return SwarmDb.GetDatabaseForWriting().CreateEvent (eventSource, eventType, actingPersonId, organizationId, geographyId, affectedPersonId, parameterInt, parameterText); } @@ -23,29 +23,29 @@ namespace Swarmops.Logic.Support return SwarmDb.GetDatabaseForReading().GetTopUnprocessedEvents(); } - public static BasicPWEvent[] ForPerson(int personId) + public static BasicPWEvent[] ForPerson (int personId) { - return SwarmDb.GetDatabaseForReading().GetEventsForPerson(personId); + return SwarmDb.GetDatabaseForReading().GetEventsForPerson (personId); } - public static Dictionary> ForPersons(int[] personIds) + public static Dictionary> ForPersons (int[] personIds) { - return SwarmDb.GetDatabaseForReading().GetEventsForPersons(personIds, new EventType[] {}); + return SwarmDb.GetDatabaseForReading().GetEventsForPersons (personIds, new EventType[] {}); } - public static Dictionary> ForPersons(int[] personIds, EventType[] eventTypes) + public static Dictionary> ForPersons (int[] personIds, EventType[] eventTypes) { - return SwarmDb.GetDatabaseForReading().GetEventsForPersons(personIds, eventTypes); + return SwarmDb.GetDatabaseForReading().GetEventsForPersons (personIds, eventTypes); } - public static BasicPWEvent[] ByType(EventType eventType) + public static BasicPWEvent[] ByType (EventType eventType) { - return SwarmDb.GetDatabaseForReading().GetEventsOfType(eventType); + return SwarmDb.GetDatabaseForReading().GetEventsOfType (eventType); } - public static void SetEventProcessed(int eventId) + public static void SetEventProcessed (int eventId) { - SwarmDb.GetDatabaseForWriting().SetEventProcessed(eventId); + SwarmDb.GetDatabaseForWriting().SetEventProcessed (eventId); } } } \ No newline at end of file diff --git a/Logic/Support/PWLog.cs b/Logic/Support/PWLog.cs index a68a4c4a..181b878c 100644 --- a/Logic/Support/PWLog.cs +++ b/Logic/Support/PWLog.cs @@ -14,43 +14,43 @@ namespace Swarmops.Logic.Support { private static string hostIp = ""; //Used in batch programs - public static void Write(DateTime dateTimeUtc, int actingPersonId, PWLogItem affectedItem, + public static void Write (DateTime dateTimeUtc, int actingPersonId, PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment, string changedField, string valueBefore, string valueAfter) { - SwarmDb.GetDatabaseForWriting().CreatePWLogEntry(dateTimeUtc, actingPersonId, affectedItem.ToString(), + SwarmDb.GetDatabaseForWriting().CreatePWLogEntry (dateTimeUtc, actingPersonId, affectedItem.ToString(), affectedItemId, actionType.ToString(), actionDescription, changedField, valueBefore, valueAfter, comment, GetCurrentIp()); } - public static void Write(DateTime dateTimeUtc, Person actingPerson, PWLogItem affectedItem, + public static void Write (DateTime dateTimeUtc, Person actingPerson, PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment, string changedField, string valueBefore, string valueAfter) { - Write(dateTimeUtc, actingPerson.Identity, affectedItem, affectedItemId, actionType, + Write (dateTimeUtc, actingPerson.Identity, affectedItem, affectedItemId, actionType, actionDescription, comment, changedField, valueBefore, valueAfter); } - public static void Write(Person actingPerson, PWLogItem affectedItem, int affectedItemId, + public static void Write (Person actingPerson, PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment, string changedField, string valueBefore, string valueAfter) { - Write(DateTime.UtcNow, actingPerson.Identity, affectedItem, affectedItemId, actionType, + Write (DateTime.UtcNow, actingPerson.Identity, affectedItem, affectedItemId, actionType, actionDescription, comment, changedField, valueBefore, valueAfter); } - public static void Write(Person actingPerson, PWLogItem affectedItem, int affectedItemId, + public static void Write (Person actingPerson, PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment) { - Write(DateTime.UtcNow, actingPerson.Identity, affectedItem, affectedItemId, actionType, + Write (DateTime.UtcNow, actingPerson.Identity, affectedItem, affectedItemId, actionType, actionDescription, comment, string.Empty, string.Empty, string.Empty); } - public static void Write(int actingPersonId, PWLogItem affectedItem, int affectedItemId, + public static void Write (int actingPersonId, PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment) { @@ -58,20 +58,20 @@ namespace Swarmops.Logic.Support { try { - comment = "Action done by " + Person.FromIdentity(actingPersonId).Name; + comment = "Action done by " + Person.FromIdentity (actingPersonId).Name; } catch { } } - Write(DateTime.UtcNow, actingPersonId, affectedItem, affectedItemId, actionType, + Write (DateTime.UtcNow, actingPersonId, affectedItem, affectedItemId, actionType, actionDescription, comment, string.Empty, string.Empty, string.Empty); } - public static void Write(PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, + public static void Write (PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, string actionDescription, string comment) { - Write(DateTime.UtcNow, 0, affectedItem, affectedItemId, actionType, + Write (DateTime.UtcNow, 0, affectedItem, affectedItemId, actionType, actionDescription, comment, string.Empty, string.Empty, string.Empty); } @@ -92,7 +92,7 @@ namespace Swarmops.Logic.Support hostIp = "n/a"; string myHostName = Dns.GetHostName(); hostIp = myHostName; - IPHostEntry ipEntry = Dns.GetHostEntry(myHostName); + IPHostEntry ipEntry = Dns.GetHostEntry (myHostName); IPAddress[] addr = ipEntry.AddressList; hostIp = addr[0].ToString(); } @@ -104,21 +104,21 @@ namespace Swarmops.Logic.Support } } - public static DateTime CheckLatest(PWLogItem affectedItemType, int affectedItemId, PWLogAction actionType) + public static DateTime CheckLatest (PWLogItem affectedItemType, int affectedItemId, PWLogAction actionType) { return SwarmDb.GetDatabaseForReading() - .CheckLogEntry(affectedItemType.ToString(), affectedItemId, actionType.ToString()); + .CheckLogEntry (affectedItemType.ToString(), affectedItemId, actionType.ToString()); } - public static BasicPWLog[] GetLatestEvents(PWLogItem affectedItemType, DateTime beforeDate, int[] affectedIds, + public static BasicPWLog[] GetLatestEvents (PWLogItem affectedItemType, DateTime beforeDate, int[] affectedIds, PWLogAction[] actionTypes) { List actionTypeList = new List(); foreach (PWLogAction at in actionTypes) - actionTypeList.Add(at.ToString()); + actionTypeList.Add (at.ToString()); return SwarmDb.GetDatabaseForReading() - .GetLatestEvents(affectedItemType.ToString(), beforeDate, affectedIds, actionTypeList.ToArray()); + .GetLatestEvents (affectedItemType.ToString(), beforeDate, affectedIds, actionTypeList.ToArray()); } } diff --git a/Logic/Support/Persistence.cs b/Logic/Support/Persistence.cs index 2f05658f..c0e3c0e5 100644 --- a/Logic/Support/Persistence.cs +++ b/Logic/Support/Persistence.cs @@ -7,19 +7,19 @@ namespace Swarmops.Logic.Support // Usage: Persistence.Key ["Foobar"] = "42"; Console.WriteLine (Persistence.Key ["Barcode"]); // Bad class name and location, refactor later - public string this[string key] + public string this [string key] { - get { return SwarmDb.GetDatabaseForReading().GetKeyValue(key); } + get { return SwarmDb.GetDatabaseForReading().GetKeyValue (key); } set { if (value == null) { - SwarmDb.GetDatabaseForWriting().SetKeyValue(key, "-null-"); // TODO: Delete the key + SwarmDb.GetDatabaseForWriting().SetKeyValue (key, "-null-"); // TODO: Delete the key } else { - SwarmDb.GetDatabaseForWriting().SetKeyValue(key, value); + SwarmDb.GetDatabaseForWriting().SetKeyValue (key, value); } } } diff --git a/Logic/Support/PilotInstallationIds.cs b/Logic/Support/PilotInstallationIds.cs index 42ef4ba8..ae364688 100644 --- a/Logic/Support/PilotInstallationIds.cs +++ b/Logic/Support/PilotInstallationIds.cs @@ -17,7 +17,7 @@ get { return "db8f4ade-07f2-4f4f-a1c7-c9da91f93ea9"; } } - public static bool IsPilot(string installationId) + public static bool IsPilot (string installationId) { string thisInstallationId = Persistence.Key["SwarmopsInstallationId"]; if (installationId == thisInstallationId) diff --git a/Logic/Support/PirateWebDebug.cs b/Logic/Support/PirateWebDebug.cs index e10892af..91875bd7 100644 --- a/Logic/Support/PirateWebDebug.cs +++ b/Logic/Support/PirateWebDebug.cs @@ -14,7 +14,7 @@ namespace Swarmops.Logic.Support if (HttpContext.Current != null) { - debug += "Application Directory: " + HttpContext.Current.Server.MapPath("~/Test.mdb") + "\r\n"; + debug += "Application Directory: " + HttpContext.Current.Server.MapPath ("~/Test.mdb") + "\r\n"; } return debug; diff --git a/Logic/Support/PluralBase.cs b/Logic/Support/PluralBase.cs index 1457d62f..77896368 100644 --- a/Logic/Support/PluralBase.cs +++ b/Logic/Support/PluralBase.cs @@ -16,45 +16,45 @@ namespace Swarmops.Logic.Support foreach (TSingular singular in this) { - result.Add(singular.Identity); + result.Add (singular.Identity); } return result.ToArray(); } } - public static TPlural FromArray(TBasic[] basicArray) + public static TPlural FromArray (TBasic[] basicArray) { TPlural result = new TPlural {Capacity = basicArray.Length*11/10}; foreach (TBasic basic in basicArray) { - result.Add((TSingular) SingularFactory.FromBasic(basic)); + result.Add ((TSingular) SingularFactory.FromBasic (basic)); } return result; } - public static TPlural FromSingle(TSingular singular) + public static TPlural FromSingle (TSingular singular) { TPlural result = new TPlural(); - result.Add(singular); + result.Add (singular); return result; } - public static TPlural FromSingle(TBasic basic) + public static TPlural FromSingle (TBasic basic) { TPlural result = new TPlural(); - result.Add((TSingular) SingularFactory.FromBasic(basic)); + result.Add ((TSingular) SingularFactory.FromBasic (basic)); return result; } - public static TPlural LogicalOr(TPlural set1, TPlural set2) + public static TPlural LogicalOr (TPlural set1, TPlural set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -89,14 +89,14 @@ namespace Swarmops.Logic.Support foreach (TSingular singular in table.Values) { - result.Add(singular); + result.Add (singular); } return result; } - public static TPlural LogicalAnd(TPlural set1, TPlural set2) + public static TPlural LogicalAnd (TPlural set1, TPlural set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -125,22 +125,22 @@ namespace Swarmops.Logic.Support TPlural result = new TPlural(); foreach (TSingular singular in set1) { - if (set2Lookup.ContainsKey(singular.Identity)) + if (set2Lookup.ContainsKey (singular.Identity)) { - result.Add(singular); + result.Add (singular); } } return result; } - public new void Remove(TSingular objectToRemove) + public new void Remove (TSingular objectToRemove) { for (int index = 0; index < Count; index++) { if (this[index].Identity == objectToRemove.Identity) { - RemoveAt(index); + RemoveAt (index); index--; } } diff --git a/Logic/Support/QuotedPrintable.cs b/Logic/Support/QuotedPrintable.cs index 022b69d0..5bc97def 100644 --- a/Logic/Support/QuotedPrintable.cs +++ b/Logic/Support/QuotedPrintable.cs @@ -17,7 +17,7 @@ namespace Swarmops.Logic.Support private readonly Encoding _encoding = Encoding.Default; - public QuotedPrintable(Encoding encoding) + public QuotedPrintable (Encoding encoding) { this._encoding = encoding; } @@ -27,15 +27,15 @@ namespace Swarmops.Logic.Support /// /// /// - public string Encode(string textToEncode) + public string Encode (string textToEncode) { if (textToEncode == null) throw new ArgumentNullException(); - return Encode(textToEncode, RFC_1521_MAX_CHARS_PER_LINE); + return Encode (textToEncode, RFC_1521_MAX_CHARS_PER_LINE); } - private string Encode(string textToEncode, int charsPerLine) + private string Encode (string textToEncode, int charsPerLine) { if (textToEncode == null) throw new ArgumentNullException(); @@ -43,7 +43,7 @@ namespace Swarmops.Logic.Support if (charsPerLine <= 0) throw new ArgumentOutOfRangeException(); - return FormatEncodedString(EncodeString(textToEncode), charsPerLine); + return FormatEncodedString (EncodeString (textToEncode), charsPerLine); } /// @@ -51,15 +51,15 @@ namespace Swarmops.Logic.Support /// /// /// - public String EncodeMailHeaderString(string textToEncode) + public String EncodeMailHeaderString (string textToEncode) { - String encChars = EncodeString(textToEncode); + String encChars = EncodeString (textToEncode); String displayName = ""; if (encChars != textToEncode) { displayName = "=?"; displayName += this._encoding.BodyName; - displayName += "?Q?" + encChars.Replace(" ", "_") + "?="; + displayName += "?Q?" + encChars.Replace (" ", "_") + "?="; } else displayName = textToEncode; @@ -71,33 +71,33 @@ namespace Swarmops.Logic.Support /// /// /// - public string EncodeString(string textToEncode) + public string EncodeString (string textToEncode) { if (textToEncode == null) throw new ArgumentNullException(); - byte[] bytes = this._encoding.GetBytes(textToEncode); + byte[] bytes = this._encoding.GetBytes (textToEncode); StringBuilder builder = new StringBuilder(); foreach (byte b in bytes) { if (b != 0) if ((b < 32) || (b > 126)) - builder.Append(String.Format("={0}", b.ToString("X2"))); + builder.Append (String.Format ("={0}", b.ToString ("X2"))); else { switch (b) { case 13: - builder.Append("=0D"); + builder.Append ("=0D"); break; case 10: - builder.Append("=0A"); + builder.Append ("=0A"); break; case 61: - builder.Append("=3D"); + builder.Append ("=3D"); break; default: - builder.Append(Convert.ToChar(b)); + builder.Append (Convert.ToChar (b)); break; } } @@ -106,7 +106,7 @@ namespace Swarmops.Logic.Support return builder.ToString(); } - private string FormatEncodedString(string qpstr, int maxcharlen) + private string FormatEncodedString (string qpstr, int maxcharlen) { if (qpstr == null) throw new ArgumentNullException(); @@ -116,11 +116,11 @@ namespace Swarmops.Logic.Support int i = 0; foreach (char c in charArray) { - builder.Append(c); + builder.Append (c); i++; if (i == maxcharlen) { - builder.AppendLine("="); + builder.AppendLine ("="); i = 0; } } @@ -128,9 +128,9 @@ namespace Swarmops.Logic.Support return builder.ToString(); } - private string HexDecoderEvaluator(Match m) + private string HexDecoderEvaluator (Match m) { - if (String.IsNullOrEmpty(m.Value)) + if (String.IsNullOrEmpty (m.Value)) return null; CaptureCollection captures = m.Groups[3].Captures; @@ -138,40 +138,40 @@ namespace Swarmops.Logic.Support for (int i = 0; i < captures.Count; i++) { - bytes[i] = Convert.ToByte(captures[i].Value, 16); + bytes[i] = Convert.ToByte (captures[i].Value, 16); } - return this._encoding.GetString(bytes); + return this._encoding.GetString (bytes); } - private string HexDecoder(string line) + private string HexDecoder (string line) { if (line == null) throw new ArgumentNullException(); - Regex re = new Regex("((\\=([0-9A-F][0-9A-F]))*)", RegexOptions.IgnoreCase); - return re.Replace(line, HexDecoderEvaluator); + Regex re = new Regex ("((\\=([0-9A-F][0-9A-F]))*)", RegexOptions.IgnoreCase); + return re.Replace (line, HexDecoderEvaluator); } - public string Decode(string encodedText) + public string Decode (string encodedText) { if (encodedText == null) throw new ArgumentNullException(); - using (StringReader sr = new StringReader(encodedText)) + using (StringReader sr = new StringReader (encodedText)) { StringBuilder builder = new StringBuilder(); string line; while ((line = sr.ReadLine()) != null) { - if (line.EndsWith("=")) - builder.Append(line.Substring(0, line.Length - 1)); + if (line.EndsWith ("=")) + builder.Append (line.Substring (0, line.Length - 1)); else - builder.Append(line); + builder.Append (line); } - return HexDecoder(builder.ToString()); + return HexDecoder (builder.ToString()); } } } diff --git a/Logic/Support/SerializableDictionary.cs b/Logic/Support/SerializableDictionary.cs index 215032ba..82db1aa6 100644 --- a/Logic/Support/SerializableDictionary.cs +++ b/Logic/Support/SerializableDictionary.cs @@ -7,7 +7,7 @@ namespace Swarmops.Logic.Support { // Code from Paul Welter's Weblog at http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx -- assumed by style, writing and tone of Q&A to be in public domain - [XmlRoot("dictionary")] + [XmlRoot ("dictionary")] public class SerializableDictionary : Dictionary, IXmlSerializable { @@ -18,10 +18,10 @@ namespace Swarmops.Logic.Support return null; } - public void ReadXml(XmlReader reader) + public void ReadXml (XmlReader reader) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + XmlSerializer keySerializer = new XmlSerializer (typeof (TKey)); + XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); @@ -31,17 +31,17 @@ namespace Swarmops.Logic.Support while (reader.NodeType != XmlNodeType.EndElement) { - reader.ReadStartElement("item"); + reader.ReadStartElement ("item"); - reader.ReadStartElement("key"); - TKey key = (TKey) keySerializer.Deserialize(reader); + reader.ReadStartElement ("key"); + TKey key = (TKey) keySerializer.Deserialize (reader); reader.ReadEndElement(); - reader.ReadStartElement("value"); - TValue value = (TValue) valueSerializer.Deserialize(reader); + reader.ReadStartElement ("value"); + TValue value = (TValue) valueSerializer.Deserialize (reader); reader.ReadEndElement(); - Add(key, value); + Add (key, value); reader.ReadEndElement(); reader.MoveToContent(); @@ -49,22 +49,22 @@ namespace Swarmops.Logic.Support reader.ReadEndElement(); } - public void WriteXml(XmlWriter writer) + public void WriteXml (XmlWriter writer) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + XmlSerializer keySerializer = new XmlSerializer (typeof (TKey)); + XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue)); foreach (TKey key in Keys) { - writer.WriteStartElement("item"); + writer.WriteStartElement ("item"); - writer.WriteStartElement("key"); - keySerializer.Serialize(writer, key); + writer.WriteStartElement ("key"); + keySerializer.Serialize (writer, key); writer.WriteEndElement(); - writer.WriteStartElement("value"); + writer.WriteStartElement ("value"); TValue value = this[key]; - valueSerializer.Serialize(writer, value); + valueSerializer.Serialize (writer, value); writer.WriteEndElement(); writer.WriteEndElement(); diff --git a/Logic/Support/SingularFactory.cs b/Logic/Support/SingularFactory.cs index 835d4a51..2559d653 100644 --- a/Logic/Support/SingularFactory.cs +++ b/Logic/Support/SingularFactory.cs @@ -18,7 +18,7 @@ namespace Swarmops.Logic.Support /// internal class SingularFactory { - public static object FromBasic(IHasIdentity basic) + public static object FromBasic (IHasIdentity basic) { string argumentType = basic.GetType().ToString(); @@ -31,110 +31,110 @@ namespace Swarmops.Logic.Support // ------------ COMMUNICATION CLASSES ------------ case "Swarmops.Basic.Types.BasicCommunicationTurnaround": - return CommunicationTurnaround.FromBasic((BasicCommunicationTurnaround) basic); + return CommunicationTurnaround.FromBasic ((BasicCommunicationTurnaround) basic); case "Swarmops.Basic.Types.Communications.BasicOutboundComm": - return OutboundComm.FromBasic((BasicOutboundComm) basic); + return OutboundComm.FromBasic ((BasicOutboundComm) basic); case "Swarmops.Basic.Types.Communications.BasicOutboundCommRecipient": - return OutboundCommRecipient.FromBasic((BasicOutboundCommRecipient) basic); + return OutboundCommRecipient.FromBasic ((BasicOutboundCommRecipient) basic); // ----------- FINANCIAL CLASSES ---------- case "Swarmops.Basic.Types.BasicExpenseClaim": - return ExpenseClaim.FromBasic((BasicExpenseClaim) basic); + return ExpenseClaim.FromBasic ((BasicExpenseClaim) basic); case "Swarmops.Basic.Types.Financial.BasicCashAdvance": - return CashAdvance.FromBasic((BasicCashAdvance) basic); + return CashAdvance.FromBasic ((BasicCashAdvance) basic); case "Swarmops.Basic.Types.BasicInboundInvoice": - return InboundInvoice.FromBasic((BasicInboundInvoice) basic); + return InboundInvoice.FromBasic ((BasicInboundInvoice) basic); case "Swarmops.Basic.Types.Financial.BasicFinancialAccount": - return FinancialAccount.FromBasic((BasicFinancialAccount) basic); + return FinancialAccount.FromBasic ((BasicFinancialAccount) basic); case "Swarmops.Basic.Types.Financial.BasicFinancialTransaction": - return FinancialTransaction.FromBasic((BasicFinancialTransaction) basic); + return FinancialTransaction.FromBasic ((BasicFinancialTransaction) basic); case "Swarmops.Basic.Types.BasicFinancialValidation": - return FinancialValidation.FromBasic((BasicFinancialValidation) basic); + return FinancialValidation.FromBasic ((BasicFinancialValidation) basic); case "Swarmops.Basic.Types.BasicOutboundInvoice": - return OutboundInvoice.FromBasic((BasicOutboundInvoice) basic); + return OutboundInvoice.FromBasic ((BasicOutboundInvoice) basic); case "Swarmops.Basic.Types.BasicOutboundInvoiceItem": - return OutboundInvoiceItem.FromBasic((BasicOutboundInvoiceItem) basic); + return OutboundInvoiceItem.FromBasic ((BasicOutboundInvoiceItem) basic); case "Swarmops.Basic.Types.BasicPayment": - return Payment.FromBasic((BasicPayment) basic); + return Payment.FromBasic ((BasicPayment) basic); case "Swarmops.Basic.Types.BasicPaymentGroup": - return PaymentGroup.FromBasic((BasicPaymentGroup) basic); + return PaymentGroup.FromBasic ((BasicPaymentGroup) basic); case "Swarmops.Basic.Types.BasicPayout": - return Payout.FromBasic((BasicPayout) basic); + return Payout.FromBasic ((BasicPayout) basic); case "Swarmops.Basic.Types.BasicPayrollAdjustment": - return PayrollAdjustment.FromBasic((BasicPayrollAdjustment) basic); + return PayrollAdjustment.FromBasic ((BasicPayrollAdjustment) basic); case "Swarmops.Basic.Types.BasicPayrollItem": - return PayrollItem.FromBasic((BasicPayrollItem) basic); + return PayrollItem.FromBasic ((BasicPayrollItem) basic); case "Swarmops.Basic.Types.BasicSalary": - return Salary.FromBasic((BasicSalary) basic); + return Salary.FromBasic ((BasicSalary) basic); case "Swarmops.Basic.Types.BasicCurrency": - return Currency.FromBasic((BasicCurrency) basic); + return Currency.FromBasic ((BasicCurrency) basic); case "Swarmops.Basic.Types.Financial.BasicFinancialTransactionTagSet": - return FinancialTransactionTagSet.FromBasic((BasicFinancialTransactionTagSet) basic); + return FinancialTransactionTagSet.FromBasic ((BasicFinancialTransactionTagSet) basic); case "Swarmops.Basic.Types.Financial.BasicFinancialTransactionTagType": - return FinancialTransactionTagType.FromBasic((BasicFinancialTransactionTagType) basic); + return FinancialTransactionTagType.FromBasic ((BasicFinancialTransactionTagType) basic); // ------------ GOVERNANCE CLASSES ------------ case "Swarmops.Basic.Types.BasicBallot": - return Ballot.FromBasic((BasicBallot) basic); + return Ballot.FromBasic ((BasicBallot) basic); case "Swarmops.Basic.Types.BasicMeetingElectionCandidate": - return MeetingElectionCandidate.FromBasic((BasicInternalPollCandidate) basic); + return MeetingElectionCandidate.FromBasic ((BasicInternalPollCandidate) basic); case "Swarmops.Basic.Types.BasicMeetingElection": - return MeetingElection.FromBasic((BasicInternalPoll) basic); + return MeetingElection.FromBasic ((BasicInternalPoll) basic); case "Swarmops.Basic.Types.BasicMeetingElectionVote": - return MeetingElectionVote.FromBasic((BasicInternalPollVote) basic); + return MeetingElectionVote.FromBasic ((BasicInternalPollVote) basic); case "Swarmops.Basic.Types.Governance.BasicMotion": - return Motion.FromBasic((BasicMotion) basic); + return Motion.FromBasic ((BasicMotion) basic); case "Swarmops.Basic.Types.Governance.BasicMotionAmendment": - return MotionAmendment.FromBasic((BasicMotionAmendment) basic); + return MotionAmendment.FromBasic ((BasicMotionAmendment) basic); // ------------ PARLEY/ACTIVISM CLASSES ------------ case "Swarmops.Basic.Types.BasicExternalActivity": - return ExternalActivity.FromBasic((BasicExternalActivity) basic); + return ExternalActivity.FromBasic ((BasicExternalActivity) basic); case "Swarmops.Basic.Types.BasicParley": - return Parley.FromBasic((BasicParley) basic); + return Parley.FromBasic ((BasicParley) basic); case "Swarmops.Basic.Types.BasicParleyAttendee": - return ParleyAttendee.FromBasic((BasicParleyAttendee) basic); + return ParleyAttendee.FromBasic ((BasicParleyAttendee) basic); case "Swarmops.Basic.Types.BasicParleyOption": - return ParleyOption.FromBasic((BasicParleyOption) basic); + return ParleyOption.FromBasic ((BasicParleyOption) basic); case "Swarmops.Basic.Types.BasicPerson": - return Person.FromBasic((BasicPerson) basic); + return Person.FromBasic ((BasicPerson) basic); // ------------------ FAIL ---------------- default: - throw new NotImplementedException("Unimplemented argument type in SingularFactory: " + argumentType); + throw new NotImplementedException ("Unimplemented argument type in SingularFactory: " + argumentType); } } } diff --git a/Logic/Support/SwarmopsLog.cs b/Logic/Support/SwarmopsLog.cs index 92d34bfe..aa15b2d8 100644 --- a/Logic/Support/SwarmopsLog.cs +++ b/Logic/Support/SwarmopsLog.cs @@ -5,19 +5,19 @@ namespace Swarmops.Logic.Support { public class SwarmopsLog { - public static SwarmopsLogEntry CreateEntry(Person person, IXmlPayload logEntry) + public static SwarmopsLogEntry CreateEntry (Person person, IXmlPayload logEntry) { string logEntryClass = logEntry.GetType().ToString(); - if (logEntryClass.StartsWith("Swarmops.Logic.Support.LogEntries.")) + if (logEntryClass.StartsWith ("Swarmops.Logic.Support.LogEntries.")) { - logEntryClass = logEntryClass.Substring("Swarmops.Logic.Support.LogEntries.".Length); + logEntryClass = logEntryClass.Substring ("Swarmops.Logic.Support.LogEntries.".Length); } - int logEntryId = SwarmDb.GetDatabaseForWriting().CreateSwarmopsLogEntry( + int logEntryId = SwarmDb.GetDatabaseForWriting().CreateSwarmopsLogEntry ( person != null ? person.Identity : 0, logEntryClass, logEntry.ToXml()); - return SwarmopsLogEntry.FromIdentityAggressive(logEntryId); + return SwarmopsLogEntry.FromIdentityAggressive (logEntryId); } } } \ No newline at end of file diff --git a/Logic/Support/SwarmopsLogEntry.cs b/Logic/Support/SwarmopsLogEntry.cs index deeee9ce..48b4168e 100644 --- a/Logic/Support/SwarmopsLogEntry.cs +++ b/Logic/Support/SwarmopsLogEntry.cs @@ -7,55 +7,55 @@ namespace Swarmops.Logic.Support { public class SwarmopsLogEntry : BasicSwarmopsLogEntry { - private SwarmopsLogEntry(BasicSwarmopsLogEntry basic) : - base(basic) + private SwarmopsLogEntry (BasicSwarmopsLogEntry basic) : + base (basic) { // private ctor } - public static SwarmopsLogEntry FromBasic(BasicSwarmopsLogEntry basic) + public static SwarmopsLogEntry FromBasic (BasicSwarmopsLogEntry basic) { - return new SwarmopsLogEntry(basic); + return new SwarmopsLogEntry (basic); } - public static SwarmopsLogEntry FromIdentity(int swarmopsLogEntryId) + public static SwarmopsLogEntry FromIdentity (int swarmopsLogEntryId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetSwarmopsLogEntry(swarmopsLogEntryId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetSwarmopsLogEntry (swarmopsLogEntryId)); } - public static SwarmopsLogEntry FromIdentityAggressive(int swarmopsLogEntryId) + public static SwarmopsLogEntry FromIdentityAggressive (int swarmopsLogEntryId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetSwarmopsLogEntry(swarmopsLogEntryId)); - // Writing intentional + return FromBasic (SwarmDb.GetDatabaseForWriting().GetSwarmopsLogEntry (swarmopsLogEntryId)); + // Writing intentional } - public static SwarmopsLogEntry Create(Person person, IXmlPayload logEntry, params object[] affectedObjects) + public static SwarmopsLogEntry Create (Person person, IXmlPayload logEntry, params object[] affectedObjects) { - SwarmopsLogEntry entry = SwarmopsLog.CreateEntry(person, logEntry); + SwarmopsLogEntry entry = SwarmopsLog.CreateEntry (person, logEntry); if (person != null) { - entry.CreateAffectedObject(person); + entry.CreateAffectedObject (person); } foreach (IHasIdentity affectedObject in affectedObjects) { - entry.CreateAffectedObject(affectedObject); + entry.CreateAffectedObject (affectedObject); } return entry; } - public void CreateAffectedObject(IHasIdentity affectedObject) + public void CreateAffectedObject (IHasIdentity affectedObject) { string className = affectedObject.GetType().ToString(); - int dotIndex = className.LastIndexOf('.'); + int dotIndex = className.LastIndexOf ('.'); - className = className.Substring(dotIndex + 1); // assumes there's always at least one dot in a class name + className = className.Substring (dotIndex + 1); // assumes there's always at least one dot in a class name SwarmDb.GetDatabaseForWriting() - .CreateSwarmopsLogEntryAffectedObject(Identity, className, affectedObject.Identity); + .CreateSwarmopsLogEntryAffectedObject (Identity, className, affectedObject.Identity); } } } \ No newline at end of file diff --git a/Logic/Support/TemporaryIdentity.cs b/Logic/Support/TemporaryIdentity.cs index d621fc7b..d2aa6d6c 100644 --- a/Logic/Support/TemporaryIdentity.cs +++ b/Logic/Support/TemporaryIdentity.cs @@ -7,7 +7,7 @@ namespace Swarmops.Logic.Support { private readonly int temporaryId; - public TemporaryIdentity(int temporaryId) + public TemporaryIdentity (int temporaryId) { this.temporaryId = temporaryId; } @@ -19,8 +19,8 @@ namespace Swarmops.Logic.Support public static TemporaryIdentity GetNew() { - return new TemporaryIdentity(SwarmDb.GetDatabaseForWriting().GetTemporaryIdentity()); - // This is actually an Insert, not a Select + return new TemporaryIdentity (SwarmDb.GetDatabaseForWriting().GetTemporaryIdentity()); + // This is actually an Insert, not a Select } } } \ No newline at end of file diff --git a/Logic/Support/UrlTranslations.cs b/Logic/Support/UrlTranslations.cs index 368df5d6..7198de5b 100644 --- a/Logic/Support/UrlTranslations.cs +++ b/Logic/Support/UrlTranslations.cs @@ -4,9 +4,9 @@ namespace Swarmops.Logic.Support { public class UrlTranslations { - public static bool Create(string url) + public static bool Create (string url) { - int id = SwarmDb.GetDatabaseForWriting().CreateUrlTranslation(url); + int id = SwarmDb.GetDatabaseForWriting().CreateUrlTranslation (url); if (id > 0) { @@ -15,14 +15,14 @@ namespace Swarmops.Logic.Support return false; } - public static void Set(string originalUrl, string translatedUrl) + public static void Set (string originalUrl, string translatedUrl) { - SwarmDb.GetDatabaseForWriting().SetUrlTranslation(originalUrl, translatedUrl); + SwarmDb.GetDatabaseForWriting().SetUrlTranslation (originalUrl, translatedUrl); } - public static string[] GetUntranslated(int maxCount) + public static string[] GetUntranslated (int maxCount) { - return SwarmDb.GetDatabaseForReading().GetUntranslatedUrls(maxCount); + return SwarmDb.GetDatabaseForReading().GetUntranslatedUrls (maxCount); } } } \ No newline at end of file diff --git a/Logic/Swarm/Activists.cs b/Logic/Swarm/Activists.cs index b6cb87dd..a091a87d 100644 --- a/Logic/Swarm/Activists.cs +++ b/Logic/Swarm/Activists.cs @@ -9,7 +9,7 @@ namespace Swarmops.Logic.Swarm { #region Creation and Construction - private Activists(int[] personIds) + private Activists (int[] personIds) { this.personIds = personIds; } @@ -39,20 +39,20 @@ namespace Swarmops.Logic.Swarm } } - public static int GetCountForGeography(Geography geography) + public static int GetCountForGeography (Geography geography) { Geographies geographies = geography.GetTree(); - return SwarmDb.GetDatabaseForReading().GetActivistCountForGeographies(geographies.Identities); + return SwarmDb.GetDatabaseForReading().GetActivistCountForGeographies (geographies.Identities); } - public static Activists FromGeography(Geography geography) + public static Activists FromGeography (Geography geography) { Geographies geographies = geography.GetTree(); - return new Activists(SwarmDb.GetDatabaseForReading().GetActivistPersonIds(geographies.Identities)); + return new Activists (SwarmDb.GetDatabaseForReading().GetActivistPersonIds (geographies.Identities)); } - public void SendPhoneMessage(string message) + public void SendPhoneMessage (string message) { VerifyPeoplePopulated(); @@ -63,13 +63,13 @@ namespace Swarmops.Logic.Swarm foreach (Person person in this.people) { // Check if we've already sent an sms to this phonenumber during this session - if (!dupeCheck.ContainsKey(person.Phone)) + if (!dupeCheck.ContainsKey (person.Phone)) { dupeCheck[person.Phone] = true; try { - person.SendPhoneMessage(message); + person.SendPhoneMessage (message); } catch (Exception) { @@ -78,13 +78,13 @@ namespace Swarmops.Logic.Swarm } } - public void SendNotice(string subject, string body) + public void SendNotice (string subject, string body) { VerifyPeoplePopulated(); foreach (Person person in this.people) { - person.SendNotice(subject, body, 1); + person.SendNotice (subject, body, 1); } } @@ -93,7 +93,7 @@ namespace Swarmops.Logic.Swarm { if (this.people == null) { - this.people = People.FromIdentities(this.personIds); + this.people = People.FromIdentities (this.personIds); } } } diff --git a/Logic/Swarm/AuditedPerson.cs b/Logic/Swarm/AuditedPerson.cs index f9df1d05..3aaeb57b 100644 --- a/Logic/Swarm/AuditedPerson.cs +++ b/Logic/Swarm/AuditedPerson.cs @@ -11,7 +11,7 @@ namespace Swarmops.Logic.Swarm private string actionDescr = ""; private Person executor; - protected AuditedPerson(Person person) + protected AuditedPerson (Person person) { this.person = person; this.executor = null; @@ -23,7 +23,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Name; } set { - AuditField("Name", Name, value); + AuditField ("Name", Name, value); this.person.Name = value; } } @@ -34,7 +34,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Street; } set { - AuditField("Street", Street, value); + AuditField ("Street", Street, value); this.person.Street = value; } } @@ -45,7 +45,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.PostalCode; } set { - AuditField("PostalCode", PostalCode, value); + AuditField ("PostalCode", PostalCode, value); this.person.PostalCode = value; } } @@ -56,7 +56,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.CityName; } set { - AuditField("City", City, value); + AuditField ("City", City, value); this.person.CityName = value; } } @@ -67,7 +67,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Country; } set { - AuditField("Country", Country == null ? "" : Country.Identity.ToString(), + AuditField ("Country", Country == null ? "" : Country.Identity.ToString(), value == null ? "" : value.Identity.ToString()); this.person.Country = value; } @@ -79,7 +79,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Geography; } set { - AuditField("Geography", Geography == null ? "" : Geography.Identity.ToString(), + AuditField ("Geography", Geography == null ? "" : Geography.Identity.ToString(), value == null ? "" : value.Identity.ToString()); this.person.Geography = value; } @@ -91,7 +91,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Mail; } set { - AuditField("Email", Email, value); + AuditField ("Email", Email, value); this.person.Mail = value; } } @@ -102,7 +102,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Phone; } set { - AuditField("Phone", Phone, value); + AuditField ("Phone", Phone, value); this.person.Phone = value; } } @@ -113,7 +113,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Birthdate; } set { - AuditField("Birthdate", Birthdate.ToString(), value.ToString()); + AuditField ("Birthdate", Birthdate.ToString(), value.ToString()); this.person.Birthdate = value; } } @@ -123,7 +123,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Gender; } set { - AuditField("Gender", Gender.ToString(), value.ToString()); + AuditField ("Gender", Gender.ToString(), value.ToString()); this.person.Gender = value; } } @@ -136,7 +136,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.PartyEmail; } set { - AuditField("PartyEmail", PartyEmail, value); + AuditField ("PartyEmail", PartyEmail, value); this.person.PartyEmail = value; } } @@ -147,7 +147,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.BankName; } set { - AuditField("BankName", BankName, value); + AuditField ("BankName", BankName, value); this.person.BankName = value; } } @@ -158,7 +158,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.BankAccount; } set { - AuditField("BankAccount", BankAccount, value); + AuditField ("BankAccount", BankAccount, value); this.person.BankAccount = value; } } @@ -169,18 +169,18 @@ namespace Swarmops.Logic.Swarm get { return this.person.BankClearing; } set { - AuditField("BankClearing", BankClearing, value); + AuditField ("BankClearing", BankClearing, value); this.person.BankClearing = value; } } - [Obsolete("Use NationalIdNumber instead")] + [Obsolete ("Use NationalIdNumber instead")] public virtual string PersonalNumber { get { return this.person.PersonalNumber; } set { - AuditField("PersonalNumber", PersonalNumber, value); + AuditField ("PersonalNumber", PersonalNumber, value); this.person.PersonalNumber = value; } } @@ -190,7 +190,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.MailUnreachable; } set { - AuditField("MailUnreachable", MailUnreachable.ToString(), value.ToString()); + AuditField ("MailUnreachable", MailUnreachable.ToString(), value.ToString()); this.person.MailUnreachable = value; } } @@ -200,7 +200,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.LimitMailToLatin1; } set { - AuditField("LimitMailToLatin1", LimitMailToLatin1.ToString(), value.ToString()); + AuditField ("LimitMailToLatin1", LimitMailToLatin1.ToString(), value.ToString()); this.person.LimitMailToLatin1 = value; } } @@ -210,7 +210,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.LimitMailToText; } set { - AuditField("LimitMailToText", LimitMailToText.ToString(), value.ToString()); + AuditField ("LimitMailToText", LimitMailToText.ToString(), value.ToString()); this.person.LimitMailToText = value; } } @@ -220,7 +220,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.NeverMail; } set { - AuditField("NeverMail", NeverMail.ToString(), value.ToString()); + AuditField ("NeverMail", NeverMail.ToString(), value.ToString()); this.person.NeverMail = value; } } @@ -230,7 +230,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.EMailIsInvalid; } set { - AuditField("EMailIsInvalid", EMailIsInvalid.ToString(), value.ToString()); + AuditField ("EMailIsInvalid", EMailIsInvalid.ToString(), value.ToString()); this.person.EMailIsInvalid = value; } } @@ -241,7 +241,7 @@ namespace Swarmops.Logic.Swarm get { return this.person.Handle; } set { - AuditField("Handle", Handle, value); + AuditField ("Handle", Handle, value); this.person.Handle = value; } } @@ -251,55 +251,55 @@ namespace Swarmops.Logic.Swarm get { return this.person.SwedishForumAccountId; } set { - AuditField("SwedishForumAccountId", SwedishForumAccountId.ToString(), value.ToString()); + AuditField ("SwedishForumAccountId", SwedishForumAccountId.ToString(), value.ToString()); this.person.SwedishForumAccountId = value; } } - public static implicit operator Person(AuditedPerson a) + public static implicit operator Person (AuditedPerson a) { return a.person; } - public static AuditedPerson FromPerson(Person person) + public static AuditedPerson FromPerson (Person person) { - return new AuditedPerson(person); + return new AuditedPerson (person); } - public static AuditedPerson FromPerson(Person person, Person executor, string actionDescr) + public static AuditedPerson FromPerson (Person person, Person executor, string actionDescr) { - AuditedPerson ap = new AuditedPerson(person); - ap.SetAudit(executor, actionDescr); + AuditedPerson ap = new AuditedPerson (person); + ap.SetAudit (executor, actionDescr); return ap; } - public void SetAudit(Person executor, string actionDescr) + public void SetAudit (Person executor, string actionDescr) { this.executor = executor; this.actionDescr = actionDescr; } - protected void AuditField(string field, string oldVal, string newVal) + protected void AuditField (string field, string oldVal, string newVal) { if (this.executor != null && ("" + oldVal).Trim() != ("" + newVal).Trim()) { - PWLog.Write(this.executor, PWLogItem.Person, this.person.Identity, PWLogAction.PersonFieldChange, + PWLog.Write (this.executor, PWLogItem.Person, this.person.Identity, PWLogAction.PersonFieldChange, this.actionDescr, "", field, "" + oldVal, "" + newVal); } } - public virtual void SetPassword(string newPassword) + public virtual void SetPassword (string newPassword) { - AuditField("SetPassword", "oldpassword", "newpassword"); - this.person.SetPassword(newPassword); + AuditField ("SetPassword", "oldpassword", "newpassword"); + this.person.SetPassword (newPassword); } - public virtual void SetSubscription(int newsletterFeedId, bool subscribe) + public virtual void SetSubscription (int newsletterFeedId, bool subscribe) { - AuditField("SetSubscription", "Feed:" + newsletterFeedId, "" + subscribe); - this.person.SetSubscription(newsletterFeedId, subscribe); + AuditField ("SetSubscription", "Feed:" + newsletterFeedId, "" + subscribe); + this.person.SetSubscription (newsletterFeedId, subscribe); } } } \ No newline at end of file diff --git a/Logic/Swarm/ChurnData.cs b/Logic/Swarm/ChurnData.cs index 019928fb..47cbe2bc 100644 --- a/Logic/Swarm/ChurnData.cs +++ b/Logic/Swarm/ChurnData.cs @@ -32,14 +32,14 @@ namespace Swarmops.Logic.Swarm } } - internal static ChurnData FromArray(BasicChurnDataPoint[] basicArray) + internal static ChurnData FromArray (BasicChurnDataPoint[] basicArray) { ChurnData result = new ChurnData(); result.Capacity = basicArray.Length*11/10; foreach (BasicChurnDataPoint basic in basicArray) { - result.Add(ChurnDataPoint.FromBasic(basic)); + result.Add (ChurnDataPoint.FromBasic (basic)); } return result; @@ -51,47 +51,47 @@ namespace Swarmops.Logic.Swarm /// /// The person churning. /// The organization churned from. - public static void LogChurn(int personId, int organizationId) + public static void LogChurn (int personId, int organizationId) { - SwarmDb.GetDatabaseForWriting().LogChurnData(personId, organizationId, true, DateTime.Now); + SwarmDb.GetDatabaseForWriting().LogChurnData (personId, organizationId, true, DateTime.Now); } - public static void LogRetention(int personId, int organizationId, DateTime expiry) + public static void LogRetention (int personId, int organizationId, DateTime expiry) { - SwarmDb.GetDatabaseForWriting().LogChurnData(personId, organizationId, false, expiry); + SwarmDb.GetDatabaseForWriting().LogChurnData (personId, organizationId, false, expiry); } - public static void LogRetention(int personId, int organizationId, DateTime expiry, DateTime decisionDateTime) + public static void LogRetention (int personId, int organizationId, DateTime expiry, DateTime decisionDateTime) { - SwarmDb.GetDatabaseForWriting().LogChurnData(personId, organizationId, false, expiry, decisionDateTime); + SwarmDb.GetDatabaseForWriting().LogChurnData (personId, organizationId, false, expiry, decisionDateTime); } - public static ChurnData ForOrganization(Organization organization) + public static ChurnData ForOrganization (Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetChurnData(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetChurnData (organization)); } - public static ChurnData ForPerson(Person person) + public static ChurnData ForPerson (Person person) { - return FromArray(SwarmDb.GetDatabaseForReading().GetChurnData(person)); + return FromArray (SwarmDb.GetDatabaseForReading().GetChurnData (person)); } - public static ChurnData GetByDate(Organization organization, DateTime date) + public static ChurnData GetByDate (Organization organization, DateTime date) { - return GetByDate(organization, date, date); + return GetByDate (organization, date, date); } - public static ChurnData GetByDate(Organization organization, DateTime dateLower, DateTime dateUpper) + public static ChurnData GetByDate (Organization organization, DateTime dateLower, DateTime dateUpper) { return - FromArray(SwarmDb.GetDatabaseForReading() - .GetChurnDataForOrganization(organization, dateLower, dateUpper)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetChurnDataForOrganization (organization, dateLower, dateUpper)); } - public int GetRetentionDecisionRangeCount(int minDays, int maxDays) + public int GetRetentionDecisionRangeCount (int minDays, int maxDays) { int count = 0; diff --git a/Logic/Swarm/ChurnDataPoint.cs b/Logic/Swarm/ChurnDataPoint.cs index 9aa384ca..eabf56de 100644 --- a/Logic/Swarm/ChurnDataPoint.cs +++ b/Logic/Swarm/ChurnDataPoint.cs @@ -4,17 +4,17 @@ namespace Swarmops.Logic.Swarm { public class ChurnDataPoint : BasicChurnDataPoint { - private ChurnDataPoint() : base(null) + private ChurnDataPoint() : base (null) { } - private ChurnDataPoint(BasicChurnDataPoint basic) : base(basic) + private ChurnDataPoint (BasicChurnDataPoint basic) : base (basic) { } - internal static ChurnDataPoint FromBasic(BasicChurnDataPoint basic) + internal static ChurnDataPoint FromBasic (BasicChurnDataPoint basic) { - return new ChurnDataPoint(basic); + return new ChurnDataPoint (basic); } } } \ No newline at end of file diff --git a/Logic/Swarm/DashboardTodos.cs b/Logic/Swarm/DashboardTodos.cs index c602543c..6ec1e609 100644 --- a/Logic/Swarm/DashboardTodos.cs +++ b/Logic/Swarm/DashboardTodos.cs @@ -10,15 +10,15 @@ namespace Swarmops.Logic.Swarm { public class DashboardTodos : List { - public static DashboardTodos ForPerson(Person person, Organization organization) + public static DashboardTodos ForPerson (Person person, Organization organization) { DashboardTodos result = new DashboardTodos(); - result.AddExpenseClaimAttestations(person, organization); - result.AddCashAdvanceAttestations(person, organization); + result.AddExpenseClaimAttestations (person, organization); + result.AddCashAdvanceAttestations (person, organization); //result.AddSalaryAttestations(person, organization); TODO! - result.AddReceiptValidations(person, organization); - result.AddPayouts(person, organization); + result.AddReceiptValidations (person, organization); + result.AddPayouts (person, organization); // TODO: Add any hooks @@ -26,14 +26,14 @@ namespace Swarmops.Logic.Swarm } - private void AddReceiptValidations(Person person, Organization organization) + private void AddReceiptValidations (Person person, Organization organization) { - if (!person.HasAccess(new Access(organization, AccessAspect.Financials, AccessType.Write))) + if (!person.HasAccess (new Access (organization, AccessAspect.Financials, AccessType.Write))) { return; } - ExpenseClaims claims = ExpenseClaims.ForOrganization(organization); + ExpenseClaims claims = ExpenseClaims.ForOrganization (organization); claims = claims.WhereUnvalidated; if (claims.Count == 0) @@ -46,27 +46,27 @@ namespace Swarmops.Logic.Swarm if (claims.Count > 1) { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Validate_Receipts_Many, - Formatting.GenerateRangeString(claims.Identities)); + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Validate_Receipts_Many, + Formatting.GenerateRangeString (claims.Identities)); } else { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Validate_Receipts_One, claims[0].Identity); + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Validate_Receipts_One, claims[0].Identity); } todo.Icon = "/Images/PageIcons/iconshock-invoice-greentick-16px.png"; todo.Url = "/Pages/v5/Financial/ValidateReceipts.aspx"; - Add(todo); + Add (todo); } // TODO: Refactor the attest-X functions into one function with minimal differences - private void AddExpenseClaimAttestations(Person person, Organization organization) + private void AddExpenseClaimAttestations (Person person, Organization organization) { - ExpenseClaims claims = ExpenseClaims.ForOrganization(organization); + ExpenseClaims claims = ExpenseClaims.ForOrganization (organization); List expenseClaimIds = new List(); bool isPersonOrgAdmin = false; @@ -96,7 +96,7 @@ namespace Swarmops.Logic.Swarm if (attestable) { - expenseClaimIds.Add(claim.Identity); + expenseClaimIds.Add (claim.Identity); } } @@ -106,25 +106,25 @@ namespace Swarmops.Logic.Swarm if (expenseClaimIds.Count > 1) { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Attest_ExpenseClaim_Many, - Formatting.GenerateRangeString(expenseClaimIds)); + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Attest_ExpenseClaim_Many, + Formatting.GenerateRangeString (expenseClaimIds)); } else { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Attest_ExpenseClaim_One, + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Attest_ExpenseClaim_One, expenseClaimIds[0]); } todo.Icon = "/Images/PageIcons/iconshock-stamped-paper-16px.png"; todo.Url = "/Pages/v5/Financial/AttestCosts.aspx"; - Add(todo); + Add (todo); } } - private void AddCashAdvanceAttestations(Person person, Organization organization) + private void AddCashAdvanceAttestations (Person person, Organization organization) { - CashAdvances advances = CashAdvances.ForOrganization(organization); + CashAdvances advances = CashAdvances.ForOrganization (organization); List cashAdvanceIds = new List(); bool isPersonOrgAdmin = false; @@ -155,7 +155,7 @@ namespace Swarmops.Logic.Swarm if (attestable) { - cashAdvanceIds.Add(advance.Identity); + cashAdvanceIds.Add (advance.Identity); } } @@ -165,25 +165,25 @@ namespace Swarmops.Logic.Swarm if (cashAdvanceIds.Count > 1) { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Attest_CashAdvance_Many, - Formatting.GenerateRangeString(cashAdvanceIds)); + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Attest_CashAdvance_Many, + Formatting.GenerateRangeString (cashAdvanceIds)); } else { - todo.Description = String.Format(Logic_Swarm_DashboardTodos.Attest_CashAdvance_One, + todo.Description = String.Format (Logic_Swarm_DashboardTodos.Attest_CashAdvance_One, cashAdvanceIds[0]); } todo.Icon = "/Images/PageIcons/iconshock-stamped-paper-16px.png"; todo.Url = "/Pages/v5/Financial/AttestCosts.aspx"; - Add(todo); + Add (todo); } } - private void AddPayouts(Person person, Organization organization) + private void AddPayouts (Person person, Organization organization) { - if (!person.HasAccess(new Access(organization, AccessAspect.Financials, AccessType.Write))) + if (!person.HasAccess (new Access (organization, AccessAspect.Financials, AccessType.Write))) { return; // do not add this if can't pay out } @@ -204,7 +204,7 @@ namespace Swarmops.Logic.Swarm int urgentPayoutCount = 0; int overduePayoutCount = 0; - Payouts payouts = Payouts.Construct(organization); + Payouts payouts = Payouts.Construct (organization); foreach (Payout payout in payouts) { @@ -216,7 +216,7 @@ namespace Swarmops.Logic.Swarm { overduePayoutCount++; } - else if (payout.ExpectedTransactionDate < DateTime.Today.AddDays(7)) + else if (payout.ExpectedTransactionDate < DateTime.Today.AddDays (7)) { urgentPayoutCount++; } @@ -226,30 +226,30 @@ namespace Swarmops.Logic.Swarm if (payoutCount > 0) { todoNormal.Description = payoutCount > 1 - ? String.Format(Logic_Swarm_DashboardTodos.Payout_Many, + ? String.Format (Logic_Swarm_DashboardTodos.Payout_Many, payoutCount) : Logic_Swarm_DashboardTodos.Payout_One; - Add(todoNormal); + Add (todoNormal); } if (overduePayoutCount > 0) { todoOverdue.Description = overduePayoutCount > 1 - ? String.Format(Logic_Swarm_DashboardTodos.Payout_Overdue_Many, + ? String.Format (Logic_Swarm_DashboardTodos.Payout_Overdue_Many, payoutCount) : Logic_Swarm_DashboardTodos.Payout_Overdue_One; todoOverdue.Urgency = TodoUrgency.Red; - Add(todoOverdue); + Add (todoOverdue); } if (urgentPayoutCount > 0) { todoUrgent.Description = overduePayoutCount > 1 - ? String.Format(Logic_Swarm_DashboardTodos.Payout_Urgent_Many, + ? String.Format (Logic_Swarm_DashboardTodos.Payout_Urgent_Many, payoutCount) : Logic_Swarm_DashboardTodos.Payout_Urgent_One; todoUrgent.Urgency = TodoUrgency.Yellow; - Add(todoUrgent); + Add (todoUrgent); } } } diff --git a/Logic/Swarm/ExternalActivities.cs b/Logic/Swarm/ExternalActivities.cs index 44452c48..5844fc6a 100644 --- a/Logic/Swarm/ExternalActivities.cs +++ b/Logic/Swarm/ExternalActivities.cs @@ -23,30 +23,30 @@ namespace Swarmops.Logic.Swarm CreationDateDescending } - public static ExternalActivities ForOrganization(Organization organization) + public static ExternalActivities ForOrganization (Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetExternalActivities(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetExternalActivities (organization)); } - public static ExternalActivities ForOrganization(Organization organization, SortOrder sort, int count) + public static ExternalActivities ForOrganization (Organization organization, SortOrder sort, int count) { return - FromArray(SwarmDb.GetDatabaseForReading() - .GetExternalActivitiesSorted(sort.ToString(), count, organization)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetExternalActivitiesSorted (sort.ToString(), count, organization)); } - public void Sort(SortOrder order) + public void Sort (SortOrder order) { switch (order) { case SortOrder.DateDescending: - Sort(ExternalActivity.CompareDateDescending); + Sort (ExternalActivity.CompareDateDescending); break; case SortOrder.CreationDateDescending: - Sort(ExternalActivity.CompareCreationDateDescending); + Sort (ExternalActivity.CompareCreationDateDescending); break; default: - throw new NotImplementedException("Unimplemented sort order"); + throw new NotImplementedException ("Unimplemented sort order"); } } } diff --git a/Logic/Swarm/ExternalActivity.cs b/Logic/Swarm/ExternalActivity.cs index 012a8fb5..fbb4414d 100644 --- a/Logic/Swarm/ExternalActivity.cs +++ b/Logic/Swarm/ExternalActivity.cs @@ -8,45 +8,45 @@ namespace Swarmops.Logic.Swarm { public class ExternalActivity : BasicExternalActivity { - private ExternalActivity(BasicExternalActivity basic) : base(basic) + private ExternalActivity (BasicExternalActivity basic) : base (basic) { // empty private ctor } public Geography Geography { - get { return Geography.FromIdentity(GeographyId); } + get { return Geography.FromIdentity (GeographyId); } } - public static ExternalActivity FromBasic(BasicExternalActivity basic) + public static ExternalActivity FromBasic (BasicExternalActivity basic) { - return new ExternalActivity(basic); + return new ExternalActivity (basic); } - public static ExternalActivity FromIdentity(int externalActivityId) + public static ExternalActivity FromIdentity (int externalActivityId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetExternalActivity(externalActivityId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetExternalActivity (externalActivityId)); } - public static ExternalActivity Create(Organization organization, Geography geograpy, ExternalActivityType type, + public static ExternalActivity Create (Organization organization, Geography geograpy, ExternalActivityType type, DateTime date, string description, Person createdByPerson) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateExternalActivity(organization.Identity, geograpy.Identity, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateExternalActivity (organization.Identity, geograpy.Identity, date, type, description, createdByPerson.Identity)); } - public static int CompareDateDescending(ExternalActivity a, ExternalActivity b) + public static int CompareDateDescending (ExternalActivity a, ExternalActivity b) { - return -DateTime.Compare(a.DateTime, b.DateTime); + return -DateTime.Compare (a.DateTime, b.DateTime); } - public static int CompareCreationDateDescending(ExternalActivity a, ExternalActivity b) + public static int CompareCreationDateDescending (ExternalActivity a, ExternalActivity b) { - return -DateTime.Compare(a.CreatedDateTime, b.CreatedDateTime); + return -DateTime.Compare (a.CreatedDateTime, b.CreatedDateTime); } } } \ No newline at end of file diff --git a/Logic/Swarm/ExternalIdentity.cs b/Logic/Swarm/ExternalIdentity.cs index e8e6122c..f4da0d2f 100644 --- a/Logic/Swarm/ExternalIdentity.cs +++ b/Logic/Swarm/ExternalIdentity.cs @@ -10,8 +10,8 @@ namespace Swarmops.Logic.Swarm { private Person attachedToPerson; - private ExternalIdentity(BasicExternalIdentity basic) - : base(basic) + private ExternalIdentity (BasicExternalIdentity basic) + : base (basic) { } @@ -21,7 +21,7 @@ namespace Swarmops.Logic.Swarm get { return base.ExternalIdentityIdentity; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } @@ -31,7 +31,7 @@ namespace Swarmops.Logic.Swarm get { return base.ExternalSystem; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } @@ -41,7 +41,7 @@ namespace Swarmops.Logic.Swarm get { return base.UserID; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } @@ -51,7 +51,7 @@ namespace Swarmops.Logic.Swarm get { return base.Password; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } @@ -61,12 +61,12 @@ namespace Swarmops.Logic.Swarm get { if (this.attachedToPerson == null) - this.attachedToPerson = Person.FromIdentity(base.AttachedToPersonID); + this.attachedToPerson = Person.FromIdentity (base.AttachedToPersonID); return this.attachedToPerson; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } @@ -76,59 +76,59 @@ namespace Swarmops.Logic.Swarm get { return base.TypeOfAccount; } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } - public static ExternalIdentity FromBasic(BasicExternalIdentity basic) + public static ExternalIdentity FromBasic (BasicExternalIdentity basic) { - return new ExternalIdentity(basic); + return new ExternalIdentity (basic); } - public static ExternalIdentity FromIdentity(int externalIdentityId) + public static ExternalIdentity FromIdentity (int externalIdentityId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetExternalIdentity(externalIdentityId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetExternalIdentity (externalIdentityId)); } - public static ExternalIdentity FromUserIdAndType(string userid, ExternalIdentityType type) + public static ExternalIdentity FromUserIdAndType (string userid, ExternalIdentityType type) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetExternalIdentityFromUserIdAndType(userid, type)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetExternalIdentityFromUserIdAndType (userid, type)); } - public static ExternalIdentity FromPersonIdAndType(int persId, ExternalIdentityType type) + public static ExternalIdentity FromPersonIdAndType (int persId, ExternalIdentityType type) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetExternalIdentityFromPersonIdAndType(persId, type)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetExternalIdentityFromPersonIdAndType (persId, type)); } - public static List ExternalItentitiesForPerson(int persId) + public static List ExternalItentitiesForPerson (int persId) { - List templist = SwarmDb.GetDatabaseForReading().GetExternalIdentities(persId); + List templist = SwarmDb.GetDatabaseForReading().GetExternalIdentities (persId); List retlist = new List(); foreach (BasicExternalIdentity ext in templist) { - retlist.Add(FromBasic(ext)); + retlist.Add (FromBasic (ext)); } return retlist; } - public ExternalIdentity SetExternalIdentity(string ExternalSystem, + public ExternalIdentity SetExternalIdentity (string ExternalSystem, string UserID, string Password, int AttachedToPerson, ExternalIdentityType TypeOfAccount) { - return FromBasic(SwarmDb.GetDatabaseForWriting().SetExternalIdentity( + return FromBasic (SwarmDb.GetDatabaseForWriting().SetExternalIdentity ( Identity, TypeOfAccount, ExternalSystem, UserID, Password, AttachedToPerson)); } - public static ExternalIdentity CreateExternalIdentity(string ExternalSystem, + public static ExternalIdentity CreateExternalIdentity (string ExternalSystem, string UserID, string Password, int AttachedToPerson, @@ -136,13 +136,13 @@ namespace Swarmops.Logic.Swarm { try { - return FromBasic(SwarmDb.GetDatabaseForWriting().SetExternalIdentity( + return FromBasic (SwarmDb.GetDatabaseForWriting().SetExternalIdentity ( 0, TypeOfAccount, ExternalSystem, UserID, Password, AttachedToPerson)); } catch (Exception ex) { - throw new Exception("Failed to create ExternalIdentity", ex); + throw new Exception ("Failed to create ExternalIdentity", ex); } } } diff --git a/Logic/Swarm/Interfaces.cs b/Logic/Swarm/Interfaces.cs index 76764f13..a6be9eb1 100644 --- a/Logic/Swarm/Interfaces.cs +++ b/Logic/Swarm/Interfaces.cs @@ -2,6 +2,6 @@ { public interface IOwnerSettable { - void SetOwner(Person newOwner); + void SetOwner (Person newOwner); } } \ No newline at end of file diff --git a/Logic/Swarm/Membership.cs b/Logic/Swarm/Membership.cs index 87764248..7a203b2e 100644 --- a/Logic/Swarm/Membership.cs +++ b/Logic/Swarm/Membership.cs @@ -17,8 +17,8 @@ namespace Swarmops.Logic.Swarm private BasicMembershipPaymentStatus paymentStatus; private Person person; - private Membership(BasicMembership basic) - : base(basic) + private Membership (BasicMembership basic) + : base (basic) { } @@ -28,7 +28,7 @@ namespace Swarmops.Logic.Swarm { if (this.person == null) { - this.person = Person.FromIdentity(base.PersonId); + this.person = Person.FromIdentity (base.PersonId); } return this.person; @@ -41,7 +41,7 @@ namespace Swarmops.Logic.Swarm { if (this.organization == null) { - this.organization = Organization.FromIdentity(base.OrganizationId); + this.organization = Organization.FromIdentity (base.OrganizationId); } return this.organization; @@ -55,11 +55,11 @@ namespace Swarmops.Logic.Swarm { if (base.Expires != value) { - if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) + if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime (1900, 1, 1)) { - ChurnData.LogRetention(PersonId, OrganizationId, base.Expires); + ChurnData.LogRetention (PersonId, OrganizationId, base.Expires); } - SwarmDb.GetDatabaseForWriting().SetMembershipExpires(Identity, value); + SwarmDb.GetDatabaseForWriting().SetMembershipExpires (Identity, value); base.Expires = value; } } @@ -74,7 +74,7 @@ namespace Swarmops.Logic.Swarm } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "It is not allowed to set PaymentStatus separately. Use SetPaymentStatus() method."); // Rick: Isn't it better to not have a setter at all and get the error compile-time rather than run-time? @@ -91,16 +91,16 @@ namespace Swarmops.Logic.Swarm } private set { - throw new InvalidOperationException( + throw new InvalidOperationException ( "It is not allowed to set PaymentStatusDate separately. Use SetPaymentStatus() method"); // Rick: Isn't it better to not have a setter at all and get the error compile-time rather than run-time? } } - public void SetPaymentStatus(MembershipPaymentStatus status, DateTime dateTime) + public void SetPaymentStatus (MembershipPaymentStatus status, DateTime dateTime) { - SwarmDb.GetDatabaseForWriting().SetMembershipPaymentStatus(Identity, status, dateTime); + SwarmDb.GetDatabaseForWriting().SetMembershipPaymentStatus (Identity, status, dateTime); LoadPaymentStatus(); this.paymentStatus.Status = status; this.paymentStatus.StatusDateTime = dateTime; @@ -110,19 +110,19 @@ namespace Swarmops.Logic.Swarm { if (this.paymentStatus == null) { - this.paymentStatus = SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatus(Identity); + this.paymentStatus = SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatus (Identity); } } //Optimization metod, loadMultiple in one call - public static void LoadPaymentStatuses(Memberships mss) + public static void LoadPaymentStatuses (Memberships mss) { Dictionary statuses = - SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatuses(mss.Identities); + SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatuses (mss.Identities); foreach (Membership ms in mss) { - if (ms.paymentStatus == null && statuses.ContainsKey(ms.Identity)) + if (ms.paymentStatus == null && statuses.ContainsKey (ms.Identity)) { ms.paymentStatus = statuses[ms.Identity]; } @@ -130,44 +130,44 @@ namespace Swarmops.Logic.Swarm } - public static Membership FromBasic(BasicMembership basic) + public static Membership FromBasic (BasicMembership basic) { - return new Membership(basic); + return new Membership (basic); } - public static Membership FromIdentity(int membershipId) + public static Membership FromIdentity (int membershipId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMembership(membershipId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetMembership (membershipId)); } - public static Membership FromIdentityAggressive(int membershipId) + public static Membership FromIdentityAggressive (int membershipId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetMembership(membershipId)); + return FromBasic (SwarmDb.GetDatabaseForWriting().GetMembership (membershipId)); } - public static Membership FromPersonAndOrganization(int personId, int organizationId) + public static Membership FromPersonAndOrganization (int personId, int organizationId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetActiveMembership(personId, organizationId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetActiveMembership (personId, organizationId)); } - public static Membership Create(int personId, int organizationId, DateTime expires) + public static Membership Create (int personId, int organizationId, DateTime expires) { - int membershipId = SwarmDb.GetDatabaseForWriting().CreateMembership(personId, organizationId, expires); + int membershipId = SwarmDb.GetDatabaseForWriting().CreateMembership (personId, organizationId, expires); - return FromIdentityAggressive(membershipId); + return FromIdentityAggressive (membershipId); } - public static Membership Create(Person person, Organization organization, DateTime expires) + public static Membership Create (Person person, Organization organization, DateTime expires) { - return Create(person.Identity, organization.Identity, expires); + return Create (person.Identity, organization.Identity, expires); } - public static Membership Import(Person person, Organization organization, DateTime memberSince, + public static Membership Import (Person person, Organization organization, DateTime memberSince, DateTime expires) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .ImportMembership(person.Identity, organization.Identity, memberSince, + FromIdentity (SwarmDb.GetDatabaseForWriting() + .ImportMembership (person.Identity, organization.Identity, memberSince, expires)); } @@ -178,7 +178,7 @@ namespace Swarmops.Logic.Swarm //} - public void Terminate(EventSource eventSource, Person actingPerson, string description) + public void Terminate (EventSource eventSource, Person actingPerson, string description) { if (base.Active) { @@ -192,15 +192,15 @@ namespace Swarmops.Logic.Swarm foreach (BasicPersonRole basicRole in roles) { - PersonRole personRole = PersonRole.FromBasic(basicRole); - theRoles.Add(personRole); + PersonRole personRole = PersonRole.FromBasic (basicRole); + theRoles.Add (personRole); if (personRole.OrganizationId == OrganizationId) { - PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, + PWEvents.CreateEvent (eventSource, EventType.DeletedRole, actingPersonId, personRole.OrganizationId, personRole.GeographyId, Person.Identity, (int) personRole.Type, string.Empty); - PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, + PWLog.Write (actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, "Role " + personRole.Type + " of " + personRole.Geography.Name + " was deleted with membership.", string.Empty); personRole.Delete(); @@ -210,13 +210,13 @@ namespace Swarmops.Logic.Swarm //now check if this means that you no longer are a member of some uplevel org, then remove those roles as well foreach (PersonRole personRole in theRoles) { - if (!Person.MemberOfWithInherited(personRole.Organization)) + if (!Person.MemberOfWithInherited (personRole.Organization)) { - PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, + PWEvents.CreateEvent (eventSource, EventType.DeletedRole, actingPersonId, personRole.OrganizationId, personRole.GeographyId, Person.Identity, (int) personRole.Type, string.Empty); - PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, + PWLog.Write (actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, "Role " + personRole.Type + " of " + personRole.Geography.Name + " was deleted with membership of all suborgs.", string.Empty); personRole.Delete(); @@ -237,18 +237,18 @@ namespace Swarmops.Logic.Swarm } - PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.MemberLost, + PWLog.Write (actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.MemberLost, eventSource + ":" + description, string.Empty); - PWEvents.CreateEvent(src, EventType.LostMember, actingPersonId, OrganizationId, Person.GeographyId, + PWEvents.CreateEvent (src, EventType.LostMember, actingPersonId, OrganizationId, Person.GeographyId, Person.Identity, 0, OrganizationId.ToString()); //Added LogChurn here to make SURE they always are logged with the membership. - if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) + if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime (1900, 1, 1)) { - ChurnData.LogChurn(PersonId, OrganizationId); + ChurnData.LogChurn (PersonId, OrganizationId); } - SwarmDb.GetDatabaseForWriting().TerminateMembership(Identity); + SwarmDb.GetDatabaseForWriting().TerminateMembership (Identity); base.Active = false; base.DateTerminated = DateTime.Now; @@ -260,9 +260,9 @@ namespace Swarmops.Logic.Swarm { try { - if (this.person.IsSubscribing(newsletterFeedId)) + if (this.person.IsSubscribing (newsletterFeedId)) { - this.person.SetSubscription(newsletterFeedId, false); + this.person.SetSubscription (newsletterFeedId, false); } } catch (Exception) diff --git a/Logic/Swarm/MembershipEvent.cs b/Logic/Swarm/MembershipEvent.cs index 05d95579..4c643786 100644 --- a/Logic/Swarm/MembershipEvent.cs +++ b/Logic/Swarm/MembershipEvent.cs @@ -25,7 +25,7 @@ namespace Swarmops.Logic.Swarm this.Gender = PersonGender.Unknown; } - public MembershipEvent(DateTime dateTime, int personId, int organizationId, int geographyId, int birthYear, + public MembershipEvent (DateTime dateTime, int personId, int organizationId, int geographyId, int birthYear, PersonGender gender, int deltaCount) { this.DateTime = dateTime; diff --git a/Logic/Swarm/MembershipEvents.cs b/Logic/Swarm/MembershipEvents.cs index 4a5420a0..6e9a998d 100644 --- a/Logic/Swarm/MembershipEvents.cs +++ b/Logic/Swarm/MembershipEvents.cs @@ -51,19 +51,19 @@ namespace Swarmops.Logic.Swarm int birthYear = 0; PersonGender gender = PersonGender.Unknown; - if (geoLookup.ContainsKey(membership.PersonId)) + if (geoLookup.ContainsKey (membership.PersonId)) { geographyId = geoLookup[membership.PersonId]; gender = genderLookup[membership.PersonId]; birthYear = birthYearLookup[membership.PersonId]; } - result.Add(new MembershipEvent(membership.MemberSince, membership.PersonId, membership.OrganizationId, + result.Add (new MembershipEvent (membership.MemberSince, membership.PersonId, membership.OrganizationId, geographyId, birthYear, gender, 1)); if (!membership.Active) { - TimeSpan safetyDelta = new TimeSpan(0); + TimeSpan safetyDelta = new TimeSpan (0); // A few records in the database have had their memberships terminated at the exact time of creation. This means that sorting will // be unpredictable, when it relies on the termination coming at a later time than the creation. @@ -73,13 +73,13 @@ namespace Swarmops.Logic.Swarm if (membership.DateTerminated.Date == membership.MemberSince.Date) // First simple check { - if ((membership.DateTerminated - membership.MemberSince) < new TimeSpan(0, 0, 5)) + if ((membership.DateTerminated - membership.MemberSince) < new TimeSpan (0, 0, 5)) { - safetyDelta = new TimeSpan(0, 0, 5); + safetyDelta = new TimeSpan (0, 0, 5); } } - result.Add(new MembershipEvent(membership.DateTerminated + safetyDelta, + result.Add (new MembershipEvent (membership.DateTerminated + safetyDelta, membership.PersonId, membership.OrganizationId, geographyId, birthYear, gender, -1)); } @@ -87,22 +87,22 @@ namespace Swarmops.Logic.Swarm // Fourth - sort - result.Sort(new MembershipEventSorter()); + result.Sort (new MembershipEventSorter()); return result; } - public static MembershipEvents FromXml(string xml) + public static MembershipEvents FromXml (string xml) { - XmlSerializer serializer = new XmlSerializer(typeof (MembershipEvents)); + XmlSerializer serializer = new XmlSerializer (typeof (MembershipEvents)); MemoryStream stream = new MemoryStream(); - byte[] xmlBytes = Encoding.Default.GetBytes(xml); - stream.Write(xmlBytes, 0, xmlBytes.Length); + byte[] xmlBytes = Encoding.Default.GetBytes (xml); + stream.Write (xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - MembershipEvents result = (MembershipEvents) serializer.Deserialize(stream); + MembershipEvents result = (MembershipEvents) serializer.Deserialize (stream); stream.Close(); return result; @@ -111,13 +111,13 @@ namespace Swarmops.Logic.Swarm public string ToXml() { - XmlSerializer serializer = new XmlSerializer(typeof (MembershipEvents)); + XmlSerializer serializer = new XmlSerializer (typeof (MembershipEvents)); MemoryStream stream = new MemoryStream(); - serializer.Serialize(stream, this); + serializer.Serialize (stream, this); byte[] xmlBytes = stream.GetBuffer(); - return Encoding.Default.GetString(xmlBytes); + return Encoding.Default.GetString (xmlBytes); } } @@ -125,7 +125,7 @@ namespace Swarmops.Logic.Swarm { #region IComparer Members - public int Compare(MembershipEvent x, MembershipEvent y) + public int Compare (MembershipEvent x, MembershipEvent y) { if (x.DateTime < y.DateTime) { diff --git a/Logic/Swarm/Memberships.cs b/Logic/Swarm/Memberships.cs index a0a2d2b8..3e59ffbe 100644 --- a/Logic/Swarm/Memberships.cs +++ b/Logic/Swarm/Memberships.cs @@ -12,17 +12,17 @@ namespace Swarmops.Logic.Swarm { public int[] Identities { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + get { return LogicServices.ObjectsToIdentifiers (ToArray()); } } - public static Memberships FromArray(BasicMembership[] basicArray) + public static Memberships FromArray (BasicMembership[] basicArray) { Memberships result = new Memberships(); result.Capacity = basicArray.Length*11/10; foreach (BasicMembership basic in basicArray) { - result.Add(Membership.FromBasic(basic)); + result.Add (Membership.FromBasic (basic)); } return result; @@ -35,102 +35,105 @@ namespace Swarmops.Logic.Swarm return LogicServices.GetDatabase().GetMembershipsForPerson(personId); }*/ - public static int GetMemberCountForOrganization(Organization organization) + public static int GetMemberCountForOrganization (Organization organization) { - return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizations(new[] {organization.Identity}); + return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizations (new[] {organization.Identity}); } - public static int GetMemberCountForOrganizations(int[] organizationIds) + public static int GetMemberCountForOrganizations (int[] organizationIds) { - return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizations(organizationIds); + return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizations (organizationIds); } - public static int GetMemberCountForOrganizationSince(Organization org, DateTime sinceDateTime) + public static int GetMemberCountForOrganizationSince (Organization org, DateTime sinceDateTime) { - return GetMemberCountForOrganizationSince(org.Identity, sinceDateTime); + return GetMemberCountForOrganizationSince (org.Identity, sinceDateTime); } - public static int GetMemberCountForOrganizationSince(int orgId, DateTime sinceDateTime) + public static int GetMemberCountForOrganizationSince (int orgId, DateTime sinceDateTime) { - return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizationsSince(new[] {orgId}, sinceDateTime); + return SwarmDb.GetDatabaseForReading() + .GetMembershipCountForOrganizationsSince (new[] {orgId}, sinceDateTime); } - public static int GetMemberCountForOrganizations(Organizations organizations) + public static int GetMemberCountForOrganizations (Organizations organizations) { List idArray = new List(); foreach (Organization organization in organizations) { - idArray.Add(organization.Identity); + idArray.Add (organization.Identity); } - return GetMemberCountForOrganizations(idArray.ToArray()); + return GetMemberCountForOrganizations (idArray.ToArray()); } - public Memberships RemoveToMatchAuthority(Geography personGeography, Authority authority) + public Memberships RemoveToMatchAuthority (Geography personGeography, Authority authority) { - return Authorization.FilterMembershipsToMatchAuthority(this, personGeography, authority); + return Authorization.FilterMembershipsToMatchAuthority (this, personGeography, authority); } - public static Memberships ForOrganization(Organization organization, bool includeTerminated) + public static Memberships ForOrganization (Organization organization, bool includeTerminated) { if (!includeTerminated) { - return ForOrganization(organization); + return ForOrganization (organization); } - return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (organization)); } - public static Memberships ForOrganization(Organization organization) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organization, DatabaseCondition.ActiveTrue)); - } - - public static Memberships ForOrganizations(Organizations organizations, bool includeTerminated) - { - if (!includeTerminated) - { - return ForOrganizations(organizations); - } - - return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organizations)); - } - - public static Memberships ForOrganizations(Organizations organizations) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organizations, DatabaseCondition.ActiveTrue)); - } - - public static Memberships GetExpiring(Organization organization, DateTime dateExpiry) - { - return GetExpiring(organization, dateExpiry, dateExpiry); - } - - public static Memberships GetExpired(Organization organization) + public static Memberships ForOrganization (Organization organization) { return - FromArray(SwarmDb.GetDatabaseForReading().GetExpiringMemberships(organization, DateTime.MinValue, + FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (organization, DatabaseCondition.ActiveTrue)); + } + + public static Memberships ForOrganizations (Organizations organizations, bool includeTerminated) + { + if (!includeTerminated) + { + return ForOrganizations (organizations); + } + + return FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (organizations)); + } + + public static Memberships ForOrganizations (Organizations organizations) + { + return + FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (organizations, DatabaseCondition.ActiveTrue)); + } + + public static Memberships GetExpiring (Organization organization, DateTime dateExpiry) + { + return GetExpiring (organization, dateExpiry, dateExpiry); + } + + public static Memberships GetExpired (Organization organization) + { + return + FromArray (SwarmDb.GetDatabaseForReading().GetExpiringMemberships (organization, DateTime.MinValue, DateTime.Now)); } - public static Memberships GetExpired(Organization organization, DateTime lowerBound, DateTime upperBound) + public static Memberships GetExpired (Organization organization, DateTime lowerBound, DateTime upperBound) { return - FromArray(SwarmDb.GetDatabaseForReading() - .GetExpiringMemberships(organization, lowerBound, upperBound, DatabaseCondition.None)); + FromArray (SwarmDb.GetDatabaseForReading() + .GetExpiringMemberships (organization, lowerBound, upperBound, DatabaseCondition.None)); } - public static Memberships GetExpiring(Organization organization, DateTime lowerBound, DateTime upperBound) + public static Memberships GetExpiring (Organization organization, DateTime lowerBound, DateTime upperBound) { return - FromArray(SwarmDb.GetDatabaseForReading().GetExpiringMemberships(organization, lowerBound, upperBound)); + FromArray (SwarmDb.GetDatabaseForReading().GetExpiringMemberships (organization, lowerBound, upperBound)); } - public static Dictionary> GetMembershipsForPeople(int[] personIds, int gracePeriod) + public static Dictionary> GetMembershipsForPeople (int[] personIds, int gracePeriod) { - return SwarmDb.GetDatabaseForReading().GetMembershipsForPeople(personIds, gracePeriod); + return SwarmDb.GetDatabaseForReading().GetMembershipsForPeople (personIds, gracePeriod); } } } \ No newline at end of file diff --git a/Logic/Swarm/OfficerChain.cs b/Logic/Swarm/OfficerChain.cs index 529be934..85aebf6b 100644 --- a/Logic/Swarm/OfficerChain.cs +++ b/Logic/Swarm/OfficerChain.cs @@ -6,26 +6,26 @@ namespace Swarmops.Logic.Swarm { private readonly int organizationId; - private OfficerChain(People original, int organizationId) + private OfficerChain (People original, int organizationId) { - InsertRange(0, original); + InsertRange (0, original); this.organizationId = organizationId; } - public new static OfficerChain FromOrganizationAndGeography(Organization org, Geography geo) + public new static OfficerChain FromOrganizationAndGeography (Organization org, Geography geo) { - int[] concernedPeopleId = Roles.GetAllUpwardRoles(org.Identity, geo.Identity); - People concernedPeople = FromIdentities(concernedPeopleId); + int[] concernedPeopleId = Roles.GetAllUpwardRoles (org.Identity, geo.Identity); + People concernedPeople = FromIdentities (concernedPeopleId); - return new OfficerChain(concernedPeople, org.Identity); + return new OfficerChain (concernedPeople, org.Identity); } - public void SendNotice(string subject, string body) + public void SendNotice (string subject, string body) { foreach (Person person in this) { - person.SendOfficerNotice(subject, body, this.organizationId); + person.SendOfficerNotice (subject, body, this.organizationId); } } } diff --git a/Logic/Swarm/Parley.cs b/Logic/Swarm/Parley.cs index 88a4e4ee..740f466c 100644 --- a/Logic/Swarm/Parley.cs +++ b/Logic/Swarm/Parley.cs @@ -11,29 +11,29 @@ namespace Swarmops.Logic.Swarm { public class Parley : BasicParley, IAttestable { - private Parley(BasicParley basic) : base(basic) + private Parley (BasicParley basic) : base (basic) { // empty pvt ctor } public ParleyOptions Options { - get { return ParleyOptions.ForParley(this); } + get { return ParleyOptions.ForParley (this); } } public ParleyAttendees Attendees { - get { return ParleyAttendees.ForParley(this); } + get { return ParleyAttendees.ForParley (this); } } public Organization Organization { - get { return Organization.FromIdentity(OrganizationId); } + get { return Organization.FromIdentity (OrganizationId); } } public Person Person { - get { return Person.FromIdentity(PersonId); } + get { return Person.FromIdentity (PersonId); } } public decimal BudgetDecimal @@ -59,7 +59,7 @@ namespace Swarmops.Logic.Swarm if (base.Open != value) { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetParleyOpen(Identity, value); + SwarmDb.GetDatabaseForWriting().SetParleyOpen (Identity, value); } } } @@ -82,7 +82,7 @@ namespace Swarmops.Logic.Swarm get { BasicFinancialValidation[] validations = - SwarmDb.GetDatabaseForReading().GetFinancialValidations(FinancialDependencyType.Parley, + SwarmDb.GetDatabaseForReading().GetFinancialValidations (FinancialDependencyType.Parley, Identity); foreach (BasicFinancialValidation validation in validations) @@ -107,13 +107,13 @@ namespace Swarmops.Logic.Swarm if (base.BudgetId < 0) { - return FinancialAccount.FromIdentity(-base.BudgetId); + return FinancialAccount.FromIdentity (-base.BudgetId); } - return this.Budget.Parent; + return Budget.Parent; } } - public void Attest(Person attester) + public void Attest (Person attester) { if (Attested) { @@ -128,7 +128,7 @@ namespace Swarmops.Logic.Swarm if (base.BudgetId < 0) // no account created yet { - ourBudget = FinancialAccount.Create(Budget.Organization, + ourBudget = FinancialAccount.Create (Budget.Organization, "Conf: " + Name, FinancialAccountType.Cost, Budget); @@ -137,7 +137,7 @@ namespace Swarmops.Logic.Swarm base.BudgetId = ourBudget.Identity; ourBudget.Owner = Person; - SwarmDb.GetDatabaseForWriting().SetParleyBudget(Identity, ourBudget.Identity); + SwarmDb.GetDatabaseForWriting().SetParleyBudget (Identity, ourBudget.Identity); } else { @@ -146,7 +146,7 @@ namespace Swarmops.Logic.Swarm if (!AttestedOnce) { - throw new InvalidOperationException( + throw new InvalidOperationException ( "Budget exists despite parley not having been attested. This should not be possible."); } @@ -154,32 +154,32 @@ namespace Swarmops.Logic.Swarm parentBudget = ParentBudget; } - ourBudget.SetBudgetCents(DateTime.Today.Year, -BudgetCents); - parentBudget.SetBudgetCents(DateTime.Today.Year, - parentBudget.GetBudgetCents(year) + BudgetCents); // cost budgets are negative + ourBudget.SetBudgetCents (DateTime.Today.Year, -BudgetCents); + parentBudget.SetBudgetCents (DateTime.Today.Year, + parentBudget.GetBudgetCents (year) + BudgetCents); // cost budgets are negative // Reserve the guarantee money - FinancialTransaction guaranteeFundsTx = FinancialTransaction.Create(OrganizationId, DateTime.Now, + FinancialTransaction guaranteeFundsTx = FinancialTransaction.Create (OrganizationId, DateTime.Now, "Conference #" + Identity + " Guarantee"); - guaranteeFundsTx.AddRow(Budget, -GuaranteeCents, attester); - guaranteeFundsTx.AddRow(Budget.Parent, GuaranteeCents, attester); + guaranteeFundsTx.AddRow (Budget, -GuaranteeCents, attester); + guaranteeFundsTx.AddRow (Budget.Parent, GuaranteeCents, attester); // Finally, set as attested - PWEvents.CreateEvent( + PWEvents.CreateEvent ( EventSource.PirateWeb, EventType.ParleyAttested, attester.Identity, OrganizationId, 0, 0, Identity, string.Empty); base.Attested = true; - SwarmDb.GetDatabaseForWriting().SetParleyAttested(Identity, true); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, + SwarmDb.GetDatabaseForWriting().SetParleyAttested (Identity, true); + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation (FinancialValidationType.Attestation, FinancialDependencyType.Parley, Identity, DateTime.Now, attester.Identity, (double) (GuaranteeDecimal)); } - public void Deattest(Person deattester) + public void Deattest (Person deattester) { throw new NotImplementedException(); /* @@ -197,58 +197,58 @@ namespace Swarmops.Logic.Swarm public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(BudgetId); } + get { return FinancialAccount.FromIdentity (BudgetId); } } - public static Parley FromBasic(BasicParley basic) + public static Parley FromBasic (BasicParley basic) { - return new Parley(basic); + return new Parley (basic); } - public static Parley FromIdentity(int parleyId) + public static Parley FromIdentity (int parleyId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParley(parleyId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetParley (parleyId)); } - public static Parley Create(Organization organization, Person person, FinancialAccount budgetInitial, + public static Parley Create (Organization organization, Person person, FinancialAccount budgetInitial, string name, Geography geography, string description, string informationUrl, DateTime startDate, DateTime endDate, Int64 budgetCents, Int64 guaranteeCents, Int64 attendanceFeeCents) { Parley newParley = - FromIdentity(SwarmDb.GetDatabaseForWriting().CreateParley(organization.Identity, person.Identity, + FromIdentity (SwarmDb.GetDatabaseForWriting().CreateParley (organization.Identity, person.Identity, -(budgetInitial.Identity), name, geography.Identity, description, informationUrl, startDate, endDate, budgetCents, guaranteeCents, attendanceFeeCents)); - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.ParleyCreated, person.Identity, organization.Identity, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.ParleyCreated, person.Identity, organization.Identity, 0, 0, newParley.Identity, string.Empty); return newParley; } - public ParleyOption CreateOption(string description, Int64 amountCents) + public ParleyOption CreateOption (string description, Int64 amountCents) { - return ParleyOption.Create(this, description, amountCents); + return ParleyOption.Create (this, description, amountCents); } - public ParleyAttendee CreateAttendee(string firstName, string lastName, string email, bool asGuest) + public ParleyAttendee CreateAttendee (string firstName, string lastName, string email, bool asGuest) { - Person newAttendee = Person.Create(firstName + "|" + lastName, email, string.Empty, string.Empty, + Person newAttendee = Person.Create (firstName + "|" + lastName, email, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, Organization.DefaultCountry.Code, DateTime.Now, PersonGender.Unknown); - return ParleyAttendee.Create(this, newAttendee, asGuest); + return ParleyAttendee.Create (this, newAttendee, asGuest); } - public void CloseBudget(Person closingPerson) + public void CloseBudget (Person closingPerson) { - Int64 remainingFunds = -Budget.GetDeltaCents(CreatedDateTime, DateTime.Now); + Int64 remainingFunds = -Budget.GetDeltaCents (CreatedDateTime, DateTime.Now); - FinancialTransaction transaction = FinancialTransaction.Create(OrganizationId, + FinancialTransaction transaction = FinancialTransaction.Create (OrganizationId, DateTime.Now, "Closing conference #" + Identity); - transaction.AddRow(Budget, remainingFunds, closingPerson); - transaction.AddRow(Budget.Parent, -remainingFunds, closingPerson); + transaction.AddRow (Budget, remainingFunds, closingPerson); + transaction.AddRow (Budget.Parent, -remainingFunds, closingPerson); } public void CancelBudget() @@ -259,9 +259,9 @@ namespace Swarmops.Logic.Swarm if (BudgetId > 0) // Budget attested and allocated { - Budget.Parent.SetBudgetCents(year, - Budget.Parent.GetBudgetCents(year) - BudgetCents); // cost budgets are negative - Budget.SetBudgetCents(year, 0); + Budget.Parent.SetBudgetCents (year, + Budget.Parent.GetBudgetCents (year) - BudgetCents); // cost budgets are negative + Budget.SetBudgetCents (year, 0); } } } diff --git a/Logic/Swarm/ParleyAttendee.cs b/Logic/Swarm/ParleyAttendee.cs index 4fb8d607..0c6de10b 100644 --- a/Logic/Swarm/ParleyAttendee.cs +++ b/Logic/Swarm/ParleyAttendee.cs @@ -9,19 +9,19 @@ namespace Swarmops.Logic.Swarm { public class ParleyAttendee : BasicParleyAttendee { - private ParleyAttendee(BasicParleyAttendee basic) : base(basic) + private ParleyAttendee (BasicParleyAttendee basic) : base (basic) { // empty pvt ctor } public ParleyOptions Options { - get { return ParleyOptions.ForParleyAttendee(this); } + get { return ParleyOptions.ForParleyAttendee (this); } } public Parley Parley { - get { return Parley.FromIdentity(ParleyId); } + get { return Parley.FromIdentity (ParleyId); } } public new bool Active @@ -31,7 +31,7 @@ namespace Swarmops.Logic.Swarm { if (value != base.Active) { - SwarmDb.GetDatabaseForWriting().SetParleyAttendeeActive(Identity, value); + SwarmDb.GetDatabaseForWriting().SetParleyAttendeeActive (Identity, value); base.Active = value; } } @@ -39,70 +39,70 @@ namespace Swarmops.Logic.Swarm public Person Person { - get { return Person.FromIdentity(PersonId); } + get { return Person.FromIdentity (PersonId); } } public OutboundInvoice Invoice { - get { return OutboundInvoice.FromIdentity(base.OutboundInvoiceId); } + get { return OutboundInvoice.FromIdentity (base.OutboundInvoiceId); } } - public static ParleyAttendee FromBasic(BasicParleyAttendee basic) + public static ParleyAttendee FromBasic (BasicParleyAttendee basic) { - return new ParleyAttendee(basic); + return new ParleyAttendee (basic); } - public static ParleyAttendee FromIdentity(int parleyAttendeeId) + public static ParleyAttendee FromIdentity (int parleyAttendeeId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyAttendee(parleyAttendeeId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetParleyAttendee (parleyAttendeeId)); } - public static ParleyAttendee Create(Parley parley, Person person, bool asGuest) + public static ParleyAttendee Create (Parley parley, Person person, bool asGuest) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateParleyAttendee(parley.Identity, person.Identity, asGuest)); + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateParleyAttendee (parley.Identity, person.Identity, asGuest)); } - public void AddOption(ParleyOption option) + public void AddOption (ParleyOption option) { - SwarmDb.GetDatabaseForWriting().AddParleyAttendeeOption(Identity, option.Identity); + SwarmDb.GetDatabaseForWriting().AddParleyAttendeeOption (Identity, option.Identity); } public void SendInvoice() { - DateTime invoiceDue = DateTime.Today.AddDays(14); - DateTime maxInvoiceDue = Parley.StartDate.AddDays(-10); + DateTime invoiceDue = DateTime.Today.AddDays (14); + DateTime maxInvoiceDue = Parley.StartDate.AddDays (-10); if (invoiceDue > maxInvoiceDue) { invoiceDue = maxInvoiceDue; } - OutboundInvoice invoice = OutboundInvoice.Create(Parley.Organization, Parley.Person, invoiceDue, + OutboundInvoice invoice = OutboundInvoice.Create (Parley.Organization, Parley.Person, invoiceDue, Parley.Budget, Person.Name, Person.Mail, string.Empty, Parley.Organization.DefaultCountry.Currency, true, string.Empty); - invoice.AddItem("Deltagarkostnad " + Parley.Name, Parley.AttendanceFeeCents); // TODO: Localize + invoice.AddItem ("Deltagarkostnad " + Parley.Name, Parley.AttendanceFeeCents); // TODO: Localize ParleyOptions options = Options; foreach (ParleyOption option in options) { - invoice.AddItem(option.Description, option.AmountCents); + invoice.AddItem (option.Description, option.AmountCents); } // Create the financial transaction with rows FinancialTransaction transaction = - FinancialTransaction.Create(Parley.OrganizationId, DateTime.Now, + FinancialTransaction.Create (Parley.OrganizationId, DateTime.Now, "Outbound Invoice #" + invoice.Identity + " to " + Person.Name); - transaction.AddRow(Parley.Organization.FinancialAccounts.AssetsOutboundInvoices, invoice.AmountCents, null); - transaction.AddRow(Parley.Budget, -invoice.AmountCents, null); + transaction.AddRow (Parley.Organization.FinancialAccounts.AssetsOutboundInvoices, invoice.AmountCents, null); + transaction.AddRow (Parley.Budget, -invoice.AmountCents, null); // Make the transaction dependent on the outbound invoice @@ -110,7 +110,7 @@ namespace Swarmops.Logic.Swarm // Create the event for PirateBot-Mono to send off mails - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoiceCreated, + PWEvents.CreateEvent (EventSource.PirateWeb, EventType.OutboundInvoiceCreated, PersonId, Parley.OrganizationId, 1, PersonId, invoice.Identity, string.Empty); @@ -119,7 +119,7 @@ namespace Swarmops.Logic.Swarm base.Invoiced = true; base.OutboundInvoiceId = invoice.Identity; - SwarmDb.GetDatabaseForWriting().SetParleyAttendeeInvoiced(Identity, invoice.Identity); + SwarmDb.GetDatabaseForWriting().SetParleyAttendeeInvoiced (Identity, invoice.Identity); } } } \ No newline at end of file diff --git a/Logic/Swarm/ParleyAttendees.cs b/Logic/Swarm/ParleyAttendees.cs index 1e8575cd..16103e02 100644 --- a/Logic/Swarm/ParleyAttendees.cs +++ b/Logic/Swarm/ParleyAttendees.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Swarm { public class ParleyAttendees : PluralBase { - public static ParleyAttendees ForParley(Parley parley) + public static ParleyAttendees ForParley (Parley parley) { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleyAttendees(parley)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleyAttendees (parley)); } } } \ No newline at end of file diff --git a/Logic/Swarm/ParleyOption.cs b/Logic/Swarm/ParleyOption.cs index 48367b6f..4e4fe576 100644 --- a/Logic/Swarm/ParleyOption.cs +++ b/Logic/Swarm/ParleyOption.cs @@ -6,7 +6,7 @@ namespace Swarmops.Logic.Swarm { public class ParleyOption : BasicParleyOption { - private ParleyOption(BasicParleyOption basic) : base(basic) + private ParleyOption (BasicParleyOption basic) : base (basic) { // empty pvt ctor } @@ -16,21 +16,21 @@ namespace Swarmops.Logic.Swarm get { return AmountCents/100.0m; } } - public static ParleyOption FromBasic(BasicParleyOption basic) + public static ParleyOption FromBasic (BasicParleyOption basic) { - return new ParleyOption(basic); + return new ParleyOption (basic); } - public static ParleyOption FromIdentity(int parleyOptionId) + public static ParleyOption FromIdentity (int parleyOptionId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyOption(parleyOptionId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetParleyOption (parleyOptionId)); } - public static ParleyOption Create(Parley parley, string description, Int64 amountCents) + public static ParleyOption Create (Parley parley, string description, Int64 amountCents) { return - FromIdentity(SwarmDb.GetDatabaseForWriting() - .CreateParleyOption(parley.Identity, description, amountCents)); + FromIdentity (SwarmDb.GetDatabaseForWriting() + .CreateParleyOption (parley.Identity, description, amountCents)); } } } \ No newline at end of file diff --git a/Logic/Swarm/ParleyOptions.cs b/Logic/Swarm/ParleyOptions.cs index 4c36bd3a..107ad2fe 100644 --- a/Logic/Swarm/ParleyOptions.cs +++ b/Logic/Swarm/ParleyOptions.cs @@ -6,34 +6,34 @@ namespace Swarmops.Logic.Swarm { public class ParleyOptions : PluralBase { - public static ParleyOptions ForParley(Parley parley) + public static ParleyOptions ForParley (Parley parley) { - return ForParley(parley, false); + return ForParley (parley, false); } - public static ParleyOptions ForParley(Parley parley, bool includeInactive) + public static ParleyOptions ForParley (Parley parley, bool includeInactive) { if (includeInactive) { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleyOptions(parley)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleyOptions (parley)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetParleyOptions(parley, DatabaseCondition.ActiveTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleyOptions (parley, DatabaseCondition.ActiveTrue)); } - public static ParleyOptions ForParleyAttendee(ParleyAttendee attendee) + public static ParleyOptions ForParleyAttendee (ParleyAttendee attendee) { - int[] parleyOptionIds = SwarmDb.GetDatabaseForReading().GetParleyAttendeeOptions(attendee.Identity); + int[] parleyOptionIds = SwarmDb.GetDatabaseForReading().GetParleyAttendeeOptions (attendee.Identity); - return FromIdentities(parleyOptionIds); + return FromIdentities (parleyOptionIds); } - public static ParleyOptions FromIdentities(int[] identities) + public static ParleyOptions FromIdentities (int[] identities) { ParleyOptions result = new ParleyOptions(); foreach (int parleyId in identities) { - result.Add(ParleyOption.FromIdentity(parleyId)); + result.Add (ParleyOption.FromIdentity (parleyId)); } return result; diff --git a/Logic/Swarm/Parleys.cs b/Logic/Swarm/Parleys.cs index f7f6ac24..7ac6cacb 100644 --- a/Logic/Swarm/Parleys.cs +++ b/Logic/Swarm/Parleys.cs @@ -13,38 +13,38 @@ namespace Swarmops.Logic.Swarm get { Parleys result = new Parleys(); - result.AddRange(this.Where(parley => !parley.Attested)); + result.AddRange (this.Where (parley => !parley.Attested)); return result; } } - public static Parleys ForOrganization(Organization organization) + public static Parleys ForOrganization (Organization organization) { - return ForOrganization(organization, false); + return ForOrganization (organization, false); } - public static Parleys ForOrganization(Organization organization, bool includeClosed) + public static Parleys ForOrganization (Organization organization, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleys (organization)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization, DatabaseCondition.OpenTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleys (organization, DatabaseCondition.OpenTrue)); } - public static Parleys ForOwner(Person person) + public static Parleys ForOwner (Person person) { - return ForOwner(person, false); + return ForOwner (person, false); } - public static Parleys ForOwner(Person person, bool includeClosed) + public static Parleys ForOwner (Person person, bool includeClosed) { if (includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(person)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleys (person)); } - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(person, DatabaseCondition.OpenTrue)); + return FromArray (SwarmDb.GetDatabaseForReading().GetParleys (person, DatabaseCondition.OpenTrue)); } } } \ No newline at end of file diff --git a/Logic/Swarm/PaymentCode.cs b/Logic/Swarm/PaymentCode.cs index 4c459d0e..bb7ad12f 100644 --- a/Logic/Swarm/PaymentCode.cs +++ b/Logic/Swarm/PaymentCode.cs @@ -7,51 +7,51 @@ namespace Swarmops.Logic.Swarm { public class PaymentCode : BasicPaymentCode { - private PaymentCode(BasicPaymentCode basic) - : base(basic) + private PaymentCode (BasicPaymentCode basic) + : base (basic) { // empty } - public static PaymentCode CreateFromPhone(string phoneNumber) + public static PaymentCode CreateFromPhone (string phoneNumber) { - return Create(phoneNumber, 0); + return Create (phoneNumber, 0); } - public static PaymentCode CreateFromPerson(Person person) + public static PaymentCode CreateFromPerson (Person person) { - return CreateFromPerson(person.Identity); + return CreateFromPerson (person.Identity); } - public static PaymentCode CreateFromPerson(int personId) + public static PaymentCode CreateFromPerson (int personId) { - return Create(string.Empty, personId); + return Create (string.Empty, personId); } - public static PaymentCode FromBasic(BasicPaymentCode basic) + public static PaymentCode FromBasic (BasicPaymentCode basic) { - return new PaymentCode(basic); + return new PaymentCode (basic); } - public static PaymentCode FromCode(string paymentCode) + public static PaymentCode FromCode (string paymentCode) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPaymentCode(paymentCode)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPaymentCode (paymentCode)); } - private static PaymentCode Create(string phoneNumber, int personId) + private static PaymentCode Create (string phoneNumber, int personId) { bool success = false; while (!success) { - string randomCode = CreateRandomCode(5); + string randomCode = CreateRandomCode (5); try { - int codeId = SwarmDb.GetDatabaseForWriting().CreatePaymentCode(randomCode, phoneNumber, personId); + int codeId = SwarmDb.GetDatabaseForWriting().CreatePaymentCode (randomCode, phoneNumber, personId); success = true; - return FromBasic(SwarmDb.GetDatabaseForReading().GetPaymentCode(randomCode)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPaymentCode (randomCode)); } catch (Exception) { @@ -65,19 +65,19 @@ namespace Swarmops.Logic.Swarm } - public void Claim(Person claimingPerson) + public void Claim (Person claimingPerson) { - Claim(claimingPerson.Identity); + Claim (claimingPerson.Identity); } - public void Claim(int claimingPersonId) + public void Claim (int claimingPersonId) { - SwarmDb.GetDatabaseForWriting().ClaimPaymentCode(Identity, claimingPersonId); + SwarmDb.GetDatabaseForWriting().ClaimPaymentCode (Identity, claimingPersonId); } - private static string CreateRandomCode(int length) + private static string CreateRandomCode (int length) { - return Authentication.CreateRandomPassword(length); + return Authentication.CreateRandomPassword (length); } } } \ No newline at end of file diff --git a/Logic/Swarm/People.cs b/Logic/Swarm/People.cs index 74876104..09d8498c 100644 --- a/Logic/Swarm/People.cs +++ b/Logic/Swarm/People.cs @@ -13,22 +13,22 @@ namespace Swarmops.Logic.Swarm { public int[] Identities { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + get { return LogicServices.ObjectsToIdentifiers (ToArray()); } } - public static People FromMemberships(Memberships memberships) + public static People FromMemberships (Memberships memberships) { List personIds = new List(); foreach (Membership membership in memberships) { - personIds.Add(membership.PersonId); + personIds.Add (membership.PersonId); } - return FromIdentities(personIds.ToArray()); + return FromIdentities (personIds.ToArray()); } - public static People FromIdentities(int[] personIds) + public static People FromIdentities (int[] personIds) { if (personIds.Length > 500) { @@ -47,104 +47,104 @@ namespace Swarmops.Logic.Swarm for (int index = 0; index < basicArray.Length; index++) { - if (lookup.ContainsKey(basicArray[index].Identity)) + if (lookup.ContainsKey (basicArray[index].Identity)) { - result.Add(Person.FromBasic(basicArray[index])); + result.Add (Person.FromBasic (basicArray[index])); } } return result; } - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeople(personIds)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeople (personIds)); } public static People GetAll() { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetAllPeople()); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetAllPeople()); } - public static People FromNamePattern(string namePattern) + public static People FromNamePattern (string namePattern) { if (namePattern.Trim().Length < 3) { return new People(); } - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromNamePattern(namePattern)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromNamePattern (namePattern)); } - public static People FromBirthDatePattern(DateTime fromdate, DateTime todate) + public static People FromBirthDatePattern (DateTime fromdate, DateTime todate) { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromBirthdate(fromdate, todate)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromBirthdate (fromdate, todate)); } - public static People FromEmailPattern(string emailPattern) + public static People FromEmailPattern (string emailPattern) { // Remove any injection codes - emailPattern = emailPattern.Replace("%", String.Empty).Trim(); + emailPattern = emailPattern.Replace ("%", String.Empty).Trim(); if (emailPattern.Length > 0) { emailPattern = "%" + emailPattern + "%"; - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern(emailPattern)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern (emailPattern)); } return null; // If no valid search string was supplied } - public static People FromCityPattern(string cityPattern) + public static People FromCityPattern (string cityPattern) { // Remove any injection codes - cityPattern = cityPattern.Replace("%", String.Empty).Trim(); + cityPattern = cityPattern.Replace ("%", String.Empty).Trim(); if (cityPattern.Length > 0) { cityPattern = "%" + cityPattern + "%"; - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromCityPattern(cityPattern)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromCityPattern (cityPattern)); } return null; // If no valid search string was supplied } - public static People FromPostalCodePattern(string pcPattern) + public static People FromPostalCodePattern (string pcPattern) { // Remove any injection codes - pcPattern = pcPattern.Replace("%", String.Empty).Trim(); + pcPattern = pcPattern.Replace ("%", String.Empty).Trim(); if (pcPattern.Length > 0) { pcPattern = pcPattern + "%"; - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromPostalCodePattern(pcPattern)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromPostalCodePattern (pcPattern)); } return null; // If no valid search string was supplied } - public static People FromPostalCodes(string[] pcodes) + public static People FromPostalCodes (string[] pcodes) { // Remove any injection codes if (pcodes.Length > 0) { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromPostalCodes(pcodes)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromPostalCodes (pcodes)); } return null; // If no valid search string was supplied } - public static People FromEmail(string email) + public static People FromEmail (string email) { if (email.Length > 0) { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromEmail(email)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromEmail (email)); } return null; // If no valid search string was supplied } - public static People LogicalAnd(People set1, People set2) + public static People LogicalAnd (People set1, People set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -173,16 +173,16 @@ namespace Swarmops.Logic.Swarm foreach (Person person in set1) { - if (set2Lookup.ContainsKey(person.Identity)) + if (set2Lookup.ContainsKey (person.Identity)) { - result.Add(person); + result.Add (person); } } return result; } - public static People LogicalOr(People set1, People set2) + public static People LogicalOr (People set1, People set2) { // If either set is invalid, return the other // (a null is different from an empty set) @@ -221,37 +221,37 @@ namespace Swarmops.Logic.Swarm foreach (Person person in table.Values) { - result.Add(person); + result.Add (person); } return result; } - public People LogicalAnd(People set2) + public People LogicalAnd (People set2) { - return LogicalAnd(this, set2); + return LogicalAnd (this, set2); } - public People LogicalOr(People set2) + public People LogicalOr (People set2) { - return LogicalOr(this, set2); + return LogicalOr (this, set2); } - public People Filter(Predicate match) + public People Filter (Predicate match) { People retlist = new People(); - ForEach(delegate(Person p) + ForEach (delegate (Person p) { - if (match(p)) - retlist.Add(p); + if (match (p)) + retlist.Add (p); }); return retlist; } - public static People FromOrganizationAndGeographyWithPattern(Organization organization, Geography geography, + public static People FromOrganizationAndGeographyWithPattern (Organization organization, Geography geography, string pattern) { Geographies geoTree = geography.GetTree(); @@ -259,7 +259,7 @@ namespace Swarmops.Logic.Swarm pattern = pattern.Trim(); if (pattern.Length == 0) { - return FromOrganizationAndGeography(organization, geography); + return FromOrganizationAndGeography (organization, geography); } if (pattern.Length < 3) { @@ -270,27 +270,27 @@ namespace Swarmops.Logic.Swarm // First, get list of people in the geography, then filter on memberships BasicPerson[] candidates = - SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern(geoTree.Identities, pattern); + SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern (geoTree.Identities, pattern); - return FilterByMembership(candidates, organization); + return FilterByMembership (candidates, organization); } - public static People FromOrganizationAndGeography(Organization organization, Geography geography) + public static People FromOrganizationAndGeography (Organization organization, Geography geography) { Geographies geoTree = geography.GetTree(); // First, get list of people in the geography, then filter on memberships - BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies(geoTree.Identities); + BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies (geoTree.Identities); // Filter on memberships - return FilterByMembership(people, organization); + return FilterByMembership (people, organization); } - private static People FilterByMembership(BasicPerson[] candidates, Organization organization) + private static People FilterByMembership (BasicPerson[] candidates, Organization organization) { // Get the organization tree @@ -310,7 +310,8 @@ namespace Swarmops.Logic.Swarm // Get the list of all memberships Dictionary> memberships = - SwarmDb.GetDatabaseForReading().GetMembershipsForPeople(LogicServices.ObjectsToIdentifiers(candidates)); + SwarmDb.GetDatabaseForReading() + .GetMembershipsForPeople (LogicServices.ObjectsToIdentifiers (candidates)); People result = new People(); @@ -318,11 +319,11 @@ namespace Swarmops.Logic.Swarm { bool memberOfOrganization = false; - if (memberships.ContainsKey(basicPerson.Identity)) + if (memberships.ContainsKey (basicPerson.Identity)) { foreach (BasicMembership membership in memberships[basicPerson.Identity]) { - if (lookup.ContainsKey(membership.OrganizationId)) + if (lookup.ContainsKey (membership.OrganizationId)) { memberOfOrganization = true; } @@ -331,108 +332,108 @@ namespace Swarmops.Logic.Swarm if (memberOfOrganization) { - result.Add(Person.FromBasic(basicPerson)); + result.Add (Person.FromBasic (basicPerson)); } } return result; } - public static People FromGeography(int geographyId) + public static People FromGeography (int geographyId) { - Geographies geoTree = Geography.FromIdentity(geographyId).GetTree(); + Geographies geoTree = Geography.FromIdentity (geographyId).GetTree(); // First, get list of people in the geography, then filter on memberships - BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies(geoTree.Identities); + BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies (geoTree.Identities); People result = new People(); foreach (BasicPerson basicPerson in people) { - result.Add(Person.FromBasic(basicPerson)); + result.Add (Person.FromBasic (basicPerson)); } return result; } - public static People FromSingle(Person person) + public static People FromSingle (Person person) { People result = new People(); - result.Add(person); + result.Add (person); return result; } - public static People FromArray(Person[] personArray) + public static People FromArray (Person[] personArray) { People result = new People(); result.Capacity = personArray.Length*11/10; foreach (Person person in personArray) { - result.Add(person); + result.Add (person); } return result; } - public static People FromArray(BasicPerson[] personArray) + public static People FromArray (BasicPerson[] personArray) { People result = new People(); result.Capacity = personArray.Length*11/10; foreach (BasicPerson basic in personArray) { - result.Add(Person.FromBasic(basic)); + result.Add (Person.FromBasic (basic)); } return result; } - public static People FromOptionalData(ObjectOptionalDataType dataType, string data) + public static People FromOptionalData (ObjectOptionalDataType dataType, string data) { return - FromIdentities(SwarmDb.GetDatabaseForReading() - .GetObjectsByOptionalData(ObjectType.Person, dataType, data)); + FromIdentities (SwarmDb.GetDatabaseForReading() + .GetObjectsByOptionalData (ObjectType.Person, dataType, data)); } - public static People FromPhoneNumber(int countryId, string phoneNumber) + public static People FromPhoneNumber (int countryId, string phoneNumber) { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber(countryId, phoneNumber)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber (countryId, phoneNumber)); } - public static People FromPhoneNumber(string countryCode, string phoneNumber) + public static People FromPhoneNumber (string countryCode, string phoneNumber) { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber(countryCode, phoneNumber)); + return People.FromArray (SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber (countryCode, phoneNumber)); } - public People GetVisiblePeopleByAuthority(Authority authority) + public People GetVisiblePeopleByAuthority (Authority authority) { - return GetVisiblePeopleByAuthority(authority, 0); + return GetVisiblePeopleByAuthority (authority, 0); } - public People GetVisiblePeopleByAuthority(Authority authority, int gracePeriod) + public People GetVisiblePeopleByAuthority (Authority authority, int gracePeriod) { - return Authorization.FilterPeopleToMatchAuthority(this, authority, gracePeriod); + return Authorization.FilterPeopleToMatchAuthority (this, authority, gracePeriod); } - public People GetVisiblePeople(Organization organization) + public People GetVisiblePeople (Organization organization) { People result = new People(); // First, get all the currently visible people for this org Dictionary roleTypeLookup = Authorization.VisibleRolesDictionary; - Roles orgRoles = Roles.FromOrganization(organization); + Roles orgRoles = Roles.FromOrganization (organization); Dictionary personIdLookup = new Dictionary(); foreach (PersonRole orgRole in orgRoles) { - if (roleTypeLookup.ContainsKey(orgRole.Type)) + if (roleTypeLookup.ContainsKey (orgRole.Type)) { personIdLookup[orgRole.PersonId] = true; } @@ -442,9 +443,9 @@ namespace Swarmops.Logic.Swarm foreach (Person person in this) { - if (personIdLookup.ContainsKey(person.Identity)) + if (personIdLookup.ContainsKey (person.Identity)) { - result.Add(person); + result.Add (person); } } @@ -454,15 +455,15 @@ namespace Swarmops.Logic.Swarm public People RemoveUnique() { BasicPerson[] arrayToFilter = ToArray(); - BasicPerson[] filtered = Authorization.FilterUniquePeople(arrayToFilter); - return FromArray(filtered); + BasicPerson[] filtered = Authorization.FilterUniquePeople (arrayToFilter); + return FromArray (filtered); } public People RemoveUnlisted() { BasicPerson[] arrayToFilter = ToArray(); - BasicPerson[] filtered = Authorization.FilterUnlistedPeople(arrayToFilter); - return FromArray(filtered); + BasicPerson[] filtered = Authorization.FilterUnlistedPeople (arrayToFilter); + return FromArray (filtered); } @@ -478,20 +479,20 @@ namespace Swarmops.Logic.Swarm } }*/ - public static People FromNewsletterFeed(int feedId) + public static People FromNewsletterFeed (int feedId) { - int[] subscriberIds = SwarmDb.GetDatabaseForReading().GetSubscribersForNewsletterFeed(2); + int[] subscriberIds = SwarmDb.GetDatabaseForReading().GetSubscribersForNewsletterFeed (2); - return FromIdentities(subscriberIds); + return FromIdentities (subscriberIds); } - public new void Remove(Person personToRemove) + public new void Remove (Person personToRemove) { for (int index = 0; index < Count; index++) { if (this[index].Identity == personToRemove.Identity) { - RemoveAt(index); + RemoveAt (index); index--; } } @@ -503,9 +504,9 @@ namespace Swarmops.Logic.Swarm return SwarmDb.GetDatabaseForReading().GetPeopleGeographies(); } - public static People FromIdentities(int[] personIds, bool preserveOrder) + public static People FromIdentities (int[] personIds, bool preserveOrder) { - People set = FromIdentities(personIds); + People set = FromIdentities (personIds); if (preserveOrder == false) { @@ -523,7 +524,7 @@ namespace Swarmops.Logic.Swarm foreach (int identity in personIds) { - result.Add(lookup[identity]); + result.Add (lookup[identity]); } return result; diff --git a/Logic/Swarm/Person.cs b/Logic/Swarm/Person.cs index dea6944e..cdfa9947 100644 --- a/Logic/Swarm/Person.cs +++ b/Logic/Swarm/Person.cs @@ -20,15 +20,15 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { [Serializable] - [DbRecordType("Person")] + [DbRecordType ("Person")] public class Person : BasicPerson, IComparable, IHasIdentity { private readonly IHandleProvider handleProvider; private ObjectOptionalData _optionalData; private Dictionary subscriptions; - protected Person(BasicPerson basic) - : base(basic) + protected Person (BasicPerson basic) + : base (basic) { // Today, we set the Swedish handle provider. This can be changed as desired. @@ -42,8 +42,8 @@ namespace Swarmops.Logic.Swarm if (this._optionalData == null) { Person p = this; - this._optionalData = ObjectOptionalData.ForObject(p); - //Added cast, otherwise it fails for subclasses + this._optionalData = ObjectOptionalData.ForObject (p); + //Added cast, otherwise it fails for subclasses } return this._optionalData; } @@ -56,20 +56,20 @@ namespace Swarmops.Logic.Swarm public bool IsActivist { - get { return SwarmDb.GetDatabaseForReading().GetActivistStatus(Identity); } + get { return SwarmDb.GetDatabaseForReading().GetActivistStatus (Identity); } } public new virtual string Name { - get { return base.Name.Replace("|", " "); } - set { SwarmDb.GetDatabaseForWriting().SetPersonName(Identity, value); } + get { return base.Name.Replace ("|", " "); } + set { SwarmDb.GetDatabaseForWriting().SetPersonName (Identity, value); } } public new virtual string Street { get { return base.Street; } - set { SwarmDb.GetDatabaseForWriting().SetPersonStreet(Identity, value); } + set { SwarmDb.GetDatabaseForWriting().SetPersonStreet (Identity, value); } } @@ -78,7 +78,7 @@ namespace Swarmops.Logic.Swarm get { return base.PostalCode; } set { - SwarmDb.GetDatabaseForWriting().SetPersonPostalCode(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPersonPostalCode (Identity, value); base.PostalCode = value; ResolveGeography(); } @@ -90,7 +90,7 @@ namespace Swarmops.Logic.Swarm get { return base.CityName; } set { - SwarmDb.GetDatabaseForWriting().SetPersonCity(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPersonCity (Identity, value); base.CityName = value; ResolveGeography(); } @@ -99,10 +99,10 @@ namespace Swarmops.Logic.Swarm public Country Country { - get { return Country.FromIdentity(base.CountryId); } + get { return Country.FromIdentity (base.CountryId); } set { - SwarmDb.GetDatabaseForWriting().SetPersonCountry(Identity, value.Identity); + SwarmDb.GetDatabaseForWriting().SetPersonCountry (Identity, value.Identity); base.CountryId = value.Identity; ResolveGeography(); } @@ -118,11 +118,11 @@ namespace Swarmops.Logic.Swarm ResolveGeography(); } - return Geography.FromIdentity(GeographyId); + return Geography.FromIdentity (GeographyId); } set { - SwarmDb.GetDatabaseForWriting().SetPersonGeography(Identity, value.Identity); + SwarmDb.GetDatabaseForWriting().SetPersonGeography (Identity, value.Identity); base.GeographyId = value.Identity; } } @@ -144,27 +144,27 @@ namespace Swarmops.Logic.Swarm public virtual string Mail { get { return base.Email; } - set { SwarmDb.GetDatabaseForWriting().SetPersonEmail(Identity, value); } + set { SwarmDb.GetDatabaseForWriting().SetPersonEmail (Identity, value); } } public new virtual string Phone { get { return base.Phone; } - set { SwarmDb.GetDatabaseForWriting().SetPersonPhone(Identity, value); } + set { SwarmDb.GetDatabaseForWriting().SetPersonPhone (Identity, value); } } public new virtual DateTime Birthdate { get { return base.Birthdate; } - set { SwarmDb.GetDatabaseForWriting().SetPersonBirthdate(Identity, value); } + set { SwarmDb.GetDatabaseForWriting().SetPersonBirthdate (Identity, value); } } public new virtual PersonGender Gender { get { return base.Gender; } - set { SwarmDb.GetDatabaseForWriting().SetPersonGender(Identity, value); } + set { SwarmDb.GetDatabaseForWriting().SetPersonGender (Identity, value); } } @@ -174,113 +174,113 @@ namespace Swarmops.Logic.Swarm { get { - string email = OptionalData.GetOptionalDataString(ObjectOptionalDataType.PartyEmail); + string email = OptionalData.GetOptionalDataString (ObjectOptionalDataType.PartyEmail); return email; } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PartyEmail, value); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.PartyEmail, value); } } public virtual string BankName { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BankName); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankName, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BankName); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BankName, value); } } public virtual string BankClearing { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BankClearing); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankClearing, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BankClearing); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BankClearing, value); } } public virtual string BankAccount { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BankAccount); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankAccount, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BankAccount); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BankAccount, value); } } public virtual string CryptoPublicKey { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.CryptoPublicKey); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.CryptoPublicKey, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.CryptoPublicKey); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.CryptoPublicKey, value); } } public virtual string CryptoSecretKey { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.CryptoSecretKey); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.CryptoSecretKey, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.CryptoSecretKey); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.CryptoSecretKey, value); } } public virtual string CryptoFingerprint { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.CryptoFingerprint); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.CryptoFingerprint, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.CryptoFingerprint); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.CryptoFingerprint, value); } } public virtual string CryptoRevocationCertificate { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.CryptoRevocation); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.CryptoRevocation, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.CryptoRevocation); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.CryptoRevocation, value); } } - [Obsolete("Use NationalIdNumber instead")] + [Obsolete ("Use NationalIdNumber instead")] public virtual string PersonalNumber { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.PersonalNumber); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PersonalNumber, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.PersonalNumber); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.PersonalNumber, value); } } public virtual string NationalIdNumber { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.NationalIdNumber); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.NationalIdNumber, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.NationalIdNumber); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.NationalIdNumber, value); } } public virtual string Longitude { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.Longitude); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.Longitude, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.Longitude); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.Longitude, value); } } public virtual string Latitude { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.Latitude); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.Latitude, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.Latitude); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.Latitude, value); } } public virtual string BitIdAddress { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BitIdLoginAddress); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BitIdLoginAddress, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BitIdLoginAddress); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BitIdLoginAddress, value); } } public virtual bool MailUnreachable { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.MailUnreachable); } - set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.MailUnreachable, value); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.MailUnreachable); } + set { OptionalData.SetOptionalDataBool (ObjectOptionalDataType.MailUnreachable, value); } } public virtual bool LimitMailToLatin1 { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.LimitMailToLatin1); } - set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.LimitMailToLatin1, value); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.LimitMailToLatin1); } + set { OptionalData.SetOptionalDataBool (ObjectOptionalDataType.LimitMailToLatin1, value); } } public virtual bool LimitMailToText { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.LimitMailToText); } - set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.LimitMailToText, value); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.LimitMailToText); } + set { OptionalData.SetOptionalDataBool (ObjectOptionalDataType.LimitMailToText, value); } } public virtual bool NeverMail { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.NeverMail); } - set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.NeverMail, value); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.NeverMail); } + set { OptionalData.SetOptionalDataBool (ObjectOptionalDataType.NeverMail, value); } } @@ -290,31 +290,31 @@ namespace Swarmops.Logic.Swarm { if (this.handleProvider == null) { - throw new NotImplementedException("No handle provider"); + throw new NotImplementedException ("No handle provider"); } - return this.handleProvider.GetPersonHandle(Identity); + return this.handleProvider.GetPersonHandle (Identity); } set { if (this.handleProvider == null) { - throw new NotImplementedException("No handle provider"); + throw new NotImplementedException ("No handle provider"); } - this.handleProvider.SetPersonHandle(Identity, value); + this.handleProvider.SetPersonHandle (Identity, value); } } public virtual int SwedishForumAccountId { - get { return OptionalData.GetOptionalDataInt(ObjectOptionalDataType.ForumAccountId); } - set { OptionalData.SetOptionalDataInt(ObjectOptionalDataType.ForumAccountId, value); } + get { return OptionalData.GetOptionalDataInt (ObjectOptionalDataType.ForumAccountId); } + set { OptionalData.SetOptionalDataInt (ObjectOptionalDataType.ForumAccountId, value); } } public virtual string SwedishForumAccountName { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.ForumAccountName); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.ForumAccountName); } } @@ -324,20 +324,20 @@ namespace Swarmops.Logic.Swarm { get { - throw (new Exception("Person.HasFinancialAccess was called; it is replaced by Authority.HasAccess(...)")); + throw (new Exception ("Person.HasFinancialAccess was called; it is replaced by Authority.HasAccess(...)")); } } public string ResetPasswordTicket { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.ResetPasswordTicket); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.ResetPasswordTicket, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.ResetPasswordTicket); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.ResetPasswordTicket, value); } } public virtual bool EMailIsInvalid { - get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.EMailIsInvalid); } - set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.EMailIsInvalid, value); } + get { return OptionalData.GetOptionalDataBool (ObjectOptionalDataType.EMailIsInvalid); } + set { OptionalData.SetOptionalDataBool (ObjectOptionalDataType.EMailIsInvalid, value); } } public new string PasswordHash @@ -345,29 +345,29 @@ namespace Swarmops.Logic.Swarm get { return base.PasswordHash; } set { - SwarmDb.GetDatabaseForWriting().SetPersonPasswordHash(Identity, value); + SwarmDb.GetDatabaseForWriting().SetPersonPasswordHash (Identity, value); base.PasswordHash = value; } } public virtual string TempPasswordHash { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.PersonTempPasswordStore); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PersonTempPasswordStore, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.PersonTempPasswordStore); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.PersonTempPasswordStore, value); } } public string Initials { get { - string[] nameWords = Name.Split(' '); + string[] nameWords = Name.Split (' '); string result = string.Empty; foreach (string nameWord in nameWords) { if (nameWord.Length > 0) { - result += Char.ToUpperInvariant(nameWord[0]); + result += Char.ToUpperInvariant (nameWord[0]); } } @@ -379,21 +379,21 @@ namespace Swarmops.Logic.Swarm { get { - if (!string.IsNullOrEmpty(OptionalData.GetOptionalDataString(ObjectOptionalDataType.PreferredCulture))) + if (!string.IsNullOrEmpty (OptionalData.GetOptionalDataString (ObjectOptionalDataType.PreferredCulture))) { - return OptionalData.GetOptionalDataString(ObjectOptionalDataType.PreferredCulture); + return OptionalData.GetOptionalDataString (ObjectOptionalDataType.PreferredCulture); } // make best guesses: - if (base.CountryId != 0 && Country != null && !string.IsNullOrEmpty(Country.Culture)) + if (base.CountryId != 0 && Country != null && !string.IsNullOrEmpty (Country.Culture)) { return Country.Culture; } //not set, make a guess... - foreach (Membership ms in GetMemberships(false)) + foreach (Membership ms in GetMemberships (false)) { try { @@ -407,7 +407,7 @@ namespace Swarmops.Logic.Swarm return CultureInfo.InvariantCulture.Name; } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PreferredCulture, value); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.PreferredCulture, value); } } public string Canonical // On the canonical format "Rick Falkvinge (#1)" @@ -419,40 +419,40 @@ namespace Swarmops.Logic.Swarm { get { - Documents docs = Documents.ForObject(this); + Documents docs = Documents.ForObject (this); if (docs.Count == 0) { return null; } - return Image.FromFile(@"C:\Data\Uploads\PirateWeb\" + docs[0].ServerFileName); + return Image.FromFile (@"C:\Data\Uploads\PirateWeb\" + docs[0].ServerFileName); } } public string PortraitPhotographer { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.PortraitPhotographer); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PortraitPhotographer, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.PortraitPhotographer); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.PortraitPhotographer, value); } } public string TShirtSize // ReSharper restore InconsistentNaming { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.TShirtSize); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.TShirtSize, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.TShirtSize); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.TShirtSize, value); } } public string BlogName { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BlogName); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BlogName, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BlogName); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BlogName, value); } } public string BlogUrl { - get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BlogUrl); } - set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BlogUrl, value); } + get { return OptionalData.GetOptionalDataString (ObjectOptionalDataType.BlogUrl); } + set { OptionalData.SetOptionalDataString (ObjectOptionalDataType.BlogUrl, value); } } public string Formal @@ -464,13 +464,13 @@ namespace Swarmops.Logic.Swarm { get { - int indexLastSpace = Name.LastIndexOf(' '); + int indexLastSpace = Name.LastIndexOf (' '); if (indexLastSpace == -1) { return Name; } - return Name.Substring(0, indexLastSpace); + return Name.Substring (0, indexLastSpace); } } @@ -478,13 +478,13 @@ namespace Swarmops.Logic.Swarm { get { - int indexLastSpace = Name.LastIndexOf(' '); + int indexLastSpace = Name.LastIndexOf (' '); if (indexLastSpace == -1) { return Name; } - return Name.Substring(indexLastSpace + 1); + return Name.Substring (indexLastSpace + 1); } } @@ -494,9 +494,9 @@ namespace Swarmops.Logic.Swarm { string email = Mail.Trim().ToLowerInvariant(); - string md5 = MD5.Hash(email); + string md5 = MD5.Hash (email); - return md5.Replace(" ", "").ToLowerInvariant(); + return md5.Replace (" ", "").ToLowerInvariant(); } } @@ -508,11 +508,11 @@ namespace Swarmops.Logic.Swarm #region IComparable Members // TODO: Is same name really a match for equality for Person? /JL - public int CompareTo(object obj) + public int CompareTo (object obj) { Person otherPerson = (Person) obj; - return String.Compare(Name, otherPerson.Name); + return String.Compare (Name, otherPerson.Name); } #endregion @@ -522,18 +522,18 @@ namespace Swarmops.Logic.Swarm if (base.CountryId == 0) { base.GeographyId = 1; - SwarmDb.GetDatabaseForWriting().SetPersonGeography(Identity, 1); + SwarmDb.GetDatabaseForWriting().SetPersonGeography (Identity, 1); return 1; // root geography, if no country set } - Cities cities = Cities.FromPostalCode(PostalCode, base.CountryId); + Cities cities = Cities.FromPostalCode (PostalCode, base.CountryId); City city = null; if (cities.Count == 0) { try { - city = City.FromName(CityName, CountryId); + city = City.FromName (CityName, CountryId); } catch (ArgumentException) { @@ -547,57 +547,58 @@ namespace Swarmops.Logic.Swarm if (city == null) { - base.GeographyId = Country.FromIdentity(base.CountryId).GeographyId; + base.GeographyId = Country.FromIdentity (base.CountryId).GeographyId; return base.GeographyId; } base.GeographyId = city.GeographyId; - SwarmDb.GetDatabaseForWriting().SetPersonGeography(Identity, base.GeographyId); + SwarmDb.GetDatabaseForWriting().SetPersonGeography (Identity, base.GeographyId); return city.GeographyId; } - public static Person FromBitIdAddress(string address) + public static Person FromBitIdAddress (string address) { - People candidates = People.FromOptionalData(ObjectOptionalDataType.BitIdLoginAddress, address); + People candidates = People.FromOptionalData (ObjectOptionalDataType.BitIdLoginAddress, address); if (candidates.Count == 1) { return candidates[0]; } - throw new ArgumentException("Zero or several candidates"); + throw new ArgumentException ("Zero or several candidates"); } - public static Person FromIdentity(int personId) + public static Person FromIdentity (int personId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPerson(personId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetPerson (personId)); } - public static Person FromIdentityAggressive(int personId) + public static Person FromIdentityAggressive (int personId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPerson(personId)); - // Note "for writing". Intentional. Queries master db and bypasses replication lag. + return FromBasic (SwarmDb.GetDatabaseForWriting().GetPerson (personId)); + // Note "for writing". Intentional. Queries master db and bypasses replication lag. } public Authority GetAuthority() { - return Authorization.GetPersonAuthority(Identity); + return Authorization.GetPersonAuthority (Identity); } - public Memberships GetMemberships(bool includeTerminated) + public Memberships GetMemberships (bool includeTerminated) { if (!includeTerminated) { return GetMemberships(); } - return Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this)); + return Memberships.FromArray (SwarmDb.GetDatabaseForReading().GetMemberships (this)); } public Memberships GetMemberships() { return - Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this, DatabaseCondition.ActiveTrue)); + Memberships.FromArray (SwarmDb.GetDatabaseForReading() + .GetMemberships (this, DatabaseCondition.ActiveTrue)); } @@ -607,11 +608,11 @@ namespace Swarmops.Logic.Swarm /// For exired, number of days to add to allow it to be returned /// /// - public Membership GetRecentMembership(int gracePeriod, int orgId) + public Membership GetRecentMembership (int gracePeriod, int orgId) { List orgIdList = new List(); - orgIdList.Add(orgId); - Memberships mss = GetRecentMemberships(orgIdList, gracePeriod); + orgIdList.Add (orgId); + Memberships mss = GetRecentMemberships (orgIdList, gracePeriod); foreach (Membership ms in mss) { if (ms.OrganizationId == orgId) @@ -625,10 +626,10 @@ namespace Swarmops.Logic.Swarm /// /// For exired, number of days to add to allow it to be returned /// - public Memberships GetRecentMemberships(int gracePeriod) + public Memberships GetRecentMemberships (int gracePeriod) { List orgIdList = new List(); - return GetRecentMemberships(orgIdList, gracePeriod); + return GetRecentMemberships (orgIdList, gracePeriod); } /// @@ -637,10 +638,10 @@ namespace Swarmops.Logic.Swarm /// List of ids. If empty, all orgs /// For exired, number of days to add to allow it to be returned /// - public Memberships GetRecentMemberships(Organizations orgs, int gracePeriod) + public Memberships GetRecentMemberships (Organizations orgs, int gracePeriod) { - List orgIdList = new List(orgs.Identities); - return GetRecentMemberships(orgIdList, gracePeriod); + List orgIdList = new List (orgs.Identities); + return GetRecentMemberships (orgIdList, gracePeriod); } /// @@ -649,26 +650,26 @@ namespace Swarmops.Logic.Swarm /// List of ids. If empty, all orgs /// For exired, number of days to add to allow it to be returned /// - public Memberships GetRecentMemberships(List orgs, int gracePeriod) + public Memberships GetRecentMemberships (List orgs, int gracePeriod) { - Memberships memberships = GetMemberships(true); + Memberships memberships = GetMemberships (true); Dictionary collectMembers = new Dictionary(); - memberships.Sort( - delegate(Membership ms1, Membership ms2) { return ms2.DateTerminated.CompareTo(ms1.DateTerminated); }); + memberships.Sort ( + delegate (Membership ms1, Membership ms2) { return ms2.DateTerminated.CompareTo (ms1.DateTerminated); }); //Keep one for each org, the active one or the one with the highest Terminationdate foreach (Membership membership in memberships) { - if (orgs.Count == 0 || orgs.Contains(membership.OrganizationId)) + if (orgs.Count == 0 || orgs.Contains (membership.OrganizationId)) { if (membership.Active) { collectMembers[membership.OrganizationId] = membership; } - else if (membership.DateTerminated.AddDays(gracePeriod) > DateTime.Today) + else if (membership.DateTerminated.AddDays (gracePeriod) > DateTime.Today) { - if (!collectMembers.ContainsKey(membership.OrganizationId) + if (!collectMembers.ContainsKey (membership.OrganizationId) || collectMembers[membership.OrganizationId].Active == false) { collectMembers[membership.OrganizationId] = membership; @@ -678,32 +679,32 @@ namespace Swarmops.Logic.Swarm } Memberships collectedMS = new Memberships(); - collectedMS.AddRange(collectMembers.Values); + collectedMS.AddRange (collectMembers.Values); if (collectedMS.Count > 0) { //sort to get most recent first - collectedMS.Sort(delegate(Membership ms1, Membership ms2) + collectedMS.Sort (delegate (Membership ms1, Membership ms2) { if (ms1.Active && ms1.Active != ms2.Active) return -1; // active before terminated if (ms1.Active != ms2.Active) return 1; // active before terminated if (ms1.Active) - return ms1.Expires.CompareTo(ms2.Expires); // active with lowest expiry - return ms2.DateTerminated.CompareTo(ms1.DateTerminated); // terminated with latest terminationdate + return ms1.Expires.CompareTo (ms2.Expires); // active with lowest expiry + return ms2.DateTerminated.CompareTo (ms1.DateTerminated); // terminated with latest terminationdate }); } return collectedMS; } - internal static Person FromBasic(BasicPerson basic) + internal static Person FromBasic (BasicPerson basic) { - return new Person(basic); + return new Person (basic); } - public static Person Create(string name, string email, string password, string phone, string street, + public static Person Create (string name, string email, string password, string phone, string street, string postal, string city, string countryCode, DateTime dateOfBirth, PersonGender gender) { @@ -711,36 +712,36 @@ namespace Swarmops.Logic.Swarm if (countryCode.Length > 0) { - country = Country.FromCode(countryCode); + country = Country.FromCode (countryCode); } // Clean data - while (name.Contains(" ")) + while (name.Contains (" ")) { - name = name.Replace(" ", " "); + name = name.Replace (" ", " "); } name = name.Trim(); email = email.ToLower().Trim(); - phone = LogicServices.CleanNumber(phone); - postal = postal.Replace(" ", "").Trim(); + phone = LogicServices.CleanNumber (phone); + postal = postal.Replace (" ", "").Trim(); - int personId = SwarmDb.GetDatabaseForWriting().CreatePerson(name, email, phone, street, postal, city, + int personId = SwarmDb.GetDatabaseForWriting().CreatePerson (name, email, phone, street, postal, city, country == null ? 0 : country.Identity, dateOfBirth, gender); // Resolve the geography - Person newPerson = FromIdentityAggressive(personId); - // aggressive bypasses replication lag, avoids race condition + Person newPerson = FromIdentityAggressive (personId); + // aggressive bypasses replication lag, avoids race condition newPerson.ResolveGeography(); // Generate the salted password hash and set it if (password.Length > 0) { - newPerson.PasswordHash = Authentication.GenerateNewPasswordHash(personId, password); + newPerson.PasswordHash = Authentication.GenerateNewPasswordHash (personId, password); } else { @@ -752,33 +753,33 @@ namespace Swarmops.Logic.Swarm return newPerson; } - public Membership AddMembership(Organization organization, DateTime expires) + public Membership AddMembership (Organization organization, DateTime expires) { - return AddMembership(organization.Identity, expires); + return AddMembership (organization.Identity, expires); } - public Membership AddMembership(int organizationId, DateTime expires) + public Membership AddMembership (int organizationId, DateTime expires) { - return Membership.Create(Identity, organizationId, expires); + return Membership.Create (Identity, organizationId, expires); } - private bool? HasExplicitSubscription(int newsletterFeedId) + private bool? HasExplicitSubscription (int newsletterFeedId) { if (null == this.subscriptions) { - this.subscriptions = SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForSubscriber(PersonId); + this.subscriptions = SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForSubscriber (PersonId); } - if (this.subscriptions.ContainsKey(newsletterFeedId)) + if (this.subscriptions.ContainsKey (newsletterFeedId)) { return this.subscriptions[newsletterFeedId]; } return null; } - public bool IsSubscribing(int newsletterFeedId) + public bool IsSubscribing (int newsletterFeedId) { - bool? subscription = HasExplicitSubscription(newsletterFeedId); + bool? subscription = HasExplicitSubscription (newsletterFeedId); if (subscription != null) { return (bool) subscription; @@ -786,7 +787,7 @@ namespace Swarmops.Logic.Swarm try { //Added try catch, throws exception on nonexisting feed id - NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); + NewsletterFeed feed = NewsletterFeed.FromIdentity (newsletterFeedId); return feed.DefaultSubscribed; } catch @@ -795,19 +796,19 @@ namespace Swarmops.Logic.Swarm } } - public virtual void SetSubscription(int newsletterFeedId, bool subscribe) + public virtual void SetSubscription (int newsletterFeedId, bool subscribe) { - bool? subscription = HasExplicitSubscription(newsletterFeedId); + bool? subscription = HasExplicitSubscription (newsletterFeedId); if (subscription != null && subscription != subscribe) { - SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); + SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription (PersonId, newsletterFeedId, subscribe); } else { - NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); + NewsletterFeed feed = NewsletterFeed.FromIdentity (newsletterFeedId); if (subscribe != feed.DefaultSubscribed) { - SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); + SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription (PersonId, newsletterFeedId, subscribe); } } this.subscriptions[newsletterFeedId] = subscribe; @@ -816,104 +817,104 @@ namespace Swarmops.Logic.Swarm public void DeleteSubscriptionData() { - SwarmDb.GetDatabaseForWriting().DeletePersonNewsletterSubscriptions(Identity); + SwarmDb.GetDatabaseForWriting().DeletePersonNewsletterSubscriptions (Identity); } /// /// Sends a phone text message to the person's mobile phone. /// - public void SendPhoneMessage(string message) + public void SendPhoneMessage (string message) { // HACK: This currently only works for Swedish people. try { - PhoneMessageTransmitter.Send(Phone, message); + PhoneMessageTransmitter.Send (Phone, message); // SwarmDb.GetDatabase().LogTransmittedPhoneMessage(Identity, Phone, message); } catch (Exception ex) { - throw new Exception( + throw new Exception ( "Failed to send phone message:[" + message + "]\r\nto person [#" + Identity + "]:\r\n" + ex.Message, ex); } } - public virtual void SetPassword(string newPassword) + public virtual void SetPassword (string newPassword) { - string hash = Authentication.GenerateNewPasswordHash(Identity, newPassword); - SwarmDb.GetDatabaseForWriting().SetPersonPasswordHash(Identity, hash); + string hash = Authentication.GenerateNewPasswordHash (Identity, newPassword); + SwarmDb.GetDatabaseForWriting().SetPersonPasswordHash (Identity, hash); base.PasswordHash = hash; } - private void SendNotice(string subject, string body, int organizationId, bool asOfficer) + private void SendNotice (string subject, string body, int organizationId, bool asOfficer) { - int mailId = SwarmDb.GetDatabaseForWriting().CreateOutboundMail( + int mailId = SwarmDb.GetDatabaseForWriting().CreateOutboundMail ( asOfficer ? MailAuthorType.PirateWeb : MailAuthorType.Service, 0, subject, body, OutboundMail.PriorityNormal, 0, GeographyId, organizationId, DateTime.Now); SwarmDb.GetDatabaseForWriting() - .CreateOutboundMailRecipient(mailId, Identity, asOfficer, + .CreateOutboundMailRecipient (mailId, Identity, asOfficer, (int) OutboundMailRecipient.RecipientType.Person); - SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount(mailId, 1); - SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved(mailId); - SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup(mailId); + SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount (mailId, 1); + SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved (mailId); + SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup (mailId); } - public void SendNotice(string subject, string body, int organizationId) + public void SendNotice (string subject, string body, int organizationId) { //TODO: Comes in here with organizationId hardcoded as 1 from a lot of places - SendNotice(subject, body, organizationId, false); + SendNotice (subject, body, organizationId, false); } - public void SendOfficerNotice(string subject, string body, int organizationId) + public void SendOfficerNotice (string subject, string body, int organizationId) { - SendNotice(subject, body, organizationId, true); + SendNotice (subject, body, organizationId, true); } - public void SendOfficerNotice(TypedMailTemplate mailtempl, int organizationId) + public void SendOfficerNotice (TypedMailTemplate mailtempl, int organizationId) { - SendNotice(mailtempl, organizationId, true); + SendNotice (mailtempl, organizationId, true); } - public void SendNotice(TypedMailTemplate mailtempl, int organizationId) + public void SendNotice (TypedMailTemplate mailtempl, int organizationId) { - SendNotice(mailtempl, organizationId, false); + SendNotice (mailtempl, organizationId, false); } - public void SendNotice(TypedMailTemplate mailtempl, int organizationId, bool asOfficer) + public void SendNotice (TypedMailTemplate mailtempl, int organizationId, bool asOfficer) { - OutboundMail mail = mailtempl.CreateFunctionalOutboundMail( + OutboundMail mail = mailtempl.CreateFunctionalOutboundMail ( asOfficer ? MailAuthorType.PirateWeb : MailAuthorType.Service, - OutboundMail.PriorityNormal, Organization.FromIdentity(organizationId), + OutboundMail.PriorityNormal, Organization.FromIdentity (organizationId), Geography.Root, DateTime.Now); - mail.AddRecipient(this, asOfficer); - mail.SetRecipientCount(1); + mail.AddRecipient (this, asOfficer); + mail.SetRecipientCount (1); mail.SetResolved(); mail.SetReadyForPickup(); } - public void CreateActivist(bool isPublic, bool isConfirmed) + public void CreateActivist (bool isPublic, bool isConfirmed) { - SwarmDb.GetDatabaseForWriting().CreateActivist(Identity, isPublic, isConfirmed); + SwarmDb.GetDatabaseForWriting().CreateActivist (Identity, isPublic, isConfirmed); } public void TerminateActivist() { - SwarmDb.GetDatabaseForWriting().TerminateActivist(Identity); + SwarmDb.GetDatabaseForWriting().TerminateActivist (Identity); } - public PersonRole AddRole(RoleType roleType, Organization organization, Geography geography) + public PersonRole AddRole (RoleType roleType, Organization organization, Geography geography) { - return AddRole(roleType, organization.Identity, geography.Identity); + return AddRole (roleType, organization.Identity, geography.Identity); } - public PersonRole AddRole(RoleType roleType, int organizationId, int geographyId) + public PersonRole AddRole (RoleType roleType, int organizationId, int geographyId) { - return PersonRole.Create(Identity, roleType, organizationId, geographyId); + return PersonRole.Create (Identity, roleType, organizationId, geographyId); } @@ -922,65 +923,65 @@ namespace Swarmops.Logic.Swarm // TODO: Handle different mail domains based on organisation of person. string name = Name.Trim(); - name = RemoveDiacritics(name); + name = RemoveDiacritics (name); name = name.ToLower(); - name = name.Replace("æ", "ae"); + name = name.Replace ("æ", "ae"); //change all non valid chars to '.' - Regex re = new Regex(@"[^-a-z0-9\.]", RegexOptions.IgnoreCase); - name = re.Replace(name, "."); + Regex re = new Regex (@"[^-a-z0-9\.]", RegexOptions.IgnoreCase); + name = re.Replace (name, "."); - while (name.Contains("..")) - name = name.Replace("..", "."); + while (name.Contains ("..")) + name = name.Replace ("..", "."); return name + "@piratpartiet.se"; } - private static string RemoveDiacritics(string stIn) + private static string RemoveDiacritics (string stIn) { // Doesn't account for æ, but strips everything else conceivable - string stFormD = stIn.Normalize(NormalizationForm.FormD); + string stFormD = stIn.Normalize (NormalizationForm.FormD); StringBuilder sb = new StringBuilder(); for (int ich = 0; ich < stFormD.Length; ich++) { - UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]); + UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory (stFormD[ich]); if (uc != UnicodeCategory.NonSpacingMark) { - sb.Append(stFormD[ich]); + sb.Append (stFormD[ich]); } } - return (sb.ToString().Normalize(NormalizationForm.FormC)); + return (sb.ToString().Normalize (NormalizationForm.FormC)); } public string CreateUniquePPMailAddress() { string newAddress = CreatePPMailAddress(); - newAddress = MailServerDatabase.FindFreeAccount(newAddress); + newAddress = MailServerDatabase.FindFreeAccount (newAddress); return newAddress; } - public bool ValidatePassword(string oldpassword) + public bool ValidatePassword (string oldpassword) { - return Authentication.ValidatePassword(this, oldpassword); + return Authentication.ValidatePassword (this, oldpassword); } public string HexIdentifier() { - string identifier = String.Format("{0:X4}", Identity); + string identifier = String.Format ("{0:X4}", Identity); char[] array = identifier.ToCharArray(); - Array.Reverse(array); - return new string(array); + Array.Reverse (array); + return new string (array); } - public bool MemberOf(Organization organization) + public bool MemberOf (Organization organization) { - return MemberOf(organization.Identity); + return MemberOf (organization.Identity); } - public bool MemberOf(int orgId) + public bool MemberOf (int orgId) { Memberships memberships = GetMemberships(); @@ -995,12 +996,12 @@ namespace Swarmops.Logic.Swarm return false; } - public bool MemberOfWithInherited(int orgId) + public bool MemberOfWithInherited (int orgId) { Memberships memberships = GetMemberships(); foreach (Membership membership in memberships) { - if (membership.Organization.IsOrInherits(orgId)) + if (membership.Organization.IsOrInherits (orgId)) { return true; } @@ -1008,9 +1009,9 @@ namespace Swarmops.Logic.Swarm return false; } - public bool MemberOfWithInherited(Organization org) + public bool MemberOfWithInherited (Organization org) { - return MemberOfWithInherited(org.Identity); + return MemberOfWithInherited (org.Identity); } /* --- not used, commented out for usage of hardcoded org ids @@ -1049,22 +1050,22 @@ namespace Swarmops.Logic.Swarm // ReSharper disable InconsistentNaming - public Tasks GetTasksForOrganization(Organization organization) + public Tasks GetTasksForOrganization (Organization organization) { - return Tasks.ForPersonOrganization(this, organization); + return Tasks.ForPersonOrganization (this, organization); } - public string GetAvatarLink(int pixelSize) + public string GetAvatarLink (int pixelSize) { - return string.Format("http://www.gravatar.com/avatar/{0}.jpg?s={1}&d=mm", MailMD5, pixelSize); + return string.Format ("http://www.gravatar.com/avatar/{0}.jpg?s={1}&d=mm", MailMD5, pixelSize); } - public string GetSecureAvatarLink(int pixelSize) + public string GetSecureAvatarLink (int pixelSize) { - return GetAvatarLink(pixelSize).Replace("http://www", "https://secure"); + return GetAvatarLink (pixelSize).Replace ("http://www", "https://secure"); } - public bool HasAccess(Access access) + public bool HasAccess (Access access) { if (access == null) { @@ -1089,11 +1090,11 @@ namespace Swarmops.Logic.Swarm List resultingPeople = new List(); - string[] idStrings = ids.Trim().Replace(" ", " ").Split(' '); + string[] idStrings = ids.Trim().Replace (" ", " ").Split (' '); foreach (string idString in idStrings) { - if (Int32.Parse(idString) == Identity) + if (Int32.Parse (idString) == Identity) { return true; } diff --git a/Logic/Swarm/PersonRole.cs b/Logic/Swarm/PersonRole.cs index 73429695..2ba50593 100644 --- a/Logic/Swarm/PersonRole.cs +++ b/Logic/Swarm/PersonRole.cs @@ -9,59 +9,59 @@ namespace Swarmops.Logic.Swarm { #region Creation and Construction - private PersonRole() : base(null) + private PersonRole() : base (null) { } - private PersonRole(BasicPersonRole basic) : base(basic) + private PersonRole (BasicPersonRole basic) : base (basic) { } - public static PersonRole Create(int personId, RoleType roleType, int organizationId, int nodeId) + public static PersonRole Create (int personId, RoleType roleType, int organizationId, int nodeId) { return - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() - .CreateRole(personId, roleType, organizationId, nodeId)); + FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + .CreateRole (personId, roleType, organizationId, nodeId)); } - public static PersonRole FromBasic(BasicPersonRole basic) + public static PersonRole FromBasic (BasicPersonRole basic) { - return new PersonRole(basic); + return new PersonRole (basic); } - public static PersonRole FromIdentity(int roleId) + public static PersonRole FromIdentity (int roleId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetRole(roleId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetRole (roleId)); } - public static PersonRole FromIdentityAggressive(int roleId) + public static PersonRole FromIdentityAggressive (int roleId) { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetRole(roleId)); - // Note "for writing". Intentional. Queries master db and bypasses replication lag to avoid race conditions. + return FromBasic (SwarmDb.GetDatabaseForWriting().GetRole (roleId)); + // Note "for writing". Intentional. Queries master db and bypasses replication lag to avoid race conditions. } #endregion public Person Person { - get { return Person.FromIdentity(base.PersonId); } + get { return Person.FromIdentity (base.PersonId); } } public Geography Geography { - get { return Geography.FromIdentity(base.GeographyId); } + get { return Geography.FromIdentity (base.GeographyId); } } public Organization Organization { - get { return Organization.FromIdentity(base.OrganizationId); } + get { return Organization.FromIdentity (base.OrganizationId); } } #region Manipulation public void Delete() { - SwarmDb.GetDatabaseForWriting().DeleteRole(Identity); + SwarmDb.GetDatabaseForWriting().DeleteRole (Identity); // After this call, the role will be invalid. } diff --git a/Logic/Swarm/RoleLookup.cs b/Logic/Swarm/RoleLookup.cs index 088c01d6..bb212420 100644 --- a/Logic/Swarm/RoleLookup.cs +++ b/Logic/Swarm/RoleLookup.cs @@ -9,26 +9,26 @@ namespace Swarmops.Logic.Swarm { private readonly Dictionary lookup; - internal RoleLookup(Roles initialSet) + internal RoleLookup (Roles initialSet) { this.lookup = new Dictionary(); foreach (PersonRole role in initialSet) { - if (!this.lookup.ContainsKey(role.Type)) + if (!this.lookup.ContainsKey (role.Type)) { this.lookup[role.Type] = new Roles(); } - this.lookup[role.Type].Add(role); + this.lookup[role.Type].Add (role); } } - public Roles this[RoleType roleType] + public Roles this [RoleType roleType] { get { - if (this.lookup.ContainsKey(roleType)) + if (this.lookup.ContainsKey (roleType)) { return this.lookup[roleType]; } @@ -37,31 +37,31 @@ namespace Swarmops.Logic.Swarm } } - public static RoleLookup FromOrganization(int organizationId) + public static RoleLookup FromOrganization (int organizationId) { Roles roles = - Roles.FromArray(SwarmDb.GetDatabaseForReading().GetRolesForOrganization(organizationId)); + Roles.FromArray (SwarmDb.GetDatabaseForReading().GetRolesForOrganization (organizationId)); - return new RoleLookup(roles); + return new RoleLookup (roles); } - public static RoleLookup FromGeographyAndOrganization(int geographyId, int organizationId) + public static RoleLookup FromGeographyAndOrganization (int geographyId, int organizationId) { Roles roles = - Roles.FromArray(SwarmDb.GetDatabaseForReading() - .GetRolesForOrganizationGeography(organizationId, geographyId)); + Roles.FromArray (SwarmDb.GetDatabaseForReading() + .GetRolesForOrganizationGeography (organizationId, geographyId)); - return new RoleLookup(roles); + return new RoleLookup (roles); } - public static RoleLookup FromGeographyAndOrganization(Geography geography, Organization organization) + public static RoleLookup FromGeographyAndOrganization (Geography geography, Organization organization) { - return FromGeographyAndOrganization(geography.Identity, organization.Identity); + return FromGeographyAndOrganization (geography.Identity, organization.Identity); } - public static RoleLookup FromOrganization(Organization organization) + public static RoleLookup FromOrganization (Organization organization) { - return FromOrganization(organization.Identity); + return FromOrganization (organization.Identity); } } } \ No newline at end of file diff --git a/Logic/Swarm/Roles.cs b/Logic/Swarm/Roles.cs index 2636afbb..14584f07 100644 --- a/Logic/Swarm/Roles.cs +++ b/Logic/Swarm/Roles.cs @@ -10,14 +10,14 @@ namespace Swarmops.Logic.Swarm { public class Roles : List { - public static Roles FromArray(BasicPersonRole[] basicArray) + public static Roles FromArray (BasicPersonRole[] basicArray) { Roles result = new Roles(); result.Capacity = basicArray.Length*11/10; foreach (BasicPersonRole basic in basicArray) { - result.Add(PersonRole.FromBasic(basic)); + result.Add (PersonRole.FromBasic (basic)); } return result; @@ -30,10 +30,10 @@ namespace Swarmops.Logic.Swarm /// The organization where something happened. /// The geonode where something happened. /// A list of person Ids that hold roles above this point. - public static int[] GetAllUpwardRoles(int organizationId, int geographyId) + public static int[] GetAllUpwardRoles (int organizationId, int geographyId) { - return GetAllUpwardRoles(organizationId, geographyId, - Authorization.RoleTypesWithPermission(Permission.CanSeePeople)); + return GetAllUpwardRoles (organizationId, geographyId, + Authorization.RoleTypesWithPermission (Permission.CanSeePeople)); } /// @@ -43,10 +43,10 @@ namespace Swarmops.Logic.Swarm /// The geonode where something happened. /// The RoleTypes which are to be collected. /// A list of person Ids that hold roles above this point. - public static int[] GetAllUpwardRoles(int organizationId, int geographyId, RoleType[] roleTypes) + public static int[] GetAllUpwardRoles (int organizationId, int geographyId, RoleType[] roleTypes) { - Organizations orgLine = Organization.FromIdentity(organizationId).GetLine(); - Geographies nodeLine = Geography.FromIdentity(geographyId).GetLine(); + Organizations orgLine = Organization.FromIdentity (organizationId).GetLine(); + Geographies nodeLine = Geography.FromIdentity (geographyId).GetLine(); int[] nodeIds = nodeLine.Identities; @@ -55,12 +55,12 @@ namespace Swarmops.Logic.Swarm foreach (Organization org in orgLine) { BasicPersonRole[] upwardPersonRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies (org.Identity, nodeIds); foreach (BasicPersonRole role in upwardPersonRoles) { - if (Array.IndexOf(roleTypes, role.Type) > -1) + if (Array.IndexOf (roleTypes, role.Type) > -1) { peopleTable[role.PersonId] = true; } @@ -73,7 +73,7 @@ namespace Swarmops.Logic.Swarm foreach (int personId in peopleTable.Keys) { - result.Add(personId); + result.Add (personId); } return result.ToArray(); @@ -83,15 +83,15 @@ namespace Swarmops.Logic.Swarm /// /// Gets a list of person IDs that are officers in the org/geography combo. /// - public static int[] GetAllDownwardRoles(int organizationId, int geographyId) + public static int[] GetAllDownwardRoles (int organizationId, int geographyId) { Organizations orgTree = null; Geographies nodeTree = null; int[] nodeIds; - orgTree = Organization.FromIdentity(organizationId).GetTree(); + orgTree = Organization.FromIdentity (organizationId).GetTree(); if (geographyId > 0) { - nodeTree = Geography.FromIdentity(geographyId).GetTree(); + nodeTree = Geography.FromIdentity (geographyId).GetTree(); nodeIds = nodeTree.Identities; } else @@ -104,7 +104,7 @@ namespace Swarmops.Logic.Swarm foreach (Organization org in orgTree) { BasicPersonRole[] downwardPersonRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies (org.Identity, nodeIds); foreach (BasicPersonRole role in downwardPersonRoles) @@ -119,13 +119,13 @@ namespace Swarmops.Logic.Swarm foreach (int personId in peopleTable.Keys) { - result.Add(personId); + result.Add (personId); } return result.ToArray(); } - public static BasicPersonRole[] GetAllDownwardRolesRoles(int organizationId, int geographyId) + public static BasicPersonRole[] GetAllDownwardRolesRoles (int organizationId, int geographyId) { Organizations orgTree = null; Geographies nodeTree = null; @@ -133,12 +133,12 @@ namespace Swarmops.Logic.Swarm int[] nodeIds; int[] orgIds; - orgTree = Organization.FromIdentity(organizationId).GetTree(); + orgTree = Organization.FromIdentity (organizationId).GetTree(); orgIds = orgTree.Identities; if (geographyId > 0) { - nodeTree = Geography.FromIdentity(geographyId).GetTree(); + nodeTree = Geography.FromIdentity (geographyId).GetTree(); nodeIds = nodeTree.Identities; } else @@ -146,77 +146,78 @@ namespace Swarmops.Logic.Swarm nodeIds = new int[0]; } - return SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(orgIds, nodeIds); + return SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies (orgIds, nodeIds); ; } - public static Roles FromOrganization(Organization organization) + public static Roles FromOrganization (Organization organization) { - return FromOrganization(organization.Identity); + return FromOrganization (organization.Identity); } - public static Roles FromOrganization(int organizationId) + public static Roles FromOrganization (int organizationId) { - BasicPersonRole[] basicPersonRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganization(organizationId); + BasicPersonRole[] basicPersonRoles = SwarmDb.GetDatabaseForReading() + .GetRolesForOrganization (organizationId); - return FromArray(basicPersonRoles); + return FromArray (basicPersonRoles); } - public static Person GetLocalLead(Organization organization, Geography geography) + public static Person GetLocalLead (Organization organization, Geography geography) { - return GetLocalLead(organization.Identity, geography.Identity); + return GetLocalLead (organization.Identity, geography.Identity); } - public static Person GetLocalLead(int organizationId, int geographyId) + public static Person GetLocalLead (int organizationId, int geographyId) { BasicPersonRole[] personRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography (organizationId, geographyId); foreach (BasicPersonRole role in personRoles) { if (role.Type == RoleType.LocalLead) { - return Person.FromIdentity(role.PersonId); + return Person.FromIdentity (role.PersonId); } } - throw new ArgumentException("No Local Lead for org/geo"); + throw new ArgumentException ("No Local Lead for org/geo"); } - public static Person GetChairman(Organization organization) + public static Person GetChairman (Organization organization) { BasicPersonRole[] personRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganization(organization.Identity); + SwarmDb.GetDatabaseForReading().GetRolesForOrganization (organization.Identity); foreach (BasicPersonRole role in personRoles) { if (role.Type == RoleType.OrganizationChairman) { - return Person.FromIdentity(role.PersonId); + return Person.FromIdentity (role.PersonId); } } - throw new ArgumentException("No Chairman for organization"); + throw new ArgumentException ("No Chairman for organization"); } - public static People GetLocalDeputies(Organization org, Geography geo) + public static People GetLocalDeputies (Organization org, Geography geo) { - return GetLocalDeputies(org.Identity, geo.Identity); + return GetLocalDeputies (org.Identity, geo.Identity); } - public static People GetLocalDeputies(int organizationId, int geographyId) + public static People GetLocalDeputies (int organizationId, int geographyId) { BasicPersonRole[] personRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography (organizationId, geographyId); People result = new People(); foreach (BasicPersonRole role in personRoles) { if (role.Type == RoleType.LocalDeputy) { - result.Add(Person.FromIdentity(role.PersonId)); + result.Add (Person.FromIdentity (role.PersonId)); } } @@ -224,13 +225,13 @@ namespace Swarmops.Logic.Swarm } - public static People GetActivists(Organization organization, Geography geography) + public static People GetActivists (Organization organization, Geography geography) { People people = new People(); // Expensive op: BasicPersonRole[] basicPersonRoles = - SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(organization.GetTree().Identities, + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies (organization.GetTree().Identities, geography.GetTree().Identities); Dictionary lookup = new Dictionary(); @@ -239,9 +240,9 @@ namespace Swarmops.Logic.Swarm if (basicRole.Type == RoleType.LocalActive || basicRole.Type == RoleType.LocalLead || basicRole.Type == RoleType.LocalDeputy) { - if (!lookup.ContainsKey(basicRole.PersonId)) + if (!lookup.ContainsKey (basicRole.PersonId)) { - people.Add(Person.FromIdentity(basicRole.PersonId)); + people.Add (Person.FromIdentity (basicRole.PersonId)); lookup[basicRole.PersonId] = true; } } @@ -254,7 +255,7 @@ namespace Swarmops.Logic.Swarm public static Roles GetAll() { - return FromArray(SwarmDb.GetDatabaseForReading().GetRoles()); + return FromArray (SwarmDb.GetDatabaseForReading().GetRoles()); } } } \ No newline at end of file diff --git a/Logic/Swarm/Volunteer.cs b/Logic/Swarm/Volunteer.cs index 289db2ff..40ea12b4 100644 --- a/Logic/Swarm/Volunteer.cs +++ b/Logic/Swarm/Volunteer.cs @@ -12,34 +12,34 @@ namespace Swarmops.Logic.Swarm #region Creation and Construction private Volunteer() - : base(0, 0, 0, DateTime.MinValue, false, DateTime.MinValue, string.Empty) + : base (0, 0, 0, DateTime.MinValue, false, DateTime.MinValue, string.Empty) { } - private Volunteer(BasicVolunteer basic) - : base(basic) + private Volunteer (BasicVolunteer basic) + : base (basic) { // empty ctor } - public static Volunteer FromIdentity(int volunteerId) + public static Volunteer FromIdentity (int volunteerId) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetVolunteer(volunteerId)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetVolunteer (volunteerId)); } - public static Volunteer FromBasic(BasicVolunteer basic) + public static Volunteer FromBasic (BasicVolunteer basic) { - return new Volunteer(basic); + return new Volunteer (basic); } - public static Volunteer Create(Person person, Person owner) + public static Volunteer Create (Person person, Person owner) { - return Create(person.Identity, owner.Identity); + return Create (person.Identity, owner.Identity); } - public static Volunteer Create(int personId, int ownerPersonId) + public static Volunteer Create (int personId, int ownerPersonId) { - return FromIdentity(SwarmDb.GetDatabaseForWriting().CreateVolunteer(personId, ownerPersonId)); + return FromIdentity (SwarmDb.GetDatabaseForWriting().CreateVolunteer (personId, ownerPersonId)); } #endregion @@ -67,7 +67,7 @@ namespace Swarmops.Logic.Swarm set { this.ownerPerson = value; - SwarmDb.GetDatabaseForWriting().SetVolunteerOwnerPersonId(Identity, value.Identity); + SwarmDb.GetDatabaseForWriting().SetVolunteerOwnerPersonId (Identity, value.Identity); } } @@ -122,35 +122,35 @@ namespace Swarmops.Logic.Swarm { get { - return VolunteerRoles.FromArray(SwarmDb.GetDatabaseForReading().GetVolunteerRolesByVolunteer(Identity)); + return VolunteerRoles.FromArray (SwarmDb.GetDatabaseForReading().GetVolunteerRolesByVolunteer (Identity)); } } - public void AddRole(Organization organization, Geography geography, RoleType roleType) + public void AddRole (Organization organization, Geography geography, RoleType roleType) { - AddRole(organization.Identity, geography.Identity, roleType); + AddRole (organization.Identity, geography.Identity, roleType); } - public void AddRole(int organizationId, int geographyId, RoleType roleType) + public void AddRole (int organizationId, int geographyId, RoleType roleType) { - SwarmDb.GetDatabaseForWriting().CreateVolunteerRole(Identity, organizationId, geographyId, roleType); + SwarmDb.GetDatabaseForWriting().CreateVolunteerRole (Identity, organizationId, geographyId, roleType); } - public void Close(string comments) + public void Close (string comments) { - SwarmDb.GetDatabaseForWriting().CloseVolunteer(Identity, comments); + SwarmDb.GetDatabaseForWriting().CloseVolunteer (Identity, comments); } private void PopulateCache() { if (this.person == null) { - this.person = Person.FromIdentity(PersonId); + this.person = Person.FromIdentity (PersonId); } if (this.ownerPerson == null) { - this.ownerPerson = Person.FromIdentity(OwnerPersonId); + this.ownerPerson = Person.FromIdentity (OwnerPersonId); } if (this.geography == null) @@ -175,7 +175,7 @@ namespace Swarmops.Logic.Swarm /// /// /// The parent of top geographies that could/should recieve volunteer (country) - public void AutoAssign(Geography geo, int withinOrg, Person defaultOwner, int stopGeography) + public void AutoAssign (Geography geo, int withinOrg, Person defaultOwner, int stopGeography) { //Note: stopGeography is only needed because Districts ar not properly defined. Districts are the ones below country. try @@ -187,9 +187,9 @@ namespace Swarmops.Logic.Swarm //Move up to target geography level //GeographyLevel targetLevel = GeographyLevel.ElectoralCircuit; GeographyLevel targetLevel = GeographyLevel.District; - //This will never hit bcse Districts ar not properly defined + //This will never hit bcse Districts ar not properly defined - while (!(volonteerGeography.AtLevel(targetLevel)) + while (!(volonteerGeography.AtLevel (targetLevel)) && (volonteerGeography.ParentGeographyId != 0) && (volonteerGeography.ParentGeographyId != stopGeography) ) @@ -197,7 +197,7 @@ namespace Swarmops.Logic.Swarm volonteerGeography = volonteerGeography.Parent; } - Person localLead = Swarm.Roles.GetLocalLead(withinOrg, volonteerGeography.Identity); + Person localLead = Swarm.Roles.GetLocalLead (withinOrg, volonteerGeography.Identity); if (localLead == null && volonteerGeography.Parent != null) { @@ -208,7 +208,7 @@ namespace Swarmops.Logic.Swarm { volonteerGeography = volonteerGeography.Parent; } - localLead = Swarm.Roles.GetLocalLead(withinOrg, volonteerGeography.Parent.Parent.Identity); + localLead = Swarm.Roles.GetLocalLead (withinOrg, volonteerGeography.Parent.Parent.Identity); } //Found anyone? otherwise leave default Owner. diff --git a/Logic/Swarm/VolunteerRole.cs b/Logic/Swarm/VolunteerRole.cs index bcdab34f..4b1ff2fa 100644 --- a/Logic/Swarm/VolunteerRole.cs +++ b/Logic/Swarm/VolunteerRole.cs @@ -6,27 +6,27 @@ namespace Swarmops.Logic.Swarm { public class VolunteerRole : BasicVolunteerRole { - private VolunteerRole(BasicVolunteerRole basic) : - base(basic) + private VolunteerRole (BasicVolunteerRole basic) : + base (basic) { } public Geography Geography { - get { return Geography.FromIdentity(base.GeographyId); } // Cache later if necessary + get { return Geography.FromIdentity (base.GeographyId); } // Cache later if necessary } - public static VolunteerRole FromBasic(BasicVolunteerRole basic) + public static VolunteerRole FromBasic (BasicVolunteerRole basic) { - return new VolunteerRole(basic); + return new VolunteerRole (basic); } - public static VolunteerRole FromIdentity(int identity) + public static VolunteerRole FromIdentity (int identity) { - return FromBasic(SwarmDb.GetDatabaseForReading().GetVolunteerRole(identity)); + return FromBasic (SwarmDb.GetDatabaseForReading().GetVolunteerRole (identity)); } - public void Close(bool wasAssigned) + public void Close (bool wasAssigned) { // TODO } diff --git a/Logic/Swarm/VolunteerRoles.cs b/Logic/Swarm/VolunteerRoles.cs index bfda178c..1588a113 100644 --- a/Logic/Swarm/VolunteerRoles.cs +++ b/Logic/Swarm/VolunteerRoles.cs @@ -5,14 +5,14 @@ namespace Swarmops.Logic.Swarm { public class VolunteerRoles : List { - public static VolunteerRoles FromArray(BasicVolunteerRole[] basicArray) + public static VolunteerRoles FromArray (BasicVolunteerRole[] basicArray) { VolunteerRoles result = new VolunteerRoles(); result.Capacity = basicArray.Length*11/10; foreach (BasicVolunteerRole basic in basicArray) { - result.Add(VolunteerRole.FromBasic(basic)); + result.Add (VolunteerRole.FromBasic (basic)); } return result; diff --git a/Logic/Swarm/Volunteers.cs b/Logic/Swarm/Volunteers.cs index 1cfe6569..b9765ead 100644 --- a/Logic/Swarm/Volunteers.cs +++ b/Logic/Swarm/Volunteers.cs @@ -13,31 +13,31 @@ namespace Swarmops.Logic.Swarm { public static Volunteers GetOpen() { - return FromArray(SwarmDb.GetDatabaseForReading().GetOpenVolunteers()); + return FromArray (SwarmDb.GetDatabaseForReading().GetOpenVolunteers()); } - public static Volunteers FromArray(BasicVolunteer[] basicArray) + public static Volunteers FromArray (BasicVolunteer[] basicArray) { Volunteers result = new Volunteers(); result.Capacity = basicArray.Length*11/10; foreach (BasicVolunteer basic in basicArray) { - result.Add(Volunteer.FromBasic(basic)); + result.Add (Volunteer.FromBasic (basic)); } return result; } - public static Volunteers FromSingle(Volunteer volunteer) + public static Volunteers FromSingle (Volunteer volunteer) { Volunteers volunteers = new Volunteers(); - volunteers.Add(volunteer); + volunteers.Add (volunteer); return volunteers; } - public void Remove(Volunteers volunteersToRemove) + public void Remove (Volunteers volunteersToRemove) { Dictionary identityLookup = new Dictionary(); @@ -50,11 +50,11 @@ namespace Swarmops.Logic.Swarm while (index < Count) { - if (identityLookup.ContainsKey(this[index].Identity)) + if (identityLookup.ContainsKey (this[index].Identity)) { // This volunteer should be removed from the list. - RemoveAt(index); + RemoveAt (index); } else { @@ -65,9 +65,9 @@ namespace Swarmops.Logic.Swarm } } - public new void Remove(Volunteer volunteerToRemove) + public new void Remove (Volunteer volunteerToRemove) { - Remove(FromSingle(volunteerToRemove)); + Remove (FromSingle (volunteerToRemove)); } public DataSet ToDataSet() @@ -76,11 +76,11 @@ namespace Swarmops.Logic.Swarm // It's possible to write it more optimized, and build the DataSet by hand, but that takes // around 100 LoC. - XmlSerializer serializer = new XmlSerializer(typeof (Volunteers)); + XmlSerializer serializer = new XmlSerializer (typeof (Volunteers)); StringWriter sw = new StringWriter(); - serializer.Serialize(sw, this); + serializer.Serialize (sw, this); DataSet ds = new DataSet(); - ds.ReadXml(sw.ToString()); + ds.ReadXml (sw.ToString()); return ds; } diff --git a/Site5/Pages/v5/Swarm/AddPerson.aspx.cs b/Site5/Pages/v5/Swarm/AddPerson.aspx.cs index 3199906d..895f94c1 100644 --- a/Site5/Pages/v5/Swarm/AddPerson.aspx.cs +++ b/Site5/Pages/v5/Swarm/AddPerson.aspx.cs @@ -2,6 +2,7 @@ using System.Web.UI; using System.Web.UI.WebControls; using Resources; +using Swarmops.Logic.Communications; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Swarm; diff --git a/Utility/BotCode/ActivityMailer.cs b/Utility/BotCode/ActivityMailer.cs index a7646f9d..f5b5dccb 100644 --- a/Utility/BotCode/ActivityMailer.cs +++ b/Utility/BotCode/ActivityMailer.cs @@ -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. diff --git a/Utility/BotCode/BallotComposer.cs b/Utility/BotCode/BallotComposer.cs index affdaa32..859ec8bd 100644 --- a/Utility/BotCode/BallotComposer.cs +++ b/Utility/BotCode/BallotComposer.cs @@ -55,11 +55,11 @@ namespace Swarmops.Utility.BotCode } - public void ComposeBallots(BallotCompositionMethod method) + public void ComposeBallots (BallotCompositionMethod method) { FinalBallots = new Dictionary(); - 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 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 /// The position of a particular ballot. /// The composition method to use. /// The position to pick from the master list, or zero if not from the master list. - 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"); } } diff --git a/Utility/BotCode/BlogTop50Scraper.cs b/Utility/BotCode/BlogTop50Scraper.cs index d1a2d45b..c95debb2 100644 --- a/Utility/BotCode/BlogTop50Scraper.cs +++ b/Utility/BotCode/BlogTop50Scraper.cs @@ -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("

(?.*?)", RegexOptions.None); + Regex regex = new Regex ("

(?.*?)", RegexOptions.None); - Match match = regex.Match(scrapeData); + Match match = regex.Match (scrapeData); List rankingList = new List(); 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()); } } } \ No newline at end of file diff --git a/Utility/BotCode/BlogWatcher.cs b/Utility/BotCode/BlogWatcher.cs index 93277619..c9c6d523 100644 --- a/Utility/BotCode/BlogWatcher.cs +++ b/Utility/BotCode/BlogWatcher.cs @@ -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) { } } diff --git a/Utility/BotCode/BotLog.cs b/Utility/BotCode/BotLog.cs index 3a33860d..5a5f6836 100644 --- a/Utility/BotCode/BotLog.cs +++ b/Utility/BotCode/BotLog.cs @@ -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); } } } diff --git a/Utility/BotCode/EventProcessor.cs b/Utility/BotCode/EventProcessor.cs index 2576d170..f59e229e 100644 --- a/Utility/BotCode/EventProcessor.cs +++ b/Utility/BotCode/EventProcessor.cs @@ -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() { /* diff --git a/Utility/BotCode/HeartBeater.cs b/Utility/BotCode/HeartBeater.cs index cfb53dba..3fbe2b6d 100644 --- a/Utility/BotCode/HeartBeater.cs +++ b/Utility/BotCode/HeartBeater.cs @@ -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(); } } diff --git a/Utility/BotCode/InternalPollMaintenance.cs b/Utility/BotCode/InternalPollMaintenance.cs index f034683f..9eb9da24 100644 --- a/Utility/BotCode/InternalPollMaintenance.cs +++ b/Utility/BotCode/InternalPollMaintenance.cs @@ -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 dupeCheck = new Dictionary(); @@ -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); } } diff --git a/Utility/BotCode/InternalPollRandomizer.cs b/Utility/BotCode/InternalPollRandomizer.cs index 9b08d321..e3ba244a 100644 --- a/Utility/BotCode/InternalPollRandomizer.cs +++ b/Utility/BotCode/InternalPollRandomizer.cs @@ -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) { diff --git a/Utility/BotCode/MailProcessor.cs b/Utility/BotCode/MailProcessor.cs index a28eb334..9e7642cd 100644 --- a/Utility/BotCode/MailProcessor.cs +++ b/Utility/BotCode/MailProcessor.cs @@ -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 QuotedPrintableEncoder = InitQpDictionary(); private static int mailQueueSize; private static readonly Object lockObject = new Object(); @@ -83,7 +83,7 @@ namespace Swarmops.Utility.BotCode { Dictionary qp = new Dictionary(); 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 recipients = new List(); 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; diff --git a/Utility/BotCode/MailResolver.cs b/Utility/BotCode/MailResolver.cs index c929a2b8..3ce732db 100644 --- a/Utility/BotCode/MailResolver.cs +++ b/Utility/BotCode/MailResolver.cs @@ -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 officerIdList = new List(); 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 personIdList = new List(); 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(); 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"; } diff --git a/Utility/BotCode/Mappery.cs b/Utility/BotCode/Mappery.cs index bf573353..ba4fd5ee 100644 --- a/Utility/BotCode/Mappery.cs +++ b/Utility/BotCode/Mappery.cs @@ -8,7 +8,7 @@ namespace Swarmops.Utility.BotCode { public Dictionary 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); } } diff --git a/Utility/BotCode/MediaWatcher.cs b/Utility/BotCode/MediaWatcher.cs index 7cab3128..2921db4a 100644 --- a/Utility/BotCode/MediaWatcher.cs +++ b/Utility/BotCode/MediaWatcher.cs @@ -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) { } } diff --git a/Utility/BotCode/NewsletterChecker.cs b/Utility/BotCode/NewsletterChecker.cs index 9bba0295..fa7ca5c6 100644 --- a/Utility/BotCode/NewsletterChecker.cs +++ b/Utility/BotCode/NewsletterChecker.cs @@ -11,7 +11,7 @@ namespace Swarmops.Utility.BotCode private static Dictionary feedErrorSignaled = new Dictionary(); - [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) { } } diff --git a/Utility/BotCode/PressReleaseChecker.cs b/Utility/BotCode/PressReleaseChecker.cs index aa6098b4..acfae581 100644 --- a/Utility/BotCode/PressReleaseChecker.cs +++ b/Utility/BotCode/PressReleaseChecker.cs @@ -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("

", "

"). - Replace("

", "

"). - Replace("“", "\""). - Replace("”", "\""). - Replace("‘", "'"). - Replace("’", "'"). - Replace("—", "--"). - Replace("…", "..."); + Replace ("

", "

"). + Replace ("

", ""). + Replace ("“", "\""). + Replace ("”", "\""). + Replace ("‘", "'"). + Replace ("’", "'"). + Replace ("—", "--"). + Replace ("…", "..."); } } } \ No newline at end of file diff --git a/Utility/BotCode/RosterHousekeeping.cs b/Utility/BotCode/RosterHousekeeping.cs index 0e550901..36b7263a 100644 --- a/Utility/BotCode/RosterHousekeeping.cs +++ b/Utility/BotCode/RosterHousekeeping.cs @@ -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 csvResultList = new List(); 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 dateLookup = new Dictionary(); DateTime lowerBound = DateTime.Today; - DateTime upperBound = lowerBound.AddDays(31); + DateTime upperBound = lowerBound.AddDays (31); List failedReminders = new List(); 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 dateSummary = new List(); 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"); } } } diff --git a/Utility/BotCode/SalaryProcessor.cs b/Utility/BotCode/SalaryProcessor.cs index 23ea2156..c3490729 100644 --- a/Utility/BotCode/SalaryProcessor.cs +++ b/Utility/BotCode/SalaryProcessor.cs @@ -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 salariesTotalPerBudget = new Dictionary(); 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); } } diff --git a/Utility/BotCode/SchulzeProcessor.cs b/Utility/BotCode/SchulzeProcessor.cs index 46933e72..fb7a7dc9 100644 --- a/Utility/BotCode/SchulzeProcessor.cs +++ b/Utility/BotCode/SchulzeProcessor.cs @@ -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(); this.indexOfCandidateId = new Dictionary(); 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 candidateIdSeen = new Dictionary(); 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. diff --git a/Utility/BotCode/TurnaroundTracker.cs b/Utility/BotCode/TurnaroundTracker.cs index 2657c6de..f8d68b78 100644 --- a/Utility/BotCode/TurnaroundTracker.cs +++ b/Utility/BotCode/TurnaroundTracker.cs @@ -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"; diff --git a/Utility/BotCode/UpdateStatsCache.cs b/Utility/BotCode/UpdateStatsCache.cs index d04ba369..e8b2fced 100644 --- a/Utility/BotCode/UpdateStatsCache.cs +++ b/Utility/BotCode/UpdateStatsCache.cs @@ -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() diff --git a/Utility/Communications/CommsTransmitterMail.cs b/Utility/Communications/CommsTransmitterMail.cs index df08005a..6b4af4f4 100644 --- a/Utility/Communications/CommsTransmitterMail.cs +++ b/Utility/Communications/CommsTransmitterMail.cs @@ -15,16 +15,16 @@ namespace Swarmops.Utility.Communications private static string _smtpServerCache = string.Empty; private static DateTime _cacheReloadTime = DateTime.MinValue; - public void Transmit(PayloadEnvelope envelope, Person person) + public void Transmit (PayloadEnvelope envelope, Person person) { if (envelope.PayloadClass != "Swarmops.Logic.Communications.Transmission.NotificationPayload") { throw new NotImplementedException(); } - ICommsRenderer renderer = NotificationPayload.FromXml(envelope.PayloadXml); + ICommsRenderer renderer = NotificationPayload.FromXml (envelope.PayloadXml); - RenderedComm comm = renderer.RenderComm(person); + RenderedComm comm = renderer.RenderComm (person); MailMessage mail = new MailMessage(); @@ -32,16 +32,16 @@ namespace Swarmops.Utility.Communications try { - mail.From = new MailAddress(comm[CommRenderPart.SenderMail], comm[CommRenderPart.SenderName], + mail.From = new MailAddress (comm[CommRenderPart.SenderMail], comm[CommRenderPart.SenderName], Encoding.UTF8); - mail.To.Add(new MailAddress(person.Mail, person.Name)); + mail.To.Add (new MailAddress (person.Mail, person.Name)); } catch (ArgumentException e) { // Address failure -- either sender or recipient _cacheReloadTime = DateTime.MinValue; - throw new OutboundCommTransmitException("Cannot send mail to " + person.Mail, e); + throw new OutboundCommTransmitException ("Cannot send mail to " + person.Mail, e); } mail.Subject = comm[CommRenderPart.Subject]; @@ -56,28 +56,28 @@ namespace Swarmops.Utility.Communications if (now > _cacheReloadTime) { smtpServer = _smtpServerCache = Persistence.Key["SmtpServer"]; - _cacheReloadTime = now.AddMinutes(5); + _cacheReloadTime = now.AddMinutes (5); } - if (string.IsNullOrEmpty(smtpServer)) + if (string.IsNullOrEmpty (smtpServer)) { smtpServer = "192.168.80.204"; - // For development use only - invalidate cache instead of this, forcing re-reload + // For development use only - invalidate cache instead of this, forcing re-reload _cacheReloadTime = DateTime.MinValue; } - SmtpClient mailClient = new SmtpClient(smtpServer); + SmtpClient mailClient = new SmtpClient (smtpServer); // TODO: SMTP Server login credentials try { - mailClient.Send(mail); + mailClient.Send (mail); } catch (Exception e) { _cacheReloadTime = DateTime.MinValue; - throw new OutboundCommTransmitException("Cannot send mail to " + person.Mail, e); + throw new OutboundCommTransmitException ("Cannot send mail to " + person.Mail, e); } } } diff --git a/Utility/ExceptionMail.cs b/Utility/ExceptionMail.cs index 94a17160..b74dd8a6 100644 --- a/Utility/ExceptionMail.cs +++ b/Utility/ExceptionMail.cs @@ -8,16 +8,16 @@ namespace Swarmops.Utility { public class ExceptionMail { - public static void Send(Exception e) + public static void Send (Exception e) { - Send(e, false); + Send (e, false); } - public static void Send(Exception e, bool logOnly) + public static void Send (Exception e, bool logOnly) { try { - SwarmDb.GetDatabaseForWriting().CreateExceptionLogEntry(DateTime.UtcNow, "ExceptionMail", e); + SwarmDb.GetDatabaseForWriting().CreateExceptionLogEntry (DateTime.UtcNow, "ExceptionMail", e); } catch { @@ -25,9 +25,9 @@ namespace Swarmops.Utility if (!logOnly) { - new MailTransmitter(Strings.MailSenderName, Strings.MailSenderAddress, + new MailTransmitter (Strings.MailSenderName, Strings.MailSenderAddress, "Swarmops EXCEPTION!", - e.ToString(), People.FromIdentities(new[] {1}), false).Send(); + e.ToString(), People.FromIdentities (new[] {1}), false).Send(); } } } diff --git a/Utility/Financial/PaymentGroupMapper.cs b/Utility/Financial/PaymentGroupMapper.cs index 12ebbc95..c1dd699f 100644 --- a/Utility/Financial/PaymentGroupMapper.cs +++ b/Utility/Financial/PaymentGroupMapper.cs @@ -11,8 +11,8 @@ namespace Swarmops.Utility.Financial foreach (Organization organization in economyEnabledOrgs) { - FinancialTransactions unbalancedTransactions = FinancialTransactions.GetUnbalanced(organization); - PaymentGroups groups = PaymentGroups.ForOrganization(organization); + FinancialTransactions unbalancedTransactions = FinancialTransactions.GetUnbalanced (organization); + PaymentGroups groups = PaymentGroups.ForOrganization (organization); FinancialAccount assetsOutboundInvoices = organization.FinancialAccounts.AssetsOutboundInvoices; // This is an N^2 search. Don't care. It runs background. @@ -21,13 +21,13 @@ namespace Swarmops.Utility.Financial { foreach (FinancialTransaction tx in unbalancedTransactions) { - if (group.Open && tx.Description.EndsWith(group.Tag.Substring(4)) && + if (group.Open && tx.Description.EndsWith (group.Tag.Substring (4)) && tx.DateTime.Date == group.DateTime.Date && tx.Rows.AmountCentsTotal == group.AmountCents) { // Match! tx.Dependency = group; - tx.AddRow(assetsOutboundInvoices, -group.AmountCents, null); + tx.AddRow (assetsOutboundInvoices, -group.AmountCents, null); group.Open = false; } } diff --git a/Utility/Financial/PaypalImporter.cs b/Utility/Financial/PaypalImporter.cs index b6bdc566..8fc087a9 100644 --- a/Utility/Financial/PaypalImporter.cs +++ b/Utility/Financial/PaypalImporter.cs @@ -11,22 +11,22 @@ namespace Swarmops.Utility.Financial { public class PaypalImporter { - public static void Run(string data, Organization organization, Person runningPerson) + public static void Run (string data, Organization organization, Person runningPerson) { - if (!data.StartsWith("Date\t Time\t Time Zone\t Name\t Type")) + if (!data.StartsWith ("Date\t Time\t Time Zone\t Name\t Type")) { - runningPerson.SendPhoneMessage( + runningPerson.SendPhoneMessage ( "The file you uploaded does not appear to be a PayPal tab-delimited file of all activity. No processing done. The data has been discarded."); - throw new ArgumentException("This does not appear to be a PayPal file"); + throw new ArgumentException ("This does not appear to be a PayPal file"); } - ImportResult result = ImportPaypal(data); + ImportResult result = ImportPaypal (data); - ImportStats stats = ProcessImportedData(result, organization, runningPerson); + ImportStats stats = ProcessImportedData (result, organization, runningPerson); try { - runningPerson.SendPhoneMessage("The PayPal file was processed. See mail for more details."); + runningPerson.SendPhoneMessage ("The PayPal file was processed. See mail for more details."); } catch (Exception) { @@ -35,31 +35,31 @@ namespace Swarmops.Utility.Financial string mailBody = string.Empty; - mailBody += String.Format("Rows processed: {0,9:N0}\r\n", stats.ProcessedTransactionCount); - mailBody += String.Format("Tx imported: {0,9:N0}\r\n", stats.ImportedTransactionCount); - mailBody += String.Format("Tx modified: {0,9:N0}\r\n", + mailBody += String.Format ("Rows processed: {0,9:N0}\r\n", stats.ProcessedTransactionCount); + mailBody += String.Format ("Tx imported: {0,9:N0}\r\n", stats.ImportedTransactionCount); + mailBody += String.Format ("Tx modified: {0,9:N0}\r\n", stats.ModifiedTransactionCount - stats.ImportedTransactionCount); - runningPerson.SendNotice("PayPal file imported", mailBody, organization.Identity); + runningPerson.SendNotice ("PayPal file imported", mailBody, organization.Identity); } - protected static ImportResult ImportPaypal(string contents) + protected static ImportResult ImportPaypal (string contents) { - string[] lines = contents.Split('\n'); + string[] lines = contents.Split ('\n'); ImportResult result = new ImportResult(); List rows = new List(); foreach (string line in lines) { - string[] parts = line.Split('\t'); + string[] parts = line.Split ('\t'); if (parts.Length < 30) { continue; } - if (StripQuotes(parts[6]) != "SEK") + if (StripQuotes (parts[6]) != "SEK") { continue; // HACK: Need to fix currency support at some time } @@ -68,7 +68,7 @@ namespace Swarmops.Utility.Financial if (result.CurrentBalance == 0.0) { - result.CurrentBalance = Double.Parse(StripQuotes(parts[34]), CultureInfo.InvariantCulture); + result.CurrentBalance = Double.Parse (StripQuotes (parts[34]), CultureInfo.InvariantCulture); } ImportedRow row = new ImportedRow(); @@ -77,25 +77,25 @@ namespace Swarmops.Utility.Financial if (Debugger.IsAttached) { - Console.WriteLine("New Row -----"); + Console.WriteLine ("New Row -----"); - Console.WriteLine("- SuppliedTxId: {0}", parts[12]); - Console.WriteLine("- Comment: {0}", parts[4]); - Console.WriteLine("- DateTime: {0} {1}", parts[0], parts[1]); - Console.WriteLine("- AmountGross: {0}", parts[7]); - Console.WriteLine("- Fee: {0}", parts[8]); - Console.WriteLine("- AmountNet: {0}", parts[9]); + Console.WriteLine ("- SuppliedTxId: {0}", parts[12]); + Console.WriteLine ("- Comment: {0}", parts[4]); + Console.WriteLine ("- DateTime: {0} {1}", parts[0], parts[1]); + Console.WriteLine ("- AmountGross: {0}", parts[7]); + Console.WriteLine ("- Fee: {0}", parts[8]); + Console.WriteLine ("- AmountNet: {0}", parts[9]); } - row.SuppliedTransactionId = StripQuotes(parts[12]); - row.Comment = StripQuotes(parts[4]); - row.DateTime = DateTime.Parse(StripQuotes(parts[0]) + " " + StripQuotes(parts[1]), + row.SuppliedTransactionId = StripQuotes (parts[12]); + row.Comment = StripQuotes (parts[4]); + row.DateTime = DateTime.Parse (StripQuotes (parts[0]) + " " + StripQuotes (parts[1]), CultureInfo.InvariantCulture); - row.AmountCentsGross = Int64.Parse(StripQuotes(parts[7]).Replace(".", "").Replace(",", "")); - row.FeeCents = Int64.Parse(StripQuotes(parts[8]).Replace(".", "").Replace(",", "")); - row.AmountCentsNet = Int64.Parse(StripQuotes(parts[9]).Replace(".", "").Replace(",", "")); + row.AmountCentsGross = Int64.Parse (StripQuotes (parts[7]).Replace (".", "").Replace (",", "")); + row.FeeCents = Int64.Parse (StripQuotes (parts[8]).Replace (".", "").Replace (",", "")); + row.AmountCentsNet = Int64.Parse (StripQuotes (parts[9]).Replace (".", "").Replace (",", "")); - rows.Add(row); + rows.Add (row); } result.Rows = rows; @@ -103,23 +103,23 @@ namespace Swarmops.Utility.Financial } - protected static string StripQuotes(string input) + protected static string StripQuotes (string input) { - if (input.StartsWith("\"")) + if (input.StartsWith ("\"")) { - input = input.Substring(1); + input = input.Substring (1); } - if (input.EndsWith("\"")) + if (input.EndsWith ("\"")) { - input = input.Substring(0, input.Length - 1); + input = input.Substring (0, input.Length - 1); } return input; } - protected static ImportStats ProcessImportedData(ImportResult import, Organization organization, + protected static ImportStats ProcessImportedData (ImportResult import, Organization organization, Person importingPerson) { FinancialAccount payPalAccount = organization.FinancialAccounts.AssetsPaypal; @@ -137,7 +137,7 @@ namespace Swarmops.Utility.Financial // If too old, ignore. - if (row.DateTime < new DateTime(2008, 12, 4)) + if (row.DateTime < new DateTime (2008, 12, 4)) { continue; } @@ -146,19 +146,19 @@ namespace Swarmops.Utility.Financial // If importKey is empty, construct a hash from the data fields. - if (string.IsNullOrEmpty(importKey)) + if (string.IsNullOrEmpty (importKey)) { string hashKey = row.HashBase + row.Comment + - (row.AmountCentsNet/100.0).ToString(CultureInfo.InvariantCulture) + - row.CurrentBalance.ToString(CultureInfo.InvariantCulture) + - row.DateTime.ToString("yyyy-MM-dd-hh-mm-ss"); + (row.AmountCentsNet/100.0).ToString (CultureInfo.InvariantCulture) + + row.CurrentBalance.ToString (CultureInfo.InvariantCulture) + + row.DateTime.ToString ("yyyy-MM-dd-hh-mm-ss"); - importKey = SHA1.Hash(hashKey).Replace(" ", ""); + importKey = SHA1.Hash (hashKey).Replace (" ", ""); } if (importKey.Length > 30) { - importKey = importKey.Substring(0, 30); + importKey = importKey.Substring (0, 30); } Int64 amountCents = row.AmountCentsNet; @@ -174,13 +174,13 @@ namespace Swarmops.Utility.Financial try { - transaction = FinancialTransaction.FromImportKey(organization, importKey); + transaction = FinancialTransaction.FromImportKey (organization, importKey); } catch (Exception) { // if we get here, that means the transaction did not yet exist - transaction = FinancialTransaction.ImportWithStub(organization.Identity, row.DateTime, + transaction = FinancialTransaction.ImportWithStub (organization.Identity, row.DateTime, payPalAccount.Identity, amountCents, row.Comment, importKey, importingPerson.Identity); @@ -230,7 +230,7 @@ namespace Swarmops.Utility.Financial if (transaction.Rows.AmountCentsTotal != 0) // If transaction is unbalanced, balance it { - if (transaction.RecalculateTransaction(nominalTransaction, importingPerson)) + if (transaction.RecalculateTransaction (nominalTransaction, importingPerson)) { result.ModifiedTransactionCount++; } diff --git a/Utility/Financial/PaysonImporter.cs b/Utility/Financial/PaysonImporter.cs index 233a4103..f713c5cd 100644 --- a/Utility/Financial/PaysonImporter.cs +++ b/Utility/Financial/PaysonImporter.cs @@ -13,29 +13,29 @@ namespace Swarmops.Utility.Financial { public class PaysonImporter { - public static void Run(string data, Organization organization, Person runningPerson) + public static void Run (string data, Organization organization, Person runningPerson) { - if (!data.StartsWith("\r\n\r\n\r\n