From fa3b05da6f3f4749a734a4675db9cc29cb8cb360 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 4 Dec 2014 23:55:03 +0100 Subject: [PATCH] Code Cleanup: Assemblies --- Backend/CommsTransmitter.cs | 7 +- Backend/Program.cs | 59 +- Backend/Properties/AssemblyInfo.cs | 18 +- Basic/Config.cs | 6 +- Basic/Diagnostics/Logging.cs | 68 +- Basic/Enums/AddressValidationResult.cs | 50 +- Basic/Enums/AutoMailType.cs | 14 +- Basic/Enums/CommunicationType.cs | 8 +- Basic/Enums/DocumentType.cs | 26 +- Basic/Enums/ExternalActivityType.cs | 3 +- Basic/Enums/ExternalIdentityType.cs | 26 +- Basic/Enums/FinancialAccountType.cs | 23 +- Basic/Enums/FinancialDependencyType.cs | 32 +- Basic/Enums/FinancialValidationType.cs | 17 +- Basic/Enums/GeographyLevel.cs | 17 +- Basic/Enums/InvalidMembershipType.cs | 8 +- Basic/Enums/MailAuthorType.cs | 51 +- Basic/Enums/MembershipPaymentStatus.cs | 31 +- Basic/Enums/ObjectOptionalDataType.cs | 165 +- .../Enums/OrganizationFinancialAccountType.cs | 85 +- Basic/Enums/OutboundCommPriority.cs | 23 +- Basic/Enums/PermissionEnum.cs | 2 +- Basic/Enums/PersonOptionalDataKey.cs | 1 - Basic/Enums/RoleTypeClass.cs | 180 ++- Basic/Interfaces/IHandleProvider.cs | 28 +- Basic/Interfaces/IHasIdentities.cs | 2 +- Basic/Properties/AssemblyInfo.cs | 24 +- Basic/Strings.cs | 9 +- Basic/Types/BasicAddressValidationRun.cs | 6 +- Basic/Types/BasicBallot.cs | 30 +- Basic/Types/BasicChurnDataPoint.cs | 24 +- Basic/Types/BasicCity.cs | 17 +- Basic/Types/BasicCommunicationTurnaround.cs | 37 +- Basic/Types/BasicCountry.cs | 31 +- Basic/Types/BasicCurrency.cs | 20 +- Basic/Types/BasicDocument.cs | 54 +- Basic/Types/BasicElection.cs | 21 +- Basic/Types/BasicExceptionLog.cs | 8 +- Basic/Types/BasicExpenseClaim.cs | 53 +- Basic/Types/BasicExternalActivity.cs | 34 +- Basic/Types/BasicExternalCredential.cs | 12 +- Basic/Types/BasicExternalIdentity.cs | 89 +- Basic/Types/BasicGeography.cs | 26 +- Basic/Types/BasicGeographyDesignation.cs | 14 +- Basic/Types/BasicInboundInvoice.cs | 48 +- Basic/Types/BasicInternalPoll.cs | 52 +- Basic/Types/BasicInternalPollCandidate.cs | 23 +- Basic/Types/BasicInternalPollVote.cs | 18 +- Basic/Types/BasicInternalPollVoteDetail.cs | 14 +- Basic/Types/BasicInternalPollVoter.cs | 25 +- Basic/Types/BasicMailTemplate.cs | 70 +- Basic/Types/BasicMediaCategory.cs | 28 +- Basic/Types/BasicMediaEntry.cs | 50 +- Basic/Types/BasicMediaKeyword.cs | 32 +- Basic/Types/BasicMedium.cs | 32 +- Basic/Types/BasicMembership.cs | 53 +- Basic/Types/BasicMembershipPaymentStatus.cs | 12 +- Basic/Types/BasicNewsletter.cs | 48 +- Basic/Types/BasicNewsletterFeed.cs | 46 +- Basic/Types/BasicNewsletterTemplate.cs | 8 +- Basic/Types/BasicObjectOptionalData.cs | 15 +- Basic/Types/BasicOrganization.cs | 133 +- Basic/Types/BasicOutboundInvoice.cs | 54 +- Basic/Types/BasicOutboundInvoiceItem.cs | 21 +- Basic/Types/BasicOutboundMail.cs | 78 +- Basic/Types/BasicOutboundMailRecipient.cs | 36 +- Basic/Types/BasicPWEvent.cs | 35 +- Basic/Types/BasicPWLog.cs | 94 +- Basic/Types/BasicPaperLetter.cs | 40 +- Basic/Types/BasicParley.cs | 52 +- Basic/Types/BasicParleyAttendee.cs | 30 +- Basic/Types/BasicParleyOption.cs | 23 +- Basic/Types/BasicPayment.cs | 33 +- Basic/Types/BasicPaymentCode.cs | 63 +- Basic/Types/BasicPaymentGroup.cs | 33 +- Basic/Types/BasicPaymentInformation.cs | 42 +- Basic/Types/BasicPayout.cs | 34 +- Basic/Types/BasicPayrollAdjustment.cs | 38 +- Basic/Types/BasicPayrollItem.cs | 76 +- Basic/Types/BasicPermission.cs | 10 +- Basic/Types/BasicPerson.cs | 53 +- Basic/Types/BasicPersonRole.cs | 40 +- Basic/Types/BasicPostalCode.cs | 14 +- Basic/Types/BasicRefund.cs | 27 +- Basic/Types/BasicReporter.cs | 53 +- Basic/Types/BasicSalary.cs | 42 +- Basic/Types/BasicSupplier.cs | 28 +- Basic/Types/BasicSwarmopsLogEntry.cs | 25 +- Basic/Types/BasicUptakeGeography.cs | 62 +- Basic/Types/BasicVolunteer.cs | 25 +- Basic/Types/BasicVolunteerRole.cs | 25 +- Basic/Types/Communications/BasicAutoMail.cs | 36 +- .../Types/Communications/BasicOutboundComm.cs | 62 +- .../BasicOutboundCommRecipient.cs | 27 +- Basic/Types/Financial/BasicCashAdvance.cs | 48 +- .../Types/Financial/BasicFinancialAccount.cs | 46 +- .../Financial/BasicFinancialAccountRow.cs | 24 +- .../Financial/BasicFinancialDependency.cs | 12 +- .../Financial/BasicFinancialTransaction.cs | 18 +- .../Financial/BasicFinancialTransactionRow.cs | 22 +- .../BasicFinancialTransactionTagSet.cs | 32 +- .../BasicFinancialTransactionTagSetType.cs | 20 +- .../BasicFinancialTransactionTagType.cs | 36 +- .../Financial/BasicFinancialValidation.cs | 28 +- Basic/Types/GeographyWithPeople.cs | 10 +- Basic/Types/Governance/BasicMeeting.cs | 33 +- Basic/Types/Governance/BasicMotion.cs | 54 +- .../Types/Governance/BasicMotionAmendment.cs | 38 +- Basic/Types/Security/BasicAuthority.cs | 39 +- Basic/Types/XmlSerializableDictionary.cs | 28 +- Database/Configuration.cs | 114 +- Database/Database-Activists.cs | 17 +- Database/Database-Attribute.cs | 25 +- Database/Database-AutoMails.cs | 19 +- Database/Database-Ballots.cs | 26 +- Database/Database-CashAdvances.cs | 29 +- Database/Database-ChurnData.cs | 20 +- Database/Database-CommunicationTurnarounds.cs | 41 +- Database/Database-Conditions.cs | 61 +- Database/Database-ConnectionsCommands.cs | 61 +- Database/Database-Constructors.cs | 131 +- Database/Database-Countries.cs | 34 +- Database/Database-Currencies.cs | 17 +- Database/Database-Documents.cs | 12 +- Database/Database-Events.cs | 101 +- Database/Database-ExceptionLog.cs | 13 +- Database/Database-Expenses.cs | 77 +- Database/Database-ExternalActivities.cs | 52 +- Database/Database-ExternalCredentials.cs | 7 +- Database/Database-ExternalIdentities.cs | 40 +- ...atabase-FinancialTransactionTagSetTypes.cs | 32 +- .../Database-FinancialTransactionTagSets.cs | 41 +- .../Database-FinancialTransactionTagTypes.cs | 55 +- Database/Database-FinancialTransactionTags.cs | 23 +- Database/Database-FinancialValidations.cs | 20 +- Database/Database-Financials.cs | 173 ++- Database/Database-FlatData.cs | 9 +- Database/Database-Geographies.cs | 88 +- Database/Database-InboundInvoices.cs | 33 +- Database/Database-Initialization.cs | 3 +- Database/Database-InternalPollCandidates.cs | 24 +- Database/Database-InternalPollVotes.cs | 61 +- Database/Database-InternalPolls.cs | 30 +- Database/Database-MailTemplates.cs | 56 +- Database/Database-Media.cs | 77 +- Database/Database-Meetings.cs | 15 +- Database/Database-Memberships.cs | 145 +- Database/Database-MotionAmendments.cs | 36 +- Database/Database-Motions.cs | 25 +- Database/Database-Newsletters.cs | 40 +- Database/Database-Optimizations.cs | 15 +- Database/Database-OptionalData.cs | 36 +- .../Database-OrganizationFinancialAccounts.cs | 17 +- Database/Database-Organizations.cs | 85 +- Database/Database-OutboundCommRecipients.cs | 43 +- Database/Database-OutboundComms.cs | 82 +- Database/Database-OutboundInvoices.cs | 48 +- Database/Database-OutboundMailRecipients.cs | 13 +- Database/Database-OutboundMails.cs | 72 +- Database/Database-PaperLetters.cs | 9 +- Database/Database-ParleyAttendees.cs | 32 +- Database/Database-ParleyOptions.cs | 21 +- Database/Database-Parleys.cs | 34 +- Database/Database-PaymentCodes.cs | 8 +- Database/Database-PaymentGroups.cs | 35 +- Database/Database-Payments.cs | 46 +- Database/Database-Payouts.cs | 66 +- Database/Database-Payroll.cs | 35 +- Database/Database-PayrollAdjustments.cs | 44 +- Database/Database-People.cs | 126 +- Database/Database-Permissions.cs | 26 +- Database/Database-PirateWebLog.cs | 57 +- Database/Database-PostalCodes.cs | 16 +- Database/Database-PostalCodesCities.cs | 77 +- Database/Database-Refunds.cs | 35 +- Database/Database-Reporters.cs | 37 +- Database/Database-Roles.cs | 46 +- Database/Database-Salaries.cs | 38 +- Database/Database-SwarmopsLog.cs | 26 +- Database/Database-TaxLevels.cs | 22 +- Database/Database-TemporaryIdentities.cs | 1 - Database/Database-Tests.cs | 8 +- Database/Database-UrlTranslations.cs | 10 +- Database/Database-Volunteers.cs | 48 +- Database/Properties/AssemblyInfo.cs | 6 +- Interface/Collections/ExpensePayouts.cs | 81 +- .../DataObjects/ExpensePayoutsDataObject.cs | 20 +- Interface/DataObjects/ListPersonDataSource.cs | 88 +- .../OrganizationRolesDataObject.cs | 138 +- Interface/Localization/LocalizationManager.cs | 112 +- Interface/Objects/ExpensePayout.cs | 272 ++-- Interface/Objects/MainMenuItem.cs | 65 +- Interface/Objects/OrganizationMetadata.cs | 54 +- Interface/PersonIcon.cs | 35 +- Interface/PirateWebMapProvider.cs | 87 +- Interface/Properties/AssemblyInfo.cs | 6 +- Interface/RssWriter.cs | 46 +- Logic/AssemblyInfo.cs | 24 +- Logic/Cache/GeographyCache.cs | 59 +- Logic/Cache/GuidCache.cs | 35 +- Logic/Cache/MailTemplateCache.cs | 33 +- Logic/Cache/OrganizationCache.cs | 158 +- Logic/Communications/AutoMail.cs | 26 +- .../Communications/CommunicationTurnaround.cs | 34 +- .../CommunicationTurnarounds.cs | 18 +- Logic/Communications/ICommsRenderer.cs | 6 +- Logic/Communications/ICommsResolver.cs | 2 +- Logic/Communications/ICommsTransmitter.cs | 5 +- Logic/Communications/MailTemplate.cs | 623 ++++---- Logic/Communications/NewsletterFeed.cs | 8 +- Logic/Communications/NewsletterFeeds.cs | 8 +- Logic/Communications/OutboundComm.cs | 360 ++--- Logic/Communications/OutboundCommRecipient.cs | 20 +- .../Communications/OutboundCommRecipients.cs | 7 +- .../OutboundCommTransmitException.cs | 12 +- Logic/Communications/OutboundComms.cs | 4 +- Logic/Communications/OutboundMail.cs | 219 +-- Logic/Communications/OutboundMailRecipient.cs | 91 +- .../Communications/OutboundMailRecipients.cs | 6 +- Logic/Communications/OutboundMails.cs | 12 +- Logic/Communications/PaperLetter.cs | 23 +- Logic/Communications/PaperLetters.cs | 14 +- Logic/Communications/PhoneMessageReceiver.cs | 139 +- .../Communications/PhoneMessageTransmitter.cs | 83 +- .../Transmission/NotificationPayload.cs | 39 +- .../Transmission/PayloadBase.cs | 16 +- .../Transmission/PayloadEnvelope.cs | 4 +- Logic/Communications/TypedMailTemplate.cs | 1196 +++++++++------ Logic/DashboardTasks/TaskAdvanceDebt.cs | 6 +- Logic/DashboardTasks/TaskAttestationLate.cs | 8 +- Logic/DashboardTasks/TaskBase.cs | 12 +- Logic/DashboardTasks/TaskExpenseClaim.cs | 6 +- Logic/DashboardTasks/TaskGroup.cs | 106 +- Logic/DashboardTasks/TaskInboundInvoice.cs | 6 +- Logic/DashboardTasks/TaskPayout.cs | 9 +- Logic/DashboardTasks/TaskReceiptValidation.cs | 9 +- Logic/DashboardTasks/TaskSalary.cs | 10 +- Logic/DashboardTasks/TaskVolunteer.cs | 4 +- Logic/DashboardTasks/Tasks.cs | 59 +- Logic/DataObjects/ExpensesDataObject.cs | 42 +- .../GeographyWithPeopleDataObject.cs | 10 +- Logic/DataObjects/MembershipsDataObject.cs | 20 +- Logic/DataObjects/OrganizationDataObject.cs | 260 ++-- Logic/DataObjects/PeopleDataObject.cs | 59 +- Logic/DataObjects/RolesDataObject.cs | 16 +- .../SEPaymentsBankgiroReader.cs | 5 +- .../TabSeparatedValuesReader.cs | 4 +- Logic/Financial/CashAdvance.cs | 77 +- Logic/Financial/CashAdvances.cs | 26 +- Logic/Financial/Currencies.cs | 10 +- Logic/Financial/Currency.cs | 64 +- Logic/Financial/ExpenseClaim.cs | 334 ++--- Logic/Financial/ExpenseClaims.cs | 51 +- Logic/Financial/ExternalBankData.cs | 127 +- Logic/Financial/ExternalBankDataProfile.cs | 79 +- Logic/Financial/ExternalBankDataRecord.cs | 31 +- Logic/Financial/FinancialAccount.cs | 349 ++--- Logic/Financial/FinancialAccountRow.cs | 16 +- Logic/Financial/FinancialAccountRows.cs | 6 +- Logic/Financial/FinancialAccounts.cs | 40 +- Logic/Financial/FinancialTransaction.cs | 224 +-- Logic/Financial/FinancialTransactionRow.cs | 32 +- Logic/Financial/FinancialTransactionRows.cs | 10 +- Logic/Financial/FinancialTransactionTagSet.cs | 36 +- .../FinancialTransactionTagSetType.cs | 8 +- .../FinancialTransactionTagSetTypesStock.cs | 2 +- .../Financial/FinancialTransactionTagSets.cs | 2 +- .../Financial/FinancialTransactionTagType.cs | 26 +- .../Financial/FinancialTransactionTagTypes.cs | 14 +- Logic/Financial/FinancialTransactions.cs | 21 +- Logic/Financial/FinancialValidation.cs | 20 +- Logic/Financial/FinancialValidations.cs | 26 +- Logic/Financial/IAttestable.cs | 5 +- .../IBankDataAccountStatementReader.cs | 4 +- Logic/Financial/IBankDataPaymentsReader.cs | 2 +- Logic/Financial/ISummable.cs | 2 +- Logic/Financial/IValidatable.cs | 2 +- Logic/Financial/ImportedBankData.cs | 10 +- Logic/Financial/InboundInvoice.cs | 232 ++- Logic/Financial/InboundInvoices.cs | 61 +- .../OrganizationFinancialAccounts.cs | 132 +- Logic/Financial/OutboundInvoice.cs | 318 ++-- Logic/Financial/OutboundInvoiceItem.cs | 20 +- Logic/Financial/OutboundInvoiceItems.cs | 6 +- Logic/Financial/OutboundInvoices.cs | 14 +- Logic/Financial/Payment.cs | 240 +-- Logic/Financial/PaymentGroup.cs | 249 ++-- Logic/Financial/PaymentGroups.cs | 13 +- Logic/Financial/PaymentInformation.cs | 25 +- Logic/Financial/Payments.cs | 6 +- Logic/Financial/Payout.cs | 434 +++--- Logic/Financial/Payouts.cs | 138 +- Logic/Financial/Payroll.cs | 37 +- Logic/Financial/PayrollAdjustment.cs | 48 +- Logic/Financial/PayrollAdjustments.cs | 11 +- Logic/Financial/PayrollItem.cs | 60 +- Logic/Financial/Refund.cs | 78 +- Logic/Financial/Salaries.cs | 49 +- Logic/Financial/Salary.cs | 305 ++-- Logic/Financial/StockBankDataReaders.cs | 16 +- Logic/Financial/TaxLevels.cs | 20 +- Logic/Financial/YearlyReport.cs | 156 +- Logic/Governance/Ballot.cs | 78 +- Logic/Governance/Ballots.cs | 10 +- Logic/Governance/Election.cs | 34 +- Logic/Governance/Meeting.cs | 8 +- Logic/Governance/MeetingElection.cs | 134 +- Logic/Governance/MeetingElectionCandidate.cs | 153 +- Logic/Governance/MeetingElectionCandidates.cs | 5 +- Logic/Governance/MeetingElectionVote.cs | 35 +- Logic/Governance/MeetingElectionVoter.cs | 24 +- Logic/Governance/MeetingElectionVoters.cs | 18 +- Logic/Governance/MeetingElectionVotes.cs | 4 +- Logic/Governance/MeetingElections.cs | 6 +- Logic/Governance/Motion.cs | 59 +- Logic/Governance/MotionAmendment.cs | 47 +- Logic/Governance/MotionAmendments.cs | 8 +- Logic/Governance/Motions.cs | 6 +- Logic/Interfaces/TreeNode.cs | 2 - Logic/Media/MediaCategories.cs | 12 +- Logic/Media/MediaCategory.cs | 8 +- Logic/Media/MediaEntries.cs | 31 +- Logic/Media/MediaEntry.cs | 21 +- Logic/Media/Reporter.cs | 67 +- Logic/Media/Reporters.cs | 14 +- Logic/Security/Accesses.cs | 26 +- Logic/Security/ActivityEnum.cs | 13 +- Logic/Security/Authentication.cs | 155 +- Logic/Security/Authority.cs | 86 +- Logic/Security/Authorization.cs | 336 +++-- Logic/Security/BCrypt.cs | 806 +++++----- Logic/Security/InternalLoginTicket.cs | 3 +- Logic/Security/MD5.cs | 6 +- Logic/Security/PermissionSet.cs | 173 +-- Logic/Security/PgpKey.cs | 11 +- Logic/Security/SHA1.cs | 6 +- Logic/Special/DummyBitcoin.cs | 16 +- Logic/Special/Mail/MailServerDatabase.cs | 82 +- Logic/Special/Sweden/SupportCase.cs | 22 +- Logic/Special/Sweden/SupportCaseDelta.cs | 21 +- Logic/Special/Sweden/SupportDatabase.cs | 120 +- Logic/Special/Sweden/SupportEmail.cs | 6 +- Logic/Special/Sweden/SwedishForumDatabase.cs | 1325 ++++++++--------- .../Sweden/SwedishForumHandleProvider.cs | 16 +- Logic/Structure/Cities.cs | 18 +- Logic/Structure/City.cs | 28 +- Logic/Structure/Countries.cs | 8 +- Logic/Structure/Country.cs | 33 +- Logic/Structure/Geographies.cs | 101 +- Logic/Structure/Geography.cs | 86 +- Logic/Structure/GeographyBar.cs | 4 +- Logic/Structure/GeographyStatistics.cs | 44 +- .../Structure/GeographyStatisticsOverTime.cs | 12 +- Logic/Structure/GeographyWithPeople.cs | 13 +- Logic/Structure/Organization.cs | 835 +++++------ Logic/Structure/OrganizationParameters.cs | 73 +- Logic/Structure/Organizations.cs | 87 +- Logic/Structure/PostalCode.cs | 27 +- Logic/Structure/PostalCodes.cs | 10 +- Logic/Structure/UptakeGeography.cs | 53 +- Logic/Support/ActivistEvents.cs | 11 +- Logic/Support/CheckDigit.cs | 225 ++- Logic/Support/DatabaseMaintenance.cs | 31 +- Logic/Support/Document.cs | 135 +- Logic/Support/Documents.cs | 28 +- Logic/Support/ExtensionMethods.cs | 26 +- Logic/Support/Formatting.cs | 81 +- Logic/Support/IXmlPayload.cs | 2 +- Logic/Support/Imagery.cs | 31 +- .../CashAdvanceRequestedLogEntry.cs | 29 +- .../LogEntries/ExpenseClaimFiledLogEntry.cs | 29 +- .../Support/LogEntries/FinancialActionBase.cs | 9 +- .../InboundInvoiceCreatedLogEntry.cs | 31 +- Logic/Support/LogEntries/LogEntryBase.cs | 16 +- .../LogEntries/PayoutCreatedLogEntry.cs | 22 +- .../LogEntries/SalaryCreatedLogEntry.cs | 27 +- Logic/Support/LogicServices.cs | 20 +- Logic/Support/ObjectOptionalData.cs | 94 +- Logic/Support/Optimizations.cs | 8 +- Logic/Support/PWEvents.cs | 22 +- Logic/Support/PWLog.cs | 148 +- Logic/Support/Persistence.cs | 4 +- Logic/Support/PilotInstallationIds.cs | 24 +- Logic/Support/PluralBase.cs | 61 +- Logic/Support/QuotedPrintable.cs | 53 +- Logic/Support/SerializableDictionary.cs | 31 +- Logic/Support/SingularFactory.cs | 79 +- Logic/Support/SwarmopsLog.cs | 4 +- Logic/Support/SwarmopsLogEntry.cs | 26 +- Logic/Support/TemporaryIdentity.cs | 26 +- Logic/Support/UrlTranslations.cs | 11 +- Logic/Swarm/Activists.cs | 19 +- Logic/Swarm/AuditedPerson.cs | 180 +-- Logic/Swarm/ChurnData.cs | 40 +- Logic/Swarm/ChurnDataPoint.cs | 4 +- Logic/Swarm/DashboardTodo.cs | 2 +- Logic/Swarm/DashboardTodos.cs | 70 +- Logic/Swarm/ExternalActivities.cs | 37 +- Logic/Swarm/ExternalActivity.cs | 38 +- Logic/Swarm/ExternalIdentity.cs | 100 +- Logic/Swarm/Interfaces.cs | 2 +- Logic/Swarm/Membership.cs | 128 +- Logic/Swarm/MembershipEvent.cs | 4 +- Logic/Swarm/MembershipEvents.cs | 38 +- Logic/Swarm/Memberships.cs | 57 +- Logic/Swarm/OfficerChain.cs | 22 +- Logic/Swarm/Parley.cs | 360 +++-- Logic/Swarm/ParleyAttendee.cs | 84 +- Logic/Swarm/ParleyAttendees.cs | 6 +- Logic/Swarm/ParleyOption.cs | 38 +- Logic/Swarm/ParleyOptions.cs | 17 +- Logic/Swarm/Parleys.cs | 62 +- Logic/Swarm/PaymentCode.cs | 20 +- Logic/Swarm/People.cs | 118 +- Logic/Swarm/Person.cs | 1174 ++++++++------- Logic/Swarm/PersonRole.cs | 13 +- Logic/Swarm/RoleLookup.cs | 13 +- Logic/Swarm/Roles.cs | 78 +- Logic/Swarm/Volunteer.cs | 48 +- Logic/Swarm/VolunteerRole.cs | 8 +- Logic/Swarm/VolunteerRoles.cs | 4 +- Logic/Swarm/Volunteers.cs | 20 +- Utility/BotCode/ActivityMailer.cs | 9 +- Utility/BotCode/BallotComposer.cs | 105 +- Utility/BotCode/BlogTop50Scraper.cs | 2 +- Utility/BotCode/BlogWatcher.cs | 25 +- Utility/BotCode/BotLog.cs | 6 +- Utility/BotCode/EventProcessor.cs | 29 +- Utility/BotCode/HeartBeater.cs | 79 +- Utility/BotCode/InternalPollMaintenance.cs | 148 +- Utility/BotCode/InternalPollRandomizer.cs | 5 +- Utility/BotCode/MailProcessor.cs | 392 ++--- Utility/BotCode/MailResolver.cs | 39 +- Utility/BotCode/Mappery.cs | 15 +- Utility/BotCode/MediaWatcher.cs | 20 +- Utility/BotCode/NewsletterChecker.cs | 30 +- Utility/BotCode/PressReleaseChecker.cs | 34 +- Utility/BotCode/RosterHousekeeping.cs | 65 +- Utility/BotCode/SalaryProcessor.cs | 11 +- Utility/BotCode/SchulzeProcessor.cs | 90 +- Utility/BotCode/TurnaroundTracker.cs | 8 +- Utility/BotCode/UpdateStatsCache.cs | 13 +- .../Communications/CommsTransmitterMail.cs | 13 +- Utility/ExceptionMail.cs | 10 +- Utility/Financial/PaymentGroupMapper.cs | 5 +- Utility/Financial/PaypalImporter.cs | 85 +- Utility/Financial/PaysonImporter.cs | 89 +- Utility/Mail/MailTransmitter.cs | 124 +- Utility/Mail/Newsletter.cs | 18 +- Utility/Mail/NewsletterTransmitter.cs | 70 +- Utility/Mail/NewsletterTransmitter3.cs | 30 +- Utility/Mail/PressReleaseTransmitter.cs | 27 +- Utility/Migrations/PeopleOptionalData.cs | 9 +- Utility/Properties/AssemblyInfo.cs | 24 +- Utility/Server/ExchangeCode.cs | 4 +- Utility/Special/Sweden/SupportMailReview.cs | 5 +- .../Special/Sweden/SwedishForumMemberCheck.cs | 5 - Utility/Special/UrlTranslator.cs | 11 +- 458 files changed, 13969 insertions(+), 13709 deletions(-) diff --git a/Backend/CommsTransmitter.cs b/Backend/CommsTransmitter.cs index 835e1b97..ef4ada4b 100644 --- a/Backend/CommsTransmitter.cs +++ b/Backend/CommsTransmitter.cs @@ -1,12 +1,13 @@ using System; using Swarmops.Logic.Communications; using Swarmops.Logic.Communications.Transmission; +using Swarmops.Utility.Communications; namespace Swarmops.Backend { internal class CommsTransmitter { - static internal void Run() + internal static void Run() { OutboundComms comms = OutboundComms.GetOpen(); @@ -24,7 +25,7 @@ namespace Swarmops.Backend throw new NotImplementedException(); } - ICommsTransmitter transmitter = new Swarmops.Utility.Communications.CommsTransmitterMail(); + ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); @@ -48,4 +49,4 @@ namespace Swarmops.Backend } } } -} +} \ No newline at end of file diff --git a/Backend/Program.cs b/Backend/Program.cs index 52cf3f59..b3e51845 100644 --- a/Backend/Program.cs +++ b/Backend/Program.cs @@ -9,6 +9,7 @@ using Swarmops.Logic.Financial; using Swarmops.Logic.Support; using Swarmops.Utility; using Swarmops.Utility.BotCode; +using Swarmops.Utility.Communications; using Swarmops.Utility.Mail; namespace Swarmops.Backend @@ -16,14 +17,16 @@ namespace Swarmops.Backend internal class Program { 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[]{ - new UnixSignal (Signum.SIGINT), - new UnixSignal (Signum.SIGTERM), + UnixSignal[] killSignals = + { + new UnixSignal(Signum.SIGINT), + new UnixSignal(Signum.SIGTERM) }; BotLog.Write(0, "MainCycle", string.Empty); @@ -33,7 +36,8 @@ namespace Swarmops.Backend if (args.Length > 0) { if (args[0].ToLower() == "test") - {/* + { +/* BotLog.Write(0, "MainCycle", "Running self-tests"); HeartBeater.Instance.Beat(heartbeatFile); // Otherwise Heartbeater.Beat() will fail in various places @@ -77,7 +81,7 @@ namespace Swarmops.Backend throw new NotImplementedException(); } - ICommsTransmitter transmitter = new Swarmops.Utility.Communications.CommsTransmitterMail(); + ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); @@ -92,7 +96,7 @@ namespace Swarmops.Backend Console.Write("\r\nAll tests run. Waiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { - System.Threading.Thread.Sleep(50); + Thread.Sleep(50); } Console.WriteLine("done."); @@ -110,12 +114,12 @@ namespace Swarmops.Backend // ----------------------- INSERT ANY ONE-OFF ACTIONS HERE ------------------------- - + Console.Write("\r\nWaiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { - System.Threading.Thread.Sleep(50); + Thread.Sleep(50); } Console.WriteLine("done."); @@ -168,7 +172,7 @@ namespace Swarmops.Backend bool exitFlag = false; - while (!exitFlag) // exit is handled by signals handling at end of loop + while (!exitFlag) // exit is handled by signals handling at end of loop { BotLog.Write(0, "MainCycle", "Cycle Start"); @@ -182,7 +186,7 @@ namespace Swarmops.Backend { OnEveryMinute(); - if (cycleStartTime.Minute % 5 == 0) + if (cycleStartTime.Minute%5 == 0) { OnEveryFiveMinutes(); } @@ -232,8 +236,9 @@ namespace Swarmops.Backend if (signalIndex < 1000) { exitFlag = true; - Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum.ToString() + ", exiting"); - BotLog.Write(0, "MainCycle", "EXIT SIGNAL (" + killSignals[signalIndex].Signum.ToString() + "), terminating backend"); + Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting"); + BotLog.Write(0, "MainCycle", + "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend"); } } } @@ -249,7 +254,7 @@ namespace Swarmops.Backend }*/ BotLog.Write(0, "MainCycle", "...done"); - + /* while (!MailTransmitter.CanExit) { @@ -259,7 +264,7 @@ namespace Swarmops.Backend Thread.Sleep(2000); } - private static void OnEveryTenSeconds () + private static void OnEveryTenSeconds() { try { @@ -301,7 +306,6 @@ namespace Swarmops.Backend } BotLog.Write(0, "MainCycle", "Ten-second exit"); - } catch (Exception e) { @@ -309,7 +313,7 @@ namespace Swarmops.Backend } } - private static void OnEveryMinute () + private static void OnEveryMinute() { try { @@ -323,7 +327,7 @@ namespace Swarmops.Backend } - private static void OnEveryFiveMinutes () + private static void OnEveryFiveMinutes() { try { @@ -374,7 +378,6 @@ namespace Swarmops.Backend // Added during election rush 2010: clean up support database every five minutes instead of once a day // SMS notifications for bounces are turned off, so people don't get SMS notifications in the middle of the night - } catch (Exception e) { @@ -428,7 +431,7 @@ namespace Swarmops.Backend } - private static void OnEveryHour () + private static void OnEveryHour() { DateTime startTime = DateTime.Now; try @@ -456,7 +459,7 @@ namespace Swarmops.Backend { TraceAndReport(e); } - + try { /*TestTrace("Running PaymentGroupMapper.Run()..."); @@ -509,7 +512,7 @@ namespace Swarmops.Backend } } - private static void OnMidnight () + private static void OnMidnight() { try { @@ -604,7 +607,7 @@ namespace Swarmops.Backend } } - private static void OnNoon () + private static void OnNoon() { BotLog.Write(0, "MainCycle", "Noon entry"); @@ -638,7 +641,6 @@ namespace Swarmops.Backend SupportDatabase.NotifyBouncingEmails(); TestTrace(" done.\r\n");*/ } - } catch (Exception e) { @@ -671,7 +673,7 @@ namespace Swarmops.Backend BotLog.Write(0, "MainCycle", "Noon exit"); } - private static void OnTuesdayMorning () + private static void OnTuesdayMorning() { try { @@ -689,22 +691,19 @@ namespace Swarmops.Backend } } - private static void TraceAndReport (Exception e) + private static void TraceAndReport(Exception e) { 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); } } - - - private static bool testMode; } } \ No newline at end of file diff --git a/Backend/Properties/AssemblyInfo.cs b/Backend/Properties/AssemblyInfo.cs index 7dd20906..4b0d447e 100644 --- a/Backend/Properties/AssemblyInfo.cs +++ b/Backend/Properties/AssemblyInfo.cs @@ -6,23 +6,23 @@ using System.Runtime.InteropServices; // associated with an assembly. [assembly: AssemblyTitle("Swarmops Backend")] -[assembly: AssemblyDescription ("")] -[assembly: AssemblyConfiguration ("")] -[assembly: AssemblyCompany ("Disorganized")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Disorganized")] [assembly: AssemblyProduct("Swarmops")] [assembly: AssemblyCopyright("In Public Domain")] -[assembly: AssemblyTrademark ("")] -[assembly: AssemblyCulture ("")] +[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 5b35e4e0..8fc48a31 100644 --- a/Basic/Config.cs +++ b/Basic/Config.cs @@ -5,7 +5,7 @@ namespace Swarmops.Basic { public class Config { - static public int SmtpPort + public static int SmtpPort { get { @@ -20,7 +20,7 @@ namespace Swarmops.Basic } } - static public string SmtpHost + public static string SmtpHost { get { @@ -35,4 +35,4 @@ namespace Swarmops.Basic } } } -} +} \ No newline at end of file diff --git a/Basic/Diagnostics/Logging.cs b/Basic/Diagnostics/Logging.cs index 6953ec64..d7b7cccc 100644 --- a/Basic/Diagnostics/Logging.cs +++ b/Basic/Diagnostics/Logging.cs @@ -3,41 +3,41 @@ using System.Diagnostics; namespace Swarmops.Basic.Diagnostics { - public class Logging - { - static public void LogError(LogSource source, string message) - { - EventLog eventLog = new EventLog(); - eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Error); - } + public class Logging + { + public static void LogError(LogSource source, string message) + { + EventLog eventLog = new EventLog(); + eventLog.Source = source.ToString(); + eventLog.WriteEntry(message, EventLogEntryType.Error); + } - static public void LogException(LogSource source, Exception exception) - { - LogError(source, exception.ToString()); - } + public static void LogException(LogSource source, Exception exception) + { + LogError(source, exception.ToString()); + } - static public void LogWarning(LogSource source, string message) - { - EventLog eventLog = new EventLog(); - eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Warning); - } + public static void LogWarning(LogSource source, string message) + { + EventLog eventLog = new EventLog(); + eventLog.Source = source.ToString(); + eventLog.WriteEntry(message, EventLogEntryType.Warning); + } - static public void LogInformation(LogSource source, string message) - { - EventLog eventLog = new EventLog(); - eventLog.Source = source.ToString(); - eventLog.WriteEntry(message, EventLogEntryType.Information); - } - } + public static void LogInformation(LogSource source, string message) + { + EventLog eventLog = new EventLog(); + eventLog.Source = source.ToString(); + eventLog.WriteEntry(message, EventLogEntryType.Information); + } + } - public enum LogSource - { - Unknown = 0, - PirateDb, - PirateBot, - PirateWeb, - PirateLogic - } -} + public enum LogSource + { + Unknown = 0, + PirateDb, + PirateBot, + PirateWeb, + PirateLogic + } +} \ No newline at end of file diff --git a/Basic/Enums/AddressValidationResult.cs b/Basic/Enums/AddressValidationResult.cs index 39ab7036..bf1165f3 100644 --- a/Basic/Enums/AddressValidationResult.cs +++ b/Basic/Enums/AddressValidationResult.cs @@ -1,26 +1,30 @@ namespace Swarmops.Basic { - public enum AddressValidationResult - { - /// - /// Unknown or undefined result. - /// - Unknown = 0, - /// - /// Confirmed valid by remote server. - /// - Valid = 1, - /// - /// Confirmed invalid by remote server. - /// - AccountInvalid = 2, - /// - /// Remote server does not respond or exist. - /// - ServerInvalid = 3, - /// - /// Email address syntax is invalid. - /// - BadSyntax = 4 - } + public enum AddressValidationResult + { + /// + /// Unknown or undefined result. + /// + Unknown = 0, + + /// + /// Confirmed valid by remote server. + /// + Valid = 1, + + /// + /// Confirmed invalid by remote server. + /// + AccountInvalid = 2, + + /// + /// Remote server does not respond or exist. + /// + ServerInvalid = 3, + + /// + /// Email address syntax is invalid. + /// + BadSyntax = 4 + } } \ No newline at end of file diff --git a/Basic/Enums/AutoMailType.cs b/Basic/Enums/AutoMailType.cs index e8cbad1a..09c65acd 100644 --- a/Basic/Enums/AutoMailType.cs +++ b/Basic/Enums/AutoMailType.cs @@ -1,9 +1,9 @@ namespace Swarmops.Basic.Enums { - public enum AutoMailType - { - Unknown = 0, - Welcome, + public enum AutoMailType + { + Unknown = 0, + Welcome, MemberMail, OfficerMail, Reminder, @@ -11,6 +11,6 @@ namespace Swarmops.Basic.Enums Expired, Newsletter, PressRelease, - WelcomeTimeLimitedContent=100 //Not implemented yet.. - } -} + WelcomeTimeLimitedContent = 100 //Not implemented yet.. + } +} \ No newline at end of file diff --git a/Basic/Enums/CommunicationType.cs b/Basic/Enums/CommunicationType.cs index 2a322634..d6afa7bb 100644 --- a/Basic/Enums/CommunicationType.cs +++ b/Basic/Enums/CommunicationType.cs @@ -3,13 +3,15 @@ namespace Swarmops.Basic.Enums public enum CommunicationType { Unknown = 0, + /// - /// Mail to the Press Office for an org + /// Mail to the Press Office for an org /// PressMail, + /// - /// General information inquiry + /// General information inquiry /// InformationMail } -} +} \ No newline at end of file diff --git a/Basic/Enums/DocumentType.cs b/Basic/Enums/DocumentType.cs index 4bf8c85c..2c65c3ab 100644 --- a/Basic/Enums/DocumentType.cs +++ b/Basic/Enums/DocumentType.cs @@ -3,37 +3,45 @@ namespace Swarmops.Basic.Enums public enum DocumentType { Unknown = 0, + /// - /// A photo that can be used to generate on-the-fly stuff, or for press images. + /// A photo that can be used to generate on-the-fly stuff, or for press images. /// PersonPhoto, + /// - /// A receipt for an expense. Filed by the expenser. + /// A receipt for an expense. Filed by the expenser. /// ExpenseClaim, + /// - /// A document supporting a transaction where assets decrease (invoice, etc). + /// A document supporting a transaction where assets decrease (invoice, etc). /// FinancialTransaction, + /// - /// A temporary identity, used while the basis of the document is still being created. + /// A temporary identity, used while the basis of the document is still being created. /// Temporary, + /// - /// An inbound invoice, going into accounts payable. + /// An inbound invoice, going into accounts payable. /// InboundInvoice, + /// - /// Something physical received in the mail + /// Something physical received in the mail /// PaperLetter, + /// - /// A document (contract or else) that creates or modifies the payroll + /// A document (contract or else) that creates or modifies the payroll /// PayrollItem, + /// - /// Photo documenting an external activity + /// Photo documenting an external activity /// ExternalActivityPhoto } -} +} \ No newline at end of file diff --git a/Basic/Enums/ExternalActivityType.cs b/Basic/Enums/ExternalActivityType.cs index d4541973..9f36a950 100644 --- a/Basic/Enums/ExternalActivityType.cs +++ b/Basic/Enums/ExternalActivityType.cs @@ -12,5 +12,4 @@ namespace Swarmops.Basic.Enums PressCoverage, Other } -} - +} \ No newline at end of file diff --git a/Basic/Enums/ExternalIdentityType.cs b/Basic/Enums/ExternalIdentityType.cs index d2e6efae..94aad90d 100644 --- a/Basic/Enums/ExternalIdentityType.cs +++ b/Basic/Enums/ExternalIdentityType.cs @@ -3,18 +3,18 @@ namespace Swarmops.Basic.Enums public enum ExternalIdentityType { /// - /// Unknown + /// Unknown /// - Unknown=0, - /// - /// JID on the Pirate Party XMPPServer - /// - PPXMPPAccount=1, - /// - /// JID on other XMPP - /// - ExternalXMPPAccount=2 - } + Unknown = 0, - -} + /// + /// JID on the Pirate Party XMPPServer + /// + PPXMPPAccount = 1, + + /// + /// JID on other XMPP + /// + ExternalXMPPAccount = 2 + } +} \ No newline at end of file diff --git a/Basic/Enums/FinancialAccountType.cs b/Basic/Enums/FinancialAccountType.cs index ed35c211..c787ef25 100644 --- a/Basic/Enums/FinancialAccountType.cs +++ b/Basic/Enums/FinancialAccountType.cs @@ -3,35 +3,42 @@ namespace Swarmops.Basic.Enums public enum FinancialAccountType { /// - /// Unknown account type. + /// Unknown account type. /// Unknown = 0, + /// - /// An asset, such as a bank account. Balance account. + /// An asset, such as a bank account. Balance account. /// Asset = 1, + /// - /// A debt, such as unprocessed activist expenses. Balance account. + /// A debt, such as unprocessed activist expenses. Balance account. /// Debt = 2, + /// - /// An income, any income. Result account. Received money is negative (sign reversed account). + /// An income, any income. Result account. Received money is negative (sign reversed account). /// Income = 3, + /// - /// A cost, any cost. Result account. Spent money is positive (sign reversed account). + /// A cost, any cost. Result account. Spent money is positive (sign reversed account). /// Cost = 4, + /// - /// Assets and debts - accounts that keep accumulating over years. + /// Assets and debts - accounts that keep accumulating over years. /// Balance = 5, + /// - /// Incomes and costs - accounts that are zeroed at year end. Sign reversed. + /// Incomes and costs - accounts that are zeroed at year end. Sign reversed. /// Result = 6, + /// - /// Meta-type which includes all accounts and group labels where applicable + /// Meta-type which includes all accounts and group labels where applicable /// All = 7 } diff --git a/Basic/Enums/FinancialDependencyType.cs b/Basic/Enums/FinancialDependencyType.cs index 02be686b..52d15556 100644 --- a/Basic/Enums/FinancialDependencyType.cs +++ b/Basic/Enums/FinancialDependencyType.cs @@ -3,47 +3,57 @@ namespace Swarmops.Basic.Enums public enum FinancialDependencyType { /// - /// Unknown dependency + /// Unknown dependency /// Unknown = 0, + /// - /// An expense claim, filed by an activist or officer + /// An expense claim, filed by an activist or officer /// ExpenseClaim, + /// - /// An invoice, received in the mail + /// An invoice, received in the mail /// InboundInvoice, + /// - /// Money leaving the organization, documented after processes + /// Money leaving the organization, documented after processes /// Payout, + /// - /// Salary paid to somebody employed or otherwise monthly compensated + /// Salary paid to somebody employed or otherwise monthly compensated /// Salary, + /// - /// An outbound invoice, requesting money from another organization + /// An outbound invoice, requesting money from another organization /// OutboundInvoice, + /// - /// A group of inbound payments + /// A group of inbound payments /// PaymentGroup, + /// - /// A dependency on (another) financial transaction - used for chaining across fiscal years + /// A dependency on (another) financial transaction - used for chaining across fiscal years /// FinancialTransaction, + /// - /// A conference or similar event (called 'parley' in lingo) + /// A conference or similar event (called 'parley' in lingo) /// Parley, + /// - /// A cash advance (prior payment, rather than doing an expense claim post purchase) + /// A cash advance (prior payment, rather than doing an expense claim post purchase) /// CashAdvance, + /// - /// A payback for a previous cash advance + /// A payback for a previous cash advance /// CashAdvancePayback } diff --git a/Basic/Enums/FinancialValidationType.cs b/Basic/Enums/FinancialValidationType.cs index 6319107b..86ab0d38 100644 --- a/Basic/Enums/FinancialValidationType.cs +++ b/Basic/Enums/FinancialValidationType.cs @@ -3,27 +3,32 @@ namespace Swarmops.Basic.Enums public enum FinancialValidationType { /// - /// Unknown type. + /// Unknown type. /// Unknown = 0, + /// - /// An attestation of an expenditure from a budget. + /// An attestation of an expenditure from a budget. /// Attestation, + /// - /// Removal of attested status. + /// Removal of attested status. /// Deattestation, + /// - /// Validation of expenditure documents. + /// Validation of expenditure documents. /// Validation, + /// - /// Devalidation - removal of validated status. + /// Devalidation - removal of validated status. /// Devalidation, + /// - /// Kill: close this financial doc as not valid. + /// Kill: close this financial doc as not valid. /// Kill } diff --git a/Basic/Enums/GeographyLevel.cs b/Basic/Enums/GeographyLevel.cs index 53502ff7..91bda839 100644 --- a/Basic/Enums/GeographyLevel.cs +++ b/Basic/Enums/GeographyLevel.cs @@ -3,27 +3,32 @@ namespace Swarmops.Basic.Enums public enum GeographyLevel { /// - /// Unknown level + /// Unknown level /// Unknown = 0, + /// - /// Municipality or city level + /// Municipality or city level /// Municipality = 1, + /// - /// Electoral circuit - usually 5-15 cities + /// Electoral circuit - usually 5-15 cities /// ElectoralCircuit = 2, + /// - /// County - usually same as electoral circuit + /// County - usually same as electoral circuit /// County = 3, + /// - /// District - 4-7 districts per state + /// District - 4-7 districts per state /// District = 4, + /// - /// State - not necessary for small countries + /// State - not necessary for small countries /// State = 5 } diff --git a/Basic/Enums/InvalidMembershipType.cs b/Basic/Enums/InvalidMembershipType.cs index c36fc033..b967ccaf 100644 --- a/Basic/Enums/InvalidMembershipType.cs +++ b/Basic/Enums/InvalidMembershipType.cs @@ -3,15 +3,17 @@ namespace Swarmops.Basic.Enums public enum InvalidMembershipType { /// - /// This membership was closed normally. + /// This membership was closed normally. /// Valid = 0, + /// - /// This membership was closed because it was a duplicate. + /// This membership was closed because it was a duplicate. /// DuplicateMember = 1, + /// - /// This membership was closed because the personae were bogus (like "Mickey Mouse"). + /// This membership was closed because the personae were bogus (like "Mickey Mouse"). /// PersonDoesNotExist = 2 } diff --git a/Basic/Enums/MailAuthorType.cs b/Basic/Enums/MailAuthorType.cs index 3a0989ed..c17cdb30 100644 --- a/Basic/Enums/MailAuthorType.cs +++ b/Basic/Enums/MailAuthorType.cs @@ -16,44 +16,43 @@ namespace Swarmops.Basic.Enums public class FunctionalMail { + public static Dictionary Address = initList(); + + 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")); + return retval; + } + public class AddressItem { - public AddressItem (string email, string name) + private readonly string email; + private readonly string name; + + public AddressItem(string email, string name) { this.email = email; this.name = name; } - private string email; - private string name; + public string Email { - get - { - return email; - } + get { return this.email; } } + public string Name { - get - { - return name; - } + get { return this.name; } } } - - static public Dictionary Address = initList(); - 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")); - return retval; - } - - } } \ No newline at end of file diff --git a/Basic/Enums/MembershipPaymentStatus.cs b/Basic/Enums/MembershipPaymentStatus.cs index 9092f0cb..9aa44386 100644 --- a/Basic/Enums/MembershipPaymentStatus.cs +++ b/Basic/Enums/MembershipPaymentStatus.cs @@ -1,41 +1,46 @@ namespace Swarmops.Basic.Enums { /// - /// For handling of membership fee payment - /// Also used for marking of accepted memberships for PPFI + /// For handling of membership fee payment + /// Also used for marking of accepted memberships for PPFI /// public enum MembershipPaymentStatus { /// - /// Undefined + /// Undefined /// Unknown = 0, + /// - /// Newly registered + /// Newly registered /// NewlyRegistered = 1, + /// - /// Membership accepted, used as bit flag + /// Membership accepted, used as bit flag /// MembershipAccepted = 2, + /// - /// Due for payment, to be used if payments are + /// Due for payment, to be used if payments are /// DueForNewPayment = 3, + /// - /// Has been listed to receive notice of payment - /// to be used if the sending out of payments is a manual process - /// just to stop them being listed as Due for payment again + /// Has been listed to receive notice of payment + /// to be used if the sending out of payments is a manual process + /// just to stop them being listed as Due for payment again /// ListedForPayment = 4, + /// - /// Notice of payment have been sent + /// Notice of payment have been sent /// PaymentRequested = 5, + /// - /// Payment have been recieved + /// Payment have been recieved /// PaymentRecieved = 6 - } -} +} \ No newline at end of file diff --git a/Basic/Enums/ObjectOptionalDataType.cs b/Basic/Enums/ObjectOptionalDataType.cs index 91d9aa91..c50ab4d9 100644 --- a/Basic/Enums/ObjectOptionalDataType.cs +++ b/Basic/Enums/ObjectOptionalDataType.cs @@ -1,6 +1,5 @@ namespace Swarmops.Basic.Enums { - public enum ObjectType { Unknown = 0, @@ -14,227 +13,277 @@ namespace Swarmops.Basic.Enums public enum ObjectOptionalDataType { Unknown = 0, + /// - /// The personal number (or equivalent) of somebody. In SE, this is a ten digit number. + /// The personal number (or equivalent) of somebody. In SE, this is a ten digit number. /// PersonalNumber, + /// - /// If a particular person is invisible to all officers. + /// If a particular person is invisible to all officers. /// Anonymous, + /// - /// ? + /// ? /// CustomEmail, + /// - /// If somebody should never ever be mailed for any reason. + /// If somebody should never ever be mailed for any reason. /// NeverMail, + /// - /// The account id of the (currently just Swedish) forum. + /// The account id of the (currently just Swedish) forum. /// ForumAccountId, + /// - /// Name of a bank. + /// Name of a bank. /// BankName, + /// - /// Clearing number of a bank, usually four digits. + /// Clearing number of a bank, usually four digits. /// BankClearing, + /// - /// Account number of a bank. Does NOT include clearing number. + /// Account number of a bank. Does NOT include clearing number. /// BankAccount, + /// - /// The party email account of a person. + /// The party email account of a person. /// PartyEmail, + /// - /// Whether this entity is unreachable by mail. + /// Whether this entity is unreachable by mail. /// MailUnreachable, + /// - /// Whether this entity wants mail in text-only format. + /// Whether this entity wants mail in text-only format. /// LimitMailToText, + /// - /// Whether this entity wants mail in ISO-8859-1 (as opposed to UTF-8). + /// Whether this entity wants mail in ISO-8859-1 (as opposed to UTF-8). /// LimitMailToLatin1, + /// - /// ? + /// ? /// ResetPasswordTicket, + /// - /// Not sure how this is used + /// Not sure how this is used /// EMailIsInvalid, + /// - /// The name of the photographer, if the person has a photo (Document type) + /// The name of the photographer, if the person has a photo (Document type) /// PortraitPhotographer, + /// - /// A flag that this Person should be manually inspected + /// A flag that this Person should be manually inspected /// AccountDetailsSuspect, // ReSharper disable InconsistentNaming /// - /// T-shirt size as indicated by Person + /// T-shirt size as indicated by Person /// TShirtSize, // ReSharper restore InconsistentNaming /// - /// Name of a blog in cleartext + /// Name of a blog in cleartext /// BlogName, + /// - /// Url of a blog, including preceding http:// + /// Url of a blog, including preceding http:// /// BlogUrl, + /// - /// Public key in PGP Armor format. + /// Public key in PGP Armor format. /// CryptoPublicKey, + /// - /// Secret AND public keypair in PGP Armor format. + /// Secret AND public keypair in PGP Armor format. /// CryptoSecretKey, + /// - /// Revocation certificate for a public key. Do not use until time for revocation. + /// Revocation certificate for a public key. Do not use until time for revocation. /// CryptoRevocation, + /// - /// Fingerprint of a crypto key, in format "ABCD 0123 4567..." + /// Fingerprint of a crypto key, in format "ABCD 0123 4567..." /// CryptoFingerprint, + /// - /// Geography of an account + /// Geography of an account /// GeographyId, + /// - /// Transaction tag for a donation to go to a particular account + /// Transaction tag for a donation to go to a particular account /// BankTransactionTag, + /// - /// The account name of the (currently just Swedish) forum. + /// The account name of the (currently just Swedish) forum. /// ForumAccountName, + /// - /// The preferred culture (for translations etc) eg. sv-SE + /// The preferred culture (for translations etc) eg. sv-SE /// PreferredCulture, + /// - /// List of functional mail addresses for organization + /// List of functional mail addresses for organization /// OrgFunctionalMail, + /// - /// A temporary place to store password hash until membership confirmed (for PPFI) + /// A temporary place to store password hash until membership confirmed (for PPFI) /// PersonTempPasswordStore, + /// - /// Flag to indicate if officer notifications are allowed to contain member names (for PPFI) + /// Flag to indicate if officer notifications are allowed to contain member names (for PPFI) /// OrgShowNamesInNotifications, + /// - /// Flag to indicate if organisation is using PaymentStatus (for PPFI) + /// Flag to indicate if organisation is using PaymentStatus (for PPFI) /// OrgUsePaymentStatus, + /// - /// Organizations: If the org has PW do bookkeeping + /// Organizations: If the org has PW do bookkeeping /// OrgEconomyEnabled, + /// - /// The highest year for which fiscal books are closed, or 0 for never + /// The highest year for which fiscal books are closed, or 0 for never /// OrgBooksClosedForYear, + /// - /// The last year for which fiscal books have been audited, or 0 for never + /// The last year for which fiscal books have been audited, or 0 for never /// OrgBooksAuditedForYear, + /// - /// Bank account for an organization's tax payments + /// Bank account for an organization's tax payments /// OrgTaxAccount, + /// - /// OCR sequence on tax payments (to the tax account) for an organization + /// OCR sequence on tax payments (to the tax account) for an organization /// OrgTaxOcr, + /// - /// True if the organization declares inbound/outbound Value Added Tax + /// True if the organization declares inbound/outbound Value Added Tax /// OrgValueAddedTaxEnabled, OrgFinancialMailName, OrgFinancialMailAddress, + /// - /// If invoice is credited, this is the credit invoice id (normative) + /// If invoice is credited, this is the credit invoice id (normative) /// OutboundInvoiceCreditedWithInvoice, + /// - /// This is a credit invoice, crediting this other invoice (informative) + /// This is a credit invoice, crediting this other invoice (informative) /// OutboundInvoiceCreditsInvoice, + /// - /// If invoice is to a person id, this is the person id + /// If invoice is to a person id, this is the person id /// OutboundInvoiceToPersonId, + /// - /// If "1", this financial account may be charged for conferences + /// If "1", this financial account may be charged for conferences /// FinancialAccountEnabledForConferences, + /// - /// If "1", this financial account may be charged with expenses + /// If "1", this financial account may be charged with expenses /// FinancialAccountEnabledForExpensing, + /// - /// If "1", this financial account may be charged with invoices + /// If "1", this financial account may be charged with invoices /// FinancialAccountEnabledForInvoicing, + /// - /// Organization's operations currency, stored as currency code + /// Organization's operations currency, stored as currency code /// OrgCurrency, + /// - /// First bookkeeping year of org in Swarmops (can set inbound balances for this year only) + /// First bookkeeping year of org in Swarmops (can set inbound balances for this year only) /// OrgFirstFiscalYear, + /// - /// Temporary mechanism for the Swarmops Red release: a coarse access list (read/write access) + /// Temporary mechanism for the Swarmops Red release: a coarse access list (read/write access) /// OrgTemporaryAccessListWrite, + /// - /// Temporary mechanism for the Swarmops Red release: a coarse access list (read-only access) + /// Temporary mechanism for the Swarmops Red release: a coarse access list (read-only access) /// OrgTemporaryAccessListRead, + /// - /// Free-text description of an inbound invoice (what's it for?) + /// Free-text description of an inbound invoice (what's it for?) /// InboundInvoiceDescription, + /// - /// Geopos - longitude. Float in degrees. Positive is north. + /// Geopos - longitude. Float in degrees. Positive is north. /// Longitude, + /// - /// Geopos - latitude. Float in degrees. Positive is east. + /// Geopos - latitude. Float in degrees. Positive is east. /// Latitude, + /// - /// A National ID number, if any. Like US SSN. + /// A National ID number, if any. Like US SSN. /// NationalIdNumber, + /// - /// What are ordinary people called in this org? + /// What are ordinary people called in this org? /// OrgRegularLabel, + /// - /// What are activists called in this org? + /// What are activists called in this org? /// OrgActivistLabel, + /// - /// For a person, the BitId address they use to login + /// For a person, the BitId address they use to login /// BitIdLoginAddress } - -} - +} \ No newline at end of file diff --git a/Basic/Enums/OrganizationFinancialAccountType.cs b/Basic/Enums/OrganizationFinancialAccountType.cs index 260edce1..75c14af9 100644 --- a/Basic/Enums/OrganizationFinancialAccountType.cs +++ b/Basic/Enums/OrganizationFinancialAccountType.cs @@ -3,116 +3,143 @@ public enum OrganizationFinancialAccountType { /// - /// Undefined + /// Undefined /// Unknown, + /// - /// Main bank transaction account - not a savings account or similar + /// Main bank transaction account - not a savings account or similar /// AssetsBankAccountMain, + /// - /// The account where outbound invoices are kept + /// The account where outbound invoices are kept /// AssetsOutboundInvoices, + /// - /// If org has a PayPal account, this is where is goes + /// If org has a PayPal account, this is where is goes /// AssetsPaypal, + /// - /// Assets held in bitcoin (if any), immediately accessible. + /// Assets held in bitcoin (if any), immediately accessible. /// AssetsBitcoinHot, + /// - /// Assets held in bitcoin cold storage (if any). + /// Assets held in bitcoin cold storage (if any). /// AssetsBitcoinCold, + /// - /// Any outstanding cash advances that have been paid out and not cleared against receipts or paid back + /// Any outstanding cash advances that have been paid out and not cleared against receipts or paid back /// AssetsOutstandingCashAdvances, + /// - /// Value Added Tax (inbound) that hasn't been declared yet and put on overall tax balance + /// Value Added Tax (inbound) that hasn't been declared yet and put on overall tax balance /// AssetsVatInbound, + /// - /// If virtual banking is enabled, this is where the virtual assets go + /// If virtual banking is enabled, this is where the virtual assets go /// AssetsVirtualBanking, + /// - /// Any expense claims on the organization that have not been paid back + /// Any expense claims on the organization that have not been paid back /// DebtsExpenseClaims, + /// - /// Invoices sent to the organization until paid against bank account + /// Invoices sent to the organization until paid against bank account /// DebtsInboundInvoices, + /// - /// Salaries due for payout until cleared against bank account + /// Salaries due for payout until cleared against bank account /// DebtsSalary, + /// - /// Taxes due for payout until cleared against bank account + /// Taxes due for payout until cleared against bank account /// DebtsTax, + /// - /// Equity - the difference between debt and assets + /// Equity - the difference between debt and assets /// DebtsEquity, + /// - /// Undeclared Value Added Tax (outbound) before putting it on tax balance + /// Undeclared Value Added Tax (outbound) before putting it on tax balance /// DebtsVatOutbound, + /// - /// If virtual banking is enabled, this is the central debt to local assets + /// If virtual banking is enabled, this is the central debt to local assets /// DebtsEarmarkedVirtualBanking, + /// - /// Earmarked assets in other ways + /// Earmarked assets in other ways /// DebtsEarmarkedOtherAssets, + /// - /// Other debts in general + /// Other debts in general /// DebtsOther, + /// - /// Income from sales - default outbound invoices to this acct + /// Income from sales - default outbound invoices to this acct /// IncomeSales, + /// - /// Income from donations - default autodonates here + /// Income from donations - default autodonates here /// IncomeDonations, + /// - /// Bank fees - default small minus posts on bank statements here + /// Bank fees - default small minus posts on bank statements here /// CostsBankFees, + /// - /// Gains from currency fluctuation (typically bitcoin or altcoins). + /// Gains from currency fluctuation (typically bitcoin or altcoins). /// IncomeCurrencyFluctuations, + /// - /// IT and such - default SMS charges, etc, here + /// IT and such - default SMS charges, etc, here /// CostsInfrastructure, + /// - /// If virtual banking is enabled, this is a counterbalance account + /// If virtual banking is enabled, this is a counterbalance account /// CostsLocalDonationTransfers, + /// - /// No description + /// No description /// CostsAllocatedFunds, + /// - /// Losses from currency fluctuation (typically bitcoin or altcoins). + /// Losses from currency fluctuation (typically bitcoin or altcoins). /// CostsCurrencyFluctuations, + /// - /// Various bookkeeping errors + /// Various bookkeeping errors /// CostsMiscalculations, + /// - /// When closing books, this is the yearly result (balanced against DebtsEquity) + /// When closing books, this is the yearly result (balanced against DebtsEquity) /// CostsYearlyResult, // multi-account type }; -} +} \ No newline at end of file diff --git a/Basic/Enums/OutboundCommPriority.cs b/Basic/Enums/OutboundCommPriority.cs index 45d57f84..36f843a6 100644 --- a/Basic/Enums/OutboundCommPriority.cs +++ b/Basic/Enums/OutboundCommPriority.cs @@ -3,33 +3,40 @@ public enum OutboundCommPriority { Unknown = 0, + /// - /// Priority 1 of 7 (highest). + /// Priority 1 of 7 (highest). /// Highest = 32, + /// - /// Priority 2 of 7 (second highest). + /// Priority 2 of 7 (second highest). /// High = 64, + /// - /// Priority 3 of 7 (just above normal priority). + /// Priority 3 of 7 (just above normal priority). /// Elevated = 96, + /// - /// Priority 4 of 7 (normal and default). + /// Priority 4 of 7 (normal and default). /// Normal = 128, + /// - /// Priority 5 of 7 (just below normal priority). + /// Priority 5 of 7 (just below normal priority). /// Lowered = 160, + /// - /// Priority 6 of 7 (second lowest). + /// Priority 6 of 7 (second lowest). /// Low = 192, + /// - /// Priority 7 of 7 (lowest). + /// Priority 7 of 7 (lowest). /// Lowest = 224 } -} +} \ No newline at end of file diff --git a/Basic/Enums/PermissionEnum.cs b/Basic/Enums/PermissionEnum.cs index 1648e7a6..f233ed63 100644 --- a/Basic/Enums/PermissionEnum.cs +++ b/Basic/Enums/PermissionEnum.cs @@ -3,7 +3,7 @@ namespace Swarmops.Basic.Enums public enum Permission { /// - /// Undefined. + /// Undefined. /// Undefined = 0, CanSeeSelf, diff --git a/Basic/Enums/PersonOptionalDataKey.cs b/Basic/Enums/PersonOptionalDataKey.cs index 30adb12f..f2f8f549 100644 --- a/Basic/Enums/PersonOptionalDataKey.cs +++ b/Basic/Enums/PersonOptionalDataKey.cs @@ -25,6 +25,5 @@ namespace Swarmops.Basic.Enums CryptoSecret, CryptoRevocation, CryptoFingerprint - } } \ No newline at end of file diff --git a/Basic/Enums/RoleTypeClass.cs b/Basic/Enums/RoleTypeClass.cs index 3fb75335..59d96bf8 100644 --- a/Basic/Enums/RoleTypeClass.cs +++ b/Basic/Enums/RoleTypeClass.cs @@ -4,118 +4,142 @@ using System.Collections.Generic; namespace Swarmops.Basic.Enums { /// - /// RoleTypes. - /// Important that the number corresponds - /// to RoleTypeId in database since roles are stored referencing - /// id rather than name. - /// - /// Add new roles at the end, and create corresponding record in db. + /// RoleTypes. + /// Important that the number corresponds + /// to RoleTypeId in database since roles are stored referencing + /// id rather than name. + /// Add new roles at the end, and create corresponding record in db. /// public enum RoleType { /// - /// Undefined + /// Undefined /// Unknown = 0, + /// - /// The primary contact for a geographical node in an organization + /// The primary contact for a geographical node in an organization /// LocalLead = 1, + /// - /// The secondary contact for a geographical node in an organization + /// The secondary contact for a geographical node in an organization /// LocalDeputy = 2, + /// - /// OBSOLETE - DO NOT USE + /// OBSOLETE - DO NOT USE /// LocalActive = 3, + /// - /// Non-public role - full access to organization's node + /// Non-public role - full access to organization's node /// LocalAdmin = 4, + /// - /// Public role - PoC for org and can perform any task on the org in the system + /// Public role - PoC for org and can perform any task on the org in the system /// OrganizationChairman = 5, + /// - /// Treasurers in an org can approve and manage expenses + /// Treasurers in an org can approve and manage expenses /// OrganizationTreasurer = 6, + /// - /// Public role - for display / PoC purposes only + /// Public role - for display / PoC purposes only /// OrganizationBoardMember = 7, + /// - /// Public role - for display / PoC purposes only + /// Public role - for display / PoC purposes only /// OrganizationSecretary = 8, + /// - /// Non-public role for people who do administrative work + /// Non-public role for people who do administrative work /// OrganizationAdmin = 9, + /// - /// Non-public role - full access to entire PirateWeb + /// Non-public role - full access to entire PirateWeb /// SystemAdmin = 10, + /// - /// Non-public role - editor of the geography tree (at a certain geo and below) + /// Non-public role - editor of the geography tree (at a certain geo and below) /// SystemGeographyEditor = 11, + /// - /// Non-public role - a member/nonmember who has full access to the organization + /// Non-public role - a member/nonmember who has full access to the organization /// OrganizationAuditor = 12, + /// - /// A deputy board member of an org + /// A deputy board member of an org /// OrganizationBoardDeputy = 13, + /// - /// First vice chairman + /// First vice chairman /// OrganizationVice1 = 14, + /// - /// Second vice chairman + /// Second vice chairman /// OrganizationVice2 = 15, + /// - /// This Role is assigned to Memberservice administrators + /// This Role is assigned to Memberservice administrators /// OrganizationMemberService = 17, + /// - /// This Role is assigned to Memberservice administrators, extra permissions + /// This Role is assigned to Memberservice administrators, extra permissions /// OrganizationMemberServiceLead = 18, + /// - /// Role assigned to elected representatives, mostly for admin purposes. No intrinsic rights. + /// Role assigned to elected representatives, mostly for admin purposes. No intrinsic rights. /// OrganizationElectedRepresentative = 19, + /// - /// A role that everybody has, although it is not set in the database on every person. - /// Letters may be sent to people in this role, in which case they are private. No intrinsic rights. + /// A role that everybody has, although it is not set in the database on every person. + /// Letters may be sent to people in this role, in which case they are private. No intrinsic rights. /// PrivateIndividual = 20, + /// - /// A person who can upload paper documents, like letters/invoices, but not access members. + /// A person who can upload paper documents, like letters/invoices, but not access members. /// OrganizationClerk = 21, + /// - /// A person who can see and manage all of the economy, but not member registry. + /// A person who can see and manage all of the economy, but not member registry. /// OrganizationEconomyAssistant = 22, + /// - /// An elected meeting official, to be assigned temporarily during a meeting + /// An elected meeting official, to be assigned temporarily during a meeting /// OrganizationMeetingOfficial = 23, + /// - /// The board's secretary. Not the same as the org's secretary. + /// The board's secretary. Not the same as the org's secretary. /// OrganizationBoardSecretary = 24, + /// - /// Role for non officers helping with ballot distribution etc + /// Role for non officers helping with ballot distribution etc /// LocalElectionSupport = 25, + /// - /// Temporary - Jörgen added this; the whole enum is deprecated anyway; added for compatibility with v4 + /// Temporary - Jörgen added this; the whole enum is deprecated anyway; added for compatibility with v4 /// OrganizationMailSender } @@ -124,67 +148,77 @@ namespace Swarmops.Basic.Enums public enum RoleClass { /// - /// Undefined + /// Undefined /// Undefined = 0, + /// - /// System-wide privileges and responsibilities + /// System-wide privileges and responsibilities /// System, + /// - /// Roles for an entire organization + /// Roles for an entire organization /// Organization, + /// - /// Roles and responsibilities to a node in an organization + /// Roles and responsibilities to a node in an organization /// Local, + /// - /// Roles that are org-agnostic but are tied to a geo node + /// Roles that are org-agnostic but are tied to a geo node /// Geographic } public class RoleTypes { - static public readonly RoleType[] AllLocalRoleTypes = new RoleType[] - { RoleType.LocalLead, - RoleType.LocalDeputy, - RoleType.LocalActive, - RoleType.LocalAdmin, - RoleType.LocalElectionSupport }; - - static public readonly RoleType[] AllOrganizationalRoleTypes = new RoleType[] - { RoleType.OrganizationChairman, - RoleType.OrganizationVice1, - RoleType.OrganizationVice2, - RoleType.OrganizationTreasurer, - RoleType.OrganizationSecretary, - RoleType.OrganizationBoardMember, - RoleType.OrganizationBoardDeputy, - RoleType.OrganizationAdmin, - RoleType.OrganizationClerk, - RoleType.OrganizationAuditor, - RoleType.OrganizationMemberService, - RoleType.OrganizationMemberServiceLead, - RoleType.OrganizationElectedRepresentative, - RoleType.OrganizationEconomyAssistant, - RoleType.OrganizationMeetingOfficial, - RoleType.OrganizationBoardSecretary }; - - static public readonly RoleType[] AllSystemRoleTypes = new RoleType[] - { RoleType.SystemAdmin, - RoleType.SystemGeographyEditor }; - - static public readonly RoleType[] AllRoleTypes = CreateAllRoleTypes(); - - private static RoleType[] CreateAllRoleTypes () + public static readonly RoleType[] AllLocalRoleTypes = { - List retList=new List(); + RoleType.LocalLead, + RoleType.LocalDeputy, + RoleType.LocalActive, + RoleType.LocalAdmin, + RoleType.LocalElectionSupport + }; + + public static readonly RoleType[] AllOrganizationalRoleTypes = + { + RoleType.OrganizationChairman, + RoleType.OrganizationVice1, + RoleType.OrganizationVice2, + RoleType.OrganizationTreasurer, + RoleType.OrganizationSecretary, + RoleType.OrganizationBoardMember, + RoleType.OrganizationBoardDeputy, + RoleType.OrganizationAdmin, + RoleType.OrganizationClerk, + RoleType.OrganizationAuditor, + RoleType.OrganizationMemberService, + RoleType.OrganizationMemberServiceLead, + RoleType.OrganizationElectedRepresentative, + RoleType.OrganizationEconomyAssistant, + RoleType.OrganizationMeetingOfficial, + RoleType.OrganizationBoardSecretary + }; + + public static readonly RoleType[] AllSystemRoleTypes = + { + RoleType.SystemAdmin, + RoleType.SystemGeographyEditor + }; + + public static readonly RoleType[] AllRoleTypes = CreateAllRoleTypes(); + + 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))) + foreach (RoleType rt in Enum.GetValues(typeof (RoleType))) { if (!retList.Contains(rt)) retList.Add(rt); @@ -193,7 +227,7 @@ namespace Swarmops.Basic.Enums return retList.ToArray(); } - static public RoleClass ClassOfRole (RoleType r) + public static RoleClass ClassOfRole(RoleType r) { if (Array.IndexOf(AllLocalRoleTypes, r) > -1) return RoleClass.Local; diff --git a/Basic/Interfaces/IHandleProvider.cs b/Basic/Interfaces/IHandleProvider.cs index 465bbf97..02cad426 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); } } @@ -28,26 +28,24 @@ namespace Swarmops.Basic.Exceptions { public class HandleException : Exception { - public HandleException (string attemptedHandle, HandleErrorType errorType) + private readonly string attemptedHandle; + private readonly HandleErrorType errorType; + + public HandleException(string attemptedHandle, HandleErrorType errorType) { this.attemptedHandle = attemptedHandle; this.errorType = errorType; } + public HandleErrorType ErrorType + { + get { return this.errorType; } + } public override string ToString() { - return "HandleException: Handle '" + attemptedHandle + "' caused '" + errorType.ToString() + "'.\r\n" + + return "HandleException: Handle '" + this.attemptedHandle + "' caused '" + this.errorType + "'.\r\n" + base.ToString(); } - - - public HandleErrorType ErrorType - { - get { return errorType; } - } - - private readonly string attemptedHandle; - private readonly HandleErrorType errorType; } } \ No newline at end of file diff --git a/Basic/Interfaces/IHasIdentities.cs b/Basic/Interfaces/IHasIdentities.cs index 11cc8d04..21f6cfd5 100644 --- a/Basic/Interfaces/IHasIdentities.cs +++ b/Basic/Interfaces/IHasIdentities.cs @@ -4,4 +4,4 @@ namespace Swarmops.Basic.Interfaces { int[] Identities { get; } } -} +} \ No newline at end of file diff --git a/Basic/Properties/AssemblyInfo.cs b/Basic/Properties/AssemblyInfo.cs index 4b4c19b6..b0fe2384 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/Strings.cs b/Basic/Strings.cs index c7e72853..18df4b63 100644 --- a/Basic/Strings.cs +++ b/Basic/Strings.cs @@ -1,3 +1,5 @@ +using System.IO; + namespace Swarmops.Basic { public class Strings @@ -6,14 +8,11 @@ namespace Swarmops.Basic { get { - if (System.IO.Path.DirectorySeparatorChar == '/') + if (Path.DirectorySeparatorChar == '/') { return "PirateWeb"; } - else - { - return "PirateWeb-W"; - } + return "PirateWeb-W"; } } diff --git a/Basic/Types/BasicAddressValidationRun.cs b/Basic/Types/BasicAddressValidationRun.cs index 97c4be30..3915ea01 100644 --- a/Basic/Types/BasicAddressValidationRun.cs +++ b/Basic/Types/BasicAddressValidationRun.cs @@ -4,13 +4,13 @@ namespace Swarmops.Basic.Types { public class BasicAddressValidationRun : IHasIdentity { - public BasicAddressValidationRun (int validationRunId) + private readonly int validationRunId; + + public BasicAddressValidationRun(int validationRunId) { this.validationRunId = validationRunId; } - private readonly int validationRunId; - public int Identity { get { return this.validationRunId; } diff --git a/Basic/Types/BasicBallot.cs b/Basic/Types/BasicBallot.cs index bc3427f8..88e2fe14 100644 --- a/Basic/Types/BasicBallot.cs +++ b/Basic/Types/BasicBallot.cs @@ -2,21 +2,24 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicBallot: IHasIdentity + public class BasicBallot : IHasIdentity { - public BasicBallot (int ballotId, int electionId, int organizationId, int geographyId, string name, int count, string deliveryAddress) + public BasicBallot(int ballotId, int electionId, int organizationId, int geographyId, string name, int count, + string deliveryAddress) { - this.BallotId = ballotId; - this.ElectionId = electionId; - this.OrganizationId = organizationId; - this.GeographyId = geographyId; - this.Name = name; - this.Count = count; - this.DeliveryAddress = deliveryAddress; + BallotId = ballotId; + ElectionId = electionId; + OrganizationId = organizationId; + GeographyId = geographyId; + Name = name; + Count = count; + DeliveryAddress = deliveryAddress; } - public BasicBallot (BasicBallot original) - :this (original.BallotId, original.ElectionId, original.OrganizationId, original.GeographyId, original.Name, original.Count, original.DeliveryAddress) + public BasicBallot(BasicBallot original) + : this( + original.BallotId, original.ElectionId, original.OrganizationId, original.GeographyId, original.Name, + original.Count, original.DeliveryAddress) { // empty copy ctor } @@ -28,9 +31,10 @@ namespace Swarmops.Basic.Types public string Name { get; private set; } public int Count { get; protected set; } public string DeliveryAddress { get; protected set; } + public int Identity { - get { return this.BallotId; } + get { return BallotId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicChurnDataPoint.cs b/Basic/Types/BasicChurnDataPoint.cs index 4860d3d5..ae7c816d 100644 --- a/Basic/Types/BasicChurnDataPoint.cs +++ b/Basic/Types/BasicChurnDataPoint.cs @@ -6,12 +6,14 @@ namespace Swarmops.Basic.Enums public enum ChurnDataType { Unknown = 0, + /// - /// The member churned (dropped out, left). + /// The member churned (dropped out, left). /// Churn, + /// - /// The member remained in the organization (renewed). + /// The member remained in the organization (renewed). /// Retention } @@ -21,8 +23,14 @@ namespace Swarmops.Basic.Types { public class BasicChurnDataPoint { - public BasicChurnDataPoint (ChurnDataType dataType, DateTime decisionDateTime, DateTime expiryDate, - int personId, int organizationId) + public readonly ChurnDataType DataType; + public readonly DateTime DecisionDateTime; + public readonly DateTime ExpiryDate; + public readonly int OrganizationId; + public readonly int PersonId; + + public BasicChurnDataPoint(ChurnDataType dataType, DateTime decisionDateTime, DateTime expiryDate, + int personId, int organizationId) { this.DataType = dataType; this.DecisionDateTime = decisionDateTime; @@ -31,17 +39,11 @@ namespace Swarmops.Basic.Types this.OrganizationId = organizationId; } - public BasicChurnDataPoint (BasicChurnDataPoint original) : + public BasicChurnDataPoint(BasicChurnDataPoint original) : this( original.DataType, original.DecisionDateTime, original.ExpiryDate, original.PersonId, original.OrganizationId) { } - - public readonly ChurnDataType DataType; - public readonly DateTime DecisionDateTime; - public readonly DateTime ExpiryDate; - public readonly int OrganizationId; - public readonly int PersonId; } } \ No newline at end of file diff --git a/Basic/Types/BasicCity.cs b/Basic/Types/BasicCity.cs index bf7cf3b7..ccb1ed5f 100644 --- a/Basic/Types/BasicCity.cs +++ b/Basic/Types/BasicCity.cs @@ -6,20 +6,20 @@ 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) { - this.CityId = cityId; - this.Name = name; - this.CountryId = countryId; - this.GeographyId = geographyId; + CityId = cityId; + Name = name; + CountryId = countryId; + GeographyId = geographyId; } - public BasicCity (BasicCity original) + 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 @@ -30,12 +30,11 @@ namespace Swarmops.Basic.Types public int CountryId { get; protected set; } public int GeographyId { get; protected set; } - #region IHasIdentity Members public int Identity { - get { return this.CityId; } + get { return CityId; } } #endregion diff --git a/Basic/Types/BasicCommunicationTurnaround.cs b/Basic/Types/BasicCommunicationTurnaround.cs index 5b5da053..d42b751f 100644 --- a/Basic/Types/BasicCommunicationTurnaround.cs +++ b/Basic/Types/BasicCommunicationTurnaround.cs @@ -3,24 +3,29 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicCommunicationTurnaround: IHasIdentity + public class BasicCommunicationTurnaround : IHasIdentity { - public BasicCommunicationTurnaround(int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeOpened, DateTime dateTimeFirstResponse, int personIdFirstResponse, DateTime dateTimeClosed, int personIdClosed, bool open, bool responded) + public BasicCommunicationTurnaround(int organizationId, int communicationTypeId, int communicationId, + DateTime dateTimeOpened, DateTime dateTimeFirstResponse, int personIdFirstResponse, DateTime dateTimeClosed, + int personIdClosed, bool open, bool responded) { - this.OrganizationId = organizationId; - this.CommunicationTypeId = communicationTypeId; - this.CommunicationId = communicationId; - this.DateTimeOpened = dateTimeOpened; - this.DateTimeFirstResponse = dateTimeFirstResponse; - this.PersonIdFirstResponse = personIdFirstResponse; - this.DateTimeClosed = dateTimeClosed; - this.PersonIdClosed = personIdClosed; - this.Open = open; - this.Responded = responded; + OrganizationId = organizationId; + CommunicationTypeId = communicationTypeId; + CommunicationId = communicationId; + DateTimeOpened = dateTimeOpened; + DateTimeFirstResponse = dateTimeFirstResponse; + PersonIdFirstResponse = personIdFirstResponse; + DateTimeClosed = dateTimeClosed; + PersonIdClosed = personIdClosed; + Open = open; + Responded = responded; } - 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) + 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) { // empty copy ctor } @@ -39,7 +44,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.CommunicationId; } // ok, this isn't great, but wtf + get { return CommunicationId; } // ok, this isn't great, but wtf } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicCountry.cs b/Basic/Types/BasicCountry.cs index d1da2151..6c698c1e 100644 --- a/Basic/Types/BasicCountry.cs +++ b/Basic/Types/BasicCountry.cs @@ -6,28 +6,31 @@ 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) { - this.CountryId = countryId; - this.Name = name; - this.Code = code; + CountryId = countryId; + Name = name; + Code = code; } - public BasicCountry (int countryId, string name, string code, string defaultCulture, string currencyCode, int geographyId, int postalCodeLength) + public BasicCountry(int countryId, string name, string code, string defaultCulture, string currencyCode, + int geographyId, int postalCodeLength) : this(countryId, name, code) { - this.Culture = defaultCulture; - this.CurrencyCode = currencyCode; - this.GeographyId = geographyId; - this.PostalCodeLength = postalCodeLength; + Culture = defaultCulture; + CurrencyCode = currencyCode; + GeographyId = geographyId; + PostalCodeLength = postalCodeLength; } - public BasicCountry (BasicCountry original) - : this(original.CountryId, original.Name, original.Code, original.Culture, original.CurrencyCode, original.GeographyId, original.PostalCodeLength ) + 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. @@ -45,7 +48,7 @@ namespace Swarmops.Basic.Types { get { - if (this.Code == "SE") + if (Code == "SE") { return 1; } @@ -58,7 +61,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.CountryId; } + get { return CountryId; } } #endregion diff --git a/Basic/Types/BasicCurrency.cs b/Basic/Types/BasicCurrency.cs index ed692da1..0cd7bf20 100644 --- a/Basic/Types/BasicCurrency.cs +++ b/Basic/Types/BasicCurrency.cs @@ -2,18 +2,18 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicCurrency: IHasIdentity + public class BasicCurrency : IHasIdentity { - public BasicCurrency (int currencyId, string code, string name, string sign) + public BasicCurrency(int currencyId, string code, string name, string sign) { - this.CurrencyId = currencyId; - this.Code = code; - this.Name = name; - this.Sign = sign; + CurrencyId = currencyId; + Code = code; + Name = name; + 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 } @@ -26,7 +26,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.CurrencyId; } + get { return CurrencyId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicDocument.cs b/Basic/Types/BasicDocument.cs index b048c4e6..0a9700f4 100644 --- a/Basic/Types/BasicDocument.cs +++ b/Basic/Types/BasicDocument.cs @@ -4,9 +4,28 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicDocument: IHasIdentity + public class BasicDocument : IHasIdentity { - public BasicDocument (int documentId, string serverFileName, string clientFileName, string description, + private readonly string clientFileName; + private readonly int documentId; + private readonly DocumentType documentType; + private readonly Int64 fileSize; + private readonly int foreignId; + private readonly int uploadedByPersonId; + private readonly DateTime uploadedDateTime; + private string description; + private string serverFileName; + + #region IHasIdentity Members + + public int Identity + { + get { return DocumentId; } + } + + #endregion + + public BasicDocument(int documentId, string serverFileName, string clientFileName, string description, DocumentType documentType, int foreignId, Int64 fileSize, int uploadedByPersonId, DateTime uploadedDateTime) { this.documentId = documentId; @@ -20,9 +39,10 @@ namespace Swarmops.Basic.Types this.uploadedDateTime = uploadedDateTime; } - public BasicDocument (BasicDocument original): - this (original.documentId, original.serverFileName, original.clientFileName, original.description, - original.documentType, original.foreignId, original.fileSize, original.uploadedByPersonId, original.uploadedDateTime) + public BasicDocument(BasicDocument original) : + this(original.documentId, original.serverFileName, original.clientFileName, original.description, + original.documentType, original.foreignId, original.fileSize, original.uploadedByPersonId, + original.uploadedDateTime) { // empty ctor apart from calling the other one } @@ -63,7 +83,7 @@ namespace Swarmops.Basic.Types { get { return this.fileSize; } } - + public int UploadedByPersonId { get { return this.uploadedByPersonId; } @@ -73,25 +93,5 @@ namespace Swarmops.Basic.Types { get { return this.uploadedDateTime; } } - - private int documentId; - private string serverFileName; - private string clientFileName; - private string description; - private DocumentType documentType; - private int foreignId; - private Int64 fileSize; - private int uploadedByPersonId; - private DateTime uploadedDateTime; - - - #region IHasIdentity Members - - public int Identity - { - get { return this.DocumentId; } - } - - #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicElection.cs b/Basic/Types/BasicElection.cs index e7698740..90cad9ac 100644 --- a/Basic/Types/BasicElection.cs +++ b/Basic/Types/BasicElection.cs @@ -3,18 +3,18 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicElection: IHasIdentity + public class BasicElection : IHasIdentity { - public BasicElection (int electionId, string name, int geographyId, DateTime date) + public BasicElection(int electionId, string name, int geographyId, DateTime date) { - this.ElectionId = electionId; - this.Name = name; - this.GeographyId = geographyId; - this.Date = date; + ElectionId = electionId; + Name = name; + GeographyId = geographyId; + 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 } @@ -23,9 +23,10 @@ namespace Swarmops.Basic.Types public string Name { get; private set; } public int GeographyId { get; private set; } public DateTime Date { get; private set; } + public int Identity { - get { return this.ElectionId; } + get { return ElectionId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicExceptionLog.cs b/Basic/Types/BasicExceptionLog.cs index 739e63d9..d1acccb2 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 } @@ -23,4 +23,4 @@ namespace Swarmops.Basic.Types public string Source { get; private set; } public string ExceptionText { get; private set; } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicExpenseClaim.cs b/Basic/Types/BasicExpenseClaim.cs index 6edf78eb..13459fdc 100644 --- a/Basic/Types/BasicExpenseClaim.cs +++ b/Basic/Types/BasicExpenseClaim.cs @@ -5,43 +5,45 @@ namespace Swarmops.Basic.Types { public class BasicExpenseClaim : IHasIdentity { + public readonly int GeographyId; + public readonly int OrganizationId; + /// - /// Normal constructor + /// 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) { - this.ExpenseClaimId = expenseClaimId; - this.ClaimingPersonId = claimingPersonId; - this.CreatedDateTime = createdDateTime; - this.Open = open; - this.Attested = attested; - this.Validated = documented; - this.Claimed = claimed; + ExpenseClaimId = expenseClaimId; + ClaimingPersonId = claimingPersonId; + CreatedDateTime = createdDateTime; + Open = open; + Attested = attested; + Validated = documented; + Claimed = claimed; this.OrganizationId = organizationId; this.GeographyId = geographyId; - this.BudgetId = budgetId; - this.ExpenseDate = expenseDate; - this.Description = description; - this.PreApprovedAmount = preApprovedAmount; - this.AmountCents = amountCents; - this.Repaid = repaid; - this.KeepSeparate = keepSeparate; + BudgetId = budgetId; + ExpenseDate = expenseDate; + Description = description; + PreApprovedAmount = preApprovedAmount; + AmountCents = amountCents; + Repaid = repaid; + KeepSeparate = keepSeparate; } /// - /// Copy constructor + /// Copy constructor /// - public BasicExpenseClaim (BasicExpenseClaim original) + 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, - original.PreApprovedAmount, original.AmountCents, original.Repaid, original.KeepSeparate) + original.Open, original.Attested, original.Validated, original.Claimed, + original.OrganizationId, original.GeographyId, original.BudgetId, + original.ExpenseDate, original.Description, + original.PreApprovedAmount, original.AmountCents, original.Repaid, original.KeepSeparate) { - } @@ -63,12 +65,9 @@ namespace Swarmops.Basic.Types // The fields below are not just encapsulated yet - public readonly int OrganizationId; - public readonly int GeographyId; - public int Identity { - get { return this.ExpenseClaimId; } + get { return ExpenseClaimId; } } } } \ No newline at end of file diff --git a/Basic/Types/BasicExternalActivity.cs b/Basic/Types/BasicExternalActivity.cs index 0d52a54f..3d7cd747 100644 --- a/Basic/Types/BasicExternalActivity.cs +++ b/Basic/Types/BasicExternalActivity.cs @@ -4,24 +4,28 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicExternalActivity: IHasIdentity + public class BasicExternalActivity : IHasIdentity { - public BasicExternalActivity (int externalActivityId, int organizationId, int geographyId, ExternalActivityType type, DateTime dateTime, string description, int createdByPersonId, DateTime createdDateTime, + public BasicExternalActivity(int externalActivityId, int organizationId, int geographyId, + ExternalActivityType type, DateTime dateTime, string description, int createdByPersonId, + DateTime createdDateTime, int dupeOfActivityId) { - this.ExternalActivityId = externalActivityId; - this.OrganizationId = organizationId; - this.GeographyId = geographyId; - this.Type = type; - this.DateTime = dateTime; - this.Description = description; - this.CreatedByPersonId = createdByPersonId; - this.CreatedDateTime = createdDateTime; - this.DupeOfActivityId = dupeOfActivityId; + ExternalActivityId = externalActivityId; + OrganizationId = organizationId; + GeographyId = geographyId; + Type = type; + DateTime = dateTime; + Description = description; + CreatedByPersonId = createdByPersonId; + CreatedDateTime = createdDateTime; + DupeOfActivityId = dupeOfActivityId; } - public BasicExternalActivity (BasicExternalActivity original): - this (original.ExternalActivityId, original.OrganizationId, original.GeographyId, original.Type, original.DateTime, original.Description, original.CreatedByPersonId, original.CreatedDateTime, original.DupeOfActivityId) + public BasicExternalActivity(BasicExternalActivity original) : + this( + original.ExternalActivityId, original.OrganizationId, original.GeographyId, original.Type, original.DateTime, + original.Description, original.CreatedByPersonId, original.CreatedDateTime, original.DupeOfActivityId) { // empty copy ctor } @@ -38,7 +42,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.ExternalActivityId; } + get { return ExternalActivityId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicExternalCredential.cs b/Basic/Types/BasicExternalCredential.cs index 2bb25d43..ac7a0c42 100644 --- a/Basic/Types/BasicExternalCredential.cs +++ b/Basic/Types/BasicExternalCredential.cs @@ -4,7 +4,12 @@ namespace Swarmops.Basic.Types { public class BasicExternalCredential : IHasIdentity { - public BasicExternalCredential (int externalCredentialId, string serviceName, string login, string password) + public readonly int ExternalCredentialId; + public readonly string Login; + public readonly string Password; + public readonly string ServiceName; + + public BasicExternalCredential(int externalCredentialId, string serviceName, string login, string password) { this.ExternalCredentialId = externalCredentialId; this.ServiceName = serviceName; @@ -12,11 +17,6 @@ namespace Swarmops.Basic.Types this.Password = password; } - public readonly int ExternalCredentialId; - public readonly string ServiceName; - public readonly string Login; - public readonly string Password; - public int Identity { diff --git a/Basic/Types/BasicExternalIdentity.cs b/Basic/Types/BasicExternalIdentity.cs index 70435fe7..45070fe5 100644 --- a/Basic/Types/BasicExternalIdentity.cs +++ b/Basic/Types/BasicExternalIdentity.cs @@ -5,13 +5,20 @@ namespace Swarmops.Basic.Types { public class BasicExternalIdentity : IHasIdentity { + private readonly int attachedToPersonID; + private readonly int externalIdentityIdentity; - public BasicExternalIdentity ( int ExternalIdentityIdentity, - ExternalIdentityType TypeOfAccount, - string ExternalSystem, - string UserID, - string Password, - int AttachedToPersonID) + private readonly string externalSystem; + private readonly string password; + private readonly ExternalIdentityType typeOfAccount; + private readonly string userID; + + public BasicExternalIdentity(int ExternalIdentityIdentity, + ExternalIdentityType TypeOfAccount, + string ExternalSystem, + string UserID, + string Password, + int AttachedToPersonID) { this.externalIdentityIdentity = ExternalIdentityIdentity; this.externalSystem = ExternalSystem; @@ -21,60 +28,42 @@ namespace Swarmops.Basic.Types this.typeOfAccount = TypeOfAccount; } - public BasicExternalIdentity (BasicExternalIdentity original) - : this(original.Identity, original.TypeOfAccount, original.ExternalSystem, original.UserID, original.Password, original.AttachedToPersonID) + public BasicExternalIdentity(BasicExternalIdentity original) + : this( + original.Identity, original.TypeOfAccount, original.ExternalSystem, original.UserID, original.Password, + original.AttachedToPersonID) { } - private int externalIdentityIdentity; - - private string externalSystem; - private string userID; - private string password; - private int attachedToPersonID; - private ExternalIdentityType typeOfAccount; - public int ExternalIdentityIdentity { - get { return externalIdentityIdentity; } + get { return this.externalIdentityIdentity; } } public string ExternalSystem { - get - { - return externalSystem; - } - } - public string UserID - { - get - { - return userID; - } - } - public string Password - { - get - { - return password; - } - } - public int AttachedToPersonID - { - get - { - return attachedToPersonID; - } - } - public ExternalIdentityType TypeOfAccount - { - get - { - return typeOfAccount; - } + get { return this.externalSystem; } } + public string UserID + { + get { return this.userID; } + } + + public string Password + { + get { return this.password; } + } + + public int AttachedToPersonID + { + get { return this.attachedToPersonID; } + } + + public ExternalIdentityType TypeOfAccount + { + get { return this.typeOfAccount; } + } #region IHasIdentity Members @@ -85,4 +74,4 @@ namespace Swarmops.Basic.Types #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicGeography.cs b/Basic/Types/BasicGeography.cs index 3415baa9..455b9b38 100644 --- a/Basic/Types/BasicGeography.cs +++ b/Basic/Types/BasicGeography.cs @@ -4,25 +4,25 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { /// - /// A geographical node. + /// A geographical node. /// [Serializable] public class BasicGeography : IHasIdentity { - public BasicGeography (int geographyId, int parentGeographyId, string name) + 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) { - this.GeographyId = geographyId; - this.ParentGeographyId = parentGeographyId; - this.Name = name; - this.Generation = generation; + GeographyId = geographyId; + ParentGeographyId = parentGeographyId; + Name = name; + Generation = generation; } - public BasicGeography (BasicGeography original) + public BasicGeography(BasicGeography original) : this(original.GeographyId, original.ParentGeographyId, original.Name, original.Generation) { } @@ -34,22 +34,22 @@ namespace Swarmops.Basic.Types } /// - /// The database id of this geography. + /// The database id of this geography. /// public int GeographyId { get; private set; } /// - /// The database id of the parent geography, for linking in a tree structure. + /// The database id of the parent geography, for linking in a tree structure. /// public int ParentGeographyId { get; protected set; } /// - /// The friendly name of the node (city, county, region, etc). + /// The friendly name of the node (city, county, region, etc). /// public string Name { get; protected set; } /// - /// The generation of this node. Used in tree-style listings. + /// The generation of this node. Used in tree-style listings. /// public int Generation { get; protected set; } @@ -57,7 +57,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.GeographyId; } + get { return GeographyId; } } #endregion diff --git a/Basic/Types/BasicGeographyDesignation.cs b/Basic/Types/BasicGeographyDesignation.cs index 9c777ddc..c5141bdc 100644 --- a/Basic/Types/BasicGeographyDesignation.cs +++ b/Basic/Types/BasicGeographyDesignation.cs @@ -4,16 +4,16 @@ namespace Swarmops.Basic.Types { public class BasicGeographyDesignation { - public BasicGeographyDesignation (int geographyId, int countryId, - string designation, GeographyLevel geoLevelId) + public BasicGeographyDesignation(int geographyId, int countryId, + string designation, GeographyLevel geoLevelId) { - this.GeographyId = geographyId; - this.CountryId = countryId; - this.Designation = designation; - this.GeographyLevel = geoLevelId; + GeographyId = geographyId; + CountryId = countryId; + Designation = designation; + GeographyLevel = geoLevelId; } - public BasicGeographyDesignation (BasicGeographyDesignation original) : + 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 5ba85e54..bbf14e2d 100644 --- a/Basic/Types/BasicInboundInvoice.cs +++ b/Basic/Types/BasicInboundInvoice.cs @@ -3,34 +3,34 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicInboundInvoice: IHasIdentity + 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, + payToAccount, string ocr, string invoiceReference, bool attested, bool open, DateTime closedDateTime, int closedByPersonId) { - this.InboundInvoiceId = inboundInvoiceId; - this.OrganizationId = organizationId; - this.CreatedDateTime = createdDateTime; - this.DueDate = dueDate; - this.AmountCents = amountCents; - this.BudgetId = budgetId; - this.Supplier = supplier; - this.PayToAccount = payToAccount; - this.Ocr = ocr; - this.InvoiceReference = invoiceReference; - this.Attested = attested; - this.Open = open; - this.ClosedDateTime = closedDateTime; - this.ClosedByPersonId = closedByPersonId; + InboundInvoiceId = inboundInvoiceId; + OrganizationId = organizationId; + CreatedDateTime = createdDateTime; + DueDate = dueDate; + AmountCents = amountCents; + BudgetId = budgetId; + Supplier = supplier; + PayToAccount = payToAccount; + Ocr = ocr; + InvoiceReference = invoiceReference; + Attested = attested; + Open = open; + ClosedDateTime = closedDateTime; + ClosedByPersonId = closedByPersonId; } - 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) + 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) { // empty copy ctor } @@ -54,9 +54,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.InboundInvoiceId; } + get { return InboundInvoiceId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicInternalPoll.cs b/Basic/Types/BasicInternalPoll.cs index 7c9019f3..771d9c60 100644 --- a/Basic/Types/BasicInternalPoll.cs +++ b/Basic/Types/BasicInternalPoll.cs @@ -3,28 +3,33 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicInternalPoll: IHasIdentity + public class BasicInternalPoll : IHasIdentity { - 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) + 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) { - this.InternalPollId = internalPollId; - this.CreatedByPersonId = createdByPersonId; - this.OrganizationId = organizationId; - this.GeographyId = geographyId; - this.Name = name; - this.RunningOpen = runningOpen; - this.VotingOpen = votingOpen; - this.MaxVoteLength = maxVoteLength; - this.RunningOpens = runningOpens; - this.RunningCloses = runningCloses; - this.VotingOpens = votingOpens; - this.VotingCloses = votingCloses; - this.ResultsType = resultsType; + InternalPollId = internalPollId; + CreatedByPersonId = createdByPersonId; + OrganizationId = organizationId; + GeographyId = geographyId; + Name = name; + RunningOpen = runningOpen; + VotingOpen = votingOpen; + MaxVoteLength = maxVoteLength; + RunningOpens = runningOpens; + RunningCloses = runningCloses; + VotingOpens = votingOpens; + VotingCloses = votingCloses; + ResultsType = resultsType; } 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, original.VotingOpens, original.VotingCloses, original.ResultsType) + : this( + original.InternalPollId, original.CreatedByPersonId, original.OrganizationId, original.GeographyId, + original.Name, original.RunningOpen, + original.VotingOpen, original.MaxVoteLength, original.RunningOpens, original.RunningCloses, + original.VotingOpens, original.VotingCloses, original.ResultsType) { // empty copy ctor } @@ -47,7 +52,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.InternalPollId; } + get { return InternalPollId; } } #endregion @@ -57,17 +62,20 @@ namespace Swarmops.Basic.Types public enum InternalPollResultsType { Unknown, + /// - /// Primaries vote -- a Condorcet Schultze divided into six lists and some other twists + /// Primaries vote -- a Condorcet Schultze divided into six lists and some other twists /// Primaries, + /// - /// A straight Condorcet Schultze, ranking the candidates + /// A straight Condorcet Schultze, ranking the candidates /// Schulze, + /// - /// Accept vote: Count the number of accepts for each candidate + /// Accept vote: Count the number of accepts for each candidate /// Accept } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicInternalPollCandidate.cs b/Basic/Types/BasicInternalPollCandidate.cs index 85c62ae5..d1b7aa3b 100644 --- a/Basic/Types/BasicInternalPollCandidate.cs +++ b/Basic/Types/BasicInternalPollCandidate.cs @@ -2,18 +2,21 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicInternalPollCandidate: IHasIdentity + public class BasicInternalPollCandidate : IHasIdentity { - public BasicInternalPollCandidate (int internalPollCandidateId, int internalPollId, int personId, string candidacyStatement) + public BasicInternalPollCandidate(int internalPollCandidateId, int internalPollId, int personId, + string candidacyStatement) { - this.InternalPollCandidateId = internalPollCandidateId; - this.InternalPollId = internalPollId; - this.PersonId = personId; - this.CandidacyStatement = candidacyStatement; + InternalPollCandidateId = internalPollCandidateId; + InternalPollId = internalPollId; + PersonId = personId; + CandidacyStatement = candidacyStatement; } - public BasicInternalPollCandidate (BasicInternalPollCandidate original) - : this (original.InternalPollCandidateId, original.InternalPollId, original.PersonId, original.CandidacyStatement) + public BasicInternalPollCandidate(BasicInternalPollCandidate original) + : this( + original.InternalPollCandidateId, original.InternalPollId, original.PersonId, + original.CandidacyStatement) { // empty copy ctor } @@ -27,9 +30,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.InternalPollCandidateId; } + get { return InternalPollCandidateId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicInternalPollVote.cs b/Basic/Types/BasicInternalPollVote.cs index 74248a2d..c4ca3767 100644 --- a/Basic/Types/BasicInternalPollVote.cs +++ b/Basic/Types/BasicInternalPollVote.cs @@ -2,17 +2,17 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicInternalPollVote: IHasIdentity + public class BasicInternalPollVote : IHasIdentity { - public BasicInternalPollVote (int internalPollVoteId, int internalPollId, string verificationCode) + public BasicInternalPollVote(int internalPollVoteId, int internalPollId, string verificationCode) { - this.InternalPollVoteId = internalPollVoteId; - this.InternalPollId = internalPollId; - this.VerificationCode = 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 } @@ -25,9 +25,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.InternalPollVoteId; } + get { return InternalPollVoteId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicInternalPollVoteDetail.cs b/Basic/Types/BasicInternalPollVoteDetail.cs index 4f409c3f..e807ac42 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) { - this.InternalPollVoteId = internalPollVoteId; - this.InternalPollCandidateId = internalPollCandidateId; - this.Position = 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 } @@ -19,4 +19,4 @@ namespace Swarmops.Basic.Types public int InternalPollCandidateId { get; private set; } public int Position { get; private set; } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicInternalPollVoter.cs b/Basic/Types/BasicInternalPollVoter.cs index 91a635a8..c1fbea7d 100644 --- a/Basic/Types/BasicInternalPollVoter.cs +++ b/Basic/Types/BasicInternalPollVoter.cs @@ -4,16 +4,16 @@ 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) { - this.PersonId = personId; - this.InternalPollId = internalPollId; - this.Open = open; - this.ClosedDateTime = closedDateTime; + PersonId = personId; + InternalPollId = internalPollId; + Open = open; + 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 } @@ -28,17 +28,20 @@ namespace Swarmops.Basic.Types public enum InternalPollVoterStatus { Unknown = 0, + /// - /// This voter is eligible and has not yet voted in this poll. + /// This voter is eligible and has not yet voted in this poll. /// CanVote, + /// - /// This voter is eligible to vote, but has already voted. + /// This voter is eligible to vote, but has already voted. /// HasAlreadyVoted, + /// - /// This person does is not on the list of eligible voters. + /// This person does is not on the list of eligible voters. /// NotEligibleForPoll } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicMailTemplate.cs b/Basic/Types/BasicMailTemplate.cs index f77121d4..084c59b8 100644 --- a/Basic/Types/BasicMailTemplate.cs +++ b/Basic/Types/BasicMailTemplate.cs @@ -4,15 +4,22 @@ namespace Swarmops.Basic.Types { public class BasicMailTemplate : IHasIdentity { + private readonly string countryCode; + private readonly string languageCode; + private readonly int organizationId; + private readonly int templateId; + private readonly string templateName; + private string templateBody; + /// - /// Basic constructor. + /// Basic constructor. /// - public BasicMailTemplate (int templateId, - string templateName, - string languageCode, - string countryCode, - int organizationId, - string templateBody) + public BasicMailTemplate(int templateId, + string templateName, + string languageCode, + string countryCode, + int organizationId, + string templateBody) { this.templateId = templateId; this.templateName = templateName; @@ -20,20 +27,19 @@ namespace Swarmops.Basic.Types this.countryCode = countryCode; this.organizationId = organizationId; this.templateBody = templateBody; - } /// - /// Copy constructor. + /// Copy constructor. /// - public BasicMailTemplate (BasicMailTemplate original) + public BasicMailTemplate(BasicMailTemplate original) : this(original.templateId, - original.templateName, - original.languageCode, - original.countryCode, - original.organizationId, - original.templateBody) + original.templateName, + original.languageCode, + original.countryCode, + original.organizationId, + original.templateBody) { } @@ -42,51 +48,37 @@ namespace Swarmops.Basic.Types get { return this.templateId; } } - public int Identity - { - get { return this.templateId; } - } - public string TemplateName { - get - { - return templateName; - } + get { return this.templateName; } } + public string LanguageCode { - get - { - return languageCode; - } + get { return this.languageCode; } } + public string CountryCode { - get - { - return countryCode; - } + get { return this.countryCode; } } + public int OrganizationId { get { return this.organizationId; } } - public string TemplateBody { get { return this.templateBody; } set { this.templateBody = value; } } - private int templateId; - private string templateName; - private string languageCode; - private string countryCode; - private int organizationId; - private string templateBody; + public int Identity + { + get { return this.templateId; } + } } } \ No newline at end of file diff --git a/Basic/Types/BasicMediaCategory.cs b/Basic/Types/BasicMediaCategory.cs index 566ad175..afafa62d 100644 --- a/Basic/Types/BasicMediaCategory.cs +++ b/Basic/Types/BasicMediaCategory.cs @@ -4,13 +4,25 @@ namespace Swarmops.Basic.Types { public class BasicMediaCategory : IHasIdentity { - public BasicMediaCategory (int mediaCategoryId, string name) + private readonly int mediaCategoryId; + private readonly string name; + + #region IHasIdentity Members + + public int Identity + { + get { return MediaCategoryId; } + } + + #endregion + + public BasicMediaCategory(int mediaCategoryId, string name) { this.mediaCategoryId = mediaCategoryId; this.name = name; } - public BasicMediaCategory (BasicMediaCategory original) : + public BasicMediaCategory(BasicMediaCategory original) : this(original.mediaCategoryId, original.name) { } @@ -30,17 +42,5 @@ namespace Swarmops.Basic.Types { get { return this.mediaCategoryId; } } - - private int mediaCategoryId; - private string name; - - #region IHasIdentity Members - - public int Identity - { - get { return MediaCategoryId; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicMediaEntry.cs b/Basic/Types/BasicMediaEntry.cs index 103bcb84..107a169d 100644 --- a/Basic/Types/BasicMediaEntry.cs +++ b/Basic/Types/BasicMediaEntry.cs @@ -5,8 +5,25 @@ namespace Swarmops.Basic.Types { public class BasicMediaEntry : IHasIdentity { - public BasicMediaEntry (int id, int keywordId, string mediaName, bool isBlog, string title, string url, - DateTime dateTime) + private readonly DateTime dateTime; + private readonly int id; + private readonly bool isBlog; + private readonly int keywordId; + private readonly string mediaName; + private readonly string title; + private readonly string url; + + #region IHasIdentity Members + + public int Identity + { + get { return Id; } + } + + #endregion + + public BasicMediaEntry(int id, int keywordId, string mediaName, bool isBlog, string title, string url, + DateTime dateTime) { this.id = id; this.keywordId = keywordId; @@ -17,7 +34,7 @@ namespace Swarmops.Basic.Types this.dateTime = dateTime; } - public BasicMediaEntry (BasicMediaEntry original) + public BasicMediaEntry(BasicMediaEntry original) : this( original.id, original.keywordId, original.mediaName, original.isBlog, original.title, original.url, original.dateTime) @@ -31,17 +48,17 @@ namespace Swarmops.Basic.Types public int Id { - get { return id; } + get { return this.id; } } public int KeywordId { - get { return keywordId; } + get { return this.keywordId; } } public string Title { - get { return title; } + get { return this.title; } } public string MediaName @@ -52,34 +69,17 @@ namespace Swarmops.Basic.Types public string Url { - get { return url; } + get { return this.url; } } public DateTime DateTime { - get { return dateTime; } + get { return this.dateTime; } } public bool IsBlog { get { return this.isBlog; } } - - private int id; - private DateTime dateTime; - private string title; - private string mediaName; - private string url; - private int keywordId; - private bool isBlog; - - #region IHasIdentity Members - - public int Identity - { - get { return Id; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicMediaKeyword.cs b/Basic/Types/BasicMediaKeyword.cs index ec0154a1..9608285a 100644 --- a/Basic/Types/BasicMediaKeyword.cs +++ b/Basic/Types/BasicMediaKeyword.cs @@ -6,13 +6,25 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicMediaKeyword : IHasIdentity { - public BasicMediaKeyword (int id, string keyword) + private readonly int id; + private readonly string keyword; + + #region IHasIdentity Members + + public int Identity + { + get { return Id; } + } + + #endregion + + 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; @@ -25,24 +37,12 @@ namespace Swarmops.Basic.Types public int Id { - get { return id; } + get { return this.id; } } public string Keyword { - get { return keyword; } + get { return this.keyword; } } - - private int id; - private string keyword; - - #region IHasIdentity Members - - public int Identity - { - get { return Id; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicMedium.cs b/Basic/Types/BasicMedium.cs index e5f6ce0f..5a9d6f26 100644 --- a/Basic/Types/BasicMedium.cs +++ b/Basic/Types/BasicMedium.cs @@ -5,15 +5,28 @@ namespace Swarmops.Basic.Types { public class BasicMedium : IHasIdentity { - public BasicMedium (int mediumId, string name, PoliticalAffiliation politicalAffiliation) + private readonly int mediumId; + private readonly string name; + private readonly PoliticalAffiliation politicalAffiliation; + + #region IHasIdentity Members + + public int Identity + { + get { return MediumId; } + } + + #endregion + + 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, Enums.PoliticalAffiliation.NotPolitical) + public BasicMedium(int mediumId, string name) + : this(mediumId, name, PoliticalAffiliation.NotPolitical) { } @@ -31,18 +44,5 @@ namespace Swarmops.Basic.Types { get { return this.mediumId; } } - - private int mediumId; - private string name; - private PoliticalAffiliation politicalAffiliation; - - #region IHasIdentity Members - - public int Identity - { - get { return this.MediumId; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicMembership.cs b/Basic/Types/BasicMembership.cs index 3b90b808..4d88c9a3 100644 --- a/Basic/Types/BasicMembership.cs +++ b/Basic/Types/BasicMembership.cs @@ -5,34 +5,34 @@ namespace Swarmops.Basic.Types { public class BasicMembership : IHasIdentity { - public BasicMembership (int personId, int organizationId) + public BasicMembership(int personId, int organizationId) { - this.PersonId = personId; - this.OrganizationId = organizationId; - this.Active = true; - this.DateTerminated = DateTime.MinValue; + PersonId = personId; + OrganizationId = organizationId; + Active = true; + DateTerminated = DateTime.MinValue; } - public BasicMembership (int personId, int organizationId, DateTime memberSince, DateTime expires) + public BasicMembership(int personId, int organizationId, DateTime memberSince, DateTime expires) : this(personId, organizationId) { - this.MemberSince = memberSince; - this.Expires = expires; + MemberSince = memberSince; + Expires = expires; } - public BasicMembership (int membershipId, int personId, int organizationId, DateTime memberSince, - DateTime expires, bool active, DateTime dateTerminated) + public BasicMembership(int membershipId, int personId, int organizationId, DateTime memberSince, + DateTime expires, bool active, DateTime dateTerminated) { - this.MembershipId = membershipId; - this.PersonId = personId; - this.OrganizationId = organizationId; - this.MemberSince = memberSince; - this.Expires = expires; - this.Active = active; - this.DateTerminated = dateTerminated; + MembershipId = membershipId; + PersonId = personId; + OrganizationId = organizationId; + MemberSince = memberSince; + Expires = expires; + Active = active; + DateTerminated = dateTerminated; } - public BasicMembership (BasicMembership original) + public BasicMembership(BasicMembership original) : this( original.MembershipId, original.PersonId, original.OrganizationId, original.MemberSince, original.Expires, original.Active, original.DateTerminated) @@ -48,23 +48,18 @@ namespace Swarmops.Basic.Types public DateTime DateTerminated { get; protected set; } public DateTime Expires { get; protected set; } - - - - // RICK NOTES: I moved the MembershipPayments to a separate table, as they are NULL on most rows. - // Not implemented as per 2010-01-11. - - // Also, note the renaming of "Valid" to "Active", consistently with other objects and analogous to "Open". - - - #region IHasIdentity Members public int Identity { - get { return this.MembershipId; } + get { return MembershipId; } } #endregion + + // RICK NOTES: I moved the MembershipPayments to a separate table, as they are NULL on most rows. + // Not implemented as per 2010-01-11. + + // Also, note the renaming of "Valid" to "Active", consistently with other objects and analogous to "Open". } } \ No newline at end of file diff --git a/Basic/Types/BasicMembershipPaymentStatus.cs b/Basic/Types/BasicMembershipPaymentStatus.cs index bc9c9706..97a54955 100644 --- a/Basic/Types/BasicMembershipPaymentStatus.cs +++ b/Basic/Types/BasicMembershipPaymentStatus.cs @@ -5,15 +5,15 @@ namespace Swarmops.Basic.Types { public class BasicMembershipPaymentStatus { - public BasicMembershipPaymentStatus (int membershipId,MembershipPaymentStatus status, DateTime statusDateTime) + public BasicMembershipPaymentStatus(int membershipId, MembershipPaymentStatus status, DateTime statusDateTime) { - this.MembershipId = membershipId ; - this.Status = status; - this.StatusDateTime = statusDateTime; + MembershipId = membershipId; + Status = status; + StatusDateTime = statusDateTime; } - public int MembershipId { get; protected set; } + public int MembershipId { get; protected set; } public MembershipPaymentStatus Status { get; set; } public DateTime StatusDateTime { get; set; } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicNewsletter.cs b/Basic/Types/BasicNewsletter.cs index 7cf57a4f..f9a0a08d 100644 --- a/Basic/Types/BasicNewsletter.cs +++ b/Basic/Types/BasicNewsletter.cs @@ -3,12 +3,22 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { /// - /// This class encapsulates a single newsletter. + /// This class encapsulates a single newsletter. /// public class BasicNewsletter : IHasIdentity { - public BasicNewsletter (int newsletterId, string title, string introduction, string body, - int authorId, int templateId, int feedId) + private readonly int authorId; + private readonly string body; + private readonly int geographyId; + private readonly string introduction; + private readonly int newsletterFeedId; + private readonly int newsletterId; + private readonly int newsletterTemplateId; + private readonly int organizationId; + private readonly string title; + + public BasicNewsletter(int newsletterId, string title, string introduction, string body, + int authorId, int templateId, int feedId) { this.newsletterId = newsletterId; this.newsletterFeedId = feedId; @@ -20,8 +30,8 @@ namespace Swarmops.Basic.Types this.newsletterFeedId = feedId; } - public BasicNewsletter (int newsletterId, string title, string introduction, string body, - int authorId, int templateId, int feedId, int organizationId, int geographyId) + 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) { @@ -31,47 +41,47 @@ namespace Swarmops.Basic.Types public int NewsletterId { - get { return newsletterId; } + get { return this.newsletterId; } } public string Title { - get { return title; } + get { return this.title; } } public string Introduction { - get { return introduction; } + get { return this.introduction; } } public string Body { - get { return body; } + get { return this.body; } } public int AuthorId { - get { return authorId; } + get { return this.authorId; } } public int NewsletterFeedId { - get { return newsletterFeedId; } + get { return this.newsletterFeedId; } } public int NewsletterTemplateId { - get { return newsletterTemplateId; } + get { return this.newsletterTemplateId; } } public int OrganizationId { - get { return organizationId; } + get { return this.organizationId; } } public int GeographyId { - get { return geographyId; } + get { return this.geographyId; } } #region IHasIdentity Members @@ -82,15 +92,5 @@ namespace Swarmops.Basic.Types } #endregion - - private int newsletterId; - private string title; - private string introduction; - private string body; - private int authorId; - private int newsletterFeedId; - private int newsletterTemplateId; - private int geographyId; - private int organizationId; } } \ No newline at end of file diff --git a/Basic/Types/BasicNewsletterFeed.cs b/Basic/Types/BasicNewsletterFeed.cs index 21a6c480..d0dd4af2 100644 --- a/Basic/Types/BasicNewsletterFeed.cs +++ b/Basic/Types/BasicNewsletterFeed.cs @@ -2,7 +2,27 @@ namespace Swarmops.Basic.Types { public class BasicNewsletterFeed { - public BasicNewsletterFeed (int newsletterId, int organizationId, bool defaultSubscribed, string name) + /// + /// If true, a new member in the owning organization will get this newsletter. + /// + public readonly bool DefaultSubscribed; + + /// + /// A friendly name for the newsletter. + /// + public readonly string Name; + + /// + /// The database identity of the newsletter feed. + /// + public readonly int NewsletterFeedId; + + /// + /// The identity of the organization that owns this newsletter. + /// + public readonly int OrganizationId; + + public BasicNewsletterFeed(int newsletterId, int organizationId, bool defaultSubscribed, string name) { this.NewsletterFeedId = newsletterId; this.OrganizationId = organizationId; @@ -12,32 +32,12 @@ namespace Swarmops.Basic.Types public BasicNewsletterFeed() { - Name = string.Empty; + this.Name = string.Empty; } - public BasicNewsletterFeed (BasicNewsletterFeed original) + public BasicNewsletterFeed(BasicNewsletterFeed original) : this(original.NewsletterFeedId, original.OrganizationId, original.DefaultSubscribed, original.Name) { } - - /// - /// The database identity of the newsletter feed. - /// - public readonly int NewsletterFeedId; - - /// - /// The identity of the organization that owns this newsletter. - /// - public readonly int OrganizationId; - - /// - /// If true, a new member in the owning organization will get this newsletter. - /// - public readonly bool DefaultSubscribed; - - /// - /// A friendly name for the newsletter. - /// - public readonly string Name; } } \ No newline at end of file diff --git a/Basic/Types/BasicNewsletterTemplate.cs b/Basic/Types/BasicNewsletterTemplate.cs index 363b8128..fe66ac52 100644 --- a/Basic/Types/BasicNewsletterTemplate.cs +++ b/Basic/Types/BasicNewsletterTemplate.cs @@ -2,13 +2,13 @@ namespace Swarmops.Basic.Types { public class BasicNewsletterTemplate { - public BasicNewsletterTemplate (string htmlTemplate, string textTemplate) + public string HtmlTemplate; + public string TextTemplate; + + public BasicNewsletterTemplate(string htmlTemplate, string textTemplate) { this.HtmlTemplate = htmlTemplate; this.TextTemplate = textTemplate; } - - public string HtmlTemplate; - public string TextTemplate; } } \ No newline at end of file diff --git a/Basic/Types/BasicObjectOptionalData.cs b/Basic/Types/BasicObjectOptionalData.cs index 84231566..fbe160b5 100644 --- a/Basic/Types/BasicObjectOptionalData.cs +++ b/Basic/Types/BasicObjectOptionalData.cs @@ -7,22 +7,23 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicObjectOptionalData { - public BasicObjectOptionalData(ObjectType objectType, int objectId, Dictionary initialData) + protected Dictionary OptionalData; + + public BasicObjectOptionalData(ObjectType objectType, int objectId, + Dictionary initialData) { - this.ObjectType = objectType; - this.ObjectId = objectId; + ObjectType = objectType; + ObjectId = objectId; this.OptionalData = initialData; } public BasicObjectOptionalData(BasicObjectOptionalData original) - : this (original.ObjectType, original.ObjectId, original.OptionalData) + : this(original.ObjectType, original.ObjectId, original.OptionalData) { // empty ctor } public ObjectType ObjectType { get; private set; } public int ObjectId { get; private set; } - - protected Dictionary OptionalData; } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicOrganization.cs b/Basic/Types/BasicOrganization.cs index 2552f6b0..6b3e4141 100644 --- a/Basic/Types/BasicOrganization.cs +++ b/Basic/Types/BasicOrganization.cs @@ -4,40 +4,51 @@ namespace Swarmops.Basic.Types { public class BasicOrganization : IHasIdentity { + private string nameShort; + + #region IHasIdentity Members + + public int Identity + { + get { return OrganizationId; } + } + + #endregion + public BasicOrganization() { } - public BasicOrganization (int organizationId, string name, string nameInternational) + public BasicOrganization(int organizationId, string name, string nameInternational) { - this.organizationId = organizationId; - this.name = name; - this.nameInternational = nameInternational; + OrganizationId = organizationId; + Name = name; + NameInternational = nameInternational; } - public BasicOrganization (int organizationId, int parentOrganizationId, string name, string nameInternational) : + public BasicOrganization(int organizationId, int parentOrganizationId, string name, string nameInternational) : this(organizationId, name, nameInternational) { - this.parentOrganizationId = parentOrganizationId; + ParentOrganizationId = parentOrganizationId; } - public BasicOrganization (int organizationId, int parentOrganizationId, string name, string nameInternational, - string nameShort, string domain, string mailPrefix, int anchorGeographyId, - bool acceptsMembers, bool autoAssignNewMembers, - int defaultCountryId) + 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.nameShort = nameShort; - this.domain = domain; - this.mailPrefix = mailPrefix; - this.anchorGeographyId = anchorGeographyId; - this.acceptsMembers = acceptsMembers; - this.autoAssignNewMembers = autoAssignNewMembers; - this.defaultCountryId = defaultCountryId; + Domain = domain; + MailPrefix = mailPrefix; + AnchorGeographyId = anchorGeographyId; + AcceptsMembers = acceptsMembers; + AutoAssignNewMembers = autoAssignNewMembers; + DefaultCountryId = defaultCountryId; } - public BasicOrganization (BasicOrganization original) + public BasicOrganization(BasicOrganization original) : this( original.Identity, original.ParentOrganizationId, original.Name, original.NameInternational, original.NameShort, original.Domain, original.MailPrefix, original.AnchorGeographyId, @@ -45,23 +56,11 @@ namespace Swarmops.Basic.Types { } - public int DefaultCountryId - { - get { return this.defaultCountryId; } - protected set { this.defaultCountryId = value; } - } + public int DefaultCountryId { get; protected set; } - public string Name - { - get { return this.name; } - protected set { this.name = value; } - } + public string Name { get; protected set; } - public string NameInternational - { - get { return this.nameInternational; } - protected set { this.nameInternational = value; } - } + public string NameInternational { get; protected set; } public string NameShort { @@ -72,75 +71,23 @@ namespace Swarmops.Basic.Types return this.nameShort; } - return this.Name; - } - set - { - this.nameShort = value; + return Name; } + set { this.nameShort = value; } } - public string Domain - { - get { return this.domain; } - protected set { this.domain = value; } - } + public string Domain { get; protected set; } - public string MailPrefix - { - get { return this.mailPrefix; } - protected set { this.mailPrefix = value; } - } + public string MailPrefix { get; protected set; } - public int AnchorGeographyId - { - get { return this.anchorGeographyId; } - protected set { this.anchorGeographyId = value; } - } + public int AnchorGeographyId { get; protected set; } - public bool AcceptsMembers - { - get { return this.acceptsMembers; } - protected set { this.acceptsMembers=value; } - } + public bool AcceptsMembers { get; protected set; } - public int OrganizationId - { - get { return this.organizationId; } - protected set { this.organizationId = value; } - } + public int OrganizationId { get; protected set; } - public int ParentOrganizationId - { - get { return this.parentOrganizationId; } - protected set { this.parentOrganizationId = value; } - } + public int ParentOrganizationId { get; protected set; } - public bool AutoAssignNewMembers - { - get { return this.autoAssignNewMembers; } - protected set { this.autoAssignNewMembers = value; } - } - - private string name; - private string nameInternational; - private string nameShort; - private string domain; - private string mailPrefix; - private int anchorGeographyId; - private bool acceptsMembers; - private bool autoAssignNewMembers; - private int organizationId; - private int parentOrganizationId; - private int defaultCountryId; - - #region IHasIdentity Members - - public int Identity - { - get { return OrganizationId; } - } - - #endregion + public bool AutoAssignNewMembers { get; protected set; } } } \ No newline at end of file diff --git a/Basic/Types/BasicOutboundInvoice.cs b/Basic/Types/BasicOutboundInvoice.cs index 96ecb3d3..6868adc1 100644 --- a/Basic/Types/BasicOutboundInvoice.cs +++ b/Basic/Types/BasicOutboundInvoice.cs @@ -3,33 +3,39 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicOutboundInvoice: IHasIdentity + public class BasicOutboundInvoice : IHasIdentity { - 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) + 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) { - this.OutboundInvoiceId = outboundInvoiceId; - this.CustomerName = customerName; - this.InvoiceAddressPaper = invoiceAddressPaper; - this.InvoiceAddressMail = invoiceAddressMail; - this.CurrencyId = currencyId; - this.OrganizationId = organizationId; - this.BudgetId = budgetId; - this.CreatedDateTime = createdDateTime; - this.CreatedByPersonId = createdByPersonId; - this.DueDate = dueDate; - this.ReminderCount = reminderCount; - this.Reference = reference; - this.Domestic = domestic; - this.Open = open; - this.Sent = sent; - this.SecurityCode = securityCode; - this.TheirReference = theirReference; + OutboundInvoiceId = outboundInvoiceId; + CustomerName = customerName; + InvoiceAddressPaper = invoiceAddressPaper; + InvoiceAddressMail = invoiceAddressMail; + CurrencyId = currencyId; + OrganizationId = organizationId; + BudgetId = budgetId; + CreatedDateTime = createdDateTime; + CreatedByPersonId = createdByPersonId; + DueDate = dueDate; + ReminderCount = reminderCount; + Reference = reference; + Domestic = domestic; + Open = open; + Sent = sent; + SecurityCode = securityCode; + TheirReference = theirReference; } - 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, original.Open, original.Sent, original.SecurityCode, original.TheirReference) + 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, + original.Open, original.Sent, original.SecurityCode, original.TheirReference) { // empty copy ctor } @@ -55,7 +61,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.OutboundInvoiceId; } + get { return OutboundInvoiceId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicOutboundInvoiceItem.cs b/Basic/Types/BasicOutboundInvoiceItem.cs index c75c5f91..7c7d7e13 100644 --- a/Basic/Types/BasicOutboundInvoiceItem.cs +++ b/Basic/Types/BasicOutboundInvoiceItem.cs @@ -3,18 +3,19 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicOutboundInvoiceItem: IHasIdentity + public class BasicOutboundInvoiceItem : IHasIdentity { - public BasicOutboundInvoiceItem (int outboundInvoiceItemId, int outboundInvoiceId, string description, Int64 amountCents) + public BasicOutboundInvoiceItem(int outboundInvoiceItemId, int outboundInvoiceId, string description, + Int64 amountCents) { - this.OutboundInvoiceItemId = outboundInvoiceItemId; - this.OutboundInvoiceId = outboundInvoiceId; - this.Description = description; - this.AmountCents = amountCents; + OutboundInvoiceItemId = outboundInvoiceItemId; + OutboundInvoiceId = outboundInvoiceId; + Description = description; + 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 } @@ -26,7 +27,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.OutboundInvoiceItemId; } + get { return OutboundInvoiceItemId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicOutboundMail.cs b/Basic/Types/BasicOutboundMail.cs index cc3d5492..dfa69373 100644 --- a/Basic/Types/BasicOutboundMail.cs +++ b/Basic/Types/BasicOutboundMail.cs @@ -14,15 +14,15 @@ namespace Swarmops.Basic.Types /// - /// Basic constructor. This is for database use and NOT for public construction. + /// Basic constructor. This is for database use and NOT for public construction. /// - 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, - bool processed, - DateTime resolvedDateTime, DateTime startProcessDateTime, DateTime endProcessDateTime, - int recipientCount, int recipientsSuccess, int recipientsFail) + 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, + bool processed, + DateTime resolvedDateTime, DateTime startProcessDateTime, DateTime endProcessDateTime, + int recipientCount, int recipientsSuccess, int recipientsFail) { this.outboundMailId = outboundMailId; this.authorType = authorType; @@ -49,24 +49,24 @@ namespace Swarmops.Basic.Types } /// - /// Constructor used by OutboundMail after creating record in db. NOT for other use + /// Constructor used by OutboundMail after creating record in db. NOT for other use /// - public BasicOutboundMail (int outboundMailId, MailAuthorType authorType, int authorPersonId, string title, - string body, int mailPriority, int mailType, int organizationId, - int geographyId, DateTime createdDateTime, DateTime releaseDateTime) + 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, - mailPriority, mailType, organizationId, geographyId, - createdDateTime, releaseDateTime, - false, false, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, 0, 0, 0) + mailPriority, mailType, organizationId, geographyId, + createdDateTime, releaseDateTime, + false, false, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, 0, 0, 0) { // nothing more to do } /// - /// Copy constructor. Used when PirateWeb.Logic constructs an OutboundMail object. + /// Copy constructor. Used when PirateWeb.Logic constructs an OutboundMail object. /// /// The original to copy. - public BasicOutboundMail (BasicOutboundMail original) + public BasicOutboundMail(BasicOutboundMail original) : this( original.outboundMailId, original.authorType, original.authorPersonId, original.title, original.body, original.mailPriority, original.mailType, @@ -87,11 +87,6 @@ namespace Swarmops.Basic.Types // ============================ - public int Identity - { - get { return this.OutboundMailId; } - } - public int OutboundMailId { get { return this.outboundMailId; } @@ -185,6 +180,11 @@ namespace Swarmops.Basic.Types set { this.recipientsFail = value; } } + public int Identity + { + get { return OutboundMailId; } + } + #endregion #region Private fields @@ -194,26 +194,26 @@ namespace Swarmops.Basic.Types // ================== - private int outboundMailId; - private MailAuthorType authorType; - private int authorPersonId; - private string title; - private string body; - private int mailPriority; - private int mailType; - private int geographyId; - private int organizationId; - private DateTime createdDateTime; - private DateTime releaseDateTime; - private bool readyForPickup; - private bool resolved; + private readonly int authorPersonId; + private readonly MailAuthorType authorType; + private readonly string body; + private readonly DateTime createdDateTime; + private readonly DateTime endProcessDateTime; + private readonly int geographyId; + private readonly int mailPriority; + private readonly int mailType; + private readonly int organizationId; + private readonly int outboundMailId; + private readonly DateTime releaseDateTime; + private readonly DateTime resolvedDateTime; private bool processed; - private DateTime resolvedDateTime; - private DateTime startProcessDateTime; - private DateTime endProcessDateTime; + private bool readyForPickup; private int recipientCount; - private int recipientsSuccess; private int recipientsFail; + private int recipientsSuccess; + private bool resolved; + private DateTime startProcessDateTime; + private string title; #endregion } diff --git a/Basic/Types/BasicOutboundMailRecipient.cs b/Basic/Types/BasicOutboundMailRecipient.cs index 1bfc13da..1ba40727 100644 --- a/Basic/Types/BasicOutboundMailRecipient.cs +++ b/Basic/Types/BasicOutboundMailRecipient.cs @@ -7,9 +7,10 @@ namespace Swarmops.Basic.Types #region Creation and Construction /// - /// Normal constructor. + /// Normal constructor. /// - public BasicOutboundMailRecipient (int outboundMailRecipientId, int outboundMailId, int personId, bool asOfficer,int personType) + public BasicOutboundMailRecipient(int outboundMailRecipientId, int outboundMailId, int personId, bool asOfficer, + int personType) { this.outboundMailId = outboundMailId; this.outboundMailRecipientId = outboundMailRecipientId; @@ -19,10 +20,12 @@ namespace Swarmops.Basic.Types } /// - /// Copy constructor. + /// Copy constructor. /// - public BasicOutboundMailRecipient (BasicOutboundMailRecipient original) - : this(original.outboundMailRecipientId, original.outboundMailId, original.personId, original.asOfficer, original.personType) + public BasicOutboundMailRecipient(BasicOutboundMailRecipient original) + : this( + original.outboundMailRecipientId, original.outboundMailId, original.personId, original.asOfficer, + original.personType) { } @@ -46,12 +49,6 @@ namespace Swarmops.Basic.Types } - public int Identity - { - get { return this.OutboundMailRecipientId; } - } - - public bool AsOfficer { get { return this.asOfficer; } @@ -59,18 +56,23 @@ namespace Swarmops.Basic.Types public int PersonType { - get { return this.personType ; } + get { return this.personType; } + } + + public int Identity + { + get { return OutboundMailRecipientId; } } #endregion #region Private fields - private int outboundMailRecipientId; - private int outboundMailId; - private int personId; - private bool asOfficer; - private int personType = 0; //0 = Person, 1 = Reporter + private readonly bool asOfficer; + private readonly int outboundMailId; + private readonly int outboundMailRecipientId; + private readonly int personId; + private readonly int personType; //0 = Person, 1 = Reporter #endregion } diff --git a/Basic/Types/BasicPWEvent.cs b/Basic/Types/BasicPWEvent.cs index 44eddc4d..fd1723d8 100644 --- a/Basic/Types/BasicPWEvent.cs +++ b/Basic/Types/BasicPWEvent.cs @@ -1,25 +1,26 @@ using System; +using Swarmops.Basic.Enums; namespace Swarmops.Basic.Types { public class BasicPWEvent { - public BasicPWEvent (int eventId, DateTime dateTime, bool open, DateTime processedDateTime, Enums.EventType eventType, - Enums.EventSource eventSource, int actingPersonId, int affectedPersonId, int organizationId, - int geographyId, int parameterInt, string parameterText) + 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) { - this.EventId = eventId; - this.DateTime = dateTime; - this.Open = open; - this.ProcessedDateTime = processedDateTime; - this.EventType = eventType; - this.EventSource = eventSource; - this.ActingPersonId = actingPersonId; - this.AffectedPersonId = affectedPersonId; - this.OrganizationId = organizationId; - this.GeographyId = geographyId; - this.ParameterInt = parameterInt; - this.ParameterText = parameterText; + EventId = eventId; + DateTime = dateTime; + Open = open; + ProcessedDateTime = processedDateTime; + EventType = eventType; + EventSource = eventSource; + ActingPersonId = actingPersonId; + AffectedPersonId = affectedPersonId; + OrganizationId = organizationId; + GeographyId = geographyId; + ParameterInt = parameterInt; + ParameterText = parameterText; } @@ -27,8 +28,8 @@ namespace Swarmops.Basic.Types public DateTime ProcessedDateTime { get; protected set; } public int EventId { get; private set; } public bool Open { get; protected set; } - public Enums.EventType EventType { get; private set; } - public Enums.EventSource EventSource { get; private set; } + public EventType EventType { get; private set; } + public EventSource EventSource { get; private set; } public int ActingPersonId { get; private set; } public int AffectedPersonId { get; private set; } public int OrganizationId { get; private set; } diff --git a/Basic/Types/BasicPWLog.cs b/Basic/Types/BasicPWLog.cs index 540f1c94..80bf4bee 100644 --- a/Basic/Types/BasicPWLog.cs +++ b/Basic/Types/BasicPWLog.cs @@ -5,17 +5,29 @@ namespace Swarmops.Basic.Types [Serializable] public class BasicPWLog { - public BasicPWLog ( DateTime dateTimeUtc, - int actingPersonId, - string affectedItemType, - int affectedItemId, - string actionType, - string actionDescription, - string changedField, - string valueBefore, - string valueAfter, - string comment, - string ipAddress) + private int actingPersonId; + private string actionDescription; + private string actionType; + private int affectedItemId; + private string affectedItemType; + private string changedField; + private string comment; + private DateTime dateTimeUtc; + private string ipAddress; + private string valueAfter; + private string valueBefore; + + public BasicPWLog(DateTime dateTimeUtc, + int actingPersonId, + string affectedItemType, + int affectedItemId, + string actionType, + string actionDescription, + string changedField, + string valueBefore, + string valueAfter, + string comment, + string ipAddress) { this.dateTimeUtc = dateTimeUtc; this.actingPersonId = actingPersonId; @@ -28,87 +40,73 @@ namespace Swarmops.Basic.Types this.valueAfter = valueAfter; this.comment = comment; this.ipAddress = ipAddress; - } public DateTime DateTimeUtc { - get { return dateTimeUtc; } - set { dateTimeUtc = value; } + get { return this.dateTimeUtc; } + set { this.dateTimeUtc = value; } } public int ActingPersonId { - get { return actingPersonId; } - set { actingPersonId = value; } + get { return this.actingPersonId; } + set { this.actingPersonId = value; } } public string AffectedItemType { - get { return affectedItemType; } - set { affectedItemType = value; } + get { return this.affectedItemType; } + set { this.affectedItemType = value; } } public int AffectedItemId { - get { return affectedItemId; } - set { affectedItemId = value; } + get { return this.affectedItemId; } + set { this.affectedItemId = value; } } public string ActionType { - get { return actionType; } - set { actionType = value; } + get { return this.actionType; } + set { this.actionType = value; } } public string ActionDescription { - get { return actionDescription; } - set { actionDescription = value; } + get { return this.actionDescription; } + set { this.actionDescription = value; } } public string ChangedField { - get { return changedField; } - set { changedField = value; } + get { return this.changedField; } + set { this.changedField = value; } } public string ValueBefore { - get { return valueBefore; } - set { valueBefore = value; } + get { return this.valueBefore; } + set { this.valueBefore = value; } } public string ValueAfter { - get { return valueAfter; } - set { valueAfter = value; } + get { return this.valueAfter; } + set { this.valueAfter = value; } } public string Comment { - get { return comment; } - set { comment = value; } + get { return this.comment; } + set { this.comment = value; } } public string IpAddress { - get { return ipAddress; } - set { ipAddress = value; } + get { return this.ipAddress; } + set { this.ipAddress = value; } } - - private DateTime dateTimeUtc; - private int actingPersonId; - private string affectedItemType; - private int affectedItemId; - private string actionType; - private string actionDescription; - private string changedField; - private string valueBefore; - private string valueAfter; - private string comment; - private string ipAddress; - } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPaperLetter.cs b/Basic/Types/BasicPaperLetter.cs index d69ed4a2..dc792994 100644 --- a/Basic/Types/BasicPaperLetter.cs +++ b/Basic/Types/BasicPaperLetter.cs @@ -4,27 +4,29 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPaperLetter: IHasIdentity + public class BasicPaperLetter : IHasIdentity { - public BasicPaperLetter (int paperLetterId, int organizationId, string fromName, string replyAddress, - DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId, DateTime uploadedDateTime) + public BasicPaperLetter(int paperLetterId, int organizationId, string fromName, string replyAddress, + DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId, + DateTime uploadedDateTime) { - this.PaperLetterId = paperLetterId; - this.OrganizationId = organizationId; - this.FromName = fromName; - this.ReplyAddress = replyAddress; - this.ReceivedDate = receivedDate; - this.ToPersonId = toPersonId; - this.ToPersonInRole = toPersonInRole; - this.Personal = personal; - this.UploadedByPersonId = uploadedByPersonId; - this.UploadedDateTime = uploadedDateTime; + PaperLetterId = paperLetterId; + OrganizationId = organizationId; + FromName = fromName; + ReplyAddress = replyAddress; + ReceivedDate = receivedDate; + ToPersonId = toPersonId; + ToPersonInRole = toPersonInRole; + Personal = personal; + UploadedByPersonId = uploadedByPersonId; + UploadedDateTime = uploadedDateTime; } - 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) + 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) { // empty copy ctor } @@ -45,9 +47,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.PaperLetterId; } + get { return PaperLetterId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicParley.cs b/Basic/Types/BasicParley.cs index d23261f1..f3e0dae5 100644 --- a/Basic/Types/BasicParley.cs +++ b/Basic/Types/BasicParley.cs @@ -3,32 +3,38 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicParley: IHasIdentity + public class BasicParley : IHasIdentity { - 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, + 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) { - this.ParleyId = parleyId; - this.OrganizationId = organizationId; - this.PersonId = personId; - this.BudgetId = budgetId; - this.CreatedDateTime = createdDateTime; - this.Open = open; - this.Attested = attested; - this.Name = name; - this.GeographyId = geographyId; - this.Description = description; - this.InformationUrl = informationUrl; - this.StartDate = startDate; - this.EndDate = endDate; - this.BudgetCents = budgetCents; - this.GuaranteeCents = guaranteeCents; - this.AttendanceFeeCents = attendanceFeeCents; - this.ClosedDateTime = closedDateTime; + ParleyId = parleyId; + OrganizationId = organizationId; + PersonId = personId; + BudgetId = budgetId; + CreatedDateTime = createdDateTime; + Open = open; + Attested = attested; + Name = name; + GeographyId = geographyId; + Description = description; + InformationUrl = informationUrl; + StartDate = startDate; + EndDate = endDate; + BudgetCents = budgetCents; + GuaranteeCents = guaranteeCents; + AttendanceFeeCents = attendanceFeeCents; + ClosedDateTime = closedDateTime; } - 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, original.BudgetCents, original.GuaranteeCents, original.AttendanceFeeCents, original.ClosedDateTime) + 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, + original.BudgetCents, original.GuaranteeCents, original.AttendanceFeeCents, original.ClosedDateTime) { // empty copy ctor } @@ -54,7 +60,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.ParleyId; } + get { return ParleyId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicParleyAttendee.cs b/Basic/Types/BasicParleyAttendee.cs index 89a0be3d..7dc0169d 100644 --- a/Basic/Types/BasicParleyAttendee.cs +++ b/Basic/Types/BasicParleyAttendee.cs @@ -3,22 +3,26 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicParleyAttendee: IHasIdentity + public class BasicParleyAttendee : IHasIdentity { - public BasicParleyAttendee (int parleyAttendeeId, int parleyId, int personId, DateTime signupDateTime, bool active, DateTime cancelDateTime, bool invoiced, int outboundInvoiceId, bool isGuest) + public BasicParleyAttendee(int parleyAttendeeId, int parleyId, int personId, DateTime signupDateTime, + bool active, DateTime cancelDateTime, bool invoiced, int outboundInvoiceId, bool isGuest) { - this.ParleyAttendeeId = parleyAttendeeId; - this.ParleyId = parleyId; - this.PersonId = personId; - this.SignupDateTime = signupDateTime; - this.Active = active; - this.CancelDateTime = cancelDateTime; - this.Invoiced = invoiced; - this.OutboundInvoiceId = outboundInvoiceId; + ParleyAttendeeId = parleyAttendeeId; + ParleyId = parleyId; + PersonId = personId; + SignupDateTime = signupDateTime; + Active = active; + CancelDateTime = cancelDateTime; + Invoiced = invoiced; + OutboundInvoiceId = outboundInvoiceId; } public BasicParleyAttendee(BasicParleyAttendee original) - : this (original.ParleyAttendeeId, original.ParleyId, original.PersonId, original.SignupDateTime, original.Active, original.CancelDateTime, original.Invoiced, original.OutboundInvoiceId, original.IsGuest) + : this( + original.ParleyAttendeeId, original.ParleyId, original.PersonId, original.SignupDateTime, + original.Active, original.CancelDateTime, original.Invoiced, original.OutboundInvoiceId, + original.IsGuest) { // empty copy ctor } @@ -35,7 +39,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.ParleyAttendeeId; } + get { return ParleyAttendeeId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicParleyOption.cs b/Basic/Types/BasicParleyOption.cs index 778d7077..4ec39789 100644 --- a/Basic/Types/BasicParleyOption.cs +++ b/Basic/Types/BasicParleyOption.cs @@ -3,19 +3,20 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicParleyOption: IHasIdentity + 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) { - this.ParleyOptionId = parleyOptionId; - this.ParleyId = parleyId; - this.Description = description; - this.AmountCents = amountCents; - this.Active = active; + ParleyOptionId = parleyOptionId; + ParleyId = parleyId; + Description = description; + AmountCents = amountCents; + Active = active; } - public BasicParleyOption (BasicParleyOption original) - : this (original.ParleyOptionId, original.ParleyId, original.Description, original.AmountCents, original.Active) + public BasicParleyOption(BasicParleyOption original) + : this( + original.ParleyOptionId, original.ParleyId, original.Description, original.AmountCents, original.Active) { // empty copy ctor } @@ -28,7 +29,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.ParleyOptionId; } + get { return ParleyOptionId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPayment.cs b/Basic/Types/BasicPayment.cs index 6b15e245..f4f2ee68 100644 --- a/Basic/Types/BasicPayment.cs +++ b/Basic/Types/BasicPayment.cs @@ -3,22 +3,25 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPayment: IHasIdentity + public class BasicPayment : IHasIdentity { - public BasicPayment (int paymentId, int paymentGroupId, Int64 amountCents, string reference, string fromAccount, string key, bool hasImage, int outboundInvoiceId) + public BasicPayment(int paymentId, int paymentGroupId, Int64 amountCents, string reference, string fromAccount, + string key, bool hasImage, int outboundInvoiceId) { - this.PaymentId = paymentId; - this.PaymentGroupId = paymentGroupId; - this.AmountCents = amountCents; - this.Reference = reference; - this.FromAccount = fromAccount; - this.Key = key; - this.HasImage = hasImage; - this.OutboundInvoiceId = outboundInvoiceId; + PaymentId = paymentId; + PaymentGroupId = paymentGroupId; + AmountCents = amountCents; + Reference = reference; + FromAccount = fromAccount; + Key = key; + HasImage = hasImage; + OutboundInvoiceId = outboundInvoiceId; } - public BasicPayment (BasicPayment original) - : this (original.PaymentId, original.PaymentGroupId, original.AmountCents, original.Reference, original.FromAccount, original.Key, original.HasImage, original.OutboundInvoiceId) + public BasicPayment(BasicPayment original) + : this( + original.PaymentId, original.PaymentGroupId, original.AmountCents, original.Reference, + original.FromAccount, original.Key, original.HasImage, original.OutboundInvoiceId) { // empty copy ctor } @@ -28,13 +31,13 @@ namespace Swarmops.Basic.Types public Int64 AmountCents { get; private set; } public string Reference { get; private set; } public string FromAccount { get; private set; } - public string Key { get; private set; } // may need to expand with URL or similar later + public string Key { get; private set; } // may need to expand with URL or similar later public bool HasImage { get; private set; } public int OutboundInvoiceId { get; protected set; } public int Identity { - get { return this.PaymentId; } + get { return PaymentId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPaymentCode.cs b/Basic/Types/BasicPaymentCode.cs index 73ba05d0..f67e5f85 100644 --- a/Basic/Types/BasicPaymentCode.cs +++ b/Basic/Types/BasicPaymentCode.cs @@ -5,8 +5,23 @@ namespace Swarmops.Basic.Types { public class BasicPaymentCode : IHasIdentity { - public BasicPaymentCode (int paymentCodeId, string paymentCode, string issuedToPhoneNumber, int issuedToPersonId, - bool claimed) + private readonly int issuedToPersonId; + private readonly string issuedToPhoneNumber; + private readonly string paymentCode; + private readonly int paymentCodeId; + private bool claimed; + + #region IHasIdentity Members + + public int Identity + { + get { return PaymentCodeId; } + } + + #endregion + + public BasicPaymentCode(int paymentCodeId, string paymentCode, string issuedToPhoneNumber, int issuedToPersonId, + bool claimed) { this.paymentCodeId = paymentCodeId; this.paymentCode = paymentCode; @@ -15,7 +30,7 @@ namespace Swarmops.Basic.Types this.claimed = claimed; } - public BasicPaymentCode (BasicPaymentCode original) + public BasicPaymentCode(BasicPaymentCode original) : this( original.paymentCodeId, original.paymentCode, original.issuedToPhoneNumber, original.issuedToPersonId, original.claimed) @@ -50,42 +65,24 @@ namespace Swarmops.Basic.Types } + public PaymentCodeIssueType IssueType + { + get + { + if (this.issuedToPersonId == 0) + { + return PaymentCodeIssueType.Phone; + } + return PaymentCodeIssueType.Person; + } + } + protected void SetClaimed() { this.claimed = true; } - public PaymentCodeIssueType IssueType - { - get - { - if (issuedToPersonId == 0) - { - return PaymentCodeIssueType.Phone; - } - else - { - return PaymentCodeIssueType.Person; - } - } - } - - - private int paymentCodeId; - private string paymentCode; - private string issuedToPhoneNumber; - private int issuedToPersonId; - private bool claimed; //private bool balanced; - - #region IHasIdentity Members - - public int Identity - { - get { return this.PaymentCodeId; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicPaymentGroup.cs b/Basic/Types/BasicPaymentGroup.cs index 654c86fb..76bbc27f 100644 --- a/Basic/Types/BasicPaymentGroup.cs +++ b/Basic/Types/BasicPaymentGroup.cs @@ -3,23 +3,26 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPaymentGroup: IHasIdentity + public class BasicPaymentGroup : IHasIdentity { - public BasicPaymentGroup (int paymentGroupId, int organizationId, DateTime dateTime, int currencyId, Int64 amountCents, string tag, int createdByPersonId, DateTime createdDateTime, bool open) + public BasicPaymentGroup(int paymentGroupId, int organizationId, DateTime dateTime, int currencyId, + Int64 amountCents, string tag, int createdByPersonId, DateTime createdDateTime, bool open) { - this.PaymentGroupId = paymentGroupId; - this.OrganizationId = organizationId; - this.Tag = tag; - this.DateTime = dateTime; - this.AmountCents = amountCents; - this.CurrencyId = currencyId; - this.CreatedByPersonId = createdByPersonId; - this.CreatedDateTime = createdDateTime; - this.Open = open; + PaymentGroupId = paymentGroupId; + OrganizationId = organizationId; + Tag = tag; + DateTime = dateTime; + AmountCents = amountCents; + CurrencyId = currencyId; + CreatedByPersonId = createdByPersonId; + CreatedDateTime = createdDateTime; + Open = open; } - public BasicPaymentGroup (BasicPaymentGroup original) - : this(original.PaymentGroupId, original.OrganizationId, original.DateTime, original.CurrencyId, original.AmountCents, original.Tag, original.CreatedByPersonId, original.CreatedDateTime, original.Open) + public BasicPaymentGroup(BasicPaymentGroup original) + : this( + original.PaymentGroupId, original.OrganizationId, original.DateTime, original.CurrencyId, + original.AmountCents, original.Tag, original.CreatedByPersonId, original.CreatedDateTime, original.Open) { // empty copy ctor } @@ -36,7 +39,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.PaymentGroupId; } + get { return PaymentGroupId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPaymentInformation.cs b/Basic/Types/BasicPaymentInformation.cs index b2d2879c..36d97c2b 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) { - this.Type = type; - this.Data = 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 } @@ -22,45 +22,55 @@ namespace Swarmops.Basic.Types public enum PaymentInformationType { Unknown = 0, + /// - /// The payer's name as supplied by the bank. + /// The payer's name as supplied by the bank. /// Name, + /// - /// The payer's street as and if supplied by the bank. + /// The payer's street as and if supplied by the bank. /// Street, + /// - /// The payer's postal code as and if supplied by the bank. + /// The payer's postal code as and if supplied by the bank. /// PostalCode, + /// - /// The payer's city as and if supplied by the bank. + /// The payer's city as and if supplied by the bank. /// City, + /// - /// The payer's org# or person# as and if supplied by the bank. + /// The payer's org# or person# as and if supplied by the bank. /// OrgNumber, + /// - /// Freeform information supplied by payer. + /// Freeform information supplied by payer. /// Freeform, + /// - /// The payer's country as and if supplied by the bank. + /// The payer's country as and if supplied by the bank. /// Country, + /// - /// The payer's country code as and if supplied by the bank. + /// The payer's country code as and if supplied by the bank. /// CountryCode, + /// - /// Payer's email as and if supplied by the bank. + /// Payer's email as and if supplied by the bank. /// Email, + /// - /// Information needed to perform a future refund. + /// Information needed to perform a future refund. /// RefundInformation } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPayout.cs b/Basic/Types/BasicPayout.cs index 92d61745..fdc00535 100644 --- a/Basic/Types/BasicPayout.cs +++ b/Basic/Types/BasicPayout.cs @@ -3,32 +3,32 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPayout: IHasIdentity + 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) { - this.PayoutId = payoutId; - this.OrganizationId = organizationId; - this.Bank = bank; - this.Account = account; - this.Reference = reference; - this.AmountCents = amountCents; - this.ExpectedTransactionDate = expectedTransactionDate; - this.Open = open; - this.CreatedDateTime = createdDateTime; - this.CreatedByPersonId = createdByPersonId; + PayoutId = payoutId; + OrganizationId = organizationId; + Bank = bank; + Account = account; + Reference = reference; + AmountCents = amountCents; + ExpectedTransactionDate = expectedTransactionDate; + Open = open; + CreatedDateTime = createdDateTime; + CreatedByPersonId = createdByPersonId; } 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) + original.Reference, original.AmountCents, original.ExpectedTransactionDate, original.Open, + original.CreatedDateTime, original.CreatedByPersonId) { // empty copy ctor } - + public int PayoutId { get; private set; } public int OrganizationId { get; protected set; } public string Bank { get; protected set; } @@ -44,9 +44,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.PayoutId; } + get { return PayoutId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPayrollAdjustment.cs b/Basic/Types/BasicPayrollAdjustment.cs index 6d860de9..cc979af2 100644 --- a/Basic/Types/BasicPayrollAdjustment.cs +++ b/Basic/Types/BasicPayrollAdjustment.cs @@ -3,23 +3,26 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPayrollAdjustment: IHasIdentity + public class BasicPayrollAdjustment : IHasIdentity { - public BasicPayrollAdjustment (int payrollAdjustmentId, int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, + public BasicPayrollAdjustment(int payrollAdjustmentId, int payrollItemId, PayrollAdjustmentType type, + Int64 amountCents, string description, bool open, int salaryId) { - this.PayrollAdjustmentId = payrollAdjustmentId; - this.PayrollItemId = payrollItemId; - this.Type = type; - this.AmountCents = amountCents; - this.Description = description; - this.Open = open; - this.SalaryId = salaryId; + PayrollAdjustmentId = payrollAdjustmentId; + PayrollItemId = payrollItemId; + Type = type; + AmountCents = amountCents; + Description = description; + Open = open; + SalaryId = salaryId; } - public BasicPayrollAdjustment (BasicPayrollAdjustment original) - : this (original.PayrollAdjustmentId, original.PayrollItemId, original.Type, original.AmountCents, original.Description, original.Open, original.SalaryId) + public BasicPayrollAdjustment(BasicPayrollAdjustment original) + : this( + original.PayrollAdjustmentId, original.PayrollItemId, original.Type, original.AmountCents, + original.Description, original.Open, original.SalaryId) { // empty copy ctor } @@ -32,9 +35,10 @@ namespace Swarmops.Basic.Types public string Description { get; private set; } public bool Open { get; protected set; } public int SalaryId { get; protected set; } + public int Identity { - get { return this.PayrollAdjustmentId; } + get { return PayrollAdjustmentId; } } } @@ -42,16 +46,18 @@ namespace Swarmops.Basic.Types public enum PayrollAdjustmentType { /// - /// Undefined value + /// Undefined value /// Unknown = 0, + /// - /// Adjustment to salary BEFORE tax (sick leave, etc) + /// Adjustment to salary BEFORE tax (sick leave, etc) /// GrossAdjustment = 1, + /// - /// Adjustment to salary AFTER tax (expenses, etc) + /// Adjustment to salary AFTER tax (expenses, etc) /// NetAdjustment = 2 } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPayrollItem.cs b/Basic/Types/BasicPayrollItem.cs index 09dd0c0b..87a33227 100644 --- a/Basic/Types/BasicPayrollItem.cs +++ b/Basic/Types/BasicPayrollItem.cs @@ -3,81 +3,93 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicPayrollItem: IHasIdentity + public class BasicPayrollItem : IHasIdentity { - public BasicPayrollItem (int payrollItemId, int personId, int organizationId, int countryId, DateTime employedDate, + 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) { - this.PayrollItemId = payrollItemId; - this.PersonId = personId; - this.OrganizationId = organizationId; - this.CountryId = countryId; - this.EmployedDate = employedDate; - this.ReportsToPersonId = reportsToPersonId; - this.BaseSalaryCents = baseSalaryCents; - this.BudgetId = budgetId; - this.Open = open; - this.TerminatedDate = terminatedDate; - this.SubtractiveTaxLevelId = subtractiveTaxLevelId; - this.AdditiveTaxLevel = additiveTaxLevel; + PayrollItemId = payrollItemId; + PersonId = personId; + OrganizationId = organizationId; + CountryId = countryId; + EmployedDate = employedDate; + ReportsToPersonId = reportsToPersonId; + BaseSalaryCents = baseSalaryCents; + BudgetId = budgetId; + Open = open; + TerminatedDate = terminatedDate; + SubtractiveTaxLevelId = subtractiveTaxLevelId; + AdditiveTaxLevel = additiveTaxLevel; } - 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) + 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) { // empty copy constructor } /// - /// Gets the identity of the payroll item. Also accessible through Identity. + /// Gets the identity of the payroll item. Also accessible through Identity. /// public int PayrollItemId { get; private set; } + /// - /// The employed person Id. + /// The employed person Id. /// public int PersonId { get; private set; } + /// - /// The employing organization. + /// The employing organization. /// public int OrganizationId { get; private set; } + /// - /// The employment country (for tax laws and such). + /// The employment country (for tax laws and such). /// public int CountryId { get; private set; } + /// - /// The date of employment. + /// The date of employment. /// public DateTime EmployedDate { get; private set; } + /// - /// The person above this person in the org chart. + /// The person above this person in the org chart. /// public int ReportsToPersonId { get; protected set; } + /// - /// The base gross montly salary in the local currency. + /// The base gross montly salary in the local currency. /// public Int64 BaseSalaryCents { get; protected set; } + /// - /// The budget charged with the costs of this employment. + /// The budget charged with the costs of this employment. /// public int BudgetId { get; protected set; } + /// - /// True if this employment is still active. + /// True if this employment is still active. /// public bool Open { get; protected set; } + /// - /// If closed, this field contains the date the employment ended. + /// If closed, this field contains the date the employment ended. /// public DateTime TerminatedDate { get; protected set; } + /// - /// The tax level code of the country of employment. Subtracted from gross salary to get net salary. + /// The tax level code of the country of employment. Subtracted from gross salary to get net salary. /// public int SubtractiveTaxLevelId { get; protected set; } + /// - /// The tax level, as a fraction, paid by the organization on top of the gross salary. + /// The tax level, as a fraction, paid by the organization on top of the gross salary. /// public double AdditiveTaxLevel { get; protected set; } @@ -85,9 +97,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.PayrollItemId; } + get { return PayrollItemId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPermission.cs b/Basic/Types/BasicPermission.cs index 9d2b8006..a244e0a4 100644 --- a/Basic/Types/BasicPermission.cs +++ b/Basic/Types/BasicPermission.cs @@ -4,13 +4,13 @@ namespace Swarmops.Basic.Types { public class BasicPermission { - public RoleType RoleType; public Permission PermissionType; + public RoleType RoleType; - public BasicPermission (RoleType pRoleType, Permission pPermissionType) + public BasicPermission(RoleType pRoleType, Permission pPermissionType) { - RoleType = pRoleType; - PermissionType = pPermissionType; + this.RoleType = pRoleType; + this.PermissionType = pPermissionType; } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicPerson.cs b/Basic/Types/BasicPerson.cs index 17e67740..f721c81e 100644 --- a/Basic/Types/BasicPerson.cs +++ b/Basic/Types/BasicPerson.cs @@ -4,39 +4,37 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - - [Serializable] public class BasicPerson : IEmailPerson, IHasIdentity { - public BasicPerson (string name, string email) + public BasicPerson(string name, string email) { - this.Name = name; - this.Email = email; + Name = name; + Email = email; } - 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) + 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) { - this.PersonId = personId; - this.PasswordHash = passwordHash; - this.Name = name; - this.Email = email; - this.Street = street; - this.PostalCode = postalCode; - this.CityName = cityName; - this.CountryId = countryId; - this.Phone = phone; - this.GeographyId = geographyId; - this.Birthdate = birthdate; - this.Gender = gender; + PersonId = personId; + PasswordHash = passwordHash; + Name = name; + Email = email; + Street = street; + PostalCode = postalCode; + CityName = cityName; + CountryId = countryId; + Phone = phone; + GeographyId = geographyId; + Birthdate = birthdate; + Gender = gender; } - 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) + 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) { } @@ -53,8 +51,6 @@ namespace Swarmops.Basic.Types public int PersonId { get; private set; } - public string Name { get; protected set; } - public string Email { get; protected set; } public string Street { get; protected set; } public string PostalCode { get; protected set; } public string CityName { get; protected set; } @@ -64,14 +60,13 @@ namespace Swarmops.Basic.Types public int GeographyId { get; protected set; } public int CountryId { get; protected set; } public PersonGender Gender { get; protected set; } + public string Name { get; protected set; } + public string Email { get; protected set; } public int Identity { get { return PersonId; } } - - - } } \ No newline at end of file diff --git a/Basic/Types/BasicPersonRole.cs b/Basic/Types/BasicPersonRole.cs index 8782d112..45d21849 100644 --- a/Basic/Types/BasicPersonRole.cs +++ b/Basic/Types/BasicPersonRole.cs @@ -5,18 +5,33 @@ namespace Swarmops.Basic.Types { public class BasicPersonRole : IHasIdentity { - protected BasicPersonRole () + private readonly int geographyId; + private readonly int organizationId; + private readonly int personId; + private readonly int roleId; + private readonly RoleType type; + + #region IHasIdentity Members + + public int Identity + { + get { return RoleId; } + } + + #endregion + + protected BasicPersonRole() { } /// - /// Normal constructor. + /// Normal constructor. /// /// The person Id. /// 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; @@ -26,9 +41,9 @@ namespace Swarmops.Basic.Types } /// - /// Copy constructor. + /// Copy constructor. /// - public BasicPersonRole (BasicPersonRole original) + public BasicPersonRole(BasicPersonRole original) : this(original.roleId, original.personId, original.type, original.organizationId, original.geographyId) { } @@ -58,20 +73,5 @@ namespace Swarmops.Basic.Types { get { return this.geographyId; } } - - private int roleId; - private int personId; - private RoleType type; - private int organizationId; - private int geographyId; - - #region IHasIdentity Members - - public int Identity - { - get { return this.RoleId; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicPostalCode.cs b/Basic/Types/BasicPostalCode.cs index 414e87dd..366126bc 100644 --- a/Basic/Types/BasicPostalCode.cs +++ b/Basic/Types/BasicPostalCode.cs @@ -7,10 +7,10 @@ namespace Swarmops.Basic.Types { public BasicPostalCode(int postalCodeId, string postalCode, int cityId, int countryId) { - this.PostalCodeId = postalCodeId; - this.PostalCode = postalCode.Replace(" ", ""); - this.CityId = cityId; - this.CountryId = countryId; + PostalCodeId = postalCodeId; + PostalCode = postalCode.Replace(" ", ""); + CityId = cityId; + CountryId = countryId; } public BasicPostalCode(BasicPostalCode original) @@ -18,15 +18,15 @@ namespace Swarmops.Basic.Types { } - [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 } public int PostalCodeId { get; private set; } - public string PostalCode { get; private set; } // any whitespace removed + public string PostalCode { get; private set; } // any whitespace removed public int CityId { get; protected set; } public int CountryId { get; protected set; } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicRefund.cs b/Basic/Types/BasicRefund.cs index fac6383c..39ad2415 100644 --- a/Basic/Types/BasicRefund.cs +++ b/Basic/Types/BasicRefund.cs @@ -3,21 +3,24 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicRefund: IHasIdentity + public class BasicRefund : IHasIdentity { - public BasicRefund (int refundId, int paymentId, bool open, Int64 amountCents, int createdByPersonId, DateTime createdDateTime, DateTime closedDateTime) + public BasicRefund(int refundId, int paymentId, bool open, Int64 amountCents, int createdByPersonId, + DateTime createdDateTime, DateTime closedDateTime) { - this.RefundId = refundId; - this.PaymentId = paymentId; - this.Open = open; - this.AmountCents = amountCents; - this.CreatedByPersonId = createdByPersonId; - this.CreatedDateTime = createdDateTime; - this.ClosedDateTime = closedDateTime; + RefundId = refundId; + PaymentId = paymentId; + Open = open; + AmountCents = amountCents; + CreatedByPersonId = createdByPersonId; + CreatedDateTime = createdDateTime; + ClosedDateTime = closedDateTime; } public BasicRefund(BasicRefund original) - :this (original.RefundId, original.PaymentId, original.Open, original.AmountCents, original.CreatedByPersonId, original.CreatedDateTime, original.ClosedDateTime) + : this( + original.RefundId, original.PaymentId, original.Open, original.AmountCents, original.CreatedByPersonId, + original.CreatedDateTime, original.ClosedDateTime) { // Empty copy ctor } @@ -32,7 +35,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.RefundId; } + get { return RefundId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicReporter.cs b/Basic/Types/BasicReporter.cs index 7bd972e6..1add44ff 100644 --- a/Basic/Types/BasicReporter.cs +++ b/Basic/Types/BasicReporter.cs @@ -4,7 +4,21 @@ namespace Swarmops.Basic.Types { public class BasicReporter : IEmailPerson, IHasIdentity { - public BasicReporter (int reporterId, string name, string email, int[] mediaCategoryIds) + private readonly string email; + private readonly string name; + private readonly int reporterId; + private int[] mediaCategoryIds; // null if not loaded + + #region IHasIdentity Members + + public int Identity + { + get { return ReporterId; } + } + + #endregion + + public BasicReporter(int reporterId, string name, string email, int[] mediaCategoryIds) { this.reporterId = reporterId; this.name = name; @@ -12,17 +26,17 @@ namespace Swarmops.Basic.Types this.mediaCategoryIds = mediaCategoryIds; } - public BasicReporter (BasicReporter original) : + public BasicReporter(BasicReporter original) : this(original.reporterId, original.name, original.email, original.mediaCategoryIds) { } public BasicReporter() { - reporterId = 0; - name = string.Empty; - email = string.Empty; - mediaCategoryIds = new int[0]; + this.reporterId = 0; + this.name = string.Empty; + this.email = string.Empty; + this.mediaCategoryIds = new int[0]; } public int ReporterId @@ -30,6 +44,12 @@ namespace Swarmops.Basic.Types get { return this.reporterId; } } + public int[] MediaCategoryIds + { + get { return this.mediaCategoryIds; } + set { this.mediaCategoryIds = value; } // this is an exception to the norm + } + public string Name { get { return this.name; } @@ -39,26 +59,5 @@ namespace Swarmops.Basic.Types { get { return this.email; } } - - public int[] MediaCategoryIds - { - get { return this.mediaCategoryIds; } - set { this.mediaCategoryIds = value; } // this is an exception to the norm - } - - - private int reporterId; - private string name; - private string email; - private int[] mediaCategoryIds; // null if not loaded - - #region IHasIdentity Members - - public int Identity - { - get { return ReporterId; } - } - - #endregion } } \ No newline at end of file diff --git a/Basic/Types/BasicSalary.cs b/Basic/Types/BasicSalary.cs index 859dec0e..81f5a339 100644 --- a/Basic/Types/BasicSalary.cs +++ b/Basic/Types/BasicSalary.cs @@ -3,28 +3,32 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicSalary: IHasIdentity + public class BasicSalary : IHasIdentity { - public BasicSalary (int salaryId, int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, + public BasicSalary(int salaryId, int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, + Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents, bool attested, bool netPaid, bool taxPaid, bool open) { - this.SalaryId = salaryId; - this.PayrollItemId = payrollItemId; - this.PayoutDate = payoutDate; - this.BaseSalaryCents = baseSalaryCents; - this.NetSalaryCents = netSalaryCents; - this.SubtractiveTaxCents = subtractiveTaxCents; - this.AdditiveTaxCents = additiveTaxCents; - this.Attested = attested; - this.NetPaid = netPaid; - this.TaxPaid = taxPaid; - this.Open = open; + SalaryId = salaryId; + PayrollItemId = payrollItemId; + PayoutDate = payoutDate; + BaseSalaryCents = baseSalaryCents; + NetSalaryCents = netSalaryCents; + SubtractiveTaxCents = subtractiveTaxCents; + AdditiveTaxCents = additiveTaxCents; + Attested = attested; + NetPaid = netPaid; + TaxPaid = taxPaid; + Open = open; } - public BasicSalary (BasicSalary original) - :this (original.SalaryId, original.PayrollItemId, original.PayoutDate, original.BaseSalaryCents, original.NetSalaryCents, - original.SubtractiveTaxCents, original.AdditiveTaxCents, original.Attested, original.NetPaid, original.TaxPaid, - original.Open) + public BasicSalary(BasicSalary original) + : this( + original.SalaryId, original.PayrollItemId, original.PayoutDate, original.BaseSalaryCents, + original.NetSalaryCents, + original.SubtractiveTaxCents, original.AdditiveTaxCents, original.Attested, original.NetPaid, + original.TaxPaid, + original.Open) { // empty copy constructor } @@ -45,9 +49,9 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.SalaryId; } + get { return SalaryId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicSupplier.cs b/Basic/Types/BasicSupplier.cs index 0e4a6968..31a8b4c1 100644 --- a/Basic/Types/BasicSupplier.cs +++ b/Basic/Types/BasicSupplier.cs @@ -3,20 +3,24 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicSupplier: IHasIdentity + public class BasicSupplier : IHasIdentity { - public BasicSupplier (int supplierId, string name, string email, string passwordHash, string bankAccount, DateTime createdDateTime, int createdByPersonId) + public BasicSupplier(int supplierId, string name, string email, string passwordHash, string bankAccount, + DateTime createdDateTime, int createdByPersonId) { - this.SupplierId = supplierId; - this.Name = name; - this.Email = email; - this.PasswordHash = passwordHash; - this.BankAccount = bankAccount; - this.CreatedDateTime = createdDateTime; - this.CreatedByPersonId = createdByPersonId; + SupplierId = supplierId; + Name = name; + Email = email; + PasswordHash = passwordHash; + BankAccount = bankAccount; + CreatedDateTime = createdDateTime; + CreatedByPersonId = createdByPersonId; } - public BasicSupplier(BasicSupplier original): this (original.SupplierId, original.Name, original.Email, original.PasswordHash, original.BankAccount, original.CreatedDateTime, original.CreatedByPersonId) + public BasicSupplier(BasicSupplier original) + : this( + original.SupplierId, original.Name, original.Email, original.PasswordHash, original.BankAccount, + original.CreatedDateTime, original.CreatedByPersonId) { // empty copy ctor } @@ -31,7 +35,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.SupplierId; } + get { return SupplierId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicSwarmopsLogEntry.cs b/Basic/Types/BasicSwarmopsLogEntry.cs index 82a55339..9819e671 100644 --- a/Basic/Types/BasicSwarmopsLogEntry.cs +++ b/Basic/Types/BasicSwarmopsLogEntry.cs @@ -3,19 +3,22 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types { - public class BasicSwarmopsLogEntry: IHasIdentity + public class BasicSwarmopsLogEntry : IHasIdentity { - public BasicSwarmopsLogEntry (int swarmopsLogEntryId, int personId, DateTime dateTime, int entryTypeId, string entryXml) + public BasicSwarmopsLogEntry(int swarmopsLogEntryId, int personId, DateTime dateTime, int entryTypeId, + string entryXml) { - this.SwarmopsLogEntryId = swarmopsLogEntryId; - this.PersonId = personId; - this.DateTime = dateTime; - this.EntryTypeId = entryTypeId; - this.EntryXml = entryXml; + SwarmopsLogEntryId = swarmopsLogEntryId; + PersonId = personId; + DateTime = dateTime; + EntryTypeId = entryTypeId; + EntryXml = entryXml; } - public BasicSwarmopsLogEntry (BasicSwarmopsLogEntry original) - : this (original.SwarmopsLogEntryId, original.PersonId, original.DateTime, original.EntryTypeId, original.EntryXml) + public BasicSwarmopsLogEntry(BasicSwarmopsLogEntry original) + : this( + original.SwarmopsLogEntryId, original.PersonId, original.DateTime, original.EntryTypeId, + original.EntryXml) { // copy ctor } @@ -28,7 +31,7 @@ namespace Swarmops.Basic.Types public int Identity { - get { return this.SwarmopsLogEntryId; } + get { return SwarmopsLogEntryId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/BasicUptakeGeography.cs b/Basic/Types/BasicUptakeGeography.cs index 72664fe5..05d92a9f 100644 --- a/Basic/Types/BasicUptakeGeography.cs +++ b/Basic/Types/BasicUptakeGeography.cs @@ -1,36 +1,36 @@ namespace Swarmops.Basic.Types { - - public class BasicUptakeGeography + public class BasicUptakeGeography + { + private int geoId; + private int orgId; + + public BasicUptakeGeography(int pOrgId, int pGeoId) { - int orgId; - public int OrgId - { - get { return orgId; } - set { orgId = value; } - } - int geoId; - public int GeoId - { - get { return geoId; } - set { geoId = value; } - } - - public BasicUptakeGeography (int pOrgId, int pGeoId) - { - orgId = pOrgId; - geoId = pGeoId; - } - - public BasicUptakeGeography () - { - } - - public BasicUptakeGeography (BasicUptakeGeography other) - { - this.orgId = other.orgId; - this.geoId = other.geoId; - } + this.orgId = pOrgId; + this.geoId = pGeoId; } -} + public BasicUptakeGeography() + { + } + + public BasicUptakeGeography(BasicUptakeGeography other) + { + this.orgId = other.orgId; + this.geoId = other.geoId; + } + + public int OrgId + { + get { return this.orgId; } + set { this.orgId = value; } + } + + public int GeoId + { + get { return this.geoId; } + set { this.geoId = value; } + } + } +} \ No newline at end of file diff --git a/Basic/Types/BasicVolunteer.cs b/Basic/Types/BasicVolunteer.cs index cd40e63d..0689fc4e 100644 --- a/Basic/Types/BasicVolunteer.cs +++ b/Basic/Types/BasicVolunteer.cs @@ -5,8 +5,16 @@ namespace Swarmops.Basic.Types { public class BasicVolunteer : IHasIdentity { - public BasicVolunteer (int volunteerId, int personId, int ownerPersonId, DateTime openedDateTime, - bool open, DateTime closedDateTime, string closingComments) + private readonly DateTime closedDateTime; + private readonly string closingComments; + private readonly bool open; + private readonly DateTime openedDateTime; + private readonly int ownerPersonId; + private readonly int personId; + private readonly int volunteerId; + + public BasicVolunteer(int volunteerId, int personId, int ownerPersonId, DateTime openedDateTime, + bool open, DateTime closedDateTime, string closingComments) { this.volunteerId = volunteerId; this.personId = personId; @@ -17,22 +25,13 @@ namespace Swarmops.Basic.Types this.closingComments = closingComments; } - public BasicVolunteer (BasicVolunteer original) + public BasicVolunteer(BasicVolunteer original) : this(original.volunteerId, original.personId, original.ownerPersonId, original.openedDateTime, - original.open, original.closedDateTime, original.closingComments) + original.open, original.closedDateTime, original.closingComments) { // copy ctor } - - private int volunteerId; - private int personId; - private int ownerPersonId; - private DateTime openedDateTime; - private bool open; - private DateTime closedDateTime; - private string closingComments; - public int VolunteerId { get { return this.volunteerId; } diff --git a/Basic/Types/BasicVolunteerRole.cs b/Basic/Types/BasicVolunteerRole.cs index 5b37bb7a..31652e92 100644 --- a/Basic/Types/BasicVolunteerRole.cs +++ b/Basic/Types/BasicVolunteerRole.cs @@ -5,8 +5,16 @@ namespace Swarmops.Basic.Types { public class BasicVolunteerRole : IHasIdentity { - public BasicVolunteerRole (int volunteerRoleId, int volunteerId, int organizationId, int geographyId, - RoleType roleType, bool open, bool assigned) + private readonly bool assigned; + private readonly int geographyId; + private readonly bool open; + private readonly int organizationId; + private readonly RoleType roleType; + private readonly int volunteerId; + private readonly int volunteerRoleId; + + public BasicVolunteerRole(int volunteerRoleId, int volunteerId, int organizationId, int geographyId, + RoleType roleType, bool open, bool assigned) { this.volunteerRoleId = volunteerRoleId; this.volunteerId = volunteerId; @@ -17,21 +25,12 @@ namespace Swarmops.Basic.Types this.assigned = assigned; } - public BasicVolunteerRole (BasicVolunteerRole original) + public BasicVolunteerRole(BasicVolunteerRole original) : this(original.volunteerRoleId, original.volunteerId, original.organizationId, original.geographyId, - original.roleType, original.open, original.assigned) + original.roleType, original.open, original.assigned) { } - - private int volunteerRoleId; - private int volunteerId; - private int organizationId; - private int geographyId; - private RoleType roleType; - private bool open; - private bool assigned; - public int VolunteerRoleId { get { return this.volunteerRoleId; } diff --git a/Basic/Types/Communications/BasicAutoMail.cs b/Basic/Types/Communications/BasicAutoMail.cs index d489049d..a5ba80ad 100644 --- a/Basic/Types/Communications/BasicAutoMail.cs +++ b/Basic/Types/Communications/BasicAutoMail.cs @@ -5,11 +5,19 @@ namespace Swarmops.Basic.Types.Communications { public class BasicAutoMail : IHasIdentity { + private readonly int authorPersonId; + private readonly int autoMailId; + private readonly int geographyId; + private readonly int organizationId; + private readonly string title; + private readonly AutoMailType type; + private string body; + /// - /// Basic constructor. + /// Basic constructor. /// - public BasicAutoMail (int autoMailId, AutoMailType type, int organizationId, int geographyId, - int authorPersonId, string title, string body) + public BasicAutoMail(int autoMailId, AutoMailType type, int organizationId, int geographyId, + int authorPersonId, string title, string body) { this.autoMailId = autoMailId; this.type = type; @@ -22,11 +30,11 @@ namespace Swarmops.Basic.Types.Communications /// - /// Copy constructor. + /// Copy constructor. /// - public BasicAutoMail (BasicAutoMail original) + public BasicAutoMail(BasicAutoMail original) : this(original.autoMailId, original.type, original.organizationId, original.geographyId, - original.authorPersonId, original.title, original.body) + original.authorPersonId, original.title, original.body) { } @@ -35,11 +43,6 @@ namespace Swarmops.Basic.Types.Communications get { return this.autoMailId; } } - public int Identity - { - get { return this.AutoMailId; } - } - public AutoMailType Type { get { return this.type; } @@ -71,12 +74,9 @@ namespace Swarmops.Basic.Types.Communications set { this.body = value; } } - private int autoMailId; - private AutoMailType type; - private int organizationId; - private int geographyId; - private int authorPersonId; - private string title; - private string body; + public int Identity + { + get { return AutoMailId; } + } } } \ No newline at end of file diff --git a/Basic/Types/Communications/BasicOutboundComm.cs b/Basic/Types/Communications/BasicOutboundComm.cs index 0595620b..f33c9059 100644 --- a/Basic/Types/Communications/BasicOutboundComm.cs +++ b/Basic/Types/Communications/BasicOutboundComm.cs @@ -4,41 +4,47 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Communications { - public class BasicOutboundComm: IHasIdentity + public class BasicOutboundComm : IHasIdentity { - 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, int recipientsSuccess, int recipientsFail) + 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, + int recipientsSuccess, int recipientsFail) { - this.OutboundCommId = outboundCommId; - this.SenderPersonId = senderPersonId; - this.FromPersonId = fromPersonId; - this.OrganizationId = organizationId; - this.CreatedDateTime = createdDateTime; - this.ResolverClass = resolverClass; - this.RecipientDataXml = recipientDataXml; - this.Resolved = resolved; - this.ResolvedDateTime = resolvedDateTime; - this.Priority = priority; - this.TransmitterClass = transmitterClass; - this.PayloadXml = payloadXml; - this.Open = open; - this.StartTransmitDateTime = startTransmitDateTime; - this.ClosedDateTime = closedDateTime; - this.RecipientCount = recipientCount; - this.RecipientsSuccess = recipientsSuccess; - this.RecipeintsFail = recipientsFail; + OutboundCommId = outboundCommId; + SenderPersonId = senderPersonId; + FromPersonId = fromPersonId; + OrganizationId = organizationId; + CreatedDateTime = createdDateTime; + ResolverClass = resolverClass; + RecipientDataXml = recipientDataXml; + Resolved = resolved; + ResolvedDateTime = resolvedDateTime; + Priority = priority; + TransmitterClass = transmitterClass; + PayloadXml = payloadXml; + Open = open; + StartTransmitDateTime = startTransmitDateTime; + ClosedDateTime = closedDateTime; + RecipientCount = recipientCount; + RecipientsSuccess = recipientsSuccess; + RecipeintsFail = recipientsFail; } - 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, - original.Open, original.StartTransmitDateTime, original.ClosedDateTime, original.RecipientCount, original.RecipientsSuccess, original.RecipeintsFail) + 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, + original.Open, original.StartTransmitDateTime, original.ClosedDateTime, original.RecipientCount, + original.RecipientsSuccess, original.RecipeintsFail) { // copy ctor } - public int OutboundCommId { get; private set; } public int SenderPersonId { get; private set; } public int FromPersonId { get; private set; } @@ -58,15 +64,13 @@ namespace Swarmops.Basic.Types.Communications public int RecipientsSuccess { get; protected set; } public int RecipeintsFail { get; protected set; } - - #region Implementation of IHasIdentity public int Identity { - get { return this.OutboundCommId; } + get { return OutboundCommId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/Communications/BasicOutboundCommRecipient.cs b/Basic/Types/Communications/BasicOutboundCommRecipient.cs index 3b8895c6..1d587460 100644 --- a/Basic/Types/Communications/BasicOutboundCommRecipient.cs +++ b/Basic/Types/Communications/BasicOutboundCommRecipient.cs @@ -2,20 +2,23 @@ namespace Swarmops.Basic.Types.Communications { - public class BasicOutboundCommRecipient: IHasIdentity + public class BasicOutboundCommRecipient : IHasIdentity { - public BasicOutboundCommRecipient (int outboundCommRecipientId, int outboundCommId, int personId, bool open, bool success, string failReason) + public BasicOutboundCommRecipient(int outboundCommRecipientId, int outboundCommId, int personId, bool open, + bool success, string failReason) { - this.OutboundCommRecipientId = outboundCommRecipientId; - this.OutboundCommId = outboundCommId; - this.PersonId = personId; - this.Open = open; - this.Success = success; - this.FailReason = failReason; + OutboundCommRecipientId = outboundCommRecipientId; + OutboundCommId = outboundCommId; + PersonId = personId; + Open = open; + Success = success; + FailReason = failReason; } - public BasicOutboundCommRecipient (BasicOutboundCommRecipient original): - this (original.OutboundCommRecipientId, original.OutboundCommId, original.PersonId, original.Open, original.Success, original.FailReason) + public BasicOutboundCommRecipient(BasicOutboundCommRecipient original) : + this( + original.OutboundCommRecipientId, original.OutboundCommId, original.PersonId, original.Open, + original.Success, original.FailReason) { // copy ctor } @@ -31,9 +34,9 @@ namespace Swarmops.Basic.Types.Communications public int Identity { - get { return this.OutboundCommRecipientId; } + get { return OutboundCommRecipientId; } } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicCashAdvance.cs b/Basic/Types/Financial/BasicCashAdvance.cs index c71f4d6a..ed0a836a 100644 --- a/Basic/Types/Financial/BasicCashAdvance.cs +++ b/Basic/Types/Financial/BasicCashAdvance.cs @@ -4,30 +4,33 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Financial { [Serializable] - public class BasicCashAdvance: IHasIdentity + public class BasicCashAdvance : IHasIdentity { - public BasicCashAdvance(int cashAdvanceId, int organizationId, int personId, DateTime createdDateTime, int createdByPersonId, - int financialAccountId, Int64 amountCents, string description, bool open, bool attested, + 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) { - this.CashAdvanceId = cashAdvanceId; - this.OrganizationId = organizationId; - this.PersonId = personId; - this.CreatedDateTime = createdDateTime; - this.CreatedByPersonId = createdByPersonId; - this.BudgetId = financialAccountId; - this.AmountCents = amountCents; - this.Description = description; - this.Open = open; - this.Attested = attested; - this.PaidOut = paidOut; - this.AttestedByPersonId = attestedByPersonId; - this.AttestedDateTime = attestedDateTime; + CashAdvanceId = cashAdvanceId; + OrganizationId = organizationId; + PersonId = personId; + CreatedDateTime = createdDateTime; + CreatedByPersonId = createdByPersonId; + BudgetId = financialAccountId; + AmountCents = amountCents; + Description = description; + Open = open; + Attested = attested; + PaidOut = paidOut; + AttestedByPersonId = attestedByPersonId; + AttestedDateTime = attestedDateTime; } - 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, + 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, original.PaidOut, original.AttestedByPersonId, original.AttestedDateTime) { // copy ctor - no action other than copying original object @@ -55,6 +58,9 @@ namespace Swarmops.Basic.Types.Financial // IHasIdentity interface - public int Identity { get { return this.CashAdvanceId; } } + public int Identity + { + get { return CashAdvanceId; } + } } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialAccount.cs b/Basic/Types/Financial/BasicFinancialAccount.cs index 709fa548..c0d9fce9 100644 --- a/Basic/Types/Financial/BasicFinancialAccount.cs +++ b/Basic/Types/Financial/BasicFinancialAccount.cs @@ -5,29 +5,33 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialAccount : IHasIdentity { - 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) + 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) { - this.FinancialAccountId = financialAccountId; - this.Name = name; - this.AccountType = accountType; - this.OrganizationId = organizationId; - this.OwnerPersonId = ownerPersonId; - this.ParentFinancialAccountId = parentFinancialAccountId; - this.Open = open; - this.OpenedYear = openedYear; - this.ClosedYear = closedYear; - this.Active = active; - this.Expensable = expensable; - this.Administrative = administrative; - this.LinkBackward = linkBackward; - this.LinkForward = linkForward; + FinancialAccountId = financialAccountId; + Name = name; + AccountType = accountType; + OrganizationId = organizationId; + OwnerPersonId = ownerPersonId; + ParentFinancialAccountId = parentFinancialAccountId; + Open = open; + OpenedYear = openedYear; + ClosedYear = closedYear; + Active = active; + Expensable = expensable; + Administrative = administrative; + LinkBackward = linkBackward; + LinkForward = linkForward; } - 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, original.LinkForward) + 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, + original.LinkForward) { // Empty copy constructor } @@ -52,7 +56,7 @@ namespace Swarmops.Basic.Types.Financial public int Identity { - get { return this.FinancialAccountId; } + get { return FinancialAccountId; } } #endregion diff --git a/Basic/Types/Financial/BasicFinancialAccountRow.cs b/Basic/Types/Financial/BasicFinancialAccountRow.cs index 1acf8a06..b6416ee1 100644 --- a/Basic/Types/Financial/BasicFinancialAccountRow.cs +++ b/Basic/Types/Financial/BasicFinancialAccountRow.cs @@ -4,21 +4,22 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialAccountRow { - public BasicFinancialAccountRow (int financialAccountId, int financialTransactionId, DateTime dateTime, - string comment, Int64 amountCents, DateTime rowDateTime, int rowCreatedByPersonId) + public BasicFinancialAccountRow(int financialAccountId, int financialTransactionId, DateTime dateTime, + string comment, Int64 amountCents, DateTime rowDateTime, int rowCreatedByPersonId) { - this.FinancialAccountId = financialAccountId; - this.FinancialTransactionId = financialTransactionId; - this.TransactionDateTime = dateTime; - this.Description = comment; - this.AmountCents = amountCents; - this.RowDateTime = rowDateTime; - this.RowCreatedByPersonId = rowCreatedByPersonId; + FinancialAccountId = financialAccountId; + FinancialTransactionId = financialTransactionId; + TransactionDateTime = dateTime; + Description = comment; + AmountCents = amountCents; + RowDateTime = rowDateTime; + RowCreatedByPersonId = rowCreatedByPersonId; } - public BasicFinancialAccountRow (BasicFinancialAccountRow original) + public BasicFinancialAccountRow(BasicFinancialAccountRow original) : this( - original.FinancialAccountId, original.FinancialTransactionId, original.TransactionDateTime, original.Description, + original.FinancialAccountId, original.FinancialTransactionId, original.TransactionDateTime, + original.Description, original.AmountCents, original.RowDateTime, original.RowCreatedByPersonId) { } @@ -30,6 +31,5 @@ namespace Swarmops.Basic.Types.Financial public Int64 AmountCents { get; private set; } public DateTime RowDateTime { get; private set; } public int RowCreatedByPersonId { get; private set; } - } } \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialDependency.cs b/Basic/Types/Financial/BasicFinancialDependency.cs index da5f3864..f7a9535a 100644 --- a/Basic/Types/Financial/BasicFinancialDependency.cs +++ b/Basic/Types/Financial/BasicFinancialDependency.cs @@ -3,19 +3,19 @@ using Swarmops.Basic.Enums; namespace Swarmops.Basic.Types.Financial { /// - /// This class encapsulates what a financial transaction was constructed from. + /// This class encapsulates what a financial transaction was constructed from. /// public class BasicFinancialDependency { - public BasicFinancialDependency (int objectId, FinancialDependencyType dependencyType, int foreignId) + public BasicFinancialDependency(int objectId, FinancialDependencyType dependencyType, int foreignId) { - this.ObjectId = objectId; - this.DependencyType = dependencyType; - this.ForeignId = foreignId; + ObjectId = objectId; + DependencyType = dependencyType; + ForeignId = foreignId; } public int ObjectId { get; private set; } public FinancialDependencyType DependencyType { get; private set; } public int ForeignId { get; private set; } } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialTransaction.cs b/Basic/Types/Financial/BasicFinancialTransaction.cs index f764ec48..1df04f62 100644 --- a/Basic/Types/Financial/BasicFinancialTransaction.cs +++ b/Basic/Types/Financial/BasicFinancialTransaction.cs @@ -5,8 +5,14 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransaction : IHasIdentity { - public BasicFinancialTransaction (int financialTransactionId, int organizationId, DateTime dateTime, - string description, string importHash) + private readonly DateTime dateTime; + private readonly int financialTransactionId; + private readonly string importHash; + private readonly int organizationId; + private string description; + + public BasicFinancialTransaction(int financialTransactionId, int organizationId, DateTime dateTime, + string description, string importHash) { this.financialTransactionId = financialTransactionId; this.organizationId = organizationId; @@ -15,19 +21,13 @@ namespace Swarmops.Basic.Types.Financial this.importHash = importHash; } - public BasicFinancialTransaction (BasicFinancialTransaction original) : + public BasicFinancialTransaction(BasicFinancialTransaction original) : this( original.financialTransactionId, original.organizationId, original.dateTime, original.description, original.importHash) { } - private int organizationId; - private int financialTransactionId; - private DateTime dateTime; - private string description; - private string importHash; - public int OrganizationId { get { return this.organizationId; } diff --git a/Basic/Types/Financial/BasicFinancialTransactionRow.cs b/Basic/Types/Financial/BasicFinancialTransactionRow.cs index d01eeea4..c69a6088 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionRow.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionRow.cs @@ -5,18 +5,18 @@ namespace Swarmops.Basic.Types.Financial { public class BasicFinancialTransactionRow : IHasIdentity { - public BasicFinancialTransactionRow (int financialTransactionRowId, int financialAccountId, - int financialTransactionId, Int64 amountCents, DateTime createdDateTime, int createdByPersonId) + public BasicFinancialTransactionRow(int financialTransactionRowId, int financialAccountId, + int financialTransactionId, Int64 amountCents, DateTime createdDateTime, int createdByPersonId) { - this.FinancialTransactionRowId = financialTransactionRowId; - this.FinancialAccountId = financialAccountId; - this.FinancialTransactionId = financialTransactionId; - this.AmountCents = amountCents; - this.CreatedDateTime = createdDateTime; - this.CreatedByPersonId = createdByPersonId; + FinancialTransactionRowId = financialTransactionRowId; + FinancialAccountId = financialAccountId; + FinancialTransactionId = financialTransactionId; + AmountCents = amountCents; + CreatedDateTime = createdDateTime; + CreatedByPersonId = createdByPersonId; } - public BasicFinancialTransactionRow (BasicFinancialTransactionRow original) + public BasicFinancialTransactionRow(BasicFinancialTransactionRow original) : this( original.FinancialTransactionRowId, original.FinancialAccountId, original.FinancialTransactionId, original.AmountCents, original.CreatedDateTime, original.CreatedByPersonId) @@ -25,7 +25,7 @@ namespace Swarmops.Basic.Types.Financial public int FinancialAccountId { get; private set; } public int FinancialTransactionId { get; private set; } - public int FinancialTransactionRowId { get; private set;} + public int FinancialTransactionRowId { get; private set; } public Int64 AmountCents { get; private set; } public DateTime CreatedDateTime { get; private set; } public int CreatedByPersonId { get; private set; } @@ -34,7 +34,7 @@ namespace Swarmops.Basic.Types.Financial public int Identity { - get { return this.FinancialTransactionRowId; } + get { return FinancialTransactionRowId; } } #endregion diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs b/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs index 73a5c1a3..033eafd9 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagSet.cs @@ -2,21 +2,24 @@ namespace Swarmops.Basic.Types.Financial { - public class BasicFinancialTransactionTagSet: IHasIdentity + public class BasicFinancialTransactionTagSet : IHasIdentity { - public BasicFinancialTransactionTagSet (int financialTransactionTagSetId, int financialTransactionTagSetTypeId, int organizationId, int order, bool allowUntagged, int visibilityLevel, int profitLossType) + public BasicFinancialTransactionTagSet(int financialTransactionTagSetId, int financialTransactionTagSetTypeId, + int organizationId, int order, bool allowUntagged, int visibilityLevel, int profitLossType) { - this.FinancialTransactionTagSetId = financialTransactionTagSetId; - this.FinancialTransactionTagSetTypeId = financialTransactionTagSetTypeId; - this.OrganizationId = organizationId; - this.Order = order; - this.AllowUntagged = allowUntagged; - this.VisibilityLevel = visibilityLevel; - this.ProfitLossType = profitLossType; + FinancialTransactionTagSetId = financialTransactionTagSetId; + FinancialTransactionTagSetTypeId = financialTransactionTagSetTypeId; + OrganizationId = organizationId; + Order = order; + AllowUntagged = allowUntagged; + VisibilityLevel = visibilityLevel; + ProfitLossType = profitLossType; } - public BasicFinancialTransactionTagSet (BasicFinancialTransactionTagSet original): - this (original.FinancialTransactionTagSetId, original.FinancialTransactionTagSetTypeId, original.OrganizationId, original.Order, original.AllowUntagged, original.VisibilityLevel, original.ProfitLossType) + public BasicFinancialTransactionTagSet(BasicFinancialTransactionTagSet original) : + this( + original.FinancialTransactionTagSetId, original.FinancialTransactionTagSetTypeId, original.OrganizationId, + original.Order, original.AllowUntagged, original.VisibilityLevel, original.ProfitLossType) { // copy ctor } @@ -31,8 +34,11 @@ namespace Swarmops.Basic.Types.Financial #region Implementation of IHasIdentity - public int Identity { get { return this.FinancialTransactionTagSetId; } } + public int Identity + { + get { return FinancialTransactionTagSetId; } + } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs b/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs index 79cfe098..6102f894 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagSetType.cs @@ -2,16 +2,16 @@ namespace Swarmops.Basic.Types.Financial { - public class BasicFinancialTransactionTagSetType: IHasIdentity + public class BasicFinancialTransactionTagSetType : IHasIdentity { - public BasicFinancialTransactionTagSetType (int financialTransactionTagSetTypeId, string resourceName) + public BasicFinancialTransactionTagSetType(int financialTransactionTagSetTypeId, string resourceName) { - this.FinancialTransactionTagSetTypeId = financialTransactionTagSetTypeId; - this.ResourceName = 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 } @@ -19,11 +19,13 @@ namespace Swarmops.Basic.Types.Financial public int FinancialTransactionTagSetTypeId { get; private set; } public string ResourceName { get; private set; } - #region Implementation of IHasIdentity - public int Identity { get { return this.FinancialTransactionTagSetTypeId; } } + public int Identity + { + get { return FinancialTransactionTagSetTypeId; } + } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialTransactionTagType.cs b/Basic/Types/Financial/BasicFinancialTransactionTagType.cs index 44e30bca..85b0fdcb 100644 --- a/Basic/Types/Financial/BasicFinancialTransactionTagType.cs +++ b/Basic/Types/Financial/BasicFinancialTransactionTagType.cs @@ -2,22 +2,27 @@ namespace Swarmops.Basic.Types.Financial { - public class BasicFinancialTransactionTagType: IHasIdentity + public class BasicFinancialTransactionTagType : IHasIdentity { - public BasicFinancialTransactionTagType (int financialTransactionTagTypeId, int parentFinancialTransactionTagTypeId, int financialTransactionTagSetId, string name, bool active, int openedYear, int closedYear) + public BasicFinancialTransactionTagType(int financialTransactionTagTypeId, + int parentFinancialTransactionTagTypeId, int financialTransactionTagSetId, string name, bool active, + int openedYear, int closedYear) { - this.FinancialTransactionTagTypeId = financialTransactionTagTypeId; - this.ParentFinancialTransactionTagTypeId = parentFinancialTransactionTagTypeId; - this.FinancialTransactionTagSetId = financialTransactionTagSetId; - this.Name = name; - this.Active = active; - this.OpenedYear = openedYear; - this.ClosedYear = closedYear; + FinancialTransactionTagTypeId = financialTransactionTagTypeId; + ParentFinancialTransactionTagTypeId = parentFinancialTransactionTagTypeId; + FinancialTransactionTagSetId = financialTransactionTagSetId; + Name = name; + Active = active; + OpenedYear = openedYear; + ClosedYear = closedYear; } - public BasicFinancialTransactionTagType (BasicFinancialTransactionTagType original): - this (original.FinancialTransactionTagTypeId, original.ParentFinancialTransactionTagTypeId, original.FinancialTransactionTagSetId, original.Name, original.Active, original.OpenedYear, original.ClosedYear) - { + public BasicFinancialTransactionTagType(BasicFinancialTransactionTagType original) : + this( + original.FinancialTransactionTagTypeId, original.ParentFinancialTransactionTagTypeId, + original.FinancialTransactionTagSetId, original.Name, original.Active, original.OpenedYear, + original.ClosedYear) + { // copy ctor } @@ -31,8 +36,11 @@ namespace Swarmops.Basic.Types.Financial #region Implementation of IHasIdentity - public int Identity { get { return this.FinancialTransactionTagTypeId; } } + public int Identity + { + get { return FinancialTransactionTagTypeId; } + } #endregion } -} +} \ No newline at end of file diff --git a/Basic/Types/Financial/BasicFinancialValidation.cs b/Basic/Types/Financial/BasicFinancialValidation.cs index d5bd4f7d..f239bc5d 100644 --- a/Basic/Types/Financial/BasicFinancialValidation.cs +++ b/Basic/Types/Financial/BasicFinancialValidation.cs @@ -4,20 +4,23 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Financial { - public class BasicFinancialValidation: IHasIdentity + public class BasicFinancialValidation : IHasIdentity { - public BasicFinancialValidation (int financialValidationId, FinancialValidationType validationType, int personId, DateTime dateTime, FinancialDependencyType dependencyType, int foreignId) + public BasicFinancialValidation(int financialValidationId, FinancialValidationType validationType, int personId, + DateTime dateTime, FinancialDependencyType dependencyType, int foreignId) { - this.FinancialValidationId = financialValidationId; - this.ValidationType = validationType; - this.PersonId = personId; - this.DateTime = dateTime; - this.DependencyType = dependencyType; - this.ForeignId = foreignId; + FinancialValidationId = financialValidationId; + ValidationType = validationType; + PersonId = personId; + DateTime = dateTime; + DependencyType = dependencyType; + ForeignId = foreignId; } - public BasicFinancialValidation (BasicFinancialValidation original) - :this (original.Identity, original.ValidationType, original.PersonId, original.DateTime, original.DependencyType, original.ForeignId) + public BasicFinancialValidation(BasicFinancialValidation original) + : this( + original.Identity, original.ValidationType, original.PersonId, original.DateTime, + original.DependencyType, original.ForeignId) { // empty copy ctor } @@ -28,9 +31,10 @@ namespace Swarmops.Basic.Types.Financial public DateTime DateTime { get; private set; } public FinancialDependencyType DependencyType { get; private set; } public int ForeignId { get; private set; } + public int Identity { - get { return this.FinancialValidationId; } + get { return FinancialValidationId; } } } -} +} \ No newline at end of file diff --git a/Basic/Types/GeographyWithPeople.cs b/Basic/Types/GeographyWithPeople.cs index 1f843245..dcf8aa5c 100644 --- a/Basic/Types/GeographyWithPeople.cs +++ b/Basic/Types/GeographyWithPeople.cs @@ -3,17 +3,17 @@ using System; namespace Swarmops.Basic.Types { [Serializable] - public class BasicGeographyWithPeople + public class BasicGeographyWithPeople { + public int ActivistCount; public int GeographyID; - public int OrgId = 0; public string GeograpyName; + public string LeadContent; + public int MemberCount; + public int OrgId = 0; public string OrgName; public int ParentGeographyId; public int ParentOrgId; - public int MemberCount; - public int ActivistCount; - public string LeadContent; public string SecondsContent; } } \ No newline at end of file diff --git a/Basic/Types/Governance/BasicMeeting.cs b/Basic/Types/Governance/BasicMeeting.cs index 063ef154..77419b6d 100644 --- a/Basic/Types/Governance/BasicMeeting.cs +++ b/Basic/Types/Governance/BasicMeeting.cs @@ -3,23 +3,28 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Governance { - public class BasicMeeting: IHasIdentity + public class BasicMeeting : IHasIdentity { - public BasicMeeting (int meetingId, int organizationId, string name, DateTime motionSubmissionEnds, DateTime amendmentSubmissionEnds, DateTime amendmentVotingStarts, DateTime amendmentVotingEnds, DateTime motionVotingStarts, DateTime motionVotingEnds) + public BasicMeeting(int meetingId, int organizationId, string name, DateTime motionSubmissionEnds, + DateTime amendmentSubmissionEnds, DateTime amendmentVotingStarts, DateTime amendmentVotingEnds, + DateTime motionVotingStarts, DateTime motionVotingEnds) { - this.MeetingId = meetingId; - this.OrganizationId = organizationId; - this.Name = name; - this.MotionSubmissionEnds = motionSubmissionEnds; - this.AmendmentSubmissionEnds = amendmentSubmissionEnds; - this.AmendmentVotingStarts = amendmentVotingStarts; - this.AmendmentVotingEnds = amendmentVotingEnds; - this.MotionVotingStarts = motionVotingStarts; - this.MotionVotingEnds = motionVotingEnds; + MeetingId = meetingId; + OrganizationId = organizationId; + Name = name; + MotionSubmissionEnds = motionSubmissionEnds; + AmendmentSubmissionEnds = amendmentSubmissionEnds; + AmendmentVotingStarts = amendmentVotingStarts; + AmendmentVotingEnds = amendmentVotingEnds; + MotionVotingStarts = motionVotingStarts; + MotionVotingEnds = motionVotingEnds; } - public BasicMeeting (BasicMeeting original): - this (original.MeetingId, original.OrganizationId, original.Name, original.MotionSubmissionEnds, original.AmendmentSubmissionEnds, original.AmendmentVotingStarts, original.AmendmentVotingEnds, original.MotionVotingStarts, original.MotionVotingEnds) + public BasicMeeting(BasicMeeting original) : + this( + original.MeetingId, original.OrganizationId, original.Name, original.MotionSubmissionEnds, + original.AmendmentSubmissionEnds, original.AmendmentVotingStarts, original.AmendmentVotingEnds, + original.MotionVotingStarts, original.MotionVotingEnds) { // empty copy ctor } @@ -36,7 +41,7 @@ namespace Swarmops.Basic.Types.Governance public int Identity { - get { return this.MeetingId; } + get { return MeetingId; } } } } \ No newline at end of file diff --git a/Basic/Types/Governance/BasicMotion.cs b/Basic/Types/Governance/BasicMotion.cs index 0a82728c..32498379 100644 --- a/Basic/Types/Governance/BasicMotion.cs +++ b/Basic/Types/Governance/BasicMotion.cs @@ -3,32 +3,40 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Governance { - public class BasicMotion: IHasIdentity + public class BasicMotion : IHasIdentity { - 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) + 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) { - this.MotionId = motionId; - this.MeetingId = meetingId; - this.SequenceNumber = sequenceNumber; - this.Designation = designation; - this.SubmittedByPersonId = submittedByPersonId; - this.CreatedByPersonId = createdByPersonId; - this.CreatedDateTime = createdDateTime; - this.Amended = amended; - this.AmendedByPersonId = amendedByPersonId; - this.AmendedDateTime = amendedDateTime; - this.Title = title; - this.Text = text; - this.AmendedText = amendedText; - this.DecisionPoints = decisionPoints; - this.AmendedDecisionPoints = amendedDecisionPoints; - this.ThreadUrl = threadUrl; - this.Open = open; - this.Carried = carried; + MotionId = motionId; + MeetingId = meetingId; + SequenceNumber = sequenceNumber; + Designation = designation; + SubmittedByPersonId = submittedByPersonId; + CreatedByPersonId = createdByPersonId; + CreatedDateTime = createdDateTime; + Amended = amended; + AmendedByPersonId = amendedByPersonId; + AmendedDateTime = amendedDateTime; + Title = title; + Text = text; + AmendedText = amendedText; + DecisionPoints = decisionPoints; + AmendedDecisionPoints = amendedDecisionPoints; + ThreadUrl = threadUrl; + Open = open; + Carried = carried; } - 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, original.DecisionPoints, original.AmendedDecisionPoints, original.ThreadUrl, original.Open, original.Carried) + 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, + original.DecisionPoints, original.AmendedDecisionPoints, original.ThreadUrl, original.Open, original.Carried + ) { // empty copy ctor } @@ -56,7 +64,7 @@ namespace Swarmops.Basic.Types.Governance public int Identity { - get { return this.MotionId; } + get { return MotionId; } } } } \ No newline at end of file diff --git a/Basic/Types/Governance/BasicMotionAmendment.cs b/Basic/Types/Governance/BasicMotionAmendment.cs index 5d60d4dc..1174400b 100644 --- a/Basic/Types/Governance/BasicMotionAmendment.cs +++ b/Basic/Types/Governance/BasicMotionAmendment.cs @@ -3,25 +3,30 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Basic.Types.Governance { - public class BasicMotionAmendment: IHasIdentity + public class BasicMotionAmendment : IHasIdentity { - public BasicMotionAmendment(int motionAmendmentId, int motionId, int sequenceNumber, int submittedByPersonId, int createdByPersonId, DateTime createdDateTime, string title, string text, string decisionPoint, bool open, bool carried) + public BasicMotionAmendment(int motionAmendmentId, int motionId, int sequenceNumber, int submittedByPersonId, + int createdByPersonId, DateTime createdDateTime, string title, string text, string decisionPoint, bool open, + bool carried) { - this.MotionAmendmentId = motionAmendmentId; - this.MotionId = motionId; - this.SequenceNumber = sequenceNumber; - this.SubmittedByPersonId = submittedByPersonId; - this.CreatedByPersonId = createdByPersonId; - this.CreatedDateTime = createdDateTime; - this.Title = title; - this.Text = text; - this.DecisionPoint = decisionPoint; - this.Open = open; - this.Carried = carried; + MotionAmendmentId = motionAmendmentId; + MotionId = motionId; + SequenceNumber = sequenceNumber; + SubmittedByPersonId = submittedByPersonId; + CreatedByPersonId = createdByPersonId; + CreatedDateTime = createdDateTime; + Title = title; + Text = text; + DecisionPoint = decisionPoint; + Open = open; + Carried = carried; } - 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) + 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) { // empty copy ctor } @@ -37,9 +42,10 @@ namespace Swarmops.Basic.Types.Governance public string DecisionPoint { get; private set; } public bool Open { get; protected set; } public bool Carried { get; protected set; } + public int Identity { - get { return this.MotionAmendmentId; } + get { return MotionAmendmentId; } } } } \ No newline at end of file diff --git a/Basic/Types/Security/BasicAuthority.cs b/Basic/Types/Security/BasicAuthority.cs index e86f5e9b..85059296 100644 --- a/Basic/Types/Security/BasicAuthority.cs +++ b/Basic/Types/Security/BasicAuthority.cs @@ -3,16 +3,23 @@ using System; namespace Swarmops.Basic.Types.Security { /// - /// Container of a person's authority within PirateWeb. + /// Container of a person's authority within PirateWeb. /// public class BasicAuthority { - public BasicAuthority (int personId, BasicPersonRole[] systemPersonRoles, BasicPersonRole[] organizationPersonRoles, - BasicPersonRole[] nodePersonRoles) + public readonly BasicPersonRole[] AllPersonRoles; + public readonly BasicPersonRole[] LocalPersonRoles; + public readonly BasicPersonRole[] OrganizationPersonRoles; + public readonly int PersonId; + public readonly BasicPersonRole[] SystemPersonRoles; + + public BasicAuthority(int personId, BasicPersonRole[] systemPersonRoles, + BasicPersonRole[] organizationPersonRoles, + BasicPersonRole[] nodePersonRoles) { if (personId < 1) { - throw new ArgumentOutOfRangeException("PersonId cannot be " + personId.ToString()); + throw new ArgumentOutOfRangeException("PersonId cannot be " + personId); } this.PersonId = personId; @@ -35,23 +42,19 @@ namespace Swarmops.Basic.Types.Security this.LocalPersonRoles = new BasicPersonRole[0]; } - AllPersonRoles = new BasicPersonRole[SystemPersonRoles.Length + OrganizationPersonRoles.Length + LocalPersonRoles.Length]; + this.AllPersonRoles = + new BasicPersonRole[ + this.SystemPersonRoles.Length + this.OrganizationPersonRoles.Length + this.LocalPersonRoles.Length]; - if (SystemPersonRoles.Length > 0) - SystemPersonRoles.CopyTo(AllPersonRoles, 0); + if (this.SystemPersonRoles.Length > 0) + this.SystemPersonRoles.CopyTo(this.AllPersonRoles, 0); - if (OrganizationPersonRoles.Length > 0) - OrganizationPersonRoles.CopyTo(AllPersonRoles, SystemPersonRoles.Length); - - if (LocalPersonRoles.Length > 0) - LocalPersonRoles.CopyTo(AllPersonRoles, SystemPersonRoles.Length + OrganizationPersonRoles.Length); + if (this.OrganizationPersonRoles.Length > 0) + this.OrganizationPersonRoles.CopyTo(this.AllPersonRoles, this.SystemPersonRoles.Length); + if (this.LocalPersonRoles.Length > 0) + this.LocalPersonRoles.CopyTo(this.AllPersonRoles, + this.SystemPersonRoles.Length + this.OrganizationPersonRoles.Length); } - - public readonly int PersonId; - public readonly BasicPersonRole[] SystemPersonRoles; - public readonly BasicPersonRole[] OrganizationPersonRoles; - public readonly BasicPersonRole[] LocalPersonRoles; - public readonly BasicPersonRole[] AllPersonRoles; } } \ No newline at end of file diff --git a/Basic/Types/XmlSerializableDictionary.cs b/Basic/Types/XmlSerializableDictionary.cs index a018fff4..a5659211 100644 --- a/Basic/Types/XmlSerializableDictionary.cs +++ b/Basic/Types/XmlSerializableDictionary.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using System.Xml; +using System.Xml.Schema; using System.Xml.Serialization; [XmlRoot("dictionary")] @@ -6,15 +8,16 @@ public class SerializableDictionary : Dictionary, IXmlSerializable { #region IXmlSerializable Members - public System.Xml.Schema.XmlSchema GetSchema () + + public XmlSchema GetSchema() { return null; } - public void ReadXml (System.Xml.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(); @@ -22,19 +25,19 @@ public class SerializableDictionary if (wasEmpty) return; - while (reader.NodeType != System.Xml.XmlNodeType.EndElement) + while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); - TKey key = (TKey)keySerializer.Deserialize(reader); + TKey key = (TKey) keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); - TValue value = (TValue)valueSerializer.Deserialize(reader); + TValue value = (TValue) valueSerializer.Deserialize(reader); reader.ReadEndElement(); - this.Add(key, value); + Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); @@ -42,12 +45,12 @@ public class SerializableDictionary reader.ReadEndElement(); } - public void WriteXml (System.Xml.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 this.Keys) + foreach (TKey key in Keys) { writer.WriteStartElement("item"); @@ -63,5 +66,6 @@ public class SerializableDictionary writer.WriteEndElement(); } } + #endregion } \ No newline at end of file diff --git a/Database/Configuration.cs b/Database/Configuration.cs index ac866296..c5d982ee 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Web; using System.Xml.Serialization; @@ -9,7 +10,7 @@ namespace Swarmops.Database public partial class SwarmDb { /// - /// This is the IN-CODE revision of the database. The version we expect to be running against. + /// This is the IN-CODE revision of the database. The version we expect to be running against. /// public static int DbVersionExpected { @@ -22,23 +23,32 @@ namespace Swarmops.Database [Serializable] public class Configuration { - public Configuration() {} - public Configuration (Credentials read, Credentials write, Credentials admin) + private static Configuration _configuration; + + public Configuration() { - this.Read = read; - this.Write = write; - this.Admin = admin; } + public Configuration(Credentials read, Credentials write, Credentials admin) + { + Read = read; + Write = write; + Admin = admin; + } + + public Credentials Read { get; set; } + public Credentials Write { get; set; } + public Credentials Admin { get; set; } + public static bool IsConfigured() { - if (Configuration._configuration == null) + if (_configuration == null) { try { - Configuration.Load(); + Load(); } - catch(Exception) + catch (Exception) { return false; } @@ -49,10 +59,6 @@ namespace Swarmops.Database return !String.IsNullOrEmpty(testString); } - public Credentials Read { get; set; } - public Credentials Write { get; set; } - public Credentials Admin { get; set; } - public Configuration Get() { @@ -64,20 +70,19 @@ namespace Swarmops.Database return _configuration; } - private static Configuration _configuration; - public static bool TestConfigurationWritable() { try { - using (FileStream stream = new FileStream(GetConfigurationFileName(), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) + using ( + FileStream stream = new FileStream(GetConfigurationFileName(), FileMode.Append, FileAccess.Write, + FileShare.ReadWrite)) { // do nothing } } catch (Exception) { - return false; } @@ -86,20 +91,21 @@ 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, FileShare.Read)) + using ( + FileStream readFileStream = new FileStream(configFileName, FileMode.Open, FileAccess.Read, + FileShare.Read)) { - _configuration = (Configuration) serializer.Deserialize(readFileStream); } } 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)) @@ -125,24 +131,43 @@ namespace Swarmops.Database return "/etc/swarmops/database.config"; } - else if (System.Diagnostics.Debugger.IsAttached) + if (Debugger.IsAttached) { // 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"); } - else - { - throw new NotImplementedException("Invalid state"); + throw new NotImplementedException("Invalid state"); - // Dev console process + // Dev console process - // Each dev needs to set the working directory to the Console directory when debugging - // return "database.config"; - } + // Each dev needs to set the working directory to the Console directory when debugging + // return "database.config"; } } + [Serializable] + public class Credentials + { + public Credentials() + { + // paramless ctor to enable serialization + } + + public Credentials(string database, ServerSet servers, string username, string password) + { + Database = database; + ServerSet = servers; + Username = username; + Password = password; + } + + public string Database { get; set; } + public ServerSet ServerSet { get; set; } + public string Username { get; set; } + public string Password { get; set; } + } + [Serializable] public class ServerSet { @@ -152,35 +177,14 @@ namespace Swarmops.Database ServerPriorities = new List(); } - public ServerSet (string singleServer) + public ServerSet(string singleServer) { ServerPriorities = new List(); ServerPriorities.Add(singleServer); } - public List ServerPriorities { get; set; } // array of semicolon-delimited hostnames; topmost string in array is first-priority servers, and so on. + public List ServerPriorities { get; set; } + // array of semicolon-delimited hostnames; topmost string in array is first-priority servers, and so on. } - - [Serializable] - public class Credentials - { - public Credentials() - { - // paramless ctor to enable serialization - } - - public Credentials (string database, ServerSet servers, string username, string password) - { - this.Database = database; - this.ServerSet = servers; - this.Username = username; - this.Password = password; - } - - public string Database { get; set; } - public ServerSet ServerSet { get; set; } - public string Username { get; set; } - public string Password { get; set; } - } } -} +} \ No newline at end of file diff --git a/Database/Database-Activists.cs b/Database/Database-Activists.cs index 9bdfc6e2..71026b55 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(); @@ -30,7 +30,7 @@ namespace Swarmops.Database 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()) { @@ -47,7 +47,7 @@ namespace Swarmops.Database } } - public int GetActivistCountForGeographies (int[] geographyIds) + public int GetActivistCountForGeographies(int[] geographyIds) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -65,7 +65,7 @@ namespace Swarmops.Database } - public bool GetActivistStatus (int personId) + public bool GetActivistStatus(int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -73,7 +73,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT * From Activists WHERE Active=1 AND PersonId=" + personId.ToString(), + "SELECT * From Activists WHERE Active=1 AND PersonId=" + personId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -89,7 +89,7 @@ namespace Swarmops.Database } - public void TerminateActivist (int personId) + public void TerminateActivist(int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -100,12 +100,7 @@ namespace Swarmops.Database AddParameterWithName(command, "personId", personId); command.ExecuteNonQuery(); - } } - - - - } } \ No newline at end of file diff --git a/Database/Database-Attribute.cs b/Database/Database-Attribute.cs index bbd9a86a..142e7124 100644 --- a/Database/Database-Attribute.cs +++ b/Database/Database-Attribute.cs @@ -3,23 +3,24 @@ using System; namespace Swarmops.Database.Attributes { /// - /// DbRecordType is used to mark a class what its database record is named - /// Needed if a Logic entity is using Database-condition and have to work with a subclass - /// i.e. [DbRecordType("Person")] on class Person + /// DbRecordType is used to mark a class what its database record is named + /// 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)] - public class DbRecordType : System.Attribute + public class DbRecordType : Attribute { - string typeName = ""; + private string typeName = ""; + + public DbRecordType(string recordname) + { + this.typeName = recordname; + } public string TypeName { - get { return typeName; } - set { typeName = value; } - } - public DbRecordType (string recordname) - { - typeName = recordname; + get { return this.typeName; } + set { this.typeName = value; } } } -} +} \ No newline at end of file diff --git a/Database/Database-AutoMails.cs b/Database/Database-AutoMails.cs index 07e9c8f8..d31f5634 100644 --- a/Database/Database-AutoMails.cs +++ b/Database/Database-AutoMails.cs @@ -13,7 +13,7 @@ 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()) { @@ -21,9 +21,10 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "select AutoMails.AutoMailId,AutoMailTypes.Name,AutoMails.OrganizationId,AutoMails.GeographyId,AutoMails.AuthorPersonId,Title,Body " + + "select AutoMails.AutoMailId,AutoMailTypes.Name,AutoMails.OrganizationId,AutoMails.GeographyId,AutoMails.AuthorPersonId,Title,Body " + "FROM AutoMails JOIN AutoMailTypes USING (AutoMailTypeId) " + - "WHERE AutoMailTypes.Name='" + type.ToString() + "' AND AutoMails.OrganizationId=" + organizationId.ToString() + " AND AutoMails.GeographyId=" + geographyId.ToString(), connection); + "WHERE AutoMailTypes.Name='" + type + "' AND AutoMails.OrganizationId=" + organizationId + + " AND AutoMails.GeographyId=" + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -38,7 +39,7 @@ 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)); @@ -49,12 +50,12 @@ namespace Swarmops.Database string body = reader.GetString(6); return new BasicAutoMail(autoMailId, type, organizationId, geographyId, authorPersonId, - title, body); + title, body); } - public int SetAutoMail (AutoMailType type, int organizationId, int geographyId, - int authorPersonId, string title, string body) + public int SetAutoMail(AutoMailType type, int organizationId, int geographyId, + int authorPersonId, string title, string body) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -75,10 +76,10 @@ namespace Swarmops.Database } - public int SetAutoMail (BasicAutoMail autoMail) + public int SetAutoMail(BasicAutoMail autoMail) { return SetAutoMail(autoMail.Type, autoMail.OrganizationId, autoMail.GeographyId, - autoMail.AuthorPersonId, autoMail.Title, autoMail.Body); + autoMail.AuthorPersonId, autoMail.Title, autoMail.Body); } } } \ No newline at end of file diff --git a/Database/Database-Ballots.cs b/Database/Database-Ballots.cs index 9b3e4bed..e3feaf34 100644 --- a/Database/Database-Ballots.cs +++ b/Database/Database-Ballots.cs @@ -11,8 +11,8 @@ namespace Swarmops.Database #region Field reading code private const string ballotFieldSequence = - " BallotId,ElectionId,Name,OrganizationId,GeographyId," + // 0-4 - "BallotCount,DeliveryAddress " + // 5-6 + " BallotId,ElectionId,Name,OrganizationId,GeographyId," + // 0-4 + "BallotCount,DeliveryAddress " + // 5-6 "FROM Ballots "; private static BasicBallot ReadBallotFromDataReader(IDataRecord reader) @@ -30,8 +30,6 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements public BasicBallot GetBallot(int ballotId) @@ -51,7 +49,7 @@ namespace Swarmops.Database return ReadBallotFromDataReader(reader); } - throw new ArgumentException("Unknown Ballot Id: " + ballotId.ToString()); + throw new ArgumentException("Unknown Ballot Id: " + ballotId); } } } @@ -91,7 +89,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT PersonId FROM BallotCandidates WHERE BallotId=" + ballotId + " ORDER BY SortOrder", connection); + "SELECT PersonId FROM BallotCandidates WHERE BallotId=" + ballotId + " ORDER BY SortOrder", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -116,7 +115,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT PersonId FROM CandidateDocumentation WHERE ElectionId=" + electionId + " AND OrganizationId=" + organizationId, connection); + "SELECT PersonId FROM CandidateDocumentation WHERE ElectionId=" + electionId + + " AND OrganizationId=" + organizationId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -130,7 +130,7 @@ namespace Swarmops.Database } } - public Dictionary GetBallotsForPerson (int personId) + public Dictionary GetBallotsForPerson(int personId) { Dictionary result = new Dictionary(); @@ -146,7 +146,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result [reader.GetInt32(0)] = reader.GetInt32(1); + result[reader.GetInt32(0)] = reader.GetInt32(1); } return result; @@ -154,14 +154,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public int CreateBallot (int electionId, string name, int organizationId, int geographyId, int ballotCount, string deliveryAddress) + public int CreateBallot(int electionId, string name, int organizationId, int geographyId, int ballotCount, + string deliveryAddress) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -215,7 +213,6 @@ namespace Swarmops.Database } - public void CreateBallotCandidate(int ballotId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -267,6 +264,5 @@ namespace Swarmops.Database } #endregion - } } \ No newline at end of file diff --git a/Database/Database-CashAdvances.cs b/Database/Database-CashAdvances.cs index 91f269d5..3e7a7f22 100644 --- a/Database/Database-CashAdvances.cs +++ b/Database/Database-CashAdvances.cs @@ -8,13 +8,12 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string cashAdvanceFieldSequence = - " CashAdvanceId,OrganizationId,PersonId,CreatedDateTime,CreatedByPersonId," + // 0-4 - "FinancialAccountId,AmountCents,Description,Open,Attested," + // 5-9 - "PaidOut,AttestedByPersonId,AttestedDateTime " + // 10-12 + " CashAdvanceId,OrganizationId,PersonId,CreatedDateTime,CreatedByPersonId," + // 0-4 + "FinancialAccountId,AmountCents,Description,Open,Attested," + // 5-9 + "PaidOut,AttestedByPersonId,AttestedDateTime " + // 10-12 "FROM CashAdvances "; private static BasicCashAdvance ReadCashAdvanceFromDataReader(IDataRecord reader) @@ -40,14 +39,11 @@ namespace Swarmops.Database paidOut, attestedByPersonId, attestedDateTime); } - #endregion - #region Database record reading -- SELECT clauses - - public BasicCashAdvance GetCashAdvance (int cashAdvanceId) + public BasicCashAdvance GetCashAdvance(int cashAdvanceId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -55,8 +51,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT " + cashAdvanceFieldSequence + - " WHERE CashAdvanceId=" + cashAdvanceId.ToString(), - connection); + " WHERE CashAdvanceId=" + cashAdvanceId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -65,10 +61,9 @@ namespace Swarmops.Database return ReadCashAdvanceFromDataReader(reader); } - throw new ArgumentException("No such CashAdvanceId:" + cashAdvanceId.ToString()); + throw new ArgumentException("No such CashAdvanceId:" + cashAdvanceId); } } - } @@ -82,7 +77,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + cashAdvanceFieldSequence + ConstructWhereClause("CashAdvances", conditions), connection); + "SELECT " + cashAdvanceFieldSequence + ConstructWhereClause("CashAdvances", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -96,13 +92,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - public int CreateCashAdvance(int personId, int createdByPersonId, int organizationId, int financialAccountId, Int64 amountCents, string description) { @@ -183,10 +176,8 @@ namespace Swarmops.Database } } - #endregion - #region Dead template code /* @@ -530,7 +521,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-ChurnData.cs b/Database/Database-ChurnData.cs index 568cc618..7d05792d 100644 --- a/Database/Database-ChurnData.cs +++ b/Database/Database-ChurnData.cs @@ -13,10 +13,10 @@ namespace Swarmops.Database #region Field reading code private const string churnDataFieldSequence = - " PersonId,OrganizationId,Churn,DecisionDateTime,ExpiryDateTime " + // 0-4 + " PersonId,OrganizationId,Churn,DecisionDateTime,ExpiryDateTime " + // 0-4 " FROM ChurnData "; - static private BasicChurnDataPoint ReadChurnDataPointFromDataReader (DbDataReader reader) + private static BasicChurnDataPoint ReadChurnDataPointFromDataReader(DbDataReader reader) { int personId = reader.GetInt32(0); int organizationId = reader.GetInt32(1); @@ -25,15 +25,14 @@ namespace Swarmops.Database DateTime expiryDateTime = reader.GetDateTime(4); return new BasicChurnDataPoint(churn ? ChurnDataType.Churn : ChurnDataType.Retention, decisionDateTime, - expiryDateTime, personId, organizationId); + expiryDateTime, personId, organizationId); } #endregion - #region Record reading code -- SELECT statements - public BasicChurnDataPoint[] GetChurnData (params object[] conditions) + public BasicChurnDataPoint[] GetChurnData(params object[] conditions) { List result = new List(); @@ -59,8 +58,8 @@ namespace Swarmops.Database } - public BasicChurnDataPoint[] GetChurnDataForOrganization (IHasIdentity organization, DateTime lowerDate, - DateTime upperDate) + public BasicChurnDataPoint[] GetChurnDataForOrganization(IHasIdentity organization, DateTime lowerDate, + DateTime upperDate) { // Since I don't trust SQL Server to make correct date comparisons, especially given // that the dates are passed in text in SQL, we get ALL the data and do @@ -71,7 +70,7 @@ namespace Swarmops.Database DateTime maximumDateTime = upperDate.Date.AddDays(1); List result = new List(); - BasicChurnDataPoint[] rawData = this.GetChurnData(organization); + BasicChurnDataPoint[] rawData = GetChurnData(organization); foreach (BasicChurnDataPoint churnPoint in rawData) { @@ -86,10 +85,9 @@ namespace Swarmops.Database return result.ToArray(); } - + #endregion - #region Record creation and manipulation code -- stored procedures public int LogChurnData(int personId, int organizationId, bool churn, DateTime expiryDateTime) @@ -98,7 +96,7 @@ namespace Swarmops.Database } public int LogChurnData(int personId, int organizationId, bool churn, DateTime expiryDateTime, - DateTime decisionDateTime) + DateTime decisionDateTime) { using (DbConnection connection = GetMySqlDbConnection()) { diff --git a/Database/Database-CommunicationTurnarounds.cs b/Database/Database-CommunicationTurnarounds.cs index dae1b8ed..187ced3e 100644 --- a/Database/Database-CommunicationTurnarounds.cs +++ b/Database/Database-CommunicationTurnarounds.cs @@ -11,8 +11,8 @@ namespace Swarmops.Database #region Field reading code private const string communicationTurnaroundFieldSequence = - " OrganizationId,CommunicationTypeId,CommunicationId,DateTimeOpened,DateTimeFirstResponse," + // 0-4 - "PersonIdFirstResponse,DateTimeClosed,PersonIdClosed,Open,Responded " + // 5-9 + " OrganizationId,CommunicationTypeId,CommunicationId,DateTimeOpened,DateTimeFirstResponse," + // 0-4 + "PersonIdFirstResponse,DateTimeClosed,PersonIdClosed,Open,Responded " + // 5-9 "FROM CommunicationTurnarounds "; private static BasicCommunicationTurnaround ReadCommunicationTurnaroundFromDataReader(IDataRecord reader) @@ -28,17 +28,16 @@ namespace Swarmops.Database bool open = reader.GetBoolean(8); bool awaitingResponse = reader.GetBoolean(9); - return new BasicCommunicationTurnaround(organizationId, communicationTypeId, communicationId, dateTimeOpened, dateTimeFirstResponse, personIdFirstResponse, dateTimeClosed, personIdClosed, open, awaitingResponse); + return new BasicCommunicationTurnaround(organizationId, communicationTypeId, communicationId, dateTimeOpened, + dateTimeFirstResponse, personIdFirstResponse, dateTimeClosed, personIdClosed, open, awaitingResponse); } #endregion - - #region Record reading - SELECT statements - - public BasicCommunicationTurnaround GetCommunicationTurnaround (int organizationId, int communicationTypeId, int communicationId) + public BasicCommunicationTurnaround GetCommunicationTurnaround(int organizationId, int communicationTypeId, + int communicationId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -46,7 +45,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + communicationTurnaroundFieldSequence + "WHERE OrganizationId=" + organizationId.ToString() + " AND CommunicationTypeId=" + communicationTypeId.ToString() + " AND CommunicationId=" + communicationId.ToString() + ";", connection); + "SELECT" + communicationTurnaroundFieldSequence + "WHERE OrganizationId=" + organizationId + + " AND CommunicationTypeId=" + communicationTypeId + " AND CommunicationId=" + communicationId + + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -55,7 +56,7 @@ namespace Swarmops.Database return ReadCommunicationTurnaroundFromDataReader(reader); } - throw new ArgumentException("Unknown Communication Id: " + communicationId.ToString()); + throw new ArgumentException("Unknown Communication Id: " + communicationId); } } } @@ -71,7 +72,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + communicationTurnaroundFieldSequence + ConstructWhereClause("CommunicationTurnarounds", conditions) + " ORDER BY DateTimeOpened", connection); + "SELECT" + communicationTurnaroundFieldSequence + + ConstructWhereClause("CommunicationTurnarounds", conditions) + " ORDER BY DateTimeOpened", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -85,14 +88,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public void CreateCommunicationTurnaround (int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeOpened) + public void CreateCommunicationTurnaround(int organizationId, int communicationTypeId, int communicationId, + DateTime dateTimeOpened) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -111,7 +112,8 @@ namespace Swarmops.Database } - public void SetCommunicationTurnaroundResponded(int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeResponded, int personIdResponded) + public void SetCommunicationTurnaroundResponded(int organizationId, int communicationTypeId, int communicationId, + DateTime dateTimeResponded, int personIdResponded) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -127,12 +129,12 @@ namespace Swarmops.Database AddParameterWithName(command, "personIdResponded", personIdResponded); command.ExecuteNonQuery(); - } } - public void SetCommunicationTurnaroundClosed(int organizationId, int communicationTypeId, int communicationId, DateTime dateTimeClosed, int personIdClosed) + public void SetCommunicationTurnaroundClosed(int organizationId, int communicationTypeId, int communicationId, + DateTime dateTimeClosed, int personIdClosed) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -148,14 +150,9 @@ namespace Swarmops.Database AddParameterWithName(command, "personIdClosed", personIdClosed); command.ExecuteNonQuery(); - } } - - - #endregion - } } \ No newline at end of file diff --git a/Database/Database-Conditions.cs b/Database/Database-Conditions.cs index ea18f3b8..861b3bb6 100644 --- a/Database/Database-Conditions.cs +++ b/Database/Database-Conditions.cs @@ -8,7 +8,7 @@ namespace Swarmops.Database public partial class SwarmDb { /// - /// Constructs a WHERE clause for a table. + /// Constructs a WHERE clause for a table. /// /// The table name, exactly as in the database. /// A sequence of IHasIdentity and/or DatabaseCondition objects. @@ -17,7 +17,7 @@ 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); @@ -33,9 +33,9 @@ namespace Swarmops.Database /// - /// Internal. Recurses for ConstructWhereClause. + /// 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(); @@ -51,16 +51,16 @@ namespace Swarmops.Database } else if (condition is DatabaseCondition) { - if ((DatabaseCondition)condition != DatabaseCondition.None) + 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); } - else if (condition is object[]) // params object inherited and added to -- recurse + else if (condition is object[]) // params object inherited and added to -- recurse { List recursed = ConstructWhereClauseRecurse(tableName, condition); @@ -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.ToString() + " "; + 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. @@ -117,21 +117,22 @@ namespace Swarmops.Database { // No ids to match. Make sure that no record is returned by asking for identity 0, which doesn't exist - identities = new int[1] { 0 }; + 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) { - typeString = ((DbRecordType)attribute).TypeName; + typeString = ((DbRecordType) attribute).TypeName; } } if (typeString == "") @@ -149,7 +150,7 @@ namespace Swarmops.Database } - private static string GetWhereClauseForCondition (DatabaseCondition condition) + private static string GetWhereClauseForCondition(DatabaseCondition condition) { switch (condition) { @@ -168,12 +169,12 @@ namespace Swarmops.Database default: throw new InvalidOperationException( "Undefined or unimplemented DatabaseCondition in GetWhereClauseForCondition: " + - condition.ToString()); + condition); } } - private static string JoinWhereClauses (params string[] clauses) + private static string JoinWhereClauses(params string[] clauses) { string result = string.Empty; @@ -198,37 +199,43 @@ namespace Swarmops.Database public enum DatabaseCondition { /// - /// Undefined + /// Undefined /// Unknown, + /// - /// Retrieve only records where Open is true. + /// Retrieve only records where Open is true. /// OpenTrue, + /// - /// Retrieve only records where Open is false (closed records). + /// Retrieve only records where Open is false (closed records). /// OpenFalse, + /// - /// Retrieve only records where Attested is true. + /// Retrieve only records where Attested is true. /// AttestedTrue, + /// - /// Retreieve only records where Attested is false. + /// Retreieve only records where Attested is false. /// AttestedFalse, + /// - /// Retrieve only records where activists, memberships etc. are active. + /// Retrieve only records where activists, memberships etc. are active. /// ActiveTrue, + /// - /// Retrieve only records where activsts, memberships are closed/deactivated. + /// Retrieve only records where activsts, memberships are closed/deactivated. /// ActiveFalse, + /// - /// No condition + /// No condition /// None } - } \ No newline at end of file diff --git a/Database/Database-ConnectionsCommands.cs b/Database/Database-ConnectionsCommands.cs index 4f0f5c5f..4853b6d3 100644 --- a/Database/Database-ConnectionsCommands.cs +++ b/Database/Database-ConnectionsCommands.cs @@ -2,6 +2,7 @@ using System; using System.Configuration; using System.Data; using System.Data.Common; +using System.Data.SqlClient; using System.Security; using System.Text; using MySql.Data.MySqlClient; @@ -10,14 +11,14 @@ namespace Swarmops.Database { public partial class SwarmDb { - public DbConnection GetSqlServerDbConnection() // Temporarily public for migratory purposes + public DbConnection GetSqlServerDbConnection() // Temporarily public for migratory purposes { - DbConnection connection = ProviderFactory.CreateConnection(); - connection.ConnectionString = ConnectionString; + DbConnection connection = this.ProviderFactory.CreateConnection(); + connection.ConnectionString = this.ConnectionString; return connection; } - protected DbConnection GetMySqlDbConnection () // This is a temporary function used during transition to MySql. + protected DbConnection GetMySqlDbConnection() // This is a temporary function used during transition to MySql. { DbConnection connection = new MySqlConnection(); @@ -35,15 +36,16 @@ namespace Swarmops.Database //-------- end change /JL if (specialConnectString == "") - specialConnectString = ConnectionString; - specialConnectString = specialConnectString.Replace("192.168.0.5", "192.168.0.7"); // for dev & debug at Rick's + specialConnectString = this.ConnectionString; + 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") @@ -66,7 +68,7 @@ namespace Swarmops.Database 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") { @@ -76,27 +78,27 @@ namespace Swarmops.Database if (value is Type) { - if ((Type) value == typeof(int)) + if ((Type) value == typeof (int)) { parameterType = SqlDbType.Int; } - else if ((Type)value == typeof(DateTime)) + else if ((Type) value == typeof (DateTime)) { parameterType = SqlDbType.DateTime; } - else if ((Type)value == typeof(bool)) + else if ((Type) value == typeof (bool)) { parameterType = SqlDbType.Bit; } - else if ((Type)value == typeof(double) || (Type)value == typeof(float)) + else if ((Type) value == typeof (double) || (Type) value == typeof (float)) { parameterType = SqlDbType.Float; } - else if ((Type)value == typeof(decimal)) + else if ((Type) value == typeof (decimal)) { parameterType = SqlDbType.Money; } - else if (!((Type)value == typeof(string))) + else if (!((Type) value == typeof (string))) { throw new Exception("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); } @@ -127,34 +129,34 @@ namespace Swarmops.Database throw new Exception("Unhandled parameter type in AddParameterWithName: " + value.GetType().Name); } - System.Data.SqlClient.SqlParameter parameter = null; + SqlParameter parameter = null; if (parameterType == SqlDbType.NText) { int textLength = 256*2; if (value != DBNull.Value) { - textLength = (value as string).Length * 2; // ntext / unicode buffer + textLength = (value as string).Length*2; // ntext / unicode buffer // establish a minimum amount of even 256-byte blocks that this string will fit in textLength += 2; // terminating zero, in unicode - textLength -= (textLength % 256); + textLength -= (textLength%256); textLength += 256; } - parameter = new System.Data.SqlClient.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 System.Data.SqlClient.SqlParameter("@" + parameterName, parameterType); + parameter = new SqlParameter("@" + parameterName, parameterType); } parameter.Value = value; - System.Data.SqlClient.SqlParameterCollection sqlCollection = - command.Parameters as System.Data.SqlClient.SqlParameterCollection; + SqlParameterCollection sqlCollection = + command.Parameters as SqlParameterCollection; sqlCollection.Add(parameter); } @@ -179,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) { @@ -200,7 +202,7 @@ namespace Swarmops.Database } // 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) { @@ -219,9 +221,9 @@ namespace Swarmops.Database 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"); } @@ -229,7 +231,11 @@ namespace Swarmops.Database private string SqlSanitize(string input) { - string[] forbiddenArray = {"\\", "--", ";", "/*", "*/", "select ", "drop ", "update ", "delete ", "insert ", "="}; + string[] forbiddenArray = + { + "\\", "--", ";", "/*", "*/", "select ", "drop ", "update ", "delete ", "insert ", + "=" + }; string output = input.Replace("'", "''"); // the typical case string inputLower = input.ToLowerInvariant(); @@ -237,7 +243,8 @@ namespace Swarmops.Database { 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 8eb0d3dd..86f1b305 100644 --- a/Database/Database-Constructors.cs +++ b/Database/Database-Constructors.cs @@ -7,10 +7,54 @@ using Swarmops.Basic.Diagnostics; namespace Swarmops.Database { /// - /// A generic database handler + /// A generic database handler /// public partial class SwarmDb { + private const string AppConfigFile = @"database.config"; + private const string WebConfigFile = @"~/database.config"; + private const string MonoConfigFile = @"/etc/swarmops/database.config"; + + private const string DefaultProviderName = "MySql.Data.MySqlClient"; + + // The cached values used by GetDatabase() + private static string _cachedConnectionString; + private readonly string ConnectionString; + private readonly DbProviderFactory ProviderFactory; + + [Obsolete("Do not use. Hardwireto MySQL.")] + public SwarmDb(DbProviderFactory ProviderFactory, string ConnectionString) + { + this.ProviderFactory = ProviderFactory; + this.ConnectionString = ConnectionString; + } + + public SwarmDb(string connectionString) + { + this.ConnectionString = connectionString; + } + + /// + /// The actual revision of the database (as told by the database). + /// + public static int DbVersion + { + get + { + // TODO: Cache for some ten minutes, perhaps? + + string dbVersionString = GetDatabaseForReading().GetKeyValue("DbVersion"); + + if (string.IsNullOrEmpty(dbVersionString)) + { + GetDatabaseForWriting().SetKeyValue("DbVersion", "1"); + return 1; + } + + return Int32.Parse(dbVersionString); + } + } + public static SwarmDb GetDatabaseForReading() { return new SwarmDb(ConstructConnectString(new Configuration().Get().Read)); @@ -32,47 +76,28 @@ namespace Swarmops.Database if (Configuration.IsConfigured()) { - throw new UnauthorizedAccessException("Cannot probe arbitrary database credentials once database initialized"); + throw new UnauthorizedAccessException( + "Cannot probe arbitrary database credentials once database initialized"); } 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=" + credentials.Database + - ";user=" + credentials.Username + ";password=" + credentials.Password; + return "server=" + credentials.ServerSet.ServerPriorities[0].Split(';')[0] + ";database=" + + credentials.Database + + ";user=" + credentials.Username + ";password=" + credentials.Password; } - /// - /// The actual revision of the database (as told by the database). - /// - public static int DbVersion - { - get - { - // TODO: Cache for some ten minutes, perhaps? - - string dbVersionString = GetDatabaseForReading().GetKeyValue("DbVersion"); - - if (string.IsNullOrEmpty(dbVersionString)) - { - GetDatabaseForWriting().SetKeyValue("DbVersion", "1"); - return 1; - } - - return Int32.Parse(dbVersionString); - } - } - - [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."); } - [Obsolete ("Do not use. Use GetDatabaseForAdmin().", true)] + [Obsolete("Do not use. Use GetDatabaseForAdmin().", true)] public static SwarmDb GetDatabaseAsAdmin() { string connectionString = string.Empty; @@ -88,21 +113,23 @@ namespace Swarmops.Database connectionString = reader.ReadLine(); Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized for Linux Backend: [" + connectionString + "]"); + "SwarmDb initialized for Linux Backend: [" + connectionString + "]"); } } else if (HttpContext.Current != null) { // 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"))) + using ( + StreamReader reader = + new StreamReader( + HttpContext.Current.Server.MapPath(WebConfigFile.Replace(".config", "-admin.config"))) ) { connectionString = reader.ReadLine(); Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized for web: [" + connectionString + "]"); + "SwarmDb initialized for web: [" + connectionString + "]"); } - } else { @@ -113,8 +140,8 @@ namespace Swarmops.Database connectionString = reader.ReadLine(); Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized for application: [" + connectionString + - "]"); + "SwarmDb initialized for application: [" + connectionString + + "]"); } } } @@ -137,11 +164,15 @@ namespace Swarmops.Database { string hostName = HttpContext.Current.Request.Url.Host; - connectionString = "server=peregrine;database=" + hostName + ";user=" + hostName + "-admin;password=" + hostName +"-admin"; // TODO: Replace "peregrine" with "localhost" + connectionString = "server=peregrine;database=" + hostName + ";user=" + hostName + + "-admin;password=" + hostName + "-admin"; + // TODO: Replace "peregrine" with "localhost" } else { - 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 + 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 } } @@ -153,31 +184,5 @@ namespace Swarmops.Database return new SwarmDb(DbProviderFactories.GetFactory(DefaultProviderName), connectionString); } - - [Obsolete ("Do not use. Hardwireto MySQL.")] - public SwarmDb(DbProviderFactory ProviderFactory, string ConnectionString) - { - this.ProviderFactory = ProviderFactory; - this.ConnectionString = ConnectionString; - } - - public SwarmDb(string connectionString) - { - this.ConnectionString = connectionString; - } - - // The instance connection details. - private DbProviderFactory ProviderFactory; - private string ConnectionString; - - // config file used by GetDatabase() - private const string AppConfigFile = @"database.config"; - private const string WebConfigFile = @"~/database.config"; - private const string MonoConfigFile = @"/etc/swarmops/database.config"; - - private const string DefaultProviderName = "MySql.Data.MySqlClient"; - - // The cached values used by GetDatabase() - private static string _cachedConnectionString = null; } -} +} \ No newline at end of file diff --git a/Database/Database-Countries.cs b/Database/Database-Countries.cs index 20b22c33..a7b23186 100644 --- a/Database/Database-Countries.cs +++ b/Database/Database-Countries.cs @@ -10,8 +10,8 @@ namespace Swarmops.Database { #region Field reading code - private const string countryFieldSequence = " CountryId,Name,Code,Culture,CurrencyCode," + // 0-4 - "GeographyId,PostalCodeLength FROM Countries "; // 5-6 + private const string countryFieldSequence = " CountryId,Name,Code,Culture,CurrencyCode," + // 0-4 + "GeographyId,PostalCodeLength FROM Countries "; // 5-6 private static BasicCountry ReadCountryFromDataReader(DbDataReader reader) @@ -29,18 +29,19 @@ namespace Swarmops.Database #endregion - #region Record reading code - public BasicCountry GetCountry (string countryCode) + public BasicCountry GetCountry(string countryCode) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + countryFieldSequence + " WHERE Code='" + countryCode.ToUpperInvariant().Replace("'", "''") + "'", - connection); + GetDbCommand( + "SELECT " + countryFieldSequence + " WHERE Code='" + + countryCode.ToUpperInvariant().Replace("'", "''") + "'", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -54,14 +55,14 @@ namespace Swarmops.Database } } - public BasicCountry GetCountry (int countryId) + public BasicCountry GetCountry(int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + countryFieldSequence + " WHERE CountryId=" + countryId.ToString(), - connection); + DbCommand command = GetDbCommand("SELECT " + countryFieldSequence + " WHERE CountryId=" + countryId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -75,7 +76,7 @@ namespace Swarmops.Database } } - public BasicCountry[] GetAllCountries () + public BasicCountry[] GetAllCountries() { List result = new List(); @@ -97,7 +98,7 @@ namespace Swarmops.Database } } - public BasicCountry[] GetCountriesInUse () + public BasicCountry[] GetCountriesInUse() { return GetAllCountries(); // Migrate this once Organizations has moved, too @@ -124,9 +125,8 @@ namespace Swarmops.Database #endregion - - - public int CreateCountry (string name, string code, string culture, int geographyId, int postalCodeLength, string collation) + public int CreateCountry(string name, string code, string culture, int geographyId, int postalCodeLength, + string collation) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -146,7 +146,7 @@ namespace Swarmops.Database } } - public int SetCountryGeographyId (int countryId, int geographyId) + public int SetCountryGeographyId(int countryId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -157,11 +157,9 @@ namespace Swarmops.Database AddParameterWithName(command, "countryId", countryId); AddParameterWithName(command, "geographyId", geographyId); - + return Convert.ToInt32(command.ExecuteScalar()); } } - - } } \ No newline at end of file diff --git a/Database/Database-Currencies.cs b/Database/Database-Currencies.cs index 9387ad0c..a747421f 100644 --- a/Database/Database-Currencies.cs +++ b/Database/Database-Currencies.cs @@ -11,7 +11,7 @@ namespace Swarmops.Database #region Field reading code private const string currencyFieldSequence = - " CurrencyId,Code,Name,Sign " + // 0-3 + " CurrencyId,Code,Name,Sign " + // 0-3 "FROM Currencies "; private static BasicCurrency ReadCurrencyFromDataReader(IDataRecord reader) @@ -26,8 +26,6 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements public BasicCurrency GetCurrency(int currencyId) @@ -47,7 +45,7 @@ namespace Swarmops.Database return ReadCurrencyFromDataReader(reader); } - throw new ArgumentException("Unknown Currency Id: " + currencyId.ToString()); + throw new ArgumentException("Unknown Currency Id: " + currencyId); } } } @@ -60,7 +58,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + currencyFieldSequence + "WHERE Code='" + currencyCode.Replace("'", "''").ToUpperInvariant() + "';", connection); + "SELECT" + currencyFieldSequence + "WHERE Code='" + + currencyCode.Replace("'", "''").ToUpperInvariant() + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -99,11 +98,8 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures public int CreateCurrency(string code, string name, string sign) @@ -126,7 +122,7 @@ namespace Swarmops.Database } - public int SetCurrencyExchangeRate (DateTime date, int currencyId, double eur100) + public int SetCurrencyExchangeRate(DateTime date, int currencyId, double eur100) { DateTime now = DateTime.Now; @@ -144,6 +140,7 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } + /* public void SetSalaryNetPaid(int salaryId, bool netPaid) @@ -223,8 +220,6 @@ namespace Swarmops.Database } */ - #endregion - } } \ No newline at end of file diff --git a/Database/Database-Documents.cs b/Database/Database-Documents.cs index 1a00979f..929bbe08 100644 --- a/Database/Database-Documents.cs +++ b/Database/Database-Documents.cs @@ -48,7 +48,7 @@ namespace Swarmops.Database "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 " + - "DocumentTypes.Name = '" + documentType.ToString() + "';", connection); + "DocumentTypes.Name = '" + documentType + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -75,7 +75,7 @@ namespace Swarmops.Database "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.UploadedDateTime > '" + DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd HH:mm") + "'"; DbCommand command = GetDbCommand(sqlQuery, connection); @@ -105,12 +105,12 @@ namespace Swarmops.Database DateTime uploadedDateTime = reader.GetDateTime(8); return new BasicDocument(documentId, serverFileName, clientFileName, description, docType, - foreignId, fileSize, uploadedByPersonId, uploadedDateTime); + foreignId, fileSize, uploadedByPersonId, uploadedDateTime); } - - public int CreateDocument(string serverFileName, string clientFileName, long fileSize, string description, DocumentType documentType, int foreignId, int uploadedByPersonId) + public int CreateDocument(string serverFileName, string clientFileName, long fileSize, string description, + DocumentType documentType, int foreignId, int uploadedByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -147,7 +147,6 @@ namespace Swarmops.Database } - public void SetDocumentServerFileName(int documentId, string serverFileName) { using (DbConnection connection = GetMySqlDbConnection()) @@ -200,7 +199,6 @@ namespace Swarmops.Database } - // The rest was copied from Database-Financials as template code. /* diff --git a/Database/Database-Events.cs b/Database/Database-Events.cs index fb6e296f..443c797d 100644 --- a/Database/Database-Events.cs +++ b/Database/Database-Events.cs @@ -12,19 +12,21 @@ namespace Swarmops.Database #region Field reading code private const string pwEventFieldSequence = - " PWEvents.EventId, PWEventTypes.Name AS EventType, PWEventSources.Name AS EventSource, PWEvents.ActingPersonId, PWEvents.AffectedPersonId, " + // 0-4 - " PWEvents.CreatedDateTime, PWEvents.ProcessedDateTime, PWEvents.Open, PWEvents.OrganizationId, PWEvents.GeographyId, " + // 5-9 + " PWEvents.EventId, PWEventTypes.Name AS EventType, PWEventSources.Name AS EventSource, PWEvents.ActingPersonId, PWEvents.AffectedPersonId, " + + // 0-4 + " PWEvents.CreatedDateTime, PWEvents.ProcessedDateTime, PWEvents.Open, PWEvents.OrganizationId, PWEvents.GeographyId, " + + // 5-9 " PWEvents.ParameterInt, PWEvents.ParameterText " + // 10-11 " FROM PWEvents " + " JOIN PWEventTypes ON (PWEvents.EventTypeId=PWEventTypes.EventTypeId) " + " 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)); + 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); @@ -35,36 +37,14 @@ namespace Swarmops.Database int parameterInt = reader.GetInt32(10); string parameterText = reader.GetString(11); - return new BasicPWEvent(eventId, eventDateTime, open, processedDateTime, eventType, eventSource, actingPersonId, + return new BasicPWEvent(eventId, eventDateTime, open, processedDateTime, eventType, eventSource, + actingPersonId, affectedPersonId, organizationId, geographyId, parameterInt, parameterText); } #endregion - - public BasicPWEvent[] GetTopUnprocessedEvents () - { - List result = new List(); - - using (DbConnection connection = GetMySqlDbConnection()) - { - connection.Open(); - - DbCommand command = GetDbCommand("SELECT " + pwEventFieldSequence + " WHERE Open=1 AND ProcessDateTime < NOW() LIMIT 10", connection); - - using (DbDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - result.Add(ReadPWEventFromDataReader(reader)); - } - - return result.ToArray(); - } - } - } - - public BasicPWEvent[] GetEventsForPerson (int personId) + public BasicPWEvent[] GetTopUnprocessedEvents() { List result = new List(); @@ -74,7 +54,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + pwEventFieldSequence + " WHERE AffectedPersonId=" + personId + " ORDER BY CreatedDateTime", + "SELECT " + pwEventFieldSequence + " WHERE Open=1 AND ProcessDateTime < NOW() LIMIT 10", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -88,13 +68,40 @@ namespace Swarmops.Database } } } - public Dictionary> GetEventsForPersons (int[] personId, EventType[] eventTypes) + + public BasicPWEvent[] GetEventsForPerson(int personId) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT " + pwEventFieldSequence + " WHERE AffectedPersonId=" + personId + + " ORDER BY CreatedDateTime", + connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadPWEventFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + public Dictionary> GetEventsForPersons(int[] personId, EventType[] eventTypes) { Dictionary> result = new Dictionary>(); List eventTypesAsString = new List(); foreach (EventType et in eventTypes) eventTypesAsString.Add(et.ToString()); - + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -103,7 +110,10 @@ namespace Swarmops.Database GetDbCommand( "SELECT " + pwEventFieldSequence + " WHERE AffectedPersonId IN (" + JoinIds(personId) + ") " - + (eventTypes.Length > 0 ? " AND PWEventTypes.Name IN (" + JoinStrings(eventTypesAsString.ToArray()) + ") " : "") + + + (eventTypes.Length > 0 + ? " AND PWEventTypes.Name IN (" + JoinStrings(eventTypesAsString.ToArray()) + ") " + : "") + " ORDER BY CreatedDateTime desc", connection); @@ -122,7 +132,7 @@ namespace Swarmops.Database } } - public BasicPWEvent[] GetEventsOfType (EventType eventType) + public BasicPWEvent[] GetEventsOfType(EventType eventType) { List result = new List(); @@ -132,7 +142,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + pwEventFieldSequence + " WHERE PWEventTypes.Name='" + eventType.ToString() + + "SELECT " + pwEventFieldSequence + " WHERE PWEventTypes.Name='" + eventType + "' ORDER BY CreatedDateTime", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -148,19 +158,18 @@ namespace Swarmops.Database } - - public int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, - int organizationId, - int geographyId, int affectedPersonId, int parameterInt, string parameterText) + 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, - parameterInt, parameterText, DateTime.Now); + parameterInt, parameterText, DateTime.Now); } - public int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, - int organizationId, - int geographyId, int affectedPersonId, int parameterInt, string parameterText, - DateTime processTime) + public int CreateEvent(EventSource eventSource, EventType eventType, int actingPersonId, + int organizationId, + int geographyId, int affectedPersonId, int parameterInt, string parameterText, + DateTime processTime) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -183,7 +192,7 @@ namespace Swarmops.Database } } - public void SetEventProcessed (int eventId) + public void SetEventProcessed(int eventId) { using (DbConnection connection = GetMySqlDbConnection()) { diff --git a/Database/Database-ExceptionLog.cs b/Database/Database-ExceptionLog.cs index 1abe53a0..42d4b955 100644 --- a/Database/Database-ExceptionLog.cs +++ b/Database/Database-ExceptionLog.cs @@ -8,11 +8,11 @@ namespace Swarmops.Database { public partial class SwarmDb { - private const string exceptionLogFieldSequence = " ExceptionID, ExceptionDateTime, Source,ExceptionText FROM ExceptionLog "; + 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); @@ -20,7 +20,7 @@ namespace Swarmops.Database 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 { @@ -42,13 +42,11 @@ namespace Swarmops.Database { //never fail from this routine, it is used in exceptionhandlig, // and if it isn't possible log the error then so be it. - return; } } - - public BasicExceptionLog[] GetExceptionLogTopEntries (int count) + public BasicExceptionLog[] GetExceptionLogTopEntries(int count) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -71,7 +69,6 @@ namespace Swarmops.Database return result.ToArray(); } } - } } } \ No newline at end of file diff --git a/Database/Database-Expenses.cs b/Database/Database-Expenses.cs index 1f52658d..e9714ccf 100644 --- a/Database/Database-Expenses.cs +++ b/Database/Database-Expenses.cs @@ -9,7 +9,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicExpenseClaim GetExpenseClaim (int expenseClaimId) + public BasicExpenseClaim GetExpenseClaim(int expenseClaimId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -19,7 +19,7 @@ namespace Swarmops.Database "SELECT ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + - "FROM ExpenseClaims WHERE ExpenseClaimId=" + expenseClaimId.ToString(), + "FROM ExpenseClaims WHERE ExpenseClaimId=" + expenseClaimId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -44,10 +44,10 @@ namespace Swarmops.Database 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), - connection); + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims " + ConstructWhereClause("ExpenseClaims", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -71,10 +71,10 @@ namespace Swarmops.Database 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.ToString(), - connection); + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE ClaimingPersonId=" + claimingPersonId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -98,10 +98,11 @@ namespace Swarmops.Database 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.ToString() + " AND OrganizationId=" + organizationId.ToString(), - connection); + "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()) { @@ -125,10 +126,10 @@ namespace Swarmops.Database 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.ToString() + " AND BudgetYear=" + budgetYear.ToString(), - connection); + "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()) { @@ -152,10 +153,10 @@ namespace Swarmops.Database 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.ToString(), - connection); + "Validated,Claimed,OrganizationId,GeographyId,BudgetId," + + "ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid,KeepSeparate " + + "FROM ExpenseClaims WHERE OrganizationId=" + organizationId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -170,7 +171,7 @@ namespace Swarmops.Database } - private BasicExpenseClaim ReadExpenseFromDataReader (DbDataReader reader) + private BasicExpenseClaim ReadExpenseFromDataReader(DbDataReader reader) { int expenseClaimId = reader.GetInt32(0); int claimingPersonId = reader.GetInt32(1); @@ -190,14 +191,14 @@ namespace Swarmops.Database bool keepSeparate = reader.GetBoolean(15); return new BasicExpenseClaim(expenseClaimId, claimingPersonId, createdDateTime, - open, attested, documented, claimed, organizationId, geographyId, - budgetId, expenseDate, description, preApprovedAmount, - amountCents, repaid, keepSeparate); + open, attested, documented, claimed, organizationId, geographyId, + budgetId, expenseDate, description, preApprovedAmount, + amountCents, repaid, keepSeparate); } public int CreateExpenseClaim(int claimingPersonId, int organizationId, int budgetId, - DateTime expenseDate, string description, double amount) + DateTime expenseDate, string description, double amount) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -218,7 +219,7 @@ namespace Swarmops.Database } public int CreateExpenseClaim(int claimingPersonId, int organizationId, int budgetId, - DateTime expenseDate, string description, Int64 amountCents) + DateTime expenseDate, string description, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -256,7 +257,7 @@ namespace Swarmops.Database } - public int SetExpenseClaimBudget (int expenseClaimId, int budgetId) + public int SetExpenseClaimBudget(int expenseClaimId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -273,7 +274,7 @@ namespace Swarmops.Database } - public int SetExpenseClaimBudgetYear (int expenseClaimId, int budgetYear) + public int SetExpenseClaimBudgetYear(int expenseClaimId, int budgetYear) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -290,7 +291,7 @@ namespace Swarmops.Database } - public int SetExpenseClaimDate (int expenseClaimId, DateTime expenseDate) + public int SetExpenseClaimDate(int expenseClaimId, DateTime expenseDate) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -324,7 +325,6 @@ namespace Swarmops.Database } - public int SetExpenseClaimAmount(int expenseClaimId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -342,7 +342,6 @@ namespace Swarmops.Database } - public int SetExpenseClaimAttested(int expenseClaimId, bool attested) { using (DbConnection connection = GetMySqlDbConnection()) @@ -360,7 +359,6 @@ namespace Swarmops.Database } - public int SetExpenseClaimValidated(int expenseClaimId, bool validated) { using (DbConnection connection = GetMySqlDbConnection()) @@ -378,7 +376,6 @@ namespace Swarmops.Database } - public int SetExpenseClaimKeepSeparate(int expenseClaimId, bool keepSeparate) { using (DbConnection connection = GetMySqlDbConnection()) @@ -396,7 +393,6 @@ namespace Swarmops.Database } - public int SetExpenseClaimClaimed(int expenseClaimId, bool claimed) { using (DbConnection connection = GetMySqlDbConnection()) @@ -414,8 +410,6 @@ namespace Swarmops.Database } - - public int SetExpenseClaimOpen(int expenseClaimId, bool open) { using (DbConnection connection = GetMySqlDbConnection()) @@ -433,8 +427,6 @@ namespace Swarmops.Database } - - public int SetExpenseClaimRepaid(int expenseClaimId, bool repaid) { using (DbConnection connection = GetMySqlDbConnection()) @@ -452,8 +444,6 @@ namespace Swarmops.Database } - - public int CreateExpenseEvent(int expenseId, ExpenseEventType eventType, int personId) { throw new NotImplementedException("Not migrated to version 4"); @@ -476,8 +466,5 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); }*/ } - - - } } \ No newline at end of file diff --git a/Database/Database-ExternalActivities.cs b/Database/Database-ExternalActivities.cs index abc0fa74..1b64a7e5 100644 --- a/Database/Database-ExternalActivities.cs +++ b/Database/Database-ExternalActivities.cs @@ -12,38 +12,38 @@ namespace Swarmops.Database #region Field reading code private const string externalActivityFieldSequence = - " ExternalActivityId,OrganizationId,GeographyId,DateTime,ExternalActivityTypes.Name," + // 0-4 + " ExternalActivityId,OrganizationId,GeographyId,DateTime,ExternalActivityTypes.Name," + // 0-4 " 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); - ExternalActivityType type = (ExternalActivityType)Enum.Parse(typeof(ExternalActivityType), reader.GetString(4)); + 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); - return new BasicExternalActivity(externalActivityId, organizationId, geographyId, type, dateTime, description, createdByPersonId, createdDateTime, dupeOfActivityId); + return new BasicExternalActivity(externalActivityId, organizationId, geographyId, type, dateTime, + description, createdByPersonId, createdDateTime, dupeOfActivityId); } #endregion - - #region Record reading - SELECT statements /// - /// Gets an external activity from the database. + /// Gets an external activity from the 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()) { @@ -51,7 +51,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + externalActivityFieldSequence + "WHERE ExternalActivityId=" + externalActivityId + ";", connection); + "SELECT" + externalActivityFieldSequence + "WHERE ExternalActivityId=" + externalActivityId + + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -60,27 +61,34 @@ namespace Swarmops.Database return ReadExternalActivityFromDataReader(reader); } - throw new ArgumentException("Unknown External Activity Id: " + externalActivityId.ToString()); + throw new ArgumentException("Unknown External Activity Id: " + externalActivityId); } } } /// - /// Gets ExternalActivities from the database. + /// Gets ExternalActivities from the database. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// A list of matching ExternalActivities. - public BasicExternalActivity[] GetExternalActivities (params object[] conditions) + public BasicExternalActivity[] GetExternalActivities(params object[] conditions) { return GetExternalActivitiesSorted("", 0, conditions); } /// - /// Gets ExternalActivities from the database. + /// Gets ExternalActivities from the database. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// A list of matching ExternalActivities. - public BasicExternalActivity[] GetExternalActivitiesSorted (string sortOrder, int limitCount, params object[] conditions) + public BasicExternalActivity[] GetExternalActivitiesSorted(string sortOrder, int limitCount, + params object[] conditions) { List result = new List(); @@ -107,7 +115,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + externalActivityFieldSequence + ConstructWhereClause("ExternalActivities", conditions) + sort + limit, connection); + "SELECT" + externalActivityFieldSequence + + ConstructWhereClause("ExternalActivities", conditions) + sort + limit, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -121,14 +130,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public int CreateExternalActivity (int organizationId, int geographyId, DateTime dateTime, ExternalActivityType type, string description, int createdByPersonId) + public int CreateExternalActivity(int organizationId, int geographyId, DateTime dateTime, + ExternalActivityType type, string description, int createdByPersonId) { if (description.Length > 256) { @@ -154,9 +161,6 @@ namespace Swarmops.Database } } - - #endregion - } } \ No newline at end of file diff --git a/Database/Database-ExternalCredentials.cs b/Database/Database-ExternalCredentials.cs index b6879297..5433b877 100644 --- a/Database/Database-ExternalCredentials.cs +++ b/Database/Database-ExternalCredentials.cs @@ -6,7 +6,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicExternalCredential GetExternalCredential (string serviceName) + public BasicExternalCredential GetExternalCredential(string serviceName) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -14,7 +14,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT ExternalCredentialId,ServiceName,Login,Password From ExternalCredentials WHERE ServiceName='" + serviceName.Replace("'", "''") + "'", + "SELECT ExternalCredentialId,ServiceName,Login,Password From ExternalCredentials WHERE ServiceName='" + + serviceName.Replace("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -30,7 +31,7 @@ namespace Swarmops.Database } - private BasicExternalCredential ReadExternalCredentialFromDataReader (DbDataReader reader) + private BasicExternalCredential ReadExternalCredentialFromDataReader(DbDataReader reader) { int externalCredentialId = reader.GetInt32(0); string serviceName = reader.GetString(1); diff --git a/Database/Database-ExternalIdentities.cs b/Database/Database-ExternalIdentities.cs index 097a1f68..e0e71c93 100644 --- a/Database/Database-ExternalIdentities.cs +++ b/Database/Database-ExternalIdentities.cs @@ -13,7 +13,7 @@ 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()) { @@ -37,7 +37,7 @@ namespace Swarmops.Database } } - public BasicExternalIdentity GetExternalIdentityFromPersonIdAndType (int persId, ExternalIdentityType type) + public BasicExternalIdentity GetExternalIdentityFromPersonIdAndType(int persId, ExternalIdentityType type) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -45,7 +45,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + readFieldsSQL + " WHERE AttachedToPerson= @persId and ExternalIdentityTypeName = @typeName", + "SELECT " + readFieldsSQL + + " WHERE AttachedToPerson= @persId and ExternalIdentityTypeName = @typeName", connection); AddParameterWithName(command, "persId", persId); AddParameterWithName(command, "typeName", type.ToString()); @@ -62,7 +63,7 @@ namespace Swarmops.Database } } - public BasicExternalIdentity GetExternalIdentityFromUserIdAndType (string userid, ExternalIdentityType type) + public BasicExternalIdentity GetExternalIdentityFromUserIdAndType(string userid, ExternalIdentityType type) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -87,7 +88,7 @@ namespace Swarmops.Database } } - public List GetExternalIdentities (int persId) + public List GetExternalIdentities(int persId) { List retval = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -112,7 +113,7 @@ namespace Swarmops.Database } /// - /// Update/Insert if id == 0 it is an insert + /// Update/Insert if id == 0 it is an insert /// /// /// @@ -121,7 +122,7 @@ namespace Swarmops.Database /// /// /// - public BasicExternalIdentity SetExternalIdentity ( + public BasicExternalIdentity SetExternalIdentity( int externalIdentityIdentity, ExternalIdentityType typeOfAccount, string externalSystem, @@ -138,8 +139,8 @@ namespace Swarmops.Database AddParameterWithName(command, "pExternalIdentityIdentity", externalIdentityIdentity); AddParameterWithName(command, "pTypeOfAccount", typeOfAccount.ToString()); - AddParameterWithName(command, "pExternalSystem", externalSystem.ToString()); - AddParameterWithName(command, "pUserID", userID.ToString()); + AddParameterWithName(command, "pExternalSystem", externalSystem); + AddParameterWithName(command, "pUserID", userID); AddParameterWithName(command, "pPassword", password); AddParameterWithName(command, "pAttachedToPerson", attachedToPerson); @@ -155,18 +156,19 @@ 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()); - string externalSystem = (string)reader["ExternalSystem"]; - string userID = (string)reader["UserID"]; - string password = (string)reader["Password"]; - int attachedToPerson = (int)reader["AttachedToPerson"]; + int externalIdentityId = (int) reader["ExternalIdentityIdentity"]; + ExternalIdentityType typeOfAccount = + (ExternalIdentityType) + 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, attachedToPerson); + return new BasicExternalIdentity(externalIdentityId, typeOfAccount, externalSystem, userID, password, + attachedToPerson); } } } \ No newline at end of file diff --git a/Database/Database-FinancialTransactionTagSetTypes.cs b/Database/Database-FinancialTransactionTagSetTypes.cs index b4928ba4..06c6d20f 100644 --- a/Database/Database-FinancialTransactionTagSetTypes.cs +++ b/Database/Database-FinancialTransactionTagSetTypes.cs @@ -9,15 +9,14 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading - private const string financialTransactionTagSetTypeFieldSequence = - " FinancialTransactionTagSetTypeId,ResourceName " + // 0-1 + " FinancialTransactionTagSetTypeId,ResourceName " + // 0-1 "FROM FinancialTransactionTagSetTypes "; - private static BasicFinancialTransactionTagSetType ReadFinancialTransactionTagSetTypeFromDataReader(IDataRecord reader) + private static BasicFinancialTransactionTagSetType ReadFinancialTransactionTagSetTypeFromDataReader( + IDataRecord reader) { int financialTransactionTagSetTypeId = reader.GetInt32(0); string resourceName = reader.GetString(1); @@ -27,30 +26,32 @@ namespace Swarmops.Database #endregion - #region Database record reading -- SELECT clauses - - public BasicFinancialTransactionTagSetType GetFinancialTransactionTagSetType (int financialTransactionTagSetTypeId) + public BasicFinancialTransactionTagSetType GetFinancialTransactionTagSetType( + int financialTransactionTagSetTypeId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT" + financialTransactionTagSetTypeFieldSequence + " WHERE FinancialTransactionTagSetTypeId=" + financialTransactionTagSetTypeId.ToString(CultureInfo.InvariantCulture), connection); + GetDbCommand( + "SELECT" + financialTransactionTagSetTypeFieldSequence + + " WHERE FinancialTransactionTagSetTypeId=" + + 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)); } } - } @@ -68,7 +69,7 @@ namespace Swarmops.Database { while (reader.Read()) { - result.Add (ReadFinancialTransactionTagSetTypeFromDataReader (reader)); + result.Add(ReadFinancialTransactionTagSetTypeFromDataReader(reader)); } return result.ToArray(); @@ -76,13 +77,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - /* TODO * * @@ -173,10 +171,8 @@ namespace Swarmops.Database } }*/ - #endregion - #region Dead template code /* @@ -520,7 +516,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-FinancialTransactionTagSets.cs b/Database/Database-FinancialTransactionTagSets.cs index 695b654b..53868ec2 100644 --- a/Database/Database-FinancialTransactionTagSets.cs +++ b/Database/Database-FinancialTransactionTagSets.cs @@ -9,34 +9,32 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading - private const string financialTransactionTagSetFieldSequence = - " FinancialTransactionTagSetId,FinancialTransactionTagSetTypeId,OrganizationId,DisplayOrder,AllowUntagged," + // 0-4 - "VisibilityLevel,ProfitLossType " + // 5-6 + " FinancialTransactionTagSetId,FinancialTransactionTagSetTypeId,OrganizationId,DisplayOrder,AllowUntagged," + + // 0-4 + "VisibilityLevel,ProfitLossType " + // 5-6 "FROM FinancialTransactionTagSets "; 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 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, organizationId, order, allowUntagged, visibilityLevel, profitLossType); + return new BasicFinancialTransactionTagSet(financialTransactionTagSetId, financialTransactionTagSetTypeId, + organizationId, order, allowUntagged, visibilityLevel, profitLossType); } #endregion - #region Database record reading -- SELECT clauses - public BasicFinancialTransactionTagSet GetFinancialTransactionTagSet(int financialTransactionTagSetId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -44,7 +42,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT" + financialTransactionTagSetFieldSequence + " WHERE FinancialTransactionTagSetId=" + financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture), connection); + GetDbCommand( + "SELECT" + financialTransactionTagSetFieldSequence + " WHERE FinancialTransactionTagSetId=" + + financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -53,10 +53,10 @@ namespace Swarmops.Database return ReadFinancialTransactionTagSetFromDataReader(reader); } - throw new ArgumentException("No such FinancialTransactionSetTypeId: " + financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture)); + throw new ArgumentException("No such FinancialTransactionSetTypeId: " + + financialTransactionTagSetId.ToString(CultureInfo.InvariantCulture)); } } - } @@ -68,7 +68,11 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT" + financialTransactionTagSetFieldSequence + ConstructWhereClause ("FinancialTransactionTagSets", conditions) + " ORDER BY DisplayOrder", connection); + DbCommand command = + GetDbCommand( + "SELECT" + financialTransactionTagSetFieldSequence + + ConstructWhereClause("FinancialTransactionTagSets", conditions) + " ORDER BY DisplayOrder", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -82,13 +86,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - /* TODO * * @@ -179,10 +180,8 @@ namespace Swarmops.Database } }*/ - #endregion - #region Dead template code /* @@ -526,7 +525,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-FinancialTransactionTagTypes.cs b/Database/Database-FinancialTransactionTagTypes.cs index 3227657d..71ee4bef 100644 --- a/Database/Database-FinancialTransactionTagTypes.cs +++ b/Database/Database-FinancialTransactionTagTypes.cs @@ -9,36 +9,32 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading - private const string financialTransactionTagTypeFieldSequence = - " FinancialTransactionTagTypeId,ParentFinancialTransactionTagTypeId,FinancialTransactionTagSetId,Name,Active," + // 0-4 - "OpenedYear,ClosedYear " + // 5-6 + " FinancialTransactionTagTypeId,ParentFinancialTransactionTagTypeId,FinancialTransactionTagSetId,Name,Active," + + // 0-4 + "OpenedYear,ClosedYear " + // 5-6 "FROM FinancialTransactionTagTypes "; 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, parentFinancialTransactionTagTypeId, financialTransactionTagSetId, name, active, openedYear, closedYear); + return new BasicFinancialTransactionTagType(financialTransactionTagTypeId, + parentFinancialTransactionTagTypeId, financialTransactionTagSetId, name, active, openedYear, closedYear); } - - #endregion - #region Database record reading -- SELECT clauses - public BasicFinancialTransactionTagType GetFinancialTransactionTagType(int financialTransactionTagTypeId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -46,7 +42,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT" + financialTransactionTagTypeFieldSequence + " WHERE FinancialTransactionTagTypeId=" + financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture), connection); + GetDbCommand( + "SELECT" + financialTransactionTagTypeFieldSequence + " WHERE FinancialTransactionTagTypeId=" + + financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -55,10 +53,10 @@ namespace Swarmops.Database return ReadFinancialTransactionTagTypeFromDataReader(reader); } - throw new ArgumentException("No such FinancialTransactionSetTypeId: " + financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture)); + throw new ArgumentException("No such FinancialTransactionSetTypeId: " + + financialTransactionTagTypeId.ToString(CultureInfo.InvariantCulture)); } } - } @@ -70,7 +68,10 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT" + financialTransactionTagTypeFieldSequence + ConstructWhereClause("FinancialTransactionTagTypes", conditions), connection); + DbCommand command = + GetDbCommand( + "SELECT" + financialTransactionTagTypeFieldSequence + + ConstructWhereClause("FinancialTransactionTagTypes", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -85,7 +86,7 @@ namespace Swarmops.Database } - public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypesByIdentity (int[] identities) + public BasicFinancialTransactionTagType[] GetFinancialTransactionTagTypesByIdentity(int[] identities) { List result = new List(); @@ -93,7 +94,10 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT" + financialTransactionTagTypeFieldSequence + " WHERE FinancialTransactionTagTypeId IN (" + JoinIds(identities) + ")", connection); + DbCommand command = + GetDbCommand( + "SELECT" + financialTransactionTagTypeFieldSequence + + " WHERE FinancialTransactionTagTypeId IN (" + JoinIds(identities) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -107,13 +111,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - /* TODO * * @@ -204,10 +205,8 @@ namespace Swarmops.Database } }*/ - #endregion - #region Dead template code /* @@ -551,7 +550,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-FinancialTransactionTags.cs b/Database/Database-FinancialTransactionTags.cs index f25c1248..eba99104 100644 --- a/Database/Database-FinancialTransactionTags.cs +++ b/Database/Database-FinancialTransactionTags.cs @@ -8,18 +8,15 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading // None for this type #endregion - #region Database record reading -- SELECT clauses - - public int[] GetFinancialTransactionTagTypes (int financialTransactionId) + public int[] GetFinancialTransactionTagTypes(int financialTransactionId) { List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -27,28 +24,27 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT FinancialTransactionTagTypeId FROM FinancialTransactionTags WHERE FinancialTransactionId=" + financialTransactionId.ToString(CultureInfo.InvariantCulture), connection); + GetDbCommand( + "SELECT FinancialTransactionTagTypeId FROM FinancialTransactionTags WHERE FinancialTransactionId=" + + 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(); } } - } - #endregion - #region Creation and manipulation -- stored procedures - public int CreateFinancialTransactionTag(int financialTransactionId, int financialTransactionTagTypeId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -61,7 +57,7 @@ namespace Swarmops.Database 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 } } @@ -95,11 +91,8 @@ namespace Swarmops.Database } } - - #endregion - #region Dead template code /* @@ -443,7 +436,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-FinancialValidations.cs b/Database/Database-FinancialValidations.cs index 387c98a9..a222d37c 100644 --- a/Database/Database-FinancialValidations.cs +++ b/Database/Database-FinancialValidations.cs @@ -12,8 +12,9 @@ namespace Swarmops.Database #region Field reading code private const string financialValidationFieldSequence = - " FinancialValidationId,FinancialValidationTypes.Name AS ValidationType,FinancialDependencyTypes.Name AS DependencyType,ForeignId,ValidatedDateTime," + // 0-4 - " PersonId,Amount " + // 5-6 + " FinancialValidationId,FinancialValidationTypes.Name AS ValidationType,FinancialDependencyTypes.Name AS DependencyType,ForeignId,ValidatedDateTime," + + // 0-4 + " PersonId,Amount " + // 5-6 " FROM FinancialValidations JOIN FinancialValidationTypes ON (FinancialValidations.TypeId=FinancialValidationTypes.FinancialValidationTypeId) " + " JOIN FinancialDependencyTypes USING (FinancialDependencyTypeId)"; @@ -23,21 +24,20 @@ namespace Swarmops.Database { 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))); + (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, dependencyType, foreignId); + return new BasicFinancialValidation(financialValidationId, validationType, personId, dateTime, + dependencyType, foreignId); } #endregion - - #region Record reading - SELECT statements public BasicFinancialValidation[] GetFinancialValidations(FinancialDependencyType dependencyType, int foreignId) @@ -50,7 +50,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + financialValidationFieldSequence + " WHERE FinancialDependencyTypes.Name='" + dependencyType.ToString() + "' AND ForeignId=" + foreignId.ToString() + " " + financialValidationOrder, connection); + "SELECT " + financialValidationFieldSequence + " WHERE FinancialDependencyTypes.Name='" + + dependencyType + "' AND ForeignId=" + foreignId + " " + financialValidationOrder, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -64,9 +65,6 @@ namespace Swarmops.Database } } - #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Financials.cs b/Database/Database-Financials.cs index 3681e7e7..82565930 100644 --- a/Database/Database-Financials.cs +++ b/Database/Database-Financials.cs @@ -16,12 +16,13 @@ namespace Swarmops.Database public partial class SwarmDb { private const string financialAccountFieldSequence = - " FinancialAccountId,Name,OrganizationId,AccountType,ParentFinancialAccountId," + // 0-4 - " OwnerPersonId,Open,OpenedYear,ClosedYear,Expensable," + // 5-9 + " FinancialAccountId,Name,OrganizationId,AccountType,ParentFinancialAccountId," + // 0-4 + " OwnerPersonId,Open,OpenedYear,ClosedYear,Expensable," + // 5-9 " Administrative,Active,LinkBackward,LinkForward " + // 10-13 " FROM FinancialAccounts "; - public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) + public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, + int pParentFinancialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -32,7 +33,7 @@ namespace Swarmops.Database AddParameterWithName(command, "pOrganizationId", pOrganizationId); AddParameterWithName(command, "pName", pName); - AddParameterWithName(command, "pAccountType", (int)pAccountType); + AddParameterWithName(command, "pAccountType", (int) pAccountType); AddParameterWithName(command, "pParentFinancialAccountId", pParentFinancialAccountId); return Convert.ToInt32(command.ExecuteScalar()); @@ -69,7 +70,7 @@ namespace Swarmops.Database public BasicFinancialAccount[] GetFinancialAccountsForOrganization(int organizationId) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -94,7 +95,7 @@ namespace Swarmops.Database public BasicFinancialAccount[] GetFinancialAccountsOwnedByPerson(int ownerPersonId) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -119,7 +120,7 @@ namespace Swarmops.Database public BasicFinancialAccount[] GetFinancialAccounts(int[] financialAccountIds) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -144,7 +145,7 @@ namespace Swarmops.Database public BasicFinancialTransaction GetFinancialTransaction(int financialTransactionId) { - var array = GetFinancialTransactions(new int[] {financialTransactionId}); + BasicFinancialTransaction[] array = GetFinancialTransactions(new[] {financialTransactionId}); if (array.Length == 0) { @@ -154,7 +155,7 @@ namespace Swarmops.Database return array[0]; } - public BasicFinancialTransaction[] GetFinancialTransactions (int[] financialTransactionIds) + public BasicFinancialTransaction[] GetFinancialTransactions(int[] financialTransactionIds) { List result = new List(); @@ -165,7 +166,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT FinancialTransactionId,OrganizationId,DateTime,Comment,ImportHash From FinancialTransactions WHERE FinancialTransactionId IN (" + - JoinIds (financialTransactionIds) + ");", connection); + JoinIds(financialTransactionIds) + ");", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -179,7 +180,7 @@ namespace Swarmops.Database } } - public BasicFinancialTransaction GetFinancialTransactionFromImportKey (int organizationId, string importKey) + public BasicFinancialTransaction GetFinancialTransactionFromImportKey(int organizationId, string importKey) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -187,7 +188,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT FinancialTransactionId,OrganizationId,DateTime,Comment,ImportHash From FinancialTransactions WHERE OrganizationId=" + organizationId.ToString() + " AND ImportHash='" + importKey.Replace("'", "''") + "';", connection); + "SELECT FinancialTransactionId,OrganizationId,DateTime,Comment,ImportHash From FinancialTransactions WHERE OrganizationId=" + + organizationId + " AND ImportHash='" + importKey.Replace("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -217,7 +219,7 @@ namespace Swarmops.Database { if (reader.Read()) { - return reader.GetInt64(0) / 100.0; + return reader.GetInt64(0)/100.0; } throw new ArgumentException("Unknown Account Id"); @@ -281,7 +283,8 @@ namespace Swarmops.Database } } - public Int64 GetFinancialAccountBalanceDeltaCents(int[] financialAccountIds, DateTime startDate, DateTime endDate) + public Int64 GetFinancialAccountBalanceDeltaCents(int[] financialAccountIds, DateTime startDate, + DateTime endDate) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -320,16 +323,16 @@ namespace Swarmops.Database return GetFinancialAccountBalanceDeltaCents(financialAccountId, startDate, endDate)/100.0m; } - public BasicFinancialAccountRow[] GetFinancialAccountRows (int financialAccountId, DateTime startDateTime, - DateTime endDateTime, bool selectFar) + public BasicFinancialAccountRow[] GetFinancialAccountRows(int financialAccountId, DateTime startDateTime, + DateTime endDateTime, bool selectFar) { - return GetFinancialAccountRows(new int[] {financialAccountId}, startDateTime, endDateTime, selectFar); + return GetFinancialAccountRows(new[] {financialAccountId}, startDateTime, endDateTime, selectFar); } public BasicFinancialAccountRow[] GetFinancialAccountRows(int[] financialAccountIds, DateTime startDateTime, - DateTime endDateTime, bool selectFar) + DateTime endDateTime, bool selectFar) { - var result = new List(); + List result = new List(); // initialize to near selector (equal sign by the lower bound @@ -351,7 +354,8 @@ namespace Swarmops.Database "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") + "' ORDER BY DateTime,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime;", + "' AND DateTime " + selectorUpper + " '" + endDateTime.ToString("yyyy-MM-dd HH:mm:ss") + + "' ORDER BY DateTime,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime;", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -367,14 +371,14 @@ namespace Swarmops.Database } - public BasicFinancialAccountRow[] GetLastFinancialAccountRows (int financialAccountId, int rowCount) + public BasicFinancialAccountRow[] GetLastFinancialAccountRows(int financialAccountId, int rowCount) { - return GetLastFinancialAccountRows(new int[] {financialAccountId}, rowCount); + return GetLastFinancialAccountRows(new[] {financialAccountId}, rowCount); } - public BasicFinancialAccountRow[] GetLastFinancialAccountRows (int[] financialAccountIds, int rowCount) + public BasicFinancialAccountRow[] GetLastFinancialAccountRows(int[] financialAccountIds, int rowCount) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -383,7 +387,9 @@ namespace Swarmops.Database DbCommand command = 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) + ") ORDER BY DateTime DESC,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime LIMIT " + rowCount.ToString() + ";", + JoinIds(financialAccountIds) + + ") ORDER BY DateTime DESC,FinancialTransactions.FinancialTransactionId,FinancialTransactionRows.CreatedDateTime LIMIT " + + rowCount + ";", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -401,7 +407,7 @@ namespace Swarmops.Database public BasicFinancialTransactionRow[] GetFinancialTransactionRows(int financialTransactionId) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -425,7 +431,7 @@ namespace Swarmops.Database } } - public BasicFinancialTransactionRow GetFinancialTransactionRow (int financialTransactionRowId) + public BasicFinancialTransactionRow GetFinancialTransactionRow(int financialTransactionRowId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -449,9 +455,9 @@ namespace Swarmops.Database } - public BasicFinancialTransaction[] GetUnbalancedFinancialTransactions (int organizationId) + public BasicFinancialTransaction[] GetUnbalancedFinancialTransactions(int organizationId) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -483,7 +489,7 @@ namespace Swarmops.Database } - public BasicFinancialTransaction GetFinancialTransactionFromDependency (IHasIdentity foreignObject) + public BasicFinancialTransaction GetFinancialTransactionFromDependency(IHasIdentity foreignObject) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -492,7 +498,8 @@ namespace Swarmops.Database string commandString = "SELECT FinancialTransactionId FROM FinancialTransactionDependencies " + "JOIN FinancialDependencyTypes ON (FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId) " + "WHERE FinancialDependencyTypes.Name='" + GetForeignTypeString(foreignObject) + - "' AND FinancialTransactionDependencies.ForeignId=" + foreignObject.Identity + ";"; + "' AND FinancialTransactionDependencies.ForeignId=" + foreignObject.Identity + + ";"; DbCommand command = GetDbCommand(commandString, connection); @@ -501,28 +508,26 @@ namespace Swarmops.Database { 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)); + GetForeignTypeString(foreignObject), foreignObject.Identity)); } } - - - } /// - /// Gets all undocumented transactions that lowers assets for a particular organization + /// Gets all undocumented transactions that lowers assets for a particular organization /// /// The organization owning the transactions /// A list of all such transactions public BasicFinancialTransaction[] GetUndocumentedFinancialTransactions(int organizationId) { - var result = new List(); + List result = new List(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -535,7 +540,8 @@ namespace Swarmops.Database "FROM FinancialTransactions " + "JOIN FinancialTransactionRows ON (FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId) " + "JOIN FinancialAccounts ON (FinancialAccounts.FinancialAccountId=FinancialTransactionRows.FinancialAccountId) " + - "WHERE FinancialTransactions.OrganizationId=" + organizationId + " AND FinancialAccounts.AccountType IN (1,2) " + + "WHERE FinancialTransactions.OrganizationId=" + organizationId + + " AND FinancialAccounts.AccountType IN (1,2) " + "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;"; @@ -563,7 +569,7 @@ namespace Swarmops.Database DbCommand command = 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()) { @@ -847,15 +853,16 @@ namespace Swarmops.Database DateTime createdDateTime = reader.GetDateTime(4); int createdByPersonId = reader.GetInt32(5); - return new BasicFinancialTransactionRow(rowId, accountId, transactionId, amountCents, createdDateTime, createdByPersonId); + 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); - var accountType = (FinancialAccountType) reader.GetInt32(3); + FinancialAccountType accountType = (FinancialAccountType) reader.GetInt32(3); int parentFinancialAccountId = reader.GetInt32(4); int ownerPersonId = reader.GetInt32(5); bool open = reader.GetBoolean(6); @@ -867,10 +874,12 @@ namespace Swarmops.Database int linkBackward = reader.GetInt32(12); int linkForward = reader.GetInt32(13); - return new BasicFinancialAccount(accountId, name, accountType, organizationId, parentFinancialAccountId, ownerPersonId, open, openedYear, closedYear, active, expensable, administrative, linkBackward, linkForward); + 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); @@ -880,11 +889,12 @@ namespace Swarmops.Database DateTime rowDateTime = reader.GetDateTime(5); int rowCreatedByPersonId = reader.GetInt32(6); - return new BasicFinancialAccountRow(accountId, transactionId, transactionDateTime, comment, amountCents, rowDateTime, rowCreatedByPersonId); + 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); @@ -895,7 +905,7 @@ namespace Swarmops.Database 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) { @@ -917,8 +927,8 @@ namespace Swarmops.Database } } - public int CreateFinancialTransactionStub (int organizationId, DateTime dateTime, int financialAccountId, - Int64 amountCents, string comment, string importHash, int personId) + public int CreateFinancialTransactionStub(int organizationId, DateTime dateTime, int financialAccountId, + Int64 amountCents, string comment, string importHash, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -940,7 +950,7 @@ namespace Swarmops.Database } public void CreateFinancialTransactionRow(int financialTransactionId, int financialAccountId, double amount, - int personId) + int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -960,7 +970,7 @@ namespace Swarmops.Database } public void CreateFinancialTransactionRow(int financialTransactionId, int financialAccountId, Int64 amountCents, - int personId) + int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -996,7 +1006,8 @@ namespace Swarmops.Database } - public void SetFinancialTransactionDependency(int financialTransactionId, FinancialDependencyType dependencyType, int foreignId) + public void SetFinancialTransactionDependency(int financialTransactionId, FinancialDependencyType dependencyType, + int foreignId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -1030,7 +1041,6 @@ namespace Swarmops.Database } - public DateTime GetFinancialAccountFirstTransactionDate(int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -1040,9 +1050,10 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT FinancialTransactions.DateTime FROM FinancialTransactions,FinancialTransactionRows " + - "WHERE FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId " + - "AND FinancialTransactionRows.FinancialAccountId = " + financialAccountId.ToString(CultureInfo.InvariantCulture) + " " + - "ORDER BY FinancialTransactions.DateTime LIMIT 1;", connection); + "WHERE FinancialTransactions.FinancialTransactionId=FinancialTransactionRows.FinancialTransactionId " + + "AND FinancialTransactionRows.FinancialAccountId = " + + financialAccountId.ToString(CultureInfo.InvariantCulture) + " " + + "ORDER BY FinancialTransactions.DateTime LIMIT 1;", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -1050,15 +1061,15 @@ namespace Swarmops.Database { return reader.GetDateTime(0); } - else - { - 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, int foreignId) + public BasicFinancialTransaction[] GetDependentFinancialTransactions(FinancialDependencyType dependencyType, + int foreignId) { List transactionIds = new List(); @@ -1069,9 +1080,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT FinancialTransactionId FROM FinancialTransactionDependencies,FinancialDependencyTypes " + - "WHERE FinancialDependencyTypes.Name='" + dependencyType.ToString() + "' AND " + + "WHERE FinancialDependencyTypes.Name='" + dependencyType + "' AND " + "FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId AND " + - "FinancialTransactionDependencies.ForeignId=" + foreignId.ToString(), connection); + "FinancialTransactionDependencies.ForeignId=" + foreignId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -1095,7 +1106,8 @@ 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, out FinancialDependencyType dependencyType, out int foreignId) + public void GetFinancialTransactionDependency(int financialTransactionId, + out FinancialDependencyType dependencyType, out int foreignId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -1106,7 +1118,8 @@ namespace Swarmops.Database "SELECT FinancialDependencyTypes.Name,FinancialTransactionDependencies.ForeignId " + "FROM FinancialTransactionDependencies,FinancialDependencyTypes " + "WHERE FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId " + - "AND FinancialTransactionDependencies.FinancialTransactionId=" + financialTransactionId.ToString(), connection); + "AND FinancialTransactionDependencies.FinancialTransactionId=" + financialTransactionId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -1114,7 +1127,8 @@ namespace Swarmops.Database { // Set OUT parameters - dependencyType = (FinancialDependencyType) Enum.Parse(typeof (FinancialDependencyType), reader.GetString(0)); + dependencyType = + (FinancialDependencyType) Enum.Parse(typeof (FinancialDependencyType), reader.GetString(0)); foreignId = reader.GetInt32(1); } else @@ -1126,14 +1140,13 @@ namespace Swarmops.Database } } } - } - // TODO: Return BasicFinancialValidation object - public void CreateFinancialValidation (FinancialValidationType validationType, FinancialDependencyType dependencyType, int foreignId, + public void CreateFinancialValidation(FinancialValidationType validationType, + FinancialDependencyType dependencyType, int foreignId, DateTime validatedDateTime, int personId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) @@ -1155,10 +1168,6 @@ namespace Swarmops.Database } - - - - // -- lines and trees and children -- @@ -1172,14 +1181,15 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + financialAccountFieldSequence + " WHERE ParentFinancialAccountId = " + parentFinancialAccountId.ToString() + + "SELECT " + financialAccountFieldSequence + " WHERE ParentFinancialAccountId = " + + parentFinancialAccountId + " ORDER BY \"Name\"", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add(ReadFinancialAccountFromDataReader (reader)); + result.Add(ReadFinancialAccountFromDataReader(reader)); } return result.ToArray(); @@ -1259,7 +1269,7 @@ namespace Swarmops.Database } - public BasicFinancialAccount[] GetFinancialAccountTreeForOrganization (int organizationId) + public BasicFinancialAccount[] GetFinancialAccountTreeForOrganization(int organizationId) { Dictionary> nodes = GetHashedFinancialAccounts(organizationId); @@ -1282,8 +1292,9 @@ namespace Swarmops.Database }*/ - private BasicFinancialAccount[] GetFinancialAccountTree(Dictionary> financialAccounts, int startNodeId, - int generation) + private BasicFinancialAccount[] GetFinancialAccountTree( + Dictionary> financialAccounts, int startNodeId, + int generation) { List result = new List(); @@ -1297,7 +1308,8 @@ namespace Swarmops.Database // Add recursively - BasicFinancialAccount[] children = GetFinancialAccountTree(financialAccounts, node.FinancialAccountId, generation + 1); + BasicFinancialAccount[] children = GetFinancialAccountTree(financialAccounts, + node.FinancialAccountId, generation + 1); if (children.Length > 0) { @@ -1317,6 +1329,5 @@ namespace Swarmops.Database return result.ToArray(); } - } } \ No newline at end of file diff --git a/Database/Database-FlatData.cs b/Database/Database-FlatData.cs index f71be63f..1e9b2d83 100644 --- a/Database/Database-FlatData.cs +++ b/Database/Database-FlatData.cs @@ -6,14 +6,15 @@ 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("'", "''") + "'", connection); + GetDbCommand("SELECT DataValue FROM FlatData WHERE DataKey='" + key.Replace("'", "''") + "'", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -28,7 +29,7 @@ namespace Swarmops.Database } - public void SetKeyValue (string key, string value) + public void SetKeyValue(string key, string value) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -45,7 +46,7 @@ namespace Swarmops.Database } - public Dictionary GetOldKeyValues() + public Dictionary GetOldKeyValues() { /* Dictionary result = new Dictionary(); diff --git a/Database/Database-Geographies.cs b/Database/Database-Geographies.cs index f6c682e9..179a7c4a 100644 --- a/Database/Database-Geographies.cs +++ b/Database/Database-Geographies.cs @@ -12,15 +12,15 @@ namespace Swarmops.Database #region Field reading code private const string geographyFieldSequence = - " GeographyId, ParentGeographyId, Name " + // 0-2 + " GeographyId, ParentGeographyId, Name " + // 0-2 " FROM Geographies "; private const string geographyDesignationFieldSequence = - " GeographyId, CountryId, Designation, GeographyLevelId " + // 0-3 + " 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); @@ -29,7 +29,7 @@ namespace Swarmops.Database 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); @@ -39,12 +39,9 @@ namespace Swarmops.Database return new BasicGeographyDesignation(geographyId, countryId, designation, level); } - - #endregion - - public BasicGeography[] GetAllGeographies () + public BasicGeography[] GetAllGeographies() { List result = new List(); @@ -53,7 +50,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 ORDER BY \"Name\"", connection); + GetDbCommand( + "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 ORDER BY \"Name\"", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -68,7 +67,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographies (int[] ids) + public BasicGeography[] GetGeographies(int[] ids) { List result = new List(); @@ -78,7 +77,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 AND GeographyId in (" + JoinIds(ids) + + "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId >= 0 AND GeographyId in (" + + JoinIds(ids) + ") ORDER BY \"Name\"", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -94,7 +94,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographyChildren (int parentGeographyId) + public BasicGeography[] GetGeographyChildren(int parentGeographyId) { List result = new List(); @@ -104,7 +104,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId=" + parentGeographyId.ToString() + + "SELECT " + geographyFieldSequence + " WHERE ParentGeographyId=" + parentGeographyId + " ORDER BY \"Name\"", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -120,7 +120,7 @@ namespace Swarmops.Database } - public Dictionary> GetHashedGeographies () + public Dictionary> GetHashedGeographies() { // This generates a Dictionary >. // @@ -158,7 +158,7 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographyLine (int leafGeographyId) + public BasicGeography[] GetGeographyLine(int leafGeographyId) { List result = new List(); @@ -188,13 +188,13 @@ namespace Swarmops.Database } - public BasicGeography[] GetGeographyTree () + public BasicGeography[] GetGeographyTree() { return GetGeographyTree(1); } - public BasicGeography[] GetGeographyTree (int startGeographyId) + public BasicGeography[] GetGeographyTree(int startGeographyId) { Dictionary> nodes = GetHashedGeographies(); @@ -202,7 +202,7 @@ namespace Swarmops.Database } - public Dictionary GetGeographyHashtable (int startGeographyId) + public Dictionary GetGeographyHashtable(int startGeographyId) { BasicGeography[] nodes = GetGeographyTree(startGeographyId); @@ -217,8 +217,8 @@ namespace Swarmops.Database } - private BasicGeography[] GetGeographyTree (Dictionary> geographies, int startNodeId, - int generation) + private BasicGeography[] GetGeographyTree(Dictionary> geographies, int startNodeId, + int generation) { List result = new List(); @@ -254,14 +254,14 @@ namespace Swarmops.Database } - public BasicGeography GetGeography (int geographyId) + public BasicGeography GetGeography(int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = GetDbCommand( - "SELECT " + geographyFieldSequence + " WHERE GeographyId=" + geographyId.ToString(), connection); + "SELECT " + geographyFieldSequence + " WHERE GeographyId=" + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -270,13 +270,13 @@ namespace Swarmops.Database return ReadGeographyFromDataReader(reader); } - throw new ArgumentException("No such GeographyId: " + geographyId.ToString()); + throw new ArgumentException("No such GeographyId: " + geographyId); } } } - public BasicGeography GetGeographyByName (string geographyName) + public BasicGeography GetGeographyByName(string geographyName) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -284,7 +284,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + geographyFieldSequence + " WHERE Name like '" + geographyName.Replace("'", "''") + "%'", + "SELECT " + geographyFieldSequence + " WHERE Name like '" + geographyName.Replace("'", "''") + + "%'", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -300,7 +301,7 @@ namespace Swarmops.Database } - public void SetGeographyName (int geographyId, string name) + public void SetGeographyName(int geographyId, string name) { throw new NotImplementedException("Renaming geographies is not migrated to MySQL"); /* @@ -318,7 +319,7 @@ namespace Swarmops.Database }*/ } - public Dictionary GetGeographyVoterCounts () + public Dictionary GetGeographyVoterCounts() { throw new NotImplementedException("Not Migrated to MySQL"); /* @@ -345,8 +346,8 @@ namespace Swarmops.Database }*/ } - public void CreateGeographyOfficialDesignation (int geographyId, GeographyLevel level, int countryId, - string designation) + public void CreateGeographyOfficialDesignation(int geographyId, GeographyLevel level, int countryId, + string designation) { throw new NotImplementedException("Not Migrated to MySQL"); /* @@ -366,7 +367,7 @@ 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()) { @@ -374,8 +375,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "select GeographyId FROM GeographyDesignations WHERE CountryId=" + countryId.ToString() + - " AND GeographyLevelId= " + ((int)level).ToString() + " AND Designation='" + + "select GeographyId FROM GeographyDesignations WHERE CountryId=" + countryId + + " AND GeographyLevelId= " + ((int) level) + " AND Designation='" + designation.Replace("'", "''") + "'", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -384,15 +385,12 @@ namespace Swarmops.Database { return reader.GetInt32(0); } - else - { - 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(); @@ -403,13 +401,13 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "select GeographyLevelId FROM GeographyDesignations WHERE GeographyId=" + - geographyId.ToString(), connection); + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add((GeographyLevel)reader.GetInt32(0)); + result.Add((GeographyLevel) reader.GetInt32(0)); } } } @@ -417,7 +415,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicGeographyDesignation[] GetGeographyDesignationsForGeographyId (int geographyId) + public BasicGeographyDesignation[] GetGeographyDesignationsForGeographyId(int geographyId) { List result = new List(); @@ -427,7 +425,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + geographyDesignationFieldSequence + " WHERE GeographyId=" + geographyId.ToString(), connection); + "SELECT " + geographyDesignationFieldSequence + " WHERE GeographyId=" + geographyId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -441,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(); @@ -452,7 +450,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "select GeographyId FROM GeographyDesignations WHERE GeographyLevelId=" + - ((int)level).ToString() + " AND CountryId=" + countryId.ToString(), connection); + ((int) level) + " AND CountryId=" + countryId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -466,7 +464,7 @@ namespace Swarmops.Database return result.ToArray(); } - public int CreateGeography (string name, int parentGeographyId) + public int CreateGeography(string name, int parentGeographyId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -481,7 +479,5 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } - - } } \ No newline at end of file diff --git a/Database/Database-InboundInvoices.cs b/Database/Database-InboundInvoices.cs index 8cc6793f..f60628ca 100644 --- a/Database/Database-InboundInvoices.cs +++ b/Database/Database-InboundInvoices.cs @@ -37,14 +37,12 @@ namespace Swarmops.Database int closedByPersonId = reader.GetInt32(14); return new BasicInboundInvoice(inboundInvoiceId, organizationId, createdDateTime, dueDate, - amountCents, budgetId, supplier, payToAccount, ocr, invoiceReference, - attested, open, closedDateTime, closedByPersonId); + amountCents, budgetId, supplier, payToAccount, ocr, invoiceReference, + attested, open, closedDateTime, closedByPersonId); } #endregion - - #region Record reading - SELECT statements public BasicInboundInvoice GetInboundInvoice(int inboundInvoiceId) @@ -55,7 +53,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + inboundInvoiceFieldSequence + "WHERE InboundInvoiceId=" + inboundInvoiceId + ";", connection); + "SELECT" + inboundInvoiceFieldSequence + "WHERE InboundInvoiceId=" + inboundInvoiceId + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -71,11 +70,11 @@ namespace Swarmops.Database /// - /// Gets a list of inbound invoices. + /// Gets a list of inbound invoices. /// /// 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(); @@ -85,7 +84,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + inboundInvoiceFieldSequence + ConstructWhereClause("InboundInvoices", conditions) + " ORDER BY DueDate;", connection); + "SELECT" + inboundInvoiceFieldSequence + ConstructWhereClause("InboundInvoices", conditions) + + " ORDER BY DueDate;", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -99,14 +99,10 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - /* -- UNUSED public int CreateInboundInvoice(int organizationId, DateTime dueDate, int budgetId, string supplier, string payToAccount, string ocr, string invoiceReference, double amount, int createdByPersonId) @@ -134,7 +130,8 @@ namespace Swarmops.Database }*/ - public int CreateInboundInvoice(int organizationId, DateTime dueDate, int budgetId, string supplier, string payToAccount, string ocr, string invoiceReference, Int64 amountCents, int createdByPersonId) + 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()) { @@ -193,7 +190,6 @@ namespace Swarmops.Database } - public void SetInboundInvoiceAmount(int inboundInvoiceId, double amount) { using (DbConnection connection = GetMySqlDbConnection()) @@ -211,7 +207,6 @@ namespace Swarmops.Database } - public void SetInboundInvoiceAmount(int inboundInvoiceId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -229,7 +224,6 @@ namespace Swarmops.Database } - public void SetInboundInvoiceBudget(int inboundInvoiceId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -247,7 +241,6 @@ namespace Swarmops.Database } - public void SetInboundInvoiceDueDate(int inboundInvoiceId, DateTime dueDate) { using (DbConnection connection = GetMySqlDbConnection()) @@ -264,16 +257,10 @@ namespace Swarmops.Database } } - - #endregion - - - #region Dead template code - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-Initialization.cs b/Database/Database-Initialization.cs index 77b1d3a6..aa9a3f27 100644 --- a/Database/Database-Initialization.cs +++ b/Database/Database-Initialization.cs @@ -23,7 +23,7 @@ namespace Swarmops.Database } } - public int ExecuteAdminCommandScalar (string sqlSequence) + public int ExecuteAdminCommandScalar(string sqlSequence) { // TODO: Verify that we're in admin mode @@ -44,6 +44,5 @@ namespace Swarmops.Database return Convert.ToInt32(result); } } - } } \ No newline at end of file diff --git a/Database/Database-InternalPollCandidates.cs b/Database/Database-InternalPollCandidates.cs index 274c1bd0..996a4963 100644 --- a/Database/Database-InternalPollCandidates.cs +++ b/Database/Database-InternalPollCandidates.cs @@ -11,7 +11,7 @@ namespace Swarmops.Database #region Field reading code private const string internalPollCandidateFieldSequence = - " InternalPollCandidateId,InternalPollId,PersonId,CandidacyStatement " + // 0-3 + " InternalPollCandidateId,InternalPollId,PersonId,CandidacyStatement " + // 0-3 "FROM InternalPollCandidates "; private static BasicInternalPollCandidate ReadInternalPollCandidateFromDataReader(IDataRecord reader) @@ -26,8 +26,6 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements public BasicInternalPollCandidate GetInternalPollCandidate(int internalPollCandidateId) @@ -38,7 +36,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollCandidateFieldSequence + "WHERE InternalPollCandidateId=" + internalPollCandidateId + ";", connection); + "SELECT" + internalPollCandidateFieldSequence + "WHERE InternalPollCandidateId=" + + internalPollCandidateId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -47,15 +46,18 @@ namespace Swarmops.Database return ReadInternalPollCandidateFromDataReader(reader); } - throw new ArgumentException("Unknown Id: " + internalPollCandidateId.ToString()); + throw new ArgumentException("Unknown Id: " + internalPollCandidateId); } } } /// - /// Gets salaries from the database. + /// Gets salaries from the database. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// A list of matching salaries. public BasicInternalPollCandidate[] GetInternalPollCandidates(params object[] conditions) { @@ -67,7 +69,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollCandidateFieldSequence + ConstructWhereClause("InternalPollCandidates", conditions) + " ORDER BY SortOrder", connection); + "SELECT" + internalPollCandidateFieldSequence + + ConstructWhereClause("InternalPollCandidates", conditions) + " ORDER BY SortOrder", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -81,11 +84,8 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures public int CreateInternalPollCandidate(int internalPollId, int personId, string candidacyStatement) @@ -137,8 +137,6 @@ namespace Swarmops.Database } } - #endregion - } } \ No newline at end of file diff --git a/Database/Database-InternalPollVotes.cs b/Database/Database-InternalPollVotes.cs index 9f5d3573..2b46436e 100644 --- a/Database/Database-InternalPollVotes.cs +++ b/Database/Database-InternalPollVotes.cs @@ -11,9 +11,13 @@ namespace Swarmops.Database #region Field reading code private const string internalPollVoteFieldSequence = - " InternalPollVoteId,InternalPollId,VerificationCode " + // 0-3 + " InternalPollVoteId,InternalPollId,VerificationCode " + // 0-3 "FROM InternalPollVotes "; + private const string internalPollVoterFieldSequence = + " PersonId,InternalPollId,Open,ClosedDateTime " + // 0-3 + "FROM InternalPollVoters "; + private static BasicInternalPollVote ReadInternalPollVoteFromDataReader(IDataRecord reader) { int internalPollVoteId = reader.GetInt32(0); @@ -23,10 +27,6 @@ namespace Swarmops.Database return new BasicInternalPollVote(internalPollVoteId, internalPollId, verificationCode); } - private const string internalPollVoterFieldSequence = - " PersonId,InternalPollId,Open,ClosedDateTime " + // 0-3 - "FROM InternalPollVoters "; - private static BasicInternalPollVoter ReadInternalPollVoterFromDataReader(IDataRecord reader) { int personId = reader.GetInt32(0); @@ -39,8 +39,6 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements public BasicInternalPollVote GetInternalPollVote(int internalPollVoteId) @@ -51,7 +49,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollVoteFieldSequence + "WHERE InternalPollVoteId=" + internalPollVoteId + ";", connection); + "SELECT" + internalPollVoteFieldSequence + "WHERE InternalPollVoteId=" + internalPollVoteId + + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -60,13 +59,13 @@ namespace Swarmops.Database return ReadInternalPollVoteFromDataReader(reader); } - throw new ArgumentException("Unknown Id: " + internalPollVoteId.ToString()); + throw new ArgumentException("Unknown Id: " + internalPollVoteId); } } } - public BasicInternalPollVote GetInternalPollVote (string verificationCode) + public BasicInternalPollVote GetInternalPollVote(string verificationCode) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -74,7 +73,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollVoteFieldSequence + "WHERE VerificationCode='" + verificationCode.Replace("'", "''") + "';", connection); + "SELECT" + internalPollVoteFieldSequence + "WHERE VerificationCode='" + + verificationCode.Replace("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -83,7 +83,7 @@ namespace Swarmops.Database return ReadInternalPollVoteFromDataReader(reader); } - throw new ArgumentException("Unknown Verification Code: " + verificationCode.ToString()); + throw new ArgumentException("Unknown Verification Code: " + verificationCode); } } } @@ -99,7 +99,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollVoteFieldSequence + ConstructWhereClause("InternalPollVotes", conditions) + " ORDER BY VerificationCode", connection); + "SELECT" + internalPollVoteFieldSequence + ConstructWhereClause("InternalPollVotes", conditions) + + " ORDER BY VerificationCode", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -114,7 +115,7 @@ namespace Swarmops.Database } - public InternalPollVoterStatus GetInternalPollVoterStatus (int internalPollId, int personId) + public InternalPollVoterStatus GetInternalPollVoterStatus(int internalPollId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -122,13 +123,16 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT Open FROM InternalPollVoters WHERE InternalPollId=" + internalPollId.ToString() + " AND PersonId=" + personId.ToString(), connection); + "SELECT Open FROM InternalPollVoters WHERE InternalPollId=" + internalPollId + " AND PersonId=" + + personId, connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return reader.GetBoolean(0)? InternalPollVoterStatus.CanVote : InternalPollVoterStatus.HasAlreadyVoted; + return reader.GetBoolean(0) + ? InternalPollVoterStatus.CanVote + : InternalPollVoterStatus.HasAlreadyVoted; } return InternalPollVoterStatus.NotEligibleForPoll; @@ -137,7 +141,7 @@ namespace Swarmops.Database } - public int[] GetInternalPollVoteDetails (int internalPollVoteId) + public int[] GetInternalPollVoteDetails(int internalPollVoteId) { List result = new List(); @@ -147,8 +151,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT InternalPollCandidateId FROM InternalPollVoteDetails WHERE InternalPollVoteId=" + - internalPollVoteId.ToString() + " ORDER BY Position", connection); + "SELECT InternalPollCandidateId FROM InternalPollVoteDetails WHERE InternalPollVoteId=" + + internalPollVoteId + " ORDER BY Position", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -163,7 +167,7 @@ namespace Swarmops.Database } - public BasicInternalPollVoter[] GetInternalPollVoters (params object[] conditions) + public BasicInternalPollVoter[] GetInternalPollVoters(params object[] conditions) { List result = new List(); @@ -172,7 +176,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = GetDbCommand( - "SELECT" + internalPollVoterFieldSequence + ConstructWhereClause("InternalPollVoters", conditions), connection); + "SELECT" + internalPollVoterFieldSequence + ConstructWhereClause("InternalPollVoters", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -184,11 +189,10 @@ namespace Swarmops.Database return result.ToArray(); } } - } - public Dictionary GetCandidateIdPersonIdMap (int pollId) + public Dictionary GetCandidateIdPersonIdMap(int pollId) { Dictionary result = new Dictionary(); @@ -198,7 +202,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT InternalPollCandidateId,PersonId FROM InternalPollCandidates WHERE InternalPollId=" + - pollId.ToString(), connection); + pollId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -212,11 +216,8 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures public int CreateInternalPollVote(int internalPollId, int voteGeographyId, string verificationCode) @@ -255,7 +256,6 @@ namespace Swarmops.Database } - public void ClearInternalPollVote(int internalPollVoteId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -272,8 +272,6 @@ namespace Swarmops.Database } - - public int CreateInternalPollVoter(int internalPollId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -309,9 +307,6 @@ namespace Swarmops.Database } } - - #endregion - } } \ No newline at end of file diff --git a/Database/Database-InternalPolls.cs b/Database/Database-InternalPolls.cs index 6e345e6a..da803b9c 100644 --- a/Database/Database-InternalPolls.cs +++ b/Database/Database-InternalPolls.cs @@ -34,17 +34,16 @@ namespace Swarmops.Database InternalPollResultsType resultsType = (InternalPollResultsType) resultsTypeId; - return new BasicInternalPoll(internalPollId, createdByPersonId, organizationId, geographyId, name, runningOpen, votingOpen, maxVoteLength, runningOpens, runningCloses, votingOpens, votingCloses, resultsType); + return new BasicInternalPoll(internalPollId, createdByPersonId, organizationId, geographyId, name, + runningOpen, votingOpen, maxVoteLength, runningOpens, runningCloses, votingOpens, votingCloses, + resultsType); } #endregion - - - #region Record reading - SELECT statements - public BasicInternalPoll GetInternalPoll (int internalPollId) + public BasicInternalPoll GetInternalPoll(int internalPollId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -52,7 +51,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + internalPollFieldSequence + "WHERE InternalPollId=" + internalPollId + ";", connection); + "SELECT" + internalPollFieldSequence + "WHERE InternalPollId=" + internalPollId + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -61,14 +61,14 @@ namespace Swarmops.Database return ReadInternalPollFromDataReader(reader); } - throw new ArgumentException("Unknown InternalPollId: " + internalPollId.ToString()); + throw new ArgumentException("Unknown InternalPollId: " + internalPollId); } } } /// - /// Gets a list of internal polls. + /// Gets a list of internal polls. /// /// Optional Organization object and/or DatabaseConditions. /// The inbound invoice list. @@ -82,7 +82,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + internalPollFieldSequence + ConstructWhereClause("InternalPoll", conditions), connection); + "SELECT " + internalPollFieldSequence + ConstructWhereClause("InternalPoll", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -96,18 +97,14 @@ namespace Swarmops.Database } } - #endregion - - - #region Creation and manipulation - stored procedures public int CreateInternalPoll(int organizationId, int geographyId, string name, int maxVoteLength, - InternalPollResultsType resultsType, int createdByPersonId, - DateTime runningOpens, DateTime runningCloses, DateTime votingOpens, - DateTime votingCloses) + InternalPollResultsType resultsType, int createdByPersonId, + DateTime runningOpens, DateTime runningCloses, DateTime votingOpens, + DateTime votingCloses) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -165,6 +162,5 @@ namespace Swarmops.Database } #endregion - } } \ No newline at end of file diff --git a/Database/Database-MailTemplates.cs b/Database/Database-MailTemplates.cs index 9777399e..61c249e6 100644 --- a/Database/Database-MailTemplates.cs +++ b/Database/Database-MailTemplates.cs @@ -8,7 +8,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicMailTemplate[] GetMailTemplatesByName (string templatename) + public BasicMailTemplate[] GetMailTemplatesByName(string templatename) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -32,15 +32,12 @@ namespace Swarmops.Database } return retlist.ToArray(); } - else - { - 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()) { @@ -48,7 +45,7 @@ namespace Swarmops.Database string sql = "SELECT * from MailTemplates where TemplateId={0}"; - sql = string.Format(sql, templateId.ToString()); + sql = string.Format(sql, templateId); DbCommand command = GetDbCommand(sql, connection); @@ -58,18 +55,19 @@ namespace Swarmops.Database { return ReadMailTemplate(reader); } - throw new ArgumentException("No mailtemplate with id: " + templateId.ToString() + " exists."); + throw new ArgumentException("No mailtemplate with id: " + templateId + " exists."); } } } - public BasicMailTemplate[] GetAllMailTemplates () + public BasicMailTemplate[] GetAllMailTemplates() { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - string sql = "SELECT * from MailTemplates order by templateName, CountryCode, LanguageCode, OrganizationId"; + string sql = + "SELECT * from MailTemplates order by templateName, CountryCode, LanguageCode, OrganizationId"; DbCommand command = GetDbCommand(sql, connection); @@ -85,23 +83,23 @@ namespace Swarmops.Database } } - 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"] : ""; - string langCode = reader["languageCode"] != DBNull.Value ? (string)reader["languageCode"] : ""; - 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"] : ""; + int templateId = (int) reader["templateId"]; + string templateName = reader["templateName"] != DBNull.Value ? (string) reader["templateName"] : ""; + string langCode = reader["languageCode"] != DBNull.Value ? (string) reader["languageCode"] : ""; + 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); } - public int SetMailTemplate (int templateId, - string templateName, - string languageCode, - string countryCode, - int organizationId, - string templateBody) + public int SetMailTemplate(int templateId, + string templateName, + string languageCode, + string countryCode, + int organizationId, + string templateBody) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -122,14 +120,14 @@ namespace Swarmops.Database } - public int SetMailTemplate (BasicMailTemplate mailTemplate) + public int SetMailTemplate(BasicMailTemplate mailTemplate) { return SetMailTemplate(mailTemplate.TemplateId, - mailTemplate.TemplateName, - mailTemplate.LanguageCode, - mailTemplate.CountryCode, - mailTemplate.OrganizationId, - mailTemplate.TemplateBody); + mailTemplate.TemplateName, + mailTemplate.LanguageCode, + mailTemplate.CountryCode, + mailTemplate.OrganizationId, + mailTemplate.TemplateBody); } } } \ No newline at end of file diff --git a/Database/Database-Media.cs b/Database/Database-Media.cs index 1b5f710b..ac6c9054 100644 --- a/Database/Database-Media.cs +++ b/Database/Database-Media.cs @@ -9,8 +9,8 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreateMediaEntryFromKeyword (string keyword, string mediaName, bool isBlog, string url, string title, - DateTime dateTime) + public int CreateMediaEntryFromKeyword(string keyword, string mediaName, bool isBlog, string url, string title, + DateTime dateTime) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -39,7 +39,7 @@ namespace Swarmops.Database } - 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"); /* @@ -49,7 +49,7 @@ 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"); @@ -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(); @@ -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(); @@ -100,7 +100,8 @@ namespace Swarmops.Database { 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))); } } } @@ -109,21 +110,22 @@ namespace Swarmops.Database } - private BasicMediaEntry ReadMediaEntryFromReader (DbDataReader reader) // NOT ok -- will need to migrate; any dependencies also won't work + private BasicMediaEntry ReadMediaEntryFromReader(DbDataReader reader) + // NOT ok -- will need to migrate; any dependencies also won't work { - int id = (int)reader["MediaKeywordEntryId"]; - int keywordId = (int)reader["MediaKeywordId"]; - string mediaName = (string)reader["MediaName"]; - bool isBlog = (bool)reader["IsBlog"]; - string mediaEntryTitle = (string)reader["MediaEntryTitle"]; - string mediaEntryUrl = (string)reader["MediaEntryUrl"]; - DateTime mediaEntryDateTime = (DateTime)reader["MediaEntryDateTime"]; + int id = (int) reader["MediaKeywordEntryId"]; + int keywordId = (int) reader["MediaKeywordId"]; + string mediaName = (string) reader["MediaName"]; + bool isBlog = (bool) reader["IsBlog"]; + string mediaEntryTitle = (string) reader["MediaEntryTitle"]; + string mediaEntryUrl = (string) reader["MediaEntryUrl"]; + DateTime mediaEntryDateTime = (DateTime) reader["MediaEntryDateTime"]; object translatedUrlObject = reader["TranslatedUrl"]; - if (!(translatedUrlObject is System.DBNull)) + if (!(translatedUrlObject is DBNull)) { - string translatedUrl = (string)translatedUrlObject; + string translatedUrl = (string) translatedUrlObject; if (translatedUrl != null && translatedUrl.Trim().Length > 0) { @@ -132,11 +134,11 @@ namespace Swarmops.Database } return new BasicMediaEntry(id, keywordId, mediaName, isBlog, mediaEntryTitle, mediaEntryUrl, - mediaEntryDateTime); + mediaEntryDateTime); } - public string[] GetBlogKeywords () // OK + public string[] GetBlogKeywords() // OK { List result = new List(); @@ -145,7 +147,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = GetDbCommand("SELECT MediaKeyword From MediaKeywords WHERE SearchBlogs=1", - connection); + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -158,7 +160,7 @@ namespace Swarmops.Database return result.ToArray(); } - public string[] GetOldMediaKeywords () // OK + public string[] GetOldMediaKeywords() // OK { List result = new List(); @@ -167,7 +169,7 @@ namespace Swarmops.Database connection.Open(); DbCommand command = GetDbCommand("SELECT MediaKeyword From MediaKeywords WHERE SearchOldMedia=1", - connection); + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -181,7 +183,7 @@ namespace Swarmops.Database } - public Dictionary GetMediaTypeTable () // OK Todo: create enum instead of bool + public Dictionary GetMediaTypeTable() // OK Todo: create enum instead of bool { Dictionary result = new Dictionary(); @@ -202,7 +204,7 @@ namespace Swarmops.Database return result; } - public int GetMediaKeywordId (string keyword) // OK + public int GetMediaKeywordId(string keyword) // OK { using (DbConnection connection = GetMySqlDbConnection()) { @@ -219,16 +221,13 @@ namespace Swarmops.Database { return reader.GetInt32(0); } - else - { - return 0; - } + return 0; } } } - public Dictionary GetMediaKeywordTable () // OK + public Dictionary GetMediaKeywordTable() // OK { Dictionary result = new Dictionary(); @@ -250,7 +249,7 @@ namespace Swarmops.Database } - public BasicMediaCategory GetMediaCategory (int mediaCategoryId) // OK + public BasicMediaCategory GetMediaCategory(int mediaCategoryId) // OK { using (DbConnection connection = GetMySqlDbConnection()) { @@ -258,7 +257,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT Name FROM MediaCategories WHERE MediaCategoryId=" + mediaCategoryId.ToString(), + "SELECT Name FROM MediaCategories WHERE MediaCategoryId=" + mediaCategoryId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -268,13 +267,13 @@ namespace Swarmops.Database return new BasicMediaCategory(mediaCategoryId, reader.GetString(0)); } - throw new ArgumentException("No such MediaCategoryId: " + mediaCategoryId.ToString()); + throw new ArgumentException("No such MediaCategoryId: " + mediaCategoryId); } } } - public BasicMediaCategory GetMediaCategoryByName (string mediaCategoryName) // OK + public BasicMediaCategory GetMediaCategoryByName(string mediaCategoryName) // OK { using (DbConnection connection = GetMySqlDbConnection()) { @@ -298,7 +297,7 @@ namespace Swarmops.Database } - public BasicMediaCategory[] GetMediaCategories (int[] mediaCategoryIds) + public BasicMediaCategory[] GetMediaCategories(int[] mediaCategoryIds) { List result = new List(); @@ -324,7 +323,7 @@ namespace Swarmops.Database } - public BasicMediaCategory[] GetMediaCategories () + public BasicMediaCategory[] GetMediaCategories() { List result = new List(); @@ -349,7 +348,7 @@ namespace Swarmops.Database } - public BasicMedium[] GetBlogTopList (DateTime date) // OK - migrated + public BasicMedium[] GetBlogTopList(DateTime date) // OK - migrated { using (DbConnection connection = GetMySqlDbConnection()) { @@ -379,7 +378,7 @@ namespace Swarmops.Database command = GetDbCommand( "select BlogRankings.MediaId,Media.Name from BlogRankings JOIN Media USING (MediaId) WHERE BlogRankings.BlogRankingDateId=" + - dateId.ToString() + " ORDER BY Ranking", connection); + dateId + " ORDER BY Ranking", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -397,7 +396,7 @@ 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()) { @@ -425,7 +424,7 @@ namespace Swarmops.Database } - private string LimitStringLength (string input, int maxLength) + private string LimitStringLength(string input, int maxLength) { if (input.Length > maxLength) { diff --git a/Database/Database-Meetings.cs b/Database/Database-Meetings.cs index 73817e65..35f3b112 100644 --- a/Database/Database-Meetings.cs +++ b/Database/Database-Meetings.cs @@ -11,8 +11,8 @@ namespace Swarmops.Database #region Field reading code private const string meetingFieldSequence = - " MeetingId,OrganizationId,Name,MotionSubmissionEnds,AmendmentSubmissionEnds," + // 0-4 - "AmendmentVotingStarts,AmendmentVotingEnds,MotionVotingStarts,MotionVotingEnds " + // 5-8 + " MeetingId,OrganizationId,Name,MotionSubmissionEnds,AmendmentSubmissionEnds," + // 0-4 + "AmendmentVotingStarts,AmendmentVotingEnds,MotionVotingStarts,MotionVotingEnds " + // 5-8 "FROM Meetings "; private static BasicMeeting ReadMeetingFromDataReader(IDataRecord reader) @@ -28,13 +28,11 @@ namespace Swarmops.Database DateTime motionVotingEnds = reader.GetDateTime(8); return new BasicMeeting(meetingId, organizationId, name, motionSubmissionEnds, amendmentSubmissionEnds, - amendmentVotingStarts, amendmentVotingEnds, motionVotingStarts, motionVotingEnds); + amendmentVotingStarts, amendmentVotingEnds, motionVotingStarts, motionVotingEnds); } #endregion - - #region Record reading - SELECT statements public BasicMeeting GetMeeting(int meetingId) @@ -54,7 +52,7 @@ namespace Swarmops.Database return ReadMeetingFromDataReader(reader); } - throw new ArgumentException("Unknown Meeting Id: " + meetingId.ToString()); + throw new ArgumentException("Unknown Meeting Id: " + meetingId); } } } @@ -83,11 +81,8 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures /* @@ -192,8 +187,6 @@ namespace Swarmops.Database } */ - #endregion - } } \ No newline at end of file diff --git a/Database/Database-Memberships.cs b/Database/Database-Memberships.cs index fec03f15..82fc0dbc 100644 --- a/Database/Database-Memberships.cs +++ b/Database/Database-Memberships.cs @@ -29,7 +29,17 @@ namespace Swarmops.Database } }*/ - public int[] GetMembersForOrganizations (int[] organizationIds) + private const string membershipFieldSequence = + " Memberships.MembershipId, Memberships.PersonId, Memberships.OrganizationId, Memberships.Active, Memberships.Expires, " + + // 0-4 + " Memberships.MemberSince, Memberships.DateTimeTerminated, Memberships.TerminatedAsInvalid " + // 5-7 + " FROM Memberships "; + + private const string membershipPaymentStatusFieldSequence = + " MembershipPayments.MembershipId, MembershipPayments.MembershipPaymentStatusId, MembershipPayments.StatusDateTime " + + " FROM MembershipPayments "; + + public int[] GetMembersForOrganizations(int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -53,7 +63,7 @@ namespace Swarmops.Database } - public int[] GetMembersForOrganizationsAndGeographies (int[] organizationIds, int[] geographyIds) + public int[] GetMembersForOrganizationsAndGeographies(int[] organizationIds, int[] geographyIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -83,7 +93,7 @@ namespace Swarmops.Database } - public BasicMembership[] GetMemberships (params object[] conditions) + public BasicMembership[] GetMemberships(params object[] conditions) { List result = new List(); @@ -91,7 +101,9 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + membershipFieldSequence + ConstructWhereClause("Memberships", conditions), connection); + DbCommand command = + GetDbCommand("SELECT " + membershipFieldSequence + ConstructWhereClause("Memberships", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -103,15 +115,15 @@ namespace Swarmops.Database return result.ToArray(); } } - } - public BasicMembership[] GetValidMembershipsForOrganizationAndPaymentStatus (int[] organizationIds, int paymentStatus) + public BasicMembership[] GetValidMembershipsForOrganizationAndPaymentStatus(int[] organizationIds, + int paymentStatus) { string sqlCommand = - @"SELECT " + membershipFieldSequence + - @" LEFT OUTER JOIN + @"SELECT " + membershipFieldSequence + + @" LEFT OUTER JOIN MembershipPayments ON Memberships.MembershipId = MembershipPayments.MembershipId WHERE (Memberships.Active = 1) AND (coalesce(MembershipPayments.MembershipPaymentStatusId, 0) = " + paymentStatus + @") @@ -140,9 +152,7 @@ namespace Swarmops.Database } - - - public int GetMembershipCountForOrganizations (int[] organizationIds) + public int GetMembershipCountForOrganizations(int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -162,7 +172,7 @@ namespace Swarmops.Database } } - public int GetMembershipCountForOrganizationsSince (int[] organizationIds, DateTime sinceWhen) + public int GetMembershipCountForOrganizationsSince(int[] organizationIds, DateTime sinceWhen) { if (organizationIds == null || organizationIds.Length == 0) { @@ -183,7 +193,7 @@ namespace Swarmops.Database } } - public int GetMemberCountForOrganizations (int[] organizationIds) + public int GetMemberCountForOrganizations(int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -203,7 +213,7 @@ namespace Swarmops.Database } } - public int GetMemberCountForOrganizationsAndGeographies (int[] organizationIds, int[] geographyIds) + public int GetMemberCountForOrganizationsAndGeographies(int[] organizationIds, int[] geographyIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -230,7 +240,7 @@ namespace Swarmops.Database } - private static int[] ReadIntegersAtZeroFromDataReader (DbDataReader reader) + private static int[] ReadIntegersAtZeroFromDataReader(DbDataReader reader) { List result = new List(); @@ -243,13 +253,13 @@ namespace Swarmops.Database } - public Dictionary> GetMembershipsForPeople (int[] personIds) + public Dictionary> GetMembershipsForPeople(int[] personIds) { return GetMembershipsForPeople(personIds, 0); } - public Dictionary> GetMembershipsForPeople (int[] personIds, int gracePeriod) + public Dictionary> GetMembershipsForPeople(int[] personIds, int gracePeriod) { Dictionary> result = new Dictionary>(); @@ -271,9 +281,11 @@ namespace Swarmops.Database connection.Open(); string commandString = "SELECT " + membershipFieldSequence + " WHERE " - + (gracePeriod == 0 ? "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) + ")"; + + (gracePeriod == 0 + ? "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) + ")"; DbCommand command = GetDbCommand(commandString, connection); command.CommandTimeout = 30; // If 30s is too short, something needs optimization. @@ -299,7 +311,8 @@ namespace Swarmops.Database return result; } - private Dictionary> GetMembershipsForPeopleOptimizedForLargeSets (int[] personIds, int gracePeriod) + private Dictionary> GetMembershipsForPeopleOptimizedForLargeSets(int[] personIds, + int gracePeriod) { // This version is optimized for larger data sets. Rather than asking the database // for the correct set of people, ALL memberships are retrieved, and the filtering is @@ -337,7 +350,8 @@ namespace Swarmops.Database 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)) { @@ -353,13 +367,11 @@ namespace Swarmops.Database } - return result; } - - public BasicMembership GetActiveMembership (int personId, int organizationId) + public BasicMembership GetActiveMembership(int personId, int organizationId) { if (personId == 0) { @@ -379,8 +391,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + membershipFieldSequence + " WHERE Active=1 AND PersonId=" + personId.ToString() + - " AND OrganizationId=" + organizationId.ToString(), connection); + "SELECT " + membershipFieldSequence + " WHERE Active=1 AND PersonId=" + personId + + " AND OrganizationId=" + organizationId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -389,14 +401,14 @@ namespace Swarmops.Database return ReadMembershipFromDataReader(reader); } - throw new ArgumentException("No active membership for personid " + personId.ToString() + - ", organizationid " + organizationId.ToString()); + 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 { @@ -410,14 +422,14 @@ 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.ToString(), connection); + GetDbCommand("SELECT " + membershipFieldSequence + " WHERE MembershipId=" + membershipId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -426,19 +438,13 @@ namespace Swarmops.Database return ReadMembershipFromDataReader(reader); } - throw new ArgumentOutOfRangeException("No such MembershipId: " + membershipId.ToString()); + throw new ArgumentOutOfRangeException("No such MembershipId: " + membershipId); } } } - private const string membershipFieldSequence = - " Memberships.MembershipId, Memberships.PersonId, Memberships.OrganizationId, Memberships.Active, Memberships.Expires, " + // 0-4 - " Memberships.MemberSince, Memberships.DateTimeTerminated, Memberships.TerminatedAsInvalid " + // 5-7 - " FROM Memberships "; - - - private static BasicMembership ReadMembershipFromDataReader (DbDataReader reader) + private static BasicMembership ReadMembershipFromDataReader(DbDataReader reader) { int membershipId = reader.GetInt32(0); int personId = reader.GetInt32(1); @@ -450,19 +456,20 @@ namespace Swarmops.Database // bool terminatedAsInvalid = reader.GetBoolean(7); Ignore this field for now return new BasicMembership(membershipId, personId, organizationId, memberSince, expires, active, - dateTerminated); + dateTerminated); } - - public BasicMembershipPaymentStatus GetMembershipPaymentStatus (int membershipId) + public BasicMembershipPaymentStatus GetMembershipPaymentStatus(int membershipId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId=" + membershipId.ToString() + " ORDER BY StatusDateTime DESC LIMIT 1", connection); + GetDbCommand( + "SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId=" + + membershipId + " ORDER BY StatusDateTime DESC LIMIT 1", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -473,12 +480,13 @@ namespace Swarmops.Database // 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) @@ -488,7 +496,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId IN (" + JoinIds(membershipIds) + ") ORDER BY StatusDateTime ASC ", connection); + GetDbCommand( + "SELECT " + membershipPaymentStatusFieldSequence + " WHERE MembershipPayments.MembershipId IN (" + + JoinIds(membershipIds) + ") ORDER BY StatusDateTime ASC ", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) @@ -499,8 +509,8 @@ namespace Swarmops.Database foreach (int i in membershipIds) { if (!retVal.ContainsKey(i)) - retVal[i] = new BasicMembershipPaymentStatus(i, MembershipPaymentStatus.Unknown, new DateTime(1900, 1, 1)); - + retVal[i] = new BasicMembershipPaymentStatus(i, MembershipPaymentStatus.Unknown, + new DateTime(1900, 1, 1)); } return retVal; } @@ -508,24 +518,18 @@ namespace Swarmops.Database } - - - private const string membershipPaymentStatusFieldSequence = - " MembershipPayments.MembershipId, MembershipPayments.MembershipPaymentStatusId, MembershipPayments.StatusDateTime " + - " FROM MembershipPayments "; - - - 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); - return new BasicMembershipPaymentStatus(membershipId, (MembershipPaymentStatus)membershipPaymentStatusId, statusDateTime); + 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()) { @@ -541,7 +545,8 @@ namespace Swarmops.Database } } - public void SetMembershipPaymentStatus (int membershipId, MembershipPaymentStatus paymentStatus, DateTime statusDateTime) + public void SetMembershipPaymentStatus(int membershipId, MembershipPaymentStatus paymentStatus, + DateTime statusDateTime) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -550,7 +555,7 @@ namespace Swarmops.Database command.CommandType = CommandType.StoredProcedure; AddParameterWithName(command, "membershipId", membershipId); - AddParameterWithName(command, "paymentStatusId", (int)paymentStatus); + AddParameterWithName(command, "paymentStatusId", (int) paymentStatus); AddParameterWithName(command, "statusDateTime", statusDateTime); command.ExecuteNonQuery(); @@ -558,7 +563,7 @@ namespace Swarmops.Database } - public int CreateMembership (int personId, int organizationId, DateTime expires) + public int CreateMembership(int personId, int organizationId, DateTime expires) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -575,7 +580,7 @@ namespace Swarmops.Database } } - 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()) { @@ -595,13 +600,13 @@ namespace Swarmops.Database } - public void TerminateMembership (int membershipId) + public void TerminateMembership(int membershipId) { TerminateMembership(membershipId, false); } - public void TerminateMembership (int membershipId, bool asInvalid) + public void TerminateMembership(int membershipId, bool asInvalid) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -617,24 +622,26 @@ namespace Swarmops.Database } } - public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime expiry) + public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime expiry) { return GetExpiringMemberships(organization, expiry, expiry); } - public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound) + public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime lowerBound, + DateTime upperBound) { return GetExpiringMemberships(organization, lowerBound, upperBound, DatabaseCondition.ActiveTrue); } - public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound, DatabaseCondition condition) + 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 // that the dates are passed in text in SQL, we get ALL the memberships and do // 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 = this.GetMemberships(organization, condition); + BasicMembership[] memberships = GetMemberships(organization, condition); DateTime minimumDateTime = lowerBound.Date; DateTime maximumDateTime = upperBound.Date.AddDays(1); diff --git a/Database/Database-MotionAmendments.cs b/Database/Database-MotionAmendments.cs index c2e89387..abd876c0 100644 --- a/Database/Database-MotionAmendments.cs +++ b/Database/Database-MotionAmendments.cs @@ -11,9 +11,11 @@ namespace Swarmops.Database #region Field reading code private const string motionAmendmentFieldSequence = - " MotionAmendmentId,MotionAmendments.MotionId,MotionAmendments.SequenceNumber,MotionAmendments.SubmittedByPersonId,MotionAmendments.CreatedByPersonId," + // 0-4 - "MotionAmendments.CreatedDateTime,MotionAmendments.Title,MotionAmendments.Text,MotionAmendments.DecisionPoint,MotionAmendments.Open," + // 5-9 - "MotionAmendments.Carried " + // 10 + " MotionAmendmentId,MotionAmendments.MotionId,MotionAmendments.SequenceNumber,MotionAmendments.SubmittedByPersonId,MotionAmendments.CreatedByPersonId," + + // 0-4 + "MotionAmendments.CreatedDateTime,MotionAmendments.Title,MotionAmendments.Text,MotionAmendments.DecisionPoint,MotionAmendments.Open," + + // 5-9 + "MotionAmendments.Carried " + // 10 "FROM MotionAmendments "; private static BasicMotionAmendment ReadMotionAmendmentFromDataReader(IDataRecord reader) @@ -30,13 +32,12 @@ namespace Swarmops.Database bool open = reader.GetBoolean(9); bool carried = reader.GetBoolean(10); - return new BasicMotionAmendment(motionAmendmentId, motionId, sequenceNumber, submittedByPersonId, createdByPersonId, createdDateTime, title, text, decisionPoint, open, carried); + return new BasicMotionAmendment(motionAmendmentId, motionId, sequenceNumber, submittedByPersonId, + createdByPersonId, createdDateTime, title, text, decisionPoint, open, carried); } #endregion - - #region Record reading - SELECT statements public BasicMotionAmendment GetMotionAmendment(int motionAmendmentId) @@ -47,7 +48,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + motionAmendmentFieldSequence + "WHERE MotionAmendmentId=" + motionAmendmentId + ";", connection); + "SELECT" + motionAmendmentFieldSequence + "WHERE MotionAmendmentId=" + motionAmendmentId + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -56,7 +58,7 @@ namespace Swarmops.Database return ReadMotionAmendmentFromDataReader(reader); } - throw new ArgumentException("Unknown MotionAmendment Id: " + motionAmendmentId.ToString()); + throw new ArgumentException("Unknown MotionAmendment Id: " + motionAmendmentId); } } } @@ -71,7 +73,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + motionAmendmentFieldSequence + ConstructWhereClause("MotionAmendments", conditions), connection); + "SELECT" + motionAmendmentFieldSequence + ConstructWhereClause("MotionAmendments", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -96,7 +99,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + motionAmendmentFieldSequence + " JOIN Motions ON (Motions.MotionId=MotionAmendments.MotionId) WHERE Motions.MeetingId=" + meetingId.ToString(), connection); + "SELECT" + motionAmendmentFieldSequence + + " JOIN Motions ON (Motions.MotionId=MotionAmendments.MotionId) WHERE Motions.MeetingId=" + + meetingId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -110,16 +115,12 @@ namespace Swarmops.Database } } - - - #endregion - - #region Creation and manipulation - stored procedures - public int CreateMotionAmendment(int motionId, int submittingPersonId, int createdByPersonId, string title, string text, string decisionPoint) + public int CreateMotionAmendment(int motionId, int submittingPersonId, int createdByPersonId, string title, + string text, string decisionPoint) { DateTime now = DateTime.Now; @@ -141,6 +142,7 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } + /* public void SetSalaryNetPaid(int salaryId, bool netPaid) @@ -220,8 +222,6 @@ namespace Swarmops.Database } */ - #endregion - } } \ No newline at end of file diff --git a/Database/Database-Motions.cs b/Database/Database-Motions.cs index 28efe89a..c3789fdf 100644 --- a/Database/Database-Motions.cs +++ b/Database/Database-Motions.cs @@ -11,10 +11,10 @@ namespace Swarmops.Database #region Field reading code private const string motionFieldSequence = - " MotionId,MeetingId,Designation,SubmittedByPersonId,CreatedByPersonId," + // 0-4 - "CreatedDateTime,AmendedByPersonId,AmendedDateTime,Title,Text," + // 5-9 - "AmendedText,DecisionPoints,AmendedDecisionPoints,Open,Carried," + // 10-14 - "ThreadUrl,Amended,SequenceNumber " + // 15-17 + " MotionId,MeetingId,Designation,SubmittedByPersonId,CreatedByPersonId," + // 0-4 + "CreatedDateTime,AmendedByPersonId,AmendedDateTime,Title,Text," + // 5-9 + "AmendedText,DecisionPoints,AmendedDecisionPoints,Open,Carried," + // 10-14 + "ThreadUrl,Amended,SequenceNumber " + // 15-17 "FROM Motions "; private static BasicMotion ReadMotionFromDataReader(IDataRecord reader) @@ -38,13 +38,13 @@ namespace Swarmops.Database bool amended = reader.GetBoolean(16); int sequenceNumber = reader.GetInt32(17); - return new BasicMotion(motionId, meetingId, sequenceNumber, designation, submittedByPersonId, createdByPersonId, createdDateTime, amended, amendedByPersonId, amendedDateTime, title, text, amendedText, decisionPoints, amendedDecisionPoints, threadUrl, open, passed); + return new BasicMotion(motionId, meetingId, sequenceNumber, designation, submittedByPersonId, + createdByPersonId, createdDateTime, amended, amendedByPersonId, amendedDateTime, title, text, + amendedText, decisionPoints, amendedDecisionPoints, threadUrl, open, passed); } #endregion - - #region Record reading - SELECT statements public BasicMotion GetMotion(int motionId) @@ -64,7 +64,7 @@ namespace Swarmops.Database return ReadMotionFromDataReader(reader); } - throw new ArgumentException("Unknown Motion Id: " + motionId.ToString()); + throw new ArgumentException("Unknown Motion Id: " + motionId); } } } @@ -93,14 +93,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public int CreateMotion(int meetingId, int submittingPersonId, int creatingPersonId, string title, string text, string decisionPoints) + public int CreateMotion(int meetingId, int submittingPersonId, int creatingPersonId, string title, string text, + string decisionPoints) { DateTime now = DateTime.Now; @@ -122,6 +120,7 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } + /* public void SetSalaryNetPaid(int salaryId, bool netPaid) @@ -201,8 +200,6 @@ namespace Swarmops.Database } */ - #endregion - } } \ No newline at end of file diff --git a/Database/Database-Newsletters.cs b/Database/Database-Newsletters.cs index 49c834e1..e3613220 100644 --- a/Database/Database-Newsletters.cs +++ b/Database/Database-Newsletters.cs @@ -9,17 +9,17 @@ namespace Swarmops.Database public partial class SwarmDb { /// - /// Gets all subscribed people for a certain newsletter. + /// Gets all subscribed people for a certain newsletter. /// /// The Report Id. /// An int array of PersonId. - public int[] GetSubscribersForNewsletterFeed (int newsletterFeedId) + public int[] GetSubscribersForNewsletterFeed(int newsletterFeedId) { - System.Collections.Generic.Dictionary hash = new Dictionary(); + Dictionary hash = new Dictionary(); // First, we get the newsletter feed we're working with. - BasicNewsletterFeed newsletterFeed = this.GetNewsletterFeed(newsletterFeedId); + BasicNewsletterFeed newsletterFeed = GetNewsletterFeed(newsletterFeedId); if (newsletterFeed.DefaultSubscribed) { @@ -31,7 +31,7 @@ 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 = this.GetOrganizationTree(newsletterFeed.OrganizationId); + BasicOrganization[] orgTree = GetOrganizationTree(newsletterFeed.OrganizationId); List organizationIds = new List(); @@ -40,7 +40,7 @@ namespace Swarmops.Database organizationIds.Add(org.Identity); } - int[] personIds = this.GetMembersForOrganizations(organizationIds.ToArray()); + int[] personIds = GetMembersForOrganizations(organizationIds.ToArray()); foreach (int personId in personIds) { @@ -92,19 +92,21 @@ namespace Swarmops.Database /// - /// Gets data about a specific newsletter. + /// Gets data about a specific newsletter. /// /// 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("SELECT OrganizationId,DefaultSubscribed,Name FROM NewsletterFeeds WHERE NewsletterFeedId=" + newsletterFeedId.ToString(), - connection); + GetDbCommand( + "SELECT OrganizationId,DefaultSubscribed,Name FROM NewsletterFeeds WHERE NewsletterFeedId=" + + newsletterFeedId.ToString(), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -125,11 +127,11 @@ namespace Swarmops.Database } /// - /// Returns all newsletterfeeds for organisation + those with org =0 + /// Returns all newsletterfeeds for organisation + those with org =0 /// /// /// - public BasicNewsletterFeed[] GetNewsletterFeedsForOrganization (int organizationId) + public BasicNewsletterFeed[] GetNewsletterFeedsForOrganization(int organizationId) { List feeds = new List(); @@ -140,7 +142,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT NewsletterFeedId, Name, DefaultSubscribed FROM NewsletterFeeds WHERE OrganizationId =" + - organizationId.ToString() , connection); + organizationId.ToString(), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -150,7 +152,7 @@ namespace Swarmops.Database string reportName = reader.GetString(1); bool defaultSubscribed = reader.GetBoolean(2); feeds.Add(new BasicNewsletterFeed(newsletterFeedId, organizationId, defaultSubscribed, - reportName)); + reportName)); } } } @@ -158,10 +160,10 @@ namespace Swarmops.Database return feeds.ToArray(); } - public System.Collections.Generic.Dictionary GetNewsletterFeedsForSubscriber (int personId) + public Dictionary GetNewsletterFeedsForSubscriber(int personId) { - System.Collections.Generic.Dictionary subs = - new System.Collections.Generic.Dictionary(); + Dictionary subs = + new Dictionary(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -186,7 +188,7 @@ 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()) { @@ -203,7 +205,7 @@ namespace Swarmops.Database } } - public void DeletePersonNewsletterSubscriptions (int personId) // reverts to default + public void DeletePersonNewsletterSubscriptions(int personId) // reverts to default { using (DbConnection connection = GetMySqlDbConnection()) { diff --git a/Database/Database-Optimizations.cs b/Database/Database-Optimizations.cs index d6b38495..d0e5faae 100644 --- a/Database/Database-Optimizations.cs +++ b/Database/Database-Optimizations.cs @@ -11,9 +11,9 @@ namespace Swarmops.Database public partial class SwarmDb { /// - /// Optimization function. + /// Optimization function. /// - public Dictionary GetPeopleWhoDeclineLocalMail (int[] personIds) + public Dictionary GetPeopleWhoDeclineLocalMail(int[] personIds) { Array.Sort(personIds); Dictionary result = new Dictionary(); @@ -59,7 +59,7 @@ namespace Swarmops.Database // Step 2 - find people who have "NeverMail" set - int[] neverMailPersonIds = this.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 @@ -76,8 +76,7 @@ namespace Swarmops.Database } - - public Dictionary GetPeopleGeographies() + public Dictionary GetPeopleGeographies() { Dictionary result = new Dictionary(); @@ -106,7 +105,7 @@ namespace Swarmops.Database } - public Dictionary GetInternalPollVoteCountsPerGeography(int pollId) + public Dictionary GetInternalPollVoteCountsPerGeography(int pollId) { Dictionary result = new Dictionary(); @@ -116,7 +115,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "select count(*) AS VoteCount,VoteGeographyId from InternalPollVotes where InternalPollId=" + pollId.ToString() + " GROUP BY VoteGeographyId", + "select count(*) AS VoteCount,VoteGeographyId from InternalPollVotes where InternalPollId=" + + pollId + " GROUP BY VoteGeographyId", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -133,6 +133,5 @@ namespace Swarmops.Database return result; } - } } \ No newline at end of file diff --git a/Database/Database-OptionalData.cs b/Database/Database-OptionalData.cs index 946fbd6d..73c3daa9 100644 --- a/Database/Database-OptionalData.cs +++ b/Database/Database-OptionalData.cs @@ -15,10 +15,9 @@ namespace Swarmops.Database "JOIN ObjectTypes ON (ObjectTypes.ObjectTypeId=ObjectOptionalData.ObjectTypeId) " + "JOIN ObjectOptionalDataTypes ON (ObjectOptionalData.ObjectOptionalDataTypeId=ObjectOptionalDataTypes.ObjectOptionalDataTypeId) "; - #region Select statements - reading data - public BasicObjectOptionalData GetObjectOptionalData (IHasIdentity forObject) + public BasicObjectOptionalData GetObjectOptionalData(IHasIdentity forObject) { Dictionary initialData = new Dictionary(); ObjectType objectType = GetObjectTypeForObject(forObject); @@ -30,8 +29,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType.ToString() + "' " + - "AND ObjectOptionalData.ObjectId=" + objectId.ToString() + ";", connection); + "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType + "' " + + "AND ObjectOptionalData.ObjectId=" + objectId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -40,11 +39,11 @@ namespace Swarmops.Database string objectOptionalDataTypeString = reader.GetString(2); string data = reader.GetString(3); - try + try { ObjectOptionalDataType objectOptionalDataType = (ObjectOptionalDataType) - Enum.Parse(typeof(ObjectOptionalDataType), objectOptionalDataTypeString); + Enum.Parse(typeof (ObjectOptionalDataType), objectOptionalDataTypeString); initialData[objectOptionalDataType] = data; } @@ -60,7 +59,7 @@ namespace Swarmops.Database } - public int[] GetObjectsByOptionalData (ObjectType objectType, ObjectOptionalDataType dataType, string data) + public int[] GetObjectsByOptionalData(ObjectType objectType, ObjectOptionalDataType dataType, string data) { List objectIds = new List(); @@ -70,8 +69,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType.ToString() + "' " + - "AND ObjectOptionalDataTypes.Name='" + dataType.ToString() + "' " + + "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType + "' " + + "AND ObjectOptionalDataTypes.Name='" + dataType + "' " + "AND ObjectOptionalData.Data='" + data.Replace("'", "''") + "';", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -87,7 +86,7 @@ namespace Swarmops.Database } - static private ObjectType GetObjectTypeForObject (IHasIdentity objectToIdentify) + private static ObjectType GetObjectTypeForObject(IHasIdentity objectToIdentify) { //string objectTypeString = objectToIdentify.GetType().ToString(); @@ -101,17 +100,17 @@ 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 { //That failed. This could be a subclass, try upwards. - Type parentType = objectToIdentify.GetType().BaseType; - while (parentType != typeof(Object)) + Type parentType = objectToIdentify.GetType().BaseType; + while (parentType != typeof (Object)) { try { - return (ObjectType)Enum.Parse(typeof(ObjectType), parentType.Name); + return (ObjectType) Enum.Parse(typeof (ObjectType), parentType.Name); } catch { @@ -119,15 +118,15 @@ 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()) { @@ -145,7 +144,6 @@ namespace Swarmops.Database } } - #endregion } -} +} \ No newline at end of file diff --git a/Database/Database-OrganizationFinancialAccounts.cs b/Database/Database-OrganizationFinancialAccounts.cs index 5a5aa625..a737c431 100644 --- a/Database/Database-OrganizationFinancialAccounts.cs +++ b/Database/Database-OrganizationFinancialAccounts.cs @@ -10,10 +10,10 @@ namespace Swarmops.Database " OrganizationFinancialAccountTypes.Name AS OrganizationFinancialAccountType,OrganizationFinancialAccounts.OrganizationId,OrganizationFinancialAccounts.FinancialAccountId FROM OrganizationFinancialAccounts " + "JOIN OrganizationFinancialAccountTypes ON (OrganizationFinancialAccounts.OrganizationFinancialAccountTypeId=OrganizationFinancialAccountTypes.OrganizationFinancialAccountTypeId) "; - #region Select statements - reading data - public int GetOrganizationFinancialAccountId(int organizationId, OrganizationFinancialAccountType organizationFinancialAccountType) + public int GetOrganizationFinancialAccountId(int organizationId, + OrganizationFinancialAccountType organizationFinancialAccountType) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -21,8 +21,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + organizationFinancialAccountsDataFieldSequence + "WHERE OrganizationFinancialAccountTypes.Name='" + organizationFinancialAccountType.ToString() + "' " + - "AND OrganizationFinancialAccounts.Organizationid=" + organizationId.ToString() + ";", connection); + "SELECT" + organizationFinancialAccountsDataFieldSequence + + "WHERE OrganizationFinancialAccountTypes.Name='" + organizationFinancialAccountType + "' " + + "AND OrganizationFinancialAccounts.Organizationid=" + organizationId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -39,6 +40,7 @@ namespace Swarmops.Database } } } + /* public int[] GetObjectsByOptionalData(ObjectType objectType, ObjectOptionalDataType dataType, string data) @@ -105,10 +107,10 @@ namespace Swarmops.Database #endregion - #region Stored procedures for modifying data - public void SetOrganizationFinancialAccountId(int organizationId, OrganizationFinancialAccountType accountType, int financialAccountId) + public void SetOrganizationFinancialAccountId(int organizationId, OrganizationFinancialAccountType accountType, + int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -125,7 +127,6 @@ namespace Swarmops.Database } } - #endregion } -} +} \ No newline at end of file diff --git a/Database/Database-Organizations.cs b/Database/Database-Organizations.cs index 100f644f..795a8c08 100644 --- a/Database/Database-Organizations.cs +++ b/Database/Database-Organizations.cs @@ -11,12 +11,12 @@ namespace Swarmops.Database #region Field reading code private const string organizationFieldSequence = - " OrganizationId, ParentOrganizationId, Name, NameInternational, NameShort, " + // 0-4 + " OrganizationId, ParentOrganizationId, Name, NameInternational, NameShort, " + // 0-4 "Domain, MailPrefix, AnchorGeographyId, AcceptsMembers, AutoAssignNewMembers, " + // 5-9 "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); @@ -31,17 +31,16 @@ namespace Swarmops.Database int defaultCountryId = reader.GetInt32(10); return new BasicOrganization(organizationId, parentOrganizationId, name, nameInternational, nameShort, - domain, mailPrefix, anchorGeographyId, acceptsMembers, autoAssignNewMembers, - defaultCountryId); + domain, mailPrefix, anchorGeographyId, acceptsMembers, autoAssignNewMembers, + defaultCountryId); } - #endregion - - public int CreateOrganization (int ParentOrganizationId, string NameInternational, string Name, string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, int DefaultCountryId) + public int CreateOrganization(int ParentOrganizationId, string NameInternational, string Name, string NameShort, + string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, bool AutoAssignNewMembers, + int DefaultCountryId) { - using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -64,7 +63,7 @@ namespace Swarmops.Database } } - public void DeleteOrganization (int OrganizationId) + public void DeleteOrganization(int OrganizationId) { int deletedOrganizationsID = 98; BasicOrganization org = GetOrganization(OrganizationId); @@ -81,12 +80,12 @@ namespace Swarmops.Database org.AutoAssignNewMembers, org.DefaultCountryId, OrganizationId); - } - 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) + 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) { - using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -110,15 +109,16 @@ namespace Swarmops.Database } - public BasicOrganization GetOrganization (int organizationId) + public BasicOrganization GetOrganization(int organizationId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId=" + organizationId.ToString(), - connection); + GetDbCommand( + "SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId=" + organizationId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -127,13 +127,13 @@ namespace Swarmops.Database return ReadOrganizationFromDataReader(reader); } - throw new ArgumentException("No such OrganizationId: " + organizationId.ToString()); + throw new ArgumentException("No such OrganizationId: " + organizationId); } } } - public int[] GetOrganizationsIdsInGeographies (BasicGeography[] nodes) + public int[] GetOrganizationsIdsInGeographies(BasicGeography[] nodes) { if (nodes == null || nodes.Length == 0) { @@ -151,7 +151,7 @@ namespace Swarmops.Database } - public int[] GetOrganizationIdsInGeographies (int[] nodeIds) + public int[] GetOrganizationIdsInGeographies(int[] nodeIds) { if (nodeIds == null || nodeIds.Length == 0) { @@ -166,7 +166,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT OrganizationId FROM Organizations Where Active=1 AND AnchorGeographyId in (" + JoinIds(nodeIds) + + "SELECT OrganizationId FROM Organizations Where Active=1 AND AnchorGeographyId in (" + + JoinIds(nodeIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -194,11 +195,10 @@ namespace Swarmops.Database int[] resultArray = new int[resultKeys.Keys.Count]; resultKeys.Keys.CopyTo(resultArray, 0); return resultArray; - } - public Dictionary> GetAllOrganizationUptakeGeographyIds () + public Dictionary> GetAllOrganizationUptakeGeographyIds() { Dictionary> result = new Dictionary>(); @@ -228,11 +228,12 @@ namespace Swarmops.Database return result; } - public int[] GetOrganizationUptakeGeographyIds (int organizationId) + + public int[] GetOrganizationUptakeGeographyIds(int organizationId) { List result = new List(); - BasicOrganization basicOrg = this.GetOrganization(organizationId); + BasicOrganization basicOrg = GetOrganization(organizationId); result.Add(basicOrg.AnchorGeographyId); using (DbConnection connection = GetMySqlDbConnection()) @@ -261,7 +262,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,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT OrganizationId, GeographyId FROM OrganizationUptakeGeographies WHERE OrganizationId" + (others ? "<>" : "=") + organizationId, + "SELECT OrganizationId, GeographyId FROM OrganizationUptakeGeographies WHERE OrganizationId" + + (others ? "<>" : "=") + organizationId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -285,7 +287,7 @@ namespace Swarmops.Database return result.ToArray(); } - public void AddOrgUptakeGeography (int OrganizationId, int GeographyId) + public void AddOrgUptakeGeography(int OrganizationId, int GeographyId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -298,12 +300,10 @@ namespace Swarmops.Database 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(); @@ -315,10 +315,9 @@ namespace Swarmops.Database AddParameterWithName(command, "p_GeographyId", GeographyId); command.ExecuteNonQuery(); } - } - public BasicOrganization[] GetAllOrganizations () + public BasicOrganization[] GetAllOrganizations() { List result = new List(); @@ -326,7 +325,10 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + organizationFieldSequence + " WHERE Active=1 AND ParentOrganizationId >= 0", connection); + DbCommand command = + GetDbCommand( + "SELECT " + organizationFieldSequence + " WHERE Active=1 AND ParentOrganizationId >= 0", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -341,7 +343,7 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizations (int[] organizationIds) + public BasicOrganization[] GetOrganizations(int[] organizationIds) { if (organizationIds == null || organizationIds.Length == 0) { @@ -356,7 +358,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId IN (" + JoinIds(organizationIds) + + "SELECT " + organizationFieldSequence + " WHERE Active=1 AND OrganizationId IN (" + + JoinIds(organizationIds) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -372,7 +375,7 @@ namespace Swarmops.Database } - public Dictionary> GetHashedOrganizations () + public Dictionary> GetHashedOrganizations() { // This generates a Dictionary >. // @@ -413,7 +416,7 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizationTree (int startOrganizationId) + public BasicOrganization[] GetOrganizationTree(int startOrganizationId) { Dictionary> organizations = GetHashedOrganizations(); @@ -421,7 +424,7 @@ namespace Swarmops.Database } - public Dictionary GetOrganizationHashtable (int startOrganizationId) + public Dictionary GetOrganizationHashtable(int startOrganizationId) { BasicOrganization[] organizations = GetOrganizationTree(startOrganizationId); @@ -436,8 +439,8 @@ namespace Swarmops.Database } - private BasicOrganization[] GetOrganizationTree (Dictionary> organizations, - int startOrganizationId, int generation) + private BasicOrganization[] GetOrganizationTree(Dictionary> organizations, + int startOrganizationId, int generation) { List result = new List(); @@ -453,7 +456,7 @@ namespace Swarmops.Database // Add recursively BasicOrganization[] children = GetOrganizationTree(organizations, organization.OrganizationId, - generation + 1); + generation + 1); if (children.Length > 0) { @@ -476,7 +479,7 @@ namespace Swarmops.Database } - public BasicOrganization[] GetOrganizationLine (int leafOrganizationId) + public BasicOrganization[] GetOrganizationLine(int leafOrganizationId) { List result = new List(); diff --git a/Database/Database-OutboundCommRecipients.cs b/Database/Database-OutboundCommRecipients.cs index 0ce8e88e..e7c37bb6 100644 --- a/Database/Database-OutboundCommRecipients.cs +++ b/Database/Database-OutboundCommRecipients.cs @@ -8,15 +8,15 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string outboundCommRecipientFieldSequence = - " OutboundCommRecipientId,OutboundCommId,PersonId,Open,Success," + // 0-4 - "FailReasonId " + // 5 + " OutboundCommRecipientId,OutboundCommId,PersonId,Open,Success," + // 0-4 + "FailReasonId " + // 5 "FROM OutboundCommRecipients "; - private BasicOutboundCommRecipient ReadOutboundCommRecipientFromDataReader(IDataRecord reader) // Not static -- accesses cache, requiring connection strings + private BasicOutboundCommRecipient ReadOutboundCommRecipientFromDataReader(IDataRecord reader) + // Not static -- accesses cache, requiring connection strings { int outboundCommRecipientId = reader.GetInt32(0); int outboundCommId = reader.GetInt32(1); @@ -27,17 +27,14 @@ namespace Swarmops.Database string failReason = GetCachedFailReasonName(failReasonId); - return new BasicOutboundCommRecipient (outboundCommRecipientId, outboundCommId, personId, open, success, failReason); - - + return new BasicOutboundCommRecipient(outboundCommRecipientId, outboundCommId, personId, open, success, + failReason); } #endregion - #region Database record reading -- SELECT clauses - public BasicOutboundCommRecipient GetOutboundCommRecipient(int outboundCommRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -46,8 +43,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + outboundCommRecipientFieldSequence + - "WHERE OutboundCommRecipientId=" + outboundCommRecipientId.ToString(), - connection); + "WHERE OutboundCommRecipientId=" + outboundCommRecipientId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -56,14 +53,12 @@ namespace Swarmops.Database return ReadOutboundCommRecipientFromDataReader(reader); } - throw new ArgumentException("No such OutboundCommRecipientId:" + outboundCommRecipientId.ToString()); + throw new ArgumentException("No such OutboundCommRecipientId:" + outboundCommRecipientId); } } - } - public BasicOutboundCommRecipient[] GetOutboundCommRecipients(params object[] conditions) { List result = new List(); @@ -74,7 +69,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundCommRecipientFieldSequence + ConstructWhereClause("OutboundCommRecipients", conditions), connection); + "SELECT" + outboundCommRecipientFieldSequence + + ConstructWhereClause("OutboundCommRecipients", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -88,10 +84,8 @@ namespace Swarmops.Database } } - #endregion - #region Database optimizations private static Dictionary _failReasonCache; @@ -114,8 +108,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM FailReasons WHERE FailReasonId=" + failReasonId.ToString(), - connection); + GetDbCommand("SELECT Name FROM FailReasons WHERE FailReasonId=" + failReasonId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -125,19 +119,15 @@ namespace Swarmops.Database return _failReasonCache[failReasonId]; } - throw new ArgumentException("No such FailReasonId:" + failReasonId.ToString()); + throw new ArgumentException("No such FailReasonId:" + failReasonId); } } - } - #endregion - #region Creation and manipulation -- stored procedures - public int CreateOutboundCommRecipient(int outboundCommId, int personId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -154,7 +144,7 @@ namespace Swarmops.Database } } - public void SetOutboundCommRecipientClosed (int outboundCommRecipientId) + public void SetOutboundCommRecipientClosed(int outboundCommRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -190,7 +180,6 @@ namespace Swarmops.Database #endregion - #region Dead template code /* @@ -534,7 +523,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-OutboundComms.cs b/Database/Database-OutboundComms.cs index 42131723..00c23b39 100644 --- a/Database/Database-OutboundComms.cs +++ b/Database/Database-OutboundComms.cs @@ -9,17 +9,17 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string outboundCommFieldSequence = - " OutboundCommId,SenderPersonId,FromPersonId,OrganizationId,CreatedDateTime," + // 0-4 - "ResolverClassId,RecipientDataXml,Resolved,ResolvedDateTime,Priority," + // 5-9 - "TransmitterClassId,PayloadXml,Open,StartTransmitDateTime,ClosedDateTime," + // 10-14 - "RecipientCount,RecipientsSuccess,RecipientsFail " + // 15-17 + " OutboundCommId,SenderPersonId,FromPersonId,OrganizationId,CreatedDateTime," + // 0-4 + "ResolverClassId,RecipientDataXml,Resolved,ResolvedDateTime,Priority," + // 5-9 + "TransmitterClassId,PayloadXml,Open,StartTransmitDateTime,ClosedDateTime," + // 10-14 + "RecipientCount,RecipientsSuccess,RecipientsFail " + // 15-17 "FROM OutboundComms "; - private BasicOutboundComm ReadOutboundCommFromDataReader(IDataRecord reader) // Not static -- accesses cache, requiring connection strings + private BasicOutboundComm ReadOutboundCommFromDataReader(IDataRecord reader) + // Not static -- accesses cache, requiring connection strings { int outboundCommId = reader.GetInt32(0); int senderPersonId = reader.GetInt32(1); @@ -27,13 +27,15 @@ namespace Swarmops.Database 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 + 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 + 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); @@ -50,19 +52,15 @@ namespace Swarmops.Database return new BasicOutboundComm (outboundCommId, senderPersonId, fromPersonId, organizationId, createdDateTime, - resolverClass, recipientDataXml, resolved, resolvedDateTime, priority, - transmitterClass, payloadXml, open, startTransmitDateTime, closedDateTime, - recipientCount, recipientSuccessCount, recipientFailCount); - - + resolverClass, recipientDataXml, resolved, resolvedDateTime, priority, + transmitterClass, payloadXml, open, startTransmitDateTime, closedDateTime, + recipientCount, recipientSuccessCount, recipientFailCount); } #endregion - #region Database record reading -- SELECT clauses - public BasicOutboundComm GetOutboundComm(int outboundCommId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -71,8 +69,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + outboundCommFieldSequence + - "WHERE OutboundCommId=" + outboundCommId.ToString(), - connection); + "WHERE OutboundCommId=" + outboundCommId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -81,14 +79,12 @@ namespace Swarmops.Database return ReadOutboundCommFromDataReader(reader); } - throw new ArgumentException("No such OutboundCommId:" + outboundCommId.ToString()); + throw new ArgumentException("No such OutboundCommId:" + outboundCommId); } } - } - public BasicOutboundComm[] GetOutboundComms(params object[] conditions) { List result = new List(); @@ -99,7 +95,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundCommFieldSequence + ConstructWhereClause("OutboundComms", conditions) + " ORDER BY Priority ASC", connection); + "SELECT" + outboundCommFieldSequence + ConstructWhereClause("OutboundComms", conditions) + + " ORDER BY Priority ASC", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -113,16 +110,14 @@ namespace Swarmops.Database } } - #endregion - #region Database optimizations private static Dictionary _resolverClassCache; - private static Dictionary _transmitterClassCache; + private static Dictionary _transmitterClassCache; - protected string GetCachedResolverClassName (int resolverClassId) + protected string GetCachedResolverClassName(int resolverClassId) { if (_resolverClassCache == null) { @@ -140,8 +135,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM ResolverClasses WHERE ResolverClassId=" + resolverClassId.ToString(), - connection); + GetDbCommand("SELECT Name FROM ResolverClasses WHERE ResolverClassId=" + resolverClassId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -151,10 +146,9 @@ namespace Swarmops.Database return _resolverClassCache[resolverClassId]; } - throw new ArgumentException("No such ResolverClassId:" + resolverClassId.ToString()); + throw new ArgumentException("No such ResolverClassId:" + resolverClassId); } } - } protected string GetCachedTransmitterClassName(int transmitterClassId) @@ -174,8 +168,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT Name FROM TransmitterClasses WHERE TransmitterClassId=" + transmitterClassId.ToString(), - connection); + GetDbCommand("SELECT Name FROM TransmitterClasses WHERE TransmitterClassId=" + transmitterClassId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -185,22 +179,17 @@ namespace Swarmops.Database return _transmitterClassCache[transmitterClassId]; } - throw new ArgumentException("No such TransmitterClassId:" + transmitterClassId.ToString()); + throw new ArgumentException("No such TransmitterClassId:" + transmitterClassId); } } - } - - - #endregion - #region Creation and manipulation -- stored procedures - - public int CreateOutboundComm(int senderPersonId, int fromPersonId, int organizationId, string resolverClass, string recipientDataXml, string transmitterClass, string payloadXml, OutboundCommPriority priority) + public int CreateOutboundComm(int senderPersonId, int fromPersonId, int organizationId, string resolverClass, + string recipientDataXml, string transmitterClass, string payloadXml, OutboundCommPriority priority) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -212,11 +201,15 @@ namespace Swarmops.Database 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, "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, "priority", (int) priority); + // convert enum to integerized priority; convert back on field read AddParameterWithName(command, "createdDateTime", DateTime.UtcNow); return Convert.ToInt32(command.ExecuteScalar()); @@ -273,7 +266,6 @@ namespace Swarmops.Database #endregion - #region Dead template code /* @@ -617,7 +609,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-OutboundInvoices.cs b/Database/Database-OutboundInvoices.cs index 85af8c7c..f0f8e715 100644 --- a/Database/Database-OutboundInvoices.cs +++ b/Database/Database-OutboundInvoices.cs @@ -11,9 +11,9 @@ namespace Swarmops.Database #region Field reading code private const string outboundInvoiceFieldSequence = - " OutboundInvoiceId,CustomerName,InvoiceAddressPaper,InvoiceAddressMail,CurrencyId," + // 0-4 - "0,OrganizationId,BudgetId,CreatedDateTime,CreatedByPersonId," + // 5-9 - "DueDate,ReminderCount,Reference,Domestic,Open, " + // 10-14 + " OutboundInvoiceId,CustomerName,InvoiceAddressPaper,InvoiceAddressMail,CurrencyId," + // 0-4 + "0,OrganizationId,BudgetId,CreatedDateTime,CreatedByPersonId," + // 5-9 + "DueDate,ReminderCount,Reference,Domestic,Open, " + // 10-14 "Sent,SecurityCode,TheirReference " + "FROM OutboundInvoices "; @@ -46,11 +46,11 @@ namespace Swarmops.Database string theirReference = reader.GetString(17); return new BasicOutboundInvoice(outboundInvoiceId, customerName, invoiceAddressPaper, invoiceAddressMail, - currencyId, organizationId, budgetId, createdDateTime, - createdByPersonId, dueDate, reminderCount, reference, domestic, open, sent, securityCode, theirReference); + 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); @@ -62,8 +62,6 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements public BasicOutboundInvoice GetOutboundInvoice(int outboundInvoiceId) @@ -74,7 +72,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundInvoiceFieldSequence + "WHERE OutboundInvoiceId=" + outboundInvoiceId + ";", connection); + "SELECT" + outboundInvoiceFieldSequence + "WHERE OutboundInvoiceId=" + outboundInvoiceId + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -90,7 +89,7 @@ namespace Swarmops.Database /// - /// Gets a list of outbound invoices. + /// Gets a list of outbound invoices. /// /// Optional Organization object and/or DatabaseConditions. /// The inbound invoice list. @@ -104,7 +103,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundInvoiceFieldSequence + ConstructWhereClause("OutboundInvoices", conditions) + " ORDER BY DueDate;", connection); + "SELECT" + outboundInvoiceFieldSequence + ConstructWhereClause("OutboundInvoices", conditions) + + " ORDER BY DueDate;", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -119,8 +119,7 @@ namespace Swarmops.Database } - - public BasicOutboundInvoiceItem GetOutboundInvoiceItem (int outboundInvoiceItemId) + public BasicOutboundInvoiceItem GetOutboundInvoiceItem(int outboundInvoiceItemId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -128,7 +127,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundInvoiceItemFieldSequence + "WHERE OutboundInvoiceItemId=" + outboundInvoiceItemId + ";", connection); + "SELECT" + outboundInvoiceItemFieldSequence + "WHERE OutboundInvoiceItemId=" + + outboundInvoiceItemId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -143,10 +143,8 @@ namespace Swarmops.Database } - - /// - /// Gets a list of outbound invoice items. + /// Gets a list of outbound invoice items. /// /// OutboundInvoice object. /// The inbound invoice list. @@ -160,7 +158,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + outboundInvoiceItemFieldSequence + ConstructWhereClause("OutboundInvoiceItems", conditions) + outboundInvoiceItemSortOrder + ";", connection); + "SELECT" + outboundInvoiceItemFieldSequence + + ConstructWhereClause("OutboundInvoiceItems", conditions) + outboundInvoiceItemSortOrder + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -174,11 +174,8 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures public int CreateOutboundInvoice(int organizationId, int createdByPersonId, DateTime dueDate, @@ -284,8 +281,6 @@ namespace Swarmops.Database } - - public void SetOutboundInvoiceReference(int inboundInvoiceId, string reference) { using (DbConnection connection = GetMySqlDbConnection()) @@ -303,8 +298,6 @@ namespace Swarmops.Database } - - public void SetOutboundInvoiceBudget(int outboundInvoiceId, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -321,15 +314,10 @@ namespace Swarmops.Database } } - #endregion - - - #region Dead template code - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-OutboundMailRecipients.cs b/Database/Database-OutboundMailRecipients.cs index a5fb8ad6..6a7fba58 100644 --- a/Database/Database-OutboundMailRecipients.cs +++ b/Database/Database-OutboundMailRecipients.cs @@ -20,12 +20,12 @@ namespace Swarmops.Database bool asOfficer = reader.GetBoolean(3); int personType = reader.GetInt32(4); - return new BasicOutboundMailRecipient(outboundMailRecipientId, outboundMailId, personId, asOfficer, personType); + 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(); @@ -36,7 +36,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT " + outboundMailRecipientFieldSequence + " WHERE OutboundMailId=" + - outboundMailId.ToString() + " LIMIT " + batchSize.ToString(), connection); + outboundMailId + " LIMIT " + batchSize, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -51,8 +51,7 @@ namespace Swarmops.Database } - - public void DeleteOutboundMailRecipient (int outboundMailRecipientId) + public void DeleteOutboundMailRecipient(int outboundMailRecipientId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -67,7 +66,7 @@ namespace Swarmops.Database } } - 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()) { diff --git a/Database/Database-OutboundMails.cs b/Database/Database-OutboundMails.cs index a323c34d..6a0baf14 100644 --- a/Database/Database-OutboundMails.cs +++ b/Database/Database-OutboundMails.cs @@ -10,13 +10,13 @@ namespace Swarmops.Database public partial class SwarmDb { private const string outboundMailFieldSequence = - " OutboundMailId,AuthorType,AuthorPersonId,Title,Body," + // 0-4 + " OutboundMailId,AuthorType,AuthorPersonId,Title,Body," + // 0-4 "MailPriority,MailType,OrganizationId,GeographyId,CreatedDateTime," + // 5-9 - "ReleaseDateTime,ReadyForPickup,Resolved,Processed,ResolvedDateTime," + // 10-14 - "StartProcessDateTime,EndProcessDateTime,RecipientCount,RecipientsSuccess,RecipientsFail " + // 15-19 + "ReleaseDateTime,ReadyForPickup,Resolved,Processed,ResolvedDateTime," + // 10-14 + "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); @@ -42,22 +42,24 @@ namespace Swarmops.Database 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, + releaseDateTime, readyForPickup, resolved, processed, resolvedDateTime, startProcessDateTime, + endProcessDateTime, recipientCount, recipientsSuccess, recipientsFail); } - public BasicOutboundMail GetOutboundMail (int outboundMailId) + public BasicOutboundMail GetOutboundMail(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + outboundMailFieldSequence + " WHERE OutboundMailId=" + outboundMailId.ToString(), - connection); + GetDbCommand( + "SELECT " + outboundMailFieldSequence + " WHERE OutboundMailId=" + outboundMailId.ToString(), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -73,7 +75,7 @@ namespace Swarmops.Database } } - public BasicOutboundMail[] GetTopUnresolvedOutboundMail (int count) + public BasicOutboundMail[] GetTopUnresolvedOutboundMail(int count) { if (count == 0) { @@ -88,7 +90,9 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + outboundMailFieldSequence + " WHERE ReadyForPickup=1 AND Resolved=0 AND Processed=0 ORDER BY MailPriority, OutboundMailId DESC LIMIT " + count.ToString(), + "SELECT " + outboundMailFieldSequence + + " WHERE ReadyForPickup=1 AND Resolved=0 AND Processed=0 ORDER BY MailPriority, OutboundMailId DESC LIMIT " + + count.ToString(), connection); using (DbDataReader reader = command.ExecuteReader()) @@ -103,7 +107,7 @@ namespace Swarmops.Database } } - public BasicOutboundMail[] GetTopUnprocessedOutboundMail (int count) + public BasicOutboundMail[] GetTopUnprocessedOutboundMail(int count) { if (count == 0) { @@ -118,7 +122,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + outboundMailFieldSequence + " WHERE ReadyForPickup=1 AND Resolved=1 AND Processed=0 " + + "SELECT " + outboundMailFieldSequence + + " WHERE ReadyForPickup=1 AND Resolved=1 AND Processed=0 " + " AND ReleaseDateTime < NOW() " + " ORDER BY MailPriority, ReleaseDateTime, OutboundMailId DESC LIMIT " + count.ToString(), connection); @@ -134,7 +139,8 @@ namespace Swarmops.Database } } } - public BasicOutboundMail[] GetOutboundMailQueue (int count) + + public BasicOutboundMail[] GetOutboundMailQueue(int count) { // This may not survive the migration. SQL Syntax, etc. @@ -182,9 +188,9 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } - public int CreateOutboundMail (MailAuthorType authorType, int authorPersonId, string title, - string body, int mailPriority, int mailType, int geographyId, - int organizationId, DateTime releaseDateTime) + public int CreateOutboundMail(MailAuthorType authorType, int authorPersonId, string title, + string body, int mailPriority, int mailType, int geographyId, + int organizationId, DateTime releaseDateTime) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -193,7 +199,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC DbCommand command = GetDbCommand("CreateOutboundMail", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "authorType", (int)authorType); + AddParameterWithName(command, "authorType", (int) authorType); AddParameterWithName(command, "authorPersonId", authorPersonId); AddParameterWithName(command, "title", title); AddParameterWithName(command, "body", body); @@ -215,7 +221,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } } - public void SetOutboundMailProcessed (int outboundMailId) + public void SetOutboundMailProcessed(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -232,7 +238,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } - public void SetOutboundMailStartProcess (int outboundMailId) + public void SetOutboundMailStartProcess(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -249,7 +255,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } - public void SetOutboundMailResolved (int outboundMailId) + public void SetOutboundMailResolved(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -265,7 +271,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } } - public void SetOutboundMailReadyForPickup (int outboundMailId) + public void SetOutboundMailReadyForPickup(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -280,7 +286,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } } - public void SetOutboundMailRecipientCount (int outboundMailId, int recipientCount) + public void SetOutboundMailRecipientCount(int outboundMailId, int recipientCount) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -296,7 +302,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } } - public void IncrementOutboundMailSuccesses (int outboundMailId) + public void IncrementOutboundMailSuccesses(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -311,7 +317,7 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } } - public void IncrementOutboundMailFailures (int outboundMailId) + public void IncrementOutboundMailFailures(int outboundMailId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -327,10 +333,9 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC } - - public BasicOutboundMail[] GetDuplicateOutboundMail (MailAuthorType authorType, int authorPersonId, string title, - string body, int mailPriority, int mailType, int geographyId, - int organizationId, DateTime createDateTime, int recieverId) + public BasicOutboundMail[] GetDuplicateOutboundMail(MailAuthorType authorType, int authorPersonId, string title, + string body, int mailPriority, int mailType, int geographyId, + int organizationId, DateTime createDateTime, int recieverId) { List result = new List(); @@ -339,9 +344,10 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC connection.Open(); DbCommand command = GetDbCommand( - "SELECT " + outboundMailFieldSequence + @" INNER JOIN OutboundMailRecipients ON OutboundMailRecipients.OutboundMailId = OutboundMails.OutboundMailId + "SELECT " + outboundMailFieldSequence + + @" INNER JOIN OutboundMailRecipients ON OutboundMailRecipients.OutboundMailId = OutboundMails.OutboundMailId WHERE (OutboundMailRecipients.PersonId = " + recieverId + @") - AND (OutboundMails.AuthorType = " + (int)authorType + @") + AND (OutboundMails.AuthorType = " + (int) authorType + @") AND (OutboundMails.AuthorPersonId = " + authorPersonId + @") AND (OutboundMails.Title = '" + title + @"') AND (OutboundMails.Body = '" + body + @"') @@ -349,7 +355,8 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC AND (OutboundMails.MailType = " + mailType + @") AND (OutboundMails.OrganizationId = " + organizationId + @") AND (OutboundMails.GeographyId = " + geographyId + @") - AND (OutboundMails.CreatedDateTime > TO_DATE('" + createDateTime.ToString("yyyy-MM-dd HH:mm:ss") + @"'))", connection); + AND (OutboundMails.CreatedDateTime > TO_DATE('" + + createDateTime.ToString("yyyy-MM-dd HH:mm:ss") + @"'))", connection); command.CommandType = CommandType.Text; @@ -362,7 +369,6 @@ order by EndProcessDateTime, MailPriority, ReleaseDateTime, OutboundMailId DESC return result.ToArray(); } - } } } diff --git a/Database/Database-PaperLetters.cs b/Database/Database-PaperLetters.cs index a9cca43a..6e8c6449 100644 --- a/Database/Database-PaperLetters.cs +++ b/Database/Database-PaperLetters.cs @@ -11,7 +11,8 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreatePaperLetter(int organizationId, string fromName, string replyAddress, DateTime receivedDate, int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId) + public int CreatePaperLetter(int organizationId, string fromName, string replyAddress, DateTime receivedDate, + int toPersonId, RoleType toPersonInRole, bool personal, int uploadedByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -35,7 +36,6 @@ namespace Swarmops.Database } - public BasicPaperLetter GetPaperLetter(int paperLetterId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -44,7 +44,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT PaperLetterId,OrganizationId,FromName,ReplyAddress,ReceivedDate,ToPersonId,"+ + "SELECT PaperLetterId,OrganizationId,FromName,ReplyAddress,ReceivedDate,ToPersonId," + "ToPersonInRoleId,Personal,UploadedByPersonId,UploadedDateTime " + "From PaperLetters WHERE PaperLetterId=" + paperLetterId + ";", connection); @@ -88,7 +88,6 @@ namespace Swarmops.Database } - public BasicPaperLetter[] GetPaperLettersForPerson(int personId) { List result = new List(); @@ -116,7 +115,6 @@ namespace Swarmops.Database } - private BasicPaperLetter ReadPaperLetterFromDataReader(DbDataReader reader) { int paperLetterId = reader.GetInt32(0); @@ -135,7 +133,6 @@ namespace Swarmops.Database } - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-ParleyAttendees.cs b/Database/Database-ParleyAttendees.cs index 7c2ca039..0ff93010 100644 --- a/Database/Database-ParleyAttendees.cs +++ b/Database/Database-ParleyAttendees.cs @@ -8,12 +8,11 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string parleyAttendeeFieldSequence = " ParleyAttendeeId, ParleyId, PersonId, SignupDateTime, Active, " + // 0-4 - "CancelDateTime, Invoiced, OutboundInvoiceId, IsGuest" + // 5-8 + "CancelDateTime, Invoiced, OutboundInvoiceId, IsGuest" + // 5-8 " FROM ParleyAttendees "; private static BasicParleyAttendee ReadParleyAttendeeFromDataReader(IDataRecord reader) @@ -29,16 +28,14 @@ namespace Swarmops.Database int outboundInvoiceId = reader.GetInt32(7); bool isGuest = reader.GetBoolean(8); - return new BasicParleyAttendee (parleyAttendeeId, parleyId, personId, signupDateTime, active, cancelDateTime, invoiced, outboundInvoiceId, isGuest); + return new BasicParleyAttendee(parleyAttendeeId, parleyId, personId, signupDateTime, active, cancelDateTime, + invoiced, outboundInvoiceId, isGuest); } - #endregion - #region Database record reading -- SELECT clauses - public BasicParleyAttendee GetParleyAttendee(int parleyAttendeeId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -47,8 +44,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + parleyAttendeeFieldSequence + - "WHERE ParleyAttendeeId=" + parleyAttendeeId.ToString(), - connection); + "WHERE ParleyAttendeeId=" + parleyAttendeeId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -57,10 +54,9 @@ namespace Swarmops.Database return ReadParleyAttendeeFromDataReader(reader); } - throw new ArgumentException("No such ParleyAttendeeId:" + parleyAttendeeId.ToString()); + throw new ArgumentException("No such ParleyAttendeeId:" + parleyAttendeeId); } } - } @@ -74,7 +70,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + parleyAttendeeFieldSequence + ConstructWhereClause("ParleyAttendees", conditions), connection); + "SELECT" + parleyAttendeeFieldSequence + ConstructWhereClause("ParleyAttendees", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -99,7 +96,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT ParleyOptionId FROM ParleyAttendeeOptions WHERE ParleyAttendeeId=" + parleyAttendeeId.ToString(), connection); + "SELECT ParleyOptionId FROM ParleyAttendeeOptions WHERE ParleyAttendeeId=" + parleyAttendeeId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -113,14 +111,11 @@ namespace Swarmops.Database } } - #endregion - #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()) { @@ -149,7 +144,8 @@ namespace Swarmops.Database 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, "cancelDateTime", DateTime.Now); + // if active=false, set to cancellation time. if active=true, ignored return Convert.ToInt32(command.ExecuteScalar()); } @@ -189,7 +185,5 @@ namespace Swarmops.Database } #endregion - - } } \ No newline at end of file diff --git a/Database/Database-ParleyOptions.cs b/Database/Database-ParleyOptions.cs index 368eee3a..51a6e641 100644 --- a/Database/Database-ParleyOptions.cs +++ b/Database/Database-ParleyOptions.cs @@ -8,11 +8,10 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string parleyOptionFieldSequence = - " ParleyId, ParleyOptionId, Description, AmountCents, Active" + // 0-4 + " ParleyId, ParleyOptionId, Description, AmountCents, Active" + // 0-4 " FROM ParleyOptions "; private static BasicParleyOption ReadParleyOptionFromDataReader(IDataRecord reader) @@ -26,13 +25,10 @@ namespace Swarmops.Database return new BasicParleyOption(parleyOptionId, parleyId, description, amountCents, active); } - #endregion - #region Database record reading -- SELECT clauses - public BasicParleyOption GetParleyOption(int parleyOptionId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -41,8 +37,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + parleyOptionFieldSequence + - "WHERE ParleyOptionId=" + parleyOptionId.ToString(), - connection); + "WHERE ParleyOptionId=" + parleyOptionId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -51,10 +47,9 @@ namespace Swarmops.Database return ReadParleyOptionFromDataReader(reader); } - throw new ArgumentException("No such ParleyOptionId:" + parleyOptionId.ToString()); + throw new ArgumentException("No such ParleyOptionId:" + parleyOptionId); } } - } @@ -68,7 +63,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + parleyOptionFieldSequence + ConstructWhereClause("ParleyOptions", conditions), connection); + "SELECT" + parleyOptionFieldSequence + ConstructWhereClause("ParleyOptions", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -82,13 +78,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - public int CreateParleyOption(int parleyId, string description, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -123,7 +116,5 @@ namespace Swarmops.Database } #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Parleys.cs b/Database/Database-Parleys.cs index 02547bf3..8c410b18 100644 --- a/Database/Database-Parleys.cs +++ b/Database/Database-Parleys.cs @@ -8,17 +8,16 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading - private const string parleyFieldSequence = - " ParleyId, OrganizationId, PersonId, BudgetId, CreatedDateTime, " + // 0-4 - "Open, Attested, Name, GeographyId, Description, " + // 5-9 + private const string parleyFieldSequence = + " ParleyId, OrganizationId, PersonId, BudgetId, CreatedDateTime, " + // 0-4 + "Open, Attested, Name, GeographyId, Description, " + // 5-9 "InformationUrl, StartDate, EndDate, BudgetCents, GuaranteeCents, " + // 10-14 - "AttendanceFeeCents, ClosedDateTime" + // 15-16 + "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); @@ -48,14 +47,11 @@ namespace Swarmops.Database attendanceFeeCents, closedDateTime); } - #endregion - #region Database record reading -- SELECT clauses - - public BasicParley GetParley (int parleyId) + public BasicParley GetParley(int parleyId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -63,8 +59,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + parleyFieldSequence + - "WHERE ParleyId=" + parleyId.ToString(), - connection); + "WHERE ParleyId=" + parleyId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -73,10 +69,9 @@ namespace Swarmops.Database return ReadParleyFromDataReader(reader); } - throw new ArgumentException("No such ParleyId:" + parleyId.ToString()); + throw new ArgumentException("No such ParleyId:" + parleyId); } } - } @@ -104,14 +99,13 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - - 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) + 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) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -181,14 +175,12 @@ namespace Swarmops.Database AddParameterWithName(command, "parleyId", parleyId); AddParameterWithName(command, "open", open); - AddParameterWithName(command, "closedDateTime", DateTime.Now); // ignored if open=true + AddParameterWithName(command, "closedDateTime", DateTime.Now); // ignored if open=true return Convert.ToInt32(command.ExecuteScalar()); } } #endregion - - } } \ No newline at end of file diff --git a/Database/Database-PaymentCodes.cs b/Database/Database-PaymentCodes.cs index 7487fc05..37d7e68c 100644 --- a/Database/Database-PaymentCodes.cs +++ b/Database/Database-PaymentCodes.cs @@ -7,7 +7,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public BasicPaymentCode GetPaymentCode (string paymentCode) + public BasicPaymentCode GetPaymentCode(string paymentCode) { using (DbConnection connection = GetSqlServerDbConnection()) { @@ -31,7 +31,7 @@ namespace Swarmops.Database } - private BasicPaymentCode ReadPaymentCodeFromDataReader (DbDataReader reader) + private BasicPaymentCode ReadPaymentCodeFromDataReader(DbDataReader reader) { int issuedToPersonId = (int) reader["IssuedToPersonId"]; string issuedToPhoneNumber = (string) reader["IssuedToPhoneNumber"]; @@ -42,7 +42,7 @@ namespace Swarmops.Database 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()) { @@ -60,7 +60,7 @@ namespace Swarmops.Database } - public int ClaimPaymentCode (int paymentCodeId, int claimingPersonId) + public int ClaimPaymentCode(int paymentCodeId, int claimingPersonId) { using (DbConnection connection = GetSqlServerDbConnection()) { diff --git a/Database/Database-PaymentGroups.cs b/Database/Database-PaymentGroups.cs index 69120283..d6e8181f 100644 --- a/Database/Database-PaymentGroups.cs +++ b/Database/Database-PaymentGroups.cs @@ -8,12 +8,11 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string paymentGroupFieldSequence = - " PaymentGroupId,OrganizationId,CurrencyId,AmountCents,DateTime," + // 0-4 - "Tag,CreatedDateTime,CreatedByPersonId,Open " + // 5-9 + " PaymentGroupId,OrganizationId,CurrencyId,AmountCents,DateTime," + // 0-4 + "Tag,CreatedDateTime,CreatedByPersonId,Open " + // 5-9 "FROM PaymentGroups "; private static BasicPaymentGroup ReadPaymentGroupFromDataReader(IDataRecord reader) @@ -29,15 +28,13 @@ namespace Swarmops.Database bool open = reader.GetBoolean(8); return new BasicPaymentGroup(paymentGroupId, organizationId, dateTime, currencyId, amountCents, tag, - createdByPersonId, createdDateTime, open); + createdByPersonId, createdDateTime, open); } #endregion - #region Database record reading -- SELECT clauses - public BasicPaymentGroup GetPaymentGroupByTag(int organizationId, string tag) { using (DbConnection connection = GetMySqlDbConnection()) @@ -46,8 +43,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + paymentGroupFieldSequence + - "WHERE OrganizationId=" + organizationId.ToString() + " AND Tag='" + tag.Replace("'", "''") + "'", - connection); + "WHERE OrganizationId=" + organizationId + " AND Tag='" + tag.Replace("'", "''") + "'", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -59,7 +56,6 @@ namespace Swarmops.Database return null; } } - } @@ -71,8 +67,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + paymentGroupFieldSequence + - "WHERE PaymentGroupId=" + paymentGroupId.ToString(), - connection); + "WHERE PaymentGroupId=" + paymentGroupId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -81,14 +77,12 @@ namespace Swarmops.Database return ReadPaymentGroupFromDataReader(reader); } - throw new ArgumentException("No such PaymentGroupId:" + paymentGroupId.ToString()); + throw new ArgumentException("No such PaymentGroupId:" + paymentGroupId); } } - } - public BasicPaymentGroup[] GetPaymentGroups(params object[] conditions) { List result = new List(); @@ -99,7 +93,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + paymentGroupFieldSequence + ConstructWhereClause("PaymentGroups", conditions), connection); + "SELECT" + paymentGroupFieldSequence + ConstructWhereClause("PaymentGroups", conditions), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -113,14 +108,12 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - - public int CreatePaymentGroup(int organizationId, DateTime dateTime, int currencyId, DateTime createdDateTime, int createdByPersonId) + public int CreatePaymentGroup(int organizationId, DateTime dateTime, int currencyId, DateTime createdDateTime, + int createdByPersonId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -207,9 +200,7 @@ namespace Swarmops.Database } } - #endregion - #region Dead template code @@ -554,7 +545,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Payments.cs b/Database/Database-Payments.cs index 9dfb7819..97cba898 100644 --- a/Database/Database-Payments.cs +++ b/Database/Database-Payments.cs @@ -8,14 +8,17 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string paymentFieldSequence = - " PaymentId,PaymentGroupId,AmountCents,Reference,FromAccount," + // 0-4 - "PaymentKey,HasImage,OutboundInvoiceId " + // 5-7 + " PaymentId,PaymentGroupId,AmountCents,Reference,FromAccount," + // 0-4 + "PaymentKey,HasImage,OutboundInvoiceId " + // 5-7 "FROM Payments "; + private const string paymentInformationFieldSequence = + " PaymentInformationId,PaymentId,PaymentInformationTypes.Name,Data " + // 0-4 + " FROM PaymentInformation JOIN PaymentInformationTypes USING (PaymentInformationTypeId) "; + private static BasicPayment ReadPaymentFromDataReader(IDataRecord reader) { int paymentId = reader.GetInt32(0); @@ -27,14 +30,11 @@ namespace Swarmops.Database bool hasImage = reader.GetBoolean(6); int outboundInvoiceId = reader.GetInt32(7); - return new BasicPayment(paymentId, paymentGroupId, amountCents, reference, fromAccount, key, hasImage, outboundInvoiceId); + return new BasicPayment(paymentId, paymentGroupId, amountCents, reference, fromAccount, key, hasImage, + outboundInvoiceId); } - private const string paymentInformationFieldSequence = - " PaymentInformationId,PaymentId,PaymentInformationTypes.Name,Data " + // 0-4 - " FROM PaymentInformation JOIN PaymentInformationTypes USING (PaymentInformationTypeId) "; - - private static BasicPaymentInformation ReadPaymentInformationFromDataReader (IDataRecord reader) + private static BasicPaymentInformation ReadPaymentInformationFromDataReader(IDataRecord reader) { string dataTypeString = reader.GetString(2); string data = reader.GetString(3); @@ -45,13 +45,10 @@ namespace Swarmops.Database return new BasicPaymentInformation(dataType, data); } - #endregion - #region Database record reading -- SELECT clauses - public BasicPayment GetPayment(int paymentId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -60,8 +57,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + paymentFieldSequence + - "WHERE PaymentId=" + paymentId.ToString(), - connection); + "WHERE PaymentId=" + paymentId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -70,14 +67,12 @@ namespace Swarmops.Database return ReadPaymentFromDataReader(reader); } - throw new ArgumentException("No such PaymentId:" + paymentId.ToString()); + throw new ArgumentException("No such PaymentId:" + paymentId); } } - } - public BasicPayment[] GetPayments(params object[] conditions) { List result = new List(); @@ -113,7 +108,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + paymentInformationFieldSequence + " WHERE PaymentId=" + paymentId.ToString(), connection); + "SELECT" + paymentInformationFieldSequence + " WHERE PaymentId=" + paymentId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -127,14 +122,12 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - - public int CreatePayment(int paymentGroupId, double amount, string reference, string fromAccount, string key, bool hasImage, int outboundInvoiceId) + public int CreatePayment(int paymentGroupId, double amount, string reference, string fromAccount, string key, + bool hasImage, int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -156,7 +149,8 @@ namespace Swarmops.Database } - public int CreatePayment(int paymentGroupId, Int64 amountCents, string reference, string fromAccount, string key, bool hasImage, int outboundInvoiceId) + public int CreatePayment(int paymentGroupId, Int64 amountCents, string reference, string fromAccount, string key, + bool hasImage, int outboundInvoiceId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -195,7 +189,7 @@ namespace Swarmops.Database } } - [Obsolete ("This should never be called, ever: it ruins trackability.")] + [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 @@ -217,10 +211,8 @@ namespace Swarmops.Database } } - #endregion - #region Dead template code /* @@ -564,7 +556,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Payouts.cs b/Database/Database-Payouts.cs index 743d02c4..287a798b 100644 --- a/Database/Database-Payouts.cs +++ b/Database/Database-Payouts.cs @@ -12,15 +12,21 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading - private const string payoutFieldSequence = - " PayoutId,OrganizationId,Bank,Account,Reference," + // 0-4 - "AmountCents,ExpectedTransactionDate,Open,CreatedDateTime,CreatedByPersonId " + // 5-9 + private const string payoutFieldSequence = + " PayoutId,OrganizationId,Bank,Account,Reference," + // 0-4 + "AmountCents,ExpectedTransactionDate,Open,CreatedDateTime,CreatedByPersonId " + // 5-9 "FROM Payouts "; - private static BasicPayout ReadPayoutFromDataReader (IDataRecord reader) + private const string payoutDependencyFieldSequence = + " PayoutDependencies.PayoutId,FinancialDependencyTypes.Name,PayoutDependencies.ForeignId " + // 0-2 + "FROM PayoutDependencies,FinancialDependencyTypes "; + + private const string payoutDependencyTableJoin = + " FinancialDependencyTypes.FinancialDependencyTypeId=PayoutDependencies.FinancialDependencyTypeId "; + + private static BasicPayout ReadPayoutFromDataReader(IDataRecord reader) { int payoutId = reader.GetInt32(0); int organizationId = reader.GetInt32(1); @@ -37,30 +43,22 @@ namespace Swarmops.Database expectedTransactionDate, open, createdDateTime, createdByPersonId); } - private const string payoutDependencyFieldSequence = - " PayoutDependencies.PayoutId,FinancialDependencyTypes.Name,PayoutDependencies.ForeignId " + // 0-2 - "FROM PayoutDependencies,FinancialDependencyTypes "; - - private const string payoutDependencyTableJoin = - " FinancialDependencyTypes.FinancialDependencyTypeId=PayoutDependencies.FinancialDependencyTypeId "; - private static BasicFinancialDependency ReadPayoutDependencyFromDataReader(IDataRecord reader) { 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), foreignId); + return new BasicFinancialDependency(payoutId, + (FinancialDependencyType) Enum.Parse(typeof (FinancialDependencyType), financialDependencyTypeString), + foreignId); } - #endregion - #region Database record reading -- SELECT clauses - - public BasicPayout GetPayout (int payoutId) + public BasicPayout GetPayout(int payoutId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -68,8 +66,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + payoutFieldSequence + - "WHERE PayoutId=" + payoutId.ToString(), - connection); + "WHERE PayoutId=" + payoutId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -78,10 +76,9 @@ namespace Swarmops.Database return ReadPayoutFromDataReader(reader); } - throw new ArgumentException("No such PayoutId:" + payoutId.ToString()); + throw new ArgumentException("No such PayoutId:" + payoutId); } } - } @@ -95,8 +92,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + payoutDependencyFieldSequence + - "WHERE PayoutDependencies.PayoutId=" + payoutId.ToString() + " AND " + payoutDependencyTableJoin, - connection); + "WHERE PayoutDependencies.PayoutId=" + payoutId + " AND " + payoutDependencyTableJoin, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -124,10 +121,12 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + payoutDependencyFieldSequence + - "WHERE PayoutDependencies.ForeignId=" + foreignObjectId.ToString(CultureInfo.InvariantCulture) + - " AND FinancialDependencyTypes.Name='" + financialDependencyTypeName + "'" + // enum - no sanitation necessary - " AND " + payoutDependencyTableJoin, - connection); + "WHERE PayoutDependencies.ForeignId=" + + foreignObjectId.ToString(CultureInfo.InvariantCulture) + + " AND FinancialDependencyTypes.Name='" + financialDependencyTypeName + "'" + + // enum - no sanitation necessary + " AND " + payoutDependencyTableJoin, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -135,10 +134,7 @@ namespace Swarmops.Database { return reader.GetInt32(0); } - else - { - return 0; - } + return 0; } } } @@ -174,13 +170,10 @@ namespace Swarmops.Database } } - #endregion - #region Creation and manipulation -- stored procedures - public int CreatePayout(int organizationId, string bank, string account, string reference, double amount, DateTime expectedTransactionDate, int createdByPersonId) { @@ -314,7 +307,6 @@ namespace Swarmops.Database } - public void SetPayoutAmount(int payoutId, Int64 amountCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -348,10 +340,8 @@ namespace Swarmops.Database } } - #endregion - #region Dead template code /* @@ -695,7 +685,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Payroll.cs b/Database/Database-Payroll.cs index 89e9bb07..c1f22336 100644 --- a/Database/Database-Payroll.cs +++ b/Database/Database-Payroll.cs @@ -11,9 +11,9 @@ namespace Swarmops.Database #region Field reading code private const string payrollFieldSequence = - " PayrollItemId,PersonId,OrganizationId,CountryId,EmployedDate," + // 0-4 - "ReportsToPersonId,BaseSalaryCents,BudgetId,Open,TerminatedDate," + // 5-9 - "SubtractiveTaxLevelId,AdditiveTaxLevel " + // 10-11 + " PayrollItemId,PersonId,OrganizationId,CountryId,EmployedDate," + // 0-4 + "ReportsToPersonId,BaseSalaryCents,BudgetId,Open,TerminatedDate," + // 5-9 + "SubtractiveTaxLevelId,AdditiveTaxLevel " + // 10-11 "FROM Payroll "; private BasicPayrollItem ReadPayrollItemFromDataReader(DbDataReader reader) @@ -32,14 +32,12 @@ namespace Swarmops.Database double additiveTaxLevel = reader.GetDouble(11); return new BasicPayrollItem(payrollItemId, personId, organizationId, countryId, employedDate, - reportsToPersonId, baseSalaryCents, budgetId, open, terminatedDate, subtractiveTaxLevelId, additiveTaxLevel); - + reportsToPersonId, baseSalaryCents, budgetId, open, terminatedDate, subtractiveTaxLevelId, + additiveTaxLevel); } #endregion - - #region Record reading - SELECT statements public BasicPayrollItem GetPayrollItem(int payrollItemId) @@ -65,11 +63,14 @@ namespace Swarmops.Database } /// - /// Gets payroll. + /// Gets payroll. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// The list of matching payroll items. - public BasicPayrollItem[] GetPayroll (params object[] conditions) + public BasicPayrollItem[] GetPayroll(params object[] conditions) { List result = new List(); @@ -93,14 +94,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public int CreatePayrollItem(int personId, int organizationId, DateTime employedDate, int reportsToPersonId, int countryId, + public int CreatePayrollItem(int personId, int organizationId, DateTime employedDate, int reportsToPersonId, + int countryId, Int64 baseSalaryCents, int subtractiveTaxLevelId, double additiveTaxLevel, int budgetId) { using (DbConnection connection = GetMySqlDbConnection()) @@ -142,7 +141,6 @@ namespace Swarmops.Database } - public void SetPayrollItemTerminatedDate(int payrollItemId, DateTime dateTimeTerminated) { using (DbConnection connection = GetMySqlDbConnection()) @@ -160,7 +158,6 @@ namespace Swarmops.Database } - public void SetPayrollItemBaseSalary(int payrollItemId, Int64 baseSalaryCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -177,16 +174,10 @@ namespace Swarmops.Database } } - - #endregion - - - #region Dead template code - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-PayrollAdjustments.cs b/Database/Database-PayrollAdjustments.cs index e2064184..42823f54 100644 --- a/Database/Database-PayrollAdjustments.cs +++ b/Database/Database-PayrollAdjustments.cs @@ -11,8 +11,8 @@ namespace Swarmops.Database #region Field reading code private const string payrollAdjustmentFieldSequence = - " PayrollAdjustmentId,PayrollAdjustmentTypeId,PayrollItemId,AmountCents,Description," + // 0-4 - "Open,SalaryId " + // 5-6 + " PayrollAdjustmentId,PayrollAdjustmentTypeId,PayrollItemId,AmountCents,Description," + // 0-4 + "Open,SalaryId " + // 5-6 "FROM PayrollAdjustments "; private BasicPayrollAdjustment ReadPayrollAdjustmentFromDataReader(DbDataReader reader) @@ -26,17 +26,15 @@ namespace Swarmops.Database int salaryId = reader.GetInt32(6); return new BasicPayrollAdjustment(payrollAdjustmentId, payrollItemId, - (PayrollAdjustmentType) payrollAdjustmentTypeId, - amountCents, description, open, salaryId); + (PayrollAdjustmentType) payrollAdjustmentTypeId, + amountCents, description, open, salaryId); } #endregion - - #region Record reading - SELECT statements - public BasicPayrollAdjustment GetPayrollAdjustment (int payrollAdjustmentId) + public BasicPayrollAdjustment GetPayrollAdjustment(int payrollAdjustmentId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -44,7 +42,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + payrollAdjustmentFieldSequence + "WHERE PayrollAdjustmentId=" + payrollAdjustmentId + ";", connection); + "SELECT" + payrollAdjustmentFieldSequence + "WHERE PayrollAdjustmentId=" + payrollAdjustmentId + + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -59,9 +58,12 @@ namespace Swarmops.Database } /// - /// Gets payroll. + /// Gets payroll. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// The list of matching payroll items. public BasicPayrollAdjustment[] GetPayrollAdjustments(params object[] conditions) { @@ -73,7 +75,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + payrollAdjustmentFieldSequence + ConstructWhereClause("PayrollAdjustments", conditions), connection); + "SELECT" + payrollAdjustmentFieldSequence + + ConstructWhereClause("PayrollAdjustments", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -87,14 +90,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, double amount, string description) + public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, double amount, + string description) { if (description.Length > 128) { @@ -109,7 +110,7 @@ namespace Swarmops.Database command.CommandType = CommandType.StoredProcedure; AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "payrollAdjustmentTypeId", (int)type); + AddParameterWithName(command, "payrollAdjustmentTypeId", (int) type); AddParameterWithName(command, "amount", amount); AddParameterWithName(command, "description", description); @@ -118,7 +119,8 @@ namespace Swarmops.Database } - public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, string description) + public int CreatePayrollAdjustment(int payrollItemId, PayrollAdjustmentType type, Int64 amountCents, + string description) { if (description.Length > 128) { @@ -133,7 +135,7 @@ namespace Swarmops.Database command.CommandType = CommandType.StoredProcedure; AddParameterWithName(command, "payrollItemId", payrollItemId); - AddParameterWithName(command, "payrollAdjustmentTypeId", (int)type); + AddParameterWithName(command, "payrollAdjustmentTypeId", (int) type); AddParameterWithName(command, "amountCents", amountCents); AddParameterWithName(command, "description", description); @@ -158,16 +160,10 @@ namespace Swarmops.Database } } - - #endregion - - - #region Dead template code - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-People.cs b/Database/Database-People.cs index 6a19bc84..88a54994 100644 --- a/Database/Database-People.cs +++ b/Database/Database-People.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Diagnostics; using Swarmops.Basic.Enums; using Swarmops.Basic.Types; @@ -17,7 +18,7 @@ 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); @@ -45,16 +46,14 @@ namespace Swarmops.Database return new BasicPerson(personId, passwordHash, name, email, street, postalCode, cityName, countryId, phone, - geographyId, birthdate, (PersonGender)genderId); + geographyId, birthdate, (PersonGender) genderId); } #endregion - - #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(); @@ -64,7 +63,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + personFieldSequence + " WHERE Name like '" + GetSqlPatternFromNamePattern(namePattern).Replace("'", "''") + "'", + "SELECT " + personFieldSequence + " WHERE Name like '" + + GetSqlPatternFromNamePattern(namePattern).Replace("'", "''") + "'", connection); command.CommandTimeout = 120; @@ -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 @@ -137,7 +137,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromEmailPattern (string emailPattern) + public BasicPerson[] GetPeopleFromEmailPattern(string emailPattern) { List result = new List(); @@ -163,7 +163,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromCityPattern (string cityPattern) + public BasicPerson[] GetPeopleFromCityPattern(string cityPattern) { List result = new List(); @@ -189,7 +189,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromPostalCodePattern (string pcPattern) + public BasicPerson[] GetPeopleFromPostalCodePattern(string pcPattern) { List result = new List(); @@ -199,7 +199,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + personFieldSequence + " WHERE PostalCode like '" + pcPattern.Replace("'", "''") + "'", + "SELECT " + personFieldSequence + " WHERE PostalCode like '" + pcPattern.Replace("'", "''") + + "'", connection); command.CommandTimeout = 120; @@ -215,7 +216,7 @@ 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) @@ -244,7 +245,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromEmail (string email) + public BasicPerson[] GetPeopleFromEmail(string email) { List result = new List(); @@ -253,8 +254,9 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personFieldSequence + " WHERE Email='" + email.Replace("'", "''").Trim() + "'", - connection); + GetDbCommand( + "SELECT " + personFieldSequence + " WHERE Email='" + email.Replace("'", "''").Trim() + "'", + connection); command.CommandTimeout = 120; using (DbDataReader reader = command.ExecuteReader()) @@ -270,9 +272,7 @@ namespace Swarmops.Database } - - - public BasicPerson[] GetPeopleFromPhoneNumber (int countryId, string phoneNumber) + public BasicPerson[] GetPeopleFromPhoneNumber(int countryId, string phoneNumber) { List result = new List(); @@ -282,7 +282,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT " + personFieldSequence + " WHERE CountryId=" + countryId.ToString() + " AND PhoneNumber='" + + "SELECT " + personFieldSequence + " WHERE CountryId=" + countryId.ToString() + + " AND PhoneNumber='" + phoneNumber.Replace("'", "''") + "'", connection); command.CommandTimeout = 300; @@ -298,7 +299,7 @@ namespace Swarmops.Database return result.ToArray(); } - public BasicPerson[] GetPeopleFromPhoneNumber (string countryCode, string phoneNumber) + public BasicPerson[] GetPeopleFromPhoneNumber(string countryCode, string phoneNumber) { BasicCountry country = GetCountry(countryCode); @@ -309,7 +310,7 @@ namespace Swarmops.Database #region Retrieving specific people or lists of people - public BasicPerson[] GetPeople (int[] personIds) + public BasicPerson[] GetPeople(int[] personIds) { if (personIds == null || personIds.Length == 0) { @@ -324,7 +325,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personFieldSequence + " WHERE PersonId in (" + JoinIds(personIds) + ")", connection); + GetDbCommand("SELECT " + personFieldSequence + " WHERE PersonId in (" + JoinIds(personIds) + ")", + connection); command.CommandTimeout = 120; using (DbDataReader reader = command.ExecuteReader()) @@ -340,7 +342,7 @@ namespace Swarmops.Database } - public BasicPerson[] GetAllPeople () + public BasicPerson[] GetAllPeople() { List result = new List(); @@ -352,7 +354,7 @@ namespace Swarmops.Database command.CommandTimeout = 120; using (DbDataReader reader = command.ExecuteReader()) - { + { while (reader.Read()) { result.Add(ReadPersonFromDataReader(reader)); @@ -364,13 +366,14 @@ 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, connection); + DbCommand command = GetDbCommand("SELECT " + personFieldSequence + " WHERE PersonId=" + personId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -386,9 +389,11 @@ namespace Swarmops.Database { // A special case here for developers who don't have the registry of people, but lots and lots of links to people in financi - if (System.Diagnostics.Debugger.IsAttached) + if (Debugger.IsAttached) { - 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); + 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); } throw new ArgumentException("No such PersonId: " + personId.ToString()); } @@ -398,7 +403,7 @@ namespace Swarmops.Database #endregion - public Dictionary GetPeopleGeographies (int[] personIds) + public Dictionary GetPeopleGeographies(int[] personIds) { Dictionary result = new Dictionary(); @@ -443,8 +448,9 @@ namespace Swarmops.Database { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + ")", - connection); + GetDbCommand( + "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + ")", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -459,8 +465,7 @@ namespace Swarmops.Database } - - public BasicPerson[] GetPeopleInGeographiesWithPattern (int[] geographyIds, string pattern) + public BasicPerson[] GetPeopleInGeographiesWithPattern(int[] geographyIds, string pattern) { if (geographyIds.Length == 0) { @@ -481,8 +486,10 @@ namespace Swarmops.Database { connection.Open(); DbCommand command = - GetDbCommand("SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + ") AND (Name like '" + sqlPattern + "' OR Email like '" + sqlPattern + "')", - connection); + GetDbCommand( + "SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + + ") AND (Name like '" + sqlPattern + "' OR Email like '" + sqlPattern + "')", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -497,49 +504,48 @@ namespace Swarmops.Database } - public void SetPersonName(int personId, string name) { - this.SetPersonBasicStringValue(personId, "Name", name); + SetPersonBasicStringValue(personId, "Name", name); } - public void SetPersonPasswordHash (int personId, string passwordHash) + public void SetPersonPasswordHash(int personId, string passwordHash) { - this.SetPersonBasicStringValue(personId, "PasswordHash", passwordHash); + SetPersonBasicStringValue(personId, "PasswordHash", passwordHash); } - public void SetPersonStreet (int personId, string street) + public void SetPersonStreet(int personId, string street) { - this.SetPersonBasicStringValue(personId, "Street", street); + SetPersonBasicStringValue(personId, "Street", street); } - public void SetPersonPostalCode (int personId, string postalCode) + public void SetPersonPostalCode(int personId, string postalCode) { - this.SetPersonBasicStringValue(personId, "PostalCode", postalCode); + SetPersonBasicStringValue(personId, "PostalCode", postalCode); } - public void SetPersonCity (int personId, string city) + public void SetPersonCity(int personId, string city) { - this.SetPersonBasicStringValue(personId, "City", city); + SetPersonBasicStringValue(personId, "City", city); } - public void SetPersonPhone (int personId, string phone) + public void SetPersonPhone(int personId, string phone) { - this.SetPersonBasicStringValue(personId, "PhoneNumber", phone); + SetPersonBasicStringValue(personId, "PhoneNumber", phone); } - public void SetPersonEmail (int personId, string email) + public void SetPersonEmail(int personId, string email) { - this.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, - DateTime.MinValue, PersonGender.Unknown); + 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 storedProcedureName = "SetPerson" + key; @@ -557,8 +563,8 @@ namespace Swarmops.Database } } - public int CreatePerson (string name, string email, string phone, string street, string postalCode, string city, - int countryId, DateTime birthDate, PersonGender gender) + 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()) { @@ -576,7 +582,7 @@ namespace Swarmops.Database AddParameterWithName(command, "city", city); AddParameterWithName(command, "countryId", countryId); AddParameterWithName(command, "birthdate", birthDate); - AddParameterWithName(command, "genderId", (int)gender); + AddParameterWithName(command, "genderId", (int) gender); int personId = Convert.ToInt32(command.ExecuteScalar()); @@ -599,7 +605,7 @@ namespace Swarmops.Database } }*/ - public void SetPersonGeography (int personId, int geographyId) + public void SetPersonGeography(int personId, int geographyId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -615,7 +621,7 @@ namespace Swarmops.Database } - public void SetPersonCountry (int personId, int countryId) + public void SetPersonCountry(int personId, int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -630,7 +636,7 @@ namespace Swarmops.Database } } - public void SetPersonGender (int personId, PersonGender gender) + public void SetPersonGender(int personId, PersonGender gender) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -640,12 +646,12 @@ namespace Swarmops.Database command.CommandType = CommandType.StoredProcedure; AddParameterWithName(command, "personId", personId); - AddParameterWithName(command, "genderId", (int)gender); + 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()) { diff --git a/Database/Database-Permissions.cs b/Database/Database-Permissions.cs index 1d894df6..072ac8da 100644 --- a/Database/Database-Permissions.cs +++ b/Database/Database-Permissions.cs @@ -9,8 +9,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - - public BasicPermission[] GetPermissionsTable () + public BasicPermission[] GetPermissionsTable() { List result = new List(); @@ -18,7 +17,8 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("Select RoleType, PermissionType from PermissionSpecifications", connection); + DbCommand command = GetDbCommand("Select RoleType, PermissionType from PermissionSpecifications", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -27,10 +27,10 @@ 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)) - ) - ); + (RoleType) (Enum.Parse(typeof (RoleType), reader.GetString(0), true)), + (Permission) (Enum.Parse(typeof (Permission), reader.GetString(1), true)) + ) + ); } catch (ArgumentException) { @@ -44,25 +44,21 @@ 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); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName(command, "p_RoleType", ((RoleType)RoleTypeId).ToString()); - AddParameterWithName(command, "p_PermissionType", ((Permission)PermissionId).ToString()); + AddParameterWithName(command, "p_RoleType", ((RoleType) RoleTypeId).ToString()); + AddParameterWithName(command, "p_PermissionType", ((Permission) PermissionId).ToString()); AddParameterWithName(command, "p_allow", allow ? 1 : 0); command.ExecuteNonQuery(); } - } - } -} +} \ No newline at end of file diff --git a/Database/Database-PirateWebLog.cs b/Database/Database-PirateWebLog.cs index 2968aba0..7bbd4116 100644 --- a/Database/Database-PirateWebLog.cs +++ b/Database/Database-PirateWebLog.cs @@ -8,10 +8,10 @@ namespace Swarmops.Database { public partial class SwarmDb { - 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) + 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) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -36,15 +36,17 @@ namespace Swarmops.Database } } - 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("SELECT Max(DateTimeUtc) from PWLog WHERE AffectedItemId=" + affectedItemId + " AND AffectedItemType='" + affectedItemType + "' AND ActionType='" + actionType + "'", - connection); + GetDbCommand( + "SELECT Max(DateTimeUtc) from PWLog WHERE AffectedItemId=" + affectedItemId + + " AND AffectedItemType='" + affectedItemType + "' AND ActionType='" + actionType + "'", + connection); using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) @@ -57,10 +59,10 @@ namespace Swarmops.Database return DateTime.MinValue; } } - } - public BasicPWLog[] GetLatestEvents (string affectedItemType, DateTime beforeDate, int[] affectedIds, string[] actionTypes) + public BasicPWLog[] GetLatestEvents(string affectedItemType, DateTime beforeDate, int[] affectedIds, + string[] actionTypes) { List retlist = new List(); using (DbConnection connection = GetMySqlDbConnection()) @@ -69,13 +71,13 @@ namespace Swarmops.Database 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", - connection); + " 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()) @@ -85,7 +87,7 @@ namespace Swarmops.Database string affectedItemTyp = reader.GetString(2); int affectedItemId = reader.GetInt32(3); string actionType = reader.GetString(4); - string actionDescription = reader.IsDBNull(5) ? "" :reader.GetString(5); + 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); @@ -93,21 +95,20 @@ namespace Swarmops.Database string ipAddress = reader.IsDBNull(10) ? "" : reader.GetString(10); retlist.Add(new BasicPWLog(dateTimeUtc, - actingPersonId, - affectedItemType, - affectedItemId, - actionType, - actionDescription, - changedField, - valueBefore, - valueAfter, - comment, - ipAddress)); + actingPersonId, + affectedItemType, + affectedItemId, + actionType, + actionDescription, + changedField, + valueBefore, + valueAfter, + comment, + ipAddress)); } } } return retlist.ToArray(); } - } } \ No newline at end of file diff --git a/Database/Database-PostalCodes.cs b/Database/Database-PostalCodes.cs index 9d20c899..87be9b38 100644 --- a/Database/Database-PostalCodes.cs +++ b/Database/Database-PostalCodes.cs @@ -25,11 +25,9 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements - public BasicPostalCode[] GetPostalCodesForCountry (int countryId) + public BasicPostalCode[] GetPostalCodesForCountry(int countryId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -37,7 +35,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + postalCodeFieldSequence + "WHERE CountryId=" + countryId.ToString() + ";", connection); + "SELECT" + postalCodeFieldSequence + "WHERE CountryId=" + countryId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -53,14 +51,10 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - /* -- UNUSED public int CreateInboundInvoice(int organizationId, DateTime dueDate, int budgetId, string supplier, string payToAccount, string ocr, string invoiceReference, double amount, int createdByPersonId) @@ -218,16 +212,10 @@ namespace Swarmops.Database } }*/ - - #endregion - - - #region Dead template code - /* public int CreateFinancialAccount(int pOrganizationId, string pName, FinancialAccountType pAccountType, int pParentFinancialAccountId) { diff --git a/Database/Database-PostalCodesCities.cs b/Database/Database-PostalCodesCities.cs index 7afa20c7..517e7804 100644 --- a/Database/Database-PostalCodesCities.cs +++ b/Database/Database-PostalCodesCities.cs @@ -13,7 +13,7 @@ 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); @@ -24,7 +24,7 @@ namespace Swarmops.Database } - public BasicCity[] GetCitiesByCountryAndPostalCode (int countryId, string postalCode) + public BasicCity[] GetCitiesByCountryAndPostalCode(int countryId, string postalCode) { List cityIdList = new List(); @@ -35,7 +35,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( "SELECT CityId FROM PostalCodes WHERE PostalCode='" + postalCode.Replace("'", "''") + - "' AND CountryId=" + countryId.ToString(), connection); + "' AND CountryId=" + countryId, connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -48,11 +48,11 @@ namespace Swarmops.Database return GetCities(cityIdList.ToArray()); } - - public Dictionary GetCitiesPerPostalCode (int countryId) + + public Dictionary GetCitiesPerPostalCode(int countryId) { Dictionary postalList = new Dictionary(); - Dictionary cityIdList = new Dictionary(); + Dictionary cityIdList = new Dictionary(); using (DbConnection connection = GetMySqlDbConnection()) { @@ -60,34 +60,34 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT CityId, PostalCode FROM PostalCodes WHERE CountryId=" + countryId.ToString(), connection); + "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); + cityIdList.Keys.CopyTo(cityIds, 0); BasicCity[] cityArr = GetCities(cityIds); - Dictionary cities= new Dictionary(); - foreach(BasicCity bc in cityArr) - cities[bc.Identity]=bc; - Dictionary result=new Dictionary(); - foreach(string pcode in postalList.Keys) + Dictionary cities = new Dictionary(); + foreach (BasicCity bc in cityArr) + cities[bc.Identity] = bc; + Dictionary result = new Dictionary(); + foreach (string pcode in postalList.Keys) { - result[pcode]=cities[postalList[pcode]]; + result[pcode] = cities[postalList[pcode]]; } return result; } - public BasicCity[] GetCities (int[] cityIds) + public BasicCity[] GetCities(int[] cityIds) { if (cityIds.Length == 0) { @@ -100,8 +100,9 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityId in (" + JoinIds(cityIds) + ")", - connection); + DbCommand command = + GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityId in (" + JoinIds(cityIds) + ")", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -116,14 +117,14 @@ 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.ToString(), - connection); + DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityId=" + cityId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -132,7 +133,7 @@ namespace Swarmops.Database return ReadCityFromDataReader(reader); } - throw new ArgumentException("No such CityId: " + cityId.ToString()); + throw new ArgumentException("No such CityId: " + cityId); } } } @@ -144,8 +145,11 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + "' AND CountryId=" + countryId.ToString(), - connection); + DbCommand command = + GetDbCommand( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + + "' AND CountryId=" + countryId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -165,8 +169,11 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + "' AND CountryCode='" + countryCode.ToUpperInvariant().Replace("'", "''") + "'", - connection); + DbCommand command = + GetDbCommand( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + + "' AND CountryCode='" + countryCode.ToUpperInvariant().Replace("'", "''") + "'", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -186,8 +193,11 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + "' AND CountryId=" + countryId.ToString(), - connection); + DbCommand command = + GetDbCommand( + "SELECT " + cityFieldSequence + " WHERE CityName='" + cityName.Replace("'", "''") + + "' AND CountryId=" + countryId, + connection); List resList = new List(); using (DbDataReader reader = command.ExecuteReader()) { @@ -213,8 +223,9 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + cityFieldSequence + " WHERE CountryId=" + country.CountryId.ToString(), - connection); + DbCommand command = GetDbCommand( + "SELECT " + cityFieldSequence + " WHERE CountryId=" + country.CountryId, + connection); List result = new List(); using (DbDataReader reader = command.ExecuteReader()) { @@ -267,7 +278,5 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } - - } } \ No newline at end of file diff --git a/Database/Database-Refunds.cs b/Database/Database-Refunds.cs index 1b9024a8..1ecc2369 100644 --- a/Database/Database-Refunds.cs +++ b/Database/Database-Refunds.cs @@ -8,11 +8,10 @@ namespace Swarmops.Database { public partial class SwarmDb { - #region Database field reading private const string refundFieldSequence = - " RefundId,PaymentId,Open,AmountCents,CreatedDateTime," + // 0-4 + " RefundId,PaymentId,Open,AmountCents,CreatedDateTime," + // 0-4 "ClosedDateTime,CreatedByPersonId" + " FROM Refunds "; @@ -26,18 +25,15 @@ namespace Swarmops.Database DateTime closedDateTime = reader.GetDateTime(5); int createdByPersonId = reader.GetInt32(6); - return new BasicRefund(refundId, paymentId, open, amountCents, createdByPersonId, createdDateTime, closedDateTime); + return new BasicRefund(refundId, paymentId, open, amountCents, createdByPersonId, createdDateTime, + closedDateTime); } - - #endregion - #region Database record reading -- SELECT clauses - - public BasicRefund GetRefund (int refundId) + public BasicRefund GetRefund(int refundId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -45,8 +41,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand("SELECT" + refundFieldSequence + - "WHERE RefundId=" + refundId.ToString(), - connection); + "WHERE RefundId=" + refundId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -55,14 +51,12 @@ namespace Swarmops.Database return ReadRefundFromDataReader(reader); } - throw new ArgumentException("No such RefundId:" + refundId.ToString()); + throw new ArgumentException("No such RefundId:" + refundId); } } - } - public BasicRefund[] GetRefunds(params object[] conditions) { List result = new List(); @@ -87,16 +81,13 @@ namespace Swarmops.Database } } - #endregion - #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 } @@ -121,7 +112,7 @@ namespace Swarmops.Database } - public void SetRefundOpen (int refundId, bool open) + public void SetRefundOpen(int refundId, bool open) { DateTime now = DateTime.Now; @@ -134,16 +125,14 @@ namespace Swarmops.Database AddParameterWithName(command, "refundId", refundId); AddParameterWithName(command, "open", open); - AddParameterWithName(command, "closedDateTime", now); // always set, but only valid if open=false + AddParameterWithName(command, "closedDateTime", now); // always set, but only valid if open=false command.ExecuteNonQuery(); } } - #endregion - #region Dead template code /* @@ -487,7 +476,5 @@ namespace Swarmops.Database */ #endregion - - } } \ No newline at end of file diff --git a/Database/Database-Reporters.cs b/Database/Database-Reporters.cs index 6264985e..95ec8741 100644 --- a/Database/Database-Reporters.cs +++ b/Database/Database-Reporters.cs @@ -8,6 +8,10 @@ namespace Swarmops.Database { public partial class SwarmDb { + private const string reporterFieldSequence = + " ReporterId,Name,Email " + // 0-2 + " FROM Reporters "; + public int CreateReporter(string name, string email) { using (DbConnection connection = GetMySqlDbConnection()) @@ -57,14 +61,14 @@ namespace Swarmops.Database } } - public BasicReporter GetReporter (int reporterId) + public BasicReporter GetReporter(int reporterId) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + reporterFieldSequence + " WHERE ReporterId=" + reporterId.ToString(), - connection); + DbCommand command = GetDbCommand("SELECT " + reporterFieldSequence + " WHERE ReporterId=" + reporterId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -73,7 +77,7 @@ namespace Swarmops.Database return ReadReporterFromReader(reader); } - throw new ArgumentException("No such ReporterId: " + reporterId.ToString()); + throw new ArgumentException("No such ReporterId: " + reporterId); } } } @@ -85,7 +89,9 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + reporterFieldSequence + ConstructWhereClause("Reporters", conditions), connection); + DbCommand command = + GetDbCommand("SELECT " + reporterFieldSequence + ConstructWhereClause("Reporters", conditions), + connection); List result = new List(); using (DbDataReader reader = command.ExecuteReader()) @@ -101,7 +107,7 @@ namespace Swarmops.Database } - public BasicReporter[] GetReportersFromMediaCategories (int[] mediaCategoryIds) + public BasicReporter[] GetReportersFromMediaCategories(int[] mediaCategoryIds) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -120,13 +126,14 @@ namespace Swarmops.Database reporterIds.Add(reader.GetInt32(0)); } } - + List result = new List(); if (reporterIds.Count > 0) { command = GetDbCommand( - "SELECT " + reporterFieldSequence + " WHERE ReporterId in (" + JoinIds(reporterIds.ToArray()) + ")", + "SELECT " + reporterFieldSequence + " WHERE ReporterId in (" + + JoinIds(reporterIds.ToArray()) + ")", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -139,13 +146,12 @@ namespace Swarmops.Database return result.ToArray(); } } - else - return result.ToArray(); + return result.ToArray(); } } - public int[] GetReporterMediaCategories (int reporterId) + public int[] GetReporterMediaCategories(int reporterId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -154,7 +160,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT MediaCategoryId From ReportersMediaCategories WHERE ReporterId=" + reporterId.ToString(), + "SELECT MediaCategoryId From ReportersMediaCategories WHERE ReporterId=" + reporterId, connection); using (DbDataReader reader = command.ExecuteReader()) @@ -170,12 +176,7 @@ namespace Swarmops.Database } - private const string reporterFieldSequence = - " ReporterId,Name,Email " + // 0-2 - " FROM Reporters "; - - - private static BasicReporter ReadReporterFromReader (DbDataReader reader) + private static BasicReporter ReadReporterFromReader(DbDataReader reader) { int id = reader.GetInt32(0); string name = reader.GetString(1); diff --git a/Database/Database-Roles.cs b/Database/Database-Roles.cs index 33a53192..986871e9 100644 --- a/Database/Database-Roles.cs +++ b/Database/Database-Roles.cs @@ -14,10 +14,11 @@ namespace Swarmops.Database #region Field reading code private const string personRoleFieldSequence = - " PeopleRoles.PersonRoleId, PersonRoleTypes.Name, PeopleRoles.PersonId, PeopleRoles.OrganizationId, PeopleRoles.GeographyId " + // 0-4 + " PeopleRoles.PersonRoleId, PersonRoleTypes.Name, PeopleRoles.PersonId, PeopleRoles.OrganizationId, PeopleRoles.GeographyId " + + // 0-4 " FROM PeopleRoles JOIN PersonRoleTypes ON (PeopleRoles.PersonRoleTypeId=PersonRoleTypes.PersonRoleTypeId) "; - static private BasicPersonRole ReadPersonRoleFromDataReader (DbDataReader reader) + private static BasicPersonRole ReadPersonRoleFromDataReader(DbDataReader reader) { int personRoleId = reader.GetInt32(0); string personRoleTypeName = reader.GetString(1); @@ -32,8 +33,7 @@ namespace Swarmops.Database #endregion - - public BasicAuthority GetPersonAuthority (IHasIdentity person) + public BasicAuthority GetPersonAuthority(IHasIdentity person) { List systemRoles = new List(); List organizationRoles = new List(); @@ -43,8 +43,9 @@ namespace Swarmops.Database { connection.Open(); - DbCommand command = GetDbCommand("SELECT " + personRoleFieldSequence + ConstructWhereClause("PersonRoles", person), - connection); + DbCommand command = + GetDbCommand("SELECT " + personRoleFieldSequence + ConstructWhereClause("PersonRoles", person), + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -68,23 +69,25 @@ namespace Swarmops.Database default: throw new InvalidOperationException("Invalid RoleTypeId (" + newPersonRole.Type + - ") in database for PersonId " + person.Identity.ToString()); + ") in database for PersonId " + + person.Identity.ToString()); } } return new BasicAuthority(person.Identity, systemRoles.ToArray(), organizationRoles.ToArray(), - localRoles.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, connection); + DbCommand command = GetDbCommand("SELECT " + personRoleFieldSequence + " WHERE PersonRoleId=" + roleId, + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -100,13 +103,14 @@ namespace Swarmops.Database } } - public BasicPersonRole[] GetPeopleWithRoleType (RoleType r, int[] orgId, int[] geoId) // TODO: Refactor to use ConstructWhereClause + public BasicPersonRole[] GetPeopleWithRoleType(RoleType r, int[] orgId, int[] geoId) + // TODO: Refactor to use ConstructWhereClause { List retlist = new List(); using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - string cmd = "SELECT " + personRoleFieldSequence + " WHERE Name= '" + r.ToString()+"'"; + string cmd = "SELECT " + personRoleFieldSequence + " WHERE Name= '" + r.ToString() + "'"; if (orgId.Length > 0) cmd += " AND OrganzationId IN (" + JoinIds(orgId) + ")"; if (geoId.Length > 0) @@ -132,22 +136,23 @@ namespace Swarmops.Database } - public BasicPersonRole[] GetRolesForOrganization (int organizationId) + public BasicPersonRole[] GetRolesForOrganization(int organizationId) { 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) // TODO: Refactor to use ConstructWhereClause + public BasicPersonRole[] GetRolesForOrganizationsGeographies(int[] organizationIds, int[] geographyIds) + // TODO: Refactor to use ConstructWhereClause { List result = new List(); @@ -184,8 +189,7 @@ 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()) { @@ -203,7 +207,7 @@ namespace Swarmops.Database } } - public void DeleteRole (int roleId) + public void DeleteRole(int roleId) { using (DbConnection connection = GetMySqlDbConnection()) { diff --git a/Database/Database-Salaries.cs b/Database/Database-Salaries.cs index 8c0297d8..d5afa6a1 100644 --- a/Database/Database-Salaries.cs +++ b/Database/Database-Salaries.cs @@ -11,9 +11,9 @@ namespace Swarmops.Database #region Field reading code private const string salaryFieldSequence = - " SalaryId,PayrollItemId,PayoutDate,Salaries.BaseSalaryCents,NetSalaryCents," + // 0-4 + " SalaryId,PayrollItemId,PayoutDate,Salaries.BaseSalaryCents,NetSalaryCents," + // 0-4 "SubtractiveTaxCents,AdditiveTaxCents,Attested,NetPaid,TaxPaid," + // 5-9 - "Salaries.Open " + // 10 + "Salaries.Open " + // 10 "FROM Salaries "; private static BasicSalary ReadSalaryFromDataReader(IDataRecord reader) @@ -30,23 +30,22 @@ namespace Swarmops.Database bool taxPaid = reader.GetBoolean(9); bool open = reader.GetBoolean(10); - return new BasicSalary(salaryId, payrollItemId, payoutDate, baseSalaryCents, netSalaryCents, subtractiveTaxCents, additiveTaxCents, - attested, netPaid, taxPaid, open); + return new BasicSalary(salaryId, payrollItemId, payoutDate, baseSalaryCents, netSalaryCents, + subtractiveTaxCents, additiveTaxCents, + attested, netPaid, taxPaid, open); } #endregion - - #region Record reading - SELECT statements /// - /// Gets a salary from the database. + /// Gets a salary from the 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()) { @@ -63,15 +62,18 @@ namespace Swarmops.Database return ReadSalaryFromDataReader(reader); } - throw new ArgumentException("Unknown Salary Id: " + salaryId.ToString()); + throw new ArgumentException("Unknown Salary Id: " + salaryId); } } } /// - /// Gets salaries from the database. + /// Gets salaries from the database. /// - /// An optional combination of a Person and/or Organization object and/or DatabaseCondition specifiers. + /// + /// An optional combination of a Person and/or Organization object and/or DatabaseCondition + /// specifiers. + /// /// A list of matching salaries. public BasicSalary[] GetSalaries(params object[] conditions) { @@ -83,7 +85,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + salaryFieldSequence + "JOIN Payroll USING (PayrollItemId)" + ConstructWhereClause("Salaries", conditions), connection); + "SELECT" + salaryFieldSequence + "JOIN Payroll USING (PayrollItemId)" + + ConstructWhereClause("Salaries", conditions), connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -97,15 +100,12 @@ namespace Swarmops.Database } } - #endregion - - #region Creation and manipulation - stored procedures - - public int CreateSalary(int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents) + public int CreateSalary(int payrollItemId, DateTime payoutDate, Int64 baseSalaryCents, Int64 netSalaryCents, + Int64 subtractiveTaxCents, Int64 additiveTaxCents) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -146,7 +146,6 @@ namespace Swarmops.Database } - public void SetSalaryNetSalary(int salaryId, Int64 netSalaryCents) { using (DbConnection connection = GetMySqlDbConnection()) @@ -200,9 +199,6 @@ namespace Swarmops.Database } } - - #endregion - } } \ No newline at end of file diff --git a/Database/Database-SwarmopsLog.cs b/Database/Database-SwarmopsLog.cs index 054eadd2..55251b85 100644 --- a/Database/Database-SwarmopsLog.cs +++ b/Database/Database-SwarmopsLog.cs @@ -27,11 +27,9 @@ namespace Swarmops.Database #endregion - - #region Record reading - SELECT statements - public BasicSwarmopsLogEntry GetSwarmopsLogEntry (int swarmopsLogEntryId) + public BasicSwarmopsLogEntry GetSwarmopsLogEntry(int swarmopsLogEntryId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -39,7 +37,8 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + swarmopsLogFieldSequence + "WHERE SwarmopsLogEntryId=" + swarmopsLogEntryId + ";", connection); + "SELECT" + swarmopsLogFieldSequence + "WHERE SwarmopsLogEntryId=" + swarmopsLogEntryId + ";", + connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -48,7 +47,7 @@ namespace Swarmops.Database return ReadSwarmopsLogEntryFromDataReader(reader); } - throw new ArgumentException("Unknown SwarmopsLogEntryId: " + swarmopsLogEntryId.ToString()); + throw new ArgumentException("Unknown SwarmopsLogEntryId: " + swarmopsLogEntryId); } } } @@ -63,7 +62,9 @@ namespace Swarmops.Database DbCommand command = 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); + "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); using (DbDataReader reader = command.ExecuteReader()) { @@ -77,16 +78,10 @@ namespace Swarmops.Database } } - #endregion - - - - #region Creation and manipulation - stored procedures - public int CreateSwarmopsLogEntry(int personId, string entryType, string entryXml) { DateTime now = DateTime.UtcNow; @@ -107,7 +102,8 @@ namespace Swarmops.Database } } - public void CreateSwarmopsLogEntryAffectedObject (int swarmopsLogEntryId, string affectedObjectType, int affectedObjectId) + public void CreateSwarmopsLogEntryAffectedObject(int swarmopsLogEntryId, string affectedObjectType, + int affectedObjectId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -120,7 +116,7 @@ namespace Swarmops.Database AddParameterWithName(command, "affectedObjectType", affectedObjectType); AddParameterWithName(command, "affectedObjectId", affectedObjectId); - command.ExecuteNonQuery(); // no return value - table has no identity + command.ExecuteNonQuery(); // no return value - table has no identity } } @@ -203,8 +199,6 @@ namespace Swarmops.Database } */ - #endregion - } } \ No newline at end of file diff --git a/Database/Database-TaxLevels.cs b/Database/Database-TaxLevels.cs index ef79864b..ebbcba09 100644 --- a/Database/Database-TaxLevels.cs +++ b/Database/Database-TaxLevels.cs @@ -6,8 +6,6 @@ namespace Swarmops.Database { public partial class SwarmDb { - - #region Record reading - SELECT statements public double GetSalaryTaxLevel(int countryId, int taxLevelId, int grossSalary) @@ -22,7 +20,9 @@ namespace Swarmops.Database DbCommand command = 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); + 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); using (DbDataReader reader = command.ExecuteReader()) { @@ -51,15 +51,11 @@ namespace Swarmops.Database } } - - #endregion - - #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()) { @@ -72,15 +68,15 @@ namespace Swarmops.Database 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, "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()) { @@ -95,10 +91,6 @@ namespace Swarmops.Database } } - - #endregion - } - } \ No newline at end of file diff --git a/Database/Database-TemporaryIdentities.cs b/Database/Database-TemporaryIdentities.cs index 50179573..75e4efe8 100644 --- a/Database/Database-TemporaryIdentities.cs +++ b/Database/Database-TemporaryIdentities.cs @@ -18,6 +18,5 @@ namespace Swarmops.Database return Convert.ToInt32(command.ExecuteScalar()); } } - } } \ No newline at end of file diff --git a/Database/Database-Tests.cs b/Database/Database-Tests.cs index fe516450..ea66f9ae 100644 --- a/Database/Database-Tests.cs +++ b/Database/Database-Tests.cs @@ -37,7 +37,8 @@ namespace Swarmops.Database " `Description` VARCHAR(256) NOT NULL," + " `DateTimeCreated` DATETIME NOT NULL," + " PRIMARY KEY (`TestId`)" + - ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table is created to test database credentials'", connection); + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table is created to test database credentials'", + connection); command.ExecuteNonQuery(); return true; @@ -59,7 +60,8 @@ namespace Swarmops.Database connection.Open(); DbCommand command = GetDbCommand( - "ALTER TABLE `CredentialsTests` ADD COLUMN `AppendedColumn` INT AFTER `DateTimeCreated`", connection); + "ALTER TABLE `CredentialsTests` ADD COLUMN `AppendedColumn` INT AFTER `DateTimeCreated`", + connection); command.ExecuteNonQuery(); return true; @@ -191,8 +193,6 @@ namespace Swarmops.Database Debug.WriteLine(debug.ToString()); return false; } - } - } } \ No newline at end of file diff --git a/Database/Database-UrlTranslations.cs b/Database/Database-UrlTranslations.cs index e63c754e..58e0e16f 100644 --- a/Database/Database-UrlTranslations.cs +++ b/Database/Database-UrlTranslations.cs @@ -7,7 +7,7 @@ namespace Swarmops.Database { public partial class SwarmDb { - public int CreateUrlTranslation (string url) + public int CreateUrlTranslation(string url) { using (DbConnection connection = GetSqlServerDbConnection()) { @@ -25,7 +25,7 @@ namespace Swarmops.Database } - public void SetUrlTranslation (string originalUrl, string translatedUrl) + public void SetUrlTranslation(string originalUrl, string translatedUrl) { using (DbConnection connection = GetSqlServerDbConnection()) { @@ -42,7 +42,7 @@ namespace Swarmops.Database } - public string[] GetUntranslatedUrls (int max) + public string[] GetUntranslatedUrls(int max) { List result = new List(); @@ -52,7 +52,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT TOP " + max.ToString() + " OriginalUrl FROM UrlTranslations WHERE Translated=0", + "SELECT TOP " + max + " OriginalUrl FROM UrlTranslations WHERE Translated=0", connection); using (DbDataReader reader = command.ExecuteReader()) @@ -68,7 +68,7 @@ namespace Swarmops.Database } - public string GetUrlTranslation (string url) + public string GetUrlTranslation(string url) { using (DbConnection connection = GetSqlServerDbConnection()) { diff --git a/Database/Database-Volunteers.cs b/Database/Database-Volunteers.cs index d44b4b81..70521a5a 100644 --- a/Database/Database-Volunteers.cs +++ b/Database/Database-Volunteers.cs @@ -13,7 +13,7 @@ namespace Swarmops.Database { List result = new List(); - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -34,16 +34,16 @@ namespace Swarmops.Database } } - public BasicVolunteer GetVolunteer (int volunteerId) + public BasicVolunteer GetVolunteer(int volunteerId) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = GetDbCommand( "SELECT VolunteerId,PersonId,OwnerPersonId,OpenedDateTime,Open,ClosedDateTime,ClosingComments FROM Volunteers WHERE VolunteerId=" + - volunteerId.ToString() + ";", connection); + volunteerId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -57,16 +57,16 @@ namespace Swarmops.Database } } - public BasicVolunteerRole GetVolunteerRole (int volunteerRoleId) + public BasicVolunteerRole GetVolunteerRole(int volunteerRoleId) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = GetDbCommand( "SELECT VolunteerRoleId,VolunteerId,OrganizationId,GeographyId,RoleTypeId,Open,Assigned FROM VolunteerRoles WHERE VolunteerRoleId=" + - volunteerRoleId.ToString() + ";", connection); + volunteerRoleId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -81,18 +81,18 @@ namespace Swarmops.Database } - public BasicVolunteerRole[] GetVolunteerRolesByVolunteer (int volunteerId) + public BasicVolunteerRole[] GetVolunteerRolesByVolunteer(int volunteerId) { List result = new List(); - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); DbCommand command = GetDbCommand( "SELECT VolunteerRoleId,VolunteerId,OrganizationId,GeographyId,RoleTypeId,Open,Assigned FROM VolunteerRoles WHERE VolunteerId=" + - volunteerId.ToString() + ";", connection); + volunteerId + ";", connection); using (DbDataReader reader = command.ExecuteReader()) { @@ -107,7 +107,7 @@ namespace Swarmops.Database } - private BasicVolunteer ReadVolunteerFromDataReader (DbDataReader reader) + private BasicVolunteer ReadVolunteerFromDataReader(DbDataReader reader) { int volunteerId = reader.GetInt32(0); int personId = reader.GetInt32(1); @@ -118,11 +118,11 @@ namespace Swarmops.Database string closingComments = reader.GetString(6); return new BasicVolunteer(volunteerId, personId, ownerPersonId, openedDateTime, open, closedDateTime, - closingComments); + closingComments); } - private BasicVolunteerRole ReadVolunteerRoleFromDataReader (DbDataReader reader) + private BasicVolunteerRole ReadVolunteerRoleFromDataReader(DbDataReader reader) { int volunteerRoleId = reader.GetInt32(0); int volunteerId = reader.GetInt32(1); @@ -133,13 +133,13 @@ namespace Swarmops.Database bool assigned = reader.GetBoolean(6); return new BasicVolunteerRole(volunteerRoleId, volunteerId, organizationId, geographyId, - (RoleType) roleTypeId, open, assigned); + (RoleType) roleTypeId, open, assigned); } - public int CreateVolunteer (int personId, int ownerPersonId) + public int CreateVolunteer(int personId, int ownerPersonId) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -154,9 +154,9 @@ namespace Swarmops.Database } } - 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 = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -172,9 +172,9 @@ namespace Swarmops.Database } } - public void SetVolunteerOwnerPersonId (int volunteerId, int ownerPersonId) + public void SetVolunteerOwnerPersonId(int volunteerId, int ownerPersonId) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -188,9 +188,9 @@ namespace Swarmops.Database } } - public void CloseVolunteer (int volunteerId, string closingComments) + public void CloseVolunteer(int volunteerId, string closingComments) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); @@ -205,9 +205,9 @@ namespace Swarmops.Database } } - public void CloseVolunteerRole (int volunteerRoleId, bool wasAssigned) + public void CloseVolunteerRole(int volunteerRoleId, bool wasAssigned) { - using (DbConnection connection = this.GetMySqlDbConnection()) + using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); diff --git a/Database/Properties/AssemblyInfo.cs b/Database/Properties/AssemblyInfo.cs index aeb08f3d..37f2ab4b 100644 --- a/Database/Properties/AssemblyInfo.cs +++ b/Database/Properties/AssemblyInfo.cs @@ -5,6 +5,7 @@ using System.Reflection; // set of attributes. Change these attribute values to modify the information // associated with an assembly. // + [assembly: AssemblyTitle("PirateWeb Database Assembly")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -12,7 +13,7 @@ using System.Reflection; [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: @@ -52,6 +53,7 @@ using System.Reflection; // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // + [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] +[assembly: AssemblyKeyName("")] \ No newline at end of file diff --git a/Interface/Collections/ExpensePayouts.cs b/Interface/Collections/ExpensePayouts.cs index 37e37d5b..7259245f 100644 --- a/Interface/Collections/ExpensePayouts.cs +++ b/Interface/Collections/ExpensePayouts.cs @@ -6,55 +6,54 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Interface.Collections { - class ExpensePayouts: List - { - private ExpensePayouts() // prevent public construction - { - } + internal class ExpensePayouts : List + { + private ExpensePayouts() // prevent public construction + { + } - public static ExpensePayouts FromOrganization(Organization org) - { - return FromOrganization(org.Identity); - } + public static ExpensePayouts FromOrganization(Organization org) + { + return FromOrganization(org.Identity); + } - public static ExpensePayouts FromOrganization(int organizationId) - { - // This aggregates a list of all pending expense payouts per person, - // and returns an ExpensePayouts object. + public static ExpensePayouts FromOrganization(int organizationId) + { + // This aggregates a list of all pending expense payouts per person, + // and returns an ExpensePayouts object. - // It uses a Dictionary> to build the data, iterating over - // all expenses, where the int key is the person identity. + // It uses a Dictionary> to build the data, iterating over + // all expenses, where the int key is the person identity. - ExpenseClaims allExpenseClaims = ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)); - Dictionary aggregation = new Dictionary(); - ExpensePayouts result = new ExpensePayouts(); + ExpenseClaims allExpenseClaims = ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)); + Dictionary aggregation = new Dictionary(); + ExpensePayouts result = new ExpensePayouts(); - // Aggregate per person + // Aggregate per person - foreach (ExpenseClaim expense in allExpenseClaims) - { - if (expense.Approved && expense.Open) - { - // Ready for payout + foreach (ExpenseClaim expense in allExpenseClaims) + { + if (expense.Approved && expense.Open) + { + // Ready for payout - if (!aggregation.ContainsKey(expense.ClaimingPersonId)) - { - aggregation[expense.ClaimingPersonId] = new ExpenseClaims(); - } + if (!aggregation.ContainsKey(expense.ClaimingPersonId)) + { + aggregation[expense.ClaimingPersonId] = new ExpenseClaims(); + } - aggregation[expense.ClaimingPersonId].Add(expense); - } - } + aggregation[expense.ClaimingPersonId].Add(expense); + } + } - // Create ExpensePayout objects + // Create ExpensePayout objects - foreach (int personId in aggregation.Keys) - { - result.Add(new ExpensePayout(Person.FromIdentity(personId), aggregation[personId])); - } + foreach (int personId in aggregation.Keys) + { + result.Add(new ExpensePayout(Person.FromIdentity(personId), aggregation[personId])); + } - return result; - } - - } -} + return result; + } + } +} \ No newline at end of file diff --git a/Interface/DataObjects/ExpensePayoutsDataObject.cs b/Interface/DataObjects/ExpensePayoutsDataObject.cs index 3b0fd138..a785c93d 100644 --- a/Interface/DataObjects/ExpensePayoutsDataObject.cs +++ b/Interface/DataObjects/ExpensePayoutsDataObject.cs @@ -5,16 +5,16 @@ using Swarmops.Interface.Objects; namespace Swarmops.Interface.DataObjects { #if !__MonoCS__ - [DataObject(true)] + [DataObject(true)] #endif - public class ExpensePayoutsDataObject - { + public class ExpensePayoutsDataObject + { #if !__MonoCS__ - [DataObjectMethod(DataObjectMethodType.Select)] + [DataObjectMethod(DataObjectMethodType.Select)] #endif - static public ExpensePayout[] SelectByOrganization(int organizationId) - { - return ExpensePayouts.FromOrganization(organizationId).ToArray(); - } - } -} + public static ExpensePayout[] SelectByOrganization(int organizationId) + { + return ExpensePayouts.FromOrganization(organizationId).ToArray(); + } + } +} \ No newline at end of file diff --git a/Interface/DataObjects/ListPersonDataSource.cs b/Interface/DataObjects/ListPersonDataSource.cs index d5938801..1f4ad39c 100644 --- a/Interface/DataObjects/ListPersonDataSource.cs +++ b/Interface/DataObjects/ListPersonDataSource.cs @@ -6,80 +6,68 @@ using Swarmops.Basic.Types; using Swarmops.Logic.Swarm; /// -/// Summary description for ListPersonDataSource +/// Summary description for ListPersonDataSource /// public class ListPerson : Person { //additional fields for the list - private DateTime joinedDate; - public DateTime JoinedDate - { - get { return joinedDate; } - set { joinedDate = value; } - } - private DateTime expiresDate; - public DateTime ExpiresDate - { - get { return expiresDate; } - set { expiresDate = value; } - } + private DateTime joinedDate; - private MembershipPaymentStatus paymentStatus; - public MembershipPaymentStatus PaymentStatus - { - get { return paymentStatus; } - set { paymentStatus = value; } - } - - int membershipId; - - public int MembershipId - { - get { return membershipId; } - set { membershipId = value; } - } - - public ListPerson (BasicPerson b) + public ListPerson(BasicPerson b) : base(b) { } - public ListPerson (Person p) + public ListPerson(Person p) : base(p) { } - public ListPerson () + public ListPerson() : base(null) { } + public DateTime JoinedDate + { + get { return this.joinedDate; } + set { this.joinedDate = value; } + } + public DateTime ExpiresDate + { + get { return this.expiresDate; } + set { this.expiresDate = value; } + } + + public MembershipPaymentStatus PaymentStatus { get; set; } + + public int MembershipId { get; set; } } public class ListPersonDataSource { - int[] listedPersons; + private readonly int[] listedPersons; public int selectedOrgId = 1; - public ListPersonDataSource () + public ListPersonDataSource() { } - public ListPersonDataSource (int[] listedPersons) + public ListPersonDataSource(int[] listedPersons) { this.listedPersons = listedPersons; } - public List GetData (string sortBy) + public List GetData(string sortBy) { - List retval = new List(); - if (listedPersons != null) + if (this.listedPersons != null) { - People ppl = People.FromIdentities(listedPersons); - Dictionary> membershipTable = Memberships.GetMembershipsForPeople(listedPersons, Membership.GracePeriod); + People ppl = People.FromIdentities(this.listedPersons); + Dictionary> membershipTable = + Memberships.GetMembershipsForPeople(this.listedPersons, Membership.GracePeriod); Memberships membershipsToLoad = new Memberships(); foreach (Person p in ppl) { @@ -87,7 +75,7 @@ public class ListPersonDataSource { foreach (BasicMembership bm in membershipTable[p.Identity]) { - if (bm.OrganizationId == selectedOrgId) + if (bm.OrganizationId == this.selectedOrgId) { Membership ms = Membership.FromBasic(bm); membershipsToLoad.Add(ms); @@ -110,7 +98,7 @@ public class ListPersonDataSource { foreach (BasicMembership bm in membershipTable[p.Identity]) { - if (bm.OrganizationId == selectedOrgId) + if (bm.OrganizationId == this.selectedOrgId) { Membership ms = memberships[bm.MembershipId]; lp.JoinedDate = ms.MemberSince; @@ -123,19 +111,19 @@ public class ListPersonDataSource } } - PropertyInfo pi = typeof(ListPerson).GetProperty(sortBy); + PropertyInfo pi = typeof (ListPerson).GetProperty(sortBy); if (pi != null) { - - MemberInfo [] miA = pi.PropertyType.GetMember("CompareTo", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + MemberInfo[] miA = pi.PropertyType.GetMember("CompareTo", MemberTypes.Method, + BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (miA.Length > 0) { - - MethodInfo mi =(MethodInfo) miA[0]; - retval.Sort(delegate(ListPerson p1, ListPerson p2) - { - return Convert.ToInt32(mi.Invoke(pi.GetValue(p1, null), new object[] { pi.GetValue(p2, null) })); - }); + MethodInfo mi = (MethodInfo) miA[0]; + retval.Sort( + delegate(ListPerson p1, ListPerson p2) + { + return Convert.ToInt32(mi.Invoke(pi.GetValue(p1, null), new[] {pi.GetValue(p2, null)})); + }); } } return retval; diff --git a/Interface/DataObjects/OrganizationRolesDataObject.cs b/Interface/DataObjects/OrganizationRolesDataObject.cs index 87d39007..b354544c 100644 --- a/Interface/DataObjects/OrganizationRolesDataObject.cs +++ b/Interface/DataObjects/OrganizationRolesDataObject.cs @@ -11,117 +11,53 @@ namespace Swarmops.Interface.DataObjects #if !__MonoCS__ [DataObject(true)] #endif - public class OrganizationRolesDataObject { public class Role : BasicPersonRole { - private string organisationName; - private string geographyName; - private string personName; - private string roleName; - private int level; - private int geoLevel; - - public Role () - : base() + public Role() { } - public Role (BasicPersonRole org) + public Role(BasicPersonRole org) : base(org) { - organisationName = Organization.FromIdentity(this.OrganizationId).Name; - personName = Person.FromIdentity(this.PersonId).Name; - roleName = Enum.GetName(this.Type.GetType(), this.Type); - geographyName = ""; - if (RoleTypes.ClassOfRole(this.Type) == RoleClass.Local) + this.OrganisationName = Organization.FromIdentity(OrganizationId).Name; + this.PersonName = Person.FromIdentity(PersonId).Name; + this.RoleName = Enum.GetName(Type.GetType(), Type); + this.GeographyName = ""; + if (RoleTypes.ClassOfRole(Type) == RoleClass.Local) { if (GeographyId > 0) { - geographyName = Geography.FromIdentity(GeographyId).Name; + this.GeographyName = Geography.FromIdentity(GeographyId).Name; } } } - public string GeographyName - { - get - { - return geographyName; - } - set - { - geographyName = value; - } - } - public int GeoLevel - { - get - { - return geoLevel; - } - set - { - geoLevel = value; - } - } - public int Level - { - get - { - return level; - } - set - { - level = value; - } - } - public string OrganisationName - { - get - { - return organisationName; - } - set - { - organisationName = value; - } - } - public string PersonName - { - get - { - return personName; - } - set - { - personName = value; - } - } - public string RoleName - { - get - { - return roleName; - } - set - { - roleName = value; - } - } + public string GeographyName { get; set; } + public int GeoLevel { get; set; } + + public int Level { get; set; } + + public string OrganisationName { get; set; } + + public string PersonName { get; set; } + + public string RoleName { get; set; } } - static private object dataLock = new object(); - static private Dictionary hierarchicalSortOrder = new Dictionary(); + private static readonly object dataLock = new object(); + private static Dictionary hierarchicalSortOrder = + new Dictionary(); #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - static public OrganizationRolesDataObject.Role[] SelectAllByOrganization (int organizationId) + public static Role[] SelectAllByOrganization(int organizationId) { try { @@ -143,11 +79,12 @@ namespace Swarmops.Interface.DataObjects } catch { - return new OrganizationRolesDataObject.Role[0]; + return new Role[0]; } } - static private void RecursiveAddInTreeOrder (List resultList, Dictionary> roleDictionary, int currentOrg, int level) + private static void RecursiveAddInTreeOrder(List resultList, Dictionary> roleDictionary, + int currentOrg, int level) { if (roleDictionary.ContainsKey(currentOrg)) { @@ -157,19 +94,24 @@ namespace Swarmops.Interface.DataObjects int res = 0; try { - res = ((int)RoleTypes.ClassOfRole(r1.Type)).CompareTo((int)RoleTypes.ClassOfRole(r2.Type)); + res = ((int) RoleTypes.ClassOfRole(r1.Type)).CompareTo((int) RoleTypes.ClassOfRole(r2.Type)); + } + catch + { } - catch { } try { if (res == 0) - res = hierarchicalSortOrder[r1.GeographyId].Order.CompareTo(hierarchicalSortOrder[r2.GeographyId].Order); + res = + hierarchicalSortOrder[r1.GeographyId].Order.CompareTo( + hierarchicalSortOrder[r2.GeographyId].Order); + } + catch + { } - catch { } if (res == 0) res = r1.Type.CompareTo(r2.Type); return res; - }); foreach (Role role in roleDictionary[currentOrg]) { @@ -186,7 +128,7 @@ namespace Swarmops.Interface.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - static public OrganizationRolesDataObject.Role[] SelectSubByOrganization (int organizationId) + public static Role[] SelectSubByOrganization(int organizationId) { try { @@ -211,14 +153,14 @@ namespace Swarmops.Interface.DataObjects } catch { - return new OrganizationRolesDataObject.Role[0]; + return new Role[0]; } } #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - static public OrganizationRolesDataObject.Role[] SelectThisByOrganization (int organizationId) + public static Role[] SelectThisByOrganization(int organizationId) { try { @@ -243,8 +185,8 @@ namespace Swarmops.Interface.DataObjects } catch { - return new OrganizationRolesDataObject.Role[0]; + return new Role[0]; } } } -} +} \ No newline at end of file diff --git a/Interface/Localization/LocalizationManager.cs b/Interface/Localization/LocalizationManager.cs index faedca90..1b9728b0 100644 --- a/Interface/Localization/LocalizationManager.cs +++ b/Interface/Localization/LocalizationManager.cs @@ -1,70 +1,74 @@ +using System.Threading; + namespace Swarmops.Interface.Localization { public class LocalizationManager { - public LocalizationManager() + public static string GetLocalString(string stringName, string defaultValue) { + // Determine current culture + + return GetLocalString(Thread.CurrentThread.CurrentCulture.Name, stringName, defaultValue); } - static public string GetLocalString (string stringName, string defaultValue) - { - // Determine current culture - - return GetLocalString(System.Threading.Thread.CurrentThread.CurrentCulture.Name, stringName, defaultValue); - } - - static public string GetLocalString (string locale, string stringName, string defaultValue) + public static string GetLocalString(string locale, string stringName, string defaultValue) { - locale = locale.Substring (0, 2).ToLower(); + locale = locale.Substring(0, 2).ToLower(); - switch (stringName) - { - case "Interface.Security.Login.WelcomeHeader": - switch (locale) - { - case "sv": - return "Välkommen till PirateWeb!"; - case "es": - return "Bienvenido en PirateWeb!"; - case "fr": - return "Bienvenue à PirateWeb!"; - case "de": - return "Willkommen zu PirateWeb!"; - case "ru": - return "????? ?????????? ?? PirateWeb!"; - case "ja": - return "PirateWeb????!"; - } - break; + switch (stringName) + { + case "Interface.Security.Login.WelcomeHeader": + switch (locale) + { + case "sv": + return "Välkommen till PirateWeb!"; + case "es": + return "Bienvenido en PirateWeb!"; + case "fr": + return "Bienvenue à PirateWeb!"; + case "de": + return "Willkommen zu PirateWeb!"; + case "ru": + return "????? ?????????? ?? PirateWeb!"; + case "ja": + return "PirateWeb????!"; + } + break; - case "Interface.Security.Login.WelcomeParagraph": - switch (locale) - { - case "sv": - return "PirateWeb är ett system för att hantera medlemmar för piratpartierna runt om i världen. För att logga in, så skriv ditt namn, medlemsnummer eller e-mail, tillsammans med ditt lösenord."; - case "es": - return "PirateWeb es un sistema de gerencia del miembro para los Partidos Piratos alrededor del mundo. A la conexión, escribir por favor su nombre, número del miembro, o dirección d'email, junto con su contraseña."; - case "fr": - return "PirateWeb est un système de gestion de membre pour les Partis Pirates autour du monde. À l'ouverture, écrire svp votre nom, nombre de membre, ou adresse d'email, avec votre mot de passe."; - case "de": - return "PirateWeb ist ein internationales Mitgliedermanagementsystem für Piraten. Zum Login geben Sie bitte ihren Namen, Mitgliedsnummer oder e-mail Adresse, zusammen mit ihrem Kennwort ein."; - case "ru": - return "PirateWeb ???????? ?????? ??????? ??????????? ????????? ?????? ?? ???? ????. ????? ??????????, ??????????, ??????? ???? ???, ?????????? ??????, ??? ????? ??????????? ?????, ? ????? ??????."; - case "ja": - return "PirateWeb??????????????????????????? ????????????????????????????????????????E???????????????"; - } - break; + case "Interface.Security.Login.WelcomeParagraph": + switch (locale) + { + case "sv": + return + "PirateWeb är ett system för att hantera medlemmar för piratpartierna runt om i världen. För att logga in, så skriv ditt namn, medlemsnummer eller e-mail, tillsammans med ditt lösenord."; + case "es": + return + "PirateWeb es un sistema de gerencia del miembro para los Partidos Piratos alrededor del mundo. A la conexión, escribir por favor su nombre, número del miembro, o dirección d'email, junto con su contraseña."; + case "fr": + return + "PirateWeb est un système de gestion de membre pour les Partis Pirates autour du monde. À l'ouverture, écrire svp votre nom, nombre de membre, ou adresse d'email, avec votre mot de passe."; + case "de": + return + "PirateWeb ist ein internationales Mitgliedermanagementsystem für Piraten. Zum Login geben Sie bitte ihren Namen, Mitgliedsnummer oder e-mail Adresse, zusammen mit ihrem Kennwort ein."; + case "ru": + return + "PirateWeb ???????? ?????? ??????? ??????????? ????????? ?????? ?? ???? ????. ????? ??????????, ??????????, ??????? ???? ???, ?????????? ??????, ??? ????? ??????????? ?????, ? ????? ??????."; + case "ja": + return + "PirateWeb??????????????????????????? ????????????????????????????????????????E???????????????"; + } + break; case "Interface.Security.Login.NewPasswordLink": - switch (locale) - { - case "sv": - return "Jag har glömt mitt lösenord..."; - } - break; - } + switch (locale) + { + case "sv": + return "Jag har glömt mitt lösenord..."; + } + break; + } return defaultValue; } } -} +} \ No newline at end of file diff --git a/Interface/Objects/ExpensePayout.cs b/Interface/Objects/ExpensePayout.cs index 3d5e0e34..1924e68d 100644 --- a/Interface/Objects/ExpensePayout.cs +++ b/Interface/Objects/ExpensePayout.cs @@ -7,174 +7,168 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Interface.Objects { - public class ExpensePayout: IHasIdentity - { - internal ExpensePayout(Person person, ExpenseClaims expenseClaims) - { - this.person = person; - this.expenseClaims = expenseClaims; + public class ExpensePayout : IHasIdentity + { + private readonly decimal amount; + private readonly ExpenseClaims expenseClaims; + private readonly Person person; - decimal total = 0.0m; + internal ExpensePayout(Person person, ExpenseClaims expenseClaims) + { + this.person = person; + this.expenseClaims = expenseClaims; - foreach (ExpenseClaim expense in expenseClaims) - { - total += expense.Amount; - } + decimal total = 0.0m; - this.amount = total; - } + foreach (ExpenseClaim expense in expenseClaims) + { + total += expense.Amount; + } - private readonly Person person; + this.amount = total; + } - public Person Person - { - get { return person; } - } + public Person Person + { + get { return this.person; } + } - private readonly decimal amount; + public decimal Amount + { + get { return this.amount; } + } - public decimal Amount - { - get { return amount; } - } - - private readonly ExpenseClaims expenseClaims; - - public ExpenseClaims ExpenseClaims - { - get { return expenseClaims; } - } - - public static ExpensePayout FromOrganizationAndPerson (int organizationId, int personId) - { - ExpenseClaims allExpenseClaims = ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)); - ExpenseClaims expenseClaims = new ExpenseClaims(); - - // Aggregate per person - - foreach (ExpenseClaim expense in allExpenseClaims) - { - if (expense.ClaimingPersonId == personId) - { - if (expense.Approved && expense.Open) - { - // Ready for payout - - expenseClaims.Add(expense); - } - } - } - - // Create ExpensePayout object - - return new ExpensePayout(Person.FromIdentity(personId), expenseClaims); - } + public ExpenseClaims ExpenseClaims + { + get { return this.expenseClaims; } + } - public string ReceiptIdentitiesString // this could be calculated on construction - { - get - { - List identities = new List(); + public string ReceiptIdentitiesString // this could be calculated on construction + { + get + { + List identities = new List(); - foreach (ExpenseClaim expense in expenseClaims) - { - identities.Add(expense.Identity.ToString()); - } + foreach (ExpenseClaim expense in this.expenseClaims) + { + identities.Add(expense.Identity.ToString()); + } - return String.Join(",", identities.ToArray()); - } - } + return String.Join(",", identities.ToArray()); + } + } - public string ReceiptList // this could be calculated on construction - { - get - { - List spans = new List(); - List expenseIdList = new List(); + public string ReceiptList // this could be calculated on construction + { + get + { + List spans = new List(); + List expenseIdList = new List(); - foreach (ExpenseClaim expense in expenseClaims) - { - expenseIdList.Add(expense.Identity); - } + foreach (ExpenseClaim expense in this.expenseClaims) + { + expenseIdList.Add(expense.Identity); + } - int[] expenseIds = expenseIdList.ToArray(); - Array.Sort(expenseIds); + int[] expenseIds = expenseIdList.ToArray(); + Array.Sort(expenseIds); - // iterate over the sorted array: group spans of ids together + // iterate over the sorted array: group spans of ids together - int spanStart = expenseIds[0]; - int spanLength = 0; - int currentIndex = 1; + int spanStart = expenseIds[0]; + int spanLength = 0; + int currentIndex = 1; - while (currentIndex < expenseIds.Length) - { - if (spanStart + spanLength + 1 == expenseIds[currentIndex]) - { - // the span continues + while (currentIndex < expenseIds.Length) + { + if (spanStart + spanLength + 1 == expenseIds[currentIndex]) + { + // the span continues - spanLength++; - currentIndex++; - } - else - { - // the span does NOT continue: add + spanLength++; + currentIndex++; + } + else + { + // the span does NOT continue: add - if (spanLength == 0) - { - spans.Add(spanStart.ToString()); - } - else if (spanLength == 1) // really means 2, is zero based - { - spans.Add(spanStart.ToString()); - spans.Add((spanStart + 1).ToString()); - } - else - { - spans.Add (String.Format ("{0}-{1}", spanStart, spanStart + spanLength)); - } + if (spanLength == 0) + { + spans.Add(spanStart.ToString()); + } + else if (spanLength == 1) // really means 2, is zero based + { + spans.Add(spanStart.ToString()); + spans.Add((spanStart + 1).ToString()); + } + else + { + spans.Add(String.Format("{0}-{1}", spanStart, spanStart + spanLength)); + } - spanStart = expenseIds[currentIndex]; - spanLength = 0; + spanStart = expenseIds[currentIndex]; + spanLength = 0; - currentIndex++; + currentIndex++; + } + } - } - } + // Add the last span - // Add the last span + if (spanLength == 0) + { + spans.Add(spanStart.ToString()); + } + else if (spanLength == 1) // really means 2, is zero based + { + spans.Add(spanStart.ToString()); + spans.Add((spanStart + 1).ToString()); + } + else if (spanLength > 1) + { + spans.Add(String.Format("{0}-{1}", spanStart, spanStart + spanLength)); + } - if (spanLength == 0) - { - spans.Add(spanStart.ToString()); - } - else if (spanLength == 1) // really means 2, is zero based - { - spans.Add(spanStart.ToString()); - spans.Add((spanStart + 1).ToString()); - } - else if (spanLength > 1) - { - spans.Add (String.Format ("{0}-{1}", spanStart, spanStart + spanLength)); - } + // Join spans together with ", " between them - // Join spans together with ", " between them + return String.Join(", ", spans.ToArray()); + } + } - return String.Join (", ", spans.ToArray()); + #region IHasIdentity Members - } - } + public int Identity + { + // We're borrowing the person's identity, as that is what we iterate across. + get { return this.person.Identity; } + } + #endregion - #region IHasIdentity Members + public static ExpensePayout FromOrganizationAndPerson(int organizationId, int personId) + { + ExpenseClaims allExpenseClaims = ExpenseClaims.FromOrganization(Organization.FromIdentity(organizationId)); + ExpenseClaims expenseClaims = new ExpenseClaims(); - public int Identity - { - // We're borrowing the person's identity, as that is what we iterate across. + // Aggregate per person - get { return person.Identity; } - } + foreach (ExpenseClaim expense in allExpenseClaims) + { + if (expense.ClaimingPersonId == personId) + { + if (expense.Approved && expense.Open) + { + // Ready for payout - #endregion - } -} + expenseClaims.Add(expense); + } + } + } + + // Create ExpensePayout object + + return new ExpensePayout(Person.FromIdentity(personId), expenseClaims); + } + } +} \ No newline at end of file diff --git a/Interface/Objects/MainMenuItem.cs b/Interface/Objects/MainMenuItem.cs index 97060288..a38c7486 100644 --- a/Interface/Objects/MainMenuItem.cs +++ b/Interface/Objects/MainMenuItem.cs @@ -5,7 +5,7 @@ using System.Xml.Serialization; namespace Swarmops.Interface.Objects { /// - /// Summary description for MainMenuItem + /// Summary description for MainMenuItem /// [Serializable] public class MainMenuItem @@ -26,10 +26,21 @@ namespace Swarmops.Interface.Objects } } + public string ResourceKey { get; set; } + public int UserLevel { get; set; } + public string Permissions { get; set; } + public string ImageUrl { get; set; } + public string NavigateUrl { get; set; } + public MenuItemType Type { get; set; } + + // TODO: INSERTION POINT (for plugins) + + public MainMenuItem[] Children { get; set; } + public static MainMenuItem Link(string image, string navUrl, string resourceKey, int userLevel, string permissions) { - MainMenuItem result = new MainMenuItem() + MainMenuItem result = new MainMenuItem { ImageUrl = image, NavigateUrl = navUrl, @@ -44,7 +55,7 @@ namespace Swarmops.Interface.Objects public static MainMenuItem Submenu(string resourceKey, int userLevel, string permissions) { - MainMenuItem result = new MainMenuItem() + MainMenuItem result = new MainMenuItem { Permissions = permissions, ResourceKey = resourceKey, @@ -57,7 +68,7 @@ namespace Swarmops.Interface.Objects public static MainMenuItem Disabled(string image, string resourceKey, int userLevel, string permissions) { - MainMenuItem result = new MainMenuItem() + MainMenuItem result = new MainMenuItem { ImageUrl = image, Permissions = permissions, @@ -82,40 +93,26 @@ namespace Swarmops.Interface.Objects public static void PrimeNewMenuFile() { - MainMenuItem todoItem = MainMenuItem.Disabled(string.Empty, "Placeholder_Todo", 1, string.Empty); - MainMenuItem[] todoItemArray = new MainMenuItem[] {todoItem}; + MainMenuItem todoItem = Disabled(string.Empty, "Placeholder_Todo", 1, string.Empty); + MainMenuItem[] todoItemArray = {todoItem}; - MainMenuItem peopleItem = MainMenuItem.Submenu("People", 1, string.Empty); + MainMenuItem peopleItem = Submenu("People", 1, string.Empty); peopleItem.Children = todoItemArray; - MainMenuItem commsItem = MainMenuItem.Submenu("Communications", 1, string.Empty); + MainMenuItem commsItem = Submenu("Communications", 1, string.Empty); peopleItem.Children = todoItemArray; - MainMenuItem claimRefundItem = MainMenuItem.Link("iconshock-moneyback", + MainMenuItem claimRefundItem = Link("iconshock-moneyback", "/Pages/v5/Financial/FileExpenseClaim.aspx", "Financial_ClaimExpense", 2, String.Empty); - MainMenuItem separatorItem = MainMenuItem.Separator; + MainMenuItem separatorItem = Separator; - MainMenuItem[] financialChildren = new[] {claimRefundItem, separatorItem}; - MainMenuItem financialItem = MainMenuItem.Submenu("Financial", 2, string.Empty); + MainMenuItem[] financialChildren = {claimRefundItem, separatorItem}; + MainMenuItem financialItem = Submenu("Financial", 2, string.Empty); financialItem.Children = financialChildren; - MainMenuItem[] protoMenu = new[] {peopleItem, commsItem, financialItem}; + MainMenuItem[] protoMenu = {peopleItem, commsItem, financialItem}; PrimeXml(protoMenu); - } - - public string ResourceKey { get; set; } - public int UserLevel { get; set; } - public string Permissions { get; set; } - public string ImageUrl { get; set; } - public string NavigateUrl { get; set; } - public MenuItemType Type { get; set; } - - // TODO: INSERTION POINT (for plugins) - - public MainMenuItem[] Children { get; set; } - - } public enum MenuItemType @@ -123,37 +120,37 @@ namespace Swarmops.Interface.Objects Unknown = 0, /// - /// A normal link + /// A normal link /// Link, /// - /// Something that looks like a menu item but is disabled + /// Something that looks like a menu item but is disabled /// Disabled, /// - /// A header (with or without image) that leads to more options as sub + /// A header (with or without image) that leads to more options as sub /// Submenu, /// - /// A thin line separating menu items + /// A thin line separating menu items /// Separator, /// - /// A major header (non-link) introducing new menu section + /// A major header (non-link) introducing new menu section /// Header, /// - /// Build number indicator + /// Build number indicator /// BuildNumber, /// - /// SPECIAL CASE: Close Books menu item + /// SPECIAL CASE: Close Books menu item /// SpecialCloseBooks } diff --git a/Interface/Objects/OrganizationMetadata.cs b/Interface/Objects/OrganizationMetadata.cs index c6d20f25..b58d8c2c 100644 --- a/Interface/Objects/OrganizationMetadata.cs +++ b/Interface/Objects/OrganizationMetadata.cs @@ -6,19 +6,39 @@ namespace Swarmops.Interface.Objects { public class OrganizationMetadata { - public OrganizationMetadata (int organizationId, bool recursive, Color color) + private readonly Color color; + private readonly int organizationId; + private readonly bool recursive; + + public OrganizationMetadata(int organizationId, bool recursive, Color color) { this.organizationId = organizationId; this.recursive = recursive; this.color = color; } + + public int OrganizationId + { + get { return this.organizationId; } + } + + public bool Recursive + { + get { return this.recursive; } + } + + public Color Color + { + get { return this.color; } + } + /// - /// Determines the organization accessed from the URL, like *.piratpartiet.se => orgid 1. + /// Determines the organization accessed from the URL, like *.piratpartiet.se => orgid 1. /// /// The url of the webpage in question, like data.piratpartiet.se/something. /// A new OrganizationMetadata instance. - static public OrganizationMetadata FromUrl (string url) + public static OrganizationMetadata FromUrl(string url) { // We could do this using regexps, but it would be messy and error-prone. So instead, I'm going to do it // the old fashioned readable way. @@ -63,7 +83,7 @@ namespace Swarmops.Interface.Objects if (url.EndsWith("localhost")) { - return new OrganizationMetadata(1, false, Color.FromArgb(0x66, 0, 0x87)); // debug purposes + return new OrganizationMetadata(1, false, Color.FromArgb(0x66, 0, 0x87)); // debug purposes } //HACK: @@ -79,29 +99,7 @@ namespace Swarmops.Interface.Objects } - - - throw new ArgumentException("Unsupported organization" ); + throw new ArgumentException("Unsupported organization"); } - - - public int OrganizationId - { - get { return this.organizationId; } - } - - public bool Recursive - { - get { return this.recursive; } - } - - public Color Color - { - get { return this.color; } - } - - private int organizationId; - private bool recursive; - private Color color; } -} +} \ No newline at end of file diff --git a/Interface/PersonIcon.cs b/Interface/PersonIcon.cs index 0bd525a0..bd065f49 100644 --- a/Interface/PersonIcon.cs +++ b/Interface/PersonIcon.cs @@ -1,6 +1,4 @@ using System; -using Swarmops.Basic.Enums; -using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Swarm; @@ -8,21 +6,8 @@ namespace Swarmops.Interface { public class PersonIcon { - public class PersonIconSpec - { - public PersonIconSpec (string image, string altText) - { - this.Image = image; - this.AltText = altText; - - } - - public string Image = ""; - public string AltText = ""; - } - - [Obsolete ("Person icons are deprecated in Swarmops in favor of individual avatars", true)] - public static PersonIconSpec ForPerson (Person person, Organizations organizations) + [Obsolete("Person icons are deprecated in Swarmops in favor of individual avatars", true)] + public static PersonIconSpec ForPerson(Person person, Organizations organizations) { throw new NotImplementedException("Person icons are deprecated in Swarmops v5 in favor of gravatars/avatars"); @@ -212,6 +197,18 @@ namespace Swarmops.Interface // unhandled role type return new PersonIconSpec("user-silhouette-question.png", "unknown role, " + (person.IsFemale ? "female" : person.IsMale ? "male" : "")); } */ - } + } + + public class PersonIconSpec + { + public string AltText = ""; + public string Image = ""; + + public PersonIconSpec(string image, string altText) + { + this.Image = image; + this.AltText = altText; + } + } } -} +} \ No newline at end of file diff --git a/Interface/PirateWebMapProvider.cs b/Interface/PirateWebMapProvider.cs index cf35a1b0..eb00f103 100644 --- a/Interface/PirateWebMapProvider.cs +++ b/Interface/PirateWebMapProvider.cs @@ -1,67 +1,70 @@ using System.Collections.Specialized; using System.Web; +using Swarmops.Interface.Localization; namespace Swarmops.Interface { - public class PirateWebMapProvider: XmlSiteMapProvider - { - public PirateWebMapProvider() - { - NameValueCollection parameters = new NameValueCollection(); + public class PirateWebMapProvider : XmlSiteMapProvider + { + public PirateWebMapProvider() + { + NameValueCollection parameters = new NameValueCollection(); #if __MonoCS__ parameters.Add("siteMapFile", HttpContext.Current.Server.MapPath("~/PirateWeb.sitemap")); #else - parameters.Add("siteMapFile", "~/PirateWeb.sitemap"); + parameters.Add("siteMapFile", "~/PirateWeb.sitemap"); #endif - base.Initialize("PirateWebMapProvider", parameters); - } + base.Initialize("PirateWebMapProvider", parameters); + } - public override SiteMapNode FindSiteMapNode(string rawUrl) - { - return base.FindSiteMapNode(rawUrl); - } + public override SiteMapNode FindSiteMapNode(string rawUrl) + { + return base.FindSiteMapNode(rawUrl); + } - public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) - { - SiteMapNodeCollection baseCollection = base.GetChildNodes(node); + public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) + { + SiteMapNodeCollection baseCollection = base.GetChildNodes(node); - SiteMapNodeCollection newCollection = new SiteMapNodeCollection(); + SiteMapNodeCollection newCollection = new SiteMapNodeCollection(); - int count = baseCollection.Count; - for (int index = 0; index < count; index++) - { - SiteMapNode oldNode = baseCollection[index]; + int count = baseCollection.Count; + for (int index = 0; index < count; index++) + { + SiteMapNode oldNode = baseCollection[index]; - // TODO: Filter on oldNode.Roles here + // TODO: Filter on oldNode.Roles here - SiteMapNode newNode = new SiteMapNode(oldNode.Provider, oldNode.Key, oldNode.Url, Localization.LocalizationManager.GetLocalString (oldNode.Description, oldNode.Title), oldNode.Description); - newCollection.Add(newNode); - } + SiteMapNode newNode = new SiteMapNode(oldNode.Provider, oldNode.Key, oldNode.Url, + LocalizationManager.GetLocalString(oldNode.Description, oldNode.Title), oldNode.Description); + newCollection.Add(newNode); + } - return baseCollection ; + return baseCollection; //return newCollection; } - public override SiteMapNode GetParentNode(SiteMapNode node) - { - return base.GetParentNode(node); - } + public override SiteMapNode GetParentNode(SiteMapNode node) + { + return base.GetParentNode(node); + } - protected override SiteMapNode GetRootNodeCore() - { + protected override SiteMapNode GetRootNodeCore() + { //return LocalizeNode (base.GetRootNodeCore()); return base.GetRootNodeCore(); } - private SiteMapNode LocalizeNode(SiteMapNode node) - { - if (node == null) - { - return null; - } - + private SiteMapNode LocalizeNode(SiteMapNode node) + { + if (node == null) + { + return null; + } - return new SiteMapNode(node.Provider, node.Key, node.Url, Localization.LocalizationManager.GetLocalString(node.Description, node.Title), node.Description); - } - } -} + + return new SiteMapNode(node.Provider, node.Key, node.Url, + LocalizationManager.GetLocalString(node.Description, node.Title), node.Description); + } + } +} \ No newline at end of file diff --git a/Interface/Properties/AssemblyInfo.cs b/Interface/Properties/AssemblyInfo.cs index e1ad67dc..2f20bec8 100644 --- a/Interface/Properties/AssemblyInfo.cs +++ b/Interface/Properties/AssemblyInfo.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("Interface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -16,9 +17,11 @@ using System.Runtime.InteropServices; // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("5519b139-b70a-47dc-917f-7312449507c7")] // Version information for an assembly consists of the following four values: @@ -30,5 +33,6 @@ using System.Runtime.InteropServices; // // 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.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Interface/RssWriter.cs b/Interface/RssWriter.cs index f51ff230..980b04ee 100644 --- a/Interface/RssWriter.cs +++ b/Interface/RssWriter.cs @@ -15,13 +15,13 @@ using System.Xml; namespace Swarmops.Interface { - public class RssWriter { - XmlWriter m_writer; + private readonly XmlWriter m_writer; + public RssWriter(XmlWriter tw) { - m_writer = tw; + this.m_writer = tw; } // Write header for RSS Feed @@ -32,24 +32,23 @@ namespace Swarmops.Interface // generator - optional string for 'generator' tag. public void WriteHeader(string title, string link, string description, string generator) { - m_writer.WriteStartElement("rss"); - m_writer.WriteAttributeString("version", "2.0"); - m_writer.WriteStartElement("channel"); - m_writer.WriteElementString("title", title); + this.m_writer.WriteStartElement("rss"); + this.m_writer.WriteAttributeString("version", "2.0"); + this.m_writer.WriteStartElement("channel"); + this.m_writer.WriteElementString("title", title); if (link != null) { - m_writer.WriteElementString("link", link); // link to generated report. + this.m_writer.WriteElementString("link", link); // link to generated report. } - m_writer.WriteElementString("description", description); + this.m_writer.WriteElementString("description", description); if (generator != null) { - m_writer.WriteElementString("generator", generator); + this.m_writer.WriteElementString("generator", generator); } - m_writer.WriteElementString("lastBuildDate", ConvertDate(new DateTime())); - + this.m_writer.WriteElementString("lastBuildDate", ConvertDate(new DateTime())); } // Write out an item. @@ -57,18 +56,21 @@ namespace Swarmops.Interface // content - main body of the blog entry // link - link the blog entry back to a webpage. // time - date for the blog entry. - public void WriteItem(string title, string content, System.Uri link, DateTime time) + public void WriteItem(string title, string content, Uri link, DateTime time) { - m_writer.WriteStartElement("item"); - WriteItemBody(m_writer, title, content, link, time); - m_writer.WriteEndElement(); // item + this.m_writer.WriteStartElement("item"); + WriteItemBody(this.m_writer, title, content, link, time); + this.m_writer.WriteEndElement(); // item } // Write just the body (InnerXml) of a new item - public static void WriteItemBody(XmlWriter w, string title, string content, System.Uri link, DateTime time) + public static void WriteItemBody(XmlWriter w, string title, string content, Uri link, DateTime time) { w.WriteElementString("title", title); - if (link != null) { w.WriteElementString("link", link.ToString()); } + if (link != null) + { + w.WriteElementString("link", link.ToString()); + } w.WriteElementString("description", content); // this will escape w.WriteElementString("pubDate", ConvertDate(time)); } @@ -77,15 +79,14 @@ namespace Swarmops.Interface // this does not close the underlying XML writer. public void Close() { - m_writer.WriteEndElement(); // channel - m_writer.WriteEndElement(); // rss + this.m_writer.WriteEndElement(); // channel + this.m_writer.WriteEndElement(); // rss } // Convert a DateTime into the format needed for RSS (from RFC 822). // This looks like: "Wed, 04 Jan 2006 16:03:00 GMT" - static string ConvertDate(DateTime t) + private static string ConvertDate(DateTime t) { - // See this for help on format string // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomdatetimeformatstrings.asp DateTime t2 = t.ToUniversalTime(); @@ -93,6 +94,5 @@ namespace Swarmops.Interface // unnecessary - t.ToUniversalTime().ToString ("r") would have done it /RF } - } } \ No newline at end of file diff --git a/Logic/AssemblyInfo.cs b/Logic/AssemblyInfo.cs index 0baa771a..7636e892 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 67f59ec6..b4f2f749 100644 --- a/Logic/Cache/GeographyCache.cs +++ b/Logic/Cache/GeographyCache.cs @@ -8,18 +8,18 @@ namespace Swarmops.Logic.Cache { public class GeographyCache { - static private DateTime lastRefresh; - static private object loadCacheLock = new object(); - static public bool loadCache = true; - static private Dictionary> __geographyCache = null; - static readonly int cacheLifeSpanMinutes = 2; + private static DateTime lastRefresh; + private static object loadCacheLock = new object(); + public static bool loadCache = true; + private static Dictionary> __geographyCache = null; + private static readonly int cacheLifeSpanMinutes = 2; - static GeographyCache () + static GeographyCache() { lastRefresh = DateTime.MinValue; } - static private Dictionary> GetHashedGeographies () + private static Dictionary> GetHashedGeographies() { lock (loadCacheLock) { @@ -34,15 +34,15 @@ namespace Swarmops.Logic.Cache } - static public Geography FromCache (int geographyId) + public static Geography FromCache(int geographyId) { lock (loadCacheLock) { - return Geography.FromBasic(GeographyCache.GetGeography(geographyId)); + return Geography.FromBasic(GetGeography(geographyId)); } } - static public BasicGeography[] GetAllGeographies () + public static BasicGeography[] GetAllGeographies() { lock (loadCacheLock) { @@ -58,27 +58,27 @@ namespace Swarmops.Logic.Cache } - static public BasicGeography[] GetGeographies (int[] ids) + public static BasicGeography[] GetGeographies(int[] ids) { List result = new List(); lock (loadCacheLock) { foreach (int i in ids) { - result.Add(GeographyCache.GetGeography(i) ); + result.Add(GetGeography(i)); } return result.ToArray(); } } - static public BasicGeography[] GetGeographyChildren (int parentGeographyId) + public static BasicGeography[] GetGeographyChildren(int parentGeographyId) { List result = new List(); lock (loadCacheLock) { // Prime the cache - BasicGeography partent = GeographyCache.GetGeography(parentGeographyId); + BasicGeography partent = GetGeography(parentGeographyId); //TODO: Possible to miss a child geography here if it was added since last cache reload. @@ -93,25 +93,24 @@ namespace Swarmops.Logic.Cache } - public static int CountGeographyChildren (int parentGeographyId) + public static int CountGeographyChildren(int parentGeographyId) { lock (loadCacheLock) { // Prime the cache - BasicGeography partent = GeographyCache.GetGeography(parentGeographyId); + BasicGeography partent = GetGeography(parentGeographyId); return GetHashedGeographies()[parentGeographyId].Count - 1; } } - - static public BasicGeography[] GetGeographyLine (int leafGeographyId) + public static BasicGeography[] GetGeographyLine(int leafGeographyId) { List result = new List(); - BasicGeography currentNode = GeographyCache.GetGeography(leafGeographyId); + BasicGeography currentNode = GetGeography(leafGeographyId); // This iterates until the zero-parentid root node is found @@ -121,7 +120,7 @@ namespace Swarmops.Logic.Cache if (currentNode.ParentGeographyId != 0) { - currentNode = GeographyCache.GetGeography(currentNode.ParentGeographyId); + currentNode = GetGeography(currentNode.ParentGeographyId); } else { @@ -135,13 +134,13 @@ namespace Swarmops.Logic.Cache } - static public BasicGeography[] GetGeographyTree () + public static BasicGeography[] GetGeographyTree() { return GetGeographyTree(1); } - public static Dictionary GetGeographyHashtable (int startGeographyId) + public static Dictionary GetGeographyHashtable(int startGeographyId) { BasicGeography[] nodes = GetGeographyTree(startGeographyId); @@ -155,7 +154,7 @@ namespace Swarmops.Logic.Cache return result; } - static public BasicGeography[] GetGeographyTree (int startGeographyId) + public static BasicGeography[] GetGeographyTree(int startGeographyId) { Dictionary> nodes = GetHashedGeographies(); @@ -163,10 +162,9 @@ namespace Swarmops.Logic.Cache } - - - static private BasicGeography[] GetGeographyTree (Dictionary> geographies, int startNodeId, - int generation) + private static BasicGeography[] GetGeographyTree(Dictionary> geographies, + int startNodeId, + int generation) { List result = new List(); @@ -202,7 +200,7 @@ namespace Swarmops.Logic.Cache } - static public BasicGeography GetGeography (int geographyId) + public static BasicGeography GetGeography(int geographyId) { lock (loadCacheLock) { @@ -224,7 +222,7 @@ namespace Swarmops.Logic.Cache } - static public BasicGeography GetGeographyByName (string geographyName) + public static BasicGeography GetGeographyByName(string geographyName) { string cmpName = geographyName.ToLower().Trim(); Dictionary> hashedGeographies = GetHashedGeographies(); @@ -238,7 +236,7 @@ namespace Swarmops.Logic.Cache } - static public 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); @@ -258,6 +256,5 @@ namespace Swarmops.Logic.Cache return SwarmDb.GetDatabaseForReading().GetGeographyIdsFromLevel(countryId, level); } ************************/ - } } \ No newline at end of file diff --git a/Logic/Cache/GuidCache.cs b/Logic/Cache/GuidCache.cs index 94a5aba8..414a353d 100644 --- a/Logic/Cache/GuidCache.cs +++ b/Logic/Cache/GuidCache.cs @@ -5,28 +5,33 @@ using System.Linq; namespace Swarmops.Logic.Cache { /// - /// This class stores arbitrary objects, keyed by a GUID, for 24 hours. Primarily intended for progress bars and similar data that - /// needs to be stored in a separate, global namespace for accessibility reasons from JavaScript. DO NOT STORE SENSITIVE STUFF here - /// as it's generally accessible, at least not without accompanying access control. - /// - /// TODO: Share this data across a web farm some bloody how. Put it in database? Too slow for progress bars... Memcached perhaps? + /// This class stores arbitrary objects, keyed by a GUID, for 24 hours. Primarily intended for progress bars and + /// similar data that + /// needs to be stored in a separate, global namespace for accessibility reasons from JavaScript. DO NOT STORE + /// SENSITIVE STUFF here + /// as it's generally accessible, at least not without accompanying access control. + /// TODO: Share this data across a web farm some bloody how. Put it in database? Too slow for progress bars... + /// Memcached perhaps? /// public class GuidCache { + private static readonly Dictionary _cache; + private static DateTime _nextGarbageCollect; + static GuidCache() { _cache = new Dictionary(); _nextGarbageCollect = DateTime.MinValue; } - static public void Set(string guidString, object objectToCache) + public static void Set(string guidString, object objectToCache) { ConditionalGarbageCollect(); - _cache[guidString] = new CachedObject() {StoredDateTime = DateTime.UtcNow, Object = objectToCache}; + _cache[guidString] = new CachedObject {StoredDateTime = DateTime.UtcNow, Object = objectToCache}; } - static public object Get(string guidString) + public static object Get(string guidString) { if (!_cache.ContainsKey(guidString)) { @@ -43,7 +48,7 @@ namespace Swarmops.Logic.Cache } } - static private void ConditionalGarbageCollect() + private static void ConditionalGarbageCollect() { lock (_cache) // thread safety { @@ -59,7 +64,8 @@ namespace Swarmops.Logic.Cache 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 + 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) { @@ -68,15 +74,10 @@ namespace Swarmops.Logic.Cache } } - static private Dictionary _cache; - private static DateTime _nextGarbageCollect; - private class CachedObject { - public DateTime StoredDateTime { get; set; } public object Object; + public DateTime StoredDateTime { get; set; } } } - - -} +} \ No newline at end of file diff --git a/Logic/Cache/MailTemplateCache.cs b/Logic/Cache/MailTemplateCache.cs index 7105ceb9..c1027948 100644 --- a/Logic/Cache/MailTemplateCache.cs +++ b/Logic/Cache/MailTemplateCache.cs @@ -8,18 +8,21 @@ namespace Swarmops.Logic.Cache { public class MailTemplateCache { - static private DateTime lastAccess = DateTime.MinValue; - static private object loadCacheLock = new object(); - static public bool loadCache = true; - static private Dictionary> __MailTemplateCache = new Dictionary>(); - static readonly int cacheLifeSpanMinutes = 1; + private static DateTime lastAccess = DateTime.MinValue; + private static readonly object loadCacheLock = new object(); + public static bool loadCache = true; - static MailTemplateCache () + private static Dictionary> __MailTemplateCache = + new Dictionary>(); + + private static readonly int cacheLifeSpanMinutes = 1; + + static MailTemplateCache() { lastAccess = DateTime.MinValue; } - static private List GetCachedTemplates (string templateName) + private static List GetCachedTemplates(string templateName) { lock (loadCacheLock) { @@ -31,10 +34,10 @@ namespace Swarmops.Logic.Cache if (!__MailTemplateCache.ContainsKey(templateName)) { - BasicMailTemplate[] basicTemplates = SwarmDb.GetDatabaseForReading().GetMailTemplatesByName(templateName); + BasicMailTemplate[] basicTemplates = + SwarmDb.GetDatabaseForReading().GetMailTemplatesByName(templateName); List tmplList = new List(basicTemplates); __MailTemplateCache[templateName] = tmplList; - } lastAccess = DateTime.Now; @@ -42,11 +45,12 @@ namespace Swarmops.Logic.Cache } } - static public BasicMailTemplate GetBestMatch (string templateName, string language, string country, Organization org) + public static BasicMailTemplate GetBestMatch(string templateName, string language, string country, + Organization org) { List tmplList = GetCachedTemplates(templateName); - Organizations orgLine = ( org != null) ? org.GetLine() : new Organizations(); + Organizations orgLine = (org != null) ? org.GetLine() : new Organizations(); int[] lineIDs = orgLine.Identities; List idlist = new List(lineIDs); @@ -75,12 +79,11 @@ namespace Swarmops.Logic.Cache } if (bestSofar != null) return bestSofar; - else if (countryDefault != null) + if (countryDefault != null) return countryDefault; - else if (templateDefault != null) + if (templateDefault != null) return templateDefault; - else - return null; + return null; } } } \ No newline at end of file diff --git a/Logic/Cache/OrganizationCache.cs b/Logic/Cache/OrganizationCache.cs index 7365cb36..e5744684 100644 --- a/Logic/Cache/OrganizationCache.cs +++ b/Logic/Cache/OrganizationCache.cs @@ -8,35 +8,18 @@ namespace Swarmops.Logic.Cache { public class OrganizationCache { - static private DateTime lastRefresh; - static private object loadCacheLock = new object(); - static public bool __loadCache = true; - static private Dictionary> __organizationCache = null; - static readonly int cacheLifeSpanMinutes = 2; + private static DateTime lastRefresh; + private static object loadCacheLock = new object(); + public static bool __loadCache = true; + private static Dictionary> __organizationCache = null; + private static readonly int cacheLifeSpanMinutes = 2; + private static Dictionary> __cachedUptakeGeographies = null; - static OrganizationCache () + static OrganizationCache() { lastRefresh = DateTime.MinValue; } - private static Dictionary> GetHashedOrganizations () - { - if (needsReload) - { - lock (loadCacheLock) - { - if (needsReload) - { - __organizationCache = SwarmDb.GetDatabaseForReading().GetHashedOrganizations(); - __cachedUptakeGeographies = null; - lastRefresh = DateTime.Now; - needsReload = false; - } - } - } - return __organizationCache; - } - public static bool needsReload { get @@ -55,52 +38,66 @@ namespace Swarmops.Logic.Cache } } - public static Organization FromCache (int OrganizationId) + private static Dictionary> GetHashedOrganizations() { + if (needsReload) + { + lock (loadCacheLock) + { + if (needsReload) + { + __organizationCache = SwarmDb.GetDatabaseForReading().GetHashedOrganizations(); + __cachedUptakeGeographies = null; + lastRefresh = DateTime.Now; + needsReload = false; + } + } + } + return __organizationCache; + } + public static Organization FromCache(int OrganizationId) + { lock (loadCacheLock) { - return Organization.FromBasic(OrganizationCache.GetOrganization(OrganizationId)); + return Organization.FromBasic(GetOrganization(OrganizationId)); } - } - internal static int CreateOrganization (int ParentOrganizationId, string NameInternational, string Name, - string NameShort, string Domain, string MailPrefix, - int AnchorGeographyId, bool AcceptsMembers, - bool AutoAssignNewMembers, int DefaultCountryId) + 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, - NameInternational, - Name, - NameShort, - Domain, - MailPrefix, - AnchorGeographyId, - AcceptsMembers, - AutoAssignNewMembers, - DefaultCountryId); + NameInternational, + Name, + NameShort, + Domain, + MailPrefix, + AnchorGeographyId, + AcceptsMembers, + AutoAssignNewMembers, + DefaultCountryId); needsReload = true; 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, - MailPrefix, AnchorGeographyId, AcceptsMembers, AutoAssignNewMembers, DefaultCountryId, - OrganizationId); - - OrganizationCache.needsReload = true; + SwarmDb.GetDatabaseForWriting() + .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; // Let this be for the moment, new and old parents need to be loaded as well. Better right now to reload the whole cache. @@ -108,13 +105,13 @@ namespace Swarmops.Logic.Cache //{ // __organizationCache[objectId][0] = Organization.FromBasic(SwarmDb.GetDatabaseForReading().GetOrganization(objectId)); //} - } - public static BasicOrganization[] GetAll () + + public static BasicOrganization[] GetAll() { lock (loadCacheLock) { - Dictionary> hashedOrganisations = OrganizationCache.GetHashedOrganizations(); + Dictionary> hashedOrganisations = GetHashedOrganizations(); List returnList = new List(); foreach (int id in hashedOrganisations.Keys) { @@ -124,12 +121,11 @@ namespace Swarmops.Logic.Cache } } - public static BasicOrganization GetOrganization (int OrganizationId) + public static BasicOrganization GetOrganization(int OrganizationId) { - lock (loadCacheLock) { - Dictionary> hashedOrganisations = OrganizationCache.GetHashedOrganizations(); + Dictionary> hashedOrganisations = GetHashedOrganizations(); if (hashedOrganisations.ContainsKey(OrganizationId)) return hashedOrganisations[OrganizationId][0]; else @@ -137,30 +133,30 @@ namespace Swarmops.Logic.Cache //Didn't find, strange, id's should exist, try reloading the cache, it could be newly added. needsReload = true; - hashedOrganisations = OrganizationCache.GetHashedOrganizations(); + hashedOrganisations = GetHashedOrganizations(); if (hashedOrganisations.ContainsKey(OrganizationId)) return hashedOrganisations[OrganizationId][0]; else { throw new ArgumentException("No such OrganizationId: " + OrganizationId.ToString()); } - }; + } + ; } - } - public static BasicOrganization[] GetOrganizationTree (int startOrganizationId) + public static BasicOrganization[] GetOrganizationTree(int startOrganizationId) { lock (loadCacheLock) { - Dictionary> organizations = OrganizationCache.GetHashedOrganizations(); + Dictionary> organizations = GetHashedOrganizations(); return GetOrganizationTree(organizations, startOrganizationId, 0); } } - public static Dictionary GetOrganizationHashtable (int startOrganizationId) + public static Dictionary GetOrganizationHashtable(int startOrganizationId) { BasicOrganization[] organizations = GetOrganizationTree(startOrganizationId); @@ -175,13 +171,13 @@ namespace Swarmops.Logic.Cache } - private static BasicOrganization[] GetOrganizationTree (Dictionary> organizations, - int startOrganizationId, int generation) + private static BasicOrganization[] GetOrganizationTree(Dictionary> organizations, + int startOrganizationId, int generation) { List result = new List(); //Prime the cache - BasicOrganization start = OrganizationCache.GetOrganization(startOrganizationId); + BasicOrganization start = GetOrganization(startOrganizationId); List thisList = organizations[startOrganizationId]; @@ -195,7 +191,7 @@ namespace Swarmops.Logic.Cache // Add recursively BasicOrganization[] children = GetOrganizationTree(organizations, organization.OrganizationId, - generation + 1); + generation + 1); if (children.Length > 0) { @@ -217,12 +213,12 @@ namespace Swarmops.Logic.Cache return result.ToArray(); } - static public BasicOrganization[] GetOrganizationChildren (int parentOrgId) + public static BasicOrganization[] GetOrganizationChildren(int parentOrgId) { List result = new List(); lock (loadCacheLock) { - BasicOrganization parent = OrganizationCache.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(); @@ -235,14 +231,13 @@ namespace Swarmops.Logic.Cache } } - public static BasicOrganization[] GetOrganizationLine (int leafOrganizationId) + public static BasicOrganization[] GetOrganizationLine(int leafOrganizationId) { - lock (loadCacheLock) { List result = new List(); - BasicOrganization currentOrganization = OrganizationCache.GetOrganization(leafOrganizationId); + BasicOrganization currentOrganization = GetOrganization(leafOrganizationId); // This iterates until the zero-parentid root Organization is found @@ -252,7 +247,7 @@ namespace Swarmops.Logic.Cache if (currentOrganization.ParentOrganizationId > 0) { - currentOrganization = OrganizationCache.GetOrganization(currentOrganization.ParentOrganizationId); + currentOrganization = GetOrganization(currentOrganization.ParentOrganizationId); } else { @@ -266,8 +261,9 @@ namespace Swarmops.Logic.Cache } } - [Obsolete ("Never use this function. Mark the org as unused, deleted. Records are needed for historic reasons.", true)] - internal static void DeleteOrganization (int p) + [Obsolete("Never use this function. Mark the org as unused, deleted. Records are needed for historic reasons.", + true)] + internal static void DeleteOrganization(int p) { SwarmDb.GetDatabaseForWriting().DeleteOrganization(p); needsReload = true; @@ -279,9 +275,8 @@ namespace Swarmops.Logic.Cache // this is nulled when a main cache load is done, so it don't need a timing parameter really // since that will be governed by the timeout of organisations. - static private Dictionary> __cachedUptakeGeographies = null; - static private Dictionary> GetUptakes () + private static Dictionary> GetUptakes() { //to make sure we dont end up loading uptakes, loding organisations, then load uptakes again. lock (loadCacheLock) @@ -296,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) { @@ -314,7 +309,7 @@ namespace Swarmops.Logic.Cache } - static public int[] GetOrganizationIdsInGeographies (int[] nodeIds) + public static int[] GetOrganizationIdsInGeographies(int[] nodeIds) { if (nodeIds == null || nodeIds.Length == 0) { @@ -358,27 +353,26 @@ 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); 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); lock (loadCacheLock) { __cachedUptakeGeographies = null; } - } } } \ No newline at end of file diff --git a/Logic/Communications/AutoMail.cs b/Logic/Communications/AutoMail.cs index a868535f..2c8dfd4e 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, - Person author, string title, string body) + public static AutoMail Create(AutoMailType type, Organization org, Geography geo, + Person author, string title, string body) { - SwarmDb.GetDatabaseForWriting().SetAutoMail (type, org.Identity, geo.Identity, - author == null ? 0 : author.Identity, title, body); - return FromTypeOrganizationAndGeography (type, org, geo); + SwarmDb.GetDatabaseForWriting().SetAutoMail(type, org.Identity, geo.Identity, + author == null ? 0 : author.Identity, title, body); + return FromTypeOrganizationAndGeography(type, org, geo); } diff --git a/Logic/Communications/CommunicationTurnaround.cs b/Logic/Communications/CommunicationTurnaround.cs index 7220af44..d01b2cb2 100644 --- a/Logic/Communications/CommunicationTurnaround.cs +++ b/Logic/Communications/CommunicationTurnaround.cs @@ -6,32 +6,36 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications { - public class CommunicationTurnaround: BasicCommunicationTurnaround + 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); } - public static CommunicationTurnaround FromIdentity (Organization organization, int communicationTypeId, int communicationId) + public static CommunicationTurnaround FromIdentity(Organization organization, int communicationTypeId, + int communicationId) { return - FromBasic(SwarmDb.GetDatabaseForReading().GetCommunicationTurnaround(organization.Identity, communicationTypeId, - communicationId)); + FromBasic(SwarmDb.GetDatabaseForReading() + .GetCommunicationTurnaround(organization.Identity, communicationTypeId, + communicationId)); } - public static CommunicationTurnaround Create (Organization organization, int communicationId, DateTime dateTimeOpened) + public static CommunicationTurnaround Create(Organization organization, int communicationId, + DateTime dateTimeOpened) { - SwarmDb.GetDatabaseForWriting().CreateCommunicationTurnaround(organization.Identity, 1, communicationId, dateTimeOpened); + SwarmDb.GetDatabaseForWriting() + .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) { @@ -50,12 +54,14 @@ namespace Swarmops.Logic.Communications personId = person.Identity; } - SwarmDb.GetDatabaseForWriting().SetCommunicationTurnaroundResponded(this.OrganizationId, this.CommunicationTypeId, this.CommunicationId, dateTime, personId); + SwarmDb.GetDatabaseForWriting() + .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) { @@ -69,9 +75,11 @@ namespace Swarmops.Logic.Communications personId = person.Identity; } - SwarmDb.GetDatabaseForWriting().SetCommunicationTurnaroundClosed(this.OrganizationId, this.CommunicationTypeId, this.CommunicationId, dateTime, personId); + SwarmDb.GetDatabaseForWriting() + .SetCommunicationTurnaroundClosed(OrganizationId, CommunicationTypeId, CommunicationId, dateTime, + personId); base.Open = false; } } -} +} \ No newline at end of file diff --git a/Logic/Communications/CommunicationTurnarounds.cs b/Logic/Communications/CommunicationTurnarounds.cs index 2bd2e87d..c16d4e7a 100644 --- a/Logic/Communications/CommunicationTurnarounds.cs +++ b/Logic/Communications/CommunicationTurnarounds.cs @@ -5,25 +5,23 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Communications { - public class CommunicationTurnarounds: PluralBase + public class CommunicationTurnarounds : + PluralBase { - public static CommunicationTurnarounds ForOrganization (Organization organization) + public static CommunicationTurnarounds ForOrganization(Organization organization) { 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)); } - else - { - return - FromArray(SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds(organization, - DatabaseCondition.OpenTrue)); - } + return + FromArray(SwarmDb.GetDatabaseForReading().GetCommunicationTurnarounds(organization, + DatabaseCondition.OpenTrue)); } } -} +} \ No newline at end of file diff --git a/Logic/Communications/ICommsRenderer.cs b/Logic/Communications/ICommsRenderer.cs index aa2d2ef2..35c0f9b7 100644 --- a/Logic/Communications/ICommsRenderer.cs +++ b/Logic/Communications/ICommsRenderer.cs @@ -4,14 +4,14 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications { /// - /// Renders an OutboundComm for one specific type of comm and for the target person. + /// Renders an OutboundComm for one specific type of comm and for the target person. /// public interface ICommsRenderer { RenderedComm RenderComm(Person person); } - public class RenderedComm: Dictionary + public class RenderedComm : Dictionary { // typeset for readability } @@ -26,4 +26,4 @@ namespace Swarmops.Logic.Communications BodyHtml, BodyImages } -} +} \ No newline at end of file diff --git a/Logic/Communications/ICommsResolver.cs b/Logic/Communications/ICommsResolver.cs index 929cc12e..cab59405 100644 --- a/Logic/Communications/ICommsResolver.cs +++ b/Logic/Communications/ICommsResolver.cs @@ -3,4 +3,4 @@ public interface ICommsResolver { } -} +} \ No newline at end of file diff --git a/Logic/Communications/ICommsTransmitter.cs b/Logic/Communications/ICommsTransmitter.cs index 471b0e35..faa8195a 100644 --- a/Logic/Communications/ICommsTransmitter.cs +++ b/Logic/Communications/ICommsTransmitter.cs @@ -6,10 +6,11 @@ namespace Swarmops.Logic.Communications public interface ICommsTransmitter { /// - /// This function transmits an outbound comm. If it fails, it must throw an OutboundCommTransmitException. It is expected to block until complete. + /// This function transmits an outbound comm. If it fails, it must throw an OutboundCommTransmitException. It is + /// expected to block until complete. /// /// The piece of communications to send. /// The person to send to. 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 4d142726..cfceca10 100644 --- a/Logic/Communications/MailTemplate.cs +++ b/Logic/Communications/MailTemplate.cs @@ -12,223 +12,39 @@ namespace Swarmops.Logic.Communications { public class MailTemplate : BasicMailTemplate { - private string originallyLoadedContent = ""; - private HtmlDocument htmlDoc = null; + private readonly string originallyLoadedContent = ""; + private HtmlDocument htmlDoc; - internal MailTemplate () + internal MailTemplate() : base(0, "", "", "", 0, "") { } - public MailTemplate (BasicMailTemplate basic) + public MailTemplate(BasicMailTemplate basic) : base(basic) { - originallyLoadedContent = basic.TemplateBody; - } - - public void ResetContent () - { - this.htmlDoc = null; - this.TemplateBody = originallyLoadedContent; - } - - public void NormalizeHtml () - { - //Make sure there is a full html document defined - this.htmlDoc = NormalizeHtmlExtracted(this.HtmlDoc, this.TemplateName.EndsWith("Plain")); - } - - private HtmlDocument NormalizeHtmlExtracted (HtmlDocument htDoc, bool forPlainText) - { - if (htDoc == null) - { - throw new Exception("NormalizeHtmlExtracted was called with null document:\nTemplateBody:" + this.TemplateBody); - } - - if (htDoc.DocumentNode == null) - { - throw new Exception("NormalizeHtmlExtracted was called with null DocumentNode:\nTemplateBody:" + this.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"); - if (bodyNode == null && headNode == null && htmlNode == null) - newHtml = "Untitled" + htDoc.DocumentNode.OuterHtml + ""; - else if (bodyNode != null && headNode == null && htmlNode == null) - newHtml = "Untitled" + bodyNode.OuterHtml + ""; - else if (bodyNode != null && headNode != null && htmlNode == null) - newHtml = "" + bodyNode.OuterHtml + ""; - else if (headNode == null && htmlNode != null) - { - headNode = htDoc.CreateElement("head"); - htmlNode.InsertAfter(headNode, null); - titleNode = htDoc.CreateElement("title"); - titleNode.InnerHtml = "Untitled"; - headNode.AppendChild(titleNode); - } - else if (titleNode == null && headNode != null) - { - titleNode = htDoc.CreateElement("title"); - titleNode.InnerHtml = "Untitled"; - headNode.AppendChild(titleNode); - } - - if (newHtml != "") - { - htDoc = new HtmlDocument(); - htDoc.LoadHtml(newHtml); - } - - if (htDoc.DocumentNode == null) - { - 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"); - - if (bodyNode2 == null) - { - throw new Exception("NormalizeHtmlExtracted bodyNode2 is null for " + newHtml); - } - - int preIx = 0; - for (preIx = 0; preIx < bodyNode2.ChildNodes.Count; ++preIx) - { - if (bodyNode2.ChildNodes[preIx].Name.ToLower() == "pre") break; - } - - if (forPlainText && preIx == bodyNode2.ChildNodes.Count) - { - 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); - } - string html = htDoc.DocumentNode.OuterHtml; - htDoc = new HtmlDocument(); - htDoc.LoadHtml(html); - } - - return htDoc; - } - - public void MarkPlaceholderSpans () - { - MarkPlaceholderSpans(this.HtmlDoc); - } - - public void MarkPlaceholderSpans (Dictionary allowedPlaceholders) - { - this.MarkPlaceholderSpans(); - HtmlNodeCollection allTags = this.HtmlBody.SelectNodes("//*[@class='placeholder2']"); - Regex reCleanup = new Regex(@"[\s%]"); - if (allTags != null) - { - foreach (HtmlNode n in allTags) - { - string key = reCleanup.Replace(n.InnerText, ""); - string keyLow = key.ToLower(); - if (!allowedPlaceholders.ContainsKey(keyLow)) - { - string classname = n.GetAttributeValue("class", ""); - classname = classname.Replace("placeholder2", "placeholderUnkn"); - n.SetAttributeValue("class", classname); - } - else if (allowedPlaceholders[keyLow] != key - && allowedPlaceholders[keyLow].ToUpper() != key - && allowedPlaceholders[keyLow].ToLower() != key) - { - n.InnerHtml = "%" + allowedPlaceholders[keyLow] + "%"; - } - } - } - } - - 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 - if (allWithTextNodes != null) - { - foreach (HtmlNode n in allWithTextNodes) - { - HtmlNodeCollection allTextNodes = n.SelectNodes("./text()");//select the #text children - if (allTextNodes != null) - { - foreach (HtmlNode tn in allTextNodes) - { - if (tn.PreviousSibling is HtmlTextNode) - { //try to normalize textnodes, accumulating the text. - tn.InnerHtml = tn.PreviousSibling.InnerHtml + tn.InnerHtml; - tn.PreviousSibling.InnerHtml = ""; - } - - //insert span tags around %tag%, trying to avoid doing it twice. - if (reTags.IsMatch(tn.InnerText) && !n.OuterHtml.Contains("placeholder2") && !tn.OuterHtml.Contains("placeholder2")) - { - tn.InnerHtml = reTags.Replace(tn.InnerHtml, "$1"); - } - } - } - } - } - } - - public void RemovePlaceholderSpans () - { - RemovePlaceholderSpans(this.HtmlDoc); - } - - public static void RemovePlaceholderSpans (HtmlDocument htDoc) - { - HtmlNodeCollection placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholder2']"); - if (placeholder2Spans != null) - { - foreach (HtmlNode n in placeholder2Spans) - { - n.ParentNode.RemoveChild(n, true); - } - } - placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholderUnkn']"); - if (placeholder2Spans != null) - { - foreach (HtmlNode n in placeholder2Spans) - { - n.ParentNode.RemoveChild(n, true); - } - } + this.originallyLoadedContent = basic.TemplateBody; } public new string TemplateBody { get { - if (htmlDoc != null) + if (this.htmlDoc != null) { - return htmlDoc.DocumentNode.OuterHtml; + return this.htmlDoc.DocumentNode.OuterHtml; } - else - return base.TemplateBody; + return base.TemplateBody; } set { try { - if (htmlDoc != null) + if (this.htmlDoc != null) { - htmlDoc = new HtmlDocument(); - htmlDoc.LoadHtml(value); + this.htmlDoc = new HtmlDocument(); + this.htmlDoc.LoadHtml(value); } } catch @@ -246,7 +62,7 @@ namespace Swarmops.Logic.Communications if (HtmlDoc.DocumentNode == null || HtmlDoc.DocumentNode.SelectSingleNode("//body") == null) { - this.NormalizeHtml(); + NormalizeHtml(); } return HtmlDoc.DocumentNode.SelectSingleNode("//body"); } @@ -254,10 +70,7 @@ namespace Swarmops.Logic.Communications public string Html { - get - { - return HtmlDoc.DocumentNode.OuterHtml; - } + get { return HtmlDoc.DocumentNode.OuterHtml; } } public string PlainText @@ -268,7 +81,7 @@ namespace Swarmops.Logic.Communications Regex re = new Regex(@"\r{0,1}\n +"); //Templates for plain text are supposedly already in a reasonable
 format
-                if (this.TemplateName.EndsWith("Plain"))
+                if (TemplateName.EndsWith("Plain"))
                     htmlText = re.Replace(htmlText, "\r\n");
                 else
                     htmlText = re.Replace(htmlText, " ");
@@ -366,111 +179,33 @@ namespace Swarmops.Logic.Communications
                 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.
+                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);
             }
-
         }
 
         public HtmlDocument HtmlDoc
         {
             get
             {
-                if (htmlDoc == null)
+                if (this.htmlDoc == null)
                 {
-                    htmlDoc = new HtmlDocument();
+                    this.htmlDoc = new HtmlDocument();
                     try
                     {
-                        htmlDoc.LoadHtml(base.TemplateBody);
+                        this.htmlDoc.LoadHtml(base.TemplateBody);
                     }
                     catch (Exception ex)
                     {
                         throw new Exception("Failed to load Html in MailTemplate", ex);
                     }
                 }
-                return htmlDoc;
+                return this.htmlDoc;
             }
         }
 
-        public HtmlNode GetElementById (string id)
-        {
-            return HtmlDoc.DocumentNode.SelectSingleNode("//*[@id='" + id + "']");
-        }
-
-        public HtmlNodeCollection GetElementsById (string id)
-        {
-            return HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
-        }
-
-        public void RemoveElementById (string id)
-        {
-            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
-            if (nodes != null)
-                foreach (HtmlNode node in nodes)
-                {
-                    node.ParentNode.RemoveChild(node);
-                }
-        }
-
-        public void RemoveEnclosingTag (string id)
-        {
-            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
-            if (nodes != null)
-                foreach (HtmlNode node in nodes)
-                {
-                    node.ParentNode.RemoveChild(node,true);
-                }
-        }
-
-        public bool ReplaceContentById (string id, string InnerHtml)
-        {
-            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);
-                    retval = true;
-                }
-
-            return retval;
-        }
-
-        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(this.TemplateBody, InnerHtml.ToUpper());
-            content = LowerPattern.Replace(content, InnerHtml.ToLower());
-            this.TemplateBody = JustPattern.Replace(content, InnerHtml);
-        }
-
-        private HtmlNode TitleNode ()
-        {
-            //Since NormalizeHtml is expensive try without first
-            HtmlNode titlenode = null;
-            if (this.HtmlDoc != null && this.HtmlDoc.DocumentNode != null)
-                titlenode = this.HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
-
-            if (titlenode == null)
-            {
-                this.NormalizeHtml();
-                titlenode = this.HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
-                if (titlenode == null)
-                {
-                    return null;
-                }
-            }
-
-            titlenode.InnerHtml = titlenode.InnerHtml.Replace("<", "<").Replace(">", ">");
-            return titlenode;
-        }
-  
         public string TemplateTitle
         {
             get
@@ -478,8 +213,7 @@ namespace Swarmops.Logic.Communications
                 HtmlNode titleNode = TitleNode();
                 if (titleNode != null)
                     return titleNode.InnerHtml;
-                else
-                    return "";
+                return "";
             }
             set
             {
@@ -496,38 +230,32 @@ namespace Swarmops.Logic.Communications
                 HtmlNode titleNode = TitleNode();
                 if (titleNode != null)
                     return HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(titleNode.InnerText));
-                else
-                    return "";
+                return "";
             }
-
         }
 
 
         //Returns an empty template to be filled by the caller
         public static MailTemplate None
         {
-            get
-            {
-                return new MailTemplate();
-            }
+            get { return new MailTemplate(); }
         }
 
-
         #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);
         }
 
-        internal static MailTemplate FromBasic (BasicMailTemplate basic)
+        internal static MailTemplate FromBasic(BasicMailTemplate basic)
         {
             MailTemplate templ = new MailTemplate(basic);
             return templ;
         }
 
-        public static List GetAll ()
+        public static List GetAll()
         {
             BasicMailTemplate[] basic = SwarmDb.GetDatabaseForReading().GetAllMailTemplates();
             List resultlist = new List();
@@ -540,40 +268,39 @@ namespace Swarmops.Logic.Communications
         }
 
 
-
-        public static MailTemplate Create (
-                                    string templateName,
-                                    string languageCode,
-                                    string countryCode,
-                                    int organizationId,
-                                    string templateBody)
+        public static MailTemplate Create(
+            string templateName,
+            string languageCode,
+            string countryCode,
+            int organizationId,
+            string templateBody)
         {
             int retId = SwarmDb.GetDatabaseForWriting().SetMailTemplate(0,
-                                                    templateName,
-                                                    languageCode,
-                                                    countryCode,
-                                                    organizationId,
-                                                    templateBody);
+                templateName,
+                languageCode,
+                countryCode,
+                organizationId,
+                templateBody);
             MailTemplateCache.loadCache = true;
 
             return FromIdentity(retId);
         }
 
-        public void Update ()
+        public void Update()
         {
             TemplateBody = TemplateBody; //to make sure the HTMlDoc is taken into account
             SwarmDb.GetDatabaseForWriting().SetMailTemplate(this); // saves changes
             MailTemplateCache.loadCache = true;
-        } 
+        }
 
 
         //----------------------------------------------//
         // 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 MailTemplate.None;
+                return None;
 
             Country country = Country.FromCode(countrycode);
             string lang = country.Culture.Substring(0, 2);
@@ -585,10 +312,10 @@ namespace Swarmops.Logic.Communications
         }
 
 
-        public static MailTemplate FromNameAndOrg (string name, Organization sender)
+        public static MailTemplate FromNameAndOrg(string name, Organization sender)
         {
             if (name == "")
-                return MailTemplate.None;
+                return None;
 
             Country country = sender.DefaultCountry;
             string countrycode = country.Code;
@@ -597,7 +324,273 @@ namespace Swarmops.Logic.Communications
             BasicMailTemplate basic = MailTemplateCache.GetBestMatch(name, lang, countrycode, sender);
             return FromBasic(basic);
         }
+
         #endregion
 
+        public void ResetContent()
+        {
+            this.htmlDoc = null;
+            TemplateBody = this.originallyLoadedContent;
+        }
+
+        public void NormalizeHtml()
+        {
+            //Make sure there is a full html document defined
+            this.htmlDoc = NormalizeHtmlExtracted(HtmlDoc, TemplateName.EndsWith("Plain"));
+        }
+
+        private HtmlDocument NormalizeHtmlExtracted(HtmlDocument htDoc, bool forPlainText)
+        {
+            if (htDoc == null)
+            {
+                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);
+            }
+
+            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");
+            if (bodyNode == null && headNode == null && htmlNode == null)
+                newHtml = "Untitled" + htDoc.DocumentNode.OuterHtml +
+                          "";
+            else if (bodyNode != null && headNode == null && htmlNode == null)
+                newHtml = "Untitled" + bodyNode.OuterHtml + "";
+            else if (bodyNode != null && headNode != null && htmlNode == null)
+                newHtml = "" + bodyNode.OuterHtml + "";
+            else if (headNode == null && htmlNode != null)
+            {
+                headNode = htDoc.CreateElement("head");
+                htmlNode.InsertAfter(headNode, null);
+                titleNode = htDoc.CreateElement("title");
+                titleNode.InnerHtml = "Untitled";
+                headNode.AppendChild(titleNode);
+            }
+            else if (titleNode == null && headNode != null)
+            {
+                titleNode = htDoc.CreateElement("title");
+                titleNode.InnerHtml = "Untitled";
+                headNode.AppendChild(titleNode);
+            }
+
+            if (newHtml != "")
+            {
+                htDoc = new HtmlDocument();
+                htDoc.LoadHtml(newHtml);
+            }
+
+            if (htDoc.DocumentNode == null)
+            {
+                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");
+
+            if (bodyNode2 == null)
+            {
+                throw new Exception("NormalizeHtmlExtracted bodyNode2 is null for " + newHtml);
+            }
+
+            int preIx = 0;
+            for (preIx = 0; preIx < bodyNode2.ChildNodes.Count; ++preIx)
+            {
+                if (bodyNode2.ChildNodes[preIx].Name.ToLower() == "pre") break;
+            }
+
+            if (forPlainText && preIx == bodyNode2.ChildNodes.Count)
+            {
+                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);
+                }
+                string html = htDoc.DocumentNode.OuterHtml;
+                htDoc = new HtmlDocument();
+                htDoc.LoadHtml(html);
+            }
+
+            return htDoc;
+        }
+
+        public void MarkPlaceholderSpans()
+        {
+            MarkPlaceholderSpans(HtmlDoc);
+        }
+
+        public void MarkPlaceholderSpans(Dictionary allowedPlaceholders)
+        {
+            MarkPlaceholderSpans();
+            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 keyLow = key.ToLower();
+                    if (!allowedPlaceholders.ContainsKey(keyLow))
+                    {
+                        string classname = n.GetAttributeValue("class", "");
+                        classname = classname.Replace("placeholder2", "placeholderUnkn");
+                        n.SetAttributeValue("class", classname);
+                    }
+                    else if (allowedPlaceholders[keyLow] != key
+                             && allowedPlaceholders[keyLow].ToUpper() != key
+                             && allowedPlaceholders[keyLow].ToLower() != key)
+                    {
+                        n.InnerHtml = "%" + allowedPlaceholders[keyLow] + "%";
+                    }
+                }
+            }
+        }
+
+        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
+            if (allWithTextNodes != null)
+            {
+                foreach (HtmlNode n in allWithTextNodes)
+                {
+                    HtmlNodeCollection allTextNodes = n.SelectNodes("./text()"); //select the #text children
+                    if (allTextNodes != null)
+                    {
+                        foreach (HtmlNode tn in allTextNodes)
+                        {
+                            if (tn.PreviousSibling is HtmlTextNode)
+                            {
+                                //try to normalize textnodes, accumulating the text.
+                                tn.InnerHtml = tn.PreviousSibling.InnerHtml + tn.InnerHtml;
+                                tn.PreviousSibling.InnerHtml = "";
+                            }
+
+                            //insert span tags around %tag%, trying to avoid doing it twice.
+                            if (reTags.IsMatch(tn.InnerText) && !n.OuterHtml.Contains("placeholder2") &&
+                                !tn.OuterHtml.Contains("placeholder2"))
+                            {
+                                tn.InnerHtml = reTags.Replace(tn.InnerHtml, "$1");
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        public void RemovePlaceholderSpans()
+        {
+            RemovePlaceholderSpans(HtmlDoc);
+        }
+
+        public static void RemovePlaceholderSpans(HtmlDocument htDoc)
+        {
+            HtmlNodeCollection placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholder2']");
+            if (placeholder2Spans != null)
+            {
+                foreach (HtmlNode n in placeholder2Spans)
+                {
+                    n.ParentNode.RemoveChild(n, true);
+                }
+            }
+            placeholder2Spans = htDoc.DocumentNode.SelectNodes("//*[@class='placeholderUnkn']");
+            if (placeholder2Spans != null)
+            {
+                foreach (HtmlNode n in placeholder2Spans)
+                {
+                    n.ParentNode.RemoveChild(n, true);
+                }
+            }
+        }
+
+        public HtmlNode GetElementById(string id)
+        {
+            return HtmlDoc.DocumentNode.SelectSingleNode("//*[@id='" + id + "']");
+        }
+
+        public HtmlNodeCollection GetElementsById(string id)
+        {
+            return HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+        }
+
+        public void RemoveElementById(string id)
+        {
+            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            if (nodes != null)
+                foreach (HtmlNode node in nodes)
+                {
+                    node.ParentNode.RemoveChild(node);
+                }
+        }
+
+        public void RemoveEnclosingTag(string id)
+        {
+            HtmlNodeCollection nodes = HtmlDoc.DocumentNode.SelectNodes("//*[@id='" + id + "']");
+            if (nodes != null)
+                foreach (HtmlNode node in nodes)
+                {
+                    node.ParentNode.RemoveChild(node, true);
+                }
+        }
+
+        public bool ReplaceContentById(string id, string InnerHtml)
+        {
+            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);
+                    retval = true;
+                }
+
+            return retval;
+        }
+
+        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);
+        }
+
+        private HtmlNode TitleNode()
+        {
+            //Since NormalizeHtml is expensive try without first
+            HtmlNode titlenode = null;
+            if (HtmlDoc != null && HtmlDoc.DocumentNode != null)
+                titlenode = HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
+
+            if (titlenode == null)
+            {
+                NormalizeHtml();
+                titlenode = HtmlDoc.DocumentNode.SelectSingleNode("//head/title");
+                if (titlenode == null)
+                {
+                    return null;
+                }
+            }
+
+            titlenode.InnerHtml = titlenode.InnerHtml.Replace("<", "<").Replace(">", ">");
+            return titlenode;
+        }
     }
 }
\ No newline at end of file
diff --git a/Logic/Communications/NewsletterFeed.cs b/Logic/Communications/NewsletterFeed.cs
index 2314abce..240dca62 100644
--- a/Logic/Communications/NewsletterFeed.cs
+++ b/Logic/Communications/NewsletterFeed.cs
@@ -20,17 +20,17 @@ namespace Swarmops.Logic.Communications
 
         #region Creation and Construction
 
-        private NewsletterFeed (BasicNewsletterFeed basic)
+        private NewsletterFeed(BasicNewsletterFeed basic)
             : base(basic)
         {
         }
 
-        public static NewsletterFeed FromIdentity (int identity)
+        public static NewsletterFeed FromIdentity(int identity)
         {
-            return FromBasic(SwarmDb.GetDatabaseForReading().GetNewsletterFeed((int)identity));
+            return FromBasic(SwarmDb.GetDatabaseForReading().GetNewsletterFeed(identity));
         }
 
-        public static NewsletterFeed FromBasic (BasicNewsletterFeed basic)
+        public static NewsletterFeed FromBasic(BasicNewsletterFeed basic)
         {
             return new NewsletterFeed(basic);
         }
diff --git a/Logic/Communications/NewsletterFeeds.cs b/Logic/Communications/NewsletterFeeds.cs
index 0f69827b..92d53982 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)
         {
-            var result = new NewsletterFeeds();
+            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 d2a130fd..7e8433ac 100644
--- a/Logic/Communications/OutboundComm.cs
+++ b/Logic/Communications/OutboundComm.cs
@@ -11,178 +11,21 @@ using Swarmops.Logic.Swarm;
 
 namespace Swarmops.Logic.Communications
 {
-    public class OutboundComm: BasicOutboundComm
+    public class OutboundComm : BasicOutboundComm
     {
-        private OutboundComm (BasicOutboundComm basic): base (basic)
+        private OutboundComm(BasicOutboundComm basic) : base(basic)
         {
             // private ctor
         }
 
-        public static OutboundComm FromBasic (BasicOutboundComm basic)
-        {
-            return new OutboundComm(basic);
-        }
-
-        public static OutboundComm FromIdentity(int outboundCommId)
-        {
-            return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundComm(outboundCommId));
-        }
-
-        public static OutboundComm FromIdentityAggressive(int outboundCommId)
-        {
-            return FromBasic(SwarmDb.GetDatabaseForWriting().GetOutboundComm(outboundCommId));
-        }
-
-        public static OutboundComm Create(Person sender, Person from, Organization organization, CommResolverClass resolverClass, string recipientDataXml, CommTransmitterClass transmitterClass, string payloadXml, OutboundCommPriority priority)
-        {
-            string resolverClassString = string.Empty;
-            if (resolverClass != CommResolverClass.Unknown)
-            {
-                resolverClassString = resolverClass.ToString();
-            }
-
-            string transmitterClassString = string.Empty;
-            if (transmitterClass != CommTransmitterClass.Unknown)
-            {
-                transmitterClassString = "Swarmops.Utility.Communications." + transmitterClass.ToString();
-            }
-
-            return Create(sender, from, organization, resolverClassString, recipientDataXml, transmitterClassString,
-                          payloadXml, priority);
-        }
-
-        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,
-                                                                           organization != null? organization.Identity: 0, resolverClassString,
-                                                                           recipientDataXml ?? string.Empty, transmitterClassString,
-                                                                           payloadXml, priority);
-
-            return FromIdentityAggressive(newId);
-        }
-
-
-        public static OutboundComm CreateNotification (Organization organization, NotificationResource notification)
-        {
-            return CreateNotification(organization, notification.ToString());
-        }
-
-
-        public static OutboundComm CreateNotification (Organization organization, string notificationResourceString)
-        {
-            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,
-                                                    CommTransmitterClass.CommsTransmitterMail,
-                                                    new PayloadEnvelope(new NotificationPayload(notificationResourceString)).ToXml(),
-                                                    OutboundCommPriority.Low);
-
-            foreach (Person person in recipients)
-            {
-                comm.AddRecipient(person);
-            }
-
-            comm.Resolved = true;
-
-            return comm;
-        }
-
-
-        public static OutboundComm CreateNotificationAttestationNeeded(FinancialAccount budget, Person concernedPerson, string supplier, double amountRequested, string purpose, NotificationResource notification)
-        {
-            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);
-            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,
-                                                    CommTransmitterClass.CommsTransmitterMail,
-                                                    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
-            }
-            else
-            {
-                comm.AddRecipient(budget.Owner);
-            }
-
-            comm.Resolved = true;
-
-            return comm;
-
-        }
-
-
-        public static OutboundComm CreateNotificationFinancialValidationNeeded (Organization organization, double amountRequested, NotificationResource notification)
-        {
-            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);
-
-            OutboundComm comm = OutboundComm.Create(null, null, organization, CommResolverClass.Unknown, null,
-                                                    CommTransmitterClass.CommsTransmitterMail,
-                                                    new PayloadEnvelope(payload).ToXml(),
-                                                    OutboundCommPriority.Low);
-
-            People validators = organization.ValidatingPeople;
-
-            foreach (Person validator in validators)
-            {
-                comm.AddRecipient(validator);
-            }
-
-            comm.Resolved = true;
-
-            return comm;
-
-        }
-
-
-        public static OutboundComm CreateNotificationOfFinancialValidation(FinancialAccount budget, Person concernedPerson, double amountRequested, string purpose, NotificationResource notification)
-        {
-            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);
-            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,
-                                                    CommTransmitterClass.CommsTransmitterMail,
-                                                    new PayloadEnvelope(payload).ToXml(),
-                                                    OutboundCommPriority.Low);
-
-            comm.AddRecipient(concernedPerson);
-
-            comm.Resolved = true;
-
-            return comm;
-
-        }
-
         public new bool Resolved
         {
             get { return base.Resolved; }
             set
             {
-                if (!base.Resolved && value == true)
+                if (!base.Resolved && value)
                 {
-                    SwarmDb.GetDatabaseForWriting().SetOutboundCommResolved(this.Identity);
+                    SwarmDb.GetDatabaseForWriting().SetOutboundCommResolved(Identity);
                     base.Resolved = true;
                 }
                 else
@@ -192,17 +35,6 @@ namespace Swarmops.Logic.Communications
             }
         }
 
-
-        public void AddRecipient (Person person)
-        {
-            if (person == null)
-            {
-                throw new ArgumentNullException("Recipient cannot be null.");
-            }
-
-            SwarmDb.GetDatabaseForWriting().CreateOutboundCommRecipient(this.Identity, person.Identity);
-        }
-
         public OutboundCommRecipients Recipients
         {
             get { return OutboundCommRecipients.ForOutboundComm(this); }
@@ -215,7 +47,7 @@ namespace Swarmops.Logic.Communications
             {
                 if (base.Open && value == false)
                 {
-                    SwarmDb.GetDatabaseForWriting().SetOutboundCommClosed(this.Identity);
+                    SwarmDb.GetDatabaseForWriting().SetOutboundCommClosed(Identity);
                     base.Open = false;
                 }
                 else
@@ -225,18 +57,192 @@ namespace Swarmops.Logic.Communications
             }
         }
 
-        public void StartTransmission()
+        public static OutboundComm FromBasic(BasicOutboundComm basic)
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommTransmissionStart(this.Identity);
+            return new OutboundComm(basic);
         }
 
+        public static OutboundComm FromIdentity(int outboundCommId)
+        {
+            return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundComm(outboundCommId));
+        }
+
+        public static OutboundComm FromIdentityAggressive(int outboundCommId)
+        {
+            return FromBasic(SwarmDb.GetDatabaseForWriting().GetOutboundComm(outboundCommId));
+        }
+
+        public static OutboundComm Create(Person sender, Person from, Organization organization,
+            CommResolverClass resolverClass, string recipientDataXml, CommTransmitterClass transmitterClass,
+            string payloadXml, OutboundCommPriority priority)
+        {
+            string resolverClassString = string.Empty;
+            if (resolverClass != CommResolverClass.Unknown)
+            {
+                resolverClassString = resolverClass.ToString();
+            }
+
+            string transmitterClassString = string.Empty;
+            if (transmitterClass != CommTransmitterClass.Unknown)
+            {
+                transmitterClassString = "Swarmops.Utility.Communications." + transmitterClass;
+            }
+
+            return Create(sender, from, organization, resolverClassString, recipientDataXml, transmitterClassString,
+                payloadXml, priority);
+        }
+
+        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,
+                    organization != null ? organization.Identity : 0, resolverClassString,
+                    recipientDataXml ?? string.Empty, transmitterClassString,
+                    payloadXml, priority);
+
+            return FromIdentityAggressive(newId);
+        }
+
+
+        public static OutboundComm CreateNotification(Organization organization, NotificationResource notification)
+        {
+            return CreateNotification(organization, notification.ToString());
+        }
+
+
+        public static OutboundComm CreateNotification(Organization organization, string notificationResourceString)
+        {
+            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,
+                CommTransmitterClass.CommsTransmitterMail,
+                new PayloadEnvelope(new NotificationPayload(notificationResourceString)).ToXml(),
+                OutboundCommPriority.Low);
+
+            foreach (Person person in recipients)
+            {
+                comm.AddRecipient(person);
+            }
+
+            comm.Resolved = true;
+
+            return comm;
+        }
+
+
+        public static OutboundComm CreateNotificationAttestationNeeded(FinancialAccount budget, Person concernedPerson,
+            string supplier, double amountRequested, string purpose, NotificationResource notification)
+        {
+            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);
+            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,
+                CommTransmitterClass.CommsTransmitterMail,
+                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
+            }
+            else
+            {
+                comm.AddRecipient(budget.Owner);
+            }
+
+            comm.Resolved = true;
+
+            return comm;
+        }
+
+
+        public static OutboundComm CreateNotificationFinancialValidationNeeded(Organization organization,
+            double amountRequested, NotificationResource notification)
+        {
+            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);
+
+            OutboundComm comm = OutboundComm.Create(null, null, organization, CommResolverClass.Unknown, null,
+                CommTransmitterClass.CommsTransmitterMail,
+                new PayloadEnvelope(payload).ToXml(),
+                OutboundCommPriority.Low);
+
+            People validators = organization.ValidatingPeople;
+
+            foreach (Person validator in validators)
+            {
+                comm.AddRecipient(validator);
+            }
+
+            comm.Resolved = true;
+
+            return comm;
+        }
+
+
+        public static OutboundComm CreateNotificationOfFinancialValidation(FinancialAccount budget,
+            Person concernedPerson, double amountRequested, string purpose, NotificationResource notification)
+        {
+            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);
+            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,
+                CommTransmitterClass.CommsTransmitterMail,
+                new PayloadEnvelope(payload).ToXml(),
+                OutboundCommPriority.Low);
+
+            comm.AddRecipient(concernedPerson);
+
+            comm.Resolved = true;
+
+            return comm;
+        }
+
+
+        public void AddRecipient(Person person)
+        {
+            if (person == null)
+            {
+                throw new ArgumentNullException("Recipient cannot be null.");
+            }
+
+            SwarmDb.GetDatabaseForWriting().CreateOutboundCommRecipient(Identity, person.Identity);
+        }
+
+        public void StartTransmission()
+        {
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommTransmissionStart(Identity);
+        }
     }
 
     public enum CommResolverClass
     {
         Unknown = 0,
         Test_Foo_Bar
-
     }
 
     public enum CommTransmitterClass
@@ -244,4 +250,4 @@ namespace Swarmops.Logic.Communications
         Unknown = 0,
         CommsTransmitterMail
     }
-}
+}
\ No newline at end of file
diff --git a/Logic/Communications/OutboundCommRecipient.cs b/Logic/Communications/OutboundCommRecipient.cs
index 7ee687da..de98f6e8 100644
--- a/Logic/Communications/OutboundCommRecipient.cs
+++ b/Logic/Communications/OutboundCommRecipient.cs
@@ -4,26 +4,26 @@ using Swarmops.Logic.Swarm;
 
 namespace Swarmops.Logic.Communications
 {
-    public class OutboundCommRecipient: BasicOutboundCommRecipient
+    public class OutboundCommRecipient : BasicOutboundCommRecipient
     {
-        private OutboundCommRecipient(BasicOutboundCommRecipient basic): base (basic)
+        private OutboundCommRecipient(BasicOutboundCommRecipient basic) : base(basic)
         {
             // private ctor
         }
 
-        public static OutboundCommRecipient FromBasic (BasicOutboundCommRecipient basic)
-        {
-            return new OutboundCommRecipient(basic);
-        }
-
         public Person Person
         {
             get { return Person.FromIdentity(base.PersonId); }
         }
 
+        public static OutboundCommRecipient FromBasic(BasicOutboundCommRecipient basic)
+        {
+            return new OutboundCommRecipient(basic);
+        }
+
         public void CloseSuccess()
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientClosed(this.Identity);
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientClosed(Identity);
 
             base.Success = true;
             base.Open = false;
@@ -31,7 +31,7 @@ namespace Swarmops.Logic.Communications
 
         public void CloseFailed(string failReason)
         {
-            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientFailed(this.Identity, failReason);
+            SwarmDb.GetDatabaseForWriting().SetOutboundCommRecipientFailed(Identity, failReason);
 
             base.Success = false;
             base.Open = false;
@@ -39,4 +39,4 @@ namespace Swarmops.Logic.Communications
 
         // TODO: CloseSuccess, CloseFail
     }
-}
+}
\ No newline at end of file
diff --git a/Logic/Communications/OutboundCommRecipients.cs b/Logic/Communications/OutboundCommRecipients.cs
index 3f168cdb..5d19eda6 100644
--- a/Logic/Communications/OutboundCommRecipients.cs
+++ b/Logic/Communications/OutboundCommRecipients.cs
@@ -4,11 +4,12 @@ using Swarmops.Logic.Support;
 
 namespace Swarmops.Logic.Communications
 {
-    public class OutboundCommRecipients: PluralBase
+    public class OutboundCommRecipients :
+        PluralBase
     {
-        public static OutboundCommRecipients ForOutboundComm (OutboundComm comm)
+        public static OutboundCommRecipients ForOutboundComm(OutboundComm 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 b1eedac6..fff06e74 100644
--- a/Logic/Communications/OutboundCommTransmitException.cs
+++ b/Logic/Communications/OutboundCommTransmitException.cs
@@ -3,20 +3,22 @@
 namespace Swarmops.Logic.Communications
 {
     /// 
-    /// This exception is thrown if transmission of an OutboundComm fails (for a specific person). The description should NOT contain personal data or anything that varies with person/time.
+    ///     This exception is thrown if transmission of an OutboundComm fails (for a specific person). The description should
+    ///     NOT contain personal data or anything that varies with person/time.
     /// 
-    public class OutboundCommTransmitException: Exception
+    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;
         }
 
         public string Description { get; set; }
     }
-}
+}
\ No newline at end of file
diff --git a/Logic/Communications/OutboundComms.cs b/Logic/Communications/OutboundComms.cs
index 6ee9d699..c98e03f3 100644
--- a/Logic/Communications/OutboundComms.cs
+++ b/Logic/Communications/OutboundComms.cs
@@ -4,11 +4,11 @@ using Swarmops.Logic.Support;
 
 namespace Swarmops.Logic.Communications
 {
-    public class OutboundComms: PluralBase
+    public class OutboundComms : PluralBase
     {
         public static OutboundComms GetOpen()
         {
             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 2125f1d5..8f65870a 100644
--- a/Logic/Communications/OutboundMail.cs
+++ b/Logic/Communications/OutboundMail.cs
@@ -21,20 +21,20 @@ namespace Swarmops.Logic.Communications
 
 
         /// 
-        /// Private constructor from basic object
+        ///     Private constructor from basic object
         /// 
-        private OutboundMail (BasicOutboundMail basic)
+        private OutboundMail(BasicOutboundMail basic)
             : base(basic)
         {
             // remember titel for templated mail, it is the name of the template.
             if (MailType > 0)
-                templateName = basic.Title;
+                this.templateName = basic.Title;
         }
 
         /// 
-        /// Creation from basic object - internal to PirateWeb.Logic
+        ///     Creation from basic object - internal to PirateWeb.Logic
         /// 
-        internal static OutboundMail FromBasic (BasicOutboundMail basic)
+        internal static OutboundMail FromBasic(BasicOutboundMail basic)
         {
             if (basic == null)
             {
@@ -46,95 +46,97 @@ namespace Swarmops.Logic.Communications
 
 
         /// 
-        /// Retrieves the OutboundMail with a certain Identity
+        ///     Retrieves the OutboundMail with a certain Identity
         /// 
         /// 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));
         }
 
 
-        public static OutboundMail Create (Person author, string title,
-                                           string body, int mailPriority, int mailType,
-                                           Organization organization, Geography geography)
+        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,
-                           geography, DateTime.Now);
+                geography, DateTime.Now);
         }
 
-        public static OutboundMail Create (Person author, string title,
-                                           string body, int mailPriority, int mailType,
-                                           Organization organization, Geography geography, DateTime releaseDateTime)
+        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,
-                                                                         body, mailPriority, mailType,
-                                                                         geography.Identity, organization.Identity,
-                                                                         releaseDateTime));
+                FromIdentity(SwarmDb.GetDatabaseForWriting()
+                    .CreateOutboundMail(MailAuthorType.Person, author.Identity, title,
+                        body, mailPriority, mailType,
+                        geography.Identity, organization.Identity,
+                        releaseDateTime));
         }
 
 
         /// 
-        /// Creates an unusable OutboundMail. Used for rendering previews - ONLY.
-        /// (this version, with the ignored priority param is for backward compability)
+        ///     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, int mailType,
-                                               Organization organization, Geography geography)
+        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);
         }
 
 
         /// 
-        /// Creates an unusable OutboundMail. Used for rendering previews - ONLY.
+        ///     Creates an unusable OutboundMail. Used for rendering previews - ONLY.
         /// 
-        public static OutboundMail CreateFake (Person author, string title,
-                                               string body, int mailType,
-                                               Organization organization, Geography geography)
+        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,
-                                                     body, 99, mailType, organization.Identity,
-                                                     geography.Identity, DateTime.Now,
-                                                     DateTime.Now, false, false, false, DateTime.MinValue,
-                                                     DateTime.MinValue, DateTime.MinValue, 0, 0, 0));
+                body, 99, mailType, organization.Identity,
+                geography.Identity, DateTime.Now,
+                DateTime.Now, false, false, false, DateTime.MinValue,
+                DateTime.MinValue, DateTime.MinValue, 0, 0, 0));
         }
 
         /// 
-        /// Creates an OutboundMail with a "functional" author. 
+        ///     Creates an OutboundMail with a "functional" author.
         /// 
-        public static OutboundMail CreateFunctional (MailAuthorType authorType, string title,
-                                           string body, int mailPriority, int mailType,
-                                           int organizationId, int geographyId, DateTime releaseDateTime)
+        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,
-                                           body, mailPriority, mailType, geographyId,
-                                           organizationId, releaseDateTime);
+                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,
-                                                    body, mailPriority, mailType, organizationId,
-                                                    geographyId, DateTime.Now,
-                                                    releaseDateTime));
+                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(this.AuthorType, AuthorPersonId, Title,
-                             Body, MailPriority, MailType, GeographyId, OrganizationId, afterTime, recipientId);
+                = SwarmDb.GetDatabaseForReading().GetDuplicateOutboundMail(AuthorType, AuthorPersonId, Title,
+                    Body, MailPriority, MailType, GeographyId, OrganizationId, afterTime, recipientId);
             foreach (BasicOutboundMail mail in mails)
             {
                 retList.Add(FromBasic(mail));
             }
 
-            return retList; ;
+            return retList;
+            ;
         }
 
-        public static OutboundMail GetFirstUnresolved ()
+        public static OutboundMail GetFirstUnresolved()
         {
             BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnresolvedOutboundMail(1);
 
@@ -146,7 +148,7 @@ namespace Swarmops.Logic.Communications
             return null;
         }
 
-        public static OutboundMail GetFirstUnprocessed ()
+        public static OutboundMail GetFirstUnprocessed()
         {
             BasicOutboundMail[] mails = SwarmDb.GetDatabaseForReading().GetTopUnprocessedOutboundMail(1);
 
@@ -176,9 +178,10 @@ namespace Swarmops.Logic.Communications
         {
             get
             {
-                if (this.AuthorType != MailAuthorType.Person)
+                if (AuthorType != MailAuthorType.Person)
                 {
-                    throw new InvalidOperationException("OutboundMail.Author is not a valid property when OutboundMail.AuthorType isn't MailAuthorType.Person.");
+                    throw new InvalidOperationException(
+                        "OutboundMail.Author is not a valid property when OutboundMail.AuthorType isn't MailAuthorType.Person.");
                 }
 
                 if (this.author == null)
@@ -218,34 +221,31 @@ namespace Swarmops.Logic.Communications
 
         public string TemplateName
         {
-            get
-            {
-                return templateName;
-            }
+            get { return this.templateName; }
         }
-        #endregion
 
+        #endregion
 
         #region Recipient access and manipulation
 
-        public OutboundMailRecipients GetNextRecipientBatch (int batchSize)
+        public OutboundMailRecipients GetNextRecipientBatch(int batchSize)
         {
             return
                 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);
         }
 
-        public void AddRecipient (Reporter person)
+        public void AddRecipient(Reporter person)
         {
             AddReporterRecipient(person.Identity);
         }
 
-        public void AddRecipients (int[] personIds, bool asOfficers)
+        public void AddRecipients(int[] personIds, bool asOfficers)
         {
             foreach (int personId in personIds)
             {
@@ -253,7 +253,7 @@ namespace Swarmops.Logic.Communications
             }
         }
 
-        public void AddReporterRecipients (int[] personIds)
+        public void AddReporterRecipients(int[] personIds)
         {
             foreach (int personId in personIds)
             {
@@ -261,50 +261,55 @@ namespace Swarmops.Logic.Communications
             }
         }
 
-        public void AddRecipient (int personId, bool asOfficer)
+        public void AddRecipient(int personId, bool asOfficer)
         {
-            SwarmDb.GetDatabaseForWriting().CreateOutboundMailRecipient(Identity, personId, asOfficer, (int)OutboundMailRecipient.RecipientType.Person);
+            SwarmDb.GetDatabaseForWriting()
+                .CreateOutboundMailRecipient(Identity, personId, asOfficer,
+                    (int) OutboundMailRecipient.RecipientType.Person);
         }
 
-        private void AddReporterRecipient (int identity)
+        private void AddReporterRecipient(int identity)
         {
-            SwarmDb.GetDatabaseForWriting().CreateOutboundMailRecipient(Identity, identity, false, (int)OutboundMailRecipient.RecipientType.Reporter);
+            SwarmDb.GetDatabaseForWriting()
+                .CreateOutboundMailRecipient(Identity, identity, false,
+                    (int) OutboundMailRecipient.RecipientType.Reporter);
         }
+
         #endregion
 
         #region Status changers
 
-        public void SetReadyForPickup ()
+        public void SetReadyForPickup()
         {
             SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup(Identity);
             base.ReadyForPickup = true;
         }
 
-        public void SetResolved ()
+        public void SetResolved()
         {
             SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved(Identity);
             base.Resolved = true;
         }
 
-        public void SetProcessed ()
+        public void SetProcessed()
         {
             SwarmDb.GetDatabaseForWriting().SetOutboundMailProcessed(Identity);
             base.Processed = true;
         }
 
-        public void SetRecipientCount (int recipientCount)
+        public void SetRecipientCount(int recipientCount)
         {
             SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount(Identity, recipientCount);
             base.RecipientCount = recipientCount;
         }
 
-        public void IncrementSuccesses ()
+        public void IncrementSuccesses()
         {
             SwarmDb.GetDatabaseForWriting().IncrementOutboundMailSuccesses(Identity);
             base.RecipientsSuccess++;
         }
 
-        public void IncrementFailures ()
+        public void IncrementFailures()
         {
             SwarmDb.GetDatabaseForWriting().IncrementOutboundMailFailures(Identity);
             base.RecipientsFail++;
@@ -315,15 +320,14 @@ namespace Swarmops.Logic.Communications
         #region Methods and Manipulation
 
         /// 
-        /// Renders the mail for a specific recipient, in text.
+        ///     Renders the mail for a specific recipient, in text.
         /// 
         /// 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)
+            if (MailType == (int) TypedMailTemplate.TemplateType.None)
             {
                 return Body;
             }
@@ -334,24 +338,22 @@ namespace Swarmops.Logic.Communications
 
 
         /// 
-        /// Renders the mail for a specific recipient, in HTML.
+        ///     Renders the mail for a specific recipient, in HTML.
         /// 
         /// 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)
+            if (MailType == (int) TypedMailTemplate.TemplateType.None)
             {
                 Regex reHtmlType = new Regex(@"()", RegexOptions.IgnoreCase);
 
                 if (reHtmlType.IsMatch(Body))
                     return Body;
-                else
-                    return "
" + Body + "
"; + return "
" + Body + "
"; } // (If there is a template, the body contains the serialized placeholder values) @@ -359,59 +361,63 @@ namespace Swarmops.Logic.Communications } /// - /// Renders the mail for a specific recipient - /// + /// Renders the mail for a specific recipient /// /// The person to render for. /// 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 - template.InsertAllPlaceHoldersToTemplate(); // Make all replacements - this.Title = template.Template.TemplateTitleText; // Get the resulting title + 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); } } - private TypedMailTemplate PrepareTemplate (string culture, bool renderText) + private TypedMailTemplate PrepareTemplate(string culture, bool renderText) { TypedMailTemplate template = null; if (renderText) { - if (templatePlain == null) + if (this.templatePlain == null) { - templatePlain = TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType( MailType) + "Plain"); - templatePlain.Initialize(culture.Substring(3), Organization.Identity, this, (renderText ? "Plain" : "")); - templatePlain.PreparePlaceholders(); + this.templatePlain = + TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType(MailType) + "Plain"); + this.templatePlain.Initialize(culture.Substring(3), Organization.Identity, this, + (renderText ? "Plain" : "")); + this.templatePlain.PreparePlaceholders(); } else - { //reuse the template, just reset the html to the saved version before replacements - templatePlain.Template.ResetContent(); + { + //reuse the template, just reset the html to the saved version before replacements + this.templatePlain.Template.ResetContent(); } - template = templatePlain; + template = this.templatePlain; } else { - if (templateHtml == null) + if (this.templateHtml == null) { - templateHtml = TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType(MailType)); - templateHtml.Initialize(culture.Substring(3), Organization.Identity, this, (renderText ? "Plain" : "")); - templateHtml.PreparePlaceholders(); + this.templateHtml = TypedMailTemplate.FromName(TypedMailTemplate.GetNameFromMailType(MailType)); + this.templateHtml.Initialize(culture.Substring(3), Organization.Identity, this, + (renderText ? "Plain" : "")); + this.templateHtml.PreparePlaceholders(); } else - { //reuse the template, just reset the html to the saved version before replacements - templateHtml.Template.ResetContent(); + { + //reuse the template, just reset the html to the saved version before replacements + this.templateHtml.Template.ResetContent(); } - template = templateHtml; + template = this.templateHtml; } return template; @@ -430,19 +436,18 @@ namespace Swarmops.Logic.Communications public static readonly int PriorityNormal = 50; public static readonly int PriorityLow = 70; public static readonly int PriorityLowest = 90; + private static readonly object lockTemplates = new object(); + private readonly string templateName = ""; private Person author; - private Organization organization; private Geography geography; + private Organization organization; //If used in a multithreaded scenario, the cached templates need to be locked while rendering. - private static object lockTemplates = new object(); - private TypedMailTemplate templateHtml = null; //Cached template to use for plain rendering - private TypedMailTemplate templatePlain = null;//Cached template to use for html rendering + private TypedMailTemplate templateHtml; //Cached template to use for plain rendering + private TypedMailTemplate templatePlain; //Cached template to use for html rendering // keeps track of the Title of the outbound mail as it were when loaded from DB - private string templateName = ""; - } } \ No newline at end of file diff --git a/Logic/Communications/OutboundMailRecipient.cs b/Logic/Communications/OutboundMailRecipient.cs index 7184bec8..bd151f1d 100644 --- a/Logic/Communications/OutboundMailRecipient.cs +++ b/Logic/Communications/OutboundMailRecipient.cs @@ -8,16 +8,22 @@ namespace Swarmops.Logic.Communications { public class OutboundMailRecipient : BasicOutboundMailRecipient { + public enum RecipientType + { + Person, + Reporter + } + private readonly OutboundMail outboundMail; private IEmailPerson person; - private OutboundMailRecipient () + private OutboundMailRecipient() : base(null) { // Never construct this way } - private OutboundMailRecipient (BasicOutboundMailRecipient basic, OutboundMail outboundMail) + private OutboundMailRecipient(BasicOutboundMailRecipient basic, OutboundMail outboundMail) : base(basic) { this.outboundMail = outboundMail; @@ -44,13 +50,42 @@ namespace Swarmops.Logic.Communications get { return this.outboundMail; } } - public enum RecipientType { Person, Reporter } + public IEmailPerson EmailPerson // Cache the Person object + { + get + { + CachePerson(); + return this.person; + } + } - private void CachePerson () + public Person Person // Cache the Person object + { + get + { + CachePerson(); + if (this.person is Person) + return (Person) this.person; + return null; + } + } + + public Reporter Reporter // Cache the Person object + { + get + { + CachePerson(); + if (this.person is Reporter) + return (Reporter) this.person; + return null; + } + } + + private void CachePerson() { if (this.person == null) { - RecipientType type = (RecipientType)base.PersonType; + RecipientType type = (RecipientType) base.PersonType; if (type == RecipientType.Person) { this.person = Person.FromIdentity(base.PersonId); @@ -62,59 +97,27 @@ namespace Swarmops.Logic.Communications } } - public IEmailPerson EmailPerson // Cache the Person object - { - get - { - CachePerson(); - return this.person; - } - } - public Person Person // Cache the Person object - { - get - { - CachePerson(); - if (this.person is Person) - return (Person)this.person; - else - return null; - } - } - - public Reporter Reporter // Cache the Person object - { - get - { - CachePerson(); - if (this.person is Reporter) - return (Reporter)this.person; - else - return null; - } - } - - internal static OutboundMailRecipient FromBasic (BasicOutboundMailRecipient basic, OutboundMail outboundMail) + internal static OutboundMailRecipient FromBasic(BasicOutboundMailRecipient basic, OutboundMail 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); } - public void Delete () + public void Delete() { SwarmDb.GetDatabaseForWriting().DeleteOutboundMailRecipient(Identity); } diff --git a/Logic/Communications/OutboundMailRecipients.cs b/Logic/Communications/OutboundMailRecipients.cs index 34850b92..fe45b416 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) { - var result = new OutboundMailRecipients(); + 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 eea565fc..ba5b59d8 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) { - var result = new OutboundMails(); + 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 e7759dc4..fab2d1ad 100644 --- a/Logic/Communications/PaperLetter.cs +++ b/Logic/Communications/PaperLetter.cs @@ -8,14 +8,14 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications { - public class PaperLetter: BasicPaperLetter + public class PaperLetter : BasicPaperLetter { - public static PaperLetter Create (Person creator, Organization organization, string fromName, - string[] replyAddressLines, DateTime receivedDate, Person recipient, RoleType recipientRole, + 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, - recipient.Identity, recipientRole, personal); + recipient.Identity, recipientRole, personal); } @@ -24,32 +24,32 @@ namespace Swarmops.Logic.Communications { return FromIdentity(SwarmDb.GetDatabaseForWriting(). CreatePaperLetter(organizationId, fromName, String.Join("|", replyAddressLines), - receivedDate, toPersonId, toPersonInRole, personal, creatingPersonId)); + receivedDate, toPersonId, toPersonInRole, personal, creatingPersonId)); } - public static PaperLetter FromIdentity (int paperLetterId) + public static PaperLetter FromIdentity(int paperLetterId) { return FromBasic(SwarmDb.GetDatabaseForReading().GetPaperLetter(paperLetterId)); } - public static PaperLetter FromBasic (BasicPaperLetter basic) + public static PaperLetter FromBasic(BasicPaperLetter 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 Support.Documents.ForObject(this); } + get { return Documents.ForObject(this); } } #pragma warning disable 169 // ReSharper disable InconsistentNaming - private new string ReplyAddress; // hides ReplyAddress in base, quite on purpose + private new string ReplyAddress; // hides ReplyAddress in base, quite on purpose // ReSharper restore InconsistentNaming #pragma warning restore 169 @@ -70,6 +70,5 @@ namespace Swarmops.Logic.Communications return Person.FromIdentity(base.ToPersonId); } } - } -} +} \ No newline at end of file diff --git a/Logic/Communications/PaperLetters.cs b/Logic/Communications/PaperLetters.cs index 857e2b2f..b179a98d 100644 --- a/Logic/Communications/PaperLetters.cs +++ b/Logic/Communications/PaperLetters.cs @@ -6,14 +6,14 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications { - public class PaperLetters: List + public class PaperLetters : List { 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. - PaperLetters result = new PaperLetters() { Capacity = (basicArray.Length * 11 / 10) }; + PaperLetters result = new PaperLetters {Capacity = (basicArray.Length*11/10)}; foreach (BasicPaperLetter basic in basicArray) { @@ -23,24 +23,24 @@ namespace Swarmops.Logic.Communications return result; } - public static PaperLetters ForOrganization (Organization organization) + public static PaperLetters ForOrganization(Organization organization) { return ForOrganization(organization.Identity); } - public static PaperLetters ForOrganization (int organizationId) + public static PaperLetters ForOrganization(int organizationId) { return FromArray(SwarmDb.GetDatabaseForReading().GetPaperLettersForOrganization(organizationId)); } - public static PaperLetters ForPerson (Person person) + public static PaperLetters ForPerson(Person person) { return ForPerson(person.Identity); } - public static PaperLetters ForPerson (int personId) + public static PaperLetters ForPerson(int 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 6cda9355..dae2ce35 100644 --- a/Logic/Communications/PhoneMessageReceiver.cs +++ b/Logic/Communications/PhoneMessageReceiver.cs @@ -6,23 +6,24 @@ using System.Text; using Swarmops.Basic.Enums; using Swarmops.Basic.Types; using Swarmops.Database; -using Swarmops.Logic.Structure; using Swarmops.Logic.Support; using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications { - class PhoneMessage + internal class PhoneMessage { + private string errorMessage = ""; private string fromNumber = ""; private string message = ""; - private DateTime sentAt; - private string errorMessage = ""; + + private Dictionary people = new Dictionary(); + //people matching the set number + private string replyMessage = ""; + private DateTime sentAt; - private Dictionary people = new Dictionary();//people matching the set number - - public PhoneMessage (string fromNumber, string message, DateTime sentAt) + public PhoneMessage(string fromNumber, string message, DateTime sentAt) { FromNumber = fromNumber; Message = message; @@ -31,91 +32,91 @@ namespace Swarmops.Logic.Communications public Dictionary People { - get { return people; } + get { return this.people; } } public string ReplyMessage { - get { return replyMessage; } - set { replyMessage = value; } + get { return this.replyMessage; } + set { this.replyMessage = value; } } + public string ErrorMessage { - get { return errorMessage; } - set { errorMessage = value; } + get { return this.errorMessage; } + set { this.errorMessage = value; } } public string FromNumber { - get { return fromNumber; } + get { return this.fromNumber; } //setting the number loads the list of matching people protected set { - fromNumber = value; + this.fromNumber = value; // 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); - people = PhoneMessageReceiver.GetPeopleFromPhoneNumbers(phoneNumbers); + this.people = PhoneMessageReceiver.GetPeopleFromPhoneNumbers(phoneNumbers); } } public string Message { - get { return message; } - protected set { message = value; } + get { return this.message; } + protected set { this.message = value; } } public DateTime SentAt { - get { return sentAt; } - protected set { sentAt = value; } + get { return this.sentAt; } + protected set { this.sentAt = value; } } - } - interface IPhoneMessageHandler + internal interface IPhoneMessageHandler { - bool Filter (PhoneMessage msg); - bool Handle (PhoneMessage msg); + bool Filter(PhoneMessage msg); + bool Handle(PhoneMessage msg); } - abstract class PhoneMessageHandler : IPhoneMessageHandler + 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; } - virtual protected 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); } } - class DefaultMessageHandler : PhoneMessageHandler + 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"; string subject = "SMS från '" + msg.FromNumber + "'"; string body = "Inkommet från telefonnummer: " + msg.FromNumber + "\r\n" + "Meddelande: " + msg.Message + "\r\n" + - "Skickades: " + msg.SentAt.ToShortDateString() + " " + msg.SentAt.ToShortTimeString() + "\r\n\r\n"; + "Skickades: " + msg.SentAt.ToShortDateString() + " " + msg.SentAt.ToShortTimeString() + + "\r\n\r\n"; if (msg.People.Count > 0) { @@ -127,7 +128,6 @@ namespace Swarmops.Logic.Communications if (!person.IsActivist) body += "ej "; body += "aktivist) \r\n"; - } string numbers = ""; foreach (BasicPerson bp in msg.People.Values) @@ -145,27 +145,29 @@ namespace Swarmops.Logic.Communications } 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, msg.Message + "\r\n" + msg.ErrorMessage); + 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, + msg.Message + "\r\n" + msg.ErrorMessage); return true; } } - class UnregisterActivistHandler : PhoneMessageHandler + internal class UnregisterActivistHandler : PhoneMessageHandler { - public override bool Filter (PhoneMessage msg) + public override bool Filter(PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - if ((smsParts[0] == "stopp" || smsParts[0] == "stop") && (smsParts[1] == "aktivist" || smsParts[1] == "activist")) + 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); } - else - return false; + 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) @@ -182,27 +184,26 @@ namespace Swarmops.Logic.Communications } msg.ReplyMessage = "Misslyckades utföra åtgärden: Vi kunde inte hitta ditt telefonnummer i vårt register."; msg.ErrorMessage = "\r\nRequest to stop being an aktivist."; - msg.ErrorMessage = "\r\nDid not find the phone number in the database.\r\n\r\nHave replied:" + msg.ReplyMessage; + msg.ErrorMessage = "\r\nDid not find the phone number in the database.\r\n\r\nHave replied:" + + msg.ReplyMessage; return false; } } - class RegisterActivistHandler : PhoneMessageHandler + internal class RegisterActivistHandler : PhoneMessageHandler { - public override bool Filter (PhoneMessage msg) + public override bool Filter(PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string[] smsParts = msg.Message.ToLower().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (smsParts[0] == "start" && (smsParts[1] == "aktivist" || smsParts[1] == "activist")) { return true; } - else - return false; + return false; } - - public override bool Handle (PhoneMessage msg) + public override bool Handle(PhoneMessage msg) { Trace.WriteLine(msg); // use parameter to suppress warning @@ -248,21 +249,19 @@ namespace Swarmops.Logic.Communications }-- */ return false; - - } + } } - class RenewMembershipHandler : PhoneMessageHandler + internal class RenewMembershipHandler : PhoneMessageHandler { - public override bool Filter (PhoneMessage msg) + public override bool Filter(PhoneMessage msg) { - string[] smsParts = msg.Message.ToLower().Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string[] smsParts = msg.Message.ToLower().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (smsParts[0] == "pp" && smsParts[1] == "igen") { return true; } - else - return false; + return false; } @@ -339,7 +338,6 @@ namespace Swarmops.Logic.Communications return false; */ - // use parameters to suppress warnings Trace.WriteLine(msg); return false; @@ -349,7 +347,7 @@ namespace Swarmops.Logic.Communications public class PhoneMessageReceiver { - private static List _handlers = new List(); + private static readonly List _handlers = new List(); private static List Handlers { @@ -369,14 +367,13 @@ namespace Swarmops.Logic.Communications /// - /// Handle one SMS message according to the registered handlers + /// Handle one SMS message according to the registered handlers /// /// /// /// - 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); @@ -388,7 +385,6 @@ namespace Swarmops.Logic.Communications // Want to handle this message ? if (handler.Filter(msg)) { - // if Handle() returns true do not call the following handlers if (handler.Handle(msg)) break; @@ -406,11 +402,12 @@ namespace Swarmops.Logic.Communications /// - /// Find persons with a phone number in one of the formats supplied - /// i + /// Find persons with a phone number in one of the formats supplied + /// + /// i /// /// - public static Dictionary GetPeopleFromPhoneNumbers (string[] phoneNumbers) + public static Dictionary GetPeopleFromPhoneNumbers(string[] phoneNumbers) { Dictionary peopleDict = new Dictionary(); @@ -418,7 +415,8 @@ namespace Swarmops.Logic.Communications { for (int i = 0; i < phoneNumbers.Length; i++) { - BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber("SE", phoneNumbers[i]); + BasicPerson[] people = SwarmDb.GetDatabaseForReading() + .GetPeopleFromPhoneNumber("SE", phoneNumbers[i]); foreach (BasicPerson bp in people) { //Only add if not seen. @@ -436,10 +434,9 @@ namespace Swarmops.Logic.Communications return peopleDict; } - static internal 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 System.Net.Mail.MailMessage(); + MailMessage mail = new MailMessage(); mail.IsBodyHtml = false; mail.Subject = subject; mail.Body = body; @@ -457,4 +454,4 @@ namespace Swarmops.Logic.Communications } } } -} +} \ No newline at end of file diff --git a/Logic/Communications/PhoneMessageTransmitter.cs b/Logic/Communications/PhoneMessageTransmitter.cs index 04a9bce3..19ea5f0c 100644 --- a/Logic/Communications/PhoneMessageTransmitter.cs +++ b/Logic/Communications/PhoneMessageTransmitter.cs @@ -15,7 +15,7 @@ namespace Swarmops.Logic.Communications { private static ServiceCredential credential; // credentials cache private static DateTime lastLoad = DateTime.MinValue; - private static object locker = new object(); + private static readonly object locker = new object(); private static ServiceCredential Credential { @@ -27,10 +27,12 @@ namespace Swarmops.Logic.Communications { lastLoad = DateTime.Now; String serviceName = Persistence.Key["SMSService"]; - BasicExternalCredential basicCredential = SwarmDb.GetDatabaseForReading().GetExternalCredential(serviceName); + BasicExternalCredential basicCredential = + SwarmDb.GetDatabaseForReading().GetExternalCredential(serviceName); Encoding enc = Encoding.GetEncoding(28591); //ISO encoding (latin1) - credential = new ServiceCredential(basicCredential.Login, basicCredential.Password, basicCredential.ServiceName, enc); + credential = new ServiceCredential(basicCredential.Login, basicCredential.Password, + basicCredential.ServiceName, enc); } return credential; @@ -54,7 +56,7 @@ namespace Swarmops.Logic.Communications } } - internal static void Send (string phoneNumber, string message) + internal static void Send(string phoneNumber, string message) { switch (Credential.ServiceName) { @@ -69,7 +71,7 @@ namespace Swarmops.Logic.Communications } } - public static bool CheckServiceStatus () + public static bool CheckServiceStatus() { switch (Credential.ServiceName) { @@ -77,35 +79,33 @@ namespace Swarmops.Logic.Communications return true; //cant test this case "SwedishKannel": - { - String username = Credential.Login; - String password = Credential.Password; - Encoding enc = Credential.Encoding; - String url = "https://nurse.sanitarium.se/kannel/status"; - String result; + { + String username = Credential.Login; + String password = Credential.Password; + Encoding enc = Credential.Encoding; + String url = "https://nurse.sanitarium.se/kannel/status"; + String result; - HttpWebResponse responseOut = null; - try - { - result = HTTPSender.Send(url, enc, 1500, out responseOut); - if (((int)responseOut.StatusCode).ToString().StartsWith("2")) - return true; - else - return false; - } - catch (Exception) - { - return false; - } + HttpWebResponse responseOut = null; + try + { + result = HTTPSender.Send(url, enc, 1500, out responseOut); + if (((int) responseOut.StatusCode).ToString().StartsWith("2")) + return true; + return false; } + catch (Exception) + { + return false; + } + } default: 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); @@ -132,7 +132,7 @@ namespace Swarmops.Logic.Communications } } - internal static void SendMoSMS (string phone, string message) + internal static void SendMoSMS(string phone, string message) { // This is the SWEDISH sms transmission mechanism. @@ -175,7 +175,7 @@ namespace Swarmops.Logic.Communications // 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("+")) @@ -199,7 +199,7 @@ namespace Swarmops.Logic.Communications return phoneNumber; } - public static string[] DeNormalizedPhoneNumber (string phoneNumber) + public static string[] DeNormalizedPhoneNumber(string phoneNumber) { string[] phoneNumbers = new string[3]; @@ -218,43 +218,41 @@ namespace Swarmops.Logic.Communications return phoneNumbers; } - #region HTTP Sending Class - private class HTTPSender : ICertificatePolicy { - - public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error) + 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); } - 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 - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); // buffer för inläsning - var buf = new byte[8092]; + byte[] buf = new byte[8092]; #pragma warning disable 618 // ServicePointManager.CertificatePolicy is obsoleted, but is the only thing that works on both windows and mono. //Needed to avoid errors from homegrown SSL cert. - + ICertificatePolicy oldPolicy = ServicePointManager.CertificatePolicy; ServicePointManager.CertificatePolicy = new HTTPSender(); // anropa websidan med aktuella data - var request = (HttpWebRequest)WebRequest.Create(http_payload); + HttpWebRequest request = (HttpWebRequest) WebRequest.Create(http_payload); if (timeout > -1) { @@ -262,7 +260,7 @@ namespace Swarmops.Logic.Communications } // ta emot svarskoder - var response = (HttpWebResponse)request.GetResponse(); + HttpWebResponse response = (HttpWebResponse) request.GetResponse(); responseOut = response; ServicePointManager.CertificatePolicy = oldPolicy; #pragma warning restore 618 @@ -292,16 +290,17 @@ namespace Swarmops.Logic.Communications } #endregion + #region Nested type: ServiceCredential internal class ServiceCredential { + internal readonly Encoding Encoding; internal readonly string Login; internal readonly string Password; internal readonly string ServiceName; - internal readonly Encoding Encoding; - 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 f03c0663..fd925217 100644 --- a/Logic/Communications/Transmission/NotificationPayload.cs +++ b/Logic/Communications/Transmission/NotificationPayload.cs @@ -1,27 +1,31 @@ using System; +using System.Net; +using Swarmops.Logic.App_GlobalResources; using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Communications.Transmission { [Serializable] - public class NotificationPayload: PayloadBase, ICommsRenderer + public class NotificationPayload : PayloadBase, ICommsRenderer { - [Obsolete("Do not use this direct constructor. It is intended for XML serialization only. Therefore, you're getting a compile-time error.", true)] + [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() { // 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) { - this.SubjectResource = notificationResource + "_Subject"; - this.BodyResource = notificationResource + "_Body"; - this.Strings = strings; + SubjectResource = notificationResource + "_Subject"; + BodyResource = notificationResource + "_Body"; + Strings = strings; } public string SubjectResource { get; set; } @@ -31,22 +35,26 @@ namespace Swarmops.Logic.Communications.Transmission public string GetSubject() { // TODO: Pick culture - - return ExpandMacros(App_GlobalResources.Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString(this.SubjectResource)); + + return + ExpandMacros( + Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString(SubjectResource)); } public string GetBody() { // TODO: Pick culture - return ExpandMacros(App_GlobalResources.Logic_Communications_Transmission_NotificationPayload.ResourceManager.GetString(this.BodyResource)); + return + 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]", System.Net.Dns.GetHostName()); + input = input.Replace("[HostName]", Dns.GetHostName()); // Loop through supplied strings and replace them in the resource. Not very efficient but who cares @@ -110,7 +118,7 @@ namespace Swarmops.Logic.Communications.Transmission public enum NotificationString { - Unknown=0, + Unknown = 0, ConcernedPersonName, ActingPersonName, TertiaryPersonName, @@ -129,9 +137,8 @@ namespace Swarmops.Logic.Communications.Transmission } [Serializable] - public class NotificationStrings: SerializableDictionary + public class NotificationStrings : SerializableDictionary { // typeset } - -} +} \ No newline at end of file diff --git a/Logic/Communications/Transmission/PayloadBase.cs b/Logic/Communications/Transmission/PayloadBase.cs index 44f1bd9f..1ba6b175 100644 --- a/Logic/Communications/Transmission/PayloadBase.cs +++ b/Logic/Communications/Transmission/PayloadBase.cs @@ -7,20 +7,20 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Communications.Transmission { [Serializable] - public class PayloadBase: IXmlPayload + public class PayloadBase : IXmlPayload { public string ToXml() { - var serializer = new XmlSerializer(typeof(T)); + XmlSerializer serializer = new XmlSerializer(typeof (T)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, this); byte[] xmlBytes = stream.GetBuffer(); return Encoding.UTF8.GetString(xmlBytes); } - public static T FromXml (string xml) + public static T FromXml(string xml) { // Compensate for stupid Mono encoding bugs @@ -32,17 +32,17 @@ namespace Swarmops.Logic.Communications.Transmission xml = xml.Replace("�", ""); xml = xml.Replace("\x00", ""); - var serializer = new XmlSerializer(typeof(T)); + XmlSerializer serializer = new XmlSerializer(typeof (T)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); stream.Write(xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - var result = (T)serializer.Deserialize(stream); + T result = (T) serializer.Deserialize(stream); stream.Close(); return result; } } -} +} \ No newline at end of file diff --git a/Logic/Communications/Transmission/PayloadEnvelope.cs b/Logic/Communications/Transmission/PayloadEnvelope.cs index 49f406d2..f4d4a79c 100644 --- a/Logic/Communications/Transmission/PayloadEnvelope.cs +++ b/Logic/Communications/Transmission/PayloadEnvelope.cs @@ -4,7 +4,7 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Communications.Transmission { [Serializable] - public class PayloadEnvelope: PayloadBase + public class PayloadEnvelope : PayloadBase { public PayloadEnvelope() { @@ -20,4 +20,4 @@ namespace Swarmops.Logic.Communications.Transmission public string PayloadClass { get; set; } public string PayloadXml { get; set; } } -} +} \ No newline at end of file diff --git a/Logic/Communications/TypedMailTemplate.cs b/Logic/Communications/TypedMailTemplate.cs index 77290983..1261c993 100644 --- a/Logic/Communications/TypedMailTemplate.cs +++ b/Logic/Communications/TypedMailTemplate.cs @@ -19,51 +19,14 @@ namespace Swarmops.Logic.Communications { public class TypedMailTemplate { - private MailTemplate template = null; + private SerializableDictionary placeholders = + new SerializableDictionary(); + + private MailTemplate template; private TemplateType templatetype = TemplateType.None; #region Class-methods - /// - /// Get a list of available TypedMailTemplate subclasses - /// - public static List GetTemplateNames () - { - List retval = new List(); - foreach (TemplateType t in templateTypes.Keys) - { - retval.Add(templateTypes[t].BaseName); - } - return retval; - } - public static string GetNameFromMailType (int mailType) - { - try - { - return templateTypes[(TemplateType)mailType].BaseName; - } - catch (Exception ex) - { - throw new Exception("Can't translate mailtype(" + mailType + ") to template name", ex); - } - } - - - public static TemplateType TypeFromName (string className) - { - 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()) - { - return t; - } - } - return TemplateType.None; - } - - private static Dictionary templateTypes = initTemplateTypes(); public enum TemplateType { None = 0, @@ -78,7 +41,49 @@ namespace Swarmops.Logic.Communications ChangeOrgMail = 9 } - private static Dictionary initTemplateTypes () + private static readonly Dictionary templateTypes = initTemplateTypes(); + + /// + /// Get a list of available TypedMailTemplate subclasses + /// + public static List GetTemplateNames() + { + List retval = new List(); + foreach (TemplateType t in templateTypes.Keys) + { + retval.Add(templateTypes[t].BaseName); + } + return retval; + } + + public static string GetNameFromMailType(int mailType) + { + try + { + return templateTypes[(TemplateType) mailType].BaseName; + } + catch (Exception ex) + { + throw new Exception("Can't translate mailtype(" + mailType + ") to template name", ex); + } + } + + + public static TemplateType TypeFromName(string className) + { + 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()) + { + return t; + } + } + return TemplateType.None; + } + + private static Dictionary initTemplateTypes() { Dictionary retval = new Dictionary(); retval.Add(TemplateType.None, new TypedMailTemplate()); @@ -94,14 +99,20 @@ namespace Swarmops.Logic.Communications return retval; } - #endregion #region Instantiation and initialization + + public TypedMailTemplate() + { + this.template = new MailTemplate(); + AddPlaceHolder(new PlaceHolder("RecieverIds", "RecieverIds", PlaceholderType.NoTag)); + } + /// - /// Create TypedMailTemplate object from name + /// Create TypedMailTemplate object from name /// - public static TypedMailTemplate FromName (string className) + public static TypedMailTemplate FromName(string className) { try { @@ -119,57 +130,53 @@ namespace Swarmops.Logic.Communications 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); } - } - public TypedMailTemplate () + protected virtual void Initialize(MailTemplate templ) { - template = new MailTemplate(); - this.AddPlaceHolder(new PlaceHolder("RecieverIds", "RecieverIds", PlaceholderType.NoTag)); - + this.template = templ; } - protected virtual void Initialize (MailTemplate templ) - { - template = templ; - } - - protected virtual void Initialize (string countryCode, int orgId, string variant) + protected virtual void Initialize(string countryCode, int orgId, string variant) { try { - template = MailTemplate.FromNameCountryAndOrg(this.BaseName + variant, countryCode, orgId); + this.template = MailTemplate.FromNameCountryAndOrg(BaseName + variant, countryCode, orgId); } catch { - string name = this.BaseName + variant; + string name = BaseName + variant; if (name.EndsWith("Plain")) { try { name = name.Substring(0, name.Length - 5); - template = MailTemplate.FromNameCountryAndOrg(name, countryCode, orgId); + this.template = MailTemplate.FromNameCountryAndOrg(name, countryCode, orgId); } catch (Exception e) { - throw new Exception("Failed to create MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + "," + orgId + ")", e); + throw new Exception( + "Failed to create MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + "," + + orgId + ")", e); } } else { try { - template = MailTemplate.FromNameCountryAndOrg(name + "Plain", countryCode, orgId); + this.template = MailTemplate.FromNameCountryAndOrg(name + "Plain", countryCode, orgId); } catch (Exception e) { - throw new Exception("Failed to create (plain) MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + "," + orgId + ")", e); + throw new Exception( + "Failed to create (plain) MailTemplate.FromNameCountryAndOrg(" + name + "," + countryCode + + "," + orgId + ")", e); } } } @@ -177,29 +184,29 @@ namespace Swarmops.Logic.Communications /// - /// Initialize a TypedMailTemplate subclass for rendering + /// 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); try { - this.DeserializePlaceHolders(mail.Body); + DeserializePlaceHolders(mail.Body); } catch (Exception ex) { try { //try to handle old mail format... just in case. - this.SetPlaceHolder("BodyContent", mail.Body); - this.SetPlaceHolder("IntroContent", string.Empty); - this.SetPlaceHolder("GeographyName", mail.Geography.Name); - this.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); } } } @@ -207,89 +214,170 @@ namespace Swarmops.Logic.Communications #endregion /// - /// MailTemplate used when rendering + /// MailTemplate used when rendering /// public MailTemplate Template { - get - { - return template; - } + get { return this.template; } } /// - /// Integer representing this class + /// Integer representing this class /// public int MailType { - get - { - return (int)this.Templatetype; - } + get { return (int) Templatetype; } } /// - /// Type of this class as enum TemplateType + /// Type of this class as enum TemplateType /// public TemplateType Templatetype { get { if (this.templatetype == TemplateType.None) - this.templatetype = TypedMailTemplate.TypeFromName(this.BaseName); - return templatetype; + this.templatetype = TypeFromName(BaseName); + return this.templatetype; } } /// - /// Name of this class + /// Name of this class /// public virtual string BaseName { - get - { - return this.GetType().Name; - } + get { return GetType().Name; } } - private SerializableDictionary placeholders = new SerializableDictionary(); /// - /// Dictionary of placeholders + /// Dictionary of placeholders /// public SerializableDictionary Placeholders { - get - { - return placeholders; - } - internal set - { - placeholders = value; - } + get { return this.placeholders; } + internal set { this.placeholders = value; } } #region PlaceHolders and PlaceHolder manipulation + + public enum PlaceholderType + { + /// + /// id of a span, If placeholeder is assigned a value this value + /// replaces the content of the span. If no value is assigned, + /// content remains untouched. + /// + Id, + + /// + /// %tag%, content will replace. + /// + Tag, + + /// + /// span with %tag% inside, whole span is removed if tag is empty. + /// %tag% can be used in other places outside the span. + /// + TagInSpan, + + /// + /// Not rendered, to be used to transfer info from creation stage to rendering stage. + /// (To be implemented) + /// + NoTag + } + + #region Inner class PlaceHolder + + [Serializable] + public class PlaceHolder + { + //this is XmlSerialized so the following two attributes should be public and no others. + // XmlSerializer uses public fields and read/write properties + + internal Type dataType = typeof (string); + internal string formatString = ""; + internal string label; // label to show + public string name; // Id for span or name for %tag% + + + internal int seq; + internal PlaceholderType tagOrId = PlaceholderType.Tag; + public string value = ""; // current value + + public PlaceHolder() + { + } + + 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) + { + this.dataType = dataType; + this.formatString = formatString; + } + + public Type DataType + { + get { return this.dataType; } + } + + public string Label + { + get { return this.label; } + } + + public int Seq + { + get { return this.seq; } + } + + public string Name + { + get { return this.name; } + } + + public string Value + { + get { return this.value; } + } + + public PlaceholderType TagOrId + { + get { return this.tagOrId; } + } + } + + #endregion + /// - /// Used to add placeholder in constructor of subclasses + /// Used to add placeholder in constructor of subclasses /// - protected void AddPlaceHolder (PlaceHolder ph) + protected void AddPlaceHolder(PlaceHolder ph) { - ph.seq = placeholders.Count; - placeholders.Add(ph.Name, ph); + ph.seq = this.placeholders.Count; + this.placeholders.Add(ph.Name, ph); } - protected void SetPlaceHolder (string name, string value) + protected void SetPlaceHolder(string name, string value) { - placeholders[name].value = value; + this.placeholders[name].value = value; } - protected void SetPlaceHolder (string name, DateTime value) + protected void SetPlaceHolder(string name, DateTime value) { - if (this.Template != null && Template.LanguageCode != "" && Template.CountryCode != "") + if (Template != null && Template.LanguageCode != "" && Template.CountryCode != "") { CultureInfo cult = new CultureInfo(Template.LanguageCode + "-" + Template.CountryCode); - string formattedDate = value.ToString(placeholders[name].formatString, cult); + string formattedDate = value.ToString(this.placeholders[name].formatString, cult); SetPlaceHolder(name, formattedDate); } else @@ -300,17 +388,20 @@ namespace Swarmops.Logic.Communications } /// - /// Serialize values from placeholder dictionary + /// Serialize values from placeholder dictionary /// - /// 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) + /// + /// 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) { } /// - /// Called to insert all placeholders from dictionary into the MailTemplate when rendering + /// Called to insert all placeholders from dictionary into the MailTemplate when rendering /// - public void InsertAllPlaceHoldersToTemplate () + public void InsertAllPlaceHoldersToTemplate() { if (Template == null) throw new ArgumentException("There is no template loaded into the TypedMailTemplate"); @@ -318,12 +409,9 @@ namespace Swarmops.Logic.Communications // 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(this.Placeholders.Values); + List sortedPlaceholders = new List(Placeholders.Values); sortedPlaceholders.Sort( - delegate(PlaceHolder ph1, PlaceHolder ph2) - { - return ph1.seq.CompareTo(ph2.seq); - }); + delegate(PlaceHolder ph1, PlaceHolder ph2) { return ph1.seq.CompareTo(ph2.seq); }); foreach (PlaceHolder ph in sortedPlaceholders) { @@ -331,7 +419,7 @@ namespace Swarmops.Logic.Communications } } - private void InsertOnePlaceholderToTemplate (PlaceHolder ph) + private void InsertOnePlaceholderToTemplate(PlaceHolder ph) { if (ph.TagOrId == PlaceholderType.Tag) { @@ -368,25 +456,27 @@ namespace Swarmops.Logic.Communications } } - protected string SerializePlaceHolders () + protected string SerializePlaceHolders() { XmlSerializer s = new XmlSerializer(Placeholders.GetType()); StringBuilder retSb = new StringBuilder(); 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 + /// Load placeholders dictionary with serialized values /// - protected void DeserializePlaceHolders (string content) + protected void DeserializePlaceHolders(string content) { XmlSerializer s = new XmlSerializer(Placeholders.GetType()); - SerializableDictionary tempPlaceHolders = new SerializableDictionary(); + SerializableDictionary tempPlaceHolders = + new SerializableDictionary(); TextReader r = new StringReader(content); - tempPlaceHolders = (SerializableDictionary)s.Deserialize(r); + tempPlaceHolders = (SerializableDictionary) s.Deserialize(r); r.Close(); foreach (PlaceHolder ph in Placeholders.Values) @@ -399,7 +489,7 @@ 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)) + 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); @@ -412,160 +502,57 @@ namespace Swarmops.Logic.Communications } } - public enum PlaceholderType - { - /// - /// id of a span, If placeholeder is assigned a value this value - /// replaces the content of the span. If no value is assigned, - /// content remains untouched. - /// - Id, - - /// - /// %tag%, content will replace. - /// - Tag, - - /// - /// span with %tag% inside, whole span is removed if tag is empty. - /// %tag% can be used in other places outside the span. - /// - TagInSpan, - - /// - /// Not rendered, to be used to transfer info from creation stage to rendering stage. - /// (To be implemented) - /// - NoTag - } - - #region Inner class PlaceHolder - [Serializable] - public class PlaceHolder - { - public PlaceHolder () { } - - //this is XmlSerialized so the following two attributes should be public and no others. - // XmlSerializer uses public fields and read/write properties - - public string name; // Id for span or name for %tag% - public string value = ""; // current value - - - - internal int seq; - internal string label; // label to show - internal PlaceholderType tagOrId = PlaceholderType.Tag; - internal Type dataType = typeof(string); - internal string formatString = ""; - - 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) - { - this.dataType = dataType; - this.formatString = formatString; - } - - public Type DataType - { - get - { - return dataType; - } - } - - public string Label - { - get - { - return label; - } - } - - public int Seq - { - get { return seq; } - } - - public string Name - { - get - { - return name; - } - } - public string Value - { - get - { - return value; - } - } - public PlaceholderType TagOrId - { - get - { - return tagOrId; - } - } - } - - #endregion #endregion - - public OutboundMail CreateOutboundMail (Person author, int mailPriority, Organization organization, Geography geography) + public OutboundMail CreateOutboundMail(Person author, int mailPriority, Organization organization, + Geography geography) { return CreateOutboundMail(author, mailPriority, organization, geography, DateTime.Now); } /// - /// Create OutboundMail with personal sender + /// Create OutboundMail with personal sender /// - public OutboundMail CreateOutboundMail (Person author, int mailPriority, - Organization organization, Geography geography, DateTime releaseDateTime) + public OutboundMail CreateOutboundMail(Person author, int mailPriority, + Organization organization, Geography geography, DateTime releaseDateTime) { - return OutboundMail.Create(author, this.BaseName, this.SerializePlaceHolders(), - mailPriority, this.MailType, organization, geography, releaseDateTime); + return OutboundMail.Create(author, BaseName, SerializePlaceHolders(), + mailPriority, MailType, organization, geography, releaseDateTime); } + /// - /// Create OutboundMail mail with "functional" sender + /// Create OutboundMail mail with "functional" sender /// - public OutboundMail CreateFunctionalOutboundMail (MailAuthorType authorType, int mailPriority, Organization organization, Geography geography) + public OutboundMail CreateFunctionalOutboundMail(MailAuthorType authorType, int mailPriority, + Organization organization, Geography geography) { return CreateFunctionalOutboundMail(authorType, mailPriority, organization, geography, DateTime.Now); } - public OutboundMail CreateFunctionalOutboundMail (MailAuthorType authorType, int mailPriority, - Organization organization, Geography geography, DateTime releaseDateTime) + public OutboundMail CreateFunctionalOutboundMail(MailAuthorType authorType, int mailPriority, + Organization organization, Geography geography, DateTime releaseDateTime) { - return OutboundMail.CreateFunctional(authorType, this.BaseName, this.SerializePlaceHolders(), - mailPriority, this.MailType, organization.Identity, geography.Identity, releaseDateTime); + 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, this.BaseName, this.SerializePlaceHolders(), 0, - this.MailType, organization, geography); + return OutboundMail.CreateFake(author, BaseName, SerializePlaceHolders(), 0, + MailType, organization, geography); } #region Handle different source formats in placeholders - public void PreparePlaceholders () + + public void PreparePlaceholders() { TypedMailTemplate template = this; - Regex reForumType = new Regex(@"(\[h.\])|(\[b\])|(\[i\])|(\[i\])|(\[blockquote\])|(\[br\])|(\[\/a\])", RegexOptions.IgnoreCase); + Regex reForumType = new Regex(@"(\[h.\])|(\[b\])|(\[i\])|(\[i\])|(\[blockquote\])|(\[br\])|(\[\/a\])", + RegexOptions.IgnoreCase); Regex reHtmlType = new Regex(@"()|(<[^>]+?/>)", RegexOptions.IgnoreCase); - foreach (TypedMailTemplate.PlaceHolder ph in template.Placeholders.Values) + foreach (PlaceHolder ph in template.Placeholders.Values) { - if (reHtmlType.IsMatch(ph.value)) { //contains HTML, try to strip dangerous features @@ -589,7 +576,8 @@ namespace Swarmops.Logic.Communications n.SetAttributeValue("src", ""); } } - HtmlNodeCollection onhandlers = tempDoc.DocumentNode.SelectNodes("//*[starts-with(local-name(@*),'on')]"); + HtmlNodeCollection onhandlers = + tempDoc.DocumentNode.SelectNodes("//*[starts-with(local-name(@*),'on')]"); if (onhandlers != null) { foreach (HtmlNode n in onhandlers) @@ -606,7 +594,8 @@ namespace Swarmops.Logic.Communications ph.value = tempDoc.DocumentNode.InnerHtml; } catch - { } + { + } } if (reForumType.IsMatch(ph.value)) @@ -622,43 +611,44 @@ namespace Swarmops.Logic.Communications } /// - /// Convert plain text to reasonable html + /// Convert plain text to reasonable html /// - private string ConvertPlainToHtml (string phvalue) + private string ConvertPlainToHtml(string 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; } /// - /// Convert a sring with "forum" tags to html + /// 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 = 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 - var regexLinks = - new Regex("(?s)\\[a\\s+href=\\\"(?[^\\\"]+)\\\"\\](?.+?)\\[/a\\]", RegexOptions.Multiline); + Regex regexLinks = + new Regex("(?s)\\[a\\s+href=\\\"(?[^\\\"]+)\\\"\\](?.+?)\\[/a\\]", + RegexOptions.Multiline); - phvalue = regexLinks.Replace(phvalue, new MatchEvaluator(RewriteUrlsInHtml)); + phvalue = regexLinks.Replace(phvalue, RewriteUrlsInHtml); phvalue = phvalue. Replace("[h1]", "

"). @@ -677,7 +667,7 @@ namespace Swarmops.Logic.Communications return phvalue; } - private static string RewriteUrlsInHtml (Match match) + private static string RewriteUrlsInHtml(Match match) { return "" + match.Groups["description"].Value + ""; } @@ -691,191 +681,367 @@ namespace Swarmops.Logic.Communications //} #endregion - } #region Specific types of mailtemplates as subclasses of TypedMailTemplate - public class MemberMail : TypedMailTemplate { - public MemberMail () + public MemberMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("GeographyName", "GeographyName", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - this.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); } } - public string pBodyContent { set { SetPlaceHolder("BodyContent", value); } } - public string pOrgName { set { SetPlaceHolder("OrgName", value); } } - public string pGeographyName { set { SetPlaceHolder("GeographyName", value); } } - string MemberNumberWithCheck { set { SetPlaceHolder("MemberNumberWithCheck", value); } } - string MemberNumber { set { SetPlaceHolder("MemberNumber", value); } } - string HexIdentifier { set { SetPlaceHolder("HexIdentifier", value); } } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } + + public string pBodyContent + { + set { SetPlaceHolder("BodyContent", value); } + } + + public string pOrgName + { + set { SetPlaceHolder("OrgName", value); } + } + + public string pGeographyName + { + set { SetPlaceHolder("GeographyName", value); } + } + + private string MemberNumberWithCheck + { + set { SetPlaceHolder("MemberNumberWithCheck", value); } + } + + private string MemberNumber + { + set { SetPlaceHolder("MemberNumber", value); } + } + + private string HexIdentifier + { + set { SetPlaceHolder("HexIdentifier", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(this.BaseName + ".MakeIndividualReplacements called with wrong type of person object"); - Person person = (Person)personObject; - this.MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); - this.HexIdentifier = person.HexIdentifier(); - this.MemberNumber = person.PersonId.ToString(); + throw new ArgumentException(BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); + Person person = (Person) personObject; + MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + HexIdentifier = person.HexIdentifier(); + MemberNumber = person.PersonId.ToString(); } } - public class WelcomeMail : MemberMail { } - public class OfficerMail : MemberMail { } - public class ActivistMail : MemberMail { } + public class WelcomeMail : MemberMail + { + } + + public class OfficerMail : MemberMail + { + } + + public class ActivistMail : MemberMail + { + } public class ExpiredMail : TypedMailTemplate { - public ExpiredMail () + public ExpiredMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("Memberships", "Memberships", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("MemberPhoneNumber", "MemberPhoneNumber", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - this.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); } } - public string pMemberships { set { SetPlaceHolder("Memberships", value); } } - public string pOrgName { set { SetPlaceHolder("OrgName", value); } } - public string pStdRenewLink { set { SetPlaceHolder("StdRenewLink", value); } } - string MemberPhoneNumber { set { SetPlaceHolder("MemberPhoneNumber", value); } } - string MemberNumberWithCheck { set { SetPlaceHolder("MemberNumberWithCheck", value); } } - string MemberNumber { set { SetPlaceHolder("MemberNumber", value); } } - string HexIdentifier { set { SetPlaceHolder("HexIdentifier", value); } } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } + + public string pMemberships + { + set { SetPlaceHolder("Memberships", value); } + } + + public string pOrgName + { + set { SetPlaceHolder("OrgName", value); } + } + + public string pStdRenewLink + { + set { SetPlaceHolder("StdRenewLink", value); } + } + + private string MemberPhoneNumber + { + set { SetPlaceHolder("MemberPhoneNumber", value); } + } + + private string MemberNumberWithCheck + { + set { SetPlaceHolder("MemberNumberWithCheck", value); } + } + + private string MemberNumber + { + set { SetPlaceHolder("MemberNumber", value); } + } + + private string HexIdentifier + { + set { SetPlaceHolder("HexIdentifier", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { try { if (!(personObject is Person)) - throw new ArgumentException(this.BaseName + ".MakeIndividualReplacements called with wrong type of person object"); - Person person = (Person)personObject; - this.MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); - this.HexIdentifier = person.HexIdentifier(); - this.MemberNumber = person.PersonId.ToString(); + throw new ArgumentException(BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); + Person person = (Person) personObject; + MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + HexIdentifier = person.HexIdentifier(); + MemberNumber = person.PersonId.ToString(); if (People.FromPhoneNumber(person.Country.Code, person.Phone).Count == 1) { - this.MemberPhoneNumber = person.Phone.ToString(); + MemberPhoneNumber = person.Phone; } } catch (Exception e) { - throw new Exception("Failed in FillIndividualPlaceholders person is " + personObject == null ? "null" : personObject.Identity.ToString(), e); + throw new Exception( + "Failed in FillIndividualPlaceholders person is " + personObject == null + ? "null" + : personObject.Identity.ToString(), e); } - } - } public class ReminderMail : TypedMailTemplate { - public ReminderMail () + public ReminderMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("Preamble", "Preamble", PlaceholderType.Id)); - this.AddPlaceHolder(new PlaceHolder("ExpirationDate", "ExpirationDate", PlaceholderType.Tag, typeof(DateTime), "d")); - this.AddPlaceHolder(new PlaceHolder("NextDate", "NextDate", PlaceholderType.Tag, typeof(DateTime), "d")); + 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")); - this.AddPlaceHolder(new PlaceHolder("TooOldForYouthOrgSpan", "TooOldForYouthOrgSpan(SPAN)", PlaceholderType.Id)); - this.AddPlaceHolder(new PlaceHolder("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("OtherOrg", "OtherOrg", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("CurrentAge", "Age this year", PlaceholderType.Tag)); - this.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)); - this.AddPlaceHolder(new PlaceHolder("WrongOrgSpan", "WrongOrgSpan(SPAN)", PlaceholderType.Id)); - this.AddPlaceHolder(new PlaceHolder("GeographyName", "GeographyName", PlaceholderType.Tag)); + AddPlaceHolder(new PlaceHolder("WrongOrgSpan", "WrongOrgSpan(SPAN)", PlaceholderType.Id)); + AddPlaceHolder(new PlaceHolder("GeographyName", "GeographyName", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - this.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); } } - public DateTime pExpirationDate { set { SetPlaceHolder("ExpirationDate", value); } } - public DateTime pNextDate { set { SetPlaceHolder("NextDate", value); } } - public string pTooOldForYouthOrgSpan { set { SetPlaceHolder("TooOldForYouthOrgSpan", value); } } - public string pCurrentOrg { set { SetPlaceHolder("CurrentOrg", value); } } - public string pOtherOrg { set { SetPlaceHolder("OtherOrg", value); } } - public string pCurrentAge { set { SetPlaceHolder("CurrentAge", value); } } - public string pOtherRenewLink { set { SetPlaceHolder("OtherRenewLink", value); } } - public string pWrongOrgSpan { set { SetPlaceHolder("WrongOrgSpan", value); } } - public string pGeographyName { set { SetPlaceHolder("GeographyName", value); } } - public string pStdRenewLink { set { SetPlaceHolder("StdRenewLink", value); } } - public string pOrgName { set { SetPlaceHolder("OrgName", value); } } - public string pPreamble { set { SetPlaceHolder("Preamble", value); } } - public string pTerminateLink { set { SetPlaceHolder("TerminateLink", value); } } - string MemberNumberWithCheck { set { SetPlaceHolder("MemberNumberWithCheck", value); } } - string MemberNumber { set { SetPlaceHolder("MemberNumber", value); } } - string HexIdentifier { set { SetPlaceHolder("HexIdentifier", value); } } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } + + public DateTime pExpirationDate + { + set { SetPlaceHolder("ExpirationDate", value); } + } + + public DateTime pNextDate + { + set { SetPlaceHolder("NextDate", value); } + } + + public string pTooOldForYouthOrgSpan + { + set { SetPlaceHolder("TooOldForYouthOrgSpan", value); } + } + + public string pCurrentOrg + { + set { SetPlaceHolder("CurrentOrg", value); } + } + + public string pOtherOrg + { + set { SetPlaceHolder("OtherOrg", value); } + } + + public string pCurrentAge + { + set { SetPlaceHolder("CurrentAge", value); } + } + + public string pOtherRenewLink + { + set { SetPlaceHolder("OtherRenewLink", value); } + } + + public string pWrongOrgSpan + { + set { SetPlaceHolder("WrongOrgSpan", value); } + } + + public string pGeographyName + { + set { SetPlaceHolder("GeographyName", value); } + } + + public string pStdRenewLink + { + set { SetPlaceHolder("StdRenewLink", value); } + } + + public string pOrgName + { + set { SetPlaceHolder("OrgName", value); } + } + + public string pPreamble + { + set { SetPlaceHolder("Preamble", value); } + } + + public string pTerminateLink + { + set { SetPlaceHolder("TerminateLink", value); } + } + + private string MemberNumberWithCheck + { + set { SetPlaceHolder("MemberNumberWithCheck", value); } + } + + private string MemberNumber + { + set { SetPlaceHolder("MemberNumber", value); } + } + + private string HexIdentifier + { + set { SetPlaceHolder("HexIdentifier", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(this.BaseName + ".MakeIndividualReplacements called with wrong type of person object"); - Person person = (Person)personObject; - this.MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); - this.HexIdentifier = person.HexIdentifier(); - this.MemberNumber = person.PersonId.ToString(); + throw new ArgumentException(BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); + Person person = (Person) personObject; + MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + HexIdentifier = person.HexIdentifier(); + MemberNumber = person.PersonId.ToString(); } } public class PressReleaseMail : TypedMailTemplate { - public PressReleaseMail () + public PressReleaseMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("Date", "Date", PlaceholderType.Tag, typeof(DateTime), "d")); - this.AddPlaceHolder(new PlaceHolder("Time", "Time", PlaceholderType.Tag, typeof(DateTime), "t")); - this.AddPlaceHolder(new PlaceHolder("PostedToCategories", "PostedToCategories", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("ReporterName", "ReporterName", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("ReporterEmail", "ReporterEmail", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("ReporterCategories", "ReporterCategories", PlaceholderType.Tag)); - this.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); } } - public string pBodyContent { set { SetPlaceHolder("BodyContent", value); } } - public DateTime pDate { set { SetPlaceHolder("Date", value); SetPlaceHolder("Time", value); } } - public string pPostedToCategories { set { SetPlaceHolder("PostedToCategories", value); } } - public string pOrgName { set { SetPlaceHolder("OrgName", value); } } - string ReporterName { set { SetPlaceHolder("ReporterName", value); } } - string ReporterEmail { set { SetPlaceHolder("ReporterEmail", value); } } - string ReporterCategories { set { SetPlaceHolder("ReporterCategories", value); } } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } + + public string pBodyContent + { + set { SetPlaceHolder("BodyContent", value); } + } + + public DateTime pDate + { + set + { + SetPlaceHolder("Date", value); + SetPlaceHolder("Time", value); + } + } + + public string pPostedToCategories + { + set { SetPlaceHolder("PostedToCategories", value); } + } + + public string pOrgName + { + set { SetPlaceHolder("OrgName", value); } + } + + private string ReporterName + { + set { SetPlaceHolder("ReporterName", value); } + } + + private string ReporterEmail + { + set { SetPlaceHolder("ReporterEmail", value); } + } + + private string ReporterCategories + { + set { SetPlaceHolder("ReporterCategories", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { if (personObject is Reporter) { - Reporter person = (Reporter)personObject; - this.ReporterEmail = person.Email; - this.ReporterName = person.Name; - this.ReporterCategories = GetConcatenatedCategoryString(person.MediaCategories); + Reporter person = (Reporter) personObject; + ReporterEmail = person.Email; + ReporterName = person.Name; + ReporterCategories = GetConcatenatedCategoryString(person.MediaCategories); } else if (personObject is Person) { - Person person = (Person)personObject; - this.ReporterEmail = person.Mail; - this.ReporterName = person.Name; - this.ReporterCategories = "Piratpartiet/Funktionär"; + Person person = (Person) personObject; + ReporterEmail = person.Mail; + ReporterName = person.Name; + ReporterCategories = "Piratpartiet/Funktionär"; } else - throw new ArgumentException(this.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 ""; @@ -887,7 +1053,8 @@ namespace Swarmops.Logic.Communications } if (categories.Count > 1) - { //TODO: Translate "och" + { + //TODO: Translate "och" result += " och " + categories[categories.Count - 1].Name; } @@ -897,46 +1064,95 @@ namespace Swarmops.Logic.Communications public class NewsletterMail : TypedMailTemplate { - public NewsletterMail () + public NewsletterMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("BodyContent", "BodyContent", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("Date", "Date", PlaceholderType.Tag, typeof(DateTime), "d MMMM yyyy")); - this.AddPlaceHolder(new PlaceHolder("ForumPostUrl", "ForumPostUrl", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("OrgName", "OrgName", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("HexIdentifier", "HexIdentifier", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("Name", "Name", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("NameUrl", "NameUrl", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("EmailBase64Url", "EmailBase64Url", PlaceholderType.Tag)); - this.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); } } - public string pBodyContent { set { SetPlaceHolder("BodyContent", value); } } - public DateTime pDate { set { SetPlaceHolder("Date", value); } } - public string pForumPostUrl { set { SetPlaceHolder("ForumPostUrl", value); } } - public string pOrgName { set { SetPlaceHolder("OrgName", value); } } - string MemberNumberWithCheck { set { SetPlaceHolder("MemberNumberWithCheck", value); } } - string MemberNumber { set { SetPlaceHolder("MemberNumber", value); } } - string HexIdentifier { set { SetPlaceHolder("HexIdentifier", value); } } - string Name { set { SetPlaceHolder("Name", value); } } - string NameUrl { set { SetPlaceHolder("NameUrl", value); } } - string EmailBase64Url { set { SetPlaceHolder("EmailBase64Url", value); } } - string PhoneBase64Url { set { SetPlaceHolder("PhoneBase64Url", value); } } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } + + public string pBodyContent + { + set { SetPlaceHolder("BodyContent", value); } + } + + public DateTime pDate + { + set { SetPlaceHolder("Date", value); } + } + + public string pForumPostUrl + { + set { SetPlaceHolder("ForumPostUrl", value); } + } + + public string pOrgName + { + set { SetPlaceHolder("OrgName", value); } + } + + private string MemberNumberWithCheck + { + set { SetPlaceHolder("MemberNumberWithCheck", value); } + } + + private string MemberNumber + { + set { SetPlaceHolder("MemberNumber", value); } + } + + private string HexIdentifier + { + set { SetPlaceHolder("HexIdentifier", value); } + } + + private string Name + { + set { SetPlaceHolder("Name", value); } + } + + private string NameUrl + { + set { SetPlaceHolder("NameUrl", value); } + } + + private string EmailBase64Url + { + set { SetPlaceHolder("EmailBase64Url", value); } + } + + private string PhoneBase64Url + { + set { SetPlaceHolder("PhoneBase64Url", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(this.BaseName + ".MakeIndividualReplacements called with wrong type of person object"); - Person person = (Person)personObject; - this.MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); - this.HexIdentifier = person.HexIdentifier(); - this.MemberNumber = person.PersonId.ToString(); - this.Name = person.Name; - this.NameUrl = HttpUtility.UrlEncode(person.Name); - this.EmailBase64Url = HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(person.Mail))); - this.PhoneBase64Url = HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(person.Phone))); + throw new ArgumentException(BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); + Person person = (Person) personObject; + 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))); } } @@ -976,49 +1192,95 @@ namespace Swarmops.Logic.Communications Hälsningar Medlemssystemet */ - public ChangeOrgMail () + + public ChangeOrgMail() { - this.AddPlaceHolder(new PlaceHolder("Subject", "Subject", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("CurrentOrg", "CurrentOrg", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("InactiveOrg", "InactiveOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("ChangeOrg", "ChangeOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("NoLocalOrg", "NoLocalOrg(Tag in SPAN)", PlaceholderType.TagInSpan)); - this.AddPlaceHolder(new PlaceHolder("NextDate", "NextDate", PlaceholderType.Tag, typeof(DateTime), "d")); - this.AddPlaceHolder(new PlaceHolder("CurrentGeo", "CurrentGeo", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("StdRenewLink", "StdRenewLink", PlaceholderType.Tag)); - this.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)); - this.AddPlaceHolder(new PlaceHolder("MemberNumberWithCheck", "MemberNumberWithCheckDigit", PlaceholderType.Tag)); - this.AddPlaceHolder(new PlaceHolder("MemberNumber", "MemberNumber", PlaceholderType.Tag)); - this.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); } } - public string pCurrentOrg { set { SetPlaceHolder("CurrentOrg", value); } } - public string pInactiveOrg { set { SetPlaceHolder("InactiveOrg", value); } } - public string pChangeOrg { set { SetPlaceHolder("ChangeOrg", value); } } - public string pNoLocalOrg { set { SetPlaceHolder("NoLocalOrg", value); } } - public DateTime pNextDate { set { SetPlaceHolder("NextDate", value); } } - public string pCurrentGeo { set { SetPlaceHolder("CurrentGeo", value); } } - public string pStdRenewLink { set { SetPlaceHolder("StdRenewLink", value); } } - public string pInactiveEnding { set { SetPlaceHolder("InactiveEnding", value); } } - string MemberNumberWithCheck { set { SetPlaceHolder("MemberNumberWithCheck", value); } } - string MemberNumber { set { SetPlaceHolder("MemberNumber", value); } } - string HexIdentifier { set { SetPlaceHolder("HexIdentifier", value); } } + public string pSubject + { + set { SetPlaceHolder("Subject", value); } + } - public override void FillIndividualPlaceholders (IEmailPerson personObject) + public string pCurrentOrg + { + set { SetPlaceHolder("CurrentOrg", value); } + } + + public string pInactiveOrg + { + set { SetPlaceHolder("InactiveOrg", value); } + } + + public string pChangeOrg + { + set { SetPlaceHolder("ChangeOrg", value); } + } + + public string pNoLocalOrg + { + set { SetPlaceHolder("NoLocalOrg", value); } + } + + public DateTime pNextDate + { + set { SetPlaceHolder("NextDate", value); } + } + + public string pCurrentGeo + { + set { SetPlaceHolder("CurrentGeo", value); } + } + + public string pStdRenewLink + { + set { SetPlaceHolder("StdRenewLink", value); } + } + + public string pInactiveEnding + { + set { SetPlaceHolder("InactiveEnding", value); } + } + + private string MemberNumberWithCheck + { + set { SetPlaceHolder("MemberNumberWithCheck", value); } + } + + private string MemberNumber + { + set { SetPlaceHolder("MemberNumber", value); } + } + + private string HexIdentifier + { + set { SetPlaceHolder("HexIdentifier", value); } + } + + public override void FillIndividualPlaceholders(IEmailPerson personObject) { if (!(personObject is Person)) - throw new ArgumentException(this.BaseName + ".MakeIndividualReplacements called with wrong type of person object"); - Person person = (Person)personObject; - this.MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); - this.HexIdentifier = person.HexIdentifier(); - this.MemberNumber = person.PersonId.ToString(); + throw new ArgumentException(BaseName + + ".MakeIndividualReplacements called with wrong type of person object"); + Person person = (Person) personObject; + MemberNumberWithCheck = CheckDigit.AppendCheckDigit(person.Identity).ToString(); + HexIdentifier = person.HexIdentifier(); + MemberNumber = person.PersonId.ToString(); } } #endregion - - -} - +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskAdvanceDebt.cs b/Logic/DashboardTasks/TaskAdvanceDebt.cs index 6e735747..833256a1 100644 --- a/Logic/DashboardTasks/TaskAdvanceDebt.cs +++ b/Logic/DashboardTasks/TaskAdvanceDebt.cs @@ -3,14 +3,14 @@ using System.Globalization; namespace Swarmops.Logic.DashboardTasks { - public class TaskAdvanceDebt: TaskBase + public class TaskAdvanceDebt : TaskBase { public TaskAdvanceDebt(decimal debt) - : base( + : base( 0, debt.ToString("N2", CultureInfo.InvariantCulture), DateTime.Now, DateTime.Now.AddDays(28)) { // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskAttestationLate.cs b/Logic/DashboardTasks/TaskAttestationLate.cs index a21208dd..21ee1b33 100644 --- a/Logic/DashboardTasks/TaskAttestationLate.cs +++ b/Logic/DashboardTasks/TaskAttestationLate.cs @@ -2,11 +2,11 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskAttestationLate: TaskBase + public class TaskAttestationLate : TaskBase { - public TaskAttestationLate (InboundInvoice invoice): base (invoice.Identity, "Invoice #" + invoice.Identity.ToString(), invoice.CreatedDateTime, invoice.DueDate) + public TaskAttestationLate(InboundInvoice invoice) + : base(invoice.Identity, "Invoice #" + invoice.Identity, invoice.CreatedDateTime, invoice.DueDate) { - } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskBase.cs b/Logic/DashboardTasks/TaskBase.cs index 699f07bc..11abdb07 100644 --- a/Logic/DashboardTasks/TaskBase.cs +++ b/Logic/DashboardTasks/TaskBase.cs @@ -4,12 +4,12 @@ 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) { - this.Identity = identity; - this.Description = description; - this.Opened = opened; - this.Expires = expires; + Identity = identity; + Description = description; + Opened = opened; + Expires = expires; } public int Identity { get; protected set; } @@ -17,4 +17,4 @@ namespace Swarmops.Logic.DashboardTasks public DateTime Opened { get; protected set; } public DateTime Expires { get; protected set; } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskExpenseClaim.cs b/Logic/DashboardTasks/TaskExpenseClaim.cs index 276d0438..08ae6f56 100644 --- a/Logic/DashboardTasks/TaskExpenseClaim.cs +++ b/Logic/DashboardTasks/TaskExpenseClaim.cs @@ -2,14 +2,14 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskExpenseClaim: TaskBase + public class TaskExpenseClaim : TaskBase { public TaskExpenseClaim(ExpenseClaim claim) : base( - claim.Identity, "Expense Claim #" + claim.Identity.ToString(), claim.CreatedDateTime, + claim.Identity, "Expense Claim #" + claim.Identity, claim.CreatedDateTime, claim.CreatedDateTime.AddDays(14)) { // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskGroup.cs b/Logic/DashboardTasks/TaskGroup.cs index ddbe284f..6dd57b48 100644 --- a/Logic/DashboardTasks/TaskGroup.cs +++ b/Logic/DashboardTasks/TaskGroup.cs @@ -6,6 +6,11 @@ namespace Swarmops.Logic.DashboardTasks { public class TaskGroup { + private static readonly Dictionary lookupDescriptionSingle; + private static readonly Dictionary lookupDescriptionMany; + private static readonly Dictionary lookupNavigateUrl; + private static readonly Dictionary lookupIconUrl; + static TaskGroup() { lookupDescriptionSingle = new Dictionary(); @@ -35,15 +40,20 @@ namespace Swarmops.Logic.DashboardTasks lookupDescriptionSingle[TaskGroupType.Volunteers] = "One waiting volunteer"; lookupDescriptionMany[TaskGroupType.Volunteers] = "{0} waiting volunteers"; - lookupNavigateUrl[TaskGroupType.ValidateExpenseClaims] = "/Pages/v4/Financial/ValidateExpenseDocumentation.aspx"; - lookupIconUrl[TaskGroupType.ValidateExpenseClaims] = "/Images/Public/Fugue/icons-shadowless/receipt-invoice.png"; + lookupNavigateUrl[TaskGroupType.ValidateExpenseClaims] = + "/Pages/v4/Financial/ValidateExpenseDocumentation.aspx"; + lookupIconUrl[TaskGroupType.ValidateExpenseClaims] = + "/Images/Public/Fugue/icons-shadowless/receipt-invoice.png"; lookupDescriptionSingle[TaskGroupType.ValidateExpenseClaims] = "One receipt to validate"; lookupDescriptionMany[TaskGroupType.ValidateExpenseClaims] = "{0} receipts to validate"; lookupNavigateUrl[TaskGroupType.DeclareAdvanceDebts] = "/Pages/v4/Financial/ClaimExpense.aspx"; - lookupIconUrl[TaskGroupType.DeclareAdvanceDebts] = "/Images/Public/Fugue/icons-shadowless/pwcustom/money-red.png"; - lookupDescriptionSingle[TaskGroupType.DeclareAdvanceDebts] = "Submit receipts for, or repay, your advance of SEK {0}"; - lookupDescriptionMany[TaskGroupType.DeclareAdvanceDebts] = "Submit receipts for, or repay, your advance of SEK {0}"; + lookupIconUrl[TaskGroupType.DeclareAdvanceDebts] = + "/Images/Public/Fugue/icons-shadowless/pwcustom/money-red.png"; + lookupDescriptionSingle[TaskGroupType.DeclareAdvanceDebts] = + "Submit receipts for, or repay, your advance of SEK {0}"; + lookupDescriptionMany[TaskGroupType.DeclareAdvanceDebts] = + "Submit receipts for, or repay, your advance of SEK {0}"; lookupNavigateUrl[TaskGroupType.Payout] = "/Pages/v4/Financial/PreparePayouts.aspx"; lookupIconUrl[TaskGroupType.Payout] = "/Images/Public/Silk/money.png"; @@ -51,42 +61,53 @@ namespace Swarmops.Logic.DashboardTasks lookupDescriptionMany[TaskGroupType.Payout] = "{0} payouts waiting"; lookupNavigateUrl[TaskGroupType.PayoutUrgently] = "/Pages/v4/Financial/PreparePayouts.aspx"; - lookupIconUrl[TaskGroupType.PayoutUrgently] = "/Images/Public/Fugue/icons-shadowless/pwcustom/money-silk-red.png"; + lookupIconUrl[TaskGroupType.PayoutUrgently] = + "/Images/Public/Fugue/icons-shadowless/pwcustom/money-silk-red.png"; lookupDescriptionSingle[TaskGroupType.PayoutUrgently] = "One URGENT payout waiting"; lookupDescriptionMany[TaskGroupType.PayoutUrgently] = "{0} URGENT payouts waiting"; lookupNavigateUrl[TaskGroupType.PayoutOverdue] = "/Pages/v4/Financial/PreparePayouts.aspx"; - lookupIconUrl[TaskGroupType.PayoutOverdue] = "/Images/Public/Fugue/icons-shadowless/pwcustom/money-silk-darkred.png"; + lookupIconUrl[TaskGroupType.PayoutOverdue] = + "/Images/Public/Fugue/icons-shadowless/pwcustom/money-silk-darkred.png"; lookupDescriptionSingle[TaskGroupType.PayoutOverdue] = "One OVERDUE payout waiting"; lookupDescriptionMany[TaskGroupType.PayoutOverdue] = "{0} OVERDUE payouts waiting"; lookupNavigateUrl[TaskGroupType.AttestationWarning] = "/Pages/v4/Financial/ViewInboundInvoices.aspx"; - lookupIconUrl[TaskGroupType.AttestationWarning] = "/Images/Public/Fugue/icons-shadowless/receipt-invoice.png"; + lookupIconUrl[TaskGroupType.AttestationWarning] = + "/Images/Public/Fugue/icons-shadowless/receipt-invoice.png"; lookupDescriptionSingle[TaskGroupType.AttestationWarning] = "Attestation for invoice {0} is running late"; lookupDescriptionMany[TaskGroupType.AttestationWarning] = "Attestations for invoices {0} are running late"; - } public TaskGroup(TaskGroupType type) { - this.Type = type; - this.Tasks = new List(); + Type = type; + Tasks = new List(); } public TaskGroupType Type { get; protected set; } public List Tasks { get; private set; } - public string NavigateUrl { get { return lookupNavigateUrl[this.Type]; } } - public string IconUrl { get { return lookupIconUrl[this.Type]; } } + + public string NavigateUrl + { + get { return lookupNavigateUrl[Type]; } + } + + public string IconUrl + { + get { return lookupIconUrl[Type]; } + } + public string Description { get { - if (this.Type == TaskGroupType.DeclareAdvanceDebts) + if (Type == TaskGroupType.DeclareAdvanceDebts) { return String.Format(lookupDescriptionSingle[TaskGroupType.DeclareAdvanceDebts], - this.Tasks[0].Description); + Tasks[0].Description); } - else if (this.Type == TaskGroupType.AttestationWarning) + if (this.Type == TaskGroupType.AttestationWarning) { List identities = new List(); @@ -98,74 +119,73 @@ namespace Swarmops.Logic.DashboardTasks identities.Sort(); string baseString = identities.Count > 1 - ? lookupDescriptionMany[TaskGroupType.AttestationWarning] - : lookupDescriptionSingle[TaskGroupType.AttestationWarning]; + ? lookupDescriptionMany[TaskGroupType.AttestationWarning] + : lookupDescriptionSingle[TaskGroupType.AttestationWarning]; return String.Format(baseString, Formatting.GenerateRangeString(identities)); } - else + if (this.Tasks.Count > 1) { - if (this.Tasks.Count > 1) - { - return String.Format(lookupDescriptionMany[this.Type], this.Tasks.Count); - } - else - { - return lookupDescriptionSingle[this.Type]; - } + return String.Format(lookupDescriptionMany[this.Type], this.Tasks.Count); } + return lookupDescriptionSingle[this.Type]; } } - - static private Dictionary lookupDescriptionSingle; - static private Dictionary lookupDescriptionMany; - static private Dictionary lookupNavigateUrl; - static private Dictionary lookupIconUrl; } public enum TaskGroupType { Unknown = 0, + /// - /// Salaries to be attested + /// Salaries to be attested /// AttestSalaries, + /// - /// Invoices to be attested + /// Invoices to be attested /// AttestInvoices, + /// - /// Expense claims to be attested + /// Expense claims to be attested /// AttestExpenseClaims, + /// - /// Volunteers that need to be taken care of + /// Volunteers that need to be taken care of /// Volunteers, + /// - /// Expense claim receipts to be validated + /// Expense claim receipts to be validated /// ValidateExpenseClaims, + /// - /// Cash advances that need to be repaid or declared + /// Cash advances that need to be repaid or declared /// DeclareAdvanceDebts, + /// - /// Payout waiting + /// Payout waiting /// Payout, + /// - /// Payout waiting and running late + /// Payout waiting and running late /// PayoutUrgently, + /// - /// Payout is overdue + /// Payout is overdue /// PayoutOverdue, + /// - /// Warning: invoice needs attestation urgently + /// Warning: invoice needs attestation urgently /// AttestationWarning } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskInboundInvoice.cs b/Logic/DashboardTasks/TaskInboundInvoice.cs index e942ede5..ec814efa 100644 --- a/Logic/DashboardTasks/TaskInboundInvoice.cs +++ b/Logic/DashboardTasks/TaskInboundInvoice.cs @@ -2,14 +2,14 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskInboundInvoice: TaskBase + public class TaskInboundInvoice : TaskBase { public TaskInboundInvoice(InboundInvoice invoice) : base( - invoice.Identity, "Inbound Invoice #" + invoice.Identity.ToString(), invoice.CreatedDateTime, + invoice.Identity, "Inbound Invoice #" + invoice.Identity, invoice.CreatedDateTime, invoice.DueDate.AddDays(-7)) { // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskPayout.cs b/Logic/DashboardTasks/TaskPayout.cs index 67b4c002..06783aa3 100644 --- a/Logic/DashboardTasks/TaskPayout.cs +++ b/Logic/DashboardTasks/TaskPayout.cs @@ -3,12 +3,11 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskPayout: TaskBase + 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) { - } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskReceiptValidation.cs b/Logic/DashboardTasks/TaskReceiptValidation.cs index cd2f9a68..14715d16 100644 --- a/Logic/DashboardTasks/TaskReceiptValidation.cs +++ b/Logic/DashboardTasks/TaskReceiptValidation.cs @@ -2,11 +2,14 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskReceiptValidation: TaskBase + public class TaskReceiptValidation : TaskBase { - public TaskReceiptValidation (ExpenseClaim claim): base (claim.Identity, "Expense Claim #" + claim.Identity, claim.CreatedDateTime, claim.CreatedDateTime.AddDays(14)) + public TaskReceiptValidation(ExpenseClaim claim) + : base( + claim.Identity, "Expense Claim #" + claim.Identity, claim.CreatedDateTime, + claim.CreatedDateTime.AddDays(14)) { // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskSalary.cs b/Logic/DashboardTasks/TaskSalary.cs index df090d29..a60efa2c 100644 --- a/Logic/DashboardTasks/TaskSalary.cs +++ b/Logic/DashboardTasks/TaskSalary.cs @@ -2,11 +2,15 @@ using Swarmops.Logic.Financial; namespace Swarmops.Logic.DashboardTasks { - public class TaskSalary: TaskBase + public class TaskSalary : TaskBase { - 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)) + 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)) { // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/TaskVolunteer.cs b/Logic/DashboardTasks/TaskVolunteer.cs index 24fdfe78..9ac2ff8c 100644 --- a/Logic/DashboardTasks/TaskVolunteer.cs +++ b/Logic/DashboardTasks/TaskVolunteer.cs @@ -2,7 +2,7 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DashboardTasks { - public class TaskVolunteer: TaskBase + public class TaskVolunteer : TaskBase { public TaskVolunteer(Volunteer volunteer) : base( @@ -12,4 +12,4 @@ namespace Swarmops.Logic.DashboardTasks // empty ctor } } -} +} \ No newline at end of file diff --git a/Logic/DashboardTasks/Tasks.cs b/Logic/DashboardTasks/Tasks.cs index a09f7a0f..62eb7469 100644 --- a/Logic/DashboardTasks/Tasks.cs +++ b/Logic/DashboardTasks/Tasks.cs @@ -8,9 +8,9 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.DashboardTasks { - public class Tasks: List + public class Tasks : List { - static public Tasks ForPersonOrganization (Person person, Organization organization) + public static Tasks ForPersonOrganization(Person person, Organization organization) { Tasks tasks = new Tasks(); @@ -26,7 +26,7 @@ namespace Swarmops.Logic.DashboardTasks return tasks; } - private void AddVolunteers (Person person, Organization organization) + private void AddVolunteers(Person person, Organization organization) { TaskGroup group = new TaskGroup(TaskGroupType.Volunteers); @@ -42,11 +42,11 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } - private void AddExpenseClaims (Person person, Organization organization) + private void AddExpenseClaims(Person person, Organization organization) { TaskGroup group = new TaskGroup(TaskGroupType.AttestExpenseClaims); @@ -71,11 +71,11 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } - private void AddSalaries (Person person, Organization organization) + private void AddSalaries(Person person, Organization organization) { TaskGroup group = new TaskGroup(TaskGroupType.AttestSalaries); @@ -93,7 +93,7 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } @@ -115,7 +115,7 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } @@ -125,7 +125,10 @@ namespace Swarmops.Logic.DashboardTasks // TODO: Loop over roles, get all open claims for roles where person can attest - if (!person.GetAuthority().HasPermission(Permission.CanDoEconomyTransactions, organization.Identity, Geography.RootIdentity, Authorization.Flag.AnyGeographyExactOrganization)) + if ( + !person.GetAuthority() + .HasPermission(Permission.CanDoEconomyTransactions, organization.Identity, Geography.RootIdentity, + Authorization.Flag.AnyGeographyExactOrganization)) { // no permission, no tasks return; @@ -137,21 +140,21 @@ namespace Swarmops.Logic.DashboardTasks { if (!claim.Validated) { - group.Tasks.Add(new TaskReceiptValidation (claim)); + group.Tasks.Add(new TaskReceiptValidation(claim)); } } if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } - private void AddAdvanceDebts (Person person, Organization organization) + private void AddAdvanceDebts(Person person, Organization organization) { TaskGroup group = new TaskGroup(TaskGroupType.DeclareAdvanceDebts); - + // TODO: One task group for each organization, actually ExpenseClaims claims = ExpenseClaims.FromClaimingPersonAndOrganization(person, organization); @@ -169,18 +172,21 @@ namespace Swarmops.Logic.DashboardTasks if (debt > 0.0m) { group.Tasks.Add(new TaskAdvanceDebt(debt)); - this.Add(group); + 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); - if (!person.GetAuthority().HasPermission(Permission.CanPayOutMoney, organization.Identity, 1, Authorization.Flag.AnyGeographyExactOrganization)) + if ( + !person.GetAuthority() + .HasPermission(Permission.CanPayOutMoney, organization.Identity, 1, + Authorization.Flag.AnyGeographyExactOrganization)) { return; } @@ -206,26 +212,29 @@ namespace Swarmops.Logic.DashboardTasks if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } if (groupUrgent.Tasks.Count > 0) { - this.Add(groupUrgent); + Add(groupUrgent); } if (groupOverdue.Tasks.Count > 0) { - this.Add(groupOverdue); + Add(groupOverdue); } } - private void AddAttestationWarnings (Person person, Organization organization) + private void AddAttestationWarnings(Person person, Organization organization) { TaskGroup group = new TaskGroup(TaskGroupType.AttestationWarning); - if (!person.GetAuthority().HasPermission(Permission.CanSeeEconomyTransactions, organization.Identity, 1, Authorization.Flag.AnyGeographyExactOrganization)) + if ( + !person.GetAuthority() + .HasPermission(Permission.CanSeeEconomyTransactions, organization.Identity, 1, + Authorization.Flag.AnyGeographyExactOrganization)) { return; } @@ -238,14 +247,14 @@ namespace Swarmops.Logic.DashboardTasks { if (invoice.DueDate < threshold && !invoice.Attested) { - group.Tasks.Add(new TaskAttestationLate (invoice)); + group.Tasks.Add(new TaskAttestationLate(invoice)); } } if (group.Tasks.Count > 0) { - this.Add(group); + Add(group); } } } -} +} \ No newline at end of file diff --git a/Logic/DataObjects/ExpensesDataObject.cs b/Logic/DataObjects/ExpensesDataObject.cs index 990ce56d..51f00222 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 5be752d1..0e7a3a89 100644 --- a/Logic/DataObjects/GeographyWithPeopleDataObject.cs +++ b/Logic/DataObjects/GeographyWithPeopleDataObject.cs @@ -10,11 +10,10 @@ namespace Swarmops.Logic.DataObjects #endif public class GeographyWithPeopleDataObject { - #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static GeographyWithPeople[] SelectSortedStatic (int orgId) + public static GeographyWithPeople[] SelectSortedStatic(int orgId) { Organizations orgs = Organization.FromIdentity(orgId).GetTree(); @@ -31,15 +30,12 @@ namespace Swarmops.Logic.DataObjects row.SecondsContent = ""; row.OrgId = orgId; Geographies gTree = geo.GetTree(); - int[] members = SwarmDb.GetDatabaseForReading().GetMembersForOrganizationsAndGeographies(orgs.Identities, gTree.Identities); - - + int[] members = SwarmDb.GetDatabaseForReading() + .GetMembersForOrganizationsAndGeographies(orgs.Identities, gTree.Identities); } return resList.ToArray(); - } - } } \ No newline at end of file diff --git a/Logic/DataObjects/MembershipsDataObject.cs b/Logic/DataObjects/MembershipsDataObject.cs index 3b520e84..3cdc2180 100644 --- a/Logic/DataObjects/MembershipsDataObject.cs +++ b/Logic/DataObjects/MembershipsDataObject.cs @@ -5,30 +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))).ToArray(); + return + 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 9816aebd..a64772f9 100644 --- a/Logic/DataObjects/OrganizationDataObject.cs +++ b/Logic/DataObjects/OrganizationDataObject.cs @@ -6,7 +6,6 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.DataObjects { - #if !__MonoCS__ [DataObject(true)] #endif @@ -14,219 +13,139 @@ namespace Swarmops.Logic.DataObjects { public class Org : Organization { - private string parentName; - private string anchorName; private string countryCode; - public Org () - : base() + public Org() { } - public Org (Organization org) + public Org(Organization org) : base(org) { try { - parentName = Organization.FromIdentity(ParentOrganizationId).Name; + ParentName = FromIdentity(ParentOrganizationId).Name; } catch { - parentName = "N/A"; + ParentName = "N/A"; } try { - anchorName = Geography.FromIdentity(AnchorGeographyId).Name; + AnchorName = Geography.FromIdentity(AnchorGeographyId).Name; } catch { - anchorName = "N/A"; + AnchorName = "N/A"; } try { - countryCode = base.DefaultCountry.Code; + this.countryCode = base.DefaultCountry.Code; } catch { - countryCode = "N/A"; + this.countryCode = "N/A"; } } #region Properties for fields + public new bool AcceptsMembers { - get - { - return base.AcceptsMembers; - } - set - { - base.AcceptsMembers = value; - } + get { return base.AcceptsMembers; } + set { base.AcceptsMembers = value; } } + public new int AnchorGeographyId { - get - { - return base.AnchorGeographyId; - } - set - { - base.AnchorGeographyId = value; - } + get { return base.AnchorGeographyId; } + set { base.AnchorGeographyId = value; } } + public new bool AutoAssignNewMembers { - get - { - return base.AutoAssignNewMembers; - } - set - { - base.AutoAssignNewMembers = value; - } + get { return base.AutoAssignNewMembers; } + set { base.AutoAssignNewMembers = value; } } + public new string Domain { - get - { - return base.Domain; - } - set - { - base.Domain = value; - } + get { return base.Domain; } + set { base.Domain = value; } } + public new string MailPrefix { - get - { - return base.MailPrefix; - } - set - { - base.MailPrefix = value; - } + get { return base.MailPrefix; } + set { base.MailPrefix = value; } } + public new string Name { - get - { - return base.Name; - } - set - { - base.Name = value; - } + get { return base.Name; } + set { base.Name = value; } } + public new string NameInternational { - get - { - return base.NameInternational; - } - set - { - base.NameInternational = value; - } + get { return base.NameInternational; } + set { base.NameInternational = value; } } + public new int Identity { - get - { - return base.OrganizationId; - } - set - { - base.OrganizationId = value; - } + get { return base.OrganizationId; } + set { base.OrganizationId = value; } } + public new string NameShort { - get - { - return base.NameShort; - } - set - { - base.NameShort = value; - } + get { return base.NameShort; } + set { base.NameShort = value; } } + public new int ParentOrganizationId { - get - { - return base.ParentOrganizationId; - } - set - { - base.ParentOrganizationId = value; - } + get { return base.ParentOrganizationId; } + set { base.ParentOrganizationId = value; } } public new int DefaultCountryId { - get - { - return base.DefaultCountryId; - } - set - { - base.DefaultCountryId = value; - } + get { return base.DefaultCountryId; } + set { base.DefaultCountryId = value; } } + #endregion - public string ParentName - { - get - { - return parentName; - } - set - { - parentName = value; - } - } - public string AnchorName - { - get - { - return anchorName; - } - set - { - anchorName = value; - } - } + + public string ParentName { get; set; } + + public string AnchorName { get; set; } + public string CountryCode { get { - if ("" + countryCode == "") - countryCode = base.DefaultCountry.Code; - return countryCode; - } - set - { - countryCode = value; + if ("" + this.countryCode == "") + this.countryCode = base.DefaultCountry.Code; + return this.countryCode; } + set { this.countryCode = value; } } } public class UptakeGeography : Structure.UptakeGeography { - public UptakeGeography () - : base() + public UptakeGeography() { } - - public UptakeGeography (Structure.UptakeGeography other) - : base(other) - { - - } - internal static UptakeGeography fromUptake (Structure.UptakeGeography up) + public UptakeGeography(Structure.UptakeGeography other) + : base(other) + { + } + + internal static UptakeGeography fromUptake(Structure.UptakeGeography up) { return new UptakeGeography(up); } @@ -235,7 +154,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select, true)] #endif - public static Org[] Select () + public static Org[] Select() { List res = new List(); @@ -251,7 +170,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select, true)] #endif - public static Org Select (int orgid) + public static Org Select(int orgid) { try { @@ -266,7 +185,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Organization[] Select (int[] OrganizationIds) + public static Organization[] Select(int[] OrganizationIds) { if (OrganizationIds == null) { @@ -279,7 +198,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Organization[] SelectStatic (Organization[] OrganizationArray) + public static Organization[] SelectStatic(Organization[] OrganizationArray) { if (OrganizationArray == null) { @@ -292,7 +211,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Organization[] SelectStatic (Organizations Organizations) + public static Organization[] SelectStatic(Organizations Organizations) { if (Organizations == null) { @@ -306,7 +225,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Organization[] SelectSortedStatic (Organizations Organizations, string sort) + public static Organization[] SelectSortedStatic(Organizations Organizations, string sort) { if (Organizations == null) { @@ -315,7 +234,7 @@ namespace Swarmops.Logic.DataObjects List pList = new List(); - Organization[] foundOrganizations = SelectStatic((Organizations)Organizations); + Organization[] foundOrganizations = SelectStatic(Organizations); foreach (Organization pers in foundOrganizations) { pList.Add(pers); @@ -323,20 +242,19 @@ namespace Swarmops.Logic.DataObjects switch (sort) { - case "OrganizationId": pList.Sort(IdentityComparison); break; + case "OrganizationId": + pList.Sort(IdentityComparison); + break; } return pList.ToArray(); } - - - #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Insert, true)] #endif - public int AddOrganization (Org org) + public int AddOrganization(Org org) { try { @@ -356,9 +274,8 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Update, false)] #endif - public int AddDuplicateOrganization (Org org) + public int AddDuplicateOrganization(Org org) { - AddOrganization(org); return org.Identity; } @@ -366,7 +283,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Update, true)] #endif - public bool UpdateOrganisation (Org org) + public bool UpdateOrganisation(Org org) { try { @@ -392,7 +309,7 @@ namespace Swarmops.Logic.DataObjects } } - 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(); @@ -417,23 +334,21 @@ namespace Swarmops.Logic.DataObjects } - public static Comparison IdentityComparison = delegate(Organization p1, Organization p2) - { - return p1.OrganizationId.CompareTo(p2.OrganizationId); - }; + public static Comparison IdentityComparison = + delegate(Organization p1, Organization p2) { return p1.OrganizationId.CompareTo(p2.OrganizationId); }; ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// - + private static UptakeGeography[] UptakeFromArray(Structure.UptakeGeography[] inputArray) { - List retlist=new List(); - - foreach(Structure.UptakeGeography up in inputArray) + List retlist = new List(); + + foreach (Structure.UptakeGeography up in inputArray) { - retlist.Add(UptakeGeography.fromUptake(up)); + retlist.Add(UptakeGeography.fromUptake(up)); } return retlist.ToArray(); } @@ -441,7 +356,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select, false)] #endif - public static UptakeGeography[] SelectOrgMineUptake (int orgid) + public static UptakeGeography[] SelectOrgMineUptake(int orgid) { try { @@ -452,10 +367,11 @@ namespace Swarmops.Logic.DataObjects return null; } } + #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select, false)] #endif - public static UptakeGeography[] SelectOrgOthersUptake (int orgid) + public static UptakeGeography[] SelectOrgOthersUptake(int orgid) { try { @@ -470,12 +386,13 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [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)); + UptakeGeography[] unfiltered = + UptakeFromArray(Organization.FromIdentity(orgid).GetUptakeGeographies(true)); foreach (UptakeGeography bu in unfiltered) { if (bu.GeoId == geoid) @@ -489,7 +406,7 @@ namespace Swarmops.Logic.DataObjects } } - public static void UpdateOrgUptake (int orgid, int[] newUptakeGeos) + public static void UpdateOrgUptake(int orgid, int[] newUptakeGeos) { try { @@ -523,7 +440,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [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); @@ -534,7 +451,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [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); @@ -542,8 +459,5 @@ namespace Swarmops.Logic.DataObjects // Return true if precisely one row was inserted, otherwise false return true; } - } - - } \ No newline at end of file diff --git a/Logic/DataObjects/PeopleDataObject.cs b/Logic/DataObjects/PeopleDataObject.cs index 55fb7bd3..98f2cac2 100644 --- a/Logic/DataObjects/PeopleDataObject.cs +++ b/Logic/DataObjects/PeopleDataObject.cs @@ -13,7 +13,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Person[] Select (int[] personIds) + public static Person[] Select(int[] personIds) { if (personIds == null) { @@ -26,7 +26,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Person[] SelectStatic (Person[] personArray) + public static Person[] SelectStatic(Person[] personArray) { if (personArray == null) { @@ -39,7 +39,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Person[] SelectStatic (People people) + public static Person[] SelectStatic(People people) { if (people == null) { @@ -53,7 +53,7 @@ namespace Swarmops.Logic.DataObjects #if !__MonoCS__ [DataObjectMethod(DataObjectMethodType.Select)] #endif - public static Person[] SelectSortedStatic (People people, string sort) + public static Person[] SelectSortedStatic(People people, string sort) { if (people == null) { @@ -62,7 +62,7 @@ namespace Swarmops.Logic.DataObjects List pList = new List(); - Person[] foundPersons = SelectStatic((People)people); + Person[] foundPersons = SelectStatic(people); foreach (Person pers in foundPersons) { pList.Add(pers); @@ -70,29 +70,39 @@ namespace Swarmops.Logic.DataObjects switch (sort) { - case "PersonId": pList.Sort(PersonIdComparison); break; - case "Name": pList.Sort(NameComparison); break; - case "PostalCode": pList.Sort(PostalCodeComparison); break; - case "CityName": pList.Sort(CityComparison); break; - case "Birthdate": pList.Sort(BirthdateComparison); break; + case "PersonId": + pList.Sort(PersonIdComparison); + break; + case "Name": + pList.Sort(NameComparison); + break; + case "PostalCode": + pList.Sort(PostalCodeComparison); + break; + case "CityName": + pList.Sort(CityComparison); + break; + case "Birthdate": + pList.Sort(BirthdateComparison); + break; - // New sortexpressions - case "Email": pList.Sort(EmailComparison); break; - case "Phone": pList.Sort(PhoneComparison); break; + // New sortexpressions + case "Email": + pList.Sort(EmailComparison); + break; + case "Phone": + pList.Sort(PhoneComparison); + break; } return pList.ToArray(); } - public static Comparison PersonIdComparison = delegate(Person p1, Person p2) - { - return p1.PersonId.CompareTo(p2.PersonId); - }; + public static Comparison PersonIdComparison = + 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); - }; + public static Comparison NameComparison = + delegate(Person p1, Person p2) { return p1.Name.CompareTo(p2.Name); }; public static Comparison CityComparison = delegate(Person p1, Person p2) { @@ -110,10 +120,8 @@ namespace Swarmops.Logic.DataObjects return cmpRes; }; - public static Comparison BirthdateComparison = delegate(Person p1, Person p2) - { - return p1.Birthdate.CompareTo(p2.Birthdate); - }; + public static Comparison BirthdateComparison = + 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) @@ -131,6 +139,5 @@ namespace Swarmops.Logic.DataObjects cmpRes = p1.Name.CompareTo(p2.Name); return cmpRes; }; - } } \ No newline at end of file diff --git a/Logic/DataObjects/RolesDataObject.cs b/Logic/DataObjects/RolesDataObject.cs index 1df62497..2b365bd7 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/SEPaymentsBankgiroReader.cs b/Logic/Financial/BankDataReaders/SEPaymentsBankgiroReader.cs index 9a8d3064..b7ce63af 100644 --- a/Logic/Financial/BankDataReaders/SEPaymentsBankgiroReader.cs +++ b/Logic/Financial/BankDataReaders/SEPaymentsBankgiroReader.cs @@ -1,8 +1,7 @@ namespace Swarmops.Logic.Financial.BankDataReaders { // ReSharper disable once InconsistentNaming - class SEPaymentsBankgiroReader: IBankDataPaymentsReader + internal class SEPaymentsBankgiroReader : IBankDataPaymentsReader { - } -} +} \ No newline at end of file diff --git a/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs b/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs index 1f20998a..1ae3471f 100644 --- a/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs +++ b/Logic/Financial/BankDataReaders/TabSeparatedValuesReader.cs @@ -3,11 +3,11 @@ using System.IO; namespace Swarmops.Logic.Financial.BankDataReaders { - public class TabSeparatedValuesReader: IBankDataAccountStatementReader + public class TabSeparatedValuesReader : IBankDataAccountStatementReader { public ImportedBankData ReadData(StreamReader data, FinancialAccount account, ExternalBankDataProfile profile) { throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/CashAdvance.cs b/Logic/Financial/CashAdvance.cs index f1c1c29b..fd28e415 100644 --- a/Logic/Financial/CashAdvance.cs +++ b/Logic/Financial/CashAdvance.cs @@ -12,81 +12,78 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { [Serializable] - public class CashAdvance: BasicCashAdvance, IAttestable + public class CashAdvance : BasicCashAdvance, IAttestable { #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); } - public static CashAdvance FromIdentity (int cashAdvanceId) + public static CashAdvance FromIdentity(int 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)); } - public static CashAdvance Create(Organization organization, Person forPerson, Person createdByPerson, Int64 amountCents, FinancialAccount budget, string description) + public static CashAdvance Create(Organization organization, Person forPerson, Person createdByPerson, + Int64 amountCents, FinancialAccount budget, string description) { - CashAdvance newAdvance = FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreateCashAdvance(forPerson.Identity, - createdByPerson.Identity, - organization.Identity, - budget.Identity, amountCents, - description)); + CashAdvance newAdvance = + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreateCashAdvance(forPerson.Identity, + createdByPerson.Identity, + organization.Identity, + budget.Identity, amountCents, + description)); - OutboundComm.CreateNotificationAttestationNeeded(budget, forPerson, string.Empty, (double) amountCents/100.0, description, NotificationResource.CashAdvance_Requested); // Slightly misplaced logic, but failsafer here + 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, (double) amountCents/100.0, budget, description), - newAdvance); + new CashAdvanceRequestedLogEntry(createdByPerson, forPerson, amountCents/100.0, budget, description), + newAdvance); return newAdvance; } #endregion - - #region Implementation of IAttestable public void Attest(Person attester) { SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.CashAdvance, this.Identity, DateTime.Now, attester.Identity, this.AmountCents / 100.0); - SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(this.Identity, true, attester.Identity); + FinancialDependencyType.CashAdvance, Identity, DateTime.Now, attester.Identity, AmountCents/100.0); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(Identity, true, attester.Identity); - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Person, (double)this.AmountCents / 100.0, this.Description, NotificationResource.CashAdvance_Attested); + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Person, AmountCents/100.0, Description, + NotificationResource.CashAdvance_Attested); } public void Deattest(Person deattester) { SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, - FinancialDependencyType.CashAdvance, this.Identity, DateTime.Now, deattester.Identity, this.AmountCents / 100.0); - SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(this.Identity, false, Person.NobodyId); + FinancialDependencyType.CashAdvance, Identity, DateTime.Now, deattester.Identity, AmountCents/100.0); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceAttested(Identity, false, Person.NobodyId); - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Person, (double)this.AmountCents / 100.0, this.Description, NotificationResource.CashAdvance_Deattested); + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Person, AmountCents/100.0, Description, + NotificationResource.CashAdvance_Deattested); } #endregion - - public Person Person + public Person Person { - get { return Person.FromIdentity(this.PersonId); } - } - - public FinancialAccount Budget - { - get { return FinancialAccount.FromIdentity(this.BudgetId); } + get { return Person.FromIdentity(PersonId); } } public new bool Open @@ -99,7 +96,7 @@ namespace Swarmops.Logic.Financial return; } - SwarmDb.GetDatabaseForWriting().SetCashAdvanceOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetCashAdvanceOpen(Identity, value); base.Open = value; } } @@ -114,7 +111,7 @@ namespace Swarmops.Logic.Financial return; } - SwarmDb.GetDatabaseForWriting().SetCashAdvancePaidOut(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetCashAdvancePaidOut(Identity, value); base.PaidOut = value; } } @@ -124,7 +121,7 @@ namespace Swarmops.Logic.Financial { get { - if (!this.PaidOut) + if (!PaidOut) { return null; // or throw? } @@ -145,13 +142,14 @@ namespace Swarmops.Logic.Financial { get { - if (!this.PaidOut) + if (!PaidOut) { return null; // or throw? } int payoutId = - SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(this, FinancialDependencyType.CashAdvancePayback); + SwarmDb.GetDatabaseForReading() + .GetPayoutIdFromDependency(this, FinancialDependencyType.CashAdvancePayback); if (payoutId == 0) { @@ -161,5 +159,10 @@ namespace Swarmops.Logic.Financial return Payout.FromIdentity(payoutId); } } + + public FinancialAccount Budget + { + get { return FinancialAccount.FromIdentity(BudgetId); } + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/CashAdvances.cs b/Logic/Financial/CashAdvances.cs index 939cd1c1..d1bfbc8a 100644 --- a/Logic/Financial/CashAdvances.cs +++ b/Logic/Financial/CashAdvances.cs @@ -7,19 +7,8 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class CashAdvances: PluralBase + public class CashAdvances : PluralBase { - static public CashAdvances ForOrganization(Organization organization) - { - return ForOrganization(organization, false); - } - - static public CashAdvances ForOrganization(Organization organization, bool includeClosed) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetCashAdvances(organization, - includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); - } - public CashAdvances WhereUnattested { get @@ -68,5 +57,16 @@ namespace Swarmops.Logic.Financial { get { return this.Sum(cashAdvance => cashAdvance.AmountCents); } } + + public static CashAdvances ForOrganization(Organization organization) + { + return ForOrganization(organization, false); + } + + public static CashAdvances ForOrganization(Organization organization, bool includeClosed) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetCashAdvances(organization, + includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Currencies.cs b/Logic/Financial/Currencies.cs index 3d7a55ba..be783973 100644 --- a/Logic/Financial/Currencies.cs +++ b/Logic/Financial/Currencies.cs @@ -1,18 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Swarmops.Basic.Types; +using Swarmops.Basic.Types; using Swarmops.Database; using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class Currencies: PluralBase + public class Currencies : PluralBase { public static Currencies GetAll() { return FromArray(SwarmDb.GetDatabaseForReading().GetCurrencies()); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Currency.cs b/Logic/Financial/Currency.cs index 6141f778..2d802ee1 100644 --- a/Logic/Financial/Currency.cs +++ b/Logic/Financial/Currency.cs @@ -1,44 +1,15 @@ -using System; using Swarmops.Basic.Types; using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class Currency: BasicCurrency + public class Currency : BasicCurrency { - private Currency (BasicCurrency basic): base (basic) + private Currency(BasicCurrency basic) : base(basic) { // empty ctor } - public static Currency FromBasic (BasicCurrency basic) - { - return new Currency(basic); - } - - public static Currency FromIdentity(int currencyId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(currencyId)); - } - - public static Currency FromIdentityAggressive(int currencyId) - { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetCurrency(currencyId)); // "For writing" is intentional - replication timing issue - } - - public static Currency FromCode(string code) - { - code = code.ToUpperInvariant(); - - return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(code)); - } - - public static Currency Create (string code, string name, string sign) - { - return FromIdentityAggressive( - SwarmDb.GetDatabaseForWriting().CreateCurrency(code, name, sign)); - } - public string DisplayCode { get @@ -51,5 +22,34 @@ namespace Swarmops.Logic.Financial return base.Code; } } + + public static Currency FromBasic(BasicCurrency basic) + { + return new Currency(basic); + } + + public static Currency FromIdentity(int currencyId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(currencyId)); + } + + public static Currency FromIdentityAggressive(int currencyId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetCurrency(currencyId)); + // "For writing" is intentional - replication timing issue + } + + public static Currency FromCode(string code) + { + code = code.ToUpperInvariant(); + + return FromBasic(SwarmDb.GetDatabaseForReading().GetCurrency(code)); + } + + public static Currency Create(string code, string name, string 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 2ceaa670..b0ec9a42 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -16,17 +16,17 @@ 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) @@ -36,17 +36,20 @@ namespace Swarmops.Logic.Financial 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, - DateTime expenseDate, string description, Int64 amountCents) + 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, - budget.Identity, expenseDate, description, amountCents)); + ExpenseClaim newClaim = + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() + .CreateExpenseClaim(claimer.Identity, organization.Identity, + budget.Identity, expenseDate, description, amountCents)); // Create the financial transaction with rows - string transactionDescription = "Expense #" + newClaim.Identity + ": " + description; // TODO: Localize + string transactionDescription = "Expense #" + newClaim.Identity + ": " + description; // TODO: Localize if (transactionDescription.Length > 64) { @@ -55,22 +58,24 @@ namespace Swarmops.Logic.Financial FinancialTransaction transaction = FinancialTransaction.Create(organization.Identity, DateTime.Now, - transactionDescription); + transactionDescription); transaction.AddRow(organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); transaction.AddRow(budget, amountCents, claimer); - + // Make the transaction dependent on the expense claim transaction.Dependency = newClaim; // Create notifications - OutboundComm.CreateNotificationAttestationNeeded(budget, claimer, string.Empty, (double)amountCents / 100.0, description, NotificationResource.ExpenseClaim_Created); // Slightly misplaced logic, but failsafer here - OutboundComm.CreateNotificationFinancialValidationNeeded(organization, (double) amountCents/100.0, - NotificationResource.Receipts_Filed); + 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, + NotificationResource.Receipts_Filed); SwarmopsLogEntry.Create(claimer, - new ExpenseClaimFiledLogEntry(claimer /*filing person*/, claimer /*beneficiary*/, (double) amountCents/100.0, budget, description), newClaim); + new ExpenseClaimFiledLogEntry(claimer /*filing person*/, claimer /*beneficiary*/, amountCents/100.0, + budget, description), newClaim); return newClaim; } @@ -79,40 +84,15 @@ namespace Swarmops.Logic.Financial public Person Claimer { - get { return Person.FromIdentity (base.ClaimingPersonId); } - } - - [Obsolete("Obsolete", true)] - public void CreateEvent (ExpenseEventType eventType, Person person) - { - // OBSOLETE - - // CreateEvent (eventType, person.Identity); - } - - public void CreateEvent (ExpenseEventType eventType, int personId) - { - // OBSOLETE - - // SwarmDb.GetDatabaseForWriting().CreateExpenseEvent (Identity, eventType, personId); - - // TODO: Repopulate Events property, when created + get { return Person.FromIdentity(base.ClaimingPersonId); } } public bool Approved { - get - { - return Validated && Attested; - } + get { return Validated && Attested; } } - public void Close() - { - this.Open = false; - } - public string ClaimerCanonical { get @@ -130,7 +110,7 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get { return Organization.FromIdentity(this.OrganizationId); } + get { return Organization.FromIdentity(OrganizationId); } } public FinancialTransaction FinancialTransaction @@ -144,27 +124,24 @@ namespace Swarmops.Logic.Financial return null; // not possible from July 26 onwards, but some grandfather work } - else if (transactions.Count == 1) + if (transactions.Count == 1) { return transactions[0]; } - throw new InvalidOperationException("It appears expense claim #" + this.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."); } } public new bool Attested { - get - { - return base.Attested; - } + get { return base.Attested; } set { if (base.Attested != value) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, value); base.Attested = value; } } @@ -172,15 +149,12 @@ namespace Swarmops.Logic.Financial public new bool Validated { - get - { - return base.Validated; - } + get { return base.Validated; } set { if (base.Validated != value) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, value); base.Validated = value; } } @@ -194,10 +168,9 @@ namespace Swarmops.Logic.Financial if (base.Open != value) { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimOpen(Identity, value); } } - } public new bool Claimed @@ -208,11 +181,10 @@ namespace Swarmops.Logic.Financial if (base.Claimed != value) { base.Claimed = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimClaimed(this.Identity, value); - UpdateFinancialTransaction(this.Claimer); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimClaimed(Identity, value); + UpdateFinancialTransaction(Claimer); } } - } public new bool Repaid @@ -223,10 +195,9 @@ namespace Swarmops.Logic.Financial if (base.Repaid != value) { base.Repaid = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimRepaid(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimRepaid(Identity, value); } } - } public new bool KeepSeparate @@ -237,39 +208,24 @@ namespace Swarmops.Logic.Financial if (base.KeepSeparate != value) { base.KeepSeparate = value; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimKeepSeparate(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimKeepSeparate(Identity, value); } } - } public new string Description { - get - { - return base.Description; - } + get { return base.Description; } set { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimDescription(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimDescription(Identity, value); base.Description = value; } } - public FinancialAccount Budget - { - get - { - return FinancialAccount.FromIdentity(base.BudgetId); - } - } - public int BudgetYear { - get - { - return this.CreatedDateTime.Year; - } + get { return CreatedDateTime.Year; } set { // ignore @@ -278,10 +234,7 @@ namespace Swarmops.Logic.Financial public decimal Amount { - get - { - return base.AmountCents / 100.0m; - } + get { return base.AmountCents/100.0m; } } public new Int64 AmountCents @@ -289,48 +242,9 @@ namespace Swarmops.Logic.Financial get { return base.AmountCents; } } - public void SetAmountCents (Int64 amountCents, Person settingPerson) - { - if (base.AmountCents == amountCents) - { - return; - } - - base.AmountCents = amountCents; - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAmount(this.Identity, amountCents); - UpdateFinancialTransaction(settingPerson); - } - - - public void SetBudget (FinancialAccount budget, Person settingPerson) - { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimBudget (this.Identity, budget.Identity); - base.BudgetId = budget.Identity; - UpdateFinancialTransaction(settingPerson); - } - - - public void Kill (Person killingPerson) - { - // Set the state to Closed, Unvalidated, Unattested - - Attested = false; - Validated = false; - Open = false; - - UpdateFinancialTransaction(killingPerson); // will zero out transaction since both Validated and Open are false - - // Mark transaction as invalid in description - - FinancialTransaction.Description = "Expense Claim #" + this.Identity.ToString() + " (killed/zeroed)"; - } - public new DateTime ExpenseDate { - get - { - return base.ExpenseDate; - } + get { return base.ExpenseDate; } set { // TODO @@ -349,41 +263,11 @@ namespace Swarmops.Logic.Financial get { return FinancialValidations.ForObject(this); } } - - public void Recalibrate() - { - UpdateFinancialTransaction(null); // only to be used for fix-bookkeeping scripts - } - - - private void UpdateFinancialTransaction(Person updatingPerson) - { - Dictionary nominalTransaction = new Dictionary(); - - int debtAccountId = this.Organization.FinancialAccounts.DebtsExpenseClaims.Identity; - - if (!this.Claimed) - { - debtAccountId = this.Organization.FinancialAccounts.CostsAllocatedFunds.Identity; - } - - if (this.Validated || this.Open) - { - // ...only holds values if not closed as invalid... - - nominalTransaction[debtAccountId] = -AmountCents; - nominalTransaction[BudgetId] = AmountCents; - } - - this.FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); - } - - public Payout Payout { get { - if (this.Open) + if (Open) { return null; // or throw? } @@ -400,59 +284,153 @@ namespace Swarmops.Logic.Financial } } - #region IValidatable Members public void Validate(Person validator) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(this.Identity, true); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, true); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Validation, - FinancialDependencyType.ExpenseClaim, this.Identity, - DateTime.Now, validator.Identity, (double) this.Amount); + FinancialDependencyType.ExpenseClaim, Identity, + DateTime.Now, validator.Identity, (double) Amount); base.Validated = true; - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Claimer, (double)this.AmountCents / 100.0, this.Description, NotificationResource.ExpenseClaim_Validated); + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + NotificationResource.ExpenseClaim_Validated); } - public void Devalidate (Person devalidator) + public void Devalidate(Person devalidator) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(this.Identity, false); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimValidated(Identity, false); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Devalidation, - FinancialDependencyType.ExpenseClaim, this.Identity, - DateTime.Now, devalidator.Identity, (double) this.Amount); + FinancialDependencyType.ExpenseClaim, Identity, + DateTime.Now, devalidator.Identity, (double) Amount); base.Validated = false; - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Claimer, (double)this.AmountCents / 100.0, this.Description, NotificationResource.ExpenseClaim_Devalidated); + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + NotificationResource.ExpenseClaim_Devalidated); } #endregion - #region IAttestable Members public void Attest(Person attester) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(this.Identity, true); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, true); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.ExpenseClaim, this.Identity, - DateTime.Now, attester.Identity, (double) this.Amount); + FinancialDependencyType.ExpenseClaim, Identity, + DateTime.Now, attester.Identity, (double) Amount); base.Attested = true; - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Claimer, (double)this.AmountCents/100.0, this.Description, NotificationResource.ExpenseClaim_Attested); - + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + NotificationResource.ExpenseClaim_Attested); } public void Deattest(Person deattester) { - SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(this.Identity, false); + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAttested(Identity, false); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, - FinancialDependencyType.ExpenseClaim, this.Identity, - DateTime.Now, deattester.Identity, (double) this.Amount); + FinancialDependencyType.ExpenseClaim, Identity, + DateTime.Now, deattester.Identity, (double) Amount); base.Attested = false; - OutboundComm.CreateNotificationOfFinancialValidation(this.Budget, this.Claimer, (double)this.AmountCents / 100.0, this.Description, NotificationResource.ExpenseClaim_Deattested); + OutboundComm.CreateNotificationOfFinancialValidation(Budget, Claimer, this.AmountCents/100.0, Description, + NotificationResource.ExpenseClaim_Deattested); } #endregion + + public FinancialAccount Budget + { + get { return FinancialAccount.FromIdentity(base.BudgetId); } + } + + [Obsolete("Obsolete", true)] + public void CreateEvent(ExpenseEventType eventType, Person person) + { + // OBSOLETE + + // CreateEvent (eventType, person.Identity); + } + + public void CreateEvent(ExpenseEventType eventType, int personId) + { + // OBSOLETE + + // SwarmDb.GetDatabaseForWriting().CreateExpenseEvent (Identity, eventType, personId); + + // TODO: Repopulate Events property, when created + } + + public void Close() + { + Open = false; + } + + public void SetAmountCents(Int64 amountCents, Person settingPerson) + { + if (base.AmountCents == amountCents) + { + return; + } + + base.AmountCents = amountCents; + SwarmDb.GetDatabaseForWriting().SetExpenseClaimAmount(Identity, amountCents); + UpdateFinancialTransaction(settingPerson); + } + + + public void SetBudget(FinancialAccount budget, Person settingPerson) + { + SwarmDb.GetDatabaseForWriting().SetExpenseClaimBudget(Identity, budget.Identity); + base.BudgetId = budget.Identity; + UpdateFinancialTransaction(settingPerson); + } + + + public void Kill(Person killingPerson) + { + // Set the state to Closed, Unvalidated, Unattested + + Attested = false; + Validated = false; + Open = false; + + UpdateFinancialTransaction(killingPerson); + // will zero out transaction since both Validated and Open are false + + // Mark transaction as invalid in description + + FinancialTransaction.Description = "Expense Claim #" + Identity + " (killed/zeroed)"; + } + + + public void Recalibrate() + { + UpdateFinancialTransaction(null); // only to be used for fix-bookkeeping scripts + } + + + private void UpdateFinancialTransaction(Person updatingPerson) + { + Dictionary nominalTransaction = new Dictionary(); + + int debtAccountId = Organization.FinancialAccounts.DebtsExpenseClaims.Identity; + + if (!Claimed) + { + debtAccountId = Organization.FinancialAccounts.CostsAllocatedFunds.Identity; + } + + if (Validated || Open) + { + // ...only holds values if not closed as invalid... + + nominalTransaction[debtAccountId] = -AmountCents; + nominalTransaction[BudgetId] = AmountCents; + } + + FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); + } } } \ No newline at end of file diff --git a/Logic/Financial/ExpenseClaims.cs b/Logic/Financial/ExpenseClaims.cs index fd997b94..5f957dee 100644 --- a/Logic/Financial/ExpenseClaims.cs +++ b/Logic/Financial/ExpenseClaims.cs @@ -8,13 +8,13 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class ExpenseClaims : PluralBase + public class ExpenseClaims : PluralBase { public ExpenseClaims WhereOpen { get { - var result = new ExpenseClaims(); + ExpenseClaims result = new ExpenseClaims(); result.AddRange(this.Where(expense => expense.Open)); return result; @@ -25,7 +25,7 @@ namespace Swarmops.Logic.Financial { get { - var result = new ExpenseClaims(); + ExpenseClaims result = new ExpenseClaims(); result.AddRange(this.Where(expense => expense.Approved)); return result; @@ -36,7 +36,7 @@ namespace Swarmops.Logic.Financial { get { - var result = new ExpenseClaims(); + ExpenseClaims result = new ExpenseClaims(); result.AddRange(this.Where(expense => !expense.Approved)); return result; @@ -56,7 +56,6 @@ namespace Swarmops.Logic.Financial } - public ExpenseClaims WhereUnvalidated { get @@ -68,60 +67,48 @@ namespace Swarmops.Logic.Financial } } + public decimal TotalAmount + { + get { return this.Sum(claim => claim.Amount); } + } + + public Int64 TotalAmountCents + { + get { return this.Sum(claim => claim.AmountCents); } + } public static ExpenseClaims FromClaimingPersonAndOrganization(Person person, Organization organization) { return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaimsByClaimerAndOrganization(person.Identity, - organization.Identity)); + organization.Identity)); } - public static ExpenseClaims FromClaimingPerson (Person person) + public static ExpenseClaims FromClaimingPerson(Person person) { 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)); } - public static ExpenseClaims ForOrganization (Organization org) + public static ExpenseClaims ForOrganization(Organization org) { 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)); } - else - { - return FromArray(SwarmDb.GetDatabaseForReading().GetExpenseClaims(org, DatabaseCondition.OpenTrue)); - } - } - - - - public decimal TotalAmount - { - get - { - return this.Sum(claim => claim.Amount); - } - } - - public Int64 TotalAmountCents - { - get - { - return this.Sum(claim => claim.AmountCents); - } + 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 de0d4060..fad2141b 100644 --- a/Logic/Financial/ExternalBankData.cs +++ b/Logic/Financial/ExternalBankData.cs @@ -9,15 +9,19 @@ namespace Swarmops.Logic.Financial { public class ExternalBankData { + public long LatestAccountBalanceCents; + public ExternalBankDataProfile Profile { get; set; } + public ExternalBankDataRecord[] Records { get; private set; } + 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); } } - public void LoadData (TextReader reader, Organization organization) + public void LoadData(TextReader reader, Organization organization) { string data = reader.ReadToEnd(); LoadData(data, organization); @@ -41,7 +45,7 @@ namespace Swarmops.Logic.Financial string organizationCurrencyCode = organization.Currency.Code; - int crlfIndex = data.IndexOfAny(new char[] {'\n', '\r'}); + int crlfIndex = data.IndexOfAny(new[] {'\n', '\r'}); string fieldKeyLine = data.Substring(0, crlfIndex); @@ -63,16 +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(); - string[] lines = data.Split(new char[] {'\r', '\n'}); + string[] lines = data.Split(new[] {'\r', '\n'}); foreach (string lineData in lines) { @@ -101,7 +106,8 @@ namespace Swarmops.Logic.Financial if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Description)) { - newRecord.Description = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Description]]); + newRecord.Description = + StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Description]]); } if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.AccountBalance)) @@ -109,7 +115,8 @@ namespace Swarmops.Logic.Financial // 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]]); + string balanceString = + StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.AccountBalance]]); try { newRecord.AccountBalanceCents = ParseAmountString(balanceString); @@ -117,11 +124,12 @@ namespace Swarmops.Logic.Financial catch (Exception innerException) { throw new FormatException("Couldn't parse account balance string - \"" + balanceString + "\"", - innerException); + 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"); } @@ -150,12 +158,13 @@ namespace Swarmops.Logic.Financial } 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 = + DateTime.Parse(StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.DateTime]]), + new CultureInfo(Profile.Culture)); } 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 @@ -164,7 +173,8 @@ namespace Swarmops.Logic.Financial 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 + dateTime -= timeZone; + // 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? @@ -173,7 +183,9 @@ 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)) + if (dateTime.Year < 2014 && organization.Identity == 1 && + fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId) && + PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) { continue; // Do not import PayPal records from before 2013 } @@ -185,7 +197,8 @@ namespace Swarmops.Logic.Financial throw new ArgumentException("There must be a transaction amount field in the bank data profile"); } - string amountNetString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionNet]]); + string amountNetString = + StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionNet]]); newRecord.TransactionNetCents = ParseAmountString(amountNetString); @@ -209,14 +222,16 @@ namespace Swarmops.Logic.Financial } else { - newRecord.TransactionGrossCents = newRecord.TransactionNetCents; // if no "Gross" field, copy from net + newRecord.TransactionGrossCents = newRecord.TransactionNetCents; + // if no "Gross" field, copy from net } // Check for consistency of gross/net/fee: if (newRecord.TransactionNetCents != newRecord.TransactionGrossCents + newRecord.FeeCents) { - throw new InvalidDataException("For a record, the net transaction amount does not match the gross less the fee."); + throw new InvalidDataException( + "For a record, the net transaction amount does not match the gross less the fee."); } if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId)) @@ -225,7 +240,8 @@ namespace Swarmops.Logic.Financial } else if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.NotUniqueId)) { - newRecord.NotUniqueId = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.NotUniqueId]]); + newRecord.NotUniqueId = + StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.NotUniqueId]]); } recordList.Add(newRecord); @@ -233,11 +249,11 @@ namespace Swarmops.Logic.Financial if (Profile.LatestTransactionLocation == LatestTransactionLocation.Top) { - LatestAccountBalanceCents = recordList[0].AccountBalanceCents; + this.LatestAccountBalanceCents = recordList[0].AccountBalanceCents; } else if (Profile.LatestTransactionLocation == LatestTransactionLocation.Bottom) { - LatestAccountBalanceCents = recordList [recordList.Count- 1].AccountBalanceCents; + this.LatestAccountBalanceCents = recordList[recordList.Count - 1].AccountBalanceCents; } else { @@ -246,11 +262,11 @@ namespace Swarmops.Logic.Financial recordList.Sort(new ExternalBankDataRecord()); - this.Records = recordList.ToArray(); + 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. @@ -329,10 +345,6 @@ namespace Swarmops.Logic.Financial return input; } - - public ExternalBankDataProfile Profile { get; set; } - public ExternalBankDataRecord[] Records { get; private set; } - public long LatestAccountBalanceCents; } @@ -342,15 +354,22 @@ namespace Swarmops.Logic.Financial public class ExternalBankMismatchingDateTime { public DateTime DateTime; - public int MasterTransactionCount; public long MasterDeltaCents; - public int SwarmopsTransactionCount; - public long SwarmopsDeltaCents; + public int MasterTransactionCount; public ExternalBankMismatchingRecordDescription[] MismatchingRecords; + public long SwarmopsDeltaCents; + public int SwarmopsTransactionCount; } public class ExternalBankMismatchingRecordDescription { + public string Description; + public long[] MasterCents; // may have multiple txs with this description + public ExternalBankMismatchResyncAction[] ResyncActions; + public long[] SwarmopsCents; // may have multiple txs with this description + // public object[] TransactionDependencies; // matching the Swarmops array + public FinancialTransaction[] Transactions; // matching the Swarmops array + public ExternalBankMismatchingRecordDescription() { this.Description = string.Empty; @@ -359,61 +378,59 @@ namespace Swarmops.Logic.Financial // this.TransactionDependencies = new object[0]; this.ResyncActions = new ExternalBankMismatchResyncAction[0]; } - - public string Description; - public long[] MasterCents; // may have multiple txs with this description - public long[] SwarmopsCents; // may have multiple txs with this description - public ExternalBankMismatchResyncAction[] ResyncActions; - // public object[] TransactionDependencies; // matching the Swarmops array - public FinancialTransaction[] Transactions; // matching the Swarmops array } public class ExternalBankMismatchConstruction { - public ExternalBankMismatchConstruction() - { - Master = new Dictionary(); - Swarmops = new Dictionary(); - } - public Dictionary Master; public Dictionary Swarmops; + + public ExternalBankMismatchConstruction() + { + this.Master = new Dictionary(); + this.Swarmops = new Dictionary(); + } } public class ExternalBankMismatchingRecordConstruction { - public ExternalBankMismatchingRecordConstruction() - { - Cents = new List(); - this.Transactions = new List(); - } - public List Cents; public List Transactions; + + public ExternalBankMismatchingRecordConstruction() + { + this.Cents = new List(); + this.Transactions = new List(); + } } public enum ExternalBankMismatchResyncAction { Unknown = 0, + /// - /// No action necessary + /// No action necessary /// NoAction, + /// - /// Zero out and rewrite the Swarmops database transaction + /// Zero out and rewrite the Swarmops database transaction /// RewriteSwarmops, + /// - /// Zero out the Swarmops database transaction (it's not in the master) + /// Zero out the Swarmops database transaction (it's not in the master) /// DeleteSwarmops, + /// - /// Create a Swarmops transaction (master exists, not in Swarmops) + /// Create a Swarmops transaction (master exists, not in Swarmops) /// CreateSwarmops, + /// - /// No resync possible - manual action required + /// No resync possible - manual action required /// ManualAction } -} +} \ No newline at end of file diff --git a/Logic/Financial/ExternalBankDataProfile.cs b/Logic/Financial/ExternalBankDataProfile.cs index 970329f7..da0cff7d 100644 --- a/Logic/Financial/ExternalBankDataProfile.cs +++ b/Logic/Financial/ExternalBankDataProfile.cs @@ -6,16 +6,20 @@ namespace Swarmops.Logic.Financial { public class ExternalBankDataProfile { + public FeeSignage FeeSignage; + public LatestTransactionLocation LatestTransactionLocation; + public ExternalBankDateTimePrecision Precision; + private ExternalBankDataProfile() { - this.FieldNames = new Dictionary(); + FieldNames = new Dictionary(); } public string DateTimeFormatString { get { - switch (Precision) + switch (this.Precision) { case ExternalBankDateTimePrecision.Day: return "yyyy-MM-dd"; @@ -26,13 +30,31 @@ namespace Swarmops.Logic.Financial case ExternalBankDateTimePrecision.Microsecond: return "yyyy-MM-dd HH:mm:ss.ffffff"; default: - throw new NotImplementedException("Unknown ExternalDateTimePrecision: " + Precision.ToString()); + throw new NotImplementedException("Unknown ExternalDateTimePrecision: " + this.Precision); } - } } - static public ExternalBankDataProfile FromIdentity (int externalBankDataProfileId) + public static int SESebId + { + get { return 1; } + } // Ugly pre-db hacks + + public static int PaypalId + { + get { return 2; } + } + + public string Name { get; set; } + public Country Country { get; set; } + public string Culture { get; set; } + public string Currency { get; set; } + public string BankDataAccountReader { get; set; } + public string BankDataPaymentsReader { get; set; } + + public Dictionary FieldNames { get; private set; } + + public static ExternalBankDataProfile FromIdentity(int externalBankDataProfileId) { ExternalBankDataProfile result = new ExternalBankDataProfile(); @@ -89,21 +111,6 @@ namespace Swarmops.Logic.Financial throw new ArgumentException("Unrecognized profile Id"); } - - static public int SESebId { get { return 1; } } // Ugly pre-db hacks - static public int PaypalId { get { return 2; } } - - public string Name { get; set; } - public Country Country { get; set; } - public string Culture { get; set; } - public string Currency { get; set; } - public LatestTransactionLocation LatestTransactionLocation; - public ExternalBankDateTimePrecision Precision; - public FeeSignage FeeSignage; - public string BankDataAccountReader { get; set; } - public string BankDataPaymentsReader { get; set; } - - public Dictionary FieldNames { get; private set; } } public enum ExternalBankDataFieldName @@ -126,12 +133,14 @@ namespace Swarmops.Logic.Financial public enum LatestTransactionLocation { Unknown = 0, + /// - /// Latest transaction is at the top of the file (the first record, meaning reverse chrono order). + /// Latest transaction is at the top of the file (the first record, meaning reverse chrono order). /// Top, + /// - /// Latest transaction is at the bottom of the file (last record, chrono order). + /// Latest transaction is at the bottom of the file (last record, chrono order). /// Bottom } @@ -139,28 +148,34 @@ namespace Swarmops.Logic.Financial public enum ExternalBankDateTimePrecision { Unknown = 0, + /// - /// The external bank has day precision only. Typical for oldbanks. + /// The external bank has day precision only. Typical for oldbanks. /// Day, + /// - /// The external bank has minute (hour:minute) precision on top of day. + /// The external bank has minute (hour:minute) precision on top of day. /// Minute, + /// - /// The external bank tags transactions with hour, minute, and second. + /// The external bank tags transactions with hour, minute, and second. /// Second, + /// - /// The external bank has millisecond-level timestamps for transactions. Not implemented. + /// The external bank has millisecond-level timestamps for transactions. Not implemented. /// Millisecond, + /// - /// The external bank has microsecond-resolution timestamp for transactions + /// The external bank has microsecond-resolution timestamp for transactions /// Microsecond, + /// - /// The external bank has nanosecond-resolution timestamp for transactions + /// The external bank has nanosecond-resolution timestamp for transactions /// Nanosecond } @@ -168,13 +183,15 @@ namespace Swarmops.Logic.Financial public enum FeeSignage { Unknown = 0, + /// - /// The transaction fee is positively listed (as a positive number), so that gross - fee = net. + /// The transaction fee is positively listed (as a positive number), so that gross - fee = net. /// Positive, + /// - /// The transaction fee is listed as negative, so that gross + fee = net. Example: Paypal. + /// The transaction fee is listed as negative, so that gross + fee = net. Example: Paypal. /// Negative } -} +} \ No newline at end of file diff --git a/Logic/Financial/ExternalBankDataRecord.cs b/Logic/Financial/ExternalBankDataRecord.cs index 8ea28239..50bff7f9 100644 --- a/Logic/Financial/ExternalBankDataRecord.cs +++ b/Logic/Financial/ExternalBankDataRecord.cs @@ -5,16 +5,19 @@ using Swarmops.Logic.Security; namespace Swarmops.Logic.Financial { - public class ExternalBankDataRecord: IComparer + public class ExternalBankDataRecord : IComparer { public long AccountBalanceCents; + public DateTime DateTime; // UTC! + public string Description; + public long FeeCents; + + public string NotUniqueId; + // As it says, but something that still assists in creating a hash together w/ other fields + public long TransactionGrossCents; public long TransactionNetCents; - public long FeeCents; - public string Description; - public DateTime DateTime; // UTC! public string UniqueId; - public string NotUniqueId; // As it says, but something that still assists in creating a hash together w/ other fields #region Implementation of IComparer @@ -33,17 +36,19 @@ namespace Swarmops.Logic.Financial { string importKey = string.Empty; - if (!string.IsNullOrEmpty(UniqueId)) + if (!string.IsNullOrEmpty(this.UniqueId)) { - importKey = UniqueId; + importKey = this.UniqueId; } - else if (!string.IsNullOrEmpty(NotUniqueId)) + else if (!string.IsNullOrEmpty(this.NotUniqueId)) { - string commentKey = Description.ToLowerInvariant(); + 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"); - string hashKey = NotUniqueId + commentKey + (TransactionNetCents / 100.0).ToString(CultureInfo.InvariantCulture) + (AccountBalanceCents / 100.0).ToString(CultureInfo.InvariantCulture) + - DateTime.ToString("yyyy-MM-dd-HH-mm-ss"); - importKey = SHA1.Hash(hashKey).Replace(" ", ""); } @@ -56,4 +61,4 @@ namespace Swarmops.Logic.Financial } } } -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialAccount.cs b/Logic/Financial/FinancialAccount.cs index a77ab66c..add568fe 100644 --- a/Logic/Financial/FinancialAccount.cs +++ b/Logic/Financial/FinancialAccount.cs @@ -11,12 +11,14 @@ namespace Swarmops.Logic.Financial { public class FinancialAccount : BasicFinancialAccount, ITreeNode, IOwnerSettable { - private FinancialAccount (BasicFinancialAccount basic) + private FinancialAccount(BasicFinancialAccount basic) : base(basic) { } - [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use BalanceTotalCents instead.", true)] + [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); } @@ -27,99 +29,11 @@ namespace Swarmops.Logic.Financial get { return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceTotalCents(Identity); } } - public static FinancialAccount FromIdentity(int identity) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialAccount(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. - } - - public static FinancialAccount FromBasic(BasicFinancialAccount basic) - { - return new FinancialAccount(basic); - } - - [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetDeltaCents instead.", true)] - public decimal GetDelta(DateTime start, DateTime end) - { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDelta(Identity, start, end); - } - - public Int64 GetDeltaCents(DateTime start, DateTime end) - { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(Identity, start, end); - } - - public FinancialAccountRows GetLastRows(int rowCount) - { - BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading().GetLastFinancialAccountRows(Identity, rowCount); - return FinancialAccountRows.FromArray(basicRows); - } - - public FinancialAccountRows GetRows(DateTime start, DateTime end) - { - BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading().GetFinancialAccountRows(Identity, start, end, false); - return FinancialAccountRows.FromArray(basicRows); - } - - public FinancialAccountRows GetRowsFar(DateTime start, DateTime end) // selects lowerbound < x <= upperbound - { - BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading().GetFinancialAccountRows(Identity, start, end, true); - return FinancialAccountRows.FromArray(basicRows); - } - - [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetBudgetCents instead.")] - public double GetBudget(int year) - { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(this.Identity, year); - } - - public Int64 GetBudgetCents (int year) - { - return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(this.Identity, year)*100); - } - - public Int64[] GetBudgetMonthly (int year) - { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudgetMonthly(this.Identity, year); - } - - [Obsolete("This method uses floating point for financials. Deprecated. Do not use.")] - public void SetBudget(int year, double amount) - { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(this.Identity, year, amount); - } - - public void SetBudgetCents (int year, Int64 amount) - { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(this.Identity, year, amount / 100.0); // TODO: Change db structure to use cents - } - - public void SetBudgetMontly (int year, int month, Int64 amountCents) - { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudgetMonthly(this.Identity, year, month, amountCents); - } - - public static FinancialAccount Create(Organization organization, string newAccountName, - FinancialAccountType accountType, FinancialAccount parentAccount) - { - return Create(organization.Identity, newAccountName, accountType, parentAccount == null? 0: parentAccount.Identity); - } - - protected static FinancialAccount Create (int organizationId, string name, FinancialAccountType accountType, int parentFinancialAccountId) - { - int accountId = SwarmDb.GetDatabaseForWriting().CreateFinancialAccount(organizationId, name, accountType, parentFinancialAccountId); - return FromIdentityAggressive(accountId); - } - public Organization Organization { get { - return Organization.FromIdentity(this.OrganizationId); // TODO: Cache + return Organization.FromIdentity(OrganizationId); // TODO: Cache } } @@ -127,36 +41,28 @@ namespace Swarmops.Logic.Financial { get { - if (this.OwnerPersonId == 0) + if (OwnerPersonId == 0) { return null; } - return Person.FromIdentity(this.OwnerPersonId); - } - set - { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountOwner(this.Identity, value.Identity); + return Person.FromIdentity(OwnerPersonId); } + set { SwarmDb.GetDatabaseForWriting().SetFinancialAccountOwner(Identity, value.Identity); } } public FinancialAccounts Children { - get { return FinancialAccounts.FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountChildren(this.Identity)); } - } - - public FinancialAccounts GetTree () - { - return FinancialAccounts.GetTree(this); + get + { + return FinancialAccounts.FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountChildren(Identity)); + } } public FinancialAccount Parent { - get - { - return FromIdentity(this.ParentFinancialAccountId); - } + get { return FromIdentity(ParentFinancialAccountId); } set { // We do not change the parent lightly. It cannot be changed if this account has transactions @@ -164,10 +70,11 @@ namespace Swarmops.Logic.Financial try { - int yearClosed = this.Organization.Parameters.FiscalBooksClosedUntilYear; - if (yearClosed > 0 && this.OpenedYear <= yearClosed) + int yearClosed = Organization.Parameters.FiscalBooksClosedUntilYear; + if (yearClosed > 0 && OpenedYear <= yearClosed) { - throw new InvalidOperationException("Can't reparent an account with transactions in closedledger space"); + throw new InvalidOperationException( + "Can't reparent an account with transactions in closedledger space"); } } catch (ArgumentException) @@ -178,7 +85,7 @@ namespace Swarmops.Logic.Financial int newParentId = value != null ? value.Identity : 0; base.ParentFinancialAccountId = newParentId; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountParent(this.Identity, newParentId); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountParent(Identity, newParentId); } } @@ -188,11 +95,11 @@ namespace Swarmops.Logic.Financial get { return - this.OptionalData.GetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences); + OptionalData.GetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences); } set { - this.OptionalData.SetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences, value); + OptionalData.SetOptionalDataBool(ObjectOptionalDataType.FinancialAccountEnabledForConferences, value); } } @@ -202,9 +109,9 @@ namespace Swarmops.Logic.Financial { // HACK HACK HACK HACK HACK for our pilots; this will be softcoded later TODO - if (this.OrganizationId == 1 && PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) + if (OrganizationId == 1 && PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) { - switch (this.FinancialAccountId) + switch (FinancialAccountId) { case 1: return ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); @@ -214,7 +121,8 @@ namespace Swarmops.Logic.Financial return null; } } - else if (this.OrganizationId == 7 && PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && this.FinancialAccountId == 29) + if (OrganizationId == 7 && PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && + FinancialAccountId == 29) { return ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); } @@ -223,31 +131,6 @@ namespace Swarmops.Logic.Financial } } - - public new string Name - { - get { return base.Name; } - set - { - try - { - int yearClosed = this.Organization.Parameters.FiscalBooksClosedUntilYear; - if (yearClosed > 0 && this.OpenedYear <= yearClosed) - { - throw new InvalidOperationException("Can't rename an account with transactions in closedledger space"); - } - } - catch (ArgumentException) - { - // This is ok and can be thrown if OpenedYear throws because there are no transactions yet. - } - - SwarmDb.GetDatabaseForWriting().SetFinancialAccountName(this.Identity, value); - base.Name = value; - } - } - - public new int OpenedYear { get @@ -259,7 +142,7 @@ namespace Swarmops.Logic.Financial try { firstTransactionDate = - SwarmDb.GetDatabaseForReading().GetFinancialAccountFirstTransactionDate(this.Identity); + SwarmDb.GetDatabaseForReading().GetFinancialAccountFirstTransactionDate(Identity); } catch (Exception) { @@ -268,8 +151,10 @@ namespace Swarmops.Logic.Financial if (firstTransactionDate.Year > 1900) { - SwarmDb.GetDatabaseForWriting().SetFinancialAccountOpenedYear(this.Identity, firstTransactionDate.Year); - base.OpenedYear = firstTransactionDate.Year; // TODO: Adapt for non-calendar fiscal years as future expansion? + SwarmDb.GetDatabaseForWriting() + .SetFinancialAccountOpenedYear(Identity, firstTransactionDate.Year); + base.OpenedYear = firstTransactionDate.Year; + // TODO: Adapt for non-calendar fiscal years as future expansion? } } @@ -277,10 +162,7 @@ namespace Swarmops.Logic.Financial { return base.OpenedYear; } - else - { - throw new ArgumentException("FinancialAccount is not opened yet (no transactions)"); - } + throw new ArgumentException("FinancialAccount is not opened yet (no transactions)"); } } @@ -295,7 +177,7 @@ namespace Swarmops.Logic.Financial } base.Active = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountActive(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountActive(Identity, value); } } @@ -311,7 +193,7 @@ namespace Swarmops.Logic.Financial } base.Expensable = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountExpensable(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountExpensable(Identity, value); } } @@ -327,23 +209,13 @@ namespace Swarmops.Logic.Financial } base.Administrative = value; - SwarmDb.GetDatabaseForWriting().SetFinancialAccountAdministrative(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetFinancialAccountAdministrative(Identity, value); } } - #region ITreeNode Members - - public int ParentIdentity - { - get { return this.ParentFinancialAccountId; } - } - - public int[] ChildrenIdentities - { - get { return Children.Identities; } - } + private ObjectOptionalData _optionalData; public Geography AssignedGeography { @@ -378,26 +250,32 @@ namespace Swarmops.Logic.Financial return null; } - set - { - OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankTransactionTag, value.ToLower()); - } + set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BankTransactionTag, value.ToLower()); } } private ObjectOptionalData OptionalData { get { - if (_optionalData == null) + if (this._optionalData == null) { - FinancialAccount acc = (FinancialAccount)this; - _optionalData = ObjectOptionalData.ForObject(acc); //Added cast, otherwise it fails for subclasses + FinancialAccount acc = this; + this._optionalData = ObjectOptionalData.ForObject(acc); + //Added cast, otherwise it fails for subclasses } - return _optionalData; + return this._optionalData; } } - private ObjectOptionalData _optionalData; + public int ParentIdentity + { + get { return ParentFinancialAccountId; } + } + + public int[] ChildrenIdentities + { + get { return Children.Identities; } + } #endregion @@ -405,9 +283,136 @@ namespace Swarmops.Logic.Financial public void SetOwner(Person newOwner) { - this.Owner = newOwner; + Owner = newOwner; } #endregion + + public new string Name + { + get { return base.Name; } + set + { + try + { + int yearClosed = Organization.Parameters.FiscalBooksClosedUntilYear; + if (yearClosed > 0 && OpenedYear <= yearClosed) + { + throw new InvalidOperationException( + "Can't rename an account with transactions in closedledger space"); + } + } + catch (ArgumentException) + { + // This is ok and can be thrown if OpenedYear throws because there are no transactions yet. + } + + SwarmDb.GetDatabaseForWriting().SetFinancialAccountName(Identity, value); + base.Name = value; + } + } + + public static FinancialAccount FromIdentity(int identity) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialAccount(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. + } + + public static FinancialAccount FromBasic(BasicFinancialAccount basic) + { + return new FinancialAccount(basic); + } + + [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetDeltaCents instead.", + true)] + public decimal GetDelta(DateTime start, DateTime end) + { + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDelta(Identity, start, end); + } + + public Int64 GetDeltaCents(DateTime start, DateTime end) + { + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(Identity, start, end); + } + + public FinancialAccountRows GetLastRows(int rowCount) + { + BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() + .GetLastFinancialAccountRows(Identity, rowCount); + return FinancialAccountRows.FromArray(basicRows); + } + + public FinancialAccountRows GetRows(DateTime start, DateTime end) + { + BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() + .GetFinancialAccountRows(Identity, start, end, false); + return FinancialAccountRows.FromArray(basicRows); + } + + public FinancialAccountRows GetRowsFar(DateTime start, DateTime end) // selects lowerbound < x <= upperbound + { + BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() + .GetFinancialAccountRows(Identity, start, end, true); + return FinancialAccountRows.FromArray(basicRows); + } + + [Obsolete("This method uses floating point for financials. Deprecated. Do not use; use GetBudgetCents instead.") + ] + public double GetBudget(int year) + { + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(Identity, year); + } + + public Int64 GetBudgetCents(int year) + { + return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget(Identity, year)*100); + } + + public Int64[] GetBudgetMonthly(int 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) + { + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(Identity, year, amount); + } + + public void SetBudgetCents(int year, Int64 amount) + { + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudget(Identity, year, amount/100.0); + // TODO: Change db structure to use cents + } + + public void SetBudgetMontly(int year, int month, Int64 amountCents) + { + SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudgetMonthly(Identity, year, month, amountCents); + } + + public static FinancialAccount Create(Organization organization, string newAccountName, + FinancialAccountType accountType, FinancialAccount parentAccount) + { + return Create(organization.Identity, newAccountName, accountType, + parentAccount == null ? 0 : parentAccount.Identity); + } + + protected static FinancialAccount Create(int organizationId, string name, FinancialAccountType accountType, + int parentFinancialAccountId) + { + int accountId = SwarmDb.GetDatabaseForWriting() + .CreateFinancialAccount(organizationId, name, accountType, parentFinancialAccountId); + return FromIdentityAggressive(accountId); + } + + public FinancialAccounts GetTree() + { + return FinancialAccounts.GetTree(this); + } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialAccountRow.cs b/Logic/Financial/FinancialAccountRow.cs index 866258f6..574cf083 100644 --- a/Logic/Financial/FinancialAccountRow.cs +++ b/Logic/Financial/FinancialAccountRow.cs @@ -6,26 +6,26 @@ namespace Swarmops.Logic.Financial { #region Construction and Creation - private FinancialAccountRow (BasicFinancialAccountRow basic) - : base (basic) + private FinancialAccountRow(BasicFinancialAccountRow basic) + : base(basic) { } - public static FinancialAccountRow FromBasic (BasicFinancialAccountRow basic) - { - return new FinancialAccountRow (basic); - } - public decimal Amount { get { return AmountCents/100.0m; } } + public static FinancialAccountRow FromBasic(BasicFinancialAccountRow basic) + { + return new FinancialAccountRow(basic); + } + #endregion public FinancialTransaction Transaction { - get { return FinancialTransaction.FromIdentity(this.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 88a9bc1f..bebd23d4 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) { - var result = new FinancialAccountRows {Capacity = (array.Length*11/10)}; + 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 964d837d..fd23885c 100644 --- a/Logic/Financial/FinancialAccounts.cs +++ b/Logic/Financial/FinancialAccounts.cs @@ -9,11 +9,12 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class FinancialAccounts : PluralBase + public class FinancialAccounts : PluralBase { public static FinancialAccounts ForOrganization(Organization organization) { - return FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountTreeForOrganization(organization.Identity)); + return + FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountTreeForOrganization(organization.Identity)); } public static FinancialAccounts ForOwner(Person person) @@ -22,8 +23,7 @@ namespace Swarmops.Logic.Financial } - - public static FinancialAccounts ForOrganization (Organization organization, FinancialAccountType accountType) + public static FinancialAccounts ForOrganization(Organization organization, FinancialAccountType accountType) { FinancialAccounts allAccounts = ForOrganization(organization); @@ -60,12 +60,13 @@ namespace Swarmops.Logic.Financial return result; } - public static FinancialAccounts FromBankTransactionTag (string tag) + public static FinancialAccounts FromBankTransactionTag(string tag) { - int[] accountIdentities = SwarmDb.GetDatabaseForReading().GetObjectsByOptionalData(ObjectType.FinancialAccount, - ObjectOptionalDataType. - BankTransactionTag, - tag.ToLower()); + int[] accountIdentities = + SwarmDb.GetDatabaseForReading().GetObjectsByOptionalData(ObjectType.FinancialAccount, + ObjectOptionalDataType. + BankTransactionTag, + tag.ToLower()); return FromIdentities(accountIdentities); } @@ -82,33 +83,35 @@ namespace Swarmops.Logic.Financial public FinancialAccountRows GetRows(DateTime start, DateTime end) { - BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading().GetFinancialAccountRows(Identities, start, end, false); + BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() + .GetFinancialAccountRows(Identities, start, end, false); return FinancialAccountRows.FromArray(basicRows); } public FinancialAccountRows GetRowsFar(DateTime start, DateTime end) { - BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading().GetFinancialAccountRows(Identities, start, end, true); + BasicFinancialAccountRow[] basicRows = SwarmDb.GetDatabaseForReading() + .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) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(this.Identities, year); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(Identities, year); } public Int64 GetBudgetSumCents(int year) { // TODO: Add support in database - return (Int64)(SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(this.Identities, year) * 100); + return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountsBudget(Identities, year)*100); } public Int64 GetDeltaCents(DateTime start, DateTime end) { - return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(this.Identities, start, end); + return SwarmDb.GetDatabaseForReading().GetFinancialAccountBalanceDeltaCents(Identities, start, end); } @@ -119,7 +122,7 @@ namespace Swarmops.Logic.Financial return GetTree(nodes, rootAccount.Identity, 0); } - + /* public Dictionary GetGeographyHashtable(int startGeographyId) { @@ -137,7 +140,7 @@ namespace Swarmops.Logic.Financial private static FinancialAccounts GetTree(Dictionary accounts, int startNodeId, - int generation) + int generation) { FinancialAccounts result = new FinancialAccounts(); @@ -184,7 +187,8 @@ namespace Swarmops.Logic.Financial Dictionary result = new Dictionary(); - FinancialAccounts allAccounts = FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountsForOrganization(organization.Identity)); + FinancialAccounts allAccounts = + FromArray(SwarmDb.GetDatabaseForReading().GetFinancialAccountsForOrganization(organization.Identity)); // Add the nodes. @@ -207,7 +211,5 @@ namespace Swarmops.Logic.Financial return result; } - - } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransaction.cs b/Logic/Financial/FinancialTransaction.cs index 8cb38e2a..5a5a160f 100644 --- a/Logic/Financial/FinancialTransaction.cs +++ b/Logic/Financial/FinancialTransaction.cs @@ -14,14 +14,14 @@ 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) @@ -31,7 +31,8 @@ namespace Swarmops.Logic.Financial 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) @@ -40,33 +41,35 @@ namespace Swarmops.Logic.Financial } - 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, - Int64 amountCents, string description, string importHash, int personId) + 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); + int transactionId = SwarmDb.GetDatabaseForWriting() + .CreateFinancialTransaction(organizationId, dateTime, description); + return FromIdentityAggressive(transactionId); } #endregion @@ -75,16 +78,15 @@ namespace Swarmops.Logic.Financial { get { - return FinancialTransactionRows.FromArray (SwarmDb.GetDatabaseForReading().GetFinancialTransactionRows (Identity)); + return + FinancialTransactionRows.FromArray( + SwarmDb.GetDatabaseForReading().GetFinancialTransactionRows(Identity)); } } public Documents Documents { - get - { - return Documents.ForObject(this); - } + get { return Documents.ForObject(this); } } public Int64 this[FinancialAccount account] @@ -93,7 +95,7 @@ namespace Swarmops.Logic.Financial { Int64 result = 0; - FinancialTransactionRows rows = this.Rows; + FinancialTransactionRows rows = Rows; foreach (FinancialTransactionRow row in rows) { @@ -110,52 +112,11 @@ namespace Swarmops.Logic.Financial public new string Description { get { return base.Description; } - set - { - base.Description = value; - SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDescription (this.Identity, value); - } - } - - [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) - { - AddRow (account, (Int64) (amount * 100), person); - } - - public void AddRow (FinancialAccount account, Int64 amountCents, Person person) - { - AddRow(account.Identity, amountCents, person != null ? person.Identity : 0); - } - - private void AddRow (int financialAccountId, Int64 amountCents, int personId) - { - if (this.DateTime.Year <= FinancialAccount.FromIdentity(financialAccountId).Organization.Parameters.FiscalBooksClosedUntilYear) + set { - // Recurse down into continuation transactions to write row in first nonclosed year - - FinancialTransaction transactionContinued = this.ContinuedTransaction; - - if (transactionContinued == null) - { - // No continuation; create one - - transactionContinued = FinancialTransaction.Create(this.OrganizationId, DateTime.Now, - "Continued Tx #" + this.Identity.ToString()); - transactionContinued.AddRow(financialAccountId, amountCents, personId); - transactionContinued.Dependency = this; - } - else - { - // Recurse - - transactionContinued.AddRow(financialAccountId, amountCents, personId); - } - - return; + base.Description = value; + SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDescription(Identity, value); } - - SwarmDb.GetDatabaseForWriting().CreateFinancialTransactionRow(Identity, financialAccountId, amountCents, personId); } private FinancialTransaction ContinuedTransaction @@ -164,7 +125,7 @@ namespace Swarmops.Logic.Financial { try { - return FinancialTransaction.FromDependency(this); + return FromDependency(this); } catch (ArgumentException) { @@ -173,28 +134,12 @@ namespace Swarmops.Logic.Financial } } - 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(); - string newClientFileName = "transaction_" + this.Identity.ToString() + "_document_" + - DateTime.Now.ToString("yyyyMMddHHmmss") + extension; - - // Create the document - - Document.Create(serverFileName, newClientFileName, fileSize, description, this, uploader); - } - - - public IHasIdentity Dependency { set { SwarmDb.GetDatabaseForWriting().SetFinancialTransactionDependency( - this.Identity, GetFinancialDependencyType(value), value.Identity); + Identity, GetFinancialDependencyType(value), value.Identity); } get { @@ -205,8 +150,8 @@ namespace Swarmops.Logic.Financial FinancialDependencyType dependencyType; int foreignId; - SwarmDb.GetDatabaseForReading().GetFinancialTransactionDependency(this.Identity, out dependencyType, - out foreignId); + SwarmDb.GetDatabaseForReading().GetFinancialTransactionDependency(Identity, out dependencyType, + out foreignId); if (foreignId == 0) { @@ -245,62 +190,119 @@ namespace Swarmops.Logic.Financial if (dependencyType == FinancialDependencyType.FinancialTransaction) { - return FinancialTransaction.FromIdentity(foreignId); + return FromIdentity(foreignId); } - throw new NotImplementedException("Unimplemented dependency type: " + dependencyType.ToString()); + throw new NotImplementedException("Unimplemented dependency type: " + dependencyType); } } + [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) + { + AddRow(account, (Int64) (amount*100), person); + } + + public void AddRow(FinancialAccount account, Int64 amountCents, Person person) + { + AddRow(account.Identity, amountCents, person != null ? person.Identity : 0); + } + + private void AddRow(int financialAccountId, Int64 amountCents, int personId) + { + if (DateTime.Year <= + FinancialAccount.FromIdentity(financialAccountId).Organization.Parameters.FiscalBooksClosedUntilYear) + { + // Recurse down into continuation transactions to write row in first nonclosed year + + FinancialTransaction transactionContinued = ContinuedTransaction; + + if (transactionContinued == null) + { + // No continuation; create one + + transactionContinued = Create(OrganizationId, DateTime.Now, + "Continued Tx #" + Identity); + transactionContinued.AddRow(financialAccountId, amountCents, personId); + transactionContinued.Dependency = this; + } + else + { + // Recurse + + transactionContinued.AddRow(financialAccountId, amountCents, personId); + } + + return; + } + + SwarmDb.GetDatabaseForWriting() + .CreateFinancialTransactionRow(Identity, financialAccountId, amountCents, personId); + } + + 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(); + string newClientFileName = "transaction_" + Identity + "_document_" + + DateTime.Now.ToString("yyyyMMddHHmmss") + extension; + + // Create the document + + Document.Create(serverFileName, newClientFileName, fileSize, description, this, uploader); + } - static private FinancialDependencyType GetFinancialDependencyType (IHasIdentity foreignObject) + private static FinancialDependencyType GetFinancialDependencyType(IHasIdentity foreignObject) { if (foreignObject is ExpenseClaim) { return FinancialDependencyType.ExpenseClaim; } - else if (foreignObject is InboundInvoice) + if (foreignObject is InboundInvoice) { return FinancialDependencyType.InboundInvoice; } - else if (foreignObject is OutboundInvoice) + if (foreignObject is OutboundInvoice) { return FinancialDependencyType.OutboundInvoice; } - else if (foreignObject is Salary) + if (foreignObject is Salary) { return FinancialDependencyType.Salary; } - else if (foreignObject is Payout) + if (foreignObject is Payout) { return FinancialDependencyType.Payout; } - else if (foreignObject is PaymentGroup) + if (foreignObject is PaymentGroup) { return FinancialDependencyType.PaymentGroup; } - else if (foreignObject is FinancialTransaction) + if (foreignObject is FinancialTransaction) { return FinancialDependencyType.FinancialTransaction; } throw new NotImplementedException("Unidentified dependency encountered in GetFinancialDependencyType:" + - foreignObject.GetType().ToString()); + 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(this.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 @@ -324,7 +326,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 @@ -339,7 +341,7 @@ namespace Swarmops.Logic.Financial Dictionary currentTransaction = new Dictionary(); - foreach (FinancialTransactionRow row in this.Rows) + foreach (FinancialTransactionRow row in Rows) { if (!currentTransaction.ContainsKey(row.FinancialAccountId)) { @@ -349,11 +351,12 @@ namespace Swarmops.Logic.Financial currentTransaction[row.FinancialAccountId] += row.AmountCents; } - FinancialTransaction continuedTransaction = this.ContinuedTransaction; + FinancialTransaction continuedTransaction = ContinuedTransaction; 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. @@ -383,10 +386,10 @@ namespace Swarmops.Logic.Financial foreach (int accountId in currentTransaction.Keys) { - if (currentTransaction [accountId] != nominalTransaction [accountId]) + if (currentTransaction[accountId] != nominalTransaction[accountId]) { - this.AddRow(accountId, nominalTransaction[accountId] - currentTransaction[accountId], - loggingPerson == null? 0: loggingPerson.Identity); + AddRow(accountId, nominalTransaction[accountId] - currentTransaction[accountId], + loggingPerson == null ? 0 : loggingPerson.Identity); changedTransaction = true; } } @@ -394,20 +397,19 @@ namespace Swarmops.Logic.Financial // TODO: Dimension 2 - return changedTransaction; } - private void AddContinuedTransactionsToLookup (Dictionary currentTransactionData) + private void AddContinuedTransactionsToLookup(Dictionary currentTransactionData) { - FinancialTransaction continuedTransaction = this.ContinuedTransaction; + FinancialTransaction continuedTransaction = ContinuedTransaction; if (continuedTransaction != null) { continuedTransaction.AddContinuedTransactionsToLookup(currentTransactionData); } - foreach (FinancialTransactionRow row in this.Rows) + foreach (FinancialTransactionRow row in Rows) { if (!currentTransactionData.ContainsKey(row.FinancialAccountId)) { diff --git a/Logic/Financial/FinancialTransactionRow.cs b/Logic/Financial/FinancialTransactionRow.cs index f0d9abed..ab04fcd9 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,32 +33,32 @@ namespace Swarmops.Logic.Financial { if (this.account == null) { - this.account = FinancialAccount.FromIdentity (base.FinancialAccountId); + this.account = FinancialAccount.FromIdentity(base.FinancialAccountId); } return this.account; } } - public static FinancialTransactionRow FromBasic (BasicFinancialTransactionRow basic) - { - return new FinancialTransactionRow (basic); - } - - public static FinancialTransactionRow FromIdentity (int identity) - { - return FromBasic (SwarmDb.GetDatabaseForReading().GetFinancialTransactionRow (identity)); - } - public string AccountName { - get { return Account.Name; } + 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) + { + return new FinancialTransactionRow(basic); + } + + public static FinancialTransactionRow FromIdentity(int 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 427bdb01..937ef0d5 100644 --- a/Logic/Financial/FinancialTransactionRows.cs +++ b/Logic/Financial/FinancialTransactionRows.cs @@ -45,7 +45,8 @@ namespace Swarmops.Logic.Financial foreach (FinancialTransactionRow row in this) { - if (row.Account.AccountType == FinancialAccountType.Asset || row.Account.AccountType == FinancialAccountType.Debt) + if (row.Account.AccountType == FinancialAccountType.Asset || + row.Account.AccountType == FinancialAccountType.Debt) { result += row.Amount; } @@ -62,7 +63,8 @@ namespace Swarmops.Logic.Financial foreach (FinancialTransactionRow row in this) { - if (row.Account.AccountType == FinancialAccountType.Asset || row.Account.AccountType == FinancialAccountType.Debt) + if (row.Account.AccountType == FinancialAccountType.Asset || + row.Account.AccountType == FinancialAccountType.Debt) { result += row.AmountCents; } @@ -73,11 +75,11 @@ namespace Swarmops.Logic.Financial public static FinancialTransactionRows FromArray(BasicFinancialTransactionRow[] basicArray) { - var result = new FinancialTransactionRows {Capacity = (basicArray.Length*11/10)}; + 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 8d3b7e38..20792c76 100644 --- a/Logic/Financial/FinancialTransactionTagSet.cs +++ b/Logic/Financial/FinancialTransactionTagSet.cs @@ -3,44 +3,46 @@ using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class FinancialTransactionTagSet: BasicFinancialTransactionTagSet + public class FinancialTransactionTagSet : BasicFinancialTransactionTagSet { - private FinancialTransactionTagSet (BasicFinancialTransactionTagSet basic): base (basic) + private FinancialTransactionTagSet(BasicFinancialTransactionTagSet basic) : base(basic) { // ctor } - public static FinancialTransactionTagSet FromBasic (BasicFinancialTransactionTagSet basic) - { - return new FinancialTransactionTagSet(basic); - } - - public static FinancialTransactionTagSet FromIdentity (int identity) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSet(identity)); - } - public new TagSetProfitLossType ProfitLossType { get { return (TagSetProfitLossType) base.ProfitLossType; } } + + public static FinancialTransactionTagSet FromBasic(BasicFinancialTransactionTagSet basic) + { + return new FinancialTransactionTagSet(basic); + } + + public static FinancialTransactionTagSet FromIdentity(int identity) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagSet(identity)); + } } public enum TagSetProfitLossType { Unknown = 0, + /// - /// This tag set should only be applied to income. + /// This tag set should only be applied to income. /// ProfitOnly = 1, + /// - /// This tag set should only be applied to costs. + /// This tag set should only be applied to costs. /// LossOnly = 2, + /// - /// This tag set should be applied to both income and costs. + /// This tag set should be applied to both income and costs. /// Both = 3 } - -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagSetType.cs b/Logic/Financial/FinancialTransactionTagSetType.cs index d0de2d07..d40ae92b 100644 --- a/Logic/Financial/FinancialTransactionTagSetType.cs +++ b/Logic/Financial/FinancialTransactionTagSetType.cs @@ -1,22 +1,22 @@ using System; +using Swarmops.Logic.App_GlobalResources; 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 - App_GlobalResources.Logic_Financial_FinancialTransactionTagSetTypesStock.ResourceManager.GetString( + Logic_Financial_FinancialTransactionTagSetTypesStock.ResourceManager.GetString( resource); } throw new NotImplementedException("Custom set names are not implemented yet"); } - } -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagSetTypesStock.cs b/Logic/Financial/FinancialTransactionTagSetTypesStock.cs index dacd471c..9f85c1e6 100644 --- a/Logic/Financial/FinancialTransactionTagSetTypesStock.cs +++ b/Logic/Financial/FinancialTransactionTagSetTypesStock.cs @@ -7,4 +7,4 @@ IncomeType = -2, ProjectName = -3 } -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactionTagSets.cs b/Logic/Financial/FinancialTransactionTagSets.cs index 9d435ccc..d988898b 100644 --- a/Logic/Financial/FinancialTransactionTagSets.cs +++ b/Logic/Financial/FinancialTransactionTagSets.cs @@ -13,4 +13,4 @@ namespace Swarmops.Logic.Financial 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 896c6c90..e342ca60 100644 --- a/Logic/Financial/FinancialTransactionTagType.cs +++ b/Logic/Financial/FinancialTransactionTagType.cs @@ -3,26 +3,26 @@ using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class FinancialTransactionTagType: BasicFinancialTransactionTagType + public class FinancialTransactionTagType : BasicFinancialTransactionTagType { - private FinancialTransactionTagType (BasicFinancialTransactionTagType basicTagType): base (basicTagType) + private FinancialTransactionTagType(BasicFinancialTransactionTagType basicTagType) : base(basicTagType) { // private ctor } - public static FinancialTransactionTagType FromBasic (BasicFinancialTransactionTagType basic) - { - return new FinancialTransactionTagType(basic); - } - - public static FinancialTransactionTagType FromIdentity (int identity) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagType(identity)); - } - public int ParentIdentity { get { return base.ParentFinancialTransactionTagTypeId; } } + + public static FinancialTransactionTagType FromBasic(BasicFinancialTransactionTagType basic) + { + return new FinancialTransactionTagType(basic); + } + + public static FinancialTransactionTagType FromIdentity(int 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 91cb4382..3aba4e68 100644 --- a/Logic/Financial/FinancialTransactionTagTypes.cs +++ b/Logic/Financial/FinancialTransactionTagTypes.cs @@ -4,21 +4,23 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class FinancialTransactionTagTypes: PluralBase + public class FinancialTransactionTagTypes : + PluralBase { - public static FinancialTransactionTagTypes ForSet (FinancialTransactionTagSet set) + public static FinancialTransactionTagTypes ForSet(FinancialTransactionTagSet 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)); } - public static FinancialTransactionTagTypes ForTransaction (FinancialTransaction transaction) + public static FinancialTransactionTagTypes ForTransaction(FinancialTransaction transaction) { - int[] tagTypeIdentities = SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes(transaction.Identity); + int[] tagTypeIdentities = + SwarmDb.GetDatabaseForReading().GetFinancialTransactionTagTypes(transaction.Identity); if (tagTypeIdentities.Length == 0) { @@ -28,4 +30,4 @@ namespace Swarmops.Logic.Financial return FromIdentities(tagTypeIdentities); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialTransactions.cs b/Logic/Financial/FinancialTransactions.cs index a8f210ad..44f9a76e 100644 --- a/Logic/Financial/FinancialTransactions.cs +++ b/Logic/Financial/FinancialTransactions.cs @@ -8,14 +8,15 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class FinancialTransactions : PluralBase + 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)); } @@ -46,16 +47,16 @@ namespace Swarmops.Logic.Financial 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) { @@ -66,7 +67,7 @@ namespace Swarmops.Logic.Financial return FinancialDependencyType.InboundInvoice; } - throw new NotImplementedException("Unimplemented dependency type:" + foreignObject.GetType().ToString()); + 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 27822029..d41d036e 100644 --- a/Logic/Financial/FinancialValidation.cs +++ b/Logic/Financial/FinancialValidation.cs @@ -3,21 +3,21 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class FinancialValidation: BasicFinancialValidation + public class FinancialValidation : BasicFinancialValidation { - private FinancialValidation (BasicFinancialValidation basic) - : base (basic) + private FinancialValidation(BasicFinancialValidation basic) + : base(basic) { } - public static FinancialValidation FromBasic (BasicFinancialValidation basic) - { - return new FinancialValidation(basic); - } - public Person Person { - get { return Person.FromIdentity(this.PersonId); } + get { return Person.FromIdentity(PersonId); } + } + + public static FinancialValidation FromBasic(BasicFinancialValidation basic) + { + return new FinancialValidation(basic); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/FinancialValidations.cs b/Logic/Financial/FinancialValidations.cs index 9ec29054..a8748b7e 100644 --- a/Logic/Financial/FinancialValidations.cs +++ b/Logic/Financial/FinancialValidations.cs @@ -8,20 +8,23 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class FinancialValidations: PluralBase + public class FinancialValidations : PluralBase { - public static void Create (FinancialValidationType validationType, IHasIdentity foreignObject, Person actingPerson) + public static void Create(FinancialValidationType validationType, IHasIdentity foreignObject, + Person actingPerson) { Create(validationType, foreignObject, actingPerson, 0.0); } - public static void Create (FinancialValidationType validationType, IHasIdentity foreignObject, Person actingPerson, double amount) + public static void Create(FinancialValidationType validationType, IHasIdentity foreignObject, + Person actingPerson, double amount) { - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(validationType, GetDependencyType(foreignObject), foreignObject.Identity, - DateTime.Now, actingPerson.Identity, amount); + SwarmDb.GetDatabaseForWriting() + .CreateFinancialValidation(validationType, GetDependencyType(foreignObject), foreignObject.Identity, + DateTime.Now, actingPerson.Identity, amount); } - static FinancialDependencyType GetDependencyType (IHasIdentity foreignObject) + private static FinancialDependencyType GetDependencyType(IHasIdentity foreignObject) { if (foreignObject is ExpenseClaim) { @@ -36,15 +39,16 @@ namespace Swarmops.Logic.Financial return FinancialDependencyType.Salary; } - throw new NotImplementedException("Unknown dependency: " + foreignObject.GetType().ToString()); + 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), - financialDependency.Identity)); + FromArray(SwarmDb.GetDatabaseForReading() + .GetFinancialValidations(GetDependencyType(financialDependency), + financialDependency.Identity)); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/IAttestable.cs b/Logic/Financial/IAttestable.cs index 9edd4e56..5b71079f 100644 --- a/Logic/Financial/IAttestable.cs +++ b/Logic/Financial/IAttestable.cs @@ -4,9 +4,8 @@ namespace Swarmops.Logic.Financial { public interface IAttestable { + FinancialAccount Budget { get; } void Attest(Person attester); void Deattest(Person deattester); - - FinancialAccount Budget { get; } } -} +} \ No newline at end of file diff --git a/Logic/Financial/IBankDataAccountStatementReader.cs b/Logic/Financial/IBankDataAccountStatementReader.cs index 2ee67c0c..bf3b1161 100644 --- a/Logic/Financial/IBankDataAccountStatementReader.cs +++ b/Logic/Financial/IBankDataAccountStatementReader.cs @@ -2,8 +2,8 @@ namespace Swarmops.Logic.Financial { - interface IBankDataAccountStatementReader + internal interface IBankDataAccountStatementReader { ImportedBankData ReadData(StreamReader data, FinancialAccount account, ExternalBankDataProfile profile); } -} +} \ No newline at end of file diff --git a/Logic/Financial/IBankDataPaymentsReader.cs b/Logic/Financial/IBankDataPaymentsReader.cs index 226406b2..9242f60b 100644 --- a/Logic/Financial/IBankDataPaymentsReader.cs +++ b/Logic/Financial/IBankDataPaymentsReader.cs @@ -10,4 +10,4 @@ string GenerateUniquePaymentGroupId(); // parameters here? void ImportPaymentsFile(); // Input parameter(s)?*/ } -} +} \ No newline at end of file diff --git a/Logic/Financial/ISummable.cs b/Logic/Financial/ISummable.cs index e52c511e..4aef84b4 100644 --- a/Logic/Financial/ISummable.cs +++ b/Logic/Financial/ISummable.cs @@ -7,4 +7,4 @@ namespace Swarmops.Logic.Financial long SumCents { get; } OrganizationFinancialAccountType CounterAccountType { get; } } -} +} \ No newline at end of file diff --git a/Logic/Financial/IValidatable.cs b/Logic/Financial/IValidatable.cs index 6f8b50a8..dc7be721 100644 --- a/Logic/Financial/IValidatable.cs +++ b/Logic/Financial/IValidatable.cs @@ -7,4 +7,4 @@ namespace Swarmops.Logic.Financial void Validate(Person validator); void Devalidate(Person devalidator); } -} +} \ No newline at end of file diff --git a/Logic/Financial/ImportedBankData.cs b/Logic/Financial/ImportedBankData.cs index 83c5abd2..fad40be4 100644 --- a/Logic/Financial/ImportedBankData.cs +++ b/Logic/Financial/ImportedBankData.cs @@ -12,13 +12,13 @@ namespace Swarmops.Logic.Financial public class ImportedBankRow { + public Int64 AmountCentsGross; + public Int64 AmountCentsNet; + public string Comment; + public Int64 CurrentBalanceCents; public DateTime DateTime; + public Int64 FeeCents; public string HashBase; public string SuppliedTransactionId; - public Int64 CurrentBalanceCents; - public Int64 AmountCentsNet; - public Int64 AmountCentsGross; - public Int64 FeeCents; - public string Comment; }; } \ No newline at end of file diff --git a/Logic/Financial/InboundInvoice.cs b/Logic/Financial/InboundInvoice.cs index 336ce095..89b1376e 100644 --- a/Logic/Financial/InboundInvoice.cs +++ b/Logic/Financial/InboundInvoice.cs @@ -12,76 +12,17 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class InboundInvoice: BasicInboundInvoice, IAttestable + public class InboundInvoice : BasicInboundInvoice, IAttestable { - 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, - supplier, payToAccount, ocr, - invoiceReference, amountCents, creatingPerson.Identity)); - - newInvoice.Description = description; // Not in original schema; not cause for schema update - - // Create a corresponding financial transaction with rows - - FinancialTransaction transaction = - FinancialTransaction.Create(organization.Identity, DateTime.Now, - "Invoice #" + newInvoice.Identity + " from " + supplier); - - transaction.AddRow(organization.FinancialAccounts.DebtsInboundInvoices, -amountCents, creatingPerson); - transaction.AddRow(budget, amountCents, creatingPerson); - - // Make the transaction dependent on the inbound invoice - - transaction.Dependency = newInvoice; - - // Create notification (slightly misplaced logic, but this is failsafest place) - - OutboundComm.CreateNotificationAttestationNeeded(budget, creatingPerson, supplier, (double)amountCents / 100.0, description, NotificationResource.InboundInvoice_Created); // Slightly misplaced logic, but failsafer here - SwarmopsLogEntry.Create(creatingPerson, - new InboundInvoiceCreatedLogEntry(creatingPerson, supplier, description, (double)amountCents / 100.0, budget), newInvoice); - - return newInvoice; - } - - public static InboundInvoice FromBasic (BasicInboundInvoice basic) - { - return new InboundInvoice(basic); - } - - private InboundInvoice(BasicInboundInvoice basicInstance): - base (basicInstance) + private InboundInvoice(BasicInboundInvoice basicInstance) : + base(basicInstance) { // constructor from basic type } - public static InboundInvoice FromIdentity (int inboundInvoiceId) - { - return new InboundInvoice(SwarmDb.GetDatabaseForReading().GetInboundInvoice(inboundInvoiceId)); - } - - public FinancialAccount Budget - { - get - { - if (base.BudgetId == 0) - { - return null; - } - - return FinancialAccount.FromIdentity(base.BudgetId); - } - } - public Documents Documents { - get - { - return Support.Documents.ForObject(this); - } + get { return Documents.ForObject(this); } } public new bool Open @@ -91,7 +32,7 @@ namespace Swarmops.Logic.Financial { if (base.Open != value) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceOpen(Identity, value); base.Open = value; } } @@ -99,27 +40,24 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get { return Organization.FromIdentity(this.OrganizationId); } + get { return Organization.FromIdentity(OrganizationId); } } public decimal Amount { - get { return base.AmountCents / 100.0m; } + get { return base.AmountCents/100.0m; } } public new DateTime DueDate { - get - { - return base.DueDate; - } + get { return base.DueDate; } set { if (value != base.DueDate) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceDueDate(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceDueDate(Identity, value); base.DueDate = value; } } @@ -136,51 +74,16 @@ namespace Swarmops.Logic.Financial return null; // not possible from July 26 onwards, but some grandfather work } - else if (transactions.Count == 1) + if (transactions.Count == 1) { return transactions[0]; } - throw new InvalidOperationException("It appears inbound invoice #" + this.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 void SetBudget (FinancialAccount budget, Person settingPerson) - { - base.BudgetId = budget.Identity; - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceBudget(this.Identity, budget.Identity); - UpdateTransaction(settingPerson); - } - - - public void SetAmountCents (Int64 amountCents, Person settingPerson) - { - base.AmountCents = amountCents; - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAmount(this.Identity, amountCents); - UpdateTransaction(settingPerson); - } - - - private void UpdateTransaction(Person updatingPerson) - { - Dictionary nominalTransaction = new Dictionary(); - - // Create an image of what the transaction SHOULD look like with changes. - - if (this.Attested || this.Open) - { - // ...only holds values if not closed as invalid... - - nominalTransaction[this.Organization.FinancialAccounts.DebtsInboundInvoices.Identity] = -AmountCents; - nominalTransaction[this.BudgetId] = AmountCents; - } - - FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); - } - - public FinancialValidations Validations { get { return FinancialValidations.ForObject(this); } @@ -198,31 +101,124 @@ namespace Swarmops.Logic.Financial set { - ObjectOptionalData.ForObject(this).SetOptionalDataString(ObjectOptionalDataType.InboundInvoiceDescription, value); + ObjectOptionalData.ForObject(this) + .SetOptionalDataString(ObjectOptionalDataType.InboundInvoiceDescription, value); } } - #region IAttestable Members public void Attest(Person attester) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(this.Identity, true); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(Identity, true); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.InboundInvoice, this.Identity, - DateTime.Now, attester.Identity, (double) this.Amount); + FinancialDependencyType.InboundInvoice, Identity, + DateTime.Now, attester.Identity, (double) Amount); base.Attested = true; } public void Deattest(Person deattester) { - SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(this.Identity, false); + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAttested(Identity, false); SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, - FinancialDependencyType.InboundInvoice, this.Identity, - DateTime.Now, deattester.Identity, (double) this.Amount); + FinancialDependencyType.InboundInvoice, Identity, + DateTime.Now, deattester.Identity, (double) Amount); base.Attested = false; } #endregion + + public FinancialAccount Budget + { + get + { + if (base.BudgetId == 0) + { + return null; + } + + return FinancialAccount.FromIdentity(base.BudgetId); + } + } + + 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, + supplier, payToAccount, ocr, + invoiceReference, amountCents, creatingPerson.Identity)); + + newInvoice.Description = description; // Not in original schema; not cause for schema update + + // Create a corresponding financial transaction with rows + + FinancialTransaction transaction = + FinancialTransaction.Create(organization.Identity, DateTime.Now, + "Invoice #" + newInvoice.Identity + " from " + supplier); + + transaction.AddRow(organization.FinancialAccounts.DebtsInboundInvoices, -amountCents, creatingPerson); + transaction.AddRow(budget, amountCents, creatingPerson); + + // Make the transaction dependent on the inbound invoice + + transaction.Dependency = newInvoice; + + // Create notification (slightly misplaced logic, but this is failsafest place) + + 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), + newInvoice); + + return newInvoice; + } + + public static InboundInvoice FromBasic(BasicInboundInvoice basic) + { + return new InboundInvoice(basic); + } + + public static InboundInvoice FromIdentity(int inboundInvoiceId) + { + return new InboundInvoice(SwarmDb.GetDatabaseForReading().GetInboundInvoice(inboundInvoiceId)); + } + + + public void SetBudget(FinancialAccount budget, Person settingPerson) + { + base.BudgetId = budget.Identity; + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceBudget(Identity, budget.Identity); + UpdateTransaction(settingPerson); + } + + + public void SetAmountCents(Int64 amountCents, Person settingPerson) + { + base.AmountCents = amountCents; + SwarmDb.GetDatabaseForWriting().SetInboundInvoiceAmount(Identity, amountCents); + UpdateTransaction(settingPerson); + } + + + private void UpdateTransaction(Person updatingPerson) + { + Dictionary nominalTransaction = new Dictionary(); + + // Create an image of what the transaction SHOULD look like with changes. + + if (Attested || Open) + { + // ...only holds values if not closed as invalid... + + nominalTransaction[Organization.FinancialAccounts.DebtsInboundInvoices.Identity] = -AmountCents; + nominalTransaction[BudgetId] = AmountCents; + } + + FinancialTransaction.RecalculateTransaction(nominalTransaction, updatingPerson); + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/InboundInvoices.cs b/Logic/Financial/InboundInvoices.cs index 1f9d6c8d..d93020dc 100644 --- a/Logic/Financial/InboundInvoices.cs +++ b/Logic/Financial/InboundInvoices.cs @@ -7,15 +7,14 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class InboundInvoices: PluralBase + public class InboundInvoices : PluralBase { - public InboundInvoices WhereAttested { get { InboundInvoices result = new InboundInvoices(); - result.AddRange(this.Where(invoice => invoice.Attested == true)); + result.AddRange(this.Where(invoice => invoice.Attested)); return result; } @@ -34,30 +33,6 @@ namespace Swarmops.Logic.Financial } - /// - /// Gets all open inbound invoices for a particular organization. - /// - /// The organization. - /// The list of inbound invoices. - public static InboundInvoices ForOrganization (Organization organization) - { - return ForOrganization(organization, false); - } - - /// - /// Gets all inbound invoices for an organization, optionally including closed ones. - /// - /// The organizations. - /// True to include closed records. - /// The list of inbound invoices. - public static InboundInvoices ForOrganization (Organization organization, bool includeClosed) - { - return FromArray (SwarmDb.GetDatabaseForReading().GetInboundInvoices(organization, - includeClosed - ? DatabaseCondition.None - : DatabaseCondition.OpenTrue)); - } - public decimal TotalAmount { get @@ -75,10 +50,10 @@ namespace Swarmops.Logic.Financial public Int64 TotalAmountCents { - get - { + get + { Int64 result = 0; - + foreach (InboundInvoice invoice in this) { result += invoice.AmountCents; @@ -87,5 +62,29 @@ namespace Swarmops.Logic.Financial return result; } } + + /// + /// Gets all open inbound invoices for a particular organization. + /// + /// The organization. + /// The list of inbound invoices. + public static InboundInvoices ForOrganization(Organization organization) + { + return ForOrganization(organization, false); + } + + /// + /// Gets all inbound invoices for an organization, optionally including closed ones. + /// + /// The organizations. + /// True to include closed records. + /// The list of inbound invoices. + public static InboundInvoices ForOrganization(Organization organization, bool includeClosed) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetInboundInvoices(organization, + includeClosed + ? DatabaseCondition.None + : DatabaseCondition.OpenTrue)); + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/OrganizationFinancialAccounts.cs b/Logic/Financial/OrganizationFinancialAccounts.cs index 971e623c..58d8dcdd 100644 --- a/Logic/Financial/OrganizationFinancialAccounts.cs +++ b/Logic/Financial/OrganizationFinancialAccounts.cs @@ -5,75 +5,29 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.Financial { /// - /// Accessors for special accounts for a particular organization. + /// Accessors for special accounts for a particular organization. /// public class OrganizationFinancialAccounts { - public static void PrimePiratpartietSE() // One-off. Once this has been run once, delete it. - { - /* -- this was a one-time one-off - if (SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId(1, OrganizationFinancialAccountType.AssetsBankAccountMain) != 0) - { - return; - } + private readonly int _organizationId; - if (!Organization.PPSE.Name.StartsWith("Piratpartiet")) - { - return; // not PP installation - } - - OrganizationFinancialAccounts organizationAccounts = new OrganizationFinancialAccounts(1); - - // HACK HACK HACK - - organizationAccounts[OrganizationFinancialAccountType.CostsBankFees] = FinancialAccount.FromIdentity(26); // - organizationAccounts[OrganizationFinancialAccountType.AssetsBankAccountMain] = FinancialAccount.FromIdentity(1); // - organizationAccounts[OrganizationFinancialAccountType.IncomeDonations] = FinancialAccount.FromIdentity(4); // - organizationAccounts[OrganizationFinancialAccountType.IncomeGeneral] = FinancialAccount.FromIdentity(131); // - organizationAccounts[OrganizationFinancialAccountType.IncomeSales] = FinancialAccount.FromIdentity(5); // - organizationAccounts[OrganizationFinancialAccountType.CostsInfrastructure] = FinancialAccount.FromIdentity(21); // - organizationAccounts[OrganizationFinancialAccountType.CostsLocalDonationTransfers] = FinancialAccount.FromIdentity(88); // - organizationAccounts[OrganizationFinancialAccountType.CostsAllocatedFunds] = FinancialAccount.FromIdentity(124); // - organizationAccounts[OrganizationFinancialAccountType.DebtsExpenseClaims] = FinancialAccount.FromIdentity(3); // - organizationAccounts[OrganizationFinancialAccountType.DebtsSalary] = FinancialAccount.FromIdentity(25); // - organizationAccounts[OrganizationFinancialAccountType.DebtsTax] = FinancialAccount.FromIdentity(86); // - organizationAccounts[OrganizationFinancialAccountType.DebtsInboundInvoices] = FinancialAccount.FromIdentity(25); // - organizationAccounts[OrganizationFinancialAccountType.DebtsOther] = FinancialAccount.FromIdentity(25); // - organizationAccounts[OrganizationFinancialAccountType.AssetsOutboundInvoices] = FinancialAccount.FromIdentity(28); // - organizationAccounts[OrganizationFinancialAccountType.DebtsEquity] = FinancialAccount.FromIdentity(96); // - organizationAccounts[OrganizationFinancialAccountType.AssetsPaypal] = FinancialAccount.FromIdentity(2); // - organizationAccounts[OrganizationFinancialAccountType.CostsYearlyResult] = FinancialAccount.FromIdentity(97); // - organizationAccounts[OrganizationFinancialAccountType.AssetsOutstandingCashAdvances] = FinancialAccount.FromIdentity(156); // - organizationAccounts[OrganizationFinancialAccountType.AssetsVat] = FinancialAccount.FromIdentity(86); // - organizationAccounts[OrganizationFinancialAccountType.DebtsVat] = FinancialAccount.FromIdentity(86); // - - FinancialAccount.FromIdentity(80).IsConferenceParent = true; - FinancialAccount.FromIdentity(27).IsConferenceParent = true; - - Organization.PPSE.IsEconomyEnabled = true; // Kill this function in base, too - */ - } - - 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) { - } - private readonly int _organizationId; - public FinancialAccount this[OrganizationFinancialAccountType accountType] { get { - int accountId = SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId(_organizationId, - accountType); + int accountId = SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId(this._organizationId, + accountType); if (accountId == 0) { @@ -84,8 +38,8 @@ namespace Swarmops.Logic.Financial } set { - SwarmDb.GetDatabaseForWriting().SetOrganizationFinancialAccountId(_organizationId, accountType, - value.Identity); + SwarmDb.GetDatabaseForWriting().SetOrganizationFinancialAccountId(this._organizationId, accountType, + value.Identity); } } @@ -239,7 +193,7 @@ namespace Swarmops.Logic.Financial FinancialAccounts costAccounts = FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), - FinancialAccountType.Cost); + FinancialAccountType.Cost); foreach (FinancialAccount account in costAccounts) { @@ -256,20 +210,20 @@ namespace Swarmops.Logic.Financial public FinancialAccounts ExpensableBudgets { // TODO: This needs to return a tree, not a flat list. - get { FinancialAccounts result = new FinancialAccounts(); - int yearlyResultId = this.CostsYearlyResult.Identity; + int yearlyResultId = CostsYearlyResult.Identity; FinancialAccounts costAccounts = - FinancialAccounts.ForOrganization(Organization.FromIdentity(_organizationId), - FinancialAccountType.Cost); + FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), + FinancialAccountType.Cost); foreach (FinancialAccount account in costAccounts) { - if (account.Identity != yearlyResultId && account.Expensable) // really should be redundant, but still... + if (account.Identity != yearlyResultId && account.Expensable) + // really should be redundant, but still... { result.Add(account); } @@ -282,20 +236,20 @@ namespace Swarmops.Logic.Financial public FinancialAccounts InvoiceableBudgetsOutbound { // TODO: This needs to return a tree, not a flat list. - get { FinancialAccounts result = new FinancialAccounts(); - int yearlyResultId = this.CostsYearlyResult.Identity; + int yearlyResultId = CostsYearlyResult.Identity; FinancialAccounts costAccounts = - FinancialAccounts.ForOrganization(Organization.FromIdentity(_organizationId), - FinancialAccountType.Income); + FinancialAccounts.ForOrganization(Organization.FromIdentity(this._organizationId), + FinancialAccountType.Income); foreach (FinancialAccount account in costAccounts) { - if (account.Identity != yearlyResultId && account.Expensable) // really should be redundant, but still... + if (account.Identity != yearlyResultId && account.Expensable) + // really should be redundant, but still... { result.Add(account); } @@ -305,5 +259,49 @@ namespace Swarmops.Logic.Financial } } + public static void PrimePiratpartietSE() // One-off. Once this has been run once, delete it. + { + /* -- this was a one-time one-off + if (SwarmDb.GetDatabaseForReading().GetOrganizationFinancialAccountId(1, OrganizationFinancialAccountType.AssetsBankAccountMain) != 0) + { + return; + } + + if (!Organization.PPSE.Name.StartsWith("Piratpartiet")) + { + return; // not PP installation + } + + OrganizationFinancialAccounts organizationAccounts = new OrganizationFinancialAccounts(1); + + // HACK HACK HACK + + organizationAccounts[OrganizationFinancialAccountType.CostsBankFees] = FinancialAccount.FromIdentity(26); // + organizationAccounts[OrganizationFinancialAccountType.AssetsBankAccountMain] = FinancialAccount.FromIdentity(1); // + organizationAccounts[OrganizationFinancialAccountType.IncomeDonations] = FinancialAccount.FromIdentity(4); // + organizationAccounts[OrganizationFinancialAccountType.IncomeGeneral] = FinancialAccount.FromIdentity(131); // + organizationAccounts[OrganizationFinancialAccountType.IncomeSales] = FinancialAccount.FromIdentity(5); // + organizationAccounts[OrganizationFinancialAccountType.CostsInfrastructure] = FinancialAccount.FromIdentity(21); // + organizationAccounts[OrganizationFinancialAccountType.CostsLocalDonationTransfers] = FinancialAccount.FromIdentity(88); // + organizationAccounts[OrganizationFinancialAccountType.CostsAllocatedFunds] = FinancialAccount.FromIdentity(124); // + organizationAccounts[OrganizationFinancialAccountType.DebtsExpenseClaims] = FinancialAccount.FromIdentity(3); // + organizationAccounts[OrganizationFinancialAccountType.DebtsSalary] = FinancialAccount.FromIdentity(25); // + organizationAccounts[OrganizationFinancialAccountType.DebtsTax] = FinancialAccount.FromIdentity(86); // + organizationAccounts[OrganizationFinancialAccountType.DebtsInboundInvoices] = FinancialAccount.FromIdentity(25); // + organizationAccounts[OrganizationFinancialAccountType.DebtsOther] = FinancialAccount.FromIdentity(25); // + organizationAccounts[OrganizationFinancialAccountType.AssetsOutboundInvoices] = FinancialAccount.FromIdentity(28); // + organizationAccounts[OrganizationFinancialAccountType.DebtsEquity] = FinancialAccount.FromIdentity(96); // + organizationAccounts[OrganizationFinancialAccountType.AssetsPaypal] = FinancialAccount.FromIdentity(2); // + organizationAccounts[OrganizationFinancialAccountType.CostsYearlyResult] = FinancialAccount.FromIdentity(97); // + organizationAccounts[OrganizationFinancialAccountType.AssetsOutstandingCashAdvances] = FinancialAccount.FromIdentity(156); // + organizationAccounts[OrganizationFinancialAccountType.AssetsVat] = FinancialAccount.FromIdentity(86); // + organizationAccounts[OrganizationFinancialAccountType.DebtsVat] = FinancialAccount.FromIdentity(86); // + + FinancialAccount.FromIdentity(80).IsConferenceParent = true; + FinancialAccount.FromIdentity(27).IsConferenceParent = true; + + Organization.PPSE.IsEconomyEnabled = true; // Kill this function in base, too + */ + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/OutboundInvoice.cs b/Logic/Financial/OutboundInvoice.cs index fd17c0f2..6e7f0ffc 100644 --- a/Logic/Financial/OutboundInvoice.cs +++ b/Logic/Financial/OutboundInvoice.cs @@ -9,78 +9,16 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class OutboundInvoice: BasicOutboundInvoice + public class OutboundInvoice : BasicOutboundInvoice { - private OutboundInvoice (BasicOutboundInvoice basic): base (basic) + private OutboundInvoice(BasicOutboundInvoice basic) : base(basic) { // empty ctor } - public static OutboundInvoice FromBasic (BasicOutboundInvoice basic) - { - return new OutboundInvoice(basic); - } - - public static OutboundInvoice FromIdentity (int outboundInvoiceId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundInvoice(outboundInvoiceId)); - } - - public static OutboundInvoice FromReference (string reference) - { - // TODO: Verify Luhn - - - - // Use identity as drogue chute - - string identityString = reference.Substring(12, reference.Length - 13); - - OutboundInvoice result = FromIdentity(Int32.Parse(identityString)); - - if (result.Reference != reference) - { - throw new ArgumentException("No such outbound invoice"); - } - - return result; - } - - 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, dueDate, - budget.Identity, customerName, invoiceAddressPaper, - invoiceAddressMail, currency.Identity, string.Empty, domestic, Authentication.CreateRandomPassword(6), theirReference)); - - // Set reference - - invoice.Reference = - Formatting.AddLuhnChecksum(Formatting.ReverseString(DateTime.Now.ToString("yyyyMMddHHmm")) + - invoice.Identity.ToString()); - - return invoice; - } - public OutboundInvoiceItems Items { - get - { - return OutboundInvoiceItems.ForInvoice(this); - } - } - - - public void AddItem(string description, double amount) - { - SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem(this.Identity, description, amount); - } - - - 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(this.Identity, description, amountCents); + get { return OutboundInvoiceItems.ForInvoice(this); } } @@ -90,7 +28,7 @@ namespace Swarmops.Logic.Financial { decimal result = 0.0m; - OutboundInvoiceItems items = this.Items; + OutboundInvoiceItems items = Items; foreach (OutboundInvoiceItem item in items) { @@ -108,7 +46,7 @@ namespace Swarmops.Logic.Financial { Int64 result = 0; - OutboundInvoiceItems items = this.Items; + OutboundInvoiceItems items = Items; foreach (OutboundInvoiceItem item in items) { @@ -122,30 +60,24 @@ namespace Swarmops.Logic.Financial public Organization Organization { - get - { - return Structure.Organization.FromIdentity(this.OrganizationId); - } + get { return Organization.FromIdentity(OrganizationId); } } public FinancialAccount Budget { - get { return FinancialAccount.FromIdentity(this.BudgetId); } + get { return FinancialAccount.FromIdentity(BudgetId); } } public new bool Sent { - get - { - return base.Sent; - } + get { return base.Sent; } set { if (value != base.Sent) { - if (value == true) + if (value) { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceSent(this.Identity, true); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceSent(Identity, true); base.Sent = true; } else @@ -163,19 +95,12 @@ namespace Swarmops.Logic.Financial { if (value != base.Open) { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceOpen(Identity, value); base.Open = value; } } } - public void SetPaid() - { - Open = false; - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, this.OrganizationId, - Geography.RootIdentity, 0, this.Identity, string.Empty); - } - public Payment Payment { get @@ -184,7 +109,7 @@ namespace Swarmops.Logic.Financial try { - payment = Financial.Payment.ForOutboundInvoice(this); + payment = Payment.ForOutboundInvoice(this); } catch (Exception) { @@ -196,13 +121,10 @@ namespace Swarmops.Logic.Financial public new string Reference { - get - { - return base.Reference; - } + get { return base.Reference; } set { - SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceReference(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetOutboundInvoiceReference(Identity, value); base.Reference = value; } } @@ -213,72 +135,6 @@ namespace Swarmops.Logic.Financial } - - public OutboundInvoice Credit(Person creditingPerson) - { - OutboundInvoice credit = OutboundInvoice.Create(this.Organization, creditingPerson, DateTime.Now, - this.Budget, this.CustomerName, - this.InvoiceAddressMail, - this.InvoiceAddressPaper, this.Currency, - this.Domestic, this.TheirReference); - if (this.Domestic) // TODO: LANGUAGE - { - credit.AddItem("Kredit för faktura " + this.Reference, -this.AmountCents); - credit.AddItem("DETTA ÄR EN KREDITFAKTURA OCH SKA EJ BETALAS", 0.00); - - this.AddItem(String.Format("KREDITERAD {0:yyyy-MM-dd} i kreditfaktura {1}", DateTime.Today, credit.Reference), 0.00); - } - else - { - credit.AddItem("Credit for invoice " + this.Reference, -this.AmountCents); - credit.AddItem("THIS IS A CREDIT. DO NOT PAY.", 0.00); - - this.AddItem(String.Format("CREDITED {0:yyyy-MM-dd} in credit invoice {1}", DateTime.Today, credit.Reference), 0.00); - } - - this.CreditInvoice = credit; - credit.CreditsInvoice = this; - - - credit.Open = false; - - // Create the financial transaction with rows - - FinancialTransaction transaction = - FinancialTransaction.Create(credit.OrganizationId, DateTime.Now, - "Credit Invoice #" + credit.Identity + " to " + credit.CustomerName); - - transaction.AddRow(Organization.FromIdentity(credit.OrganizationId).FinancialAccounts.AssetsOutboundInvoices, credit.AmountCents, creditingPerson); - transaction.AddRow(credit.Budget, -credit.AmountCents, creditingPerson); - - // Make the transaction dependent on the credit - - transaction.Dependency = credit; - - // Create the event for PirateBot-Mono to send off mails - - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoiceCreated, creditingPerson.Identity, - this.OrganizationId, Geography.RootIdentity, 0, credit.Identity, string.Empty); - - // If this invoice was already closed, issue a credit. If not closed, close it. - - if (this.Open) - { - this.Open = false; - } - else - { - Payment payment = this.Payment; - - if (payment != null) - { - payment.Refund(creditingPerson); - } - } - - return credit; - } - public Person Person { get @@ -312,7 +168,7 @@ namespace Swarmops.Logic.Financial return null; } - return OutboundInvoice.FromIdentity(invoiceId); + return FromIdentity(invoiceId); } set { @@ -333,7 +189,7 @@ namespace Swarmops.Logic.Financial return null; } - return OutboundInvoice.FromIdentity(invoiceId); + return FromIdentity(invoiceId); } set { @@ -342,5 +198,145 @@ namespace Swarmops.Logic.Financial } } + public static OutboundInvoice FromBasic(BasicOutboundInvoice basic) + { + return new OutboundInvoice(basic); + } + + public static OutboundInvoice FromIdentity(int outboundInvoiceId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundInvoice(outboundInvoiceId)); + } + + public static OutboundInvoice FromReference(string reference) + { + // TODO: Verify Luhn + + + // Use identity as drogue chute + + string identityString = reference.Substring(12, reference.Length - 13); + + OutboundInvoice result = FromIdentity(Int32.Parse(identityString)); + + if (result.Reference != reference) + { + throw new ArgumentException("No such outbound invoice"); + } + + return result; + } + + 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, + dueDate, + budget.Identity, customerName, invoiceAddressPaper, + invoiceAddressMail, currency.Identity, string.Empty, domestic, + Authentication.CreateRandomPassword(6), theirReference)); + + // Set reference + + invoice.Reference = + Formatting.AddLuhnChecksum(Formatting.ReverseString(DateTime.Now.ToString("yyyyMMddHHmm")) + + invoice.Identity); + + return invoice; + } + + public void AddItem(string description, double amount) + { + SwarmDb.GetDatabaseForWriting().CreateOutboundInvoiceItem(Identity, description, amount); + } + + + 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); + } + + public void SetPaid() + { + Open = false; + PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoicePaid, 0, OrganizationId, + Geography.RootIdentity, 0, Identity, string.Empty); + } + + public OutboundInvoice Credit(Person creditingPerson) + { + 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); + + 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); + + AddItem( + String.Format("CREDITED {0:yyyy-MM-dd} in credit invoice {1}", DateTime.Today, credit.Reference), + 0.00); + } + + CreditInvoice = credit; + credit.CreditsInvoice = this; + + + credit.Open = false; + + // Create the financial transaction with rows + + FinancialTransaction transaction = + FinancialTransaction.Create(credit.OrganizationId, DateTime.Now, + "Credit Invoice #" + credit.Identity + " to " + credit.CustomerName); + + transaction.AddRow( + Organization.FromIdentity(credit.OrganizationId).FinancialAccounts.AssetsOutboundInvoices, + credit.AmountCents, creditingPerson); + transaction.AddRow(credit.Budget, -credit.AmountCents, creditingPerson); + + // Make the transaction dependent on the credit + + transaction.Dependency = credit; + + // Create the event for PirateBot-Mono to send off mails + + 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. + + if (Open) + { + Open = false; + } + else + { + Payment payment = Payment; + + if (payment != null) + { + payment.Refund(creditingPerson); + } + } + + return credit; + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/OutboundInvoiceItem.cs b/Logic/Financial/OutboundInvoiceItem.cs index 521f7086..34a53d14 100644 --- a/Logic/Financial/OutboundInvoiceItem.cs +++ b/Logic/Financial/OutboundInvoiceItem.cs @@ -3,26 +3,26 @@ using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class OutboundInvoiceItem: BasicOutboundInvoiceItem + public class OutboundInvoiceItem : BasicOutboundInvoiceItem { - private OutboundInvoiceItem (BasicOutboundInvoiceItem basic): base (basic) + private OutboundInvoiceItem(BasicOutboundInvoiceItem basic) : base(basic) { // empty ctor } - public static OutboundInvoiceItem FromBasic (BasicOutboundInvoiceItem basic) + public decimal Amount + { + get { return AmountCents/100.0m; } + } + + public static OutboundInvoiceItem FromBasic(BasicOutboundInvoiceItem basic) { return new OutboundInvoiceItem(basic); } - public static OutboundInvoiceItem FromIdentity (int outboundInvoiceItemId) + public static OutboundInvoiceItem FromIdentity(int outboundInvoiceItemId) { return FromBasic(SwarmDb.GetDatabaseForReading().GetOutboundInvoiceItem(outboundInvoiceItemId)); } - - public decimal Amount - { - get { return (decimal) AmountCents/100.0m; } - } } -} +} \ No newline at end of file diff --git a/Logic/Financial/OutboundInvoiceItems.cs b/Logic/Financial/OutboundInvoiceItems.cs index 6ad3242a..b053d4e2 100644 --- a/Logic/Financial/OutboundInvoiceItems.cs +++ b/Logic/Financial/OutboundInvoiceItems.cs @@ -4,11 +4,11 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class OutboundInvoiceItems: PluralBase + public class OutboundInvoiceItems : PluralBase { - public static OutboundInvoiceItems ForInvoice (OutboundInvoice invoice) + public static OutboundInvoiceItems ForInvoice(OutboundInvoice 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 66d26e92..9aaca39b 100644 --- a/Logic/Financial/OutboundInvoices.cs +++ b/Logic/Financial/OutboundInvoices.cs @@ -5,23 +5,21 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class OutboundInvoices: PluralBase + public class OutboundInvoices : PluralBase { - public static OutboundInvoices ForOrganization (Organization organization) + public static OutboundInvoices ForOrganization(Organization organization) { 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)); } - else - { - return FromArray (SwarmDb.GetDatabaseForReading().GetOutboundInvoices(organization, DatabaseCondition.OpenTrue)); - } + return + 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 0d2f688e..fdb5e18b 100644 --- a/Logic/Financial/Payment.cs +++ b/Logic/Financial/Payment.cs @@ -10,104 +10,14 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class Payment: BasicPayment + public class Payment : BasicPayment { - private Payment (BasicPayment payment) - : base (payment) - { - // empty copy ctor - } - - public static Payment FromBasic (BasicPayment basic) - { - return new Payment(basic); - } - - public static Payment FromIdentity(int paymentId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPayment(paymentId)); - } - - private static Payment FromIdentityAggressive(int paymentId) - { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPayment(paymentId)); // "Writing" intentional - avoid race conditions - } - - public static Payment ForOutboundInvoice(OutboundInvoice invoice) - { - BasicPayment[] array = SwarmDb.GetDatabaseForReading().GetPayments(invoice); - - if (array.Length == 0) - { - return null; // or throw exception? - } - - if (array.Length > 1) - { - throw new InvalidDataException("There can not be two payments for one invoice"); - } - - return FromBasic(array[0]); - } - - 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); - - // TODO: Verify that invoice is not already closed; if so, issue refund - - // TODO: Verify correct amount - - invoice.Open = false; - - 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 - - return FromIdentityAggressive (SwarmDb.GetDatabaseForWriting().CreatePayment(group.Identity, amount, reference, fromAccount, key, hasImage, - invoice.Identity)); - } - - 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 - - // TODO: Verify correct amount - - invoice.SetPaid(); - - PaymentGroup group = PaymentGroup.Create(organization, dateTime, currency, createdByPerson); - Payment newPayment = FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreatePayment(group.Identity, amountCents, string.Empty, string.Empty, string.Empty, false, - invoice.Identity)); - group.AmountCents = amountCents; - - return newPayment; - } - private PaymentInformationList informationList; - private void PopulateInformation() + private Payment(BasicPayment payment) + : base(payment) { - if (informationList == null) - { - informationList = PaymentInformationList.ForPayment(this); // caution: assumes the list is static over lifetime of the payment object - } - } - - private string GetSinglePaymentInformation (PaymentInformationType type) - { - PopulateInformation(); - - foreach (PaymentInformation infoPiece in informationList) - { - if (infoPiece.Type == type) - { - return infoPiece.Data; - } - } - - return null; + // empty copy ctor } public string[] PaymentInformation @@ -118,7 +28,7 @@ namespace Swarmops.Logic.Financial PopulateInformation(); - foreach (PaymentInformation infoPiece in informationList) + foreach (PaymentInformation infoPiece in this.informationList) { if (infoPiece.Type == PaymentInformationType.Freeform) { @@ -155,35 +65,131 @@ namespace Swarmops.Logic.Financial get { return GetSinglePaymentInformation(PaymentInformationType.OrgNumber); } } - public void AddInformation (PaymentInformationType type, string data) - { - if (!string.IsNullOrEmpty(data)) - { - SwarmDb.GetDatabaseForWriting().CreatePaymentInformation(this.Identity, type, data); - } - } - public PaymentGroup Group { - get { return PaymentGroup.FromIdentity(this.PaymentGroupId); } - } - - public void Refund (Person refundingPerson) - { - Financial.Refund.Create(this, refundingPerson); - } - - public void Refund (Int64 amountCents, Person refundingPerson) - { - Financial.Refund.Create(this, refundingPerson, amountCents); + get { return PaymentGroup.FromIdentity(PaymentGroupId); } } public OutboundInvoice OutboundInvoice { - get + get { return OutboundInvoice.FromIdentity(OutboundInvoiceId); } + } + + public static Payment FromBasic(BasicPayment basic) + { + return new Payment(basic); + } + + public static Payment FromIdentity(int paymentId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetPayment(paymentId)); + } + + private static Payment FromIdentityAggressive(int paymentId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetPayment(paymentId)); + // "Writing" intentional - avoid race conditions + } + + public static Payment ForOutboundInvoice(OutboundInvoice invoice) + { + BasicPayment[] array = SwarmDb.GetDatabaseForReading().GetPayments(invoice); + + if (array.Length == 0) { - return Financial.OutboundInvoice.FromIdentity(this.OutboundInvoiceId); + return null; // or throw exception? + } + + if (array.Length > 1) + { + throw new InvalidDataException("There can not be two payments for one invoice"); + } + + return FromBasic(array[0]); + } + + 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); + + // TODO: Verify that invoice is not already closed; if so, issue refund + + // TODO: Verify correct amount + + invoice.Open = false; + + 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 + + return + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() + .CreatePayment(group.Identity, amount, reference, fromAccount, key, hasImage, + invoice.Identity)); + } + + 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 + + // TODO: Verify correct amount + + invoice.SetPaid(); + + PaymentGroup group = PaymentGroup.Create(organization, dateTime, currency, createdByPerson); + Payment newPayment = + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() + .CreatePayment(group.Identity, amountCents, string.Empty, string.Empty, string.Empty, false, + invoice.Identity)); + group.AmountCents = amountCents; + + return newPayment; + } + + private void PopulateInformation() + { + if (this.informationList == null) + { + this.informationList = PaymentInformationList.ForPayment(this); + // caution: assumes the list is static over lifetime of the payment object } } + + private string GetSinglePaymentInformation(PaymentInformationType type) + { + PopulateInformation(); + + foreach (PaymentInformation infoPiece in this.informationList) + { + if (infoPiece.Type == type) + { + return infoPiece.Data; + } + } + + return null; + } + + public void AddInformation(PaymentInformationType type, string data) + { + if (!string.IsNullOrEmpty(data)) + { + SwarmDb.GetDatabaseForWriting().CreatePaymentInformation(Identity, type, data); + } + } + + public void Refund(Person refundingPerson) + { + Financial.Refund.Create(this, refundingPerson); + } + + public void Refund(Int64 amountCents, Person refundingPerson) + { + 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 332d8055..59295f75 100644 --- a/Logic/Financial/PaymentGroup.cs +++ b/Logic/Financial/PaymentGroup.cs @@ -8,70 +8,30 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class PaymentGroup: BasicPaymentGroup, ISummable + public class PaymentGroup : BasicPaymentGroup, ISummable { - private PaymentGroup(BasicPaymentGroup basic): base (basic) + private PaymentGroup(BasicPaymentGroup basic) : base(basic) { // empty ctor } - public static PaymentGroup FromIdentity(int paymentGroupId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPaymentGroup(paymentGroupId)); - } - - private static PaymentGroup FromIdentityAggressive(int paymentGroupId) - { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPaymentGroup(paymentGroupId)); // "For writing" intentional - solves race conditions on create - } - - public static PaymentGroup FromBasic(BasicPaymentGroup basic) - { - return new PaymentGroup(basic); - } - - public static PaymentGroup Create (Organization organization, DateTime timestamp, Currency currency, Person createdByPerson) - { - return - FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreatePaymentGroup(organization.Identity, timestamp, - currency.Identity, - System.DateTime.Now, createdByPerson == null? 0: createdByPerson.Identity)); - } - - public static PaymentGroup FromTag (Organization organization, string tag) - { - BasicPaymentGroup basicGroup = SwarmDb.GetDatabaseForReading().GetPaymentGroupByTag(organization.Identity, tag); - - if (basicGroup == null) - { - return null; - } - - return FromBasic(basicGroup); - } - - public Payment CreatePayment (double amount, string reference, string fromAccount, string key, bool hasImage) - { - return Payment.Create(this, amount, reference, fromAccount, key, hasImage); - } - public new string Tag { get { return base.Tag; } - set - { + set + { base.Tag = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupTag(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupTag(Identity, value); } } public new Int64 AmountCents { get { return base.AmountCents; } - set + set { base.AmountCents = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupAmount(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupAmount(Identity, value); } } @@ -83,82 +43,17 @@ namespace Swarmops.Logic.Financial public new bool Open { get { return base.Open; } - set - { + set + { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetPaymentGroupOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPaymentGroupOpen(Identity, value); } } public Organization Organization { - get { return Organization.FromIdentity(this.OrganizationId); } - } - - - - public bool MapTransaction() - { - // 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(this.Organization); - - return this.MapTransaction(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 - - switch (Char.ToLowerInvariant(this.Tag[5])) - { - case 'm': - namespaceLength = 6; // unique per year and month - break; - case 'd': - namespaceLength = 8; // unique per year, month, day - break; - default: - // do nothing -- assume year, namespace length 4 as declared on init - break; - } - - string lookfor = this.Tag.Substring(5 + namespaceLength).ToLowerInvariant().Trim(); - int year = Int32.Parse(this.Tag.Substring(5, 4)); - - if (Char.IsDigit(this.Tag[0])) - { - lookfor = this.Tag.Substring(namespaceLength); // temp - remove after PPSE books closed for 2011 - year = Int32.Parse(this.Tag.Substring(0, 4)); - } - - foreach (FinancialTransaction transaction in transactions) - { - if (transaction.Description.Length >= this.Organization.IncomingPaymentTag.Length + lookfor.Length && - transaction.Description.ToLowerInvariant().StartsWith(this.Organization.IncomingPaymentTag) && - transaction.Description.Trim().ToLowerInvariant().EndsWith(lookfor)) - { - if (transaction.Rows.AmountCentsTotal == this.AmountCents) - { - if (transaction.DateTime.Year == year) - { - // TODO: Prep for matching month/date too, when those namespaces appear - - // match! - - transaction.AddRow(Organization.FinancialAccounts.AssetsOutboundInvoices, -AmountCents, null); - transaction.Dependency = this; - this.Open = false; - return true; - } - } - } - } - - return false; + get { return Organization.FromIdentity(OrganizationId); } } public Payments Payments @@ -168,8 +63,8 @@ namespace Swarmops.Logic.Financial public string Payers { - get - { + get + { List payerList = new List(); foreach (Payment payment in Payments) { @@ -185,12 +80,11 @@ namespace Swarmops.Logic.Financial } } - #region Implementation of ISummable - public long SumCents - { - get { return this.AmountCents; } + public long SumCents + { + get { return AmountCents; } } public OrganizationFinancialAccountType CounterAccountType @@ -199,5 +93,114 @@ namespace Swarmops.Logic.Financial } #endregion + + public static PaymentGroup FromIdentity(int paymentGroupId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetPaymentGroup(paymentGroupId)); + } + + private static PaymentGroup FromIdentityAggressive(int paymentGroupId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetPaymentGroup(paymentGroupId)); + // "For writing" intentional - solves race conditions on create + } + + public static PaymentGroup FromBasic(BasicPaymentGroup basic) + { + return new PaymentGroup(basic); + } + + public static PaymentGroup Create(Organization organization, DateTime timestamp, Currency currency, + Person createdByPerson) + { + return + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() + .CreatePaymentGroup(organization.Identity, timestamp, + currency.Identity, + DateTime.Now, createdByPerson == null ? 0 : createdByPerson.Identity)); + } + + public static PaymentGroup FromTag(Organization organization, string tag) + { + BasicPaymentGroup basicGroup = SwarmDb.GetDatabaseForReading() + .GetPaymentGroupByTag(organization.Identity, tag); + + if (basicGroup == null) + { + return null; + } + + return FromBasic(basicGroup); + } + + public Payment CreatePayment(double amount, string reference, string fromAccount, string key, bool hasImage) + { + return Payment.Create(this, amount, reference, fromAccount, key, hasImage); + } + + + public bool MapTransaction() + { + // 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); + + return MapTransaction(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 + + switch (Char.ToLowerInvariant(Tag[5])) + { + case 'm': + namespaceLength = 6; // unique per year and month + break; + case 'd': + namespaceLength = 8; // unique per year, month, day + break; + default: + // do nothing -- assume year, namespace length 4 as declared on init + break; + } + + string lookfor = Tag.Substring(5 + namespaceLength).ToLowerInvariant().Trim(); + int year = Int32.Parse(Tag.Substring(5, 4)); + + if (Char.IsDigit(Tag[0])) + { + 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)) + { + if (transaction.Rows.AmountCentsTotal == AmountCents) + { + if (transaction.DateTime.Year == year) + { + // TODO: Prep for matching month/date too, when those namespaces appear + + // match! + + transaction.AddRow(Organization.FinancialAccounts.AssetsOutboundInvoices, -AmountCents, null); + transaction.Dependency = this; + Open = false; + return true; + } + } + } + } + + return false; + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/PaymentGroups.cs b/Logic/Financial/PaymentGroups.cs index 4d12024a..637fa9d5 100644 --- a/Logic/Financial/PaymentGroups.cs +++ b/Logic/Financial/PaymentGroups.cs @@ -5,23 +5,20 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class PaymentGroups: PluralBase + public class PaymentGroups : PluralBase { - public static PaymentGroups ForOrganization (Organization organization) + public static PaymentGroups ForOrganization(Organization organization) { 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)); } - else - { - 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 495efe35..10a2b5f5 100644 --- a/Logic/Financial/PaymentInformation.cs +++ b/Logic/Financial/PaymentInformation.cs @@ -4,39 +4,40 @@ using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class PaymentInformation: BasicPaymentInformation + 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); } } - public class PaymentInformationList: List + public class PaymentInformationList : List { - static public PaymentInformationList FromArray(BasicPaymentInformation[] basicArray) + public static PaymentInformationList FromArray(BasicPaymentInformation[] basicArray) { - var result = new PaymentInformationList() { Capacity = basicArray.Length * 11 / 10 }; + PaymentInformationList result = new PaymentInformationList {Capacity = basicArray.Length*11/10}; foreach (BasicPaymentInformation basic in basicArray) { - result.Add((PaymentInformation)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); + BasicPaymentInformation[] basicInfoList = + SwarmDb.GetDatabaseForReading().GetPaymentInformation(payment.Identity); return FromArray(basicInfoList); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Payments.cs b/Logic/Financial/Payments.cs index a8b220a2..e636b461 100644 --- a/Logic/Financial/Payments.cs +++ b/Logic/Financial/Payments.cs @@ -4,11 +4,11 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class Payments: PluralBase + public class Payments : PluralBase { - public static Payments ForPaymentGroup (PaymentGroup group) + public static Payments ForPaymentGroup(PaymentGroup 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 83a053d1..9bdbe110 100644 --- a/Logic/Financial/Payout.cs +++ b/Logic/Financial/Payout.cs @@ -14,18 +14,24 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class Payout: BasicPayout, ISummable + public class Payout : BasicPayout, ISummable { #region Creation and Construction - public static void Create () + private Payout(BasicPayout basic) : + base(basic) + { + LoadDependencies(); + } + + public static void Create() { // is this even needed? throw new NotImplementedException(); } - public static Payout Create (Payout payout) + public static Payout Create(Payout payout) { throw new NotImplementedException(); // Seems not to be needed @@ -37,65 +43,60 @@ namespace Swarmops.Logic.Financial // return payout; } - private Payout (BasicPayout basic): - base (basic) - { - LoadDependencies(); - } - private void LoadDependencies() { - DependentExpenseClaims = new ExpenseClaims(); - DependentInvoices = new InboundInvoices(); - DependentSalariesNet = new Salaries(); - DependentSalariesTax = new Salaries(); - DependentCashAdvancesPayout = new CashAdvances(); - DependentCashAdvancesPayback = new CashAdvances(); + this.DependentExpenseClaims = new ExpenseClaims(); + this.DependentInvoices = new InboundInvoices(); + this.DependentSalariesNet = new Salaries(); + this.DependentSalariesTax = new Salaries(); + this.DependentCashAdvancesPayout = new CashAdvances(); + this.DependentCashAdvancesPayback = new CashAdvances(); - BasicFinancialDependency[] dependencies = SwarmDb.GetDatabaseForReading().GetPayoutDependencies(this.Identity); + BasicFinancialDependency[] dependencies = SwarmDb.GetDatabaseForReading().GetPayoutDependencies(Identity); foreach (BasicFinancialDependency dependency in dependencies) { switch (dependency.DependencyType) { case FinancialDependencyType.ExpenseClaim: - DependentExpenseClaims.Add(ExpenseClaim.FromIdentity(dependency.ForeignId)); + this.DependentExpenseClaims.Add(ExpenseClaim.FromIdentity(dependency.ForeignId)); break; case FinancialDependencyType.InboundInvoice: - DependentInvoices.Add(InboundInvoice.FromIdentity(dependency.ForeignId)); + this.DependentInvoices.Add(InboundInvoice.FromIdentity(dependency.ForeignId)); break; case FinancialDependencyType.Salary: Salary salary = Salary.FromIdentity(dependency.ForeignId); - if (salary.NetSalaryCents == this.AmountCents) // HACK: Assumes that tax total is not identical + if (salary.NetSalaryCents == AmountCents) // HACK: Assumes that tax total is not identical { - DependentSalariesNet.Add(salary); + this.DependentSalariesNet.Add(salary); } else { - DependentSalariesTax.Add(salary); + this.DependentSalariesTax.Add(salary); } break; case FinancialDependencyType.CashAdvance: - DependentCashAdvancesPayout.Add(CashAdvance.FromIdentity(dependency.ForeignId)); + this.DependentCashAdvancesPayout.Add(CashAdvance.FromIdentity(dependency.ForeignId)); break; case FinancialDependencyType.CashAdvancePayback: - DependentCashAdvancesPayback.Add(CashAdvance.FromIdentity(dependency.ForeignId)); + this.DependentCashAdvancesPayback.Add(CashAdvance.FromIdentity(dependency.ForeignId)); break; default: - throw new NotImplementedException("Unknown financial dependency type in Payout.LoadDependencies(): " + dependency.ToString()); + 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); } - public static Payout FromIdentity (int payoutId) + public static Payout FromIdentity(int payoutId) { try { @@ -107,81 +108,168 @@ namespace Swarmops.Logic.Financial } } - #endregion - public InboundInvoices DependentInvoices; + public CashAdvances DependentCashAdvancesPayback; + public CashAdvances DependentCashAdvancesPayout; public ExpenseClaims DependentExpenseClaims; + public InboundInvoices DependentInvoices; public Salaries DependentSalariesNet; public Salaries DependentSalariesTax; - public CashAdvances DependentCashAdvancesPayout; - public CashAdvances DependentCashAdvancesPayback; public decimal Amount { set { - if (this.Identity != 0) + if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutAmount(this.Identity, (Int64)(value * 100)); + SwarmDb.GetDatabaseForWriting().SetPayoutAmount(Identity, (Int64) (value*100)); } - base.AmountCents = (Int64)value * 100; - } - get - { - return base.AmountCents / 100.0m; + base.AmountCents = (Int64) value*100; } + get { return base.AmountCents/100.0m; } } public new Int64 AmountCents { set { - if (this.Identity != 0) + if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutAmount(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutAmount(Identity, value); } base.AmountCents = value; } - get - { - return base.AmountCents; - } + get { return base.AmountCents; } } public new string Reference { set { - if (this.Identity != 0) + if (Identity != 0) { - SwarmDb.GetDatabaseForWriting().SetPayoutReference(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutReference(Identity, value); } base.Reference = value; } - get - { - return base.Reference; - } + get { return base.Reference; } } public new bool Open { - get - { - return base.Open; - } + get { return base.Open; } set { - SwarmDb.GetDatabaseForWriting().SetPayoutOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetPayoutOpen(Identity, value); base.Open = value; } } + public string ProtoIdentity + { + get + { + if (Identity != 0) + { + throw new InvalidOperationException( + "Should never use ProtoIdentity after Identity has been established"); + } - public static Payout CreateFromProtoIdentity (Person creator, string protoIdentity) + string result = string.Empty; + + // ReSharper disable LoopCanBeConvertedToQuery + + foreach (InboundInvoice invoice in this.DependentInvoices) + { + result += "|I" + invoice.Identity.ToString(CultureInfo.InvariantCulture); + } + + foreach (ExpenseClaim claim in this.DependentExpenseClaims) + { + result += "|C" + claim.Identity.ToString(CultureInfo.InvariantCulture); + } + + foreach (CashAdvance advancePayback in this.DependentCashAdvancesPayback) + { + result += "|a" + advancePayback.Identity.ToString(CultureInfo.InvariantCulture); + } + + foreach (CashAdvance advance in this.DependentCashAdvancesPayout) + { + result += "|A" + advance.Identity.ToString(CultureInfo.InvariantCulture); + } + + foreach (Salary salary in this.DependentSalariesNet) + { + result += "|S" + salary.Identity.ToString(CultureInfo.InvariantCulture); + } + + foreach (Salary salary in this.DependentSalariesTax) + { + result += "|T" + salary.Identity.ToString(CultureInfo.InvariantCulture); + } + + // ReSharper restore LoopCanBeConvertedToQuery + + if (result.Length > 0) + { + return result.Substring(1); + } + + return string.Empty; + } + } + + public string Recipient + { + get + { + if (this.DependentExpenseClaims == null || this.DependentInvoices == null) + { + // TODO: read from db instead + + throw new InvalidOperationException("Dependencies not initialized"); + } + + if (this.DependentInvoices.Count > 0) + { + return this.DependentInvoices[0].Supplier; + } + if (this.DependentExpenseClaims.Count > 0) + { + return this.DependentExpenseClaims[0].ClaimerCanonical; + } + if (this.DependentCashAdvancesPayout.Count > 0) + { + return this.DependentCashAdvancesPayout[0].Person.Canonical; + } + if (this.DependentSalariesNet.Count > 0) + { + return this.DependentSalariesNet[0].PayrollItem.PersonCanonical; + } + if (this.DependentSalariesTax.Count > 0) + { + return "The Tax Man"; + } + throw new InvalidOperationException("No dependencies for payout #" + Identity); + } + } + + public Organization Organization + { + get { return Organization.FromIdentity(OrganizationId); } + } + + + public FinancialTransaction FinancialTransaction + { + get { return FinancialTransaction.FromDependency(this); } + } + + public static Payout CreateFromProtoIdentity(Person creator, string protoIdentity) { string[] components = protoIdentity.Split('|'); int payoutId = 0; @@ -194,7 +282,7 @@ namespace Swarmops.Logic.Financial return null; } - if (components [0][0] == 'A') + if (components[0][0] == 'A') { // Cash advance(s) to be paid out. @@ -225,13 +313,14 @@ namespace Swarmops.Logic.Financial //advance.Open = false; // isn't this closed only when settling the debt? Serious bug here? SwarmopsLogEntry.Create(creator, - new PayoutCreatedLogEntry(creator, advance.Person, organization, - organization.Currency, (double) amountCents/100.0, - "Cash Advance Paid Out"), - advance.Person, advance); + new PayoutCreatedLogEntry(creator, advance.Person, organization, + organization.Currency, amountCents/100.0, + "Cash Advance Paid Out"), + advance.Person, advance); - OutboundComm.CreateNotificationOfFinancialValidation(advance.Budget, advance.Person, (double)advance.AmountCents / 100.0, advance.Description, NotificationResource.CashAdvance_PaidOut); + OutboundComm.CreateNotificationOfFinancialValidation(advance.Budget, advance.Person, + advance.AmountCents/100.0, advance.Description, NotificationResource.CashAdvance_PaidOut); } string referenceString = string.Empty; @@ -247,16 +336,17 @@ namespace Swarmops.Logic.Financial } payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(organizationId, bank, account, - referenceString, amountCents, DateTime.Today.AddDays(1), - creator.Identity); + referenceString, amountCents, DateTime.Today.AddDays(1), + creator.Identity); foreach (int advanceId in identityList) { - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvance, - advanceId); + SwarmDb.GetDatabaseForWriting() + .CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvance, + advanceId); } } - else if (components [0][0] == 'C') + else if (components[0][0] == 'C') { // Expense claims, possibly followed up by cash advance paybacks @@ -293,7 +383,8 @@ namespace Swarmops.Logic.Financial claim.Repaid = true; claim.Close(); - OutboundComm.CreateNotificationOfFinancialValidation(claim.Budget, claim.Claimer, (double)claim.AmountCents / 100.0, claim.Description, NotificationResource.ExpenseClaim_PaidOut); + OutboundComm.CreateNotificationOfFinancialValidation(claim.Budget, claim.Claimer, + claim.AmountCents/100.0, claim.Description, NotificationResource.ExpenseClaim_PaidOut); } else if (component[0] == 'a') { @@ -318,25 +409,27 @@ namespace Swarmops.Logic.Financial } SwarmopsLogEntry.Create(creator, - new PayoutCreatedLogEntry(creator, beneficiaryPerson, organization, - organization.Currency, amountCents/100.0, - referenceString), - beneficiaryPerson); + 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), - creator.Identity); + referenceString, amountCents, DateTime.Today.AddDays(1), + creator.Identity); foreach (int claimId in claimIdentityList) { - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.ExpenseClaim, - claimId); + SwarmDb.GetDatabaseForWriting() + .CreatePayoutDependency(payoutId, FinancialDependencyType.ExpenseClaim, + claimId); } foreach (int advancePaybackId in advancePaybackIdentityList) { - SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvancePayback, - advancePaybackId); + SwarmDb.GetDatabaseForWriting() + .CreatePayoutDependency(payoutId, FinancialDependencyType.CashAdvancePayback, + advancePaybackId); } } else if (components[0][0] == 'I') @@ -352,33 +445,36 @@ namespace Swarmops.Logic.Financial expectedPayment = DateTime.Today; } - payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(invoice.OrganizationId, string.Empty, invoice.PayToAccount, - invoice.Ocr.Length > 0 ? "OCR " + invoice.Ocr : "Ref# " + invoice.InvoiceReference, - invoice.AmountCents, expectedPayment, - creator.Identity); + payoutId = SwarmDb.GetDatabaseForWriting() + .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); + invoice.Identity); invoice.Open = false; } - else if (components [0][0] == 'S') + else if (components[0][0] == 'S') { // Salary, net payment Salary salary = Salary.FromIdentity(Int32.Parse(components[0].Substring(1))); - payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(salary.PayrollItem.OrganizationId, salary.PayrollItem.Person.BankName, salary.PayrollItem.Person.BankAccount, - "Salary " + salary.PayoutDate.ToString("yyyy-MMM"), - salary.NetSalaryCents, salary.PayoutDate, - creator.Identity); + payoutId = SwarmDb.GetDatabaseForWriting() + .CreatePayout(salary.PayrollItem.OrganizationId, salary.PayrollItem.Person.BankName, + salary.PayrollItem.Person.BankAccount, + "Salary " + salary.PayoutDate.ToString("yyyy-MMM"), + salary.NetSalaryCents, salary.PayoutDate, + creator.Identity); SwarmDb.GetDatabaseForWriting().CreatePayoutDependency(payoutId, FinancialDependencyType.Salary, - salary.Identity); + salary.Identity); salary.NetPaid = true; } - else if (components [0][0] == 'T') + else if (components[0][0] == 'T') { // Tax payment for multiple salaries. @@ -409,7 +505,7 @@ namespace Swarmops.Logic.Financial if (identityList.Count == 1) { - referenceString = "Tax for salary #" + identityList[0].ToString(); + referenceString = "Tax for salary #" + identityList[0]; } else { @@ -417,128 +513,29 @@ namespace Swarmops.Logic.Financial referenceString = "Tax for salaries " + Formatting.GenerateRangeString(identityList); } - payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(organization.Identity, "The Tax Man", organization.Parameters.TaxAccount, organization.Parameters.TaxOcr, - amountCents, payDay, creator.Identity); + payoutId = SwarmDb.GetDatabaseForWriting() + .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, - salaryId); + salaryId); } } else { - throw new NotImplementedException(); + throw new NotImplementedException(); } return FromIdentity(payoutId); } - - - public string ProtoIdentity - { - get - { - if (this.Identity != 0) - { - throw new InvalidOperationException("Should never use ProtoIdentity after Identity has been established"); - } - - string result = string.Empty; - - // ReSharper disable LoopCanBeConvertedToQuery - - foreach (InboundInvoice invoice in DependentInvoices) - { - result += "|I" + invoice.Identity.ToString(CultureInfo.InvariantCulture); - } - - foreach (ExpenseClaim claim in DependentExpenseClaims) - { - result += "|C" + claim.Identity.ToString(CultureInfo.InvariantCulture); - } - - foreach (CashAdvance advancePayback in DependentCashAdvancesPayback) - { - result += "|a" + advancePayback.Identity.ToString(CultureInfo.InvariantCulture); - } - - foreach (CashAdvance advance in DependentCashAdvancesPayout) - { - result += "|A" + advance.Identity.ToString(CultureInfo.InvariantCulture); - } - - foreach (Salary salary in DependentSalariesNet) - { - result += "|S" + salary.Identity.ToString(CultureInfo.InvariantCulture); - } - - foreach (Salary salary in DependentSalariesTax) - { - result += "|T" + salary.Identity.ToString(CultureInfo.InvariantCulture); - } - - // ReSharper restore LoopCanBeConvertedToQuery - - if (result.Length > 0) - { - return result.Substring(1); - } - - return string.Empty; - } - } - - public string Recipient - { - get - { - if (this.DependentExpenseClaims == null || this.DependentInvoices == null) - { - // TODO: read from db instead - - throw new InvalidOperationException("Dependencies not initialized"); - } - - if (this.DependentInvoices.Count > 0) - { - return this.DependentInvoices[0].Supplier; - } - else if (this.DependentExpenseClaims.Count > 0) - { - return this.DependentExpenseClaims[0].ClaimerCanonical; - } - else if (this.DependentCashAdvancesPayout.Count > 0) - { - return this.DependentCashAdvancesPayout[0].Person.Canonical; - } - else if (this.DependentSalariesNet.Count > 0) - { - return this.DependentSalariesNet[0].PayrollItem.PersonCanonical; - } - else if (this.DependentSalariesTax.Count > 0) - { - return "The Tax Man"; - } - else - { - throw new InvalidOperationException("No dependencies for payout #" + this.Identity); - } - - } - } - - public Organization Organization - { - get { return Organization.FromIdentity(this.OrganizationId); } - } - - - public void BindToTransactionAndClose (FinancialTransaction transaction, Person bindingPerson) + public void BindToTransactionAndClose(FinancialTransaction transaction, Person bindingPerson) { Dictionary accountDebitLookup = new Dictionary(); - Organization organization = this.Organization; + Organization organization = Organization; accountDebitLookup[organization.FinancialAccounts.DebtsExpenseClaims.Identity] = 0; accountDebitLookup[organization.FinancialAccounts.DebtsInboundInvoices.Identity] = 0; @@ -573,7 +570,8 @@ namespace Swarmops.Logic.Financial } if (this.DependentCashAdvancesPayback.Count > 0) { - accountDebitLookup[organization.FinancialAccounts.AssetsOutstandingCashAdvances.Identity] -= // observe the minus + accountDebitLookup[organization.FinancialAccounts.AssetsOutstandingCashAdvances.Identity] -= + // observe the minus this.DependentCashAdvancesPayback.TotalAmountCents; } @@ -582,18 +580,12 @@ namespace Swarmops.Logic.Financial if (accountDebitLookup[financialAccountId] != 0) { transaction.AddRow(FinancialAccount.FromIdentity(financialAccountId), - accountDebitLookup[financialAccountId], bindingPerson); + accountDebitLookup[financialAccountId], bindingPerson); } } transaction.Dependency = this; - this.Open = false; - } - - - public FinancialTransaction FinancialTransaction - { - get { return FinancialTransaction.FromDependency(this); } + Open = false; } @@ -603,11 +595,11 @@ namespace Swarmops.Logic.Financial } - public void MigrateDependenciesTo (Payout migrationTarget) + public void MigrateDependenciesTo(Payout migrationTarget) { - SwarmDb.GetDatabaseForWriting().MovePayoutDependencies(this.Identity, migrationTarget.Identity); + SwarmDb.GetDatabaseForWriting().MovePayoutDependencies(Identity, migrationTarget.Identity); migrationTarget.RecalculateAmount(); - this.RecalculateAmount(); + RecalculateAmount(); } @@ -622,16 +614,15 @@ namespace Swarmops.Logic.Financial newAmountCents += this.DependentSalariesNet.TotalAmountCentsNet; newAmountCents += this.DependentSalariesTax.TotalAmountCentsTax; - this.AmountCents = newAmountCents; + AmountCents = newAmountCents; } - public void UndoPayout() { // This only works on still-open payouts - if (!this.Open) + if (!Open) { throw new InvalidOperationException("Payout is already closed - cannot undo"); } @@ -645,7 +636,7 @@ namespace Swarmops.Logic.Financial foreach (CashAdvance advance in this.DependentCashAdvancesPayout) { advance.PaidOut = false; - advance.Open = true; // BUG: Why is this here? Isn't the cash advance open until repaid? + advance.Open = true; // BUG: Why is this here? Isn't the cash advance open until repaid? } foreach (InboundInvoice invoice in this.DependentInvoices) @@ -663,16 +654,23 @@ namespace Swarmops.Logic.Financial salary.TaxPaid = false; } - SwarmDb.GetDatabaseForWriting().ClearPayoutDependencies(this.Identity); + SwarmDb.GetDatabaseForWriting().ClearPayoutDependencies(Identity); RecalculateAmount(); - this.Open = false; + Open = false; } #region Implementation of ISummable - public long SumCents { get { return this.AmountCents; } } - public OrganizationFinancialAccountType CounterAccountType { get { return OrganizationFinancialAccountType.Unknown; } } + public long SumCents + { + get { return AmountCents; } + } + + public OrganizationFinancialAccountType CounterAccountType + { + get { return OrganizationFinancialAccountType.Unknown; } + } #endregion } -} +} \ No newline at end of file diff --git a/Logic/Financial/Payouts.cs b/Logic/Financial/Payouts.cs index 8138f033..a218b354 100644 --- a/Logic/Financial/Payouts.cs +++ b/Logic/Financial/Payouts.cs @@ -9,26 +9,53 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class Payouts: PluralBase + public class Payouts : PluralBase { - public static Payouts ForOrganization (Organization organization) + public decimal TotalAmount + { + get + { + decimal result = 0.0m; + + foreach (Payout payout in this) + { + result += payout.Amount; + } + + return result; + } + } + + public Int64 TotalAmountCents + { + get + { + Int64 result = 0; + + foreach (Payout payout in this) + { + result += payout.AmountCents; + } + + return result; + } + } + + public static Payouts ForOrganization(Organization organization) { 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)); } - else - { - 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. @@ -71,8 +98,8 @@ namespace Swarmops.Logic.Financial // No. Create a new payout for this person. 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); + claim.Claimer.BankClearing + " / " + claim.Claimer.BankAccount, string.Empty, 0, + DateTime.MinValue, false, DateTime.Now, 0); Payout payout = Payout.FromBasic(basicPayout); payout.DependentExpenseClaims.Add(claim); @@ -121,19 +148,21 @@ namespace Swarmops.Logic.Financial } string lessAdvancesIndicator = payout.DependentCashAdvancesPayback.Count > 0 - ? "LessAdvances" - : string.Empty; + ? "LessAdvances" + : string.Empty; payout.AmountCents = newAmountCents; if (claimIds.Count == 1) { - payout.Reference = "[Loc]Financial_ExpenseClaimSpecification" + lessAdvancesIndicator + "|" + claimIds[0].ToString(CultureInfo.InvariantCulture); + payout.Reference = "[Loc]Financial_ExpenseClaimSpecification" + lessAdvancesIndicator + "|" + + claimIds[0].ToString(CultureInfo.InvariantCulture); } else { claimIds.Sort(); - payout.Reference = "[Loc]Financial_ExpenseClaimsSpecification" + lessAdvancesIndicator + "|" + Formatting.GenerateRangeString(claimIds); + payout.Reference = "[Loc]Financial_ExpenseClaimsSpecification" + lessAdvancesIndicator + "|" + + Formatting.GenerateRangeString(claimIds); } if (newAmountCents > 0) @@ -141,11 +170,9 @@ namespace Swarmops.Logic.Financial payoutList.Add(payout); } } - } - private static void AddUnpaidCashAdvances(Payouts payoutList, Organization organization) { CashAdvances advances = CashAdvances.ForOrganization(organization); @@ -160,7 +187,8 @@ namespace Swarmops.Logic.Financial if (!advance.Open || !advance.Attested || advance.PaidOut) { - throw new InvalidOperationException("Got into loop with closed/unattested/paid-out cash advances - this is not a possible state"); + throw new InvalidOperationException( + "Got into loop with closed/unattested/paid-out cash advances - this is not a possible state"); } if (payoutLookup.ContainsKey(advance.PersonId)) @@ -174,8 +202,8 @@ namespace Swarmops.Logic.Financial // No. Create a new payout for this person. 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); + advance.Person.BankClearing + " / " + advance.Person.BankAccount, string.Empty, 0, + DateTime.MinValue, false, DateTime.Now, 0); Payout payout = Payout.FromBasic(basicPayout); payout.DependentCashAdvancesPayout.Add(advance); @@ -202,12 +230,14 @@ namespace Swarmops.Logic.Financial if (advanceIds.Count == 1) { - payout.Reference = "[Loc]Financial_CashAdvanceSpecification|" + advanceIds[0].ToString(CultureInfo.InvariantCulture); + payout.Reference = "[Loc]Financial_CashAdvanceSpecification|" + + advanceIds[0].ToString(CultureInfo.InvariantCulture); } else { advanceIds.Sort(); - payout.Reference = "[Loc]Financial_CashAdvancesSpecification|" + Formatting.GenerateRangeString(advanceIds); + payout.Reference = "[Loc]Financial_CashAdvancesSpecification|" + + Formatting.GenerateRangeString(advanceIds); } if (newAmountCents > 0) @@ -218,7 +248,6 @@ namespace Swarmops.Logic.Financial } - private static void AddUnpaidInboundInvoices(Payouts payoutList, Organization organization) { InboundInvoices invoices = InboundInvoices.ForOrganization(organization); @@ -228,8 +257,10 @@ namespace Swarmops.Logic.Financial if (invoice.Attested) { 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); + 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.DependentInvoices.Add(invoice); @@ -239,7 +270,7 @@ namespace Swarmops.Logic.Financial } } - private static void AddUnpaidSalaries (Payouts payoutList, Organization organization) + private static void AddUnpaidSalaries(Payouts payoutList, Organization organization) { Int64 taxTotalCents = 0; @@ -260,8 +291,10 @@ namespace Swarmops.Logic.Financial Person employee = payrollItem.Person; BasicPayout basicPayout = new BasicPayout(0, organization.Identity, employee.BankName, - employee.BankClearing+" / "+employee.BankAccount, "[Loc]Financial_SalarySpecification|[Date]" + salary.PayoutDate.ToString(CultureInfo.InvariantCulture), - salary.NetSalaryCents, salary.PayoutDate, false, DateTime.Now, 0); + employee.BankClearing + " / " + employee.BankAccount, + "[Loc]Financial_SalarySpecification|[Date]" + + salary.PayoutDate.ToString(CultureInfo.InvariantCulture), + salary.NetSalaryCents, salary.PayoutDate, false, DateTime.Now, 0); Payout payout = Payout.FromBasic(basicPayout); payout.DependentSalariesNet.Add(salary); @@ -294,18 +327,19 @@ namespace Swarmops.Logic.Financial if (identityList.Count == 1) { - referenceString = "[Loc]Financial_TaxSpecification|" + identityList[0].ToString(); + referenceString = "[Loc]Financial_TaxSpecification|" + identityList[0]; } else { identityList.Sort(); - referenceString = "[Loc]Financial_TaxesSpecification|" + Formatting.GenerateRangeString(identityList); + referenceString = "[Loc]Financial_TaxesSpecification|" + + Formatting.GenerateRangeString(identityList); } BasicPayout basicPayout = new BasicPayout(0, organization.Identity, "[Loc]Financial_TheTaxMan", - string.Empty, referenceString, - taxTotalCents, payDay, false, DateTime.Now, 0); + string.Empty, referenceString, + taxTotalCents, payDay, false, DateTime.Now, 0); Payout payout = Payout.FromBasic(basicPayout); foreach (int salaryId in identityList) @@ -324,7 +358,7 @@ namespace Swarmops.Logic.Financial // Should this be in bot? - Payouts payouts = Payouts.ForOrganization(organization); + Payouts payouts = ForOrganization(organization); FinancialTransactions transactions = FinancialTransactions.GetUnbalanced(organization); @@ -372,7 +406,8 @@ namespace Swarmops.Logic.Financial DateTime payoutLowerTimeLimit = timeLow; DateTime payoutUpperTimeLimit = timeHigh; - if (payout.AmountCents == -transaction.Rows.AmountCentsTotal && (payout.DependentCashAdvancesPayout.Count > 0 || payout.DependentCashAdvancesPayback.Count > 0)) + if (payout.AmountCents == -transaction.Rows.AmountCentsTotal && + (payout.DependentCashAdvancesPayout.Count > 0 || payout.DependentCashAdvancesPayback.Count > 0)) { // HACK: While PW5 doesn't have a manual-debug interface, special case for cash advances @@ -380,7 +415,9 @@ namespace Swarmops.Logic.Financial payoutUpperTimeLimit = transaction.DateTime.AddDays(60); } - if (payout.ExpectedTransactionDate >= payoutLowerTimeLimit && payout.ExpectedTransactionDate <= payoutUpperTimeLimit && payout.AmountCents == -transaction.Rows.AmountCentsTotal) + if (payout.ExpectedTransactionDate >= payoutLowerTimeLimit && + payout.ExpectedTransactionDate <= payoutUpperTimeLimit && + payout.AmountCents == -transaction.Rows.AmountCentsTotal) { // Console.WriteLine(" - - payout #{0} matches ({1}, {2:yyyy-MM-dd})", payout.Identity, payout.Recipient, payout.ExpectedTransactionDate); @@ -413,39 +450,8 @@ namespace Swarmops.Logic.Financial { Payout payout = Payout.FromIdentity(payoutIdFound); payout.BindToTransactionAndClose(transaction, null); - } } } - - public decimal TotalAmount - { - get - { - decimal result = 0.0m; - - foreach (Payout payout in this) - { - result += payout.Amount; - } - - return result; - } - } - - public Int64 TotalAmountCents - { - get - { - Int64 result = 0; - - foreach (Payout payout in this) - { - result += payout.AmountCents; - } - - return result; - } - } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Payroll.cs b/Logic/Financial/Payroll.cs index afcb1404..5d688312 100644 --- a/Logic/Financial/Payroll.cs +++ b/Logic/Financial/Payroll.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Globalization; -using Swarmops.Basic.Enums; using Swarmops.Basic.Types; using Swarmops.Database; using Swarmops.Logic.Structure; @@ -10,34 +8,34 @@ using Swarmops.Logic.Support.LogEntries; namespace Swarmops.Logic.Financial { - public class Payroll: PluralBase + public class Payroll : PluralBase { /// - /// Returns all open payroll items for an organization. + /// Returns all open payroll items for an organization. /// /// The organization. /// The payroll. - public static Payroll ForOrganization (Organization organization) + public static Payroll ForOrganization(Organization organization) { - return ForOrganization(organization, false); + return ForOrganization(organization, false); } /// - /// Returns all payroll items for an organization, optionally including closed ones. + /// Returns all payroll items for an organization, optionally including closed ones. /// /// 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, - includeClosed? DatabaseCondition.None : DatabaseCondition.OpenTrue)); + return FromArray(SwarmDb.GetDatabaseForReading().GetPayroll(organization, + includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } /// - /// Returns all open payroll for all organizations. + /// Returns all open payroll for all organizations. /// /// The payroll. public static Payroll GetAll() @@ -47,17 +45,20 @@ namespace Swarmops.Logic.Financial /// - /// Returns all payroll for all organizations, optionally including closed ones. + /// Returns all payroll for all organizations, optionally including closed ones. /// /// True to include closed records. /// The payroll. public static Payroll GetAll(bool includeClosed) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayroll(includeClosed? DatabaseCondition.None : DatabaseCondition.OpenTrue)); + return + FromArray( + SwarmDb.GetDatabaseForReading() + .GetPayroll(includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); } /// - /// Processes all payroll for all organizations system-wide. Should run on the 1st of every month. + /// Processes all payroll for all organizations system-wide. Should run on the 1st of every month. /// public static void ProcessMonthly() { @@ -67,7 +68,8 @@ namespace Swarmops.Logic.Financial string expectedLastRun = today.ToString("yyyyMM", CultureInfo.InvariantCulture); - if (lastRun != null && String.Compare(lastRun, expectedLastRun, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) >= 0) + if (lastRun != null && + String.Compare(lastRun, expectedLastRun, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) >= 0) { // nothing to do, return @@ -79,7 +81,7 @@ namespace Swarmops.Logic.Financial // Process the payroll for all organizations. Assume payday is 25th. // TODO: Different payday per organization? - Payroll payroll = Payroll.GetAll(); + Payroll payroll = GetAll(); DateTime payday = new DateTime(today.Year, today.Month, 25); foreach (PayrollItem payrollItem in payroll) @@ -88,8 +90,7 @@ namespace Swarmops.Logic.Financial SwarmopsLog.CreateEntry(payrollItem.Person, new SalaryCreatedLogEntry(salary)); // TODO: CREATE SALARY SPECIFICATION, SEND TO PERSON - } } } -} +} \ No newline at end of file diff --git a/Logic/Financial/PayrollAdjustment.cs b/Logic/Financial/PayrollAdjustment.cs index 65c93a49..63ade99e 100644 --- a/Logic/Financial/PayrollAdjustment.cs +++ b/Logic/Financial/PayrollAdjustment.cs @@ -4,23 +4,13 @@ using Swarmops.Database; namespace Swarmops.Logic.Financial { - public class PayrollAdjustment: BasicPayrollAdjustment + public class PayrollAdjustment : BasicPayrollAdjustment { - private PayrollAdjustment (BasicPayrollAdjustment basic): base (basic) + private PayrollAdjustment(BasicPayrollAdjustment basic) : base(basic) { // private constructor } - public static PayrollAdjustment FromBasic (BasicPayrollAdjustment basic) - { - return new PayrollAdjustment(basic); // invoke private ctor - } - - public static PayrollAdjustment FromIdentity (int payrollAdjustmentId) - { - return FromBasic (SwarmDb.GetDatabaseForReading().GetPayrollAdjustment(payrollAdjustmentId)); - } - public new bool Open { @@ -35,29 +25,41 @@ namespace Swarmops.Logic.Financial // Hide setter } + public decimal AmountDecimal + { + get { return base.AmountCents/100.0m; } + } - public void Close (Salary salary) + public static PayrollAdjustment FromBasic(BasicPayrollAdjustment basic) + { + return new PayrollAdjustment(basic); // invoke private ctor + } + + public static PayrollAdjustment FromIdentity(int payrollAdjustmentId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetPayrollAdjustment(payrollAdjustmentId)); + } + + + public void Close(Salary salary) { if (!Open) { - throw new InvalidOperationException("Payroll adjustment #" + this.Identity.ToString() + " cannot be closed; is already closed"); + throw new InvalidOperationException("Payroll adjustment #" + Identity + + " cannot be closed; is already closed"); } - SwarmDb.GetDatabaseForWriting().ClosePayrollAdjustment(this.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, string description) + public static PayrollAdjustment Create(PayrollItem item, PayrollAdjustmentType type, double amount, + string description) { int id = SwarmDb.GetDatabaseForWriting().CreatePayrollAdjustment(item.Identity, type, amount, description); - return PayrollAdjustment.FromIdentity(id); - } - - public decimal AmountDecimal - { - get { return base.AmountCents/100.0m; } + return FromIdentity(id); } } -} +} \ No newline at end of file diff --git a/Logic/Financial/PayrollAdjustments.cs b/Logic/Financial/PayrollAdjustments.cs index 359b0fcc..7b541809 100644 --- a/Logic/Financial/PayrollAdjustments.cs +++ b/Logic/Financial/PayrollAdjustments.cs @@ -4,16 +4,17 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class PayrollAdjustments: PluralBase + public class PayrollAdjustments : PluralBase { - static public PayrollAdjustments ForPayrollItem (PayrollItem payrollItem) + public static PayrollAdjustments ForPayrollItem(PayrollItem payrollItem) { - return FromArray(SwarmDb.GetDatabaseForReading().GetPayrollAdjustments(payrollItem, DatabaseCondition.OpenTrue)); + return + FromArray(SwarmDb.GetDatabaseForReading().GetPayrollAdjustments(payrollItem, DatabaseCondition.OpenTrue)); } - static public PayrollAdjustments ForSalary (Salary salary) + public static PayrollAdjustments ForSalary(Salary 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 32ebd962..288803a3 100644 --- a/Logic/Financial/PayrollItem.cs +++ b/Logic/Financial/PayrollItem.cs @@ -5,78 +5,58 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class PayrollItem: BasicPayrollItem + public class PayrollItem : BasicPayrollItem { - private PayrollItem (BasicPayrollItem basic): base (basic) + private PayrollItem(BasicPayrollItem basic) : base(basic) { // private constructor } - public static PayrollItem FromBasic (BasicPayrollItem basic) - { - return new PayrollItem(basic); // invoke private ctor - } - - public static PayrollItem FromIdentity (int payrollItemId) - { - return FromBasic (SwarmDb.GetDatabaseForReading().GetPayrollItem(payrollItemId)); - } - private new int PersonId { - get - { - return base.PersonId; // hides base's personId + get { return base.PersonId; // hides base's personId } } 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 { - get - { - return this.Person.Canonical; - } + get { return Person.Canonical; } } 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 Structure.Organization.FromIdentity(this.OrganizationId); - } + get { return Organization.FromIdentity(OrganizationId); } + } + + public static PayrollItem FromBasic(BasicPayrollItem basic) + { + return new PayrollItem(basic); // invoke private ctor + } + + public static PayrollItem FromIdentity(int 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 b11c780d..5049ff86 100644 --- a/Logic/Financial/Refund.cs +++ b/Logic/Financial/Refund.cs @@ -8,64 +8,64 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class Refund: BasicRefund + public class Refund : BasicRefund { - private Refund (BasicRefund basic): base (basic) + private Refund(BasicRefund basic) : base(basic) { // empty pvt ctor } - public static Refund FromBasic (BasicRefund basic) - { - return new Refund(basic); - } - - public static Refund FromIdentity (int refundId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetRefund(refundId)); - } - - public static Refund Create (Payment payment, Person creatingPerson) - { - return Create(payment, creatingPerson, 0L); - } - - public static Refund Create (Payment payment, Person creatingPerson, Int64 amountCents) - { - if (amountCents > payment.AmountCents) - { - throw new ArgumentException("Refund amount cannot exceed payment amount"); - } - - Refund refund = FromIdentity(SwarmDb.GetDatabaseForWriting().CreateRefund(payment.Identity, creatingPerson.Identity, amountCents)); - - PWEvents.CreateEvent(EventSource.PirateWeb, EventType.RefundCreated, 0, refund.Payment.OutboundInvoice.Organization.Identity, - Geography.RootIdentity, 0, refund.Identity, string.Empty); - - return refund; - } - public Payment Payment { - get - { - return Payment.FromIdentity(this.PaymentId); - } + get { return Payment.FromIdentity(PaymentId); } } public decimal AmountDecimal { get { - long cents = this.AmountCents; + long cents = AmountCents; if (AmountCents == 0) { - cents = this.Payment.AmountCents; + cents = Payment.AmountCents; } return cents/100.0m; } } + + public static Refund FromBasic(BasicRefund basic) + { + return new Refund(basic); + } + + public static Refund FromIdentity(int refundId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetRefund(refundId)); + } + + public static Refund Create(Payment payment, Person creatingPerson) + { + return Create(payment, creatingPerson, 0L); + } + + public static Refund Create(Payment payment, Person creatingPerson, Int64 amountCents) + { + if (amountCents > payment.AmountCents) + { + throw new ArgumentException("Refund amount cannot exceed payment amount"); + } + + Refund refund = + FromIdentity(SwarmDb.GetDatabaseForWriting() + .CreateRefund(payment.Identity, creatingPerson.Identity, amountCents)); + + PWEvents.CreateEvent(EventSource.PirateWeb, EventType.RefundCreated, 0, + refund.Payment.OutboundInvoice.Organization.Identity, + Geography.RootIdentity, 0, refund.Identity, string.Empty); + + return refund; + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Salaries.cs b/Logic/Financial/Salaries.cs index b971bd17..5bc06c94 100644 --- a/Logic/Financial/Salaries.cs +++ b/Logic/Financial/Salaries.cs @@ -7,21 +7,8 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { - public class Salaries: PluralBase + public class Salaries : PluralBase { - static public Salaries ForOrganization(Organization organization) - { - return ForOrganization(organization, false); - } - - static public Salaries ForOrganization(Organization organization, bool includeClosed) - { - return FromArray (SwarmDb.GetDatabaseForReading().GetSalaries(organization, - includeClosed? DatabaseCondition.None : DatabaseCondition.OpenTrue)); - } - - - public Salaries WhereAttested { get @@ -34,7 +21,6 @@ namespace Swarmops.Logic.Financial } - public Salaries WhereUnattested { get @@ -47,38 +33,35 @@ 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) + { + return ForOrganization(organization, false); + } + + public static Salaries ForOrganization(Organization organization, bool includeClosed) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetSalaries(organization, + includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)); + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/Salary.cs b/Logic/Financial/Salary.cs index 25a70aea..c56bfe37 100644 --- a/Logic/Financial/Salary.cs +++ b/Logic/Financial/Salary.cs @@ -7,147 +7,17 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Financial { - public class Salary: BasicSalary, IAttestable + public class Salary : BasicSalary, IAttestable { - internal Salary (BasicSalary basic): base (basic) + internal Salary(BasicSalary basic) : base(basic) { // private ctor } - static public Salary FromBasic (BasicSalary basic) - { - return new Salary(basic); - } - - static public Salary FromIdentity (int salaryId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetSalary(salaryId)); - } - - static public Salary Create (int payrollItemId, DateTime payoutDate) - { - return Create(PayrollItem.FromIdentity(payrollItemId), payoutDate); - } - - static public Salary Create (PayrollItem payrollItem, DateTime payoutDate) - { - // Load the existing adjustments. - - PayrollAdjustments adjustments = PayrollAdjustments.ForPayrollItem(payrollItem); - - Int64 payCents = payrollItem.BaseSalaryCents; - - // Apply all before-tax adjustments - - foreach (PayrollAdjustment adjustment in adjustments) - { - if (adjustment.Type == PayrollAdjustmentType.GrossAdjustment) - { - payCents += adjustment.AmountCents; - } - } - - // calculate tax - - double subtractiveTax = TaxLevels.GetTax (payrollItem.Country, payrollItem.SubtractiveTaxLevelId, payCents / 100.0); - - if (subtractiveTax < 1.0) - { - // this is a percentage and not an absolute number - - subtractiveTax = payCents * subtractiveTax; - } - Int64 subtractiveTaxCents = (Int64) (subtractiveTax*100); - - Int64 additiveTaxCents = (Int64) (payCents * payrollItem.AdditiveTaxLevel); - - payCents -= subtractiveTaxCents; - - // Apply all after-tax adjustments - - foreach (PayrollAdjustment adjustment in adjustments) - { - if (adjustment.Type == PayrollAdjustmentType.NetAdjustment) - { - payCents += adjustment.AmountCents; - } - } - - // Create salary, close adjustments - - Salary salary = Salary.Create(payrollItem, payoutDate, payCents, subtractiveTaxCents, additiveTaxCents); - - // For each adjustment, close and bind to salary - - foreach (PayrollAdjustment adjustment in adjustments) - { - adjustment.Close(salary); - } - - // If net is negative, create rollover adjustment - - if (payCents < 0) - { - PayrollAdjustment rollover1 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, -payCents, - "Deficit rolls over to next salary"); - - rollover1.Close(salary); - - PayrollAdjustment rollover2 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, - payCents, "Deficit rolled over from " + - payoutDate.ToString("yyyy-MM-dd")); - - // keep rollover2 open, so the deficit from this salary is carried to the next - - salary.NetSalaryCents = 0; - } - - // Add the financial transaction - - FinancialTransaction transaction = - 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); - 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) - - if (salary.NetSalaryCents == 0) - { - salary.NetPaid = true; - } - - if (salary.TaxTotalCents == 0) - { - salary.TaxPaid = true; - } - - return salary; - } - - static private Salary Create (PayrollItem payrollItem, DateTime payoutDate, Int64 netSalaryCents, Int64 subtractiveTaxCents, Int64 additiveTaxCents) - { - return - FromIdentity(SwarmDb.GetDatabaseForWriting().CreateSalary(payrollItem.Identity, payoutDate, payrollItem.BaseSalaryCents, netSalaryCents, - subtractiveTaxCents, additiveTaxCents)); - } - public PayrollItem PayrollItem { - get - { - return PayrollItem.FromIdentity(this.PayrollItemId); - } - } - - public FinancialAccount Budget // needed for IAttestable - { - get { return this.PayrollItem.Budget; } + get { return PayrollItem.FromIdentity(PayrollItemId); } } @@ -182,29 +52,27 @@ namespace Swarmops.Logic.Financial public new Int64 NetSalaryCents { - get { return base.NetSalaryCents; } // TODO: CONVERT TO MAKE CENTS-BASED CALCULATIONS THE MASTER + get { return base.NetSalaryCents; } // TODO: CONVERT TO MAKE CENTS-BASED CALCULATIONS THE MASTER set { if (value != base.NetSalaryCents) { - SwarmDb.GetDatabaseForWriting().SetSalaryNetSalary(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryNetSalary(Identity, value); base.NetSalaryCents = value; } } } - public Int64 GrossSalaryCents { get { - - Int64 payCents = this.BaseSalaryCents; + Int64 payCents = BaseSalaryCents; // Apply all before-tax adjustments - foreach (PayrollAdjustment adjustment in this.Adjustments) + foreach (PayrollAdjustment adjustment in Adjustments) { if (adjustment.Type == PayrollAdjustmentType.GrossAdjustment) { @@ -223,17 +91,17 @@ namespace Swarmops.Logic.Financial public decimal CostTotalDecimal { - get { return CostTotalCents / 100.0m; } + get { return CostTotalCents/100.0m; } } public decimal TaxTotalDecimal { - get { return TaxTotalCents / 100.0m; } + get { return TaxTotalCents/100.0m; } } public Int64 TaxTotalCents { - get { return AdditiveTaxCents + SubtractiveTaxCents; } + get { return AdditiveTaxCents + SubtractiveTaxCents; } } public new bool NetPaid @@ -241,7 +109,7 @@ namespace Swarmops.Logic.Financial get { return base.NetPaid; } set { - SwarmDb.GetDatabaseForWriting().SetSalaryNetPaid(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryNetPaid(Identity, value); base.NetPaid = value; base.Open = !(base.NetPaid && base.TaxPaid); } @@ -252,7 +120,7 @@ namespace Swarmops.Logic.Financial get { return base.TaxPaid; } set { - SwarmDb.GetDatabaseForWriting().SetSalaryTaxPaid(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetSalaryTaxPaid(Identity, value); base.NetPaid = value; base.Open = !(base.NetPaid && base.TaxPaid); } @@ -272,35 +140,164 @@ namespace Swarmops.Logic.Financial { // Usually a salary is attested by the budget owner -- except when that person is the target of the payout - Person budgetOwner = this.PayrollItem.Budget.Owner; + Person budgetOwner = PayrollItem.Budget.Owner; - if (this.PayrollItem.Person.Identity == budgetOwner.Identity) + if (PayrollItem.Person.Identity == budgetOwner.Identity) { - return this.PayrollItem.ReportsToPerson; + return PayrollItem.ReportsToPerson; } return budgetOwner; } } - - #region IAttestable Members public void Attest(Person attester) { SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.Salary, this.Identity, DateTime.Now, attester.Identity, this.NetSalaryCents / 100.0); - SwarmDb.GetDatabaseForWriting().SetSalaryAttested(this.Identity, true); + FinancialDependencyType.Salary, Identity, DateTime.Now, attester.Identity, NetSalaryCents/100.0); + SwarmDb.GetDatabaseForWriting().SetSalaryAttested(Identity, true); } public void Deattest(Person deattester) { SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.Salary, this.Identity, DateTime.Now, deattester.Identity, this.NetSalaryCents / 100.0); - SwarmDb.GetDatabaseForWriting().SetSalaryAttested(this.Identity, false); + FinancialDependencyType.Salary, Identity, DateTime.Now, deattester.Identity, NetSalaryCents/100.0); + SwarmDb.GetDatabaseForWriting().SetSalaryAttested(Identity, false); } #endregion + + public FinancialAccount Budget // needed for IAttestable + { + get { return PayrollItem.Budget; } + } + + public static Salary FromBasic(BasicSalary basic) + { + return new Salary(basic); + } + + public static Salary FromIdentity(int salaryId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetSalary(salaryId)); + } + + public static Salary Create(int payrollItemId, DateTime payoutDate) + { + return Create(PayrollItem.FromIdentity(payrollItemId), payoutDate); + } + + public static Salary Create(PayrollItem payrollItem, DateTime payoutDate) + { + // Load the existing adjustments. + + PayrollAdjustments adjustments = PayrollAdjustments.ForPayrollItem(payrollItem); + + Int64 payCents = payrollItem.BaseSalaryCents; + + // Apply all before-tax adjustments + + foreach (PayrollAdjustment adjustment in adjustments) + { + if (adjustment.Type == PayrollAdjustmentType.GrossAdjustment) + { + payCents += adjustment.AmountCents; + } + } + + // calculate tax + + double subtractiveTax = TaxLevels.GetTax(payrollItem.Country, payrollItem.SubtractiveTaxLevelId, + payCents/100.0); + + if (subtractiveTax < 1.0) + { + // this is a percentage and not an absolute number + + subtractiveTax = payCents*subtractiveTax; + } + Int64 subtractiveTaxCents = (Int64) (subtractiveTax*100); + + Int64 additiveTaxCents = (Int64) (payCents*payrollItem.AdditiveTaxLevel); + + payCents -= subtractiveTaxCents; + + // Apply all after-tax adjustments + + foreach (PayrollAdjustment adjustment in adjustments) + { + if (adjustment.Type == PayrollAdjustmentType.NetAdjustment) + { + payCents += adjustment.AmountCents; + } + } + + // Create salary, close adjustments + + Salary salary = Create(payrollItem, payoutDate, payCents, subtractiveTaxCents, additiveTaxCents); + + // For each adjustment, close and bind to salary + + foreach (PayrollAdjustment adjustment in adjustments) + { + adjustment.Close(salary); + } + + // If net is negative, create rollover adjustment + + if (payCents < 0) + { + PayrollAdjustment rollover1 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, + -payCents, + "Deficit rolls over to next salary"); + + rollover1.Close(salary); + + PayrollAdjustment rollover2 = PayrollAdjustment.Create(payrollItem, PayrollAdjustmentType.NetAdjustment, + payCents, "Deficit rolled over from " + + payoutDate.ToString("yyyy-MM-dd")); + + // keep rollover2 open, so the deficit from this salary is carried to the next + + salary.NetSalaryCents = 0; + } + + // Add the financial transaction + + FinancialTransaction transaction = + 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); + 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) + + if (salary.NetSalaryCents == 0) + { + salary.NetPaid = true; + } + + if (salary.TaxTotalCents == 0) + { + salary.TaxPaid = true; + } + + return salary; + } + + 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, + subtractiveTaxCents, additiveTaxCents)); + } } -} +} \ No newline at end of file diff --git a/Logic/Financial/StockBankDataReaders.cs b/Logic/Financial/StockBankDataReaders.cs index 943d6981..8112f9d2 100644 --- a/Logic/Financial/StockBankDataReaders.cs +++ b/Logic/Financial/StockBankDataReaders.cs @@ -1,10 +1,18 @@ namespace Swarmops.Logic.Financial { // ReSharper disable InconsistentNaming - class StockBankDataReaders + internal class StockBankDataReaders { - public static string TabSeparatedValuesAccountReader { get { return "TabSeparatedValuesReader"; }} - public static string SEPaymentsBankgiroReader { get { return "SEPaymentsBankgiroReader"; }} + public static string TabSeparatedValuesAccountReader + { + get { return "TabSeparatedValuesReader"; } + } + + public static string SEPaymentsBankgiroReader + { + get { return "SEPaymentsBankgiroReader"; } + } } + // ReSharper restore InconsistentNaming -} +} \ No newline at end of file diff --git a/Logic/Financial/TaxLevels.cs b/Logic/Financial/TaxLevels.cs index f56739ad..74bc71d5 100644 --- a/Logic/Financial/TaxLevels.cs +++ b/Logic/Financial/TaxLevels.cs @@ -1,21 +1,20 @@ using System; using Swarmops.Database; using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { public class TaxLevels { - static public 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 + if (grossSalary < 1.0) // The lowest tax bracket is 1 currency unit { - return 0.0; // no tax + return 0.0; // no tax } double taxLevel = SwarmDb.GetDatabaseForReading().GetSalaryTaxLevel(country.Identity, taxLevelIdentifier, - (int) Math.Floor(grossSalary)); + (int) Math.Floor(grossSalary)); if (taxLevel < 1.0) { @@ -29,14 +28,14 @@ namespace Swarmops.Logic.Financial return taxLevel; } - static public 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"); } - 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) { @@ -62,12 +61,13 @@ namespace Swarmops.Logic.Financial if (isPercentage) { - tax = tax / 100.0; + tax = tax/100.0; } - SwarmDb.GetDatabaseForWriting().CreateSalaryTaxLevel(country.Identity, taxLevelId, lowerBracket, year, tax); + SwarmDb.GetDatabaseForWriting() + .CreateSalaryTaxLevel(country.Identity, taxLevelId, lowerBracket, year, tax); } } } } -} +} \ No newline at end of file diff --git a/Logic/Financial/YearlyReport.cs b/Logic/Financial/YearlyReport.cs index 4a9ad479..c0e5e1ba 100644 --- a/Logic/Financial/YearlyReport.cs +++ b/Logic/Financial/YearlyReport.cs @@ -9,7 +9,16 @@ namespace Swarmops.Logic.Financial [Serializable] public class YearlyReport { - public static YearlyReport Create (Organization organization, int year, FinancialAccountType accountType) + public Organization Organization; + public List ReportLines; + public YearlyReportNode Totals; + public int Year; + private FinancialAccountType _accountType; + private Dictionary[] _singleLookups; + private Dictionary[] _treeLookups; + private Dictionary> _treeMap; + + public static YearlyReport Create(Organization organization, int year, FinancialAccountType accountType) { YearlyReport report = new YearlyReport(); report.Organization = organization; @@ -50,10 +59,11 @@ namespace Swarmops.Logic.Financial } - FinancialAccounts orderedList = new FinancialAccounts(); // This list is guaranteed to have parents before children + FinancialAccounts orderedList = new FinancialAccounts(); + // 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(); @@ -72,9 +82,6 @@ namespace Swarmops.Logic.Financial } - private FinancialAccountType _accountType; - - private void AggregateAccounts() { const int assetIdentity = 1000000001; @@ -82,30 +89,31 @@ namespace Swarmops.Logic.Financial const int incomeIdentity = 1000000003; const int costIdentity = 1000000004; - Dictionary remapLookup = new Dictionary(); + Dictionary remapLookup = + new Dictionary(); List newRootLevel = new List(); - int equityIdentity = _treeMap[0][0].Organization.FinancialAccounts.DebtsEquity.Identity; + int equityIdentity = this._treeMap[0][0].Organization.FinancialAccounts.DebtsEquity.Identity; - if (_accountType == FinancialAccountType.Balance) + if (this._accountType == FinancialAccountType.Balance) { YearlyReportLine assetLine = new YearlyReportLine - {AccountId = assetIdentity, AccountName = "%ASSET_ACCOUNTGROUP%"}; + {AccountId = assetIdentity, AccountName = "%ASSET_ACCOUNTGROUP%"}; YearlyReportLine debtLine = new YearlyReportLine - {AccountId = debtIdentity, AccountName = "%DEBT_ACCOUNTGROUP%"}; + {AccountId = debtIdentity, AccountName = "%DEBT_ACCOUNTGROUP%"}; remapLookup[FinancialAccountType.Asset] = assetLine; remapLookup[FinancialAccountType.Debt] = debtLine; newRootLevel.Add(assetLine); newRootLevel.Add(debtLine); } - else if (_accountType == FinancialAccountType.Result) + else if (this._accountType == FinancialAccountType.Result) { YearlyReportLine incomeLine = new YearlyReportLine - {AccountId = incomeIdentity, AccountName = "%INCOME_ACCOUNTGROUP%"}; + {AccountId = incomeIdentity, AccountName = "%INCOME_ACCOUNTGROUP%"}; YearlyReportLine costLine = new YearlyReportLine - {AccountId = costIdentity, AccountName = "%COST_ACCOUNTGROUP%"}; + {AccountId = costIdentity, AccountName = "%COST_ACCOUNTGROUP%"}; remapLookup[FinancialAccountType.Income] = incomeLine; remapLookup[FinancialAccountType.Cost] = costLine; @@ -114,10 +122,11 @@ namespace Swarmops.Logic.Financial } else { - throw new InvalidOperationException("AccountType other than Balance or Result passed to YearlyReport.AggregateAccounts()"); + throw new InvalidOperationException( + "AccountType other than Balance or Result passed to YearlyReport.AggregateAccounts()"); } - foreach (YearlyReportLine reportLine in ReportLines) + foreach (YearlyReportLine reportLine in this.ReportLines) { if (reportLine.AccountId == equityIdentity) { @@ -152,16 +161,16 @@ namespace Swarmops.Logic.Financial { this.Totals = new YearlyReportNode(); - this.Totals.PreviousYear = PopulateOneTotal(_singleLookups[0]); - this.Totals.ThisYear = PopulateOneTotal(_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(_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(); @@ -169,18 +178,18 @@ namespace Swarmops.Logic.Financial } - private void RecurseAddLines (List list, int renderNodeId) + private void RecurseAddLines(List list, int renderNodeId) { - foreach (FinancialAccount account in _treeMap[renderNodeId]) + foreach (FinancialAccount account in this._treeMap[renderNodeId]) { YearlyReportLine newLine = new YearlyReportLine(); newLine.AccountId = account.Identity; newLine.AccountName = account.Name; newLine.AccountType = account.AccountType; - newLine.AccountValues = CreateYearlyReportNode(account.Identity, _singleLookups); - newLine.AccountTreeValues = CreateYearlyReportNode(account.Identity, _treeLookups); + newLine.AccountValues = CreateYearlyReportNode(account.Identity, this._singleLookups); + newLine.AccountTreeValues = CreateYearlyReportNode(account.Identity, this._treeLookups); - if (_treeMap.ContainsKey(account.Identity)) + if (this._treeMap.ContainsKey(account.Identity)) { RecurseAddLines(newLine.Children, account.Identity); } @@ -190,11 +199,11 @@ namespace Swarmops.Logic.Financial } - private YearlyReportNode CreateYearlyReportNode (int accountId, Dictionary[] lookup) + private YearlyReportNode CreateYearlyReportNode(int accountId, Dictionary[] lookup) { YearlyReportNode node = new YearlyReportNode(); node.PreviousYear = lookup[0][accountId]; - + for (int quarter = 1; quarter <= 4; quarter++) { node.Quarters[quarter - 1] = lookup[quarter][accountId]; @@ -207,31 +216,27 @@ namespace Swarmops.Logic.Financial private void PopulateOrderedList(FinancialAccounts orderedList, int renderNodeId) { - foreach (FinancialAccount account in _treeMap[renderNodeId]) + foreach (FinancialAccount account in this._treeMap[renderNodeId]) { orderedList.Add(account); - if (_treeMap.ContainsKey(account.Identity)) + if (this._treeMap.ContainsKey(account.Identity)) { PopulateOrderedList(orderedList, account.Identity); // recursive call } } } - private Dictionary> _treeMap; - private Dictionary[] _singleLookups; - private Dictionary[] _treeLookups; - private void PopulateLookups(FinancialAccounts accounts) { - _singleLookups = new Dictionary[6]; - _treeLookups = new Dictionary[6]; + this._singleLookups = new Dictionary[6]; + this._treeLookups = new Dictionary[6]; for (int index = 0; index < 6; index++) { - _treeLookups[index] = new Dictionary(); - _singleLookups[index] = new Dictionary(); + this._treeLookups[index] = new Dictionary(); + this._singleLookups[index] = new Dictionary(); } DateTime[] quarterBoundaries = @@ -249,51 +254,54 @@ namespace Swarmops.Logic.Financial { // Find this year's inbound - if (_accountType == FinancialAccountType.Result) + if (this._accountType == FinancialAccountType.Result) { - _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 (_accountType == FinancialAccountType.Balance) + else if (this._accountType == FinancialAccountType.Balance) { - _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("Can only calculate yearly reports for balance or P&L statements"); + throw new InvalidOperationException( + "Can only calculate yearly reports for balance or P&L statements"); } // Find quarter diffs for (int quarter = 0; quarter < 4; quarter++) { - _singleLookups[quarter + 1][account.Identity] = account.GetDeltaCents(quarterBoundaries[quarter], - quarterBoundaries[quarter + 1]); + this._singleLookups[quarter + 1][account.Identity] = + account.GetDeltaCents(quarterBoundaries[quarter], + quarterBoundaries[quarter + 1]); } // Find outbound - if (_accountType == FinancialAccountType.Result) + if (this._accountType == FinancialAccountType.Result) { - _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 (_accountType == FinancialAccountType.Balance) + else if (this._accountType == FinancialAccountType.Balance) { - _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("Can only calculate yearly reports for balance or P&L statements"); + throw new InvalidOperationException( + "Can only calculate yearly reports for balance or P&L statements"); } // copy to treeLookups for (int index = 0; index < 6; index++) { - _treeLookups[index][account.Identity] = _singleLookups[index][account.Identity]; + this._treeLookups[index][account.Identity] = this._singleLookups[index][account.Identity]; } } @@ -301,7 +309,7 @@ namespace Swarmops.Logic.Financial for (int index = 0; index < 6; index++) { - AddChildrenValuesToParents(_treeLookups[index], accounts); + AddChildrenValuesToParents(this._treeLookups[index], accounts); } // Done. @@ -323,46 +331,38 @@ namespace Swarmops.Logic.Financial } } } - - - - - public List ReportLines; - public YearlyReportNode Totals; - public Organization Organization; - public int Year; } [Serializable] public class YearlyReportLine { - public YearlyReportLine() - { - Children = new List(); - AccountValues = new YearlyReportNode(); - AccountTreeValues = new YearlyReportNode(); - } - public int AccountId; public string AccountName; + public YearlyReportNode AccountTreeValues; public FinancialAccountType AccountType; public YearlyReportNode AccountValues; - public YearlyReportNode AccountTreeValues; public List Children; + + public YearlyReportLine() + { + this.Children = new List(); + this.AccountValues = new YearlyReportNode(); + this.AccountTreeValues = new YearlyReportNode(); + } } [Serializable] public class YearlyReportNode { - public YearlyReportNode() - { - Quarters = new Int64[4]; - } - public Int64 PreviousYear; public Int64[] Quarters; public Int64 ThisYear; + + public YearlyReportNode() + { + this.Quarters = new Int64[4]; + } } -} +} \ No newline at end of file diff --git a/Logic/Governance/Ballot.cs b/Logic/Governance/Ballot.cs index e9690ac2..7492ab92 100644 --- a/Logic/Governance/Ballot.cs +++ b/Logic/Governance/Ballot.cs @@ -5,58 +5,31 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class Ballot: BasicBallot + public class Ballot : BasicBallot { - private Ballot (BasicBallot basic): base (basic) + private Ballot(BasicBallot basic) : base(basic) { // empty ctor } - public static Ballot FromBasic (BasicBallot basic) - { - return new Ballot(basic); - } - - public static Ballot FromIdentity (int ballotId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetBallot(ballotId)); - } - - 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, deliveryAddress)); - } - - public void AddCandidate (Person person) - { - SwarmDb.GetDatabaseForWriting().CreateBallotCandidate(this.Identity, person.Identity); - } - - public void ClearCandidates() - { - SwarmDb.GetDatabaseForWriting().ClearBallotCandidates(this.Identity); - } - public People Candidates { - get - { - return People.FromIdentities(SwarmDb.GetDatabaseForReading().GetBallotCandidates(this.Identity), true); - } + get { return People.FromIdentities(SwarmDb.GetDatabaseForReading().GetBallotCandidates(Identity), true); } } public Geography Geography { - get { return Geography.FromIdentity(this.GeographyId); } + get { return Geography.FromIdentity(GeographyId); } } public new int Count { - set - { - if (value != base.Count) { + set + { + if (value != base.Count) + { base.Count = value; - SwarmDb.GetDatabaseForWriting().SetBallotCount(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetBallotCount(Identity, value); } } get { return base.Count; } @@ -69,10 +42,39 @@ namespace Swarmops.Logic.Governance if (value != base.DeliveryAddress) { base.DeliveryAddress = value; - SwarmDb.GetDatabaseForWriting().SetBallotDeliveryAddress(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetBallotDeliveryAddress(Identity, value); } } get { return base.DeliveryAddress; } } + + public static Ballot FromBasic(BasicBallot basic) + { + return new Ballot(basic); + } + + public static Ballot FromIdentity(int ballotId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetBallot(ballotId)); + } + + 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, + deliveryAddress)); + } + + public void AddCandidate(Person person) + { + SwarmDb.GetDatabaseForWriting().CreateBallotCandidate(Identity, person.Identity); + } + + public void ClearCandidates() + { + SwarmDb.GetDatabaseForWriting().ClearBallotCandidates(Identity); + } } -} +} \ No newline at end of file diff --git a/Logic/Governance/Ballots.cs b/Logic/Governance/Ballots.cs index 505e81d6..909ac8d4 100644 --- a/Logic/Governance/Ballots.cs +++ b/Logic/Governance/Ballots.cs @@ -7,19 +7,19 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class Ballots: PluralBase + public class Ballots : PluralBase { // 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)); } - public static Dictionary GetBallotsForPerson (Person person) + public static Dictionary GetBallotsForPerson(Person person) { 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 38b3cf57..99cb5ef1 100644 --- a/Logic/Governance/Election.cs +++ b/Logic/Governance/Election.cs @@ -6,52 +6,56 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class Election: BasicElection + public class Election : BasicElection { - private Election (BasicElection basic): base (basic) + private Election(BasicElection basic) : base(basic) { // empty private ctor } - public static Election FromBasic (BasicElection basic) + public static Election September2010 + { + get { return FromIdentity(3); } + } + + public static Election FromBasic(BasicElection 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))); + new DateTime(2006, 9, 17))); case 2: return FromBasic(new BasicElection(2, "SE European Elections", Country.FromCode("SE").GeographyId, - new DateTime(2009, 6, 7))); + new DateTime(2009, 6, 7))); case 3: return FromBasic(new BasicElection(3, "SE General Elections", Country.FromCode("SE").GeographyId, - new DateTime(2010, 9, 19))); + new DateTime(2010, 9, 19))); default: 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(this.Identity, - organization.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(this.Identity, organization.Identity, candidate.Identity); + SwarmDb.GetDatabaseForWriting() + .SetCandidateDocumentationReceived(Identity, organization.Identity, candidate.Identity); } - - public static Election September2010 { get { return FromIdentity(3); } } } -} +} \ No newline at end of file diff --git a/Logic/Governance/Meeting.cs b/Logic/Governance/Meeting.cs index 1ebf1464..07409256 100644 --- a/Logic/Governance/Meeting.cs +++ b/Logic/Governance/Meeting.cs @@ -3,19 +3,19 @@ using Swarmops.Database; namespace Swarmops.Logic.Governance { - public class Meeting: BasicMeeting + 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); } - public static Meeting FromIdentity (int meetingId) + public static Meeting FromIdentity(int meetingId) { return FromBasic(SwarmDb.GetDatabaseForReading().GetMeeting(meetingId)); } diff --git a/Logic/Governance/MeetingElection.cs b/Logic/Governance/MeetingElection.cs index c2d9ef6a..00f775fb 100644 --- a/Logic/Governance/MeetingElection.cs +++ b/Logic/Governance/MeetingElection.cs @@ -8,33 +8,14 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class MeetingElection: BasicInternalPoll + public class MeetingElection : BasicInternalPoll { private MeetingElection(BasicInternalPoll basic) : base(basic) { // private ctor } - public static MeetingElection FromBasic (BasicInternalPoll basic) - { - return new MeetingElection(basic); - } - 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, - resultsType, creator.Identity, runningOpens, - runningCloses, votingOpens, votingCloses)); - } - - - public static MeetingElection FromIdentity (int internalPollId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPoll(internalPollId)); - } - - public static MeetingElection Primaries2010Simulation { get { return FromIdentity(1); } @@ -55,19 +36,78 @@ namespace Swarmops.Logic.Governance get { return MeetingElectionCandidates.ForPoll(this); } } - public void AddCandidate (Person person, string candidacyStatement) + public Organization Organization + { + get { return Organization.FromIdentity(base.OrganizationId); } + } + + public new bool VotingOpen + { + get { return base.VotingOpen; } + set + { + if (value != base.VotingOpen) + { + SwarmDb.GetDatabaseForWriting().SetInternalPollVotingOpen(Identity, value); + base.VotingOpen = value; + } + } + } + + public new bool RunningOpen + { + get { return base.RunningOpen; } + set + { + if (value != base.RunningOpen) + { + SwarmDb.GetDatabaseForWriting().SetInternalPollRunningOpen(Identity, value); + base.RunningOpen = value; + } + } + } + + public Person Creator + { + get { return Person.FromIdentity(base.CreatedByPersonId); } + } + + public static MeetingElection FromBasic(BasicInternalPoll basic) + { + return new MeetingElection(basic); + } + + 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, + resultsType, creator.Identity, runningOpens, + runningCloses, votingOpens, votingCloses)); + } + + + public static MeetingElection FromIdentity(int internalPollId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPoll(internalPollId)); + } + + public void AddCandidate(Person person, string candidacyStatement) { MeetingElectionCandidate.Create(this, person, candidacyStatement); } - public void AddVoter (Person person) + public void AddVoter(Person person) { - SwarmDb.GetDatabaseForWriting().CreateInternalPollVoter(this.Identity, person.Identity); + SwarmDb.GetDatabaseForWriting().CreateInternalPollVoter(Identity, person.Identity); } public MeetingElectionVote CreateVote(Person person, string ipAddress) { - if (SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus(this.Identity, person.Identity) != InternalPollVoterStatus.CanVote) + if (SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus(Identity, person.Identity) != + InternalPollVoterStatus.CanVote) { throw new InvalidOperationException("Voter status is not open"); } @@ -86,59 +126,23 @@ namespace Swarmops.Logic.Governance voteGeography = person.Geography; } - SwarmDb.GetDatabaseForWriting().CloseInternalPollVoter(this.Identity, person.Identity, ipAddress); + 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(this.Identity, person.Identity); + return SwarmDb.GetDatabaseForReading().GetInternalPollVoterStatus(Identity, person.Identity); } - public Dictionary GetCandidatePersonMap() + public Dictionary GetCandidatePersonMap() { - return SwarmDb.GetDatabaseForReading().GetCandidateIdPersonIdMap(this.Identity); + return SwarmDb.GetDatabaseForReading().GetCandidateIdPersonIdMap(Identity); } public MeetingElectionVoters GetClosedVoters() { return MeetingElectionVoters.ForPollClosed(this); } - - public Organization Organization - { - get { return Structure.Organization.FromIdentity(base.OrganizationId); } - } - - public new bool VotingOpen - { - get { return base.VotingOpen; } - set - { - if (value != base.VotingOpen) - { - SwarmDb.GetDatabaseForWriting().SetInternalPollVotingOpen(this.Identity, value); - base.VotingOpen = value; - } - } - } - - public new bool RunningOpen - { - get { return base.RunningOpen; } - set - { - if (value != base.RunningOpen) - { - SwarmDb.GetDatabaseForWriting().SetInternalPollRunningOpen(this.Identity, value); - base.RunningOpen = value; - } - } - } - - public Person Creator - { - get { return Person.FromIdentity(base.CreatedByPersonId); } - } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionCandidate.cs b/Logic/Governance/MeetingElectionCandidate.cs index 96cb2ed3..7683350d 100644 --- a/Logic/Governance/MeetingElectionCandidate.cs +++ b/Logic/Governance/MeetingElectionCandidate.cs @@ -6,81 +6,40 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class MeetingElectionCandidate: BasicInternalPollCandidate + public class MeetingElectionCandidate : BasicInternalPollCandidate { - private MeetingElectionCandidate (BasicInternalPollCandidate basic): base (basic) - { - // private ctor - } - - public static MeetingElectionCandidate FromBasic (BasicInternalPollCandidate basic) - { - return new MeetingElectionCandidate(basic); - } - - public static MeetingElectionCandidate FromIdentity (int internalPollCandidateId) - { - if (!cache.ContainsKey(internalPollCandidateId)) - { - cache [internalPollCandidateId] = FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollCandidate(internalPollCandidateId)); - } - - return cache[internalPollCandidateId]; - } - - public static MeetingElectionCandidate FromPersonAndPoll (Person person, MeetingElection poll) - { - MeetingElectionCandidates candidates = - MeetingElectionCandidates.FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollCandidates(person, poll)); - - if (candidates.Count == 0) - { - return null; // Or throw exception? Which is the most accurate? - } - - if (candidates.Count > 1) - { - throw new InvalidOperationException( - "A specific person can not be a candidate more than once for a specific poll"); - } - - return candidates[0]; - } - - - public static MeetingElectionCandidate Create (MeetingElection poll, Person person, string candidacyStatement) - { - return FromIdentity (SwarmDb.GetDatabaseForWriting().CreateInternalPollCandidate(poll.Identity, person.Identity, candidacyStatement)); - } - - private static Dictionary cache; + private static readonly Dictionary cache; + private Person personCache; static MeetingElectionCandidate() { cache = new Dictionary(); } + private MeetingElectionCandidate(BasicInternalPollCandidate basic) : base(basic) + { + // private ctor + } + public string PersonName { - get { return this.Person.Name; } + get { return Person.Name; } } public Person Person { get { - if (personCache == null) + if (this.personCache == null) { - personCache = Person.FromIdentity(this.PersonId); + this.personCache = Person.FromIdentity(PersonId); } - return personCache; + return this.personCache; } } - private Person personCache; - public string PersonSubtitle { get @@ -99,45 +58,87 @@ namespace Swarmops.Logic.Governance public string PersonBlogHtml { - get - { - return "Blogg: " + Person.BlogName + ""; - } + get { return "Blogg: " + Person.BlogName + ""; } } public string PersonPhotoHtml { get { - return ""; + return ""; } } - public override string ToString() - { - return this.Identity.ToString(); - } - - public void SetSortOrder(string sortOrder) - { - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder(this.Identity, sortOrder); - } - - public void RandomizeSortOrder() - { - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder(this.Identity, System.Guid.NewGuid().ToString()); - } - public new string CandidacyStatement - { + { get { return base.CandidacyStatement; } set { base.CandidacyStatement = value; - cache[this.Identity] = this; // Replace cache instance - SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateStatement(this.Identity, value); + cache[Identity] = this; // Replace cache instance + SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateStatement(Identity, value); } } + + public static MeetingElectionCandidate FromBasic(BasicInternalPollCandidate basic) + { + return new MeetingElectionCandidate(basic); + } + + public static MeetingElectionCandidate FromIdentity(int internalPollCandidateId) + { + if (!cache.ContainsKey(internalPollCandidateId)) + { + cache[internalPollCandidateId] = + FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollCandidate(internalPollCandidateId)); + } + + return cache[internalPollCandidateId]; + } + + public static MeetingElectionCandidate FromPersonAndPoll(Person person, MeetingElection poll) + { + MeetingElectionCandidates candidates = + MeetingElectionCandidates.FromArray(SwarmDb.GetDatabaseForReading() + .GetInternalPollCandidates(person, poll)); + + if (candidates.Count == 0) + { + return null; // Or throw exception? Which is the most accurate? + } + + if (candidates.Count > 1) + { + throw new InvalidOperationException( + "A specific person can not be a candidate more than once for a specific poll"); + } + + return candidates[0]; + } + + + public static MeetingElectionCandidate Create(MeetingElection poll, Person person, string candidacyStatement) + { + return + FromIdentity(SwarmDb.GetDatabaseForWriting() + .CreateInternalPollCandidate(poll.Identity, person.Identity, candidacyStatement)); + } + + public override string ToString() + { + return Identity.ToString(); + } + + public void SetSortOrder(string sortOrder) + { + SwarmDb.GetDatabaseForWriting().SetInternalPollCandidateSortOrder(Identity, sortOrder); + } + + public void RandomizeSortOrder() + { + 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 d423eca2..e3d509af 100644 --- a/Logic/Governance/MeetingElectionCandidates.cs +++ b/Logic/Governance/MeetingElectionCandidates.cs @@ -4,9 +4,10 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Governance { - public class MeetingElectionCandidates: PluralBase + public class MeetingElectionCandidates : + PluralBase { - public static MeetingElectionCandidates ForPoll (MeetingElection poll) + public static MeetingElectionCandidates ForPoll(MeetingElection poll) { return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollCandidates(poll)); } diff --git a/Logic/Governance/MeetingElectionVote.cs b/Logic/Governance/MeetingElectionVote.cs index 5de46dd0..bae6144b 100644 --- a/Logic/Governance/MeetingElectionVote.cs +++ b/Logic/Governance/MeetingElectionVote.cs @@ -5,49 +5,50 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.Governance { - public class MeetingElectionVote: BasicInternalPollVote + public class MeetingElectionVote : BasicInternalPollVote { - private MeetingElectionVote (BasicInternalPollVote basic): base (basic) + private MeetingElectionVote(BasicInternalPollVote basic) : base(basic) { // empty private ctor } - static public MeetingElectionVote FromBasic (BasicInternalPollVote basic) + public int[] SelectedCandidateIdsInOrder + { + get { return SwarmDb.GetDatabaseForReading().GetInternalPollVoteDetails(Identity); } + } + + public static MeetingElectionVote FromBasic(BasicInternalPollVote basic) { return new MeetingElectionVote(basic); } - static public MeetingElectionVote FromIdentity (int internalPollVoteId) + public static MeetingElectionVote FromIdentity(int internalPollVoteId) { return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollVote(internalPollVoteId)); } - static public MeetingElectionVote FromVerificationCode (string verificationCode) + public static MeetingElectionVote FromVerificationCode(string verificationCode) { return FromBasic(SwarmDb.GetDatabaseForReading().GetInternalPollVote(verificationCode)); } - static public MeetingElectionVote Create (MeetingElection poll, Geography voteGeography) + public static MeetingElectionVote Create(MeetingElection poll, Geography voteGeography) { return - FromIdentity(SwarmDb.GetDatabaseForWriting().CreateInternalPollVote(poll.Identity, voteGeography.Identity, - Authentication. - CreateRandomPassword(12))); + FromIdentity(SwarmDb.GetDatabaseForWriting() + .CreateInternalPollVote(poll.Identity, voteGeography.Identity, + Authentication. + CreateRandomPassword(12))); } - public void AddDetail (int position, MeetingElectionCandidate candidate) + public void AddDetail(int position, MeetingElectionCandidate candidate) { - SwarmDb.GetDatabaseForWriting().CreateInternalPollVoteDetail(this.Identity, candidate.Identity, position); + SwarmDb.GetDatabaseForWriting().CreateInternalPollVoteDetail(Identity, candidate.Identity, position); } public void Clear() { - SwarmDb.GetDatabaseForWriting().ClearInternalPollVote(this.Identity); - } - - public int[] SelectedCandidateIdsInOrder - { - get { return SwarmDb.GetDatabaseForReading().GetInternalPollVoteDetails(this.Identity); } + SwarmDb.GetDatabaseForWriting().ClearInternalPollVote(Identity); } /* diff --git a/Logic/Governance/MeetingElectionVoter.cs b/Logic/Governance/MeetingElectionVoter.cs index 3df0b37b..b2a2b29c 100644 --- a/Logic/Governance/MeetingElectionVoter.cs +++ b/Logic/Governance/MeetingElectionVoter.cs @@ -3,24 +3,16 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class MeetingElectionVoter: BasicInternalPollVoter + public class MeetingElectionVoter : BasicInternalPollVoter { - private MeetingElectionVoter (BasicInternalPollVoter basic): base (basic) + private MeetingElectionVoter(BasicInternalPollVoter basic) : base(basic) { // empty ctor } - public static MeetingElectionVoter FromBasic (BasicInternalPollVoter basic) - { - return new MeetingElectionVoter(basic); - } - public Person Person { - get - { - return Person.FromIdentity(base.PersonId); - } + get { return Person.FromIdentity(base.PersonId); } } public MeetingElection Poll @@ -30,10 +22,12 @@ namespace Swarmops.Logic.Governance public InternalPollVoterStatus VoterStatus { - get - { - return base.Open ? InternalPollVoterStatus.CanVote : InternalPollVoterStatus.HasAlreadyVoted; - } + get { return base.Open ? InternalPollVoterStatus.CanVote : InternalPollVoterStatus.HasAlreadyVoted; } + } + + public static MeetingElectionVoter FromBasic(BasicInternalPollVoter basic) + { + return new MeetingElectionVoter(basic); } } } \ No newline at end of file diff --git a/Logic/Governance/MeetingElectionVoters.cs b/Logic/Governance/MeetingElectionVoters.cs index b3e00335..243995db 100644 --- a/Logic/Governance/MeetingElectionVoters.cs +++ b/Logic/Governance/MeetingElectionVoters.cs @@ -4,11 +4,11 @@ using Swarmops.Database; namespace Swarmops.Logic.Governance { - public class MeetingElectionVoters: List + public class MeetingElectionVoters : List { - static public MeetingElectionVoters FromArray(BasicInternalPollVoter[] basicArray) + public static MeetingElectionVoters FromArray(BasicInternalPollVoter[] basicArray) { - var result = new MeetingElectionVoters { Capacity = basicArray.Length * 11 / 10 }; + MeetingElectionVoters result = new MeetingElectionVoters {Capacity = basicArray.Length*11/10}; foreach (BasicInternalPollVoter basic in basicArray) { @@ -18,27 +18,23 @@ namespace Swarmops.Logic.Governance return result; } - static public MeetingElectionVoters ForPoll(MeetingElection poll, bool includeClosed) + public static MeetingElectionVoters ForPoll(MeetingElection poll, bool includeClosed) { if (includeClosed) { return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll)); } - else - { - return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll, DatabaseCondition.OpenTrue)); - } + return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVoters(poll, DatabaseCondition.OpenTrue)); } - static public MeetingElectionVoters ForPoll(MeetingElection poll) + public static MeetingElectionVoters ForPoll(MeetingElection poll) { return ForPoll(poll, false); } - static public MeetingElectionVoters ForPollClosed (MeetingElection poll) + public static MeetingElectionVoters ForPollClosed(MeetingElection poll) { 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 16f50496..12273113 100644 --- a/Logic/Governance/MeetingElectionVotes.cs +++ b/Logic/Governance/MeetingElectionVotes.cs @@ -4,9 +4,9 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Governance { - public class MeetingElectionVotes: PluralBase + public class MeetingElectionVotes : PluralBase { - static public MeetingElectionVotes ForInternalPoll (MeetingElection poll) + public static MeetingElectionVotes ForInternalPoll(MeetingElection poll) { return FromArray(SwarmDb.GetDatabaseForReading().GetInternalPollVotes(poll)); } diff --git a/Logic/Governance/MeetingElections.cs b/Logic/Governance/MeetingElections.cs index aff64cb2..fb5915c6 100644 --- a/Logic/Governance/MeetingElections.cs +++ b/Logic/Governance/MeetingElections.cs @@ -5,14 +5,14 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Governance { - public class MeetingElections: PluralBase + public class MeetingElections : PluralBase { - public static MeetingElections ForOrganization (Organization organization) + public static MeetingElections ForOrganization(Organization 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)); } diff --git a/Logic/Governance/Motion.cs b/Logic/Governance/Motion.cs index 781ece75..2d3179c8 100644 --- a/Logic/Governance/Motion.cs +++ b/Logic/Governance/Motion.cs @@ -4,50 +4,51 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class Motion: BasicMotion + public class Motion : BasicMotion { - private Motion (BasicMotion basic): base (basic) + private Motion(BasicMotion basic) : base(basic) { // empty ctor } - public static Motion FromBasic (BasicMotion basic) - { - return new Motion(basic); - } - - public static Motion FromIdentity (int motionId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMotion(motionId)); - } - - public static Motion Create (Meeting meeting, Person submittingPerson, Person creatingPerson, string title, string text, string decisionPoints) - { - return - Motion.FromIdentity(SwarmDb.GetDatabaseForWriting().CreateMotion(meeting.Identity, submittingPerson.Identity, creatingPerson.Identity, title, text, decisionPoints)); - } - public MotionAmendments Amendments { - get - { - return MotionAmendments.ForMotion(this); - } - } - - public MotionAmendment AddAmendment (string title, string text, string decisionPoint, Person submittingPerson, Person createdByPerson) - { - return MotionAmendment.Create(this, title, text, decisionPoint, submittingPerson, createdByPerson); + get { return MotionAmendments.ForMotion(this); } } public Meeting Meeting { - get { return Meeting.FromIdentity(this.MeetingId); } + get { return Meeting.FromIdentity(MeetingId); } } public Person Submitter { - get { return Person.FromIdentity(this.SubmittedByPersonId); } + get { return Person.FromIdentity(SubmittedByPersonId); } + } + + public static Motion FromBasic(BasicMotion basic) + { + return new Motion(basic); + } + + public static Motion FromIdentity(int motionId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetMotion(motionId)); + } + + 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, + decisionPoints)); + } + + public MotionAmendment AddAmendment(string title, string text, string decisionPoint, Person submittingPerson, + Person 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 bf1bdc07..41d21ba3 100644 --- a/Logic/Governance/MotionAmendment.cs +++ b/Logic/Governance/MotionAmendment.cs @@ -4,42 +4,47 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Governance { - public class MotionAmendment: BasicMotionAmendment + public class MotionAmendment : BasicMotionAmendment { - private MotionAmendment (BasicMotionAmendment basic): - base (basic) + private MotionAmendment(BasicMotionAmendment basic) : + base(basic) { // empty ctor } - public static MotionAmendment FromBasic (BasicMotionAmendment basic) - { - return new MotionAmendment(basic); - } - - public static MotionAmendment FromIdentity (int motionAmendmentId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetMotionAmendment(motionAmendmentId)); - } - - 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, text, decisionPoint)); - } - public Motion Motion { - get { return Motion.FromIdentity(this.MotionId); } + get { return Motion.FromIdentity(MotionId); } } public string Designation { - get { return this.Motion.SequenceNumber + "-" + ((char) ((int) ('A') + this.SequenceNumber - 1)); } // HACK: only works till Z, need something that works beyond + get { return Motion.SequenceNumber + "-" + ((char) ('A' + SequenceNumber - 1)); } + // HACK: only works till Z, need something that works beyond } public Person Submitter { - get { return Person.FromIdentity(this.SubmittedByPersonId); } + get { return Person.FromIdentity(SubmittedByPersonId); } + } + + public static MotionAmendment FromBasic(BasicMotionAmendment basic) + { + return new MotionAmendment(basic); + } + + public static MotionAmendment FromIdentity(int motionAmendmentId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetMotionAmendment(motionAmendmentId)); + } + + 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, + text, decisionPoint)); } } } \ No newline at end of file diff --git a/Logic/Governance/MotionAmendments.cs b/Logic/Governance/MotionAmendments.cs index 863bdd95..737c72d0 100644 --- a/Logic/Governance/MotionAmendments.cs +++ b/Logic/Governance/MotionAmendments.cs @@ -4,14 +4,14 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Governance { - public class MotionAmendments: PluralBase + public class MotionAmendments : PluralBase { - static public MotionAmendments ForMotion (Motion motion) + public static MotionAmendments ForMotion(Motion motion) { - return MotionAmendments.FromArray(SwarmDb.GetDatabaseForReading().GetMotionAmendments(motion)); + return FromArray(SwarmDb.GetDatabaseForReading().GetMotionAmendments(motion)); } - static public MotionAmendments ForMeeting (Meeting meeting) + public static MotionAmendments ForMeeting(Meeting meeting) { return FromArray(SwarmDb.GetDatabaseForReading().GetMotionAmendmentsForMeeting(meeting.Identity)); } diff --git a/Logic/Governance/Motions.cs b/Logic/Governance/Motions.cs index a957ba0f..f328656b 100644 --- a/Logic/Governance/Motions.cs +++ b/Logic/Governance/Motions.cs @@ -4,11 +4,11 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Governance { - public class Motions: PluralBase + public class Motions : PluralBase { - static public Motions ForMeeting (Meeting meeting) + public static Motions ForMeeting(Meeting meeting) { - return Motions.FromArray(SwarmDb.GetDatabaseForReading().GetMotions(meeting)); + return FromArray(SwarmDb.GetDatabaseForReading().GetMotions(meeting)); } } } \ No newline at end of file diff --git a/Logic/Interfaces/TreeNode.cs b/Logic/Interfaces/TreeNode.cs index ae189c56..bc19540c 100644 --- a/Logic/Interfaces/TreeNode.cs +++ b/Logic/Interfaces/TreeNode.cs @@ -26,7 +26,5 @@ namespace Swarmops.Logic.Interfaces ITreeNodeObject ParentObject { get; } List ChildObjects { get; } - } - } \ No newline at end of file diff --git a/Logic/Media/MediaCategories.cs b/Logic/Media/MediaCategories.cs index 727b88f7..fa13d501 100644 --- a/Logic/Media/MediaCategories.cs +++ b/Logic/Media/MediaCategories.cs @@ -9,25 +9,25 @@ 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) { - var result = new MediaCategories(); + 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() diff --git a/Logic/Media/MediaCategory.cs b/Logic/Media/MediaCategory.cs index 3b91f7b8..98cbe31b 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)); } - 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 85f6a26d..8ab6e4e9 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) { - var result = new MediaEntries(); + 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,21 +58,22 @@ namespace Swarmops.Logic.Media return SwarmDb.GetDatabaseForReading().GetMediaKeywordTable(); } - public static MediaEntries FromKeywordsSimplified (string[] keywords) + public static MediaEntries FromKeywordsSimplified(string[] keywords) { - var keywordIds = new List(); + 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())); + return + 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 b3d0b8f1..894c299e 100644 --- a/Logic/Media/MediaEntry.cs +++ b/Logic/Media/MediaEntry.cs @@ -6,30 +6,27 @@ 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, - DateTime dateTime) + 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) { return true; // an object was created } - else - { - return false; - } + return false; } } } \ No newline at end of file diff --git a/Logic/Media/Reporter.cs b/Logic/Media/Reporter.cs index f41a1c5e..2c6a2a2d 100644 --- a/Logic/Media/Reporter.cs +++ b/Logic/Media/Reporter.cs @@ -8,11 +8,36 @@ namespace Swarmops.Logic.Media { private MediaCategories mediaCategories; - private Reporter (BasicReporter original) : base (original) + private Reporter(BasicReporter original) : base(original) { } - public static Reporter Create (string name, string email, string[] categories) + public MediaCategories MediaCategories + { + get + { + if (MediaCategoryIds == null) + { + MediaCategoryIds = SwarmDb.GetDatabaseForReading().GetReporterMediaCategories(Identity); + } + + if (this.mediaCategories == null) + { + if (MediaCategoryIds.Length > 0) + { + this.mediaCategories = MediaCategories.FromIdentities(MediaCategoryIds); + } + else + { + this.mediaCategories = new MediaCategories(); + } + } + + return this.mediaCategories; + } + } + + public static Reporter Create(string name, string email, string[] categories) { Reporter reporter = FromIdentity(SwarmDb.GetDatabaseForWriting().CreateReporter(name, email)); @@ -27,46 +52,20 @@ namespace Swarmops.Logic.Media public void Delete() { - SwarmDb.GetDatabaseForWriting().DeleteReporter(this.Identity); + SwarmDb.GetDatabaseForWriting().DeleteReporter(Identity); // After this operation, the object is no longer valid. } - public MediaCategories MediaCategories + public static Reporter FromBasic(BasicReporter basic) { - get - { - if (MediaCategoryIds == null) - { - MediaCategoryIds = SwarmDb.GetDatabaseForReading().GetReporterMediaCategories (Identity); - } - - if (this.mediaCategories == null) - { - if (MediaCategoryIds.Length > 0) - { - this.mediaCategories = MediaCategories.FromIdentities(MediaCategoryIds); - } - else - { - this.mediaCategories = new MediaCategories(); - } - - } - - return this.mediaCategories; - } + return new Reporter(basic); } - public static Reporter FromBasic (BasicReporter basic) + public static Reporter FromIdentity(int identity) { - return new Reporter (basic); - } - - public static Reporter FromIdentity (int identity) - { - return Reporter.FromBasic(SwarmDb.GetDatabaseForReading().GetReporter(identity)); + return FromBasic(SwarmDb.GetDatabaseForReading().GetReporter(identity)); } #region IComparable Members @@ -75,7 +74,7 @@ namespace Swarmops.Logic.Media { Reporter otherReporter = (Reporter) obj; - return this.Name.CompareTo(otherReporter.Name); + return Name.CompareTo(otherReporter.Name); } #endregion diff --git a/Logic/Media/Reporters.cs b/Logic/Media/Reporters.cs index d25ea7cd..d7df2b72 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) { - var result = new Reporters(); + 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 aa588e72..be02e310 100644 --- a/Logic/Security/Accesses.cs +++ b/Logic/Security/Accesses.cs @@ -4,7 +4,12 @@ namespace Swarmops.Logic.Security { public class Access { - public Access (AccessAspect aspect, AccessType type) + public readonly AccessAspect Aspect; + public readonly Geography Geography; + public readonly Organization Organization; + public readonly AccessType Type; + + public Access(AccessAspect aspect, AccessType type) { this.Aspect = aspect; this.Type = type; @@ -24,31 +29,30 @@ namespace Swarmops.Logic.Security this.Aspect = aspect; this.Type = type; } - - public readonly Organization Organization; - public readonly Geography Geography; - public readonly AccessAspect Aspect; - public readonly AccessType Type; } public enum AccessAspect { Unknown = 0, + /// - /// Access to underlying ledgers + /// Access to underlying ledgers /// Bookkeeping, + /// - /// Access to regular accounting + /// Access to regular accounting /// Financials, + /// - /// Access to personal details about people in org + /// Access to personal details about people in org /// PersonData, + /// - /// Access to change organization's fundamental operating parameters + /// Access to change organization's fundamental operating parameters /// Administration } @@ -59,4 +63,4 @@ namespace Swarmops.Logic.Security Read, Write } -} +} \ No newline at end of file diff --git a/Logic/Security/ActivityEnum.cs b/Logic/Security/ActivityEnum.cs index 6ff9db1d..4cc8fe4e 100644 --- a/Logic/Security/ActivityEnum.cs +++ b/Logic/Security/ActivityEnum.cs @@ -3,20 +3,23 @@ namespace Swarmops.Logic.Security public enum Activity { /// - /// Undefined. + /// Undefined. /// Undefined = 0, + /// - /// Add or remove roles and responsibilities + /// Add or remove roles and responsibilities /// AddRemoveRolesResponsibilities, + /// - /// Add or remove members or memberships + /// Add or remove members or memberships /// AddRemoveMembers, + /// - /// View and Edit existing members + /// View and Edit existing members /// ViewEditMembers } -} +} \ No newline at end of file diff --git a/Logic/Security/Authentication.cs b/Logic/Security/Authentication.cs index bdf43e3b..8eea9767 100644 --- a/Logic/Security/Authentication.cs +++ b/Logic/Security/Authentication.cs @@ -12,35 +12,17 @@ namespace Swarmops.Logic.Security { private const int EmailVerificationTicketLength = 8; - public class VerificationTicketTooOldException : Exception - { - internal VerificationTicketTooOldException (string msg) : base(msg) - { - } - } - - public class VerificationTicketWrongException : Exception - { - internal VerificationTicketWrongException (string msg) : base(msg) - { - } - } - - public class VerificationTicketLengthException : Exception - { - internal VerificationTicketLengthException (string msg) : base(msg) - { - } - } - /// - /// Returns one authenticated user from login token and password. + /// Returns one authenticated user from login token and password. /// /// The login token provided. /// The password provided. /// Exactly one authenticated user, if successful. - /// This function will throw an UnauthorizedAccessException if the user cannot be authenticated using the supplied credentials. - public static Person Authenticate (string loginToken, string password) + /// + /// This function will throw an UnauthorizedAccessException if the user + /// cannot be authenticated using the supplied credentials. + /// + public static Person Authenticate(string loginToken, string password) { // Get the list of people that match the login token. @@ -129,11 +111,11 @@ namespace Swarmops.Logic.Security } - public static string CreateRandomPassword (int length) + public static string CreateRandomPassword(int length) { string allowedChars = "ABCDEFHJKMNPQRTUVWXYZ23456789"; - var chars = new char[length]; - var randomizer = new Random(); + char[] chars = new char[length]; + Random randomizer = new Random(); for (int index = 0; index < length; index++) { @@ -144,12 +126,12 @@ namespace Swarmops.Logic.Security } /// - /// Generates a SHA-1 password hash, salted with the person's unique id. + /// Generates a SHA-1 password hash, salted with the person's unique id. /// /// 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) { @@ -164,9 +146,10 @@ namespace Swarmops.Logic.Security 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 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; @@ -185,12 +168,12 @@ namespace Swarmops.Logic.Security } /// - /// Generates password hashes for legacy passwords in system (that are no longer generated). + /// Generates password hashes for legacy passwords in system (that are no longer generated). /// /// 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 @@ -202,21 +185,20 @@ namespace Swarmops.Logic.Security MD5.Hash(password + person.PersonalNumber + "Pirate") }; } - else - return new[] - { - SHA1.Hash(password + person.Identity + "Pirate") - }; + return new[] + { + SHA1.Hash(password + person.Identity + "Pirate") + }; #pragma warning restore 618 } /// - /// Get all person IDs that match a certain login token. + /// Get all person IDs that match a certain login token. /// /// 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(); @@ -249,8 +231,8 @@ namespace Swarmops.Logic.Security if (cleanedNumber.Length == 10) { int[] personIds = database.GetObjectsByOptionalData(ObjectType.Person, - ObjectOptionalDataType.PersonalNumber, - cleanedNumber); + ObjectOptionalDataType.PersonalNumber, + cleanedNumber); foreach (int personId in personIds) { @@ -273,7 +255,7 @@ namespace Swarmops.Logic.Security 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); @@ -281,7 +263,8 @@ namespace Swarmops.Logic.Security People candidatePeople = null; if (personID == 0) { - BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern(eMail.ToLower().Replace("%", "").Trim()); + BasicPerson[] 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. @@ -295,7 +278,7 @@ namespace Swarmops.Logic.Security } else { - candidatePeople = People.FromIdentities(new int[] {personID}); + candidatePeople = People.FromIdentities(new[] {personID}); if (candidatePeople.Count > 0) { authenticatedUser = candidatePeople[0]; @@ -322,7 +305,7 @@ namespace Swarmops.Logic.Security if (candidatePeople.Count == 1) { App_LocalResources.Authentication.Culture = - System.Globalization.CultureInfo.GetCultureInfo(authenticatedUser.PreferredCulture); + CultureInfo.GetCultureInfo(authenticatedUser.PreferredCulture); mailbody = App_LocalResources.Authentication.RequestNewPassword_Mail_Preamble; mailbody += App_LocalResources.Authentication.RequestNewPassword_Mail_ClickOneLink; @@ -341,7 +324,7 @@ namespace Swarmops.Logic.Security } links += "\r\n\r\n"; - links += "#" + p.PersonId.ToString(); + links += "#" + p.PersonId; links += " [Member of:"; Memberships msList = p.GetMemberships(); foreach (Membership ms in msList) @@ -369,7 +352,7 @@ namespace Swarmops.Logic.Security } - public static void RequestMembershipConfirmation (Person p, string URL) + public static void RequestMembershipConfirmation(Person p, string URL) { string passwordTicket = CreateRandomPassword(EmailVerificationTicketLength); @@ -379,7 +362,7 @@ namespace Swarmops.Logic.Security string mailbody = ""; App_LocalResources.Authentication.Culture = - System.Globalization.CultureInfo.GetCultureInfo(p.PreferredCulture); + CultureInfo.GetCultureInfo(p.PreferredCulture); mailbody = App_LocalResources.Authentication.MembershipConf_Mail_Preamble; mailbody += "\r\n" + String.Format(URL, p.PersonId, passwordTicket); @@ -389,29 +372,29 @@ namespace Swarmops.Logic.Security 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.ToString() + " characters."); + EmailVerificationTicketLength + " characters."); } string storedTicket = pers.ResetPasswordTicket; - string[] storedParts = storedTicket.Split(new char[] {';'}); + string[] storedParts = storedTicket.Split(new[] {';'}); if (storedParts.Length < 2) { throw new VerificationTicketWrongException("No such code exists."); } DateTime createdTime = DateTime.MinValue; DateTime.TryParseExact(storedParts[1].Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, - DateTimeStyles.None, out createdTime); + DateTimeStyles.None, out createdTime); if (DateTime.Now.Subtract(createdTime).TotalHours > 10) { throw new VerificationTicketTooOldException( "Verification code too old, it must be used within 10 hours."); } - else if (SHA1.Hash(token) == storedParts[0]) + if (SHA1.Hash(token) == storedParts[0]) { // Yes, proceed to next step } @@ -421,7 +404,7 @@ namespace Swarmops.Logic.Security } } - public static void SetPasswordByEmailVerificationTicket (Person pers, string token, string newPassword) + public static void SetPasswordByEmailVerificationTicket(Person pers, string token, string newPassword) { ValidateEmailVerificationTicket(pers, token); @@ -429,30 +412,27 @@ namespace Swarmops.Logic.Security pers.ResetPasswordTicket = ""; } - internal static bool ValidatePassword (Person person, string oldpassword) + internal static bool ValidatePassword(Person person, string oldpassword) { if (CheckPassword(person, oldpassword)) { return true; } - else + // If the most recent password hash mechanism fails, try legacy hashes + + string[] legacyHashes = GenerateLegacyPasswordHashes(person, oldpassword); + + foreach (string legacyHash in legacyHashes) { - // If the most recent password hash mechanism fails, try legacy hashes - - string[] legacyHashes = GenerateLegacyPasswordHashes(person, oldpassword); - - foreach (string legacyHash in legacyHashes) + if (legacyHash == person.PasswordHash) { - if (legacyHash == person.PasswordHash) - { - return true; - } + return true; } } 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); @@ -461,7 +441,8 @@ namespace Swarmops.Logic.Security bool personIsActivist = false; if (personID == 0) { - BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleFromEmailPattern(eMail.ToLower().Replace("%", "").Trim()); + BasicPerson[] 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. @@ -475,7 +456,7 @@ namespace Swarmops.Logic.Security } else { - candidatePeople = People.FromIdentities(new int[] {personID}); + candidatePeople = People.FromIdentities(new[] {personID}); if (candidatePeople.Count > 0) { authenticatedUser = candidatePeople[0]; @@ -490,7 +471,7 @@ namespace Swarmops.Logic.Security //TODO: Localize string mailbody = ""; - App_LocalResources.Authentication.Culture = System.Globalization.CultureInfo.InvariantCulture; + App_LocalResources.Authentication.Culture = CultureInfo.InvariantCulture; if (candidatePeople.Count == 1 && candidatePeople[0].IsActivist) @@ -505,7 +486,7 @@ namespace Swarmops.Logic.Security string encodedPasswordTicket = SHA1.Hash(p.Identity.ToString(CultureInfo.InvariantCulture)).Replace(" ", "").Substring(0, 4) + - p.Identity.ToString(); + p.Identity; mailbody = App_LocalResources.Authentication.RequestActivistSignoff_Mail_Preamble; mailbody += App_LocalResources.Authentication.RequestActivistSignoff_Mail_ClickOneLink; @@ -530,9 +511,9 @@ namespace Swarmops.Logic.Security string encodedPasswordTicket = GenerateNewPasswordHash(p, p.Identity.ToString()).Replace(" ", "").Substring(0, 4) + - p.Identity.ToString(); + p.Identity; links += "\r\n\r\n"; - links += "#" + p.PersonId.ToString(); + links += "#" + p.PersonId; links += "\r\n" + String.Format(URL, encodedPasswordTicket); } @@ -548,20 +529,42 @@ namespace Swarmops.Logic.Security if (personIsActivist) { authenticatedUser.SendNotice(App_LocalResources.Authentication.RequestActivistSignoff_Mail_Subject, - mailbody, 1); + 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) + p.Identity.ToString(); + SHA1.Hash(p.Identity.ToString(CultureInfo.InvariantCulture)).Replace(" ", "").Substring(0, 4) + + p.Identity; if (code != encodedPasswordTicket) { throw new VerificationTicketWrongException("No such code exists."); } } + + public class VerificationTicketLengthException : Exception + { + internal VerificationTicketLengthException(string msg) : base(msg) + { + } + } + + public class VerificationTicketTooOldException : Exception + { + internal VerificationTicketTooOldException(string msg) : base(msg) + { + } + } + + public class VerificationTicketWrongException : Exception + { + internal VerificationTicketWrongException(string msg) : base(msg) + { + } + } } } \ No newline at end of file diff --git a/Logic/Security/Authority.cs b/Logic/Security/Authority.cs index 840946ac..9ca01f49 100644 --- a/Logic/Security/Authority.cs +++ b/Logic/Security/Authority.cs @@ -12,32 +12,32 @@ namespace Swarmops.Logic.Security { #region Construction and Creation - private Authority () + private Authority() : base(0, null, null, null) { } - private Authority (BasicAuthority basic) + 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); } #endregion - public Organizations GetOrganizations (RoleType[] forRoles) + public Organizations GetOrganizations(RoleType[] forRoles) { if (HasRoleType(RoleType.SystemAdmin)) { return Organizations.GetAll(); } - var orgIdentities = new List(); + List orgIdentities = new List(); foreach (BasicPersonRole role in OrganizationPersonRoles) { @@ -55,10 +55,10 @@ namespace Swarmops.Logic.Security } - 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); if (filteredList.Count == 0) @@ -70,39 +70,38 @@ namespace Swarmops.Logic.Security } - public Geographies GetGeographiesForOrganization (Organization organization) + public Geographies GetGeographiesForOrganization(Organization organization) { return 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, roleTypes)); + Geographies.FromArray(Authorization.GetNodesInAuthorityForOrganization(this, organization.Identity, + roleTypes)); } - public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, Authorization.Flag flags) + public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + Authorization.Flag flags) { return HasLocalRoleAtOrganizationGeography(organization, geography, RoleTypes.AllLocalRoleTypes, flags); } - - public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, - RoleType roleType, Authorization.Flag flags) + public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + RoleType roleType, Authorization.Flag flags) { return HasLocalRoleAtOrganizationGeography(organization, geography, - new RoleType[] { roleType }, flags); + new[] {roleType}, flags); } - - public bool HasLocalRoleAtOrganizationGeography (Organization organization, Geography geography, - RoleType[] roleTypes, Authorization.Flag flags) + public bool HasLocalRoleAtOrganizationGeography(Organization organization, Geography geography, + RoleType[] roleTypes, Authorization.Flag flags) { - if (organization != null && organization.Identity == Organization.SandboxIdentity) { return true; // UGLY UGLY HACK @@ -181,24 +180,23 @@ 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); } - 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[] { 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) { if ((flags & Authorization.Flag.AnyOrganization) != 0) return true; - else - return false; + return false; } if (organization != null && organization.Identity == Organization.SandboxIdentity) @@ -235,40 +233,42 @@ namespace Swarmops.Logic.Security } - public bool HasRoleType (RoleType roleType) + public bool HasRoleType(RoleType roleType) { - return HasAnyRoleType(new RoleType[] { roleType }); + return HasAnyRoleType(new[] {roleType}); } - public bool HasAnyRoleType (RoleType[] roleTypes) + public bool HasAnyRoleType(RoleType[] roleTypes) { foreach (RoleType r in roleTypes) { - foreach (BasicPersonRole r2 in this.LocalPersonRoles) + foreach (BasicPersonRole r2 in LocalPersonRoles) if (r2.Type == r) return true; - foreach (BasicPersonRole r2 in this.OrganizationPersonRoles) + foreach (BasicPersonRole r2 in OrganizationPersonRoles) if (r2.Type == r) return true; - foreach (BasicPersonRole r2 in this.SystemPersonRoles) + foreach (BasicPersonRole r2 in SystemPersonRoles) if (r2.Type == r) return true; } return false; } - public bool CanEditSystemRoles () + public bool CanEditSystemRoles() { - return HasPermission(Permission.CanEditSystemRoles, -1, -1, Authorization.Flag.ExactGeography | Authorization.Flag.ExactOrganization); + 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); } - public bool HasAnyPermission (Permission perm) + public bool HasAnyPermission(Permission perm) { - return Authorization.CheckAuthorization(new PermissionSet(perm), -1, -1, this, Authorization.Flag.AnyGeographyAnyOrganization); + return Authorization.CheckAuthorization(new PermissionSet(perm), -1, -1, this, + Authorization.Flag.AnyGeographyAnyOrganization); } /* -- unused, apparently @@ -277,24 +277,24 @@ 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, geographyId, this, flags); + 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); } - 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); } - - public Organizations OrganisationsWithPermission (Permission perm, RoleType[] roles) + public Organizations OrganisationsWithPermission(Permission perm, RoleType[] roles) { Organizations orgList = GetOrganizations(roles); Organizations retList = new Organizations(); diff --git a/Logic/Security/Authorization.cs b/Logic/Security/Authorization.cs index 2030d955..1c4af1bb 100644 --- a/Logic/Security/Authorization.cs +++ b/Logic/Security/Authorization.cs @@ -16,49 +16,71 @@ namespace Swarmops.Logic.Security public enum Flag { NotSpecified = 0, + /// - /// Default equals NotSpecified, and means that Inheritance paths will be checked + /// Default equals NotSpecified, and means that Inheritance paths will be checked /// Default = 0, + /// - /// AnyGeography means that Geograpy of found role is not checked. Use to find PersonRole with permission, regardless of type and geograpy + /// AnyGeography means that Geograpy of found role is not checked. Use to find PersonRole with permission, regardless + /// of type and geograpy /// AnyGeography = 1 << 0, + /// - /// ExactGeography means that Inheritance paths will NOT be checked, only exact hit is found + /// ExactGeography means that Inheritance paths will NOT be checked, only exact hit is found /// ExactGeography = 1 << 1, + /// - /// AnyGeography means that Organization of found role is not checked. Use to find PersonRole with permission, regardless of type and organisation + /// AnyGeography means that Organization of found role is not checked. Use to find PersonRole with permission, + /// regardless of type and organisation /// AnyOrganization = 1 << 3, + /// - /// ExactOrganization means that Inheritance paths will NOT be checked, only exact hit is found + /// ExactOrganization means that Inheritance paths will NOT be checked, only exact hit is found /// ExactOrganization = 1 << 4, + /// - /// Combined for ease of use + /// Combined for ease of use /// AnyGeographyAnyOrganization = AnyGeography | AnyOrganization, + /// - /// Combined for ease of use + /// Combined for ease of use /// AnyGeographyExactOrganization = AnyGeography | ExactOrganization, + /// - /// Combined for ease of use + /// Combined for ease of use /// ExactGeographyAnyOrganization = ExactGeography | AnyOrganization, + /// - /// Combined for ease of use + /// Combined for ease of use /// ExactGeographyExactOrganization = ExactGeography | ExactOrganization }; - static Dictionary _PermissonsDict - = new Dictionary(); + private static Dictionary _PermissonsDict + = new Dictionary(); - static Dictionary> _PermissonsPerRoleTypeDict - = new Dictionary>(); + private static Dictionary> _PermissonsPerRoleTypeDict + = new Dictionary>(); + + public static Boolean flagReload = true; + + public static DateTime lastReload = DateTime.Now; + + private static readonly object reloadLock = new object(); + + static Authorization() + { + InitializeStaticData(); + } private static Dictionary PermissonsDict { @@ -66,12 +88,49 @@ namespace Swarmops.Logic.Security { if (flagReload) InitializeStaticData(); - return Authorization._PermissonsDict; + return _PermissonsDict; } - set { Authorization._PermissonsDict = value; } + set { _PermissonsDict = value; } } - public static bool RoleTypeHasPermission (RoleType r, Permission p) + /// + /// List of the roles which make a member visible outwards. + /// + public static RoleType[] VisibleRoles + { + get + { + return new[] + { + RoleType.LocalLead, RoleType.LocalDeputy, RoleType.OrganizationChairman, + RoleType.OrganizationSecretary, RoleType.OrganizationTreasurer, + RoleType.OrganizationVice1, RoleType.OrganizationVice2, + RoleType.OrganizationBoardMember, RoleType.OrganizationBoardDeputy + }; + } + } + + /// + /// Like VisibleRoles, but in dictionary form. + /// + public static Dictionary VisibleRolesDictionary + { + get + { + Dictionary result = new Dictionary(); + + RoleType[] roleTypes = VisibleRoles; + + foreach (RoleType roleType in roleTypes) + { + result[roleType] = true; + } + + return result; + } + } + + public static bool RoleTypeHasPermission(RoleType r, Permission p) { if (flagReload) InitializeStaticData(); @@ -86,12 +145,12 @@ namespace Swarmops.Logic.Security } - public static RoleType[] RoleTypesWithPermission (Permission p) + public static RoleType[] RoleTypesWithPermission(Permission p) { 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) @@ -105,19 +164,7 @@ namespace Swarmops.Logic.Security } - - static Authorization () - { - InitializeStaticData(); - } - - static public Boolean flagReload = true; - - static public DateTime lastReload = DateTime.Now; - - static object reloadLock = new object(); - - public static void InitializeStaticData () + public static void InitializeStaticData() { lock (reloadLock) { @@ -146,7 +193,7 @@ namespace Swarmops.Logic.Security tempDict[perm].Add(role); } Dictionary newPermissonsDict - = new Dictionary(); + = new Dictionary(); foreach (Permission p in tempDict.Keys) { RoleType[] roles = tempDict[p].ToArray(); @@ -159,35 +206,31 @@ namespace Swarmops.Logic.Security } - internal class FoundItException : Exception - { - } - - - public static Authority GetPersonAuthority (int personId) + public static Authority GetPersonAuthority(int 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); } - public static BasicGeography[] GetNodesInAuthorityForOrganization (BasicAuthority authority, int organizationId, RoleType[] roleTypes) + public static BasicGeography[] GetNodesInAuthorityForOrganization(BasicAuthority authority, int organizationId, + RoleType[] roleTypes) { Organizations organizationLine = Organization.FromIdentity(organizationId).GetLine(); // Build lookup tables - var orgLookup = new Dictionary(); + Dictionary orgLookup = new Dictionary(); foreach (BasicOrganization organization in organizationLine) { orgLookup[organization.OrganizationId] = organization; } - var roleLookup = new Dictionary(); + Dictionary roleLookup = new Dictionary(); foreach (RoleType roleType in roleTypes) { roleLookup[roleType] = true; @@ -195,7 +238,7 @@ namespace Swarmops.Logic.Security // Create list - var result = new List(); + List result = new List(); if (authority.AllPersonRoles.Length > 0) { @@ -235,42 +278,55 @@ namespace Swarmops.Logic.Security /// - /// Checks for authorization for a specific activity. + /// Checks for authorization for a specific activity. /// /// The permissions to allow or disallow. /// The organization the activity is applied to. /// 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, int checkedPersonId, Flag flags) + public static bool CheckAuthorization(PermissionSet permissionsNeeded, int organizationId, int geoNodeId, + int checkedPersonId, Flag flags) { - return CheckAuthorization(permissionsNeeded, organizationId, geoNodeId, GetPersonAuthority(checkedPersonId), flags); + return CheckAuthorization(permissionsNeeded, organizationId, geoNodeId, GetPersonAuthority(checkedPersonId), + flags); } /// - /// Checks for authorization for a specific activity. + /// Checks for authorization for a specific activity. /// /// The permissions to allow or disallow. /// The organization the activity is applied to. /// 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, Authority authority, Flag flags) + public static bool CheckAuthorization(PermissionSet permissionsNeeded, int organizationId, int geoNodeId, + Authority authority, Flag flags) { if (permissionsNeeded == null) return false; Geography currentGeo = null; if (geoNodeId > 0) { - try { currentGeo = Geography.FromIdentity(geoNodeId); } - catch { } + try + { + currentGeo = Geography.FromIdentity(geoNodeId); + } + catch + { + } } Organization currentOrg = null; if (organizationId > 0) { - try { currentOrg = Organization.FromIdentity(organizationId); } - catch { } + try + { + currentOrg = Organization.FromIdentity(organizationId); + } + catch + { + } } @@ -282,48 +338,56 @@ namespace Swarmops.Logic.Security if (perm.geographyId > 0) { - try { innerCurrentGeo = Geography.FromIdentity(perm.geographyId); } - catch { } + try + { + innerCurrentGeo = Geography.FromIdentity(perm.geographyId); + } + catch + { + } } else innerCurrentGeo = currentGeo; if (perm.orgId > 0) { - try { innerCurrentOrg = Organization.FromIdentity(perm.orgId); } - catch { } + try + { + innerCurrentOrg = Organization.FromIdentity(perm.orgId); + } + catch + { + } } else innerCurrentOrg = currentOrg; - RoleType[] rolesForPerm = new RoleType[] { }; + RoleType[] rolesForPerm = {}; 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, flags); + thisFound = CheckSpecificValidRoles(authority, rolesForPerm, innerCurrentGeo, innerCurrentOrg, + thisFound, flags); if (permissionsNeeded.NeedOne && thisFound == 1) return true; if (permissionsNeeded.NeedAll && thisFound == -1) return false; - } //If Need all and not already returned, no false one was found if (permissionsNeeded.NeedAll) return true; - else - - return false; + return false; } - private static int CheckSpecificValidRoles (Authority authority, RoleType[] roles, - Geography currentGeo, Organization currentOrg, - int thisFound, Flag flags) + private static int CheckSpecificValidRoles(Authority authority, RoleType[] roles, + Geography currentGeo, Organization currentOrg, + int thisFound, Flag flags) { if (authority.HasAnyRoleType(roles)) { @@ -332,14 +396,17 @@ namespace Swarmops.Logic.Security { if (authority.HasRoleType(r) && (Array.IndexOf(RoleTypes.AllLocalRoleTypes, r) > -1)) { - thisFound = authority.HasLocalRoleAtOrganizationGeography(currentOrg, currentGeo, r, flags) ? 1 : thisFound; + thisFound = authority.HasLocalRoleAtOrganizationGeography(currentOrg, currentGeo, r, flags) + ? 1 + : thisFound; } else if (authority.HasRoleType(r) && ((Array.IndexOf(RoleTypes.AllOrganizationalRoleTypes, r) > -1))) { thisFound = authority.HasRoleAtOrganization(currentOrg, r, flags) ? 1 : thisFound; } else if (authority.HasRoleType(r) && ((Array.IndexOf(RoleTypes.AllSystemRoleTypes, r) > -1))) - { //System PersonRole + { + //System PersonRole thisFound = 1; } // break if we found one that gives access @@ -357,8 +424,8 @@ namespace Swarmops.Logic.Security } - public static Memberships FilterMembershipsToMatchAuthority (Memberships memberships, Geography personGeography, - Authority authority) + public static Memberships FilterMembershipsToMatchAuthority(Memberships memberships, Geography personGeography, + Authority authority) { // First: If sysadmin, return the whole list uncensored. @@ -367,7 +434,7 @@ namespace Swarmops.Logic.Security return memberships; } - var clearedMemberships = new Dictionary(); + Dictionary clearedMemberships = new Dictionary(); // foreach (BasicPersonRole role in authority.OrganizationPersonRoles) @@ -380,7 +447,9 @@ namespace Swarmops.Logic.Security bool organizationClear = clearedOrganizations.ContainsKey(membership.OrganizationId); if (organizationClear - && authority.HasPermission(Permission.CanViewMemberships, membership.OrganizationId, membership.Person.GeographyId, Flag.Default)) + && + authority.HasPermission(Permission.CanViewMemberships, membership.OrganizationId, + membership.Person.GeographyId, Flag.Default)) { clearedMemberships[membership.Identity] = membership; } @@ -390,12 +459,15 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.LocalPersonRoles) { - Dictionary clearedGeographies = GeographyCache.GetGeographyHashtable(role.GeographyId); + Dictionary clearedGeographies = + GeographyCache.GetGeographyHashtable(role.GeographyId); Dictionary clearedOrganizations = OrganizationCache.GetOrganizationHashtable(role.OrganizationId); bool geographyClear = clearedGeographies.ContainsKey(personGeography.Identity); - geographyClear = geographyClear && authority.HasPermission(Permission.CanViewMemberships, role.OrganizationId, personGeography.Identity, Flag.Default); + geographyClear = geographyClear && + authority.HasPermission(Permission.CanViewMemberships, role.OrganizationId, + personGeography.Identity, Flag.Default); if (geographyClear) { @@ -414,7 +486,7 @@ namespace Swarmops.Logic.Security // Assemble the array - var result = new Memberships(); + Memberships result = new Memberships(); foreach (Membership membership in clearedMemberships.Values) { @@ -425,14 +497,14 @@ namespace Swarmops.Logic.Security } - public static People FilterPeopleToMatchAuthority (People people, Authority authority) + public static People FilterPeopleToMatchAuthority(People people, Authority authority) { 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. @@ -446,10 +518,11 @@ namespace Swarmops.Logic.Security if (gracePeriod == -1) gracePeriod = Membership.GracePeriod; - Dictionary> membershipTable = databaseRead.GetMembershipsForPeople(people.Identities, gracePeriod); + Dictionary> membershipTable = + databaseRead.GetMembershipsForPeople(people.Identities, gracePeriod); Dictionary geographyTable = databaseRead.GetPeopleGeographies(people.Identities); - var clearedPeople = new Dictionary(); + Dictionary clearedPeople = new Dictionary(); // TODO: Add org admin role, able to see previous members that aren't anonymized yet @@ -469,19 +542,24 @@ namespace Swarmops.Logic.Security foreach (BasicMembership membership in membershipTable[person.Identity]) { if (clearedOrganizations.ContainsKey(membership.OrganizationId) - && authority.HasPermission(Permission.CanSeePeople, membership.OrganizationId, person.GeographyId, Flag.Default)) + && + 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 - && authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default))) + && + authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, + membership.OrganizationId, person.GeographyId, Flag.Default))) { clearedPeople[person.Identity] = person; break; } } } - } /* -- 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; @@ -499,12 +577,13 @@ namespace Swarmops.Logic.Security foreach (BasicPersonRole role in authority.LocalPersonRoles) { - Dictionary clearedGeographies = GeographyCache.GetGeographyHashtable(role.GeographyId); - Dictionary clearedOrganizations = OrganizationCache.GetOrganizationHashtable(role.OrganizationId); + Dictionary clearedGeographies = + GeographyCache.GetGeographyHashtable(role.GeographyId); + Dictionary clearedOrganizations = + 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)) @@ -524,12 +603,16 @@ namespace Swarmops.Logic.Security if (organizationClear > 0 && geographyClear > 0 - && authority.HasPermission(Permission.CanSeePeople, organizationClear, geographyClear, Flag.Default)) + && + authority.HasPermission(Permission.CanSeePeople, organizationClear, geographyClear, + Flag.Default)) { if (membership.Active || (membership.Expires > DateTime.Now.AddDays(-gracePeriod) && membership.Expires.AddDays(1) > membership.DateTerminated - && authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default))) + && + authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, + membership.OrganizationId, person.GeographyId, Flag.Default))) { clearedPeople[person.Identity] = person; break; @@ -542,10 +625,9 @@ namespace Swarmops.Logic.Security } - // End: Assemble an array of the resulting cleared people - var result = new People(); + People result = new People(); foreach (Person clearedPerson in clearedPeople.Values) { @@ -556,10 +638,10 @@ namespace Swarmops.Logic.Security } - public static BasicPerson[] FilterUnlistedPeople (BasicPerson[] people) + public static BasicPerson[] FilterUnlistedPeople(BasicPerson[] people) { - var unlistedTable = new Dictionary(); - var result = new List(); + Dictionary unlistedTable = new Dictionary(); + List result = new List(); // If list is empty, return empty @@ -570,7 +652,8 @@ 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"); + int[] anonymousPersonIds = SwarmDb.GetDatabaseForReading() + .GetObjectsByOptionalData(ObjectType.Person, ObjectOptionalDataType.Anonymous, "1"); foreach (int anonymousPersonId in anonymousPersonIds) { @@ -591,17 +674,17 @@ 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 // changed to 3 different lists, should be more efficient // JL - var uniqueTableName = new Dictionary>(); - var uniqueTablePhone = new Dictionary>(); - var uniqueTableEmail = new Dictionary>(); + Dictionary> uniqueTableName = new Dictionary>(); + Dictionary> uniqueTablePhone = new Dictionary>(); + Dictionary> uniqueTableEmail = new Dictionary>(); - var result = new Dictionary(); - var inputLookup = new Dictionary(); + Dictionary result = new Dictionary(); + Dictionary inputLookup = new Dictionary(); // If list is empty, return empty @@ -612,10 +695,9 @@ namespace Swarmops.Logic.Security foreach (Person p in people) { - if (uniqueTableName.ContainsKey(p.Name)) { - foreach (var sameperson in uniqueTableName[p.Name]) + foreach (Person sameperson in uniqueTableName[p.Name]) { MatchPerson(result, p, sameperson); } @@ -629,7 +711,7 @@ namespace Swarmops.Logic.Security if (uniqueTablePhone.ContainsKey(p.Phone) && p.Phone.Replace("0", "").Trim() != "") { - foreach (var sameperson in uniqueTablePhone[p.Phone]) + foreach (Person sameperson in uniqueTablePhone[p.Phone]) { MatchPerson(result, p, sameperson); } @@ -643,7 +725,7 @@ namespace Swarmops.Logic.Security if (uniqueTableEmail.ContainsKey(p.Mail)) { - foreach (var sameperson in uniqueTableEmail[p.Mail]) + foreach (Person sameperson in uniqueTableEmail[p.Mail]) { MatchPerson(result, p, sameperson); } @@ -659,9 +741,9 @@ namespace Swarmops.Logic.Security 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) { - var matches = 0; + int matches = 0; if (p.Name.Trim().ToLower() == sameperson.Name.Trim().ToLower()) ++matches; if (p.Phone.Trim() == sameperson.Phone.Trim()) @@ -677,7 +759,7 @@ namespace Swarmops.Logic.Security } } - private static bool IsSystemAdministrator (BasicAuthority authority) + private static bool IsSystemAdministrator(BasicAuthority authority) { foreach (BasicPersonRole role in authority.SystemPersonRoles) { @@ -690,44 +772,7 @@ namespace Swarmops.Logic.Security return false; } - /// - /// List of the roles which make a member visible outwards. - /// - public static RoleType[] VisibleRoles - { - get - { - return new RoleType[] - { - RoleType.LocalLead, RoleType.LocalDeputy, RoleType.OrganizationChairman, - RoleType.OrganizationSecretary, RoleType.OrganizationTreasurer, - RoleType.OrganizationVice1, RoleType.OrganizationVice2, - RoleType.OrganizationBoardMember, RoleType.OrganizationBoardDeputy - }; - } - } - - /// - /// Like VisibleRoles, but in dictionary form. - /// - public static Dictionary VisibleRolesDictionary - { - get - { - Dictionary result = new Dictionary(); - - RoleType[] roleTypes = VisibleRoles; - - foreach (RoleType roleType in roleTypes) - { - result[roleType] = true; - } - - return result; - } - } - - 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) @@ -736,7 +781,7 @@ namespace Swarmops.Logic.Security 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(); @@ -746,5 +791,8 @@ namespace Swarmops.Logic.Security return retList.ToArray(); } + internal class FoundItException : Exception + { + } } } \ No newline at end of file diff --git a/Logic/Security/BCrypt.cs b/Logic/Security/BCrypt.cs index 6761f4d9..51cf36dc 100644 --- a/Logic/Security/BCrypt.cs +++ b/Logic/Security/BCrypt.cs @@ -21,45 +21,54 @@ namespace Swarmops.Logic.Security // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - /// BCrypt implements OpenBSD-style Blowfish password hashing - /// using the scheme described in "A Future-Adaptable Password Scheme" - /// by Niels Provos and David Mazieres. + /// + /// BCrypt implements OpenBSD-style Blowfish password hashing + /// using the scheme described in "A Future-Adaptable Password Scheme" + /// by Niels Provos and David Mazieres. + /// /// - /// This password hashing system tries to thwart offline - /// password cracking using a computationally-intensive hashing - /// algorithm, based on Bruce Schneier's Blowfish cipher. The work - /// factor of the algorithm is parametized, so it can be increased as - /// computers get faster. - /// To hash a password for the first time, call the - /// HashPassword method with a random salt, like this: - /// + /// + /// This password hashing system tries to thwart offline + /// password cracking using a computationally-intensive hashing + /// algorithm, based on Bruce Schneier's Blowfish cipher. The work + /// factor of the algorithm is parametized, so it can be increased as + /// computers get faster. + /// + /// + /// To hash a password for the first time, call the + /// HashPassword method with a random salt, like this: + /// + /// /// string hashed = BCrypt.HashPassword(plainPassword, BCrypt.GenerateSalt()); /// - /// To check whether a plaintext password matches one that has - /// been hashed previously, use the CheckPassword method: - /// + /// + /// To check whether a plaintext password matches one that has + /// been hashed previously, use the CheckPassword method: + /// + /// /// if (BCrypt.CheckPassword(candidatePassword, storedHash)) { /// Console.WriteLine("It matches"); /// } else { /// Console.WriteLine("It does not match"); /// } /// - /// The GenerateSalt method takes an optional parameter - /// (logRounds) that determines the computational complexity of the - /// hashing: - /// + /// + /// The GenerateSalt method takes an optional parameter + /// (logRounds) that determines the computational complexity of the + /// hashing: + /// + /// /// string strongSalt = BCrypt.GenerateSalt(10); /// string strongerSalt = BCrypt.GenerateSalt(12); /// - /// - /// The amount of work increases exponentially (2**log_rounds), so - /// each increment is twice as much work. The default log_rounds is - /// 10, and the valid range is 4 to 31. - /// + /// + /// The amount of work increases exponentially (2**log_rounds), so + /// each increment is twice as much work. The default log_rounds is + /// 10, and the valid range is 4 to 31. + /// /// public class BCrypt { - private const int GENSALT_DEFAULT_LOG2_ROUNDS = 10; private const int BCRYPT_SALT_LEN = 16; @@ -67,327 +76,333 @@ namespace Swarmops.Logic.Security private const int BLOWFISH_NUM_ROUNDS = 16; // Initial contents of key schedule. - private static readonly uint[] p_orig = { - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b - }; + private static readonly uint[] p_orig = + { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b + }; - private static readonly uint[] s_orig = { - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - }; + private static readonly uint[] s_orig = + { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + }; // bcrypt IV: "OrpheanBeholderScryDoubt". - private static readonly uint[] bf_crypt_ciphertext = { - 0x4f727068, 0x65616e42, 0x65686f6c, - 0x64657253, 0x63727944, 0x6f756274 - }; + private static readonly uint[] bf_crypt_ciphertext = + { + 0x4f727068, 0x65616e42, 0x65686f6c, + 0x64657253, 0x63727944, 0x6f756274 + }; // Table for Base64 encoding. - private static readonly char[] base64_code = { - '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', - 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', - 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9' - }; + private static readonly char[] base64_code = + { + '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9' + }; // Table for Base64 decoding. - private static readonly int[] index_64 = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, - -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - -1, -1, -1, -1, -1, -1, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, -1, -1, -1, -1, -1 - }; + private static readonly int[] index_64 = + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, + -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + -1, -1, -1, -1, -1, -1, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, -1, -1, -1, -1, -1 + }; // Expanded Blowfish key. private uint[] p; private uint[] s; - /// Encode a byte array using bcrypt's slightly-modified - /// Base64 encoding scheme. Note that this is _not_ compatible - /// with the standard MIME-Base64 encoding. + /// + /// Encode a byte array using bcrypt's slightly-modified + /// Base64 encoding scheme. Note that this is _not_ compatible + /// with the standard MIME-Base64 encoding. + /// /// The byte array to encode /// The number of bytes to encode /// A Base64-encoded string private static string EncodeBase64(byte[] d, int length) { - if (length <= 0 || length > d.Length) { 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; ) + for (int offset = 0, c1, c2; offset < length;) { c1 = d[offset++] & 0xff; rs.Append(base64_code[(c1 >> 2) & 0x3f]); @@ -415,26 +430,29 @@ namespace Swarmops.Logic.Security return rs.ToString(); } - /// Look up the 3 bits base64-encoded by the specified - /// character, range-checking against the conversion - /// table. + /// + /// Look up the 3 bits base64-encoded by the specified + /// character, range-checking against the conversion + /// table. + /// /// The Base64-encoded value /// The decoded value of x private static int Char64(char c) { - int i = (int)c; + int i = c; return (i < 0 || i > index_64.Length) ? -1 : index_64[i]; } - /// Decode a string encoded using BCrypt's Base64 scheme to a - /// byte array. Note that this is _not_ compatible with the standard - /// MIME-Base64 encoding. + /// + /// Decode a string encoded using BCrypt's Base64 scheme to a + /// byte array. Note that this is _not_ compatible with the standard + /// MIME-Base64 encoding. + /// /// 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) { - List bytes = new List(Math.Min(maximumLength, s.Length)); if (maximumLength <= 0) @@ -442,7 +460,7 @@ namespace Swarmops.Logic.Security throw new ArgumentOutOfRangeException("maximumLength", maximumLength, null); } - for (int offset = 0, slen = s.Length, length = 0; offset < slen - 1 && length < maximumLength; ) + for (int offset = 0, slen = s.Length, length = 0; offset < slen - 1 && length < maximumLength;) { int c1 = Char64(s[offset++]); int c2 = Char64(s[offset++]); @@ -451,7 +469,7 @@ namespace Swarmops.Logic.Security break; } - bytes.Add((byte)((c1 << 2) | ((c2 & 0x30) >> 4))); + bytes.Add((byte) ((c1 << 2) | ((c2 & 0x30) >> 4))); if (++length >= maximumLength || offset >= s.Length) { break; @@ -463,14 +481,14 @@ namespace Swarmops.Logic.Security 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)); + bytes.Add((byte) (((c3 & 0x03) << 6) | c4)); ++length; } @@ -479,20 +497,24 @@ namespace Swarmops.Logic.Security } /// - /// Blowfish encipher a single 64-bit block encoded as two 32-bit - /// halves. + /// Blowfish encipher a single 64-bit block encoded as two 32-bit + /// halves. /// - /// An array containing the two 32-bit half - /// blocks. - /// The position in the array of the - /// blocks. + /// + /// An array containing the two 32-bit half + /// blocks. + /// + /// + /// The position in the array of the + /// blocks. + /// private void Encipher(uint[] block, int offset) { - uint i, n, l = block[offset], r = block[offset + 1]; l ^= this.p[0]; - unchecked // Added as per http://bcrypt.codeplex.com/SourceControl/network/forks/mammo/UncheckedFix/changeset/96b7f8314be4 to fix overflow exception. + unchecked + // Added as per http://bcrypt.codeplex.com/SourceControl/network/forks/mammo/UncheckedFix/changeset/96b7f8314be4 to fix overflow exception. { for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) { @@ -516,28 +538,29 @@ namespace Swarmops.Logic.Security } /// - /// Cycically extract a word of key material. + /// Cycically extract a word of key material. /// - /// The string to extract the data - /// from. + /// + /// The string to extract the data + /// from. + /// /// The current offset into data. /// The next work of material from data. private static uint StreamToWord(byte[] data, ref int offset) { - uint word = 0; for (int i = 0; i < 4; i++) { word = (word << 8) | data[offset]; - offset = (offset + 1) % data.Length; + offset = (offset + 1)%data.Length; } return word; } /// - /// Initialize the Blowfish key schedule. + /// Initialize the Blowfish key schedule. /// private void InitKey() { @@ -548,13 +571,12 @@ namespace Swarmops.Logic.Security } /// - /// Key the Blowfish cipher. + /// Key the Blowfish cipher. /// /// An array containing the key. private void Key(byte[] key) { - - uint[] lr = { 0, 0 }; + uint[] lr = {0, 0}; int plen = this.p.Length, slen = this.s.Length; int offset = 0; @@ -579,16 +601,15 @@ namespace Swarmops.Logic.Security } /// - /// Perform the "enhanced key schedule" step described by Provos - /// and Mazieres in "A Future-Adaptable Password Scheme" - /// (http://www.openbsd.org/papers/bcrypt-paper.ps). + /// Perform the "enhanced key schedule" step described by Provos + /// and Mazieres in "A Future-Adaptable Password Scheme" + /// (http://www.openbsd.org/papers/bcrypt-paper.ps). /// /// Salt information. /// Password information. private void EksKey(byte[] data, byte[] key) { - - uint[] lr = { 0, 0 }; + uint[] lr = {0, 0}; int plen = this.p.Length, slen = this.s.Length; int keyOffset = 0; @@ -618,18 +639,21 @@ namespace Swarmops.Logic.Security } /// - /// Perform the central password hashing step in the bcrypt - /// scheme. + /// Perform the central password hashing step in the bcrypt + /// scheme. /// /// The password to hash. - /// The binary salt to hash with the - /// password. - /// The binary logarithm of the number of - /// rounds of hashing to apply. + /// + /// The binary salt to hash with the + /// password. + /// + /// + /// The binary logarithm of the number of + /// rounds of hashing to apply. + /// /// An array containing the binary hashed password. private byte[] CryptRaw(byte[] password, byte[] salt, int logRounds) { - uint[] cdata = new uint[bf_crypt_ciphertext.Length]; bf_crypt_ciphertext.CopyTo(cdata, 0); @@ -664,24 +688,26 @@ namespace Swarmops.Logic.Security } } - ret = new byte[clen * 4]; + ret = new byte[clen*4]; for (int i = 0, j = 0; i < clen; i++) { - ret[j++] = (byte)((cdata[i] >> 24) & 0xff); - ret[j++] = (byte)((cdata[i] >> 16) & 0xff); - ret[j++] = (byte)((cdata[i] >> 8) & 0xff); - ret[j++] = (byte)(cdata[i] & 0xff); + ret[j++] = (byte) ((cdata[i] >> 24) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 16) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 8) & 0xff); + ret[j++] = (byte) (cdata[i] & 0xff); } return ret; } /// - /// Hash a password using the OpenBSD bcrypt scheme. + /// Hash a password using the OpenBSD bcrypt scheme. /// /// The password to hash. - /// The salt to hash with (perhaps generated - /// using BCrypt.GenerateSalt). + /// + /// The salt to hash with (perhaps generated + /// using BCrypt.GenerateSalt). + /// /// The hashed password. public static string HashPassword(string password, string salt) { @@ -694,7 +720,7 @@ namespace Swarmops.Logic.Security throw new ArgumentNullException("salt"); } - char minor = (char)0; + char minor = (char) 0; if (salt[0] != '$' || salt[1] != '2') { @@ -726,7 +752,7 @@ namespace Swarmops.Logic.Security byte[] passwordBytes = Encoding.UTF8.GetBytes(password + (minor >= 'a' ? "\0" : String.Empty)); byte[] saltBytes = DecodeBase64(salt.Substring(offset + 3, 22), - BCRYPT_SALT_LEN); + BCRYPT_SALT_LEN); BCrypt bcrypt = new BCrypt(); @@ -748,26 +774,27 @@ namespace Swarmops.Logic.Security rs.Append('$'); rs.Append(EncodeBase64(saltBytes, saltBytes.Length)); rs.Append(EncodeBase64(hashed, - (bf_crypt_ciphertext.Length * 4) - 1)); + (bf_crypt_ciphertext.Length*4) - 1)); return rs.ToString(); } /// - /// Generate a salt for use with the BCrypt.HashPassword() method. + /// Generate a salt for use with the BCrypt.HashPassword() method. /// - /// The log2 of the number of rounds of - /// hashing to apply. The work factor therefore increases as (2 ** - /// logRounds). + /// + /// The log2 of the number of rounds of + /// hashing to apply. The work factor therefore increases as (2 ** + /// logRounds). + /// /// An encoded salt value. public static string GenerateSalt(int logRounds) { - byte[] randomBytes = new byte[BCRYPT_SALT_LEN]; RandomNumberGenerator.Create().GetBytes(randomBytes); - StringBuilder rs = new StringBuilder((randomBytes.Length * 2) + 8); + StringBuilder rs = new StringBuilder((randomBytes.Length*2) + 8); rs.Append("$2a$"); if (logRounds < 10) @@ -782,9 +809,9 @@ namespace Swarmops.Logic.Security } /// - /// Generate a salt for use with the BCrypt.HashPassword() - /// method, selecting a reasonable default for the number of hashing - /// rounds to apply. + /// Generate a salt for use with the BCrypt.HashPassword() + /// method, selecting a reasonable default for the number of hashing + /// rounds to apply. /// /// An encoded salt value. public static string GenerateSalt() @@ -793,17 +820,18 @@ namespace Swarmops.Logic.Security } /// - /// Check that a plaintext password matches a previously hashed - /// one. + /// Check that a plaintext password matches a previously hashed + /// one. /// /// The plaintext password to verify. /// The previously hashed password. - /// true if the passwords, false - /// otherwise. + /// + /// true if the passwords, false + /// otherwise. + /// public static bool CheckPassword(string plaintext, string hashed) { return StringComparer.Ordinal.Compare(hashed, HashPassword(plaintext, hashed)) == 0; } - } -} +} \ No newline at end of file diff --git a/Logic/Security/InternalLoginTicket.cs b/Logic/Security/InternalLoginTicket.cs index a14e1d9a..50b1fe4d 100644 --- a/Logic/Security/InternalLoginTicket.cs +++ b/Logic/Security/InternalLoginTicket.cs @@ -7,5 +7,4 @@ namespace Swarmops.Logic.Security public DateTime created = DateTime.MinValue; public int validatedUserID = -1; } - -} +} \ No newline at end of file diff --git a/Logic/Security/MD5.cs b/Logic/Security/MD5.cs index 960f4113..f71a0956 100644 --- a/Logic/Security/MD5.cs +++ b/Logic/Security/MD5.cs @@ -4,11 +4,11 @@ using System.Text; namespace Swarmops { /// - /// Summary description for MD5. + /// Summary description for MD5. /// public class MD5 { - public static string Hash (string input) + public static string Hash(string input) { byte[] data = Encoding.GetEncoding(1252).GetBytes(input); @@ -17,7 +17,7 @@ namespace Swarmops // Write the resulting hash to a string of hex values. - var result = new StringBuilder(); + StringBuilder result = new StringBuilder(); foreach (byte oneByte in hash) { diff --git a/Logic/Security/PermissionSet.cs b/Logic/Security/PermissionSet.cs index 9eae89c8..5d765442 100644 --- a/Logic/Security/PermissionSet.cs +++ b/Logic/Security/PermissionSet.cs @@ -8,76 +8,34 @@ namespace Swarmops.Logic.Security { public class PermissionSet { - public class Item + private bool needAll; + public List permsList = new List(); + + + public PermissionSet(Permission p) { - public Item (int pOrgId, int pGeoId, Permission pPerm) - { - orgId = pOrgId; - geographyId = pGeoId; - perm = pPerm; - } - public Item (int pOrgId, Permission pPerm) - { - orgId = pOrgId; - geographyId = -1; - perm = pPerm; - } - public Item (Permission pPerm) - { - orgId = -1; - geographyId = -1; - perm = pPerm; - } - - public int orgId - { get; private set; } - - public int geographyId - { get; private set; } - - public Permission perm - { get; private set; } - - } - public List permsList = new List(); - - private bool needAll = false; - - public bool NeedAll - { - get { return needAll; } - set { needAll = value; } + this.permsList.Add(new Item(-1, -1, p)); } - public bool NeedOne + public PermissionSet(Permission p, int orgId) { - get { return !needAll; } - set { needAll = !value; } + this.permsList.Add(new Item(orgId, -1, p)); } - - public PermissionSet (Permission p) + public PermissionSet(Permission p, int orgId, int geoId) { - permsList.Add(new Item(-1, -1, p)); - } - public PermissionSet (Permission p,int orgId) - { - permsList.Add(new Item(orgId , -1, p)); - } - public PermissionSet (Permission p, int orgId, int geoId) - { - permsList.Add(new Item(orgId , geoId , p)); + this.permsList.Add(new Item(orgId, geoId, p)); } - public PermissionSet (PermissionSet.Item pi) + public PermissionSet(Item pi) { - permsList.Add(pi); + this.permsList.Add(pi); } - public PermissionSet (string permsString) + public PermissionSet(string permsString) { Regex re = new Regex( -@" # will search Permission(1,1),Permission(1,1),Permission + @" # will search Permission(1,1),Permission(1,1),Permission ( # group for each ,Permission(1,1) or ,Permission ( ( # Permission(1) @@ -104,7 +62,7 @@ namespace Swarmops.Logic.Security try { string pars = m.Groups["params"].Value; - string[] split = pars.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] split = pars.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); if (pars.Length > 0) { org = int.Parse(split[0]); @@ -113,92 +71,135 @@ namespace Swarmops.Logic.Security } } catch - { } - Permission p = (Permission)Enum.Parse(typeof(Permission), hit, true); - PermissionSet.Item item = new Item(org, geo, p); - permsList.Add(item); + { + } + Permission p = (Permission) Enum.Parse(typeof (Permission), hit, true); + Item item = new Item(org, geo, p); + this.permsList.Add(item); } catch - { } + { + } } } - public bool IsInSet (Permission p) + public bool NeedAll { - foreach (PermissionSet.Item ps in permsList) + get { return this.needAll; } + set { this.needAll = value; } + } + + public bool NeedOne + { + get { return !this.needAll; } + set { this.needAll = !value; } + } + + public bool IsInSet(Permission p) + { + foreach (Item ps in this.permsList) if (ps.perm == p) return true; return false; } - public bool IsInSet (PermissionSet ps) + public bool IsInSet(PermissionSet ps) { foreach (Permission p in ps) - if (!this.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 (this.IsInSet(p)) + if (IsInSet(p)) return true; return false; } - public override string ToString () + public override string ToString() { - List reslist = new List(); - foreach (PermissionSet.Item itm in this) + List reslist = new List(); + foreach (Item itm in this) { reslist.Add(itm.perm.ToString()); } string[] resArr = reslist.ToArray(); - string res = string.Join(needAll ? " & " : " | ", resArr); + string res = string.Join(this.needAll ? " & " : " | ", resArr); return res; } - public Enumerator GetEnumerator () + public Enumerator GetEnumerator() { return new Enumerator(this); } public class Enumerator : IEnumerator { - int currentIndex = -1; - PermissionSet parent; + private readonly PermissionSet parent; + private int currentIndex = -1; - internal Enumerator (PermissionSet p) + internal Enumerator(PermissionSet p) { this.parent = p; - this.Reset(); + Reset(); } public object Current { get { - if (currentIndex < 0 || currentIndex > parent.permsList.Count - 1) + if (this.currentIndex < 0 || this.currentIndex > this.parent.permsList.Count - 1) return null; - return parent.permsList[currentIndex]; + return this.parent.permsList[this.currentIndex]; } } - public bool MoveNext () + public bool MoveNext() { - ++currentIndex; + ++this.currentIndex; if (Current != null) return true; - else - return false; + return false; } - public void Reset () + public void Reset() { - currentIndex = -1; + this.currentIndex = -1; } } + + public class Item + { + public Item(int pOrgId, int pGeoId, Permission pPerm) + { + orgId = pOrgId; + geographyId = pGeoId; + perm = pPerm; + } + + public Item(int pOrgId, Permission pPerm) + { + orgId = pOrgId; + geographyId = -1; + perm = pPerm; + } + + public Item(Permission pPerm) + { + orgId = -1; + geographyId = -1; + perm = pPerm; + } + + public int orgId { get; private set; } + + public int geographyId { get; private set; } + + public Permission perm { get; private set; } + } } -} +} \ No newline at end of file diff --git a/Logic/Security/PgpKey.cs b/Logic/Security/PgpKey.cs index a7aa8127..a69e0355 100644 --- a/Logic/Security/PgpKey.cs +++ b/Logic/Security/PgpKey.cs @@ -7,12 +7,14 @@ namespace Swarmops.Logic.Security { public class PgpKey { - static public void Generate (Person person, Organization organization) + public string Fingerprint { get; private set; } + + 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)); + new DateTime(DateTime.Today.Year + 2, 12, 31)); GnuPGKeyCollection keys = new GnuPG().GetKeys(); foreach (GnuPGKey key in keys) @@ -33,9 +35,6 @@ namespace Swarmops.Logic.Security person.CryptoFingerprint = key.Fingerprint; } } - } - - public string Fingerprint { get; private set; } } -} +} \ No newline at end of file diff --git a/Logic/Security/SHA1.cs b/Logic/Security/SHA1.cs index d4e8b54c..78126bc1 100644 --- a/Logic/Security/SHA1.cs +++ b/Logic/Security/SHA1.cs @@ -4,11 +4,11 @@ using System.Text; namespace Swarmops.Logic.Security { /// - /// Summary description for SHA1. + /// Summary description for SHA1. /// public class SHA1 { - public static string Hash (string input) + public static string Hash(string input) { byte[] data = Encoding.GetEncoding(1252).GetBytes(input); @@ -17,7 +17,7 @@ namespace Swarmops.Logic.Security // Write the resulting hash to a string of hex values. - var result = new StringBuilder(); + StringBuilder result = new StringBuilder(); foreach (byte oneByte in hash) { diff --git a/Logic/Special/DummyBitcoin.cs b/Logic/Special/DummyBitcoin.cs index 0e16cd0b..f52f2b7d 100644 --- a/Logic/Special/DummyBitcoin.cs +++ b/Logic/Special/DummyBitcoin.cs @@ -1,22 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NBitcoin; +using NBitcoin; namespace Swarmops.Logic.Special { /// - /// The point of this class is to reference NBitcoin, so its assembly and dependencies get copied to the output dir, - /// as the Site can't reference assemblies directly. + /// The point of this class is to reference NBitcoin, so its assembly and dependencies get copied to the output dir, + /// as the Site can't reference assemblies directly. /// public class DummyBitcoin { - public static BitcoinAddress Address { get; set; } - public DummyBitcoin() { Address = new BitcoinAddress("abcdefgh"); } + + public static BitcoinAddress Address { get; set; } } -} +} \ No newline at end of file diff --git a/Logic/Special/Mail/MailServerDatabase.cs b/Logic/Special/Mail/MailServerDatabase.cs index a163b80b..69715057 100644 --- a/Logic/Special/Mail/MailServerDatabase.cs +++ b/Logic/Special/Mail/MailServerDatabase.cs @@ -9,24 +9,14 @@ namespace Swarmops.Logic.Special.Mail // Have moved this Class from Utility to Logic to avoid circular dependency between assemblies /JL public class MailServerDatabase { - /// - /// class MailAccount is used for transport of results only - /// - public class MailAccount - { - public string account { get; set; } - public List forwardedTo = new List(); - public List forwardedFrom = new List(); + private static readonly string connectionString = ""; - } - - - static MailServerDatabase () + static MailServerDatabase() { 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)) { @@ -37,14 +27,14 @@ namespace Swarmops.Logic.Special.Mail new MySqlCommand( "INSERT INTO users (email, password, quota) VALUES ('" + email.Replace("'", "''") + "', ENCRYPT('" + initialPassword.Replace("'", "''") + "'), " + - (1048576 * quotaMegabytes).ToString() + ");", connection)) + (1048576*quotaMegabytes) + ");", connection)) { command.ExecuteNonQuery(); } } } - public static List SearchAccount (string email) + public static List SearchAccount(string email) { //temporary test @@ -89,9 +79,8 @@ namespace Swarmops.Logic.Special.Mail 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) { @@ -104,19 +93,22 @@ namespace Swarmops.Logic.Special.Mail using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); - using (MySqlCommand command = new MySqlCommand("select * from users where email = '" + email + "'", connection)) + using ( + MySqlCommand command = new MySqlCommand("select * from users where email = '" + email + "'", + connection)) { using (DbDataReader reader = command.ExecuteReader()) { if (!reader.Read()) - { //Address not found, it's OK to use + { + //Address not found, it's OK to use return email; } } } - string[] splitDom = email.Split(new char[] { '@' }); + string[] splitDom = email.Split(new[] {'@'}); - string[] splitArr = splitDom[0].Split(new char[] { '.' }); + string[] splitArr = splitDom[0].Split(new[] {'.'}); string firstPart = splitArr[0]; splitArr[0] = ""; @@ -131,20 +123,22 @@ namespace Swarmops.Logic.Special.Mail MySqlCommand command = new MySqlCommand( "select * from users where email RLIKE " + - "'^" + firstPart + "([.period.][^[.period.]]+){0,1}[.period.]" + secondPartRegEx + "@" + domainRegex + "'", + "'^" + firstPart + "([.period.][^[.period.]]+){0,1}[.period.]" + secondPartRegEx + "@" + + domainRegex + "'", connection)) { - List foundAddresses = new List(); ; + List foundAddresses = new List(); + ; using (DbDataReader reader = command.ExecuteReader()) { 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); + char suggestChar2 = (char) ('a' - 1); while (foundAddresses.Contains(suggestMail.Trim().ToLowerInvariant())) { string suggestString = "" + suggestChar; @@ -159,7 +153,6 @@ namespace Swarmops.Logic.Special.Mail suggestMail = firstPart + "." + suggestString + "." + secondPart + "@" + splitDom[1]; ++suggestChar; - } return suggestMail; } @@ -167,7 +160,7 @@ 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)) { @@ -181,11 +174,10 @@ namespace Swarmops.Logic.Special.Mail { 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("'", "''"); @@ -223,12 +215,13 @@ namespace Swarmops.Logic.Special.Mail { if (reader.Read()) { - string tmpDest = ((string)reader["destination"]).Trim().ToLower(); + string tmpDest = ((string) reader["destination"]).Trim().ToLower(); loopDict.Add(loopEmail, tmpDest); loopEmail = tmpDest; } else - { //Address not found + { + //Address not found loopEmail = ""; } } @@ -260,7 +253,7 @@ 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) @@ -288,7 +281,8 @@ 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) @@ -310,7 +304,7 @@ 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) @@ -325,8 +319,8 @@ namespace Swarmops.Logic.Special.Mail using ( MySqlCommand command = new MySqlCommand( - // Shortcut past the account that is to be removed - @"Update forwardings + // Shortcut past the account that is to be removed + @"Update forwardings INNER JOIN (SELECT DISTINCT forwardings.source, @@ -340,11 +334,11 @@ namespace Swarmops.Logic.Special.Mail ON (forwardings.source = Subquery.source) set destination=Subquery.newDestination where Subquery.orgDestination='" + fromEmail + "';" + - // Delete where the removed account is source of forwarding + // Delete where the removed account is source of forwarding "DELETE FROM forwardings WHERE source='" + fromEmail + "';" + - // Delete where the removed account is target of forwarding + // Delete where the removed account is target of forwarding "DELETE FROM forwardings WHERE destination='" + fromEmail + "';" + - // Delete the user + // Delete the user "DELETE FROM users WHERE email='" + fromEmail + "';" , connection)) { @@ -353,6 +347,14 @@ namespace Swarmops.Logic.Special.Mail } } - private static string connectionString = ""; + /// + /// class MailAccount is used for transport of results only + /// + public class MailAccount + { + public List forwardedFrom = new List(); + public List forwardedTo = new List(); + public string account { get; set; } + } } } \ No newline at end of file diff --git a/Logic/Special/Sweden/SupportCase.cs b/Logic/Special/Sweden/SupportCase.cs index 4442cf6a..b573b839 100644 --- a/Logic/Special/Sweden/SupportCase.cs +++ b/Logic/Special/Sweden/SupportCase.cs @@ -5,7 +5,13 @@ namespace Swarmops.Logic.Special.Sweden { public class SupportCase : IHasIdentity { - public SupportCase (int identity, string title) + public readonly DateTime DateTimeClosed; + public readonly string Email; + public readonly bool Open; + public readonly int SupportCaseId; + public readonly string Title; + + public SupportCase(int identity, string title) { this.SupportCaseId = identity; this.Title = title; @@ -14,7 +20,7 @@ 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; @@ -28,20 +34,14 @@ namespace Swarmops.Logic.Special.Sweden } } - public readonly int SupportCaseId; - public readonly string Title; - public readonly bool Open; - public readonly string Email; - public readonly DateTime DateTimeClosed; - public int Identity { - get { return SupportCaseId; } + get { return this.SupportCaseId; } } - public void CloseWithComment (string comment) + public void CloseWithComment(string comment) { - SupportDatabase.CloseWithComment(this.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 740d4d97..0bc01613 100644 --- a/Logic/Special/Sweden/SupportCaseDelta.cs +++ b/Logic/Special/Sweden/SupportCaseDelta.cs @@ -3,16 +3,17 @@ using Swarmops.Basic.Interfaces; namespace Swarmops.Logic.Special.Sweden { - public class SupportCaseDelta: IHasIdentity + public class SupportCaseDelta : IHasIdentity { - public SupportCaseDelta (int supportCaseDeltaId, int supportCaseId, int supportPersonId, DateTime dateTime, string verb, string changes) + public SupportCaseDelta(int supportCaseDeltaId, int supportCaseId, int supportPersonId, DateTime dateTime, + string verb, string changes) { - this.SupportCaseDeltaId = supportCaseDeltaId; - this.SupportCaseId = supportCaseId; - this.Verb = verb; - this.DateTime = dateTime; - this.Changes = changes; - this.SupportPersonId = supportPersonId; + SupportCaseDeltaId = supportCaseDeltaId; + SupportCaseId = supportCaseId; + Verb = verb; + DateTime = dateTime; + Changes = changes; + SupportPersonId = supportPersonId; } @@ -26,7 +27,7 @@ namespace Swarmops.Logic.Special.Sweden public int Identity { - get { return this.SupportCaseDeltaId; } + get { return SupportCaseDeltaId; } } } -} +} \ No newline at end of file diff --git a/Logic/Special/Sweden/SupportDatabase.cs b/Logic/Special/Sweden/SupportDatabase.cs index 14187d9f..a1e1a5fb 100644 --- a/Logic/Special/Sweden/SupportDatabase.cs +++ b/Logic/Special/Sweden/SupportDatabase.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Data; +using System.Data.SqlTypes; using System.Text; using System.Text.RegularExpressions; using MySql.Data.MySqlClient; @@ -11,20 +13,20 @@ namespace Swarmops.Logic.Special.Sweden { public class SupportDatabase { - private static MySqlConnection GetConnection () + private static MySqlConnection GetConnection() { string connect = Persistence.Key["SupportDatabaseConnect"]; return new MySqlConnection(connect); } - private static SupportCase[] GetUndeliverableCases () + private static SupportCase[] GetUndeliverableCases() { return GetUndeliverableCases(0, 99999); } - public static SupportCaseDelta[] GetCaseDeltas (int fromDeltaId) + public static SupportCaseDelta[] GetCaseDeltas(int fromDeltaId) { List result = new List(); @@ -34,7 +36,8 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = new MySqlCommand( - "SELECT ixBugEvent,ixBug,ixPerson,dt,sVerb,sChanges FROM BugEvent WHERE ixBugEvent > " + fromDeltaId.ToString() + " ORDER BY ixBugEvent", + "SELECT ixBugEvent,ixBug,ixPerson,dt,sVerb,sChanges FROM BugEvent WHERE ixBugEvent > " + + fromDeltaId + " ORDER BY ixBugEvent", connection); command.CommandTimeout = 600; @@ -42,7 +45,7 @@ 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)); } @@ -54,8 +57,7 @@ namespace Swarmops.Logic.Special.Sweden } - - public static SupportCase[] GetOpenCases () + public static SupportCase[] GetOpenCases() { List result = new List(); @@ -75,7 +77,7 @@ namespace Swarmops.Logic.Special.Sweden { result.Add(ReadFullSupportCaseFromReader(reader)); } - catch (System.Data.SqlTypes.SqlNullValueException) + catch (SqlNullValueException) { Console.WriteLine("Exception on bug {0}", reader.GetInt32(0)); } @@ -87,8 +89,7 @@ namespace Swarmops.Logic.Special.Sweden } - - public static SupportCase GetCase (int supportCaseId) + public static SupportCase GetCase(int supportCaseId) { using (MySqlConnection connection = GetConnection()) { @@ -96,7 +97,7 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = new MySqlCommand( - "SELECT ixBug,sTitle,sCustomerEmail FROM Bug WHERE ixBug=" + supportCaseId.ToString(), connection); + "SELECT ixBug,sTitle,sCustomerEmail FROM Bug WHERE ixBug=" + supportCaseId, connection); using (MySqlDataReader reader = command.ExecuteReader()) { @@ -105,14 +106,13 @@ namespace Swarmops.Logic.Special.Sweden return ReadFullSupportCaseFromReader(reader); } - throw new ArgumentException("No such Support Case Id: " + supportCaseId.ToString()); + 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(); @@ -122,7 +122,8 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = 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.ToString() + " order by ixBug LIMIT " + limit.ToString(), + "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); using (MySqlDataReader reader = command.ExecuteReader()) @@ -137,7 +138,7 @@ namespace Swarmops.Logic.Special.Sweden return result.ToArray(); } - private static SupportCase[] GetDelayWarnings () + private static SupportCase[] GetDelayWarnings() { List result = new List(); @@ -163,7 +164,7 @@ namespace Swarmops.Logic.Special.Sweden } - public static bool IsCaseOpen (int caseId) + public static bool IsCaseOpen(int caseId) { using (MySqlConnection connection = GetConnection()) { @@ -171,7 +172,7 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = new MySqlCommand( - "SELECT fOpen FROM Bug WHERE ixBug=" + caseId.ToString(), + "SELECT fOpen FROM Bug WHERE ixBug=" + caseId, connection); using (MySqlDataReader reader = command.ExecuteReader()) @@ -190,8 +191,7 @@ namespace Swarmops.Logic.Special.Sweden } - - public static DateTime? GetCaseCloseDateTime (int caseId) + public static DateTime? GetCaseCloseDateTime(int caseId) { using (MySqlConnection connection = GetConnection()) { @@ -199,7 +199,7 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = new MySqlCommand( - "SELECT dtClosed FROM Bug WHERE ixBug=" + caseId.ToString(), + "SELECT dtClosed FROM Bug WHERE ixBug=" + caseId, connection); using (MySqlDataReader reader = command.ExecuteReader()) @@ -218,8 +218,7 @@ namespace Swarmops.Logic.Special.Sweden } - - public static void CloseDelayWarnings () + public static void CloseDelayWarnings() { SupportCase[] cases = GetDelayWarnings(); @@ -230,7 +229,7 @@ namespace Swarmops.Logic.Special.Sweden } - public static SupportEmail[] GetRecentOutgoingEmails (int sinceEventId) + public static SupportEmail[] GetRecentOutgoingEmails(int sinceEventId) { List result = new List(); @@ -256,7 +255,7 @@ namespace Swarmops.Logic.Special.Sweden } - public static string GetFirstEventText (int bugId) + public static string GetFirstEventText(int bugId) { using (MySqlConnection connection = GetConnection()) { @@ -264,14 +263,14 @@ namespace Swarmops.Logic.Special.Sweden MySqlCommand command = new MySqlCommand( - "SELECT s FROM BugEvent WHERE ixBug = " + bugId.ToString() + " ORDER BY ixBugEvent LIMIT 1", + "SELECT s FROM BugEvent WHERE ixBug = " + bugId + " ORDER BY ixBugEvent LIMIT 1", connection); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - return (string)reader[0]; + return (string) reader[0]; } return string.Empty; @@ -280,7 +279,7 @@ namespace Swarmops.Logic.Special.Sweden } - private static SupportEmail ReadSupportEmailFromReader (MySqlDataReader reader) + private static SupportEmail ReadSupportEmailFromReader(MySqlDataReader reader) { SupportEmail email = new SupportEmail(); @@ -297,7 +296,7 @@ namespace Swarmops.Logic.Special.Sweden } - private static SupportCase ReadFullSupportCaseFromReader (MySqlDataReader reader) + private static SupportCase ReadFullSupportCaseFromReader(MySqlDataReader reader) { // ixBug,sTitle,sCustomerEmail @@ -314,7 +313,7 @@ namespace Swarmops.Logic.Special.Sweden } - private static SupportCase ReadSupportCaseFromReader (MySqlDataReader reader) + private static SupportCase ReadSupportCaseFromReader(MySqlDataReader reader) { // ixBug,sTitle @@ -325,7 +324,7 @@ namespace Swarmops.Logic.Special.Sweden } - private static SupportCaseDelta ReadSupportCaseDeltaFromReader (MySqlDataReader reader) + private static SupportCaseDelta ReadSupportCaseDeltaFromReader(MySqlDataReader reader) { // ixBug,sTitle @@ -341,9 +340,7 @@ namespace Swarmops.Logic.Special.Sweden } - - - internal static void CloseWithComment (int bugId, string comment) + internal static void CloseWithComment(int bugId, string comment) { using (MySqlConnection connection = GetConnection()) { @@ -354,17 +351,17 @@ namespace Swarmops.Logic.Special.Sweden command.Parameters.AddWithValue("comment", comment); command.Parameters.AddWithValue("dateTime", DateTime.Now); - command.CommandType = System.Data.CommandType.StoredProcedure; + command.CommandType = CommandType.StoredProcedure; command.ExecuteNonQuery(); } } - public static void NotifyBouncingEmails () + public static void NotifyBouncingEmails() { Regex regex = new Regex(@"(?[a-z_0-9\.\+\-]+\@[a-z_0-9\.\-]+)", - RegexOptions.Compiled | RegexOptions.IgnoreCase); + RegexOptions.Compiled | RegexOptions.IgnoreCase); string SMSBouncingEmail = ("" + Persistence.Key["SMSBouncingEmail"]).ToUpper().Trim(); Regex reIsNo = new Regex(@"(NO)|(N)|(NEJ)", RegexOptions.IgnoreCase); @@ -378,9 +375,9 @@ namespace Swarmops.Logic.Special.Sweden SupportCase[] cases = null; while (lastCaseHandled == 0 || (cases != null && cases.Length > 0)) { - cases = SupportDatabase.GetUndeliverableCases(lastCaseHandled, 100); + cases = GetUndeliverableCases(lastCaseHandled, 100); - if (cases.Length == 0) // very very important bugfix + if (cases.Length == 0) // very very important bugfix { break; } @@ -430,7 +427,7 @@ namespace Swarmops.Logic.Special.Sweden if (people.Count > 2) { CloseWithComment(@case.Identity, - "Bounced message closed. More than one person matches the email address. Both marked unreachable."); + "Bounced message closed. More than one person matches the email address. Both marked unreachable."); foreach (Person person in people) { @@ -441,7 +438,7 @@ namespace Swarmops.Logic.Special.Sweden else if (people.Count < 1) { CloseWithComment(@case.Identity, - "Bounced message closed. No person in the database matches the email address."); + "Bounced message closed. No person in the database matches the email address."); } else @@ -472,29 +469,29 @@ namespace Swarmops.Logic.Special.Sweden if (dontSendSMS) { CloseWithComment(@case.Identity, - "The person at phone# " + person.Phone + ", " + person.Name + - " (#" + person.Identity.ToString() + - "), was not contacted due to that SMS notification is currently turned off. Bounced message closed."); + "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."); } else { try { - person.SendPhoneMessage("Piratpartiet: den mailadress vi har till dig (" + - person.Mail + - ") studsar. Kontakta medlemsservice@piratpartiet.se med ny adress."); + person.SendPhoneMessage( + "Piratpartiet: den mailadress vi har till dig (" + + person.Mail + + ") studsar. Kontakta medlemsservice@piratpartiet.se med ny adress."); CloseWithComment(@case.Identity, - "Successfully notified the member at phone# " + person.Phone + - ", " + person.Name + " (#" + person.Identity.ToString() + - "), about the bounced email using an SMS message. Case closed."); - + "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, - "The person at phone# " + person.Phone + ", " + person.Name + - " (#" + person.Identity.ToString() + - "), could not be reached over SMS. This member has been marked unreachable. Bounced message closed."); + "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."); person.MailUnreachable = true; } } @@ -502,8 +499,8 @@ namespace Swarmops.Logic.Special.Sweden else { CloseWithComment(@case.Identity, - person.Name + " (#" + person.Identity.ToString() + - ") does not have a listed phone number. This member has been marked unreachable. Bounced message closed."); + person.Name + " (#" + person.Identity + + ") does not have a listed phone number. This member has been marked unreachable. Bounced message closed."); person.MailUnreachable = true; } } @@ -511,15 +508,16 @@ namespace Swarmops.Logic.Special.Sweden else { CloseWithComment(@case.Identity, - "The person at phone# " + person.Phone + ", " + person.Name + " (#" + - person.Identity.ToString() + - ") has no active memberships. Bounced message closed."); + "The person at phone# " + person.Phone + ", " + person.Name + " (#" + + person.Identity + + ") has no active memberships. Bounced message closed."); } } } else { - CloseWithComment(@case.Identity, "Bounced message closed. No email address could be located."); + CloseWithComment(@case.Identity, + "Bounced message closed. No email address could be located."); } } else @@ -530,4 +528,4 @@ namespace Swarmops.Logic.Special.Sweden } } } -} +} \ No newline at end of file diff --git a/Logic/Special/Sweden/SupportEmail.cs b/Logic/Special/Sweden/SupportEmail.cs index 5347b28c..e4ce491f 100644 --- a/Logic/Special/Sweden/SupportEmail.cs +++ b/Logic/Special/Sweden/SupportEmail.cs @@ -2,11 +2,11 @@ namespace Swarmops.Logic.Special.Sweden { public class SupportEmail { + public string Body; + public int CaseId; + public string CaseTitle; public int EventId; public string From; public string To; - public int CaseId; - public string CaseTitle; - public string Body; } } \ No newline at end of file diff --git a/Logic/Special/Sweden/SwedishForumDatabase.cs b/Logic/Special/Sweden/SwedishForumDatabase.cs index 0d6ff04e..8c5b3a63 100644 --- a/Logic/Special/Sweden/SwedishForumDatabase.cs +++ b/Logic/Special/Sweden/SwedishForumDatabase.cs @@ -17,65 +17,57 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Special.Sweden { - public interface IForumDatabase { - 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); - System.Collections.Generic.Dictionary GetPollVotes (int pollId); - bool IsPartyMember (int accountId); - void SetPartyMember (int accountId); - void SetPartyNonmember (int accountId); bool TestMode { get; set; } + 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); } 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); - else - return SwedishForumDatabaseVBulletin.GetDatabase(connectionstring); + return SwedishForumDatabaseVBulletin.GetDatabase(connectionstring); } - public static IForumDatabase GetDatabase (int type) + public static IForumDatabase GetDatabase(int type) { if (type == 1) return SwedishForumDatabaseInstantForum.GetDatabase(); - else - return SwedishForumDatabaseVBulletin.GetDatabase(); + return SwedishForumDatabaseVBulletin.GetDatabase(); } - public static IForumDatabase GetDatabase () + public static IForumDatabase GetDatabase() { if (Path.DirectorySeparatorChar == '/') { if (string.IsNullOrEmpty(Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Bot"])) return GetDatabase(1); - else - return GetDatabase(2); + return GetDatabase(2); } - else - { - if (string.IsNullOrEmpty(Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Web"])) - return GetDatabase(1); - else - return GetDatabase(2); - } - + if (string.IsNullOrEmpty(Persistence.Key["SwedishForumDatabaseVBulletin_ConnectionString_Web"])) + return GetDatabase(1); + return GetDatabase(2); } } public class SwedishForumDatabaseInstantForum : IForumDatabase { - const int ForumIdTestPost = 326; - private int forceForumId = 0; + private const int ForumIdTestPost = 326; + private int forceForumId; #region Connectionstring definitions + // config file used by GetDatabase() private const string AppConfigFile = @"./database.config"; @@ -94,19 +86,359 @@ namespace Swarmops.Logic.Special.Sweden private static string CachedConnectionString; private static string CachedProviderName; private readonly string connectString = string.Empty; + #endregion - public SwedishForumDatabaseInstantForum (string connectString) + public SwedishForumDatabaseInstantForum(string connectString) { this.connectString = connectString; } - public static IForumDatabase GetDatabase (string connectionstring) + public int GetAccountId(string nick) + { + if (nick == null) + { + throw new ArgumentNullException("nick"); + } + + 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); + + using (SqlDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return reader.GetInt32(0); + } + throw new ArgumentException("No such nick in database"); + } + } + } + + public string GetAccountName(int accountId) + { + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = + 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); + } + throw new ArgumentException("No such nick in database"); + } + } + } + + public int[] GetAccountList() + { + List result = new List(); + + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + 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)); + } + + return result.ToArray(); + } + } + } + + public bool TestMode + { + get { return this.forceForumId != 0; } + set + { + if (value) + this.forceForumId = ForumIdTestPost; + else + this.forceForumId = 0; + } + } + + #region Party Membership + + public bool IsPartyMember(int accountId) + { + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = + 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); + if (roleId == 7) + { + return true; + } + return false; + } + + throw new Exception("Account Id does not exist"); + } + } + } + + + public void SetPartyMember(int accountId) + { + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = new SqlCommand("PirateSetMember", connection); + command.CommandType = CommandType.StoredProcedure; + + command.Parameters.AddWithValue("@accountId", accountId); + command.ExecuteNonQuery(); + } + } + + + public void SetPartyNonmember(int accountId) + { + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = new SqlCommand("PirateSetNonmember", connection); + command.CommandType = CommandType.StoredProcedure; + + command.Parameters.AddWithValue("@accountId", accountId); + command.ExecuteNonQuery(); + } + } + + #endregion + + #region Polls + + public int GetPollIdFromTopicId(int topicId) + { + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = + 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); + } + + throw new ArgumentOutOfRangeException(); + } + } + } + + + public Dictionary GetPollVotes(int pollId) + { + // First, let's get the list of alternatives. + + Dictionary pollAlternatives = GetPollAlternatives(pollId); + + // Construct a comma-separated list of the answer IDs. + + StringBuilder altStringBuilder = new StringBuilder(); + + foreach (int pollAlternativeId in pollAlternatives.Keys) + { + altStringBuilder.Append("," + pollAlternativeId); + } + + string altString = altStringBuilder.ToString().Substring(1); + + Dictionary result = new Dictionary(); + + using (SqlConnection connection = new SqlConnection(this.connectString)) + { + connection.Open(); + + SqlCommand command = + new SqlCommand( + String.Format( + "Select PollAnswerID,UserID from InstantForum_PollVotes WHERE PollAnswerId IN (" + altString + + ")"), connection); + + using (SqlDataReader reader = command.ExecuteReader()) + { + int voteCount = 0; + + while (reader.Read()) + { + voteCount++; + int forumUserId = reader.GetInt32(1); + + People people = People.FromOptionalData(ObjectOptionalDataType.ForumAccountId, + forumUserId.ToString()); + if (people.Count > 1) + { + Person[] array = people.ToArray(); + foreach (Person testPerson in array) + { + if (testPerson.GetMemberships().Count == 0) + { + people.Remove(testPerson); + } + } + + if (people.Count > 1) + { + throw new Exception("This is not possible -- check userid " + forumUserId + + ", appears to be tied to several personIds"); + } + } + + Person person = null; + + if (people.Count > 0) + { + person = people[0]; + } + + int pollAnswerId = reader.GetInt32(0); + string pollAnswer = pollAlternatives[pollAnswerId]; + + if (!result.ContainsKey(pollAnswer)) + { + result[pollAnswer] = new People(); + } + + result[pollAnswer].Add(person); + } + + return result; + } + } + } + + + private Dictionary GetPollAlternatives(int pollId) + { + Dictionary result = new Dictionary(); + + 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); + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result[reader.GetInt32(0)] = reader.GetString(1); + } + + return result; + } + } + } + + #endregion + + #region Create 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)) + { + connection.Open(); + + // First, insert the post itself + + 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"); + + SqlParameter parameterText = new SqlParameter("@strMessage", SqlDbType.NText, post.Length*2 + 2048); + parameterText.Value = post; + + command.Parameters.Add(parameterText); + + SqlParameter parameterResult = new SqlParameter("@intIdentity", SqlDbType.Int, 4); + parameterResult.Direction = ParameterDirection.Output; + + command.Parameters.Add(parameterResult); + + command.ExecuteNonQuery(); + + int postId = (int) parameterResult.Value; + + // Then, update the LastRead for this forum + + 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.ExecuteNonQuery(); + + return postId; + } + } + + #endregion + + public static IForumDatabase GetDatabase(string connectionstring) { return new SwedishForumDatabaseInstantForum(CachedConnectionString); } - public static IForumDatabase GetDatabase () + public static IForumDatabase GetDatabase() { // First, check if a previous invocation has put anything in the cashe. string ConnectionString = CachedConnectionString; @@ -119,8 +451,8 @@ namespace Swarmops.Logic.Special.Sweden ProviderName = ConfigurationManager.ConnectionStrings["PirateWeb"].ProviderName; Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized from Config ConnectionString: [" + ConnectionString + - "] / [" + ProviderName + "]"); + "SwarmDb initialized from Config ConnectionString: [" + ConnectionString + + "] / [" + ProviderName + "]"); } // If the app/web config is empty, check the database config file on disk @@ -132,41 +464,42 @@ namespace Swarmops.Logic.Special.Sweden { // We are running under mono - using (var reader = new StreamReader(MonoConfigFile)) + using (StreamReader reader = new StreamReader(MonoConfigFile)) { ConnectionString = reader.ReadLine(); ProviderName = reader.ReadLine(); Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized for Linux: [" + ConnectionString + "] / [" + - ProviderName + "]"); + "SwarmDb initialized for Linux: [" + ConnectionString + "] / [" + + ProviderName + "]"); } } else if (HttpContext.Current != null) { // We are running a web application - using (var 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, - "SwarmDb initialized for web: [" + ConnectionString + "] / [" + - ProviderName + "]"); + "SwarmDb initialized for web: [" + ConnectionString + "] / [" + + ProviderName + "]"); } } else { // We are running an application, presumably directly from Visual Studio. // If so, the current working directory is "PirateWeb/30/Console/bin". - using (var reader = new StreamReader(AppConfigFile)) + using (StreamReader reader = new StreamReader(AppConfigFile)) { ConnectionString = reader.ReadLine(); ProviderName = reader.ReadLine(); Logging.LogInformation(LogSource.PirateDb, - "SwarmDb initialized for application: [" + ConnectionString + - "] / [" + ProviderName + "]"); + "SwarmDb initialized for application: [" + ConnectionString + + "] / [" + ProviderName + "]"); } } } @@ -213,72 +546,99 @@ namespace Swarmops.Logic.Special.Sweden return new SwedishForumDatabaseInstantForum(CachedConnectionString); } + } - public int GetAccountId (string nick) + public class ErrorIgnorerPolicy : ICertificatePolicy + { + public bool CheckValidationResult(ServicePoint sp, X509Certificate certificate, WebRequest request, int error) + { + if (error == 0) + return true; + // only ask for trust failure (you may want to handle more cases) + if (error != -2146762486) + return false; + + return true; + } + } + + public class SwedishForumDatabaseVBulletin : IForumDatabase + { + private const int ForumIdTestPost = 262; + // The cached values used by GetDatabase() + private static string CachedConnectionString; + + private static readonly int partymembergroupid = 16; + private static readonly int nonmembergroupid = 2; + private readonly string connectString = string.Empty; + private int forceForumId; + + public SwedishForumDatabaseVBulletin(string connectString) + { + this.connectString = connectString; + } + + + public int GetAccountId(string nick) { if (nick == null) { throw new ArgumentNullException("nick"); } - using (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand( - String.Format("Select UserId from InstantASP_Users Where Username='{0}'", - nick.Replace("'", "''")), connection); - - using (SqlDataReader reader = command.ExecuteReader()) + MySqlCommand command = + 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); } - else - { - 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 (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand(String.Format("Select Username from InstantASP_Users Where UserId=" + accountId), - connection); + MySqlCommand command = + new MySqlCommand(String.Format("Select username from vb_user Where userid=" + accountId), + connection); - using (SqlDataReader reader = command.ExecuteReader()) + using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { return reader.GetString(0); } - else - { - throw new ArgumentException("No such nick in database"); - } + throw new ArgumentException("No such nick in database"); } } } - public int[] GetAccountList () + public int[] GetAccountList() { - var result = new List(); + List result = new List(); - using (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = new SqlCommand(String.Format("Select UserId from InstantASP_Users"), connection); + MySqlCommand command = new MySqlCommand(String.Format("Select userid from vb_user"), connection); - using (SqlDataReader reader = command.ExecuteReader()) + using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { @@ -290,31 +650,47 @@ namespace Swarmops.Logic.Special.Sweden } } - #region Party Membership - public bool IsPartyMember (int accountId) + public bool TestMode { - using (var connection = new SqlConnection(this.connectString)) + get { return this.forceForumId != 0; } + set + { + if (value) + this.forceForumId = ForumIdTestPost; + else + this.forceForumId = 0; + } + } + + #region Party Membership + + public bool IsPartyMember(int accountId) + { + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand( - String.Format("Select PrimaryRoleID from InstantASP_Users where UserID=" + accountId), + MySqlCommand command = + new MySqlCommand( + String.Format("Select membergroupids from vb_user where userid=" + accountId), connection); - using (SqlDataReader reader = command.ExecuteReader()) + using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - int roleId = reader.GetInt16(0); - if (roleId == 7) + string allGroups = ","; + + if (!reader.IsDBNull(0)) + allGroups += "" + reader.GetString(0) + ","; + + allGroups = allGroups.Replace(" ", ""); + + if (allGroups.Contains("," + partymembergroupid + ",")) { return true; } - else - { - return false; - } + return false; } throw new Exception("Account Id does not exist"); @@ -323,51 +699,115 @@ namespace Swarmops.Logic.Special.Sweden } - public void SetPartyMember (int accountId) + public void SetPartyMember(int accountId) { - using (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); + //TODO: Convert back to stored procedure + //var command = new MySqlCommand("PirateSetMember", connection); + //command.CommandType = CommandType.StoredProcedure; - var command = new SqlCommand("PirateSetMember", connection); - command.CommandType = CommandType.StoredProcedure; + //command.Parameters.AddWithValue("@accountId", accountId); + //command.ExecuteNonQuery(); - command.Parameters.AddWithValue("@accountId", accountId); - command.ExecuteNonQuery(); + string allGroups = ","; + + 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 (!allGroups.Contains("," + partymembergroupid + ",")) + { + allGroups = (allGroups + .Replace(" ", "") + .Replace(",,", ",") + .Trim(',') + "," + partymembergroupid).Trim(','); + + command = + new MySqlCommand( + String.Format( + "Update vb_user set membergroupids='{0}', displaygroupid={1} where userid={2}", + allGroups, partymembergroupid, accountId), + connection); + + command.ExecuteNonQuery(); + } } } - public void SetPartyNonmember (int accountId) + public void SetPartyNonmember(int accountId) { - using (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = new SqlCommand("PirateSetNonmember", connection); - command.CommandType = CommandType.StoredProcedure; + //TODO: Convert back to stored procedure + //var command = new MySqlCommand("PirateSetNonmember", connection); + //command.CommandType = CommandType.StoredProcedure; - command.Parameters.AddWithValue("@accountId", accountId); - command.ExecuteNonQuery(); + //command.Parameters.AddWithValue("@accountId", accountId); + //command.ExecuteNonQuery(); + + string allGroups = ","; + + 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 (allGroups.Contains("," + partymembergroupid + ",")) + { + allGroups = allGroups + .Replace(" ", "") + .Replace("," + partymembergroupid + ",", ",") + .Replace(",,", ",").Trim(','); + + command = + new MySqlCommand( + String.Format("Update vb_user set membergroupids='{0}',displaygroupid={1} where userid={2}", + allGroups, nonmembergroupid, accountId + ), + connection); + + command.ExecuteNonQuery(); + } } } - #endregion - #region Polls + #region Get Polls - public int GetPollIdFromTopicId (int topicId) + public int GetPollIdFromTopicId(int threadId) { - using (var connection = new SqlConnection(this.connectString)) + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand(String.Format("Select PollID from InstantForum_Polls where PostID=" + topicId), - connection); + MySqlCommand command = new MySqlCommand( + String.Format("Select pollid from vb_thread where threadid=" + threadId), + connection); - using (SqlDataReader reader = command.ExecuteReader()) + using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { @@ -380,46 +820,32 @@ namespace Swarmops.Logic.Special.Sweden } - public Dictionary GetPollVotes (int pollId) + public Dictionary GetPollVotes(int pollId) { - // First, let's get the list of alternatives. + //// First, let's get the list of alternatives. Dictionary pollAlternatives = GetPollAlternatives(pollId); - // Construct a comma-separated list of the answer IDs. - - var altStringBuilder = new StringBuilder(); - - foreach (int pollAlternativeId in pollAlternatives.Keys) - { - altStringBuilder.Append("," + pollAlternativeId); - } - - string altString = altStringBuilder.ToString().Substring(1); - - var result = new Dictionary(); - - using (var connection = new SqlConnection(this.connectString)) + Dictionary result = new Dictionary(); + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand( - String.Format( - "Select PollAnswerID,UserID from InstantForum_PollVotes WHERE PollAnswerId IN (" + altString + - ")"), connection); + MySqlCommand command = new MySqlCommand( + String.Format("Select userid, voteoption from pw_pollvote where pollid=" + pollId), + connection); - using (SqlDataReader reader = command.ExecuteReader()) + using (MySqlDataReader reader = command.ExecuteReader()) { int voteCount = 0; while (reader.Read()) { voteCount++; - int forumUserId = reader.GetInt32(1); + int forumUserId = reader.GetInt32(0); People people = People.FromOptionalData(ObjectOptionalDataType.ForumAccountId, - forumUserId.ToString()); + forumUserId.ToString()); if (people.Count > 1) { Person[] array = people.ToArray(); @@ -433,8 +859,11 @@ namespace Swarmops.Logic.Special.Sweden if (people.Count > 1) { + 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"); + ", appears to be tied to several personIds:" + ids); } } @@ -445,7 +874,11 @@ namespace Swarmops.Logic.Special.Sweden person = people[0]; } - int pollAnswerId = reader.GetInt32(0); + int pollAnswerId = reader.GetInt32(1); + pollAnswerId--; //One based + if (!pollAlternatives.ContainsKey(pollAnswerId)) + pollAlternatives[pollAnswerId] = "" + pollAnswerId; + string pollAnswer = pollAlternatives[pollAnswerId]; if (!result.ContainsKey(pollAnswer)) @@ -462,148 +895,134 @@ namespace Swarmops.Logic.Special.Sweden } - private Dictionary GetPollAlternatives (int pollId) + private Dictionary GetPollAlternatives(int pollId) { - var result = new Dictionary(); + Dictionary result = new Dictionary(); - using (var connection = new SqlConnection(this.connectString)) + //Förslag A |||Förslag B |||Förslag C |||Förslag D |||Förslag E |||Avstår + using (MySqlConnection connection = new MySqlConnection(this.connectString)) { connection.Open(); - var command = - new SqlCommand( - String.Format("Select PollAnswerID,AnswerText from InstantForum_PollAnswers WHERE PollId=" + - pollId), connection); - - using (SqlDataReader reader = command.ExecuteReader()) + MySqlCommand command = new MySqlCommand( + String.Format("Select options from pw_poll where pollid=" + pollId), + connection); + string options = ""; + using (MySqlDataReader reader = command.ExecuteReader()) { - while (reader.Read()) + if (reader.Read()) { - result[reader.GetInt32(0)] = reader.GetString(1); + options = reader.GetString(0); } + else - return result; + throw new ArgumentOutOfRangeException(); } + string[] results = options.Replace("|||", "\x12").Split('\x12'); + for (int i = 0; i < results.Length; ++i) + result[i] = results[i].Trim(); } + return result; } - #endregion #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 (forceForumId != 0) forumId = forceForumId; + // call to vBulletin plugin to add post + //key = special value secret key / selecting function to perform + //forumid = id:t för forumet, tex 49 + //userid = användarid:t, tex 3 + //title = trådtiteln, tex Hej + //pagetext = texten i inlägget, html och [b]bb-kod[/b] fungerar - using (var connection = new SqlConnection(this.connectString)) + if (this.forceForumId != 0) + forumId = this.forceForumId; + + string postTopicKey = Persistence.Key["ForumPostTopicKey"]; + string personAccountId = "" + poster.SwedishForumAccountId; + string url = "http://vBulletin.piratpartiet.se/"; + + try { - connection.Open(); +#pragma warning disable 618 + // ServicePointManager.CertificatePolicy is obsoleted, but is the only thing that works on both windows and mono. + //Needed to avoid errors from homegrown SSL cert. + ServicePointManager.CertificatePolicy = new ErrorIgnorerPolicy(); +#pragma warning restore 618 + HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url); + //string proxy = null; + Encoding recieverEncoding = Encoding.GetEncoding("iso-8859-1"); - // First, insert the post itself + 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)); - var command = new SqlCommand("if_sp_InsertPost", connection); - command.CommandType = CommandType.StoredProcedure; + byte[] buffer = recieverEncoding.GetBytes(data); //Forum was set up for Latin-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"); + req.Method = "POST"; + req.ContentType = "application/x-www-form-urlencoded"; + req.ContentLength = buffer.Length; - var parameterText = new SqlParameter("@strMessage", SqlDbType.NText, post.Length * 2 + 2048); - parameterText.Value = post; + //req.Proxy = new WebProxy(proxy, true); // ignore for local addresses - command.Parameters.Add(parameterText); + //req.CookieContainer = new CookieContainer(); // enable cookies - var parameterResult = new SqlParameter("@intIdentity", SqlDbType.Int, 4); - parameterResult.Direction = ParameterDirection.Output; + req.ServicePoint.Expect100Continue = false; //Disable stupid feature - command.Parameters.Add(parameterResult); + req.Headers.Add("Pragma", "no-cache"); - command.ExecuteNonQuery(); + Stream reqst = req.GetRequestStream(); // add form data to request stream - var postId = (int)parameterResult.Value; + reqst.Write(buffer, 0, buffer.Length); + reqst.Flush(); + reqst.Close(); - // Then, update the LastRead for this forum - command = new SqlCommand("if_sp_UpdateForumLastPostInformation", connection); - command.CommandType = CommandType.StoredProcedure; + HttpWebResponse res = (HttpWebResponse) req.GetResponse(); - 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)); + Stream resst = res.GetResponseStream(); + StreamReader sr = new StreamReader(resst); + string response = sr.ReadToEnd(); - command.ExecuteNonQuery(); - return postId; + int postId = 0; + if (int.TryParse(response, out postId)) + { + return postId; + } + throw new Exception("Error when calling CreateNewPost:" + response); } - } - #endregion - - public bool TestMode - { - get + catch (WebException ex) { - return forceForumId != 0; - } - set - { - if (value) - forceForumId = ForumIdTestPost; - else - forceForumId = 0; + throw new Exception("WebException when calling CreateNewPost:" + ex.Message); } } - } - - public class ErrorIgnorerPolicy : ICertificatePolicy - { - - public bool CheckValidationResult(ServicePoint sp, X509Certificate certificate, WebRequest request, int error) + private string UrlEncode(string toEncode) { - if (error == 0) - return true; - // only ask for trust failure (you may want to handle more cases) - if (error != -2146762486) - return false; + return HttpUtility.UrlEncode(toEncode, Encoding.GetEncoding("iso-8859-1")); + } + public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { return true; } - } - public class SwedishForumDatabaseVBulletin : IForumDatabase - { - const int ForumIdTestPost = 262; - private int forceForumId = 0; - // The cached values used by GetDatabase() - private static string CachedConnectionString; - private readonly string connectString = string.Empty; + #endregion - private readonly static int partymembergroupid = 16; - private readonly static int nonmembergroupid = 2; - - public SwedishForumDatabaseVBulletin (string connectString) - { - this.connectString = connectString; - } - - public static IForumDatabase GetDatabase (string connectionstring) + public static IForumDatabase GetDatabase(string connectionstring) { return new SwedishForumDatabaseVBulletin(connectionstring); } - public static IForumDatabase GetDatabase () + public static IForumDatabase GetDatabase() { // First, check if a previous invocation has put anything in the cashe. string ConnectionString = CachedConnectionString; @@ -631,7 +1050,6 @@ namespace Swarmops.Logic.Special.Sweden { ConnectionString = null; } - } // Now write the correct data to the cache, for faster lookup next time. @@ -642,464 +1060,5 @@ namespace Swarmops.Logic.Special.Sweden return new SwedishForumDatabaseVBulletin(CachedConnectionString); } - - - public int GetAccountId (string nick) - { - if (nick == null) - { - throw new ArgumentNullException("nick"); - } - - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var command = - 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); - } - else - { - throw new ArgumentException("No such nick in database"); - } - } - } - } - - - public string GetAccountName (int accountId) - { - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var command = - 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); - } - else - { - throw new ArgumentException("No such nick in database"); - } - } - } - } - - public int[] GetAccountList () - { - var result = new List(); - - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var command = new MySqlCommand(String.Format("Select userid from vb_user"), connection); - - using (MySqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - result.Add(reader.GetInt32(0)); - } - - return result.ToArray(); - } - } - } - - - #region Party Membership - public bool IsPartyMember (int accountId) - { - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var command = - new MySqlCommand( - String.Format("Select membergroupids from vb_user where userid=" + accountId), - connection); - - using (MySqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - string allGroups = ","; - - if (!reader.IsDBNull(0)) - allGroups += "" + reader.GetString(0).ToString() + ","; - - allGroups = allGroups.Replace(" ", ""); - - if (allGroups.Contains("," + partymembergroupid + ",")) - { - return true; - } - else - { - return false; - } - } - - throw new Exception("Account Id does not exist"); - } - } - } - - - public void SetPartyMember (int accountId) - { - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - //TODO: Convert back to stored procedure - //var command = new MySqlCommand("PirateSetMember", connection); - //command.CommandType = CommandType.StoredProcedure; - - //command.Parameters.AddWithValue("@accountId", accountId); - //command.ExecuteNonQuery(); - - string allGroups = ","; - - var 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).ToString() + ","; - } - } - - if (!allGroups.Contains("," + partymembergroupid + ",")) - { - allGroups = (allGroups - .Replace(" ", "") - .Replace(",,", ",") - .Trim(',') + "," + partymembergroupid).Trim(','); - - command = new MySqlCommand(String.Format("Update vb_user set membergroupids='{0}', displaygroupid={1} where userid={2}", - allGroups, partymembergroupid, accountId), - connection); - - command.ExecuteNonQuery(); - - } - } - } - - - public void SetPartyNonmember (int accountId) - { - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - //TODO: Convert back to stored procedure - //var command = new MySqlCommand("PirateSetNonmember", connection); - //command.CommandType = CommandType.StoredProcedure; - - //command.Parameters.AddWithValue("@accountId", accountId); - //command.ExecuteNonQuery(); - - string allGroups = ","; - - var 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).ToString() + ","; - } - } - - if (allGroups.Contains("," + partymembergroupid + ",")) - { - - allGroups = allGroups - .Replace(" ", "") - .Replace("," + partymembergroupid + ",", ",") - .Replace(",,", ",").Trim(','); - - command = new MySqlCommand(String.Format("Update vb_user set membergroupids='{0}',displaygroupid={1} where userid={2}", - allGroups, nonmembergroupid, accountId - ), - connection); - - command.ExecuteNonQuery(); - - } - } - } - - #endregion - - #region Get Polls - - public int GetPollIdFromTopicId (int threadId) - { - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var 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); - } - - throw new ArgumentOutOfRangeException(); - } - } - } - - - public Dictionary GetPollVotes (int pollId) - { - - //// First, let's get the list of alternatives. - - Dictionary pollAlternatives = GetPollAlternatives(pollId); - - var result = new Dictionary(); - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var command = new MySqlCommand( - String.Format("Select userid, voteoption from pw_pollvote where pollid=" + pollId), - connection); - - using (MySqlDataReader reader = command.ExecuteReader()) - { - int voteCount = 0; - - while (reader.Read()) - { - voteCount++; - int forumUserId = reader.GetInt32(0); - - People people = People.FromOptionalData(ObjectOptionalDataType.ForumAccountId, - forumUserId.ToString()); - if (people.Count > 1) - { - Person[] array = people.ToArray(); - foreach (Person testPerson in array) - { - if (testPerson.GetMemberships().Count == 0) - { - people.Remove(testPerson); - } - } - - if (people.Count > 1) - { - 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); - } - } - - Person person = null; - - if (people.Count > 0) - { - person = people[0]; - } - - int pollAnswerId = reader.GetInt32(1); - pollAnswerId--; //One based - if (!pollAlternatives.ContainsKey(pollAnswerId)) - pollAlternatives[pollAnswerId] = "" + pollAnswerId; - - string pollAnswer = pollAlternatives[pollAnswerId]; - - if (!result.ContainsKey(pollAnswer)) - { - result[pollAnswer] = new People(); - } - - result[pollAnswer].Add(person); - } - - return result; - } - } - } - - - private Dictionary GetPollAlternatives (int pollId) - { - var result = new Dictionary(); - - //Förslag A |||Förslag B |||Förslag C |||Förslag D |||Förslag E |||Avstår - using (var connection = new MySqlConnection(this.connectString)) - { - connection.Open(); - - var 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); - } - else - - throw new ArgumentOutOfRangeException(); - } - string[] results = options.Replace("|||", "\x12").Split('\x12'); - for (int i = 0; i < results.Length; ++i) - result[i] = results[i].Trim(); - } - return result; - } - - #endregion - - #region Create Post - private string UrlEncode (string toEncode) - { - return HttpUtility.UrlEncode(toEncode, Encoding.GetEncoding("iso-8859-1")); - } - - public static bool Validator (object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - return true; - } - - - 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 - //forumid = id:t för forumet, tex 49 - //userid = användarid:t, tex 3 - //title = trådtiteln, tex Hej - //pagetext = texten i inlägget, html och [b]bb-kod[/b] fungerar - - if (forceForumId != 0) - forumId = forceForumId; - - string postTopicKey = Persistence.Key["ForumPostTopicKey"]; - string personAccountId = "" + poster.SwedishForumAccountId; - string url = "http://vBulletin.piratpartiet.se/"; - - try - { -#pragma warning disable 618 - // ServicePointManager.CertificatePolicy is obsoleted, but is the only thing that works on both windows and mono. - //Needed to avoid errors from homegrown SSL cert. - ServicePointManager.CertificatePolicy = new ErrorIgnorerPolicy(); -#pragma warning restore 618 - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - //string proxy = null; - 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)); - - byte[] buffer = recieverEncoding.GetBytes(data);//Forum was set up for Latin-1 - - req.Method = "POST"; - req.ContentType = "application/x-www-form-urlencoded"; - req.ContentLength = buffer.Length; - - //req.Proxy = new WebProxy(proxy, true); // ignore for local addresses - - //req.CookieContainer = new CookieContainer(); // enable cookies - - req.ServicePoint.Expect100Continue = false; //Disable stupid feature - - req.Headers.Add("Pragma", "no-cache"); - - Stream reqst = req.GetRequestStream(); // add form data to request stream - - reqst.Write(buffer, 0, buffer.Length); - reqst.Flush(); - reqst.Close(); - - - HttpWebResponse res = (HttpWebResponse)req.GetResponse(); - - Stream resst = res.GetResponseStream(); - StreamReader sr = new StreamReader(resst); - string response = sr.ReadToEnd(); - - - int postId = 0; - if (int.TryParse(response, out postId)) - { - return postId; - } - else - { - throw new Exception("Error when calling CreateNewPost:" + response); - } - } - catch (WebException ex) - { - throw new Exception("WebException when calling CreateNewPost:" + ex.Message); - - } - } - - #endregion - - - - public bool TestMode - { - get - { - return forceForumId != 0; - } - set - { - if (value) - forceForumId = ForumIdTestPost; - else - forceForumId = 0; - } - } - - } - -} +} \ No newline at end of file diff --git a/Logic/Special/Sweden/SwedishForumHandleProvider.cs b/Logic/Special/Sweden/SwedishForumHandleProvider.cs index 692bb5fc..c0412f54 100644 --- a/Logic/Special/Sweden/SwedishForumHandleProvider.cs +++ b/Logic/Special/Sweden/SwedishForumHandleProvider.cs @@ -1,10 +1,7 @@ using System; using System.Diagnostics; using Swarmops.Basic.Enums; -using Swarmops.Basic.Exceptions; using Swarmops.Basic.Interfaces; -using Swarmops.Database; -using Swarmops.Logic.Structure; using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Special.Sweden @@ -14,7 +11,7 @@ namespace Swarmops.Logic.Special.Sweden { #region IHandleProvider Members - public string GetPersonHandle (int personId) + public string GetPersonHandle(int personId) { Person person = Person.FromIdentity(personId); @@ -27,8 +24,9 @@ namespace Swarmops.Logic.Special.Sweden } - public void SetPersonHandle (int personId, string newHandle) - { /* -- unused in Swarmops + public void SetPersonHandle(int personId, string newHandle) + { + /* -- unused in Swarmops Person person = Person.FromIdentity(personId); int newHandleAccountId = 0; @@ -74,14 +72,14 @@ namespace Swarmops.Logic.Special.Sweden 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."); } - public int GetPersonByHandle (string handle) + public int GetPersonByHandle(string handle) { throw new Exception("The method or operation is not implemented."); } diff --git a/Logic/Structure/Cities.cs b/Logic/Structure/Cities.cs index d1edff66..de5dae16 100644 --- a/Logic/Structure/Cities.cs +++ b/Logic/Structure/Cities.cs @@ -6,9 +6,9 @@ namespace Swarmops.Logic.Structure { public class Cities : List { - public static Cities FromArray (BasicCity[] array) + public static Cities FromArray(BasicCity[] array) { - var result = new Cities {Capacity = (array.Length*11/10)}; + Cities result = new Cities {Capacity = (array.Length*11/10)}; foreach (BasicCity basic in array) { @@ -19,29 +19,29 @@ namespace Swarmops.Logic.Structure } - public static Cities FromPostalCode (string postalCode, Country country) + public static Cities FromPostalCode(string postalCode, Country country) { 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); } - public static Cities FromPostalCode (string postalCode, int countryId) + public static Cities FromPostalCode(string postalCode, int countryId) { 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)); } - 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 32e41fe0..e418e79e 100644 --- a/Logic/Structure/City.cs +++ b/Logic/Structure/City.cs @@ -7,47 +7,47 @@ namespace Swarmops.Logic.Structure [Serializable] public class City : BasicCity { - private City (BasicCity 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. } - public static City FromIdentity (int cityId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetCity(cityId)); - } - public Geography Geography { get { return Geography.FromIdentity(GeographyId); } // TODO: Cache } - public static City FromBasic (BasicCity basic) + public static City FromIdentity(int cityId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetCity(cityId)); + } + + public static City FromBasic(BasicCity 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)); } - - public static City FromName (string cityName, string countryCode) + + public static City FromName(string cityName, string 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 City.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 13f316df..689128cc 100644 --- a/Logic/Structure/Countries.cs +++ b/Logic/Structure/Countries.cs @@ -6,19 +6,19 @@ namespace Swarmops.Logic.Structure { public class Countries : List { - public static Countries GetAll () + public static Countries GetAll() { return FromArray(SwarmDb.GetDatabaseForReading().GetAllCountries()); } - public static Countries GetInUse () + public static Countries GetInUse() { return FromArray(SwarmDb.GetDatabaseForReading().GetCountriesInUse()); } - public static Countries FromArray (BasicCountry[] basicArray) + public static Countries FromArray(BasicCountry[] basicArray) { - var result = new Countries {Capacity = (basicArray.Length*11/10)}; + Countries result = new Countries {Capacity = (basicArray.Length*11/10)}; foreach (BasicCountry basic in basicArray) { diff --git a/Logic/Structure/Country.cs b/Logic/Structure/Country.cs index ddc2bcca..fd0001f0 100644 --- a/Logic/Structure/Country.cs +++ b/Logic/Structure/Country.cs @@ -8,43 +8,42 @@ namespace Swarmops.Logic.Structure [Serializable] public class Country : BasicCountry { - private Country (BasicCountry 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 static Country FromBasic (BasicCountry basic) + public Geography Geography + { + get { return Geography.FromIdentity(GeographyId); } + } + + public Currency Currency + { + get { return Currency.FromIdentity(CurrencyId); } + } + + public static Country FromBasic(BasicCountry 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)); } - public static Country FromCode (string countryCode) + public static Country FromCode(string countryCode) { return FromBasic(SwarmDb.GetDatabaseForReading().GetCountry(countryCode)); } - - public Geography Geography - { - get { return Geography.FromIdentity(this.GeographyId); } - } - - public Currency Currency - { - get { return Financial.Currency.FromIdentity(this.CurrencyId); } - } - } } \ No newline at end of file diff --git a/Logic/Structure/Geographies.cs b/Logic/Structure/Geographies.cs index 3e5e345e..a5043203 100644 --- a/Logic/Structure/Geographies.cs +++ b/Logic/Structure/Geographies.cs @@ -12,11 +12,11 @@ namespace Swarmops.Logic.Structure { #region Creation and Construction - public static Geographies FromArray (BasicGeography[] basicArray) + public static Geographies FromArray(BasicGeography[] basicArray) { - var result = new Geographies(); + Geographies result = new Geographies(); - result.Capacity = basicArray.Length * 11 / 10; + result.Capacity = basicArray.Length*11/10; foreach (BasicGeography basic in basicArray) { result.Add(Geography.FromBasic(basic)); @@ -25,27 +25,27 @@ namespace Swarmops.Logic.Structure return result; } - public static Geographies FromSingle (Geography geography) + public static Geographies FromSingle(Geography geography) { - var result = new Geographies(); + Geographies result = new Geographies(); result.Add(geography); return result; } - public static Geographies FromIdentities (int[] geoIds) + public static Geographies FromIdentities(int[] 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); } - public static Geographies FromLevel (int countryId, GeographyLevel level) + public static Geographies FromLevel(int countryId, GeographyLevel level) { return FromIdentities(SwarmDb.GetDatabaseForReading().GetGeographyIdsFromLevel(countryId, level)); } @@ -76,22 +76,22 @@ namespace Swarmops.Logic.Structure /// - /// For every node in the list, pushes the node down in the tree to - /// at highest be "filterNode". For example, if World and Sweden was - /// passed with Europe as filterNode, Europe and Sweden would be - /// returned. + /// For every node in the list, pushes the node down in the tree to + /// at highest be "filterNode". For example, if World and Sweden was + /// passed with Europe as filterNode, Europe and Sweden would be + /// returned. /// /// The list of nodes. /// The highest node to return. /// The filtered list. - public Geographies FilterAbove (Geography topGeography) + public Geographies FilterAbove(Geography topGeography) { - var result = new Geographies(); + Geographies result = new Geographies(); // Build lookup Geographies filterLine = topGeography.GetLine(); - var lineLookup = new Dictionary(); + Dictionary lineLookup = new Dictionary(); foreach (Geography node in filterLine) { lineLookup[node.Identity] = true; @@ -117,9 +117,9 @@ namespace Swarmops.Logic.Structure } - public Geographies RemoveRedundant () + public Geographies RemoveRedundant() { - var remaining = new Dictionary(); + Dictionary remaining = new Dictionary(); foreach (Geography geo in this) { @@ -163,7 +163,7 @@ namespace Swarmops.Logic.Structure // Assemble result - var result = new Geographies(); + Geographies result = new Geographies(); foreach (int nodeId in remaining.Keys) { @@ -174,7 +174,7 @@ namespace Swarmops.Logic.Structure } - 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) @@ -191,7 +191,7 @@ namespace Swarmops.Logic.Structure // Build table, eliminating duplicates - var table = new Dictionary(); + Dictionary table = new Dictionary(); foreach (Geography geography in set1) { @@ -205,7 +205,7 @@ namespace Swarmops.Logic.Structure // Assemble result - var result = new Geographies(); + Geographies result = new Geographies(); foreach (Geography geography in table.Values) { @@ -215,57 +215,56 @@ namespace Swarmops.Logic.Structure return result; } - public Geographies LogicalOr (Geographies set2) + public Geographies LogicalOr(Geographies set2) { return LogicalOr(this, set2); } - public class HierSortOrder - { - internal HierSortOrder (int pOrder, int pLevel) - { - order = pOrder; - level = pLevel; - } - private int order; - private int level; - public int Level - { - get - { - return level; - } - } - public int Order - { - get - { - return order; - } - } - } - - static public Dictionary GetHierarchicalSortOrder () + public static Dictionary GetHierarchicalSortOrder() { Dictionary resultDictionary = new Dictionary(); BuildHierarchicalSortOrder(resultDictionary, Geography.Root, 0); return resultDictionary; } - static private void BuildHierarchicalSortOrder (Dictionary resultDictionary, Geography currentParent, int level) + 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.ToString() + ", " + currentParent.Name); + throw new Exception("Detected loop in Geographic data at geography id:" + currentParent.Identity + ", " + + currentParent.Name); } 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); } + + public class HierSortOrder + { + private readonly int level; + private readonly int order; + + internal HierSortOrder(int pOrder, int pLevel) + { + this.order = pOrder; + this.level = pLevel; + } + + public int Level + { + get { return this.level; } + } + + public int Order + { + get { return this.order; } + } + } } } \ No newline at end of file diff --git a/Logic/Structure/Geography.cs b/Logic/Structure/Geography.cs index 8368035e..2e501eed 100644 --- a/Logic/Structure/Geography.cs +++ b/Logic/Structure/Geography.cs @@ -12,33 +12,32 @@ namespace Swarmops.Logic.Structure [Serializable] public class Geography : BasicGeography, ITreeNode, ITreeNodeObject { - #region Construction and Creation - private Geography () + private Geography() : base(0, 0, string.Empty) { // private ctor prevents construction } - private Geography (BasicGeography 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); } - public static Geography FromIdentity (int geographyId) + public static Geography FromIdentity(int 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 @@ -47,48 +46,20 @@ namespace Swarmops.Logic.Structure } - 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); } - 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, - designation)); + designation)); } #endregion - public Geographies Children - { - get - { - return Geographies.FromArray(GeographyCache.GetGeographyChildren(Identity)); - } - } - - public int ChildrenCount - { - get - { - return GeographyCache.CountGeographyChildren(Identity); - } - } - - - public static Geography Root - { - get { return FromIdentity(RootIdentity); } - } - - public Geography Parent - { - get { return FromIdentity(ParentIdentity); } - } - - public static readonly int RootIdentity = 1; // The identity of the root geography (i.e., "World") public static readonly int SwedenId = 30; @@ -109,15 +80,15 @@ namespace Swarmops.Logic.Structure get { return Children.Identities; } } - [XmlIgnore] // interface cannot be serialized - [SoapIgnore] + [XmlIgnore] // interface cannot be serialized + [SoapIgnore] public ITreeNodeObject ParentObject { - get { return this.Parent; } + get { return Parent; } } [XmlIgnore] // interface cannot be serialized - [SoapIgnore] + [SoapIgnore] public List ChildObjects { get @@ -131,24 +102,45 @@ namespace Swarmops.Logic.Structure #endregion - public Geographies GetTree () + public Geographies Children + { + get { return Geographies.FromArray(GeographyCache.GetGeographyChildren(Identity)); } + } + + public int ChildrenCount + { + get { return GeographyCache.CountGeographyChildren(Identity); } + } + + + public static Geography Root + { + get { return FromIdentity(RootIdentity); } + } + + public Geography Parent + { + get { return FromIdentity(ParentIdentity); } + } + + public Geographies GetTree() { return Geographies.FromArray(GeographyCache.GetGeographyTree(Identity)); // return Geographies.FromArray(SwarmDb.GetDatabaseForReading().GetGeographyTree(Identity)); } - public Geographies GetLine () + public Geographies GetLine() { 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); } - public bool Inherits (int prospectiveParentGeographyId) + public bool Inherits(int prospectiveParentGeographyId) { // Returns true if prospectiveParent is a parent of ours. @@ -166,7 +158,7 @@ namespace Swarmops.Logic.Structure } - public bool AtLevel (GeographyLevel level) + public bool AtLevel(GeographyLevel level) { GeographyLevel[] levels = SwarmDb.GetDatabaseForReading().GetGeographyLevelsAtGeographyId(Identity); @@ -181,7 +173,7 @@ namespace Swarmops.Logic.Structure return false; } - public BasicGeographyDesignation[] GetGeographyDesignations () + public BasicGeographyDesignation[] GetGeographyDesignations() { return SwarmDb.GetDatabaseForReading().GetGeographyDesignationsForGeographyId(Identity); } diff --git a/Logic/Structure/GeographyBar.cs b/Logic/Structure/GeographyBar.cs index 3e58044a..a8c051b2 100644 --- a/Logic/Structure/GeographyBar.cs +++ b/Logic/Structure/GeographyBar.cs @@ -10,9 +10,9 @@ namespace Swarmops.Logic.Structure #region IComparable Members - public int CompareTo (object obj) + public int CompareTo(object obj) { - var otherBar = (GeographyBar) obj; + GeographyBar otherBar = (GeographyBar) obj; return this.Value.CompareTo(otherBar.Value); } diff --git a/Logic/Structure/GeographyStatistics.cs b/Logic/Structure/GeographyStatistics.cs index 94bb83c4..014b4449 100644 --- a/Logic/Structure/GeographyStatistics.cs +++ b/Logic/Structure/GeographyStatistics.cs @@ -19,21 +19,21 @@ 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(); - var result = new GeographyStatistics(); + GeographyStatistics result = new GeographyStatistics(); // Step 1 - tally the leaf nodes foreach (int geographyId in voterCounts.Keys) { - var dataPoint = new GeographyDataPoint - { - GeographyName = Geography.FromIdentity(geographyId).Name, - GeographyId = geographyId, - VoterCount = voterCounts[geographyId] - }; + GeographyDataPoint dataPoint = new GeographyDataPoint + { + GeographyName = Geography.FromIdentity(geographyId).Name, + GeographyId = geographyId, + VoterCount = voterCounts[geographyId] + }; result[geographyId] = dataPoint; } @@ -94,7 +94,7 @@ namespace Swarmops.Logic.Structure { Geographies localTree = geography.GetTree(); int voterCount = 0; - var tempOrgData = new GeographyOrganizationDataPoint[2]; // HACK + GeographyOrganizationDataPoint[] tempOrgData = new GeographyOrganizationDataPoint[2]; // HACK tempOrgData[0] = new GeographyOrganizationDataPoint(); tempOrgData[1] = new GeographyOrganizationDataPoint(); @@ -130,10 +130,10 @@ namespace Swarmops.Logic.Structure if (!result.ContainsKey(geography.Identity)) { result[geography.Identity] = new GeographyDataPoint - { - GeographyId = geography.Identity, - GeographyName = geography.Name - }; + { + GeographyId = geography.Identity, + GeographyName = geography.Name + }; } // Save our temp values to the processed node. @@ -164,11 +164,11 @@ namespace Swarmops.Logic.Structure return result; } - public static GeographyStatistics FromXml (string xml) + public static GeographyStatistics FromXml(string xml) { GeographyStatisticsSerializable serializable = GeographyStatisticsSerializable.FromXml(xml); - var result = new GeographyStatistics(); + GeographyStatistics result = new GeographyStatistics(); foreach (GeographyDataPoint dataPoint in serializable) { @@ -184,7 +184,7 @@ namespace Swarmops.Logic.Structure { // Serialize through a GeographyStatisticsSerializable. - var serializable = new GeographyStatisticsSerializable(); + GeographyStatisticsSerializable serializable = new GeographyStatisticsSerializable(); foreach (GeographyDataPoint dataPoint in Values) { @@ -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) { - var serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); + XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); byte[] xmlBytes = Encoding.Default.GetBytes(xml); stream.Write(xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - var result = (GeographyStatisticsSerializable) serializer.Deserialize(stream); + GeographyStatisticsSerializable result = (GeographyStatisticsSerializable) serializer.Deserialize(stream); stream.Close(); return result; @@ -217,9 +217,9 @@ namespace Swarmops.Logic.Structure public string ToXml() { - var serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); + XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsSerializable)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, this); byte[] xmlBytes = stream.GetBuffer(); diff --git a/Logic/Structure/GeographyStatisticsOverTime.cs b/Logic/Structure/GeographyStatisticsOverTime.cs index d32c3e63..cd70504a 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) { - var serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); + XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); byte[] xmlBytes = Encoding.Default.GetBytes(xml); stream.Write(xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - var result = (GeographyStatisticsOverTime) serializer.Deserialize(stream); + GeographyStatisticsOverTime result = (GeographyStatisticsOverTime) serializer.Deserialize(stream); stream.Close(); return result; @@ -25,9 +25,9 @@ namespace Swarmops.Logic.Structure public string ToXml() { - var serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); + XmlSerializer serializer = new XmlSerializer(typeof (GeographyStatisticsOverTime)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, this); byte[] xmlBytes = stream.GetBuffer(); diff --git a/Logic/Structure/GeographyWithPeople.cs b/Logic/Structure/GeographyWithPeople.cs index 5e609b66..22c7cc1d 100644 --- a/Logic/Structure/GeographyWithPeople.cs +++ b/Logic/Structure/GeographyWithPeople.cs @@ -3,18 +3,16 @@ using System; namespace Swarmops.Logic.Structure { [Serializable] - public class GeographyWithPeople + public class GeographyWithPeople { - - + public int ActivistCount; public int GeographyID; - public int OrgId=0; + public string LeadContent; + public int MemberCount; public string Name; + public int OrgId = 0; public int ParentGeographyId; - public int MemberCount; - public int ActivistCount; - public string LeadContent; public string SecondsContent; @@ -22,6 +20,5 @@ namespace Swarmops.Logic.Structure { get { return 1; } // The identity of the root geography (i.e., "World") } - } } \ No newline at end of file diff --git a/Logic/Structure/Organization.cs b/Logic/Structure/Organization.cs index f5bef0cb..0f95b2f1 100644 --- a/Logic/Structure/Organization.cs +++ b/Logic/Structure/Organization.cs @@ -21,31 +21,31 @@ namespace Swarmops.Logic.Structure #region Creation and Construction // ReSharper disable UnusedPrivateMember - protected Organization () - // ReSharper restore UnusedPrivateMember + protected Organization() + // ReSharper restore UnusedPrivateMember { } // disallow public direct construction - private Organization (BasicOrganization basic) + private Organization(BasicOrganization basic) : base(basic) { } - protected Organization (Organization org) + protected Organization(Organization org) : base(org) { } public static Organization FromIdentity(int identity) { - return FromBasic(OrganizationCache.GetOrganization(identity)); //return FromBasic(SwarmDb.GetDatabaseForReading().GetOrganization(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) @@ -55,83 +55,237 @@ namespace Swarmops.Logic.Structure #endregion - private ObjectOptionalData _optionalData = null; + private ObjectOptionalData _optionalData; + + private Geography anchorGeography; + private string mailPrefixInherited; + + #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; + + public static Organization Sandbox + { + get { return FromIdentity(SandboxIdentity); } + } + + public static int SandboxIdentity + { + get + { + if (FromIdentity(1).Name.StartsWith("Sandbox")) + { + return 1; + } + if (FromIdentity(3).Name.StartsWith("Sandbox")) + { + return 3; + } + + throw new InvalidOperationException("Cannot locate Sandbox organization's identity"); + } + } + + + [Obsolete("This should never be used anymore!", true)] + public static Organization PPSE + { + get { return FromIdentity(PPSEid); } + } + + #endregion + + #region IComparable Members + + public int CompareTo(object obj) + { + Organization org2 = obj as Organization; + + if (org2 == null) + { + return 0; // undefined + } + + if (org2.CatchAll && !CatchAll) + { + return -1; + } + + if (!org2.CatchAll && CatchAll) + { + return 1; + } + + // TODO: Read culture from organization's default country instead of hardcoding like this + + return String.Compare(Name, org2.Name, true, new CultureInfo("sv-SE")); + } + + #endregion + + #region ITreeNode Members + + public int ParentIdentity + { + get { return ParentOrganizationId; } + } + + + public int[] ChildrenIdentities + { + get { return Children.Identities; } + } + + public ITreeNodeObject ParentObject + { + get { return Parent; } + } + + public List ChildObjects + { + get + { + List retVal = new List(); + foreach (Organization child in Children) + retVal.Add(child); + return retVal; + } + } + + #endregion + private ObjectOptionalData OptionalData { get { - if (_optionalData == null) + if (this._optionalData == null) { - Organization o = (Organization)this; - _optionalData = ObjectOptionalData.ForObject(o); //Added cast, otherwise it fails for subclasses + Organization o = this; + this._optionalData = ObjectOptionalData.ForObject(o); + //Added cast, otherwise it fails for subclasses } - return _optionalData; + return this._optionalData; } } + public Organization Parent + { + get { return OrganizationCache.FromCache(ParentIdentity); } + } + + public Organizations Children + { + get { return Organizations.FromArray(OrganizationCache.GetOrganizationChildren(Identity)); } + } + + + public OrganizationFinancialAccounts FinancialAccounts + { + get { return new OrganizationFinancialAccounts(Identity); } + } + + public FinancialAccounts FinancialAccountsExternal + { + get + { + // HACK: MUST FETCH THIS FROM ACTUAL ACCOUNTS + // HACK HACK HACK HACK HACK HACK + + if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE) && OrganizationId == 1) + { + FinancialAccounts result = new FinancialAccounts(); + result.Add(FinancialAccount.FromIdentity(1)); + result.Add(FinancialAccount.FromIdentity(2)); + + return result; + } + if (PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && OrganizationId == 7) + { + FinancialAccounts result = new FinancialAccounts(); + result.Add(FinancialAccount.FromIdentity(29)); + + return result; + } + + throw new NotImplementedException(); + } + } + + + public OrganizationParameters Parameters + { + get { return new OrganizationParameters(this); } + } + + + public string IncomingPaymentTag + { + // HACK: REmove this property altogether - should be per account + get { return "bg 451-0061 "; } // TODO: Per organization, of course + } + + + public People ValidatingPeople + { + get + { + People result = new People(); + + // HACK: this gets the TEMPORARY list + + string peopleIdstring = Parameters.TemporaryAccessListWrite; + string[] peopleIds = peopleIdstring.Split(' '); + + foreach (string peopleId in peopleIds) + { + result.Add(Person.FromIdentity(Int32.Parse(peopleId))); + } + + return result; + } + } + + public string RegularLabel + { + get + { + string optionalData = OptionalData[ObjectOptionalDataType.OrgRegularLabel]; + if (string.IsNullOrEmpty(optionalData)) + { + RegularLabel = "Member"; + return "Member"; // Legacy + } + + return optionalData; + } + set { OptionalData[ObjectOptionalDataType.OrgRegularLabel] = value; } + } + + public string ActivistLabel + { + get + { + string optionalData = OptionalData[ObjectOptionalDataType.OrgActivistLabel]; + if (string.IsNullOrEmpty(optionalData)) + { + ActivistLabel = "Activist"; + return "Activist"; + } + + return optionalData; + } + set { OptionalData[ObjectOptionalDataType.OrgActivistLabel] = value; } + } #region Public methods - public bool IsOrInherits (Organization prospectiveParent) - { - if (this.Identity == prospectiveParent.Identity) - return true; - return Inherits(prospectiveParent.Identity); - } - - public bool Inherits (Organization prospectiveParent) - { - return Inherits(prospectiveParent.Identity); - } - - public bool IsOrInherits (int prospectiveParentOrganizationId) - { - if (this.Identity == prospectiveParentOrganizationId) - return true; - return Inherits(prospectiveParentOrganizationId); - } - - public bool Inherits (int prospectiveParentOrganizationId) - { - // Returns true if prospectiveParent is a parent of ours. - - Organizations line = GetLine(); - - for (int index = 0; index < line.Count - 1; index++) - { - if (line[index].Identity == prospectiveParentOrganizationId) - { - return true; - } - } - - return false; - } - - public Organizations GetLine () - { - 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(SwarmDb.GetDatabaseForReading().GetOrganizationTree(Identity)); - } - - public int GetMemberCount () - { - return Memberships.GetMemberCountForOrganization(this); - } - - public NewsletterFeeds GetNewsletterFeeds () - { - return NewsletterFeeds.FromArray(SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForOrganization(Identity)); - } - - public bool IsEconomyEnabled { get { return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled); } @@ -143,24 +297,25 @@ namespace Swarmops.Logic.Structure { if (!IsEconomyEnabled) { - throw new InvalidOperationException("Cannot request first fiscal year; organization is not economy-enabled"); + throw new InvalidOperationException( + "Cannot request first fiscal year; organization is not economy-enabled"); } int year = Parameters.FirstFiscalYear; if (year < 2000) { - if (this.Identity == 1 && this.Name.StartsWith("Piratpartiet")) + if (Identity == 1 && Name.StartsWith("Piratpartiet")) { OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2009); year = 2009; } - else if (this.Identity == 7 && this.Name.StartsWith("Europirate Acad")) + else if (Identity == 7 && Name.StartsWith("Europirate Acad")) { OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2012); year = 2012; } - else if (this.Identity == 1 && this.Name.StartsWith("Sandbox")) + else if (Identity == 1 && Name.StartsWith("Sandbox")) { OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, 2012); year = 2012; @@ -184,13 +339,13 @@ namespace Swarmops.Logic.Structure if (string.IsNullOrEmpty(currencyCode)) { - if (this.Identity == 1 && (this.Name.StartsWith("Piratpartiet") || this.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"); currencyCode = "SEK"; } - if (this.Identity == 2 && (this.Name.StartsWith("European"))) + if (Identity == 2 && (Name.StartsWith("European"))) { OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgCurrency, "SEK"); currencyCode = "SEK"; @@ -201,6 +356,66 @@ namespace Swarmops.Logic.Structure } } + public bool IsOrInherits(Organization prospectiveParent) + { + if (Identity == prospectiveParent.Identity) + return true; + return Inherits(prospectiveParent.Identity); + } + + public bool Inherits(Organization prospectiveParent) + { + return Inherits(prospectiveParent.Identity); + } + + public bool IsOrInherits(int prospectiveParentOrganizationId) + { + if (Identity == prospectiveParentOrganizationId) + return true; + return Inherits(prospectiveParentOrganizationId); + } + + public bool Inherits(int prospectiveParentOrganizationId) + { + // Returns true if prospectiveParent is a parent of ours. + + Organizations line = GetLine(); + + for (int index = 0; index < line.Count - 1; index++) + { + if (line[index].Identity == prospectiveParentOrganizationId) + { + return true; + } + } + + return false; + } + + public Organizations GetLine() + { + 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(SwarmDb.GetDatabaseForReading().GetOrganizationTree(Identity)); + } + + public int GetMemberCount() + { + return Memberships.GetMemberCountForOrganization(this); + } + + public NewsletterFeeds GetNewsletterFeeds() + { + return NewsletterFeeds.FromArray(SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForOrganization(Identity)); + } + + public void EnableEconomy(Currency currency) { if (IsEconomyEnabled) @@ -267,7 +482,7 @@ namespace Swarmops.Logic.Structure // Finally, create the first conference parent FinancialAccount conferenceBase = FinancialAccount.Create(this, "Conferences", - FinancialAccountType.Cost, null); + FinancialAccountType.Cost, null); conferenceBase.IsConferenceParent = true; // Set the currency @@ -276,32 +491,28 @@ namespace Swarmops.Logic.Structure // Set current year to first fiscal year - this.OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, DateTime.Today.Year); + OptionalData.SetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear, DateTime.Today.Year); // Finally, flag the org as enabled - this.OptionalData.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); + OptionalData.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); } - #endregion #region Public properties - /// - /// The purpose of this property is to hide the base property from the Organization object. - /// DefaultCountry should be used instead. - /// - /// Wich has been disabled because we need to be able to update it... /JL - /// - /// //protected new int DefaultCountryId //{ // get { return base.DefaultCountryId; } //} - /// - /// Gets the default country for this organization. + /// The purpose of this property is to hide the base property from the Organization object. + /// DefaultCountry should be used instead. + /// Wich has been disabled because we need to be able to update it... /JL + /// + /// + /// Gets the default country for this organization. /// public Country DefaultCountry { @@ -316,7 +527,7 @@ namespace Swarmops.Logic.Structure } /// - /// Gets true if this is a fallback organization allocation (like UP Piratnätet). + /// Gets true if this is a fallback organization allocation (like UP Piratnätet). /// public bool CatchAll { @@ -334,8 +545,8 @@ namespace Swarmops.Logic.Structure } /// - /// Gets the mail prefix for this organization. If there is none, - /// traverses the hierarchy upward until one is found. + /// Gets the mail prefix for this organization. If there is none, + /// traverses the hierarchy upward until one is found. /// public string MailPrefixInherited // Cached { @@ -379,30 +590,11 @@ namespace Swarmops.Logic.Structure return this.anchorGeography; } } + #endregion #region UptakeGeographies - public void AddUptakeGeography (Geography geo) - { - AddUptakeGeography(geo.Identity); - } - - public void DeleteUptakeGeography (Geography geo) - { - DeleteUptakeGeography(geo.Identity); - } - - public void AddUptakeGeography (int geoId) - { - OrganizationCache.AddOrgUptakeGeography(this.Identity, geoId); - } - - public void DeleteUptakeGeography (int geoId) - { - OrganizationCache.DeleteOrgUptakeGeography(this.Identity, geoId); - } - private List uptakeGeographies; public ReadOnlyCollection UptakeGeographies @@ -412,16 +604,38 @@ 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 UptakeGeography[] GetUptakeGeographies (bool others) + public void AddUptakeGeography(Geography geo) { - BasicUptakeGeography[] basics = SwarmDb.GetDatabaseForReading().GetOrganizationUptakeGeographies(Identity, others); + AddUptakeGeography(geo.Identity); + } + + public void DeleteUptakeGeography(Geography geo) + { + DeleteUptakeGeography(geo.Identity); + } + + public void AddUptakeGeography(int geoId) + { + OrganizationCache.AddOrgUptakeGeography(Identity, geoId); + } + + public void DeleteUptakeGeography(int geoId) + { + OrganizationCache.DeleteOrgUptakeGeography(Identity, geoId); + } + + public UptakeGeography[] GetUptakeGeographies(bool others) + { + BasicUptakeGeography[] basics = SwarmDb.GetDatabaseForReading() + .GetOrganizationUptakeGeographies(Identity, others); List retVal = new List(); foreach (BasicUptakeGeography b in basics) { @@ -456,12 +670,9 @@ namespace Swarmops.Logic.Structure } }*/ } - else - { - 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(); } @@ -470,109 +681,109 @@ namespace Swarmops.Logic.Structure #region FunctionalMailAddresses - private Dictionary functionalMailDict = null; + private Dictionary functionalMailDict; - public FunctionalMail.AddressItem GetFunctionalMailAddressInh (MailAuthorType authorType) + public FunctionalMail.AddressItem GetFunctionalMailAddressInh(MailAuthorType authorType) { LoadFunctionalMailAddress(); - if (functionalMailDict.ContainsKey(authorType)) - return functionalMailDict[authorType]; - else - { - if (this.ParentIdentity != 0) - return this.Parent.GetFunctionalMailAddressInh(authorType); - else if (FunctionalMail.Address.ContainsKey(authorType)) - return FunctionalMail.Address[authorType];// Default. - else - return null; - } + if (this.functionalMailDict.ContainsKey(authorType)) + return this.functionalMailDict[authorType]; + if (this.ParentIdentity != 0) + return this.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 (functionalMailDict.ContainsKey(authorType)) - return functionalMailDict[authorType]; - else - { - return null; - } + if (this.functionalMailDict.ContainsKey(authorType)) + return this.functionalMailDict[authorType]; + return null; } - private void LoadFunctionalMailAddress () + private void LoadFunctionalMailAddress() { - if (functionalMailDict == null) + if (this.functionalMailDict == null) { - functionalMailDict = new Dictionary(); + this.functionalMailDict = new Dictionary(); string funcMails = OptionalData.GetOptionalDataString(ObjectOptionalDataType.OrgFunctionalMail); - string[] rows = funcMails.Replace("\r", "\n").Replace("\n\n", "\n").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); + string[] rows = funcMails.Replace("\r", "\n") + .Replace("\n\n", "\n") + .Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries); - Regex reSplitAddress = new Regex(@"^(?.+?):(?.+)[,;:]\s*(?
\S+?@\S+?)$", RegexOptions.IgnoreCase); + Regex reSplitAddress = new Regex(@"^(?.+?):(?.+)[,;:]\s*(?
\S+?@\S+?)$", + RegexOptions.IgnoreCase); foreach (string row in rows) { Match match = reSplitAddress.Match(row); try { - MailAuthorType maType = (MailAuthorType)Enum.Parse(typeof(MailAuthorType), match.Groups["Type"].Value); + MailAuthorType maType = + (MailAuthorType) Enum.Parse(typeof (MailAuthorType), match.Groups["Type"].Value); string name = match.Groups["Name"].Value; string address = match.Groups["Address"].Value; - functionalMailDict[maType] = new FunctionalMail.AddressItem(address, name); + this.functionalMailDict[maType] = new FunctionalMail.AddressItem(address, name); + } + catch + { } - catch { } } } } - public void SetFunctionalMailAddress (MailAuthorType authorType, string name, string email) + public void SetFunctionalMailAddress(MailAuthorType authorType, string name, string email) { if (string.IsNullOrEmpty(email.Trim())) { - functionalMailDict.Remove(authorType); + this.functionalMailDict.Remove(authorType); } else { - functionalMailDict[authorType] = new FunctionalMail.AddressItem(email, name); + this.functionalMailDict[authorType] = new FunctionalMail.AddressItem(email, name); } SaveFunctionalMailDict(); } - private void SaveFunctionalMailDict () + private void SaveFunctionalMailDict() { StringBuilder sb = new StringBuilder(); - foreach (MailAuthorType ma in functionalMailDict.Keys) + foreach (MailAuthorType ma in this.functionalMailDict.Keys) { - sb.AppendFormat("{0}:{1};{2}\r\n", ma.ToString(), functionalMailDict[ma].Name, functionalMailDict[ma].Email); + sb.AppendFormat("{0}:{1};{2}\r\n", ma, this.functionalMailDict[ma].Name, + this.functionalMailDict[ma].Email); } OptionalData.SetOptionalDataString(ObjectOptionalDataType.OrgFunctionalMail, sb.ToString()); } + #endregion #region ShowNamesInNotifications + public bool ShowNamesInNotificationsInh { get { if (OptionalData.HasData(ObjectOptionalDataType.OrgShowNamesInNotifications)) return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); - else if (this.ParentIdentity != 0) + if (this.ParentIdentity != 0) return this.Parent.ShowNamesInNotificationsInh; - else - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); + return this.OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); } } - public Nullable ShowNamesInNotifications + public bool? ShowNamesInNotifications { get { if (OptionalData.HasData(ObjectOptionalDataType.OrgShowNamesInNotifications)) return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgShowNamesInNotifications); - else - return null; + return null; } set { @@ -586,29 +797,30 @@ namespace Swarmops.Logic.Structure } } } + #endregion + #region UsePaymentStatus + public bool UsePaymentStatusInh { get { if (OptionalData.HasData(ObjectOptionalDataType.OrgUsePaymentStatus)) return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); - else if (this.ParentIdentity != 0) + if (this.ParentIdentity != 0) return this.Parent.UsePaymentStatusInh; - else - return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); + return this.OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); } } - public Nullable UsePaymentStatus + public bool? UsePaymentStatus { get { if (OptionalData.HasData(ObjectOptionalDataType.OrgUsePaymentStatus)) return OptionalData.GetOptionalDataBool(ObjectOptionalDataType.OrgUsePaymentStatus); - else - return null; + return null; } set { @@ -622,142 +834,15 @@ namespace Swarmops.Logic.Structure } } } - #endregion - - private Geography anchorGeography; - private string mailPrefixInherited; - - - #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; - - public static Organization Sandbox - { - get { return FromIdentity(SandboxIdentity); } - } - - public static int SandboxIdentity - { - get - { - if (Organization.FromIdentity(1).Name.StartsWith("Sandbox")) - { - return 1; - } - else if (Organization.FromIdentity(3).Name.StartsWith("Sandbox")) - { - return 3; - } - - throw new InvalidOperationException("Cannot locate Sandbox organization's identity"); - } - } - - - [Obsolete ("This should never be used anymore!", true)] - public static Organization PPSE - { - get { return Organization.FromIdentity(Organization.PPSEid); } - } #endregion - #region IComparable Members - - public int CompareTo (object obj) - { - var org2 = obj as Organization; - - if (org2 == null) - { - return 0; // undefined - } - - if (org2.CatchAll && !this.CatchAll) - { - return -1; - } - - if (!org2.CatchAll && this.CatchAll) - { - return 1; - } - - // TODO: Read culture from organization's default country instead of hardcoding like this - - return String.Compare(Name, org2.Name, true, new CultureInfo("sv-SE")); - } - - #endregion - - #region ITreeNode Members - - public int ParentIdentity - { - get { return ParentOrganizationId; } - } - - - public int[] ChildrenIdentities - { - get { return Children.Identities; } - } - - public ITreeNodeObject ParentObject - { - get { return this.Parent; } - } - - public List ChildObjects - { - get - { - List retVal = new List(); - foreach (Organization child in Children) - retVal.Add(child); - return retVal; - } - } - - #endregion - - public Organization Parent - { - get - { - return OrganizationCache.FromCache(ParentIdentity); - } - } - - public Organizations Children - { - get - { - return Organizations.FromArray(OrganizationCache.GetOrganizationChildren(Identity)); - } - } - - public Person GetTreasurer () + public Person GetTreasurer() { Organizations line = GetLine(); BasicPersonRole[] treasurers - = SwarmDb.GetDatabaseForReading().GetPeopleWithRoleType(RoleType.OrganizationTreasurer, line.Identities, new int[] { }); + = SwarmDb.GetDatabaseForReading() + .GetPeopleWithRoleType(RoleType.OrganizationTreasurer, line.Identities, new int[] {}); if (treasurers.Length == 0) throw new Exception("No Treasurer Found"); @@ -780,174 +865,70 @@ namespace Swarmops.Logic.Structure } - public Memberships GetMemberships (bool includeTerminated) + public Memberships GetMemberships(bool includeTerminated) { return Memberships.ForOrganization(this, includeTerminated); } - public Memberships GetMemberships () + public Memberships GetMemberships() { return GetMemberships(false); } - - public OrganizationFinancialAccounts FinancialAccounts - { - get - { - return new OrganizationFinancialAccounts(this.Identity); - } - } - - public FinancialAccounts FinancialAccountsExternal - { - get - { - // HACK: MUST FETCH THIS FROM ACTUAL ACCOUNTS - // HACK HACK HACK HACK HACK HACK - - if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE) && this.OrganizationId == 1) - { - FinancialAccounts result = new FinancialAccounts(); - result.Add(FinancialAccount.FromIdentity(1)); - result.Add(FinancialAccount.FromIdentity(2)); - - return result; - } - else if (PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && this.OrganizationId == 7) - { - FinancialAccounts result = new FinancialAccounts(); - result.Add(FinancialAccount.FromIdentity(29)); - - return result; - } - - throw new NotImplementedException(); - } - } - - - public static Organization Create (int parentOrganizationId, string nameInternational, string name, string nameShort, string domain, string mailPrefix, int anchorGeographyId, bool acceptsMembers, bool autoAssignNewMembers, int defaultCountryId) + 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, - nameInternational, - name, - nameShort, - domain, - mailPrefix, - anchorGeographyId, - acceptsMembers, - autoAssignNewMembers, - defaultCountryId)); + nameInternational, + name, + nameShort, + domain, + mailPrefix, + anchorGeographyId, + acceptsMembers, + autoAssignNewMembers, + defaultCountryId)); } [Obsolete("Never use this function. Mark the organization as unused. Records are needed for history.", true)] - public void Delete () + public void Delete() { string problems = ""; - int ChildrenCount = this.Children.Count; - int ActiveMembershipsCount = this.GetMemberships(false).Count; - int HistoricalMembershipsCount = this.GetMemberships(true).Count - ActiveMembershipsCount; + int ChildrenCount = Children.Count; + int ActiveMembershipsCount = GetMemberships(false).Count; + int HistoricalMembershipsCount = GetMemberships(true).Count - ActiveMembershipsCount; if (ChildrenCount > 0) - problems += ChildrenCount.ToString() + " child organisations\n\r"; + problems += ChildrenCount + " child organisations\n\r"; if (ActiveMembershipsCount > 0) - problems += ActiveMembershipsCount.ToString() + " active memberships\n\r"; + problems += ActiveMembershipsCount + " active memberships\n\r"; if (HistoricalMembershipsCount > 0) - problems += HistoricalMembershipsCount.ToString() + " historical memberships\n\r"; + problems += HistoricalMembershipsCount + " historical memberships\n\r"; if (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, - string NameShort, string Domain, string MailPrefix, int AnchorGeographyId, bool AcceptsMembers, - bool AutoAssignNewMembers, int DefaultCountryId, int OrganizationId) + 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, MailPrefix, AnchorGeographyId, AcceptsMembers, AutoAssignNewMembers, DefaultCountryId, OrganizationId); } - - public OrganizationParameters Parameters - { - get { return new OrganizationParameters(this); } - } - - - public string IncomingPaymentTag - { - // HACK: REmove this property altogether - should be per account - get { return "bg 451-0061 "; } // TODO: Per organization, of course - } - - 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); } - - - - public People ValidatingPeople - { - get - { - People result = new People(); - - // HACK: this gets the TEMPORARY list - - string peopleIdstring = Parameters.TemporaryAccessListWrite; - string[] peopleIds = peopleIdstring.Split(' '); - - foreach (string peopleId in peopleIds) - { - result.Add(Person.FromIdentity(Int32.Parse(peopleId))); - } - - return result; - } - } - - public string RegularLabel - { - get - { - string optionalData = OptionalData[ObjectOptionalDataType.OrgRegularLabel]; - if (string.IsNullOrEmpty(optionalData)) - { - this.RegularLabel = "Member"; - return "Member"; // Legacy - } - - return optionalData; - } - set { OptionalData[ObjectOptionalDataType.OrgRegularLabel] = value; } - } - - public string ActivistLabel - { - get - { - string optionalData = OptionalData[ObjectOptionalDataType.OrgActivistLabel]; - if (string.IsNullOrEmpty(optionalData)) - { - this.ActivistLabel = "Activist"; - return "Activist"; - } - - return optionalData; - } - set { OptionalData[ObjectOptionalDataType.OrgActivistLabel] = value; } - } - } } \ No newline at end of file diff --git a/Logic/Structure/OrganizationParameters.cs b/Logic/Structure/OrganizationParameters.cs index 779620f0..5436c85a 100644 --- a/Logic/Structure/OrganizationParameters.cs +++ b/Logic/Structure/OrganizationParameters.cs @@ -5,24 +5,27 @@ namespace Swarmops.Logic.Structure { public class OrganizationParameters { - public OrganizationParameters (Organization organization) + private readonly ObjectOptionalData data; + private readonly Organization organization; + + public OrganizationParameters(Organization organization) { this.organization = organization; - data = ObjectOptionalData.ForObject(organization); + this.data = ObjectOptionalData.ForObject(organization); } public bool EconomyEnabled { get { - if (data.HasData(ObjectOptionalDataType.OrgEconomyEnabled)) + if (this.data.HasData(ObjectOptionalDataType.OrgEconomyEnabled)) { - return data.GetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled); + return this.data.GetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled); } - if (organization.Identity == 1) // temp + if (this.organization.Identity == 1) // temp { - data.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); + this.data.SetOptionalDataBool(ObjectOptionalDataType.OrgEconomyEnabled, true); } return false; @@ -32,9 +35,9 @@ namespace Swarmops.Logic.Structure public int FirstFiscalYear { - get - { - int year = data.GetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear); + get + { + int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgFirstFiscalYear); return year; } } @@ -44,14 +47,11 @@ namespace Swarmops.Logic.Structure { get { - int year = data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); + int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); return year; } - set - { - data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, value); - } + set { this.data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, value); } } @@ -59,11 +59,11 @@ namespace Swarmops.Logic.Structure { get { - int year = data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); + int year = this.data.GetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear); - if (year == 0 && organization.Identity == 1) + if (year == 0 && this.organization.Identity == 1) { - data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, 2009); + this.data.SetOptionalDataInt(ObjectOptionalDataType.OrgBooksClosedForYear, 2009); return 2009; } @@ -73,14 +73,14 @@ namespace Swarmops.Logic.Structure public string TaxAccount { - get - { - string taxAccount = data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount); + get + { + string taxAccount = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount); - if (string.IsNullOrEmpty(taxAccount) && organization.Identity == 1) + if (string.IsNullOrEmpty(taxAccount) && this.organization.Identity == 1) { taxAccount = "Bg 5050-1055"; - data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount, taxAccount); + this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxAccount, taxAccount); } return taxAccount; @@ -89,14 +89,14 @@ namespace Swarmops.Logic.Structure public string TaxOcr { - get - { - string taxOcr = data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr); + get + { + string taxOcr = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr); - if (string.IsNullOrEmpty(taxOcr) && organization.Identity == 1) + if (string.IsNullOrEmpty(taxOcr) && this.organization.Identity == 1) { taxOcr = "1680243045141"; - data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr, taxOcr); + this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTaxOcr, taxOcr); } return taxOcr; @@ -107,7 +107,7 @@ namespace Swarmops.Logic.Structure { get { - string accessList = data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead); + string accessList = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead); if (string.IsNullOrEmpty(accessList)) { @@ -116,17 +116,14 @@ namespace Swarmops.Logic.Structure return accessList; } - set - { - data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead, value); - } + set { this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListRead, value); } } public string TemporaryAccessListWrite { get { - string accessList = data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite); + string accessList = this.data.GetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite); if (string.IsNullOrEmpty(accessList)) { @@ -135,13 +132,7 @@ namespace Swarmops.Logic.Structure return accessList; } - set - { - data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite, value); - } + set { this.data.SetOptionalDataString(ObjectOptionalDataType.OrgTemporaryAccessListWrite, value); } } - - private ObjectOptionalData data; - private Organization organization; } -} +} \ No newline at end of file diff --git a/Logic/Structure/Organizations.cs b/Logic/Structure/Organizations.cs index 6d10175c..74a3ced1 100644 --- a/Logic/Structure/Organizations.cs +++ b/Logic/Structure/Organizations.cs @@ -12,16 +12,16 @@ namespace Swarmops.Logic.Structure { #region Creation and Construction - public static Organizations FromSingle (Organization organization) + public static Organizations FromSingle(Organization organization) { - var result = new Organizations { organization }; + Organizations result = new Organizations {organization}; return result; } - public static Organizations FromArray (Organization[] organizationArray) + public static Organizations FromArray(Organization[] organizationArray) { - var result = new Organizations { Capacity = (organizationArray.Length * 11 / 10) }; + Organizations result = new Organizations {Capacity = (organizationArray.Length*11/10)}; foreach (Organization organization in organizationArray) { @@ -31,9 +31,9 @@ namespace Swarmops.Logic.Structure return result; } - public static Organizations FromArray (BasicOrganization[] organizationArray) + public static Organizations FromArray(BasicOrganization[] organizationArray) { - var result = new Organizations { Capacity = (organizationArray.Length * 11 / 10) }; + Organizations result = new Organizations {Capacity = (organizationArray.Length*11/10)}; foreach (BasicOrganization basic in organizationArray) { @@ -43,12 +43,12 @@ namespace Swarmops.Logic.Structure return result; } - public static Organizations GetAll () + public static Organizations 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) @@ -58,14 +58,13 @@ namespace Swarmops.Logic.Structure 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)); } - public static Organizations GetAllOrganizationsAvailableAtGeography (int geographyId) + public static Organizations GetAllOrganizationsAvailableAtGeography(int geographyId) { List nodeList = new List(); nodeList.AddRange(GeographyCache.GetGeographyLine(geographyId)); @@ -78,9 +77,9 @@ namespace Swarmops.Logic.Structure #region Manipulation - public Organizations RemoveRedundant () + public Organizations RemoveRedundant() { - var remaining = new Dictionary(); + Dictionary remaining = new Dictionary(); foreach (Organization organization in this) { @@ -124,7 +123,7 @@ namespace Swarmops.Logic.Structure // Assemble result - var result = new Organizations(); + Organizations result = new Organizations(); foreach (int organizationId in remaining.Keys) { @@ -134,9 +133,9 @@ namespace Swarmops.Logic.Structure return result; } - public Organizations ExpandAll () + public Organizations ExpandAll() { - var table = new Dictionary(); + Dictionary table = new Dictionary(); // Build table, eliminating duplicates @@ -152,7 +151,7 @@ namespace Swarmops.Logic.Structure // Assemble result - var result = new Organizations(); + Organizations result = new Organizations(); foreach (Organization org in table.Values) { @@ -166,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) @@ -183,7 +182,7 @@ namespace Swarmops.Logic.Structure // Build table, eliminating duplicates - var table = new Dictionary(); + Dictionary table = new Dictionary(); foreach (Organization org in set1) { @@ -197,7 +196,7 @@ namespace Swarmops.Logic.Structure // Assemble result - var result = new Organizations(); + Organizations result = new Organizations(); foreach (Organization org in table.Values) { @@ -207,7 +206,7 @@ namespace Swarmops.Logic.Structure 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) @@ -222,7 +221,7 @@ namespace Swarmops.Logic.Structure return set1; } - var set2Lookup = new Dictionary(); + Dictionary set2Lookup = new Dictionary(); // Build set2's lookup table @@ -233,7 +232,7 @@ namespace Swarmops.Logic.Structure // Build result - var result = new Organizations(); + Organizations result = new Organizations(); foreach (Organization org in set1) { if (set2Lookup.ContainsKey(org.Identity)) @@ -245,12 +244,12 @@ namespace Swarmops.Logic.Structure return result; } - public Organizations LogicalAnd (Organizations set2) + public Organizations LogicalAnd(Organizations set2) { return LogicalAnd(this, set2); } - public Organizations LogicalOr (Organizations set2) + public Organizations LogicalOr(Organizations set2) { return LogicalOr(this, set2); } @@ -260,7 +259,7 @@ namespace Swarmops.Logic.Structure #region Properties and Get Methods /// - /// Gets all economy-enabled organizations. + /// Gets all economy-enabled organizations. /// public static Organizations EconomyEnabled { @@ -287,28 +286,29 @@ namespace Swarmops.Logic.Structure } - public int GetMembershipCount () + public int GetMembershipCount() { return Memberships.GetMemberCountForOrganizations(this); } - public int GetMemberCount () + public int GetMemberCount() { return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizations(Identities); } - public int GetMemberCountForGeographies (Geographies geographies) + public int GetMemberCountForGeographies(Geographies geographies) { return SwarmDb.GetDatabaseForReading().GetMemberCountForOrganizationsAndGeographies(Identities, - geographies.Identities); + geographies.Identities); } - public int GetRoleHolderCountForGeographies (Geographies geographies) + public int GetRoleHolderCountForGeographies(Geographies geographies) { - var result = new Dictionary(); + Dictionary result = new Dictionary(); - BasicPersonRole[] personRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, - geographies.Identities); + BasicPersonRole[] personRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, + geographies.Identities); foreach (BasicPersonRole role in personRoles) { @@ -319,19 +319,20 @@ namespace Swarmops.Logic.Structure } - public People GetRoleHoldersForGeographies (Geographies geographies) + public People GetRoleHoldersForGeographies(Geographies geographies) { - var result = new Dictionary(); + Dictionary result = new Dictionary(); - BasicPersonRole[] personRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, - geographies.Identities); + BasicPersonRole[] personRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(Identities, + geographies.Identities); foreach (BasicPersonRole role in personRoles) { result[role.PersonId] = true; } - var list = new List(); + List list = new List(); foreach (int key in result.Keys) { @@ -348,7 +349,7 @@ 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". @@ -358,7 +359,7 @@ namespace Swarmops.Logic.Structure // Second, only note those that inherit from the supplied root: - var table = new Dictionary(); + Dictionary table = new Dictionary(); foreach (Organization org in orgList) { @@ -376,7 +377,9 @@ namespace Swarmops.Logic.Structure // No organizations! throw new ArgumentException( - string.Format("No organizations eligible under supplied organization ({0}) for supplied geography({1})", rootOrganizationId, geographyId)); + string.Format( + "No organizations eligible under supplied organization ({0}) for supplied geography({1})", + rootOrganizationId, geographyId)); } int maxLength = 0; diff --git a/Logic/Structure/PostalCode.cs b/Logic/Structure/PostalCode.cs index f9e43763..78bbb441 100644 --- a/Logic/Structure/PostalCode.cs +++ b/Logic/Structure/PostalCode.cs @@ -4,39 +4,38 @@ using Swarmops.Basic.Types; namespace Swarmops.Logic.Structure { [Serializable] - public class PostalCode: BasicPostalCode + 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. } - static public PostalCode FromBasic (BasicPostalCode basic) - { - return new PostalCode(basic); - } - public Country Country { - get { return Country.FromIdentity (this.CountryId); } + get { return Country.FromIdentity(CountryId); } } public City City { - get { return City.FromIdentity(this.CityId); } + get { return City.FromIdentity(CityId); } } public string CityName { - get { return this.City.Name; } + get { return City.Name; } } + public static PostalCode FromBasic(BasicPostalCode basic) + { + return new PostalCode(basic); + } } -} +} \ No newline at end of file diff --git a/Logic/Structure/PostalCodes.cs b/Logic/Structure/PostalCodes.cs index 7a6e62e8..d30e6190 100644 --- a/Logic/Structure/PostalCodes.cs +++ b/Logic/Structure/PostalCodes.cs @@ -6,11 +6,11 @@ using Swarmops.Database; namespace Swarmops.Logic.Structure { [Serializable] - public class PostalCodes: List + public class PostalCodes : List { public static PostalCodes FromArray(BasicPostalCode[] array) { - var result = new PostalCodes { Capacity = (array.Length * 11 / 10) }; + PostalCodes result = new PostalCodes {Capacity = (array.Length*11/10)}; foreach (BasicPostalCode basic in array) { @@ -20,14 +20,14 @@ namespace Swarmops.Logic.Structure return result; } - public static PostalCodes ForCountry (string countryCode) + public static PostalCodes ForCountry(string countryCode) { return ForCountry(Country.FromCode(countryCode).Identity); } - public static PostalCodes ForCountry (int countryId) + public static PostalCodes ForCountry(int 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 0db7b455..369de96a 100644 --- a/Logic/Structure/UptakeGeography.cs +++ b/Logic/Structure/UptakeGeography.cs @@ -7,23 +7,23 @@ namespace Swarmops.Logic.Structure #region Creation and Construction // ReSharper disable UnusedPrivateMember - protected UptakeGeography () - // ReSharper restore UnusedPrivateMember + protected UptakeGeography() + // ReSharper restore UnusedPrivateMember { } // disallow public direct construction - private UptakeGeography (BasicUptakeGeography basic) + private UptakeGeography(BasicUptakeGeography basic) : base(basic) { } - protected UptakeGeography (UptakeGeography other) + protected UptakeGeography(UptakeGeography other) : base(other) { } - public static UptakeGeography FromBasic (BasicUptakeGeography basic) + public static UptakeGeography FromBasic(BasicUptakeGeography basic) { return new UptakeGeography(basic); } @@ -32,26 +32,18 @@ namespace Swarmops.Logic.Structure #region Public methods - #endregion #region Public properties - public string GeoName { - get - { - return this.Geography.Name; - } + get { return Geography.Name; } } public string OrgName { - get - { - return this.Organization.Name; - } + get { return Organization.Name; } } public Geography Geography @@ -59,18 +51,18 @@ namespace Swarmops.Logic.Structure get { if (this.geography == null) - this.geography = Geography.FromIdentity(this.GeoId); - return geography; + this.geography = Geography.FromIdentity(GeoId); + return this.geography; } protected set { - if (this.Organization != null) - this.Organization.DeleteUptakeGeography(this.GeoId); + if (Organization != null) + Organization.DeleteUptakeGeography(GeoId); - if (value != null && this.Organization != null) - this.Organization.AddUptakeGeography(value.GeographyId); + if (value != null && Organization != null) + Organization.AddUptakeGeography(value.GeographyId); - geography = value; + this.geography = value; } } @@ -79,24 +71,23 @@ namespace Swarmops.Logic.Structure get { if (this.organization == null) - this.organization = Organization.FromIdentity(this.OrgId); + this.organization = Organization.FromIdentity(OrgId); - return organization; + return this.organization; } protected set { - if (this.Organization != null) - this.Organization.DeleteUptakeGeography(this.GeoId); + if (Organization != null) + Organization.DeleteUptakeGeography(GeoId); if (value != null) - value.AddUptakeGeography(this.GeoId); - organization = value; + value.AddUptakeGeography(GeoId); + this.organization = value; } } + #endregion private Geography geography; private Organization organization; - - - } + } } \ No newline at end of file diff --git a/Logic/Support/ActivistEvents.cs b/Logic/Support/ActivistEvents.cs index f7d8420d..8bcbde3e 100644 --- a/Logic/Support/ActivistEvents.cs +++ b/Logic/Support/ActivistEvents.cs @@ -6,7 +6,7 @@ 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, @@ -22,7 +22,8 @@ namespace Swarmops.Logic.Support } - public static void CreateActivistWithLogging (Geography geo, Person newActivist, string logMessage, EventSource evtSrc, bool isPublic, bool isConfirmed, int orgId) + public static void CreateActivistWithLogging(Geography geo, Person newActivist, string logMessage, + EventSource evtSrc, bool isPublic, bool isConfirmed, int orgId) { PWEvents.CreateEvent(evtSrc, EventType.NewActivist, @@ -33,8 +34,8 @@ namespace Swarmops.Logic.Support 0, string.Empty); newActivist.CreateActivist(isPublic, isConfirmed); - PWLog.Write(newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, "New activist joined.", logMessage); + PWLog.Write(newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, + "New activist joined.", logMessage); } - } -} +} \ No newline at end of file diff --git a/Logic/Support/CheckDigit.cs b/Logic/Support/CheckDigit.cs index 3d06917a..c35e537e 100644 --- a/Logic/Support/CheckDigit.cs +++ b/Logic/Support/CheckDigit.cs @@ -4,65 +4,72 @@ using System.Text; namespace Swarmops.Logic.Support { /// - /// This class implements the Verhoeff check digit scheme. - /// This is one of the best available check digit algorithms - /// that works with any length input. - /// See: http://www.cs.utsa.edu/~wagner/laws/verhoeff.html - /// http://www.augustana.ca/~mohrj/algorithms/checkdigit.html - /// http://modp.com/release/checkdigits/ + /// This class implements the Verhoeff check digit scheme. + /// This is one of the best available check digit algorithms + /// that works with any length input. + /// See: http://www.cs.utsa.edu/~wagner/laws/verhoeff.html + /// http://www.augustana.ca/~mohrj/algorithms/checkdigit.html + /// http://modp.com/release/checkdigits/ /// public sealed class CheckDigit { #region Private Static Variables + //----------------------------------------------------------------------------------------------- - private static CheckDigit _instance = null; + private static CheckDigit _instance; //----------------------------------------------------------------------------------------------- + #endregion #region Private Instance Variables + //----------------------------------------------------------------------------------------------- - private int[][] op = new int[10][]; - private int[] inv = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 }; - private int[][] F = new int[8][]; + private readonly int[][] F = new int[8][]; + private readonly int[] inv = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; + private readonly int[][] op = new int[10][]; //----------------------------------------------------------------------------------------------- + #endregion #region Private Constructor + //----------------------------------------------------------------------------------------------- private CheckDigit() { - op[0] = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - op[1] = new int[] {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}; - op[2] = new int[] {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}; - op[3] = new int[] {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}; - op[4] = new int[] {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}; - op[5] = new int[] {5, 9, 8, 7, 6, 0, 4, 3, 2 ,1}; - op[6] = new int[] {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}; - op[7] = new int[] {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}; - op[8] = new int[] {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}; - op[9] = new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + this.op[0] = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + this.op[1] = new[] {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}; + this.op[2] = new[] {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}; + this.op[3] = new[] {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}; + this.op[4] = new[] {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}; + this.op[5] = new[] {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}; + this.op[6] = new[] {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}; + this.op[7] = new[] {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}; + this.op[8] = new[] {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}; + this.op[9] = new[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; - F[0] = new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // identity permutation - F[1] = new int[]{ 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }; // "magic" permutation + this.F[0] = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // identity permutation + this.F[1] = new[] {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}; // "magic" permutation for (int i = 2; i < 8; i++) { // iterate for remaining permutations - F[i] = new int[10]; + this.F[i] = new int[10]; for (int j = 0; j < 10; j++) - F[i][j] = F[i - 1][F[1][j]]; + this.F[i][j] = this.F[i - 1][this.F[1][j]]; } } + //----------------------------------------------------------------------------------------------- + #endregion #region Public Static Methods - //----------------------------------------------------------------------------------------------- #region AppendCheckDigit Method + //----------------------------------------------------------------------------------------------- /// - /// Calculates the Verhoeff check digit for the given input, then returns - /// the input with the check digit appended at the end. + /// Calculates the Verhoeff check digit for the given input, then returns + /// the input with the check digit appended at the end. /// /// The string for which the check digit is to be calculated. /// The input with the calculated check digit appended. @@ -81,8 +88,8 @@ namespace Swarmops.Logic.Support } /// - /// Calculates the Verhoeff check digit for the given input, then returns - /// the input with the check digit appended at the end. + /// Calculates the Verhoeff check digit for the given input, then returns + /// the input with the check digit appended at the end. /// /// The long integer for which the check digit is to be calculated. /// The input with the calculated check digit appended. @@ -93,8 +100,8 @@ namespace Swarmops.Logic.Support } /// - /// Calculates the Verhoeff check digit for the given input, then returns - /// the input with the check digit appended at the end. + /// Calculates the Verhoeff check digit for the given input, then returns + /// the input with the check digit appended at the end. /// /// The integer for which the check digit is to be calculated. /// The input with the calculated check digit appended. @@ -102,12 +109,12 @@ namespace Swarmops.Logic.Support { int[] resultArray = Instance._AppendCheckDigit(_ConvertToIntArray(input)); long resultLong = _ConvertToLong(resultArray); - return (int)resultLong; + return (int) resultLong; } /// - /// Calculates the Verhoeff check digit for the given input, then returns - /// the input with the check digit appended at the end. + /// Calculates the Verhoeff check digit for the given input, then returns + /// the input with the check digit appended at the end. /// /// The integer array for which the check digit is to be calculated. /// The input with the calculated check digit appended. @@ -115,13 +122,16 @@ namespace Swarmops.Logic.Support { return Instance._AppendCheckDigit(input); } + //----------------------------------------------------------------------------------------------- + #endregion #region CalculateCheckDigit Method + //----------------------------------------------------------------------------------------------- /// - /// Calculates the Verhoeff check digit for the given input. + /// Calculates the Verhoeff check digit for the given input. /// /// The string for which the check digit is to be calculated. /// The check digit for the input. @@ -131,7 +141,7 @@ namespace Swarmops.Logic.Support } /// - /// Calculates the Verhoeff check digit for the given input. + /// Calculates the Verhoeff check digit for the given input. /// /// The long integer for which the check digit is to be calculated. /// The check digit for the input. @@ -141,7 +151,7 @@ namespace Swarmops.Logic.Support } /// - /// Calculates the Verhoeff check digit for the given input. + /// Calculates the Verhoeff check digit for the given input. /// /// The integer for which the check digit is to be calculated. /// The check digit for the input. @@ -151,7 +161,7 @@ namespace Swarmops.Logic.Support } /// - /// Calculates the Verhoeff check digit for the given input. + /// Calculates the Verhoeff check digit for the given input. /// /// The integer array for which the check digit is to be calculated. /// The check digit for the input. @@ -159,114 +169,159 @@ namespace Swarmops.Logic.Support { return Instance._CalculateCheckDigit(input); } + //----------------------------------------------------------------------------------------------- + #endregion #region Check Method + //----------------------------------------------------------------------------------------------- /// - /// Verifies that a given string has a valid Verhoeff check digit as the last digit. + /// Verifies that a given string has a valid Verhoeff check digit as the last digit. /// - /// The string for which the check digit is to be checked. The check digit is the last digit in the string. - /// Returns true if the last digit of the input is the valid check digit for - /// the input. Otherwise returns false. + /// + /// The string for which the check digit is to be checked. The check digit is the last digit in the + /// string. + /// + /// + /// 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) { return Instance._Check(_ConvertToIntArray(input)); } /// - /// Verifies that a given long integer has a valid Verhoeff check digit as the last digit. + /// Verifies that a given long integer has a valid Verhoeff check digit as the last digit. /// - /// The long integer for which the check digit is to be checked. The check digit is the last digit in the input. - /// Returns true if the last digit of the input is the valid check digit for - /// the input. Otherwise returns false. + /// + /// The long integer for which the check digit is to be checked. The check digit is the last digit in + /// the input. + /// + /// + /// 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) { return Instance._Check(_ConvertToIntArray(input)); } /// - /// Verifies that a given integer has a valid Verhoeff check digit as the last digit. + /// Verifies that a given integer has a valid Verhoeff check digit as the last digit. /// - /// The integer for which the check digit is to be checked. The check digit is the last digit in the input. - /// Returns true if the last digit of the input is the valid check digit for - /// the input. Otherwise returns false. + /// + /// The integer for which the check digit is to be checked. The check digit is the last digit in the + /// input. + /// + /// + /// 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) { return Instance._Check(_ConvertToIntArray(input)); } /// - /// Verifies that a given integer array has a valid Verhoeff check digit as the last digit - /// in the array. + /// Verifies that a given integer array has a valid Verhoeff check digit as the last digit + /// in the array. /// - /// The integer array for which the check digit is to be checked. The check digit is the last element of the array. - /// Returns true if the last digit of the input is the valid check digit for - /// the input. Otherwise returns false. + /// + /// The integer array for which the check digit is to be checked. The check digit is the last element + /// of the array. + /// + /// + /// 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) { return Instance._Check(input); } /// - /// Verifies the Verhoeff check digit for a given string. + /// Verifies the Verhoeff check digit for a given string. /// - /// The string for which the check digit is to be verified. The input - /// does not include the check digit. + /// + /// The string for which the check digit is to be verified. The input + /// does not include the check digit. + /// /// The check digit to be verified. - /// Returns true if the check digit is valid for - /// the input. Otherwise returns false. + /// + /// Returns true if the check digit is valid for + /// the input. Otherwise returns false. + /// public static bool Check(string input, int checkDigit) { return Instance._Check(_ConvertToIntArray(input), checkDigit); } /// - /// Verifies the Verhoeff check digit for a given long integer. + /// Verifies the Verhoeff check digit for a given long integer. /// - /// The long integer for which the check digit is to be verified. The input - /// does not include the check digit. + /// + /// The long integer for which the check digit is to be verified. The input + /// does not include the check digit. + /// /// The check digit to be verified. - /// Returns true if the check digit is valid for - /// the input. Otherwise returns false. + /// + /// Returns true if the check digit is valid for + /// the input. Otherwise returns false. + /// public static bool Check(long input, int checkDigit) { return Instance._Check(_ConvertToIntArray(input), checkDigit); } /// - /// Verifies the Verhoeff check digit for a given integer. + /// Verifies the Verhoeff check digit for a given integer. /// - /// The integer for which the check digit is to be verified. The input - /// does not include the check digit. + /// + /// The integer for which the check digit is to be verified. The input + /// does not include the check digit. + /// /// The check digit to be verified. - /// Returns true if the check digit is valid for - /// the input. Otherwise returns false. + /// + /// Returns true if the check digit is valid for + /// the input. Otherwise returns false. + /// public static bool Check(int input, int checkDigit) { return Instance._Check(_ConvertToIntArray(input), checkDigit); } /// - /// Verifies the Verhoeff check digit for a given integer array. + /// Verifies the Verhoeff check digit for a given integer array. /// - /// The integer array for which the check digit is to be verified. The input - /// does not include the check digit. + /// + /// The integer array for which the check digit is to be verified. The input + /// does not include the check digit. + /// /// The check digit to be verified. - /// Returns true if the check digit is valid for - /// the input. Otherwise returns false. + /// + /// Returns true if the check digit is valid for + /// the input. Otherwise returns false. + /// public static bool Check(int[] input, int checkDigit) { return Instance._Check(input, checkDigit); } + //----------------------------------------------------------------------------------------------- + #endregion //----------------------------------------------------------------------------------------------- + + //----------------------------------------------------------------------------------------------- + #endregion #region Private Static Properties + //----------------------------------------------------------------------------------------------- private static CheckDigit Instance { @@ -277,10 +332,13 @@ namespace Swarmops.Logic.Support return _instance; } } + //----------------------------------------------------------------------------------------------- + #endregion #region Private Static Methods + //----------------------------------------------------------------------------------------------- private static int[] _ConvertToIntArray(string input) { @@ -309,16 +367,19 @@ namespace Swarmops.Logic.Support for (int i = 0; i < input.Length; i++) { - result += input[input.Length - (i + 1)] * power; + result += input[input.Length - (i + 1)]*power; power *= 10; } return result; } + //----------------------------------------------------------------------------------------------- + #endregion #region Private Instance Methods + //----------------------------------------------------------------------------------------------- private int[] _AppendCheckDigit(int[] input) { @@ -339,8 +400,8 @@ namespace Swarmops.Logic.Support int check = 0; for (int i = 0; i < reversedInput.Length; i++) - check = op[check][F[(i + 1) % 8][reversedInput[i]]]; - int checkDigit = inv[check]; + check = this.op[check][this.F[(i + 1)%8][reversedInput[i]]]; + int checkDigit = this.inv[check]; return checkDigit; } @@ -354,8 +415,8 @@ namespace Swarmops.Logic.Support int check = 0; for (int i = 0; i < reversedInput.Length; i++) - check = op[check][F[i % 8][reversedInput[i]]]; - + check = this.op[check][this.F[i%8][reversedInput[i]]]; + return (check == 0); } @@ -366,7 +427,9 @@ namespace Swarmops.Logic.Support newInput[newInput.Length - 1] = checkDigit; return _Check(newInput); } + //----------------------------------------------------------------------------------------------- + #endregion } -} +} \ No newline at end of file diff --git a/Logic/Support/DatabaseMaintenance.cs b/Logic/Support/DatabaseMaintenance.cs index ea668e6c..d8e090c1 100644 --- a/Logic/Support/DatabaseMaintenance.cs +++ b/Logic/Support/DatabaseMaintenance.cs @@ -12,9 +12,10 @@ namespace Swarmops.Logic.Support public class DatabaseMaintenance { /// - /// Feeds a newly-created database with an empty structure. Do not use on populated databases; it's like a Genesis Device. + /// Feeds a newly-created database with an empty structure. Do not use on populated databases; it's like a Genesis + /// Device. /// - static public void FirstInitialization() + public static void FirstInitialization() { // Security check: make sure we throw an exception if we try to get person 1. @@ -32,17 +33,21 @@ namespace Swarmops.Logic.Support // Do nothing, the exception is expected } - if (initialized == true && personOne != null) // double checks in case Database behavior should change to return null rather than throw later + if (initialized && personOne != null) + // double checks in case Database behavior should change to return null rather than throw later { - throw new InvalidOperationException("Cannot run Genesis Device style initalization on already-populated database"); + 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) { @@ -52,7 +57,7 @@ namespace Swarmops.Logic.Support SwarmDb.GetDatabaseForWriting().SetKeyValue("DbVersion", "1"); // We're at baseline } - static public void UpgradeSchemata() + public static void UpgradeSchemata() { int currentDbVersion = SwarmDb.DbVersion; int expectedDbVersion = SwarmDb.DbVersionExpected; @@ -63,14 +68,16 @@ namespace Swarmops.Logic.Support { currentDbVersion++; - string fileName = String.Format("http://packages.swarmops.com/schemata/upgrade-{0:D4}.sql", currentDbVersion); + string fileName = String.Format("http://packages.swarmops.com/schemata/upgrade-{0:D4}.sql", + currentDbVersion); using (WebClient client = new WebClient()) { 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) { @@ -89,7 +96,9 @@ namespace Swarmops.Logic.Support } upgraded = true; - SwarmDb.GetDatabaseForWriting().SetKeyValue("DbVersion", currentDbVersion.ToString(CultureInfo.InvariantCulture)); // Increment after each successful run + SwarmDb.GetDatabaseForWriting() + .SetKeyValue("DbVersion", currentDbVersion.ToString(CultureInfo.InvariantCulture)); + // Increment after each successful run } if (upgraded) @@ -105,4 +114,4 @@ namespace Swarmops.Logic.Support } } } -} +} \ No newline at end of file diff --git a/Logic/Support/Document.cs b/Logic/Support/Document.cs index aca51a72..a7d79cd4 100644 --- a/Logic/Support/Document.cs +++ b/Logic/Support/Document.cs @@ -12,11 +12,63 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { - public class Document: BasicDocument + public class Document : BasicDocument { - private Document (BasicDocument document): base (document) + private Document(BasicDocument document) : base(document) { - + } + + public new string ServerFileName + { + get { return base.ServerFileName; } + set + { + SwarmDb.GetDatabaseForWriting().SetDocumentServerFileName(Identity, value); + base.ServerFileName = value; + } + } + + public IHasIdentity ForeignObject + { + get + { + switch (DocumentType) + { + case DocumentType.ExpenseClaim: + return ExpenseClaim.FromIdentity(ForeignId); + + case DocumentType.FinancialTransaction: + return FinancialTransaction.FromIdentity(ForeignId); + + case DocumentType.InboundInvoice: + return InboundInvoice.FromIdentity(ForeignId); + + case DocumentType.PaperLetter: + return PaperLetter.FromIdentity(ForeignId); + + case DocumentType.PayrollItem: + return PayrollItem.FromIdentity(ForeignId); + + default: + throw new NotImplementedException("DocumentType needs implementation: " + + DocumentType.ToString()); + } + } + } + + protected static string StorageRoot + { + get + { + if (Debugger.IsAttached) + { + return @"C:\Windows\Temp\Swarmops-Debug\"; // Windows debugging environment + } + else + { + return "/var/lib/swarmops/upload/"; // production location on Debian installation + } + } } public static Document FromIdentity(int documentId) @@ -26,7 +78,8 @@ namespace Swarmops.Logic.Support 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) @@ -34,16 +87,18 @@ namespace Swarmops.Logic.Support 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), identifiableObject == null? 0: identifiableObject.Identity, uploader.Identity); + CreateDocument(serverFileName, clientFileName, fileSize, description, + GetDocumentTypeForObject(identifiableObject), + identifiableObject == null ? 0 : identifiableObject.Identity, uploader.Identity); return FromIdentityAggressive(newDocumentId); } - public static DocumentType GetDocumentTypeForObject (IHasIdentity foreignObject) + public static DocumentType GetDocumentTypeForObject(IHasIdentity foreignObject) { if (foreignObject == null) { @@ -85,48 +140,12 @@ namespace Swarmops.Logic.Support } } - public new string ServerFileName + public void SetForeignObject(IHasIdentity foreignObject) { - get { return base.ServerFileName; } - set - { - SwarmDb.GetDatabaseForWriting().SetDocumentServerFileName(this.Identity, value); - base.ServerFileName = value; - } + SwarmDb.GetDatabaseForWriting() + .SetDocumentForeignObject(Identity, GetDocumentTypeForObject(foreignObject), foreignObject.Identity); } - public void SetForeignObject (IHasIdentity foreignObject) - { - SwarmDb.GetDatabaseForWriting().SetDocumentForeignObject(this.Identity, GetDocumentTypeForObject(foreignObject), foreignObject.Identity); - } - - - public IHasIdentity ForeignObject - { - get - { - switch (DocumentType) - { - case DocumentType.ExpenseClaim: - return ExpenseClaim.FromIdentity(this.ForeignId); - - case DocumentType.FinancialTransaction: - return FinancialTransaction.FromIdentity(this.ForeignId); - - case DocumentType.InboundInvoice: - return InboundInvoice.FromIdentity(this.ForeignId); - - case DocumentType.PaperLetter: - return PaperLetter.FromIdentity(this.ForeignId); - - case DocumentType.PayrollItem: - return PayrollItem.FromIdentity(this.ForeignId); - - default: - throw new NotImplementedException("DocumentType needs implementation: " + DocumentType.ToString()); - } - } - } public void Delete() { @@ -134,35 +153,17 @@ namespace Swarmops.Logic.Support SetForeignObject(new TemporaryIdentity(0)); File.Delete(StorageRoot + ServerFileName); - SwarmDb.GetDatabaseForWriting().SetDocumentDescription(this.Identity, "Deleted"); - - } - - protected static string StorageRoot - { - get - { - if (Debugger.IsAttached) - { - return @"C:\Windows\Temp\Swarmops-Debug\"; // Windows debugging environment - } - else - { - return "/var/lib/swarmops/upload/"; // production location on Debian installation - } - } + SwarmDb.GetDatabaseForWriting().SetDocumentDescription(Identity, "Deleted"); } public StreamReader GetReader(Encoding encoding) { - return new StreamReader(StorageRoot + this.ServerFileName, encoding); + return new StreamReader(StorageRoot + ServerFileName, encoding); } public StreamReader GetReader(int 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 79e9c1dd..6f0ca8f8 100644 --- a/Logic/Support/Documents.cs +++ b/Logic/Support/Documents.cs @@ -7,9 +7,11 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { - public class Documents: List + public class Documents : List { - public static Documents ForObject (IHasIdentity identifiableObject) + private IHasIdentity sourceObject; + + public static Documents ForObject(IHasIdentity identifiableObject) { Documents newInstance = FromArray( @@ -21,9 +23,9 @@ namespace Swarmops.Logic.Support return newInstance; } - public static Documents FromArray (BasicDocument[] basicArray) + public static Documents FromArray(BasicDocument[] basicArray) { - var result = new Documents { Capacity = (basicArray.Length * 11 / 10) }; + Documents result = new Documents {Capacity = (basicArray.Length*11/10)}; foreach (BasicDocument basic in basicArray) { @@ -34,22 +36,22 @@ namespace Swarmops.Logic.Support } - 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 // Expenses.Documents.Add (...), or is it just stupid? - if (sourceObject == null) + if (this.sourceObject == null) { throw new InvalidOperationException( "Cannot add documents to a Documents instance that was not created from an object."); } - Document newDocument = + Document newDocument = Document.Create(serverFileName, clientFileName, fileSize, description, - sourceObject, uploader); + this.sourceObject, uploader); base.Add(newDocument); @@ -57,20 +59,18 @@ namespace Swarmops.Logic.Support } - 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); } } - - private IHasIdentity sourceObject = null; } -} +} \ No newline at end of file diff --git a/Logic/Support/ExtensionMethods.cs b/Logic/Support/ExtensionMethods.cs index f1e8651d..8ebb949c 100644 --- a/Logic/Support/ExtensionMethods.cs +++ b/Logic/Support/ExtensionMethods.cs @@ -4,39 +4,37 @@ using System.IO; namespace System.Web.ExtensionMethods { /// - /// Extension methods for HTTP Response. + /// Extension methods for HTTP Response. /// public static class HttpResponseExtensions { /// - /// Set the response to be JSON format, and add appropriate headers. + /// Set the response to be JSON format, and add appropriate headers. /// /// None. 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.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"); } } - /// - /// Extension methods for HTTP Request. - /// - /// See the HTTP 1.1 specification http://www.w3.org/Protocols/rfc2616/rfc2616.html - /// for details of implementation decisions. - /// + /// Extension methods for HTTP Request. + /// + /// See the HTTP 1.1 specification http://www.w3.org/Protocols/rfc2616/rfc2616.html + /// for details of implementation decisions. + /// /// public static class HttpRequestExtensions { - /// - /// Dump the raw http request to a string. + /// Dump the raw http request to a string. /// - /// The that should be dumped. + /// The that should be dumped. /// The raw HTTP request. public static string ToRaw(this HttpRequest request) { @@ -71,7 +69,7 @@ namespace System.Web.ExtensionMethods { foreach (string key in request.Headers.AllKeys) { - writer.WriteLine(string.Format("{0}: {1}", key, request.Headers[key])); + writer.WriteLine("{0}: {1}", key, request.Headers[key]); } writer.WriteLine(); @@ -93,4 +91,4 @@ namespace System.Web.ExtensionMethods } } } -} +} \ No newline at end of file diff --git a/Logic/Support/Formatting.cs b/Logic/Support/Formatting.cs index 8d8072c7..916dda41 100644 --- a/Logic/Support/Formatting.cs +++ b/Logic/Support/Formatting.cs @@ -8,44 +8,47 @@ namespace Swarmops.Logic.Support { public static class Formatting { - public static string CleanNumber (string input) + public static string CleanNumber(string input) { return LogicServices.CleanNumber(input); } - public static string GeneratePassword (int length) + public static string GeneratePassword(int 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"; - string ccTLD = "ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|" - + "ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|" - + "ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|" - + "de|dj|dk|dm|do|dz|" - + "ec|ee|eg|er|es|et|eu|" - + "fi|fj|fk|fm|fo|fr|" - + "ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|" - + "hk|hm|hn|hr|ht|hu|" - + "id|ie|il|im|in|io|iq|ir|is|it|" - + "je|jm|jo|jp|" - + "ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|" - + "la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|" - + "ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|" - + "na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|" - + "pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|" - + "re|ro|rs|ru|rw|" - + "sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|" - + "tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|" - + "ua|ug|uk|us|uy|uz|" - + "va|vc|ve|vg|vi|vn|vu|" - + "wf|ws|ye|yt|yu|za|zm|zw"; - Regex re = new Regex(@"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:" + ccTLD + "|" + gTLD + ")$", RegexOptions.IgnoreCase); + + "mobi|museum|name|net|org|pro|tel|travel"; + string ccTLD = "ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|" + + "ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|" + + "ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|" + + "de|dj|dk|dm|do|dz|" + + "ec|ee|eg|er|es|et|eu|" + + "fi|fj|fk|fm|fo|fr|" + + "ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|" + + "hk|hm|hn|hr|ht|hu|" + + "id|ie|il|im|in|io|iq|ir|is|it|" + + "je|jm|jo|jp|" + + "ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|" + + "la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|" + + "ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|" + + "na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|" + + "pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|" + + "re|ro|rs|ru|rw|" + + "sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|" + + "tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|" + + "ua|ug|uk|us|uy|uz|" + + "va|vc|ve|vg|vi|vn|vu|" + + "wf|ws|ye|yt|yu|za|zm|zw"; + Regex re = + 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); } @@ -79,17 +82,17 @@ namespace Swarmops.Logic.Support { // The last sequence was just a single number. - result += ", #" + ids[index - 1].ToString(); + result += ", #" + ids[index - 1]; } else if (indexOfLastDiscontinuity == index - 2) { // Two numbers in last sequence. Treat as discontinuous. - result += ", #" + ids[indexOfLastDiscontinuity].ToString() + ", #" + ids[index - 1].ToString(); + result += ", #" + ids[indexOfLastDiscontinuity] + ", #" + ids[index - 1]; } else { // Contiguity. - result += ", #" + ids[indexOfLastDiscontinuity].ToString() + "-" + ids[index - 1].ToString(); + result += ", #" + ids[indexOfLastDiscontinuity] + "-" + ids[index - 1]; } indexOfLastDiscontinuity = index; @@ -99,34 +102,34 @@ namespace Swarmops.Logic.Support 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++){ - int temp = (number[i] - '0') * (((number.Length - i) % 2) == 1 ? 2 : 1); + for (int i = 0; i < number.Length; i++) + { + int temp = (number[i] - '0')*(((number.Length - i)%2) == 1 ? 2 : 1); if (temp > 9) temp -= 9; sum += temp; } - return number + ((10 - (sum % 10)) % 10).ToString(); - + return number + ((10 - (sum%10))%10); } - 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()); } - public static string JoinIdentities (int[] ids) + public static string JoinIdentities(int[] ids) { if (ids.Length == 0) { diff --git a/Logic/Support/IXmlPayload.cs b/Logic/Support/IXmlPayload.cs index f73333c9..e8f57ca9 100644 --- a/Logic/Support/IXmlPayload.cs +++ b/Logic/Support/IXmlPayload.cs @@ -4,4 +4,4 @@ namespace Swarmops.Logic.Support { string ToXml(); } -} +} \ No newline at end of file diff --git a/Logic/Support/Imagery.cs b/Logic/Support/Imagery.cs index 3bd6226b..da43f07e 100644 --- a/Logic/Support/Imagery.cs +++ b/Logic/Support/Imagery.cs @@ -1,3 +1,4 @@ +using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; @@ -6,9 +7,7 @@ namespace Swarmops.Logic.Support { public class Imagery { - - - static public 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 @@ -23,33 +22,33 @@ namespace Swarmops.Logic.Support float nPercentW = 0; float nPercentH = 0; - nPercentW = ((float)width / (float)sourceWidth); - nPercentH = ((float)height / (float)sourceHeight); - if (nPercentH > nPercentW) // modified: crop, don't pad + nPercentW = (width/(float) sourceWidth); + nPercentH = (height/(float) sourceHeight); + if (nPercentH > nPercentW) // modified: crop, don't pad { nPercent = nPercentH; - destX = System.Convert.ToInt16((width - - (sourceWidth * nPercent)) / 2); + destX = Convert.ToInt16((width - + (sourceWidth*nPercent))/2); } else { nPercent = nPercentW; - destY = System.Convert.ToInt16((height - - (sourceHeight * nPercent)) / 2); + destY = Convert.ToInt16((height - + (sourceHeight*nPercent))/2); } - int destWidth = (int)(sourceWidth * nPercent); - int destHeight = (int)(sourceHeight * nPercent); + int destWidth = (int) (sourceWidth*nPercent); + int destHeight = (int) (sourceHeight*nPercent); Bitmap bmPhoto = new Bitmap(width, height, - PixelFormat.Format24bppRgb); + PixelFormat.Format24bppRgb); bmPhoto.SetResolution(sourceImage.HorizontalResolution, - sourceImage.VerticalResolution); + sourceImage.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.Red); grPhoto.InterpolationMode = - InterpolationMode.HighQualityBicubic; + InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(sourceImage, new Rectangle(destX, destY, destWidth, destHeight), @@ -60,4 +59,4 @@ namespace Swarmops.Logic.Support return bmPhoto; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs b/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs index 26e6c993..915abd15 100644 --- a/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs +++ b/Logic/Support/LogEntries/CashAdvanceRequestedLogEntry.cs @@ -5,26 +5,27 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class CashAdvanceRequestedLogEntry: FinancialActionBase + public class CashAdvanceRequestedLogEntry : FinancialActionBase { public CashAdvanceRequestedLogEntry() { // empty ctor needed for serialize } - public CashAdvanceRequestedLogEntry(Person actingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason) + public CashAdvanceRequestedLogEntry(Person actingPerson, Person beneficiaryPerson, double amount, + FinancialAccount budget, string reason) { - this.Amount = amount; - this.Currency = budget.Organization.Currency.Code; - this.DateTime = DateTime.UtcNow; - this.Description = reason; - this.OrganizationId = budget.OrganizationId; - this.FinancialAccountId = budget.Identity; - this.FinancialAccountName = budget.Name; // redundancy in case of future name changes - this.OwnerPersonId = budget.OwnerPersonId; - this.OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; - this.ActingPersonId = actingPerson.Identity; // do not save name for data retention reasons - this.BeneficiaryPersonId = beneficiaryPerson.Identity; + Amount = amount; + Currency = budget.Organization.Currency.Code; + DateTime = DateTime.UtcNow; + Description = reason; + OrganizationId = budget.OrganizationId; + FinancialAccountId = budget.Identity; + FinancialAccountName = budget.Name; // redundancy in case of future name changes + OwnerPersonId = budget.OwnerPersonId; + OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; + ActingPersonId = actingPerson.Identity; // do not save name for data retention reasons + BeneficiaryPersonId = beneficiaryPerson.Identity; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs b/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs index aff8f71e..9a5ad3dd 100644 --- a/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs +++ b/Logic/Support/LogEntries/ExpenseClaimFiledLogEntry.cs @@ -5,26 +5,27 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class ExpenseClaimFiledLogEntry: FinancialActionBase + public class ExpenseClaimFiledLogEntry : FinancialActionBase { public ExpenseClaimFiledLogEntry() { // empty ctor needed for serialize } - public ExpenseClaimFiledLogEntry(Person filingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason) + public ExpenseClaimFiledLogEntry(Person filingPerson, Person beneficiaryPerson, double amount, + FinancialAccount budget, string reason) { - this.Amount = amount; - this.Currency = budget.Organization.Currency.Code; - this.DateTime = DateTime.UtcNow; - this.Description = reason; - this.OrganizationId = budget.OrganizationId; - this.FinancialAccountId = budget.Identity; - this.FinancialAccountName = budget.Name; // redundancy in case of future name changes - this.OwnerPersonId = budget.OwnerPersonId; - this.OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; - this.ActingPersonId = filingPerson.Identity; // do not save name for data retention reasons - this.BeneficiaryPersonId = beneficiaryPerson.Identity; + Amount = amount; + Currency = budget.Organization.Currency.Code; + DateTime = DateTime.UtcNow; + Description = reason; + OrganizationId = budget.OrganizationId; + FinancialAccountId = budget.Identity; + FinancialAccountName = budget.Name; // redundancy in case of future name changes + OwnerPersonId = budget.OwnerPersonId; + OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; + ActingPersonId = filingPerson.Identity; // do not save name for data retention reasons + BeneficiaryPersonId = beneficiaryPerson.Identity; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/FinancialActionBase.cs b/Logic/Support/LogEntries/FinancialActionBase.cs index 8e60c2b4..01c69a3a 100644 --- a/Logic/Support/LogEntries/FinancialActionBase.cs +++ b/Logic/Support/LogEntries/FinancialActionBase.cs @@ -3,13 +3,8 @@ namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class FinancialActionBase: LogEntryBase + public class FinancialActionBase : LogEntryBase { - public FinancialActionBase() - { - // necessary for serialization - } - public int FinancialAccountId { get; set; } public string FinancialAccountName { get; set; } public int ActingPersonId { get; set; } @@ -22,4 +17,4 @@ namespace Swarmops.Logic.Support.LogEntries public string OwnerPersonName { get; set; } public DateTime DateTime { get; set; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs b/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs index 0e713df2..492d0985 100644 --- a/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/InboundInvoiceCreatedLogEntry.cs @@ -5,29 +5,30 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class InboundInvoiceCreatedLogEntry: FinancialActionBase + public class InboundInvoiceCreatedLogEntry : FinancialActionBase { public InboundInvoiceCreatedLogEntry() { // empty ctor needed for serialize } - public InboundInvoiceCreatedLogEntry(Person creatingPerson, string supplier, string description, double amount, FinancialAccount budget) + public InboundInvoiceCreatedLogEntry(Person creatingPerson, string supplier, string description, double amount, + FinancialAccount budget) { - this.Amount = amount; - this.Currency = budget.Organization.Currency.Code; - this.DateTime = DateTime.UtcNow; - this.Description = description; - this.OrganizationId = budget.OrganizationId; - this.FinancialAccountId = budget.Identity; - this.FinancialAccountName = budget.Name; // redundancy in case of future name changes - this.OwnerPersonId = budget.OwnerPersonId; - this.OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; - this.ActingPersonId = creatingPerson.Identity; // do not save name for data retention reasons - this.BeneficiaryPersonId = 0; - this.Supplier = supplier; + Amount = amount; + Currency = budget.Organization.Currency.Code; + DateTime = DateTime.UtcNow; + Description = description; + OrganizationId = budget.OrganizationId; + FinancialAccountId = budget.Identity; + FinancialAccountName = budget.Name; // redundancy in case of future name changes + OwnerPersonId = budget.OwnerPersonId; + OwnerPersonName = budget.OwnerPersonId != 0 ? budget.Owner.Name : string.Empty; + ActingPersonId = creatingPerson.Identity; // do not save name for data retention reasons + BeneficiaryPersonId = 0; + Supplier = supplier; } public string Supplier { get; set; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/LogEntryBase.cs b/Logic/Support/LogEntries/LogEntryBase.cs index bab06ee5..643f6403 100644 --- a/Logic/Support/LogEntries/LogEntryBase.cs +++ b/Logic/Support/LogEntries/LogEntryBase.cs @@ -6,20 +6,20 @@ using System.Xml.Serialization; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class LogEntryBase: IXmlPayload + public class LogEntryBase : IXmlPayload { public virtual string ToXml() { - var serializer = new XmlSerializer(this.GetType()); + XmlSerializer serializer = new XmlSerializer(GetType()); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, this); byte[] xmlBytes = stream.GetBuffer(); 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 @@ -31,17 +31,17 @@ namespace Swarmops.Logic.Support.LogEntries xml = xml.Replace("�", ""); xml = xml.Replace("\x00", ""); - var serializer = new XmlSerializer(typeof(T)); + XmlSerializer serializer = new XmlSerializer(typeof (T)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); stream.Write(xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - var result = (T)serializer.Deserialize(stream); + T result = (T) serializer.Deserialize(stream); stream.Close(); return result; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs b/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs index 473b116a..c9238758 100644 --- a/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/PayoutCreatedLogEntry.cs @@ -6,23 +6,23 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class PayoutCreatedLogEntry: FinancialActionBase + public class PayoutCreatedLogEntry : FinancialActionBase { public PayoutCreatedLogEntry() { // public ctor required for serializability } - public PayoutCreatedLogEntry(Person payingPerson, Person beneficiaryPerson, Organization organization, Currency currency, double amount, string reason) + public PayoutCreatedLogEntry(Person payingPerson, Person beneficiaryPerson, Organization organization, + Currency currency, double amount, string reason) { - this.Amount = amount; - this.Currency = currency.Code; - this.OrganizationId = organization.Identity; - this.DateTime = DateTime.UtcNow; - this.Description = reason; - this.ActingPersonId = payingPerson.Identity; // do not save name for data retention reasons - this.BeneficiaryPersonId = (beneficiaryPerson != null ? beneficiaryPerson.Identity : 0); + Amount = amount; + Currency = currency.Code; + OrganizationId = organization.Identity; + DateTime = DateTime.UtcNow; + Description = reason; + ActingPersonId = payingPerson.Identity; // do not save name for data retention reasons + BeneficiaryPersonId = (beneficiaryPerson != null ? beneficiaryPerson.Identity : 0); } - } -} +} \ No newline at end of file diff --git a/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs b/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs index 1f52e823..68f57859 100644 --- a/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs +++ b/Logic/Support/LogEntries/SalaryCreatedLogEntry.cs @@ -1,13 +1,10 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using Swarmops.Logic.Financial; namespace Swarmops.Logic.Support.LogEntries { [Serializable] - public class SalaryCreatedLogEntry: FinancialActionBase + public class SalaryCreatedLogEntry : FinancialActionBase { [Obsolete("Do not call this constructor directly.", true)] public SalaryCreatedLogEntry() @@ -17,16 +14,16 @@ namespace Swarmops.Logic.Support.LogEntries public SalaryCreatedLogEntry(Salary salary) { - this.ActingPersonId = 0; - this.BeneficiaryPersonId = salary.PayrollItem.PersonId; - this.Amount = salary.NetSalaryCents/100.0; - this.Currency = salary.Budget.Organization.Currency.Code; - this.DateTime = DateTime.UtcNow; - this.FinancialAccountId = salary.Budget.Identity; - this.FinancialAccountName = salary.Budget.Name; - this.OrganizationId = salary.PayrollItem.OrganizationId; - this.OwnerPersonId = salary.PayrollItem.ReportsToPersonId; - this.OwnerPersonName = salary.PayrollItem.ReportsToPerson.Canonical; + ActingPersonId = 0; + BeneficiaryPersonId = salary.PayrollItem.PersonId; + Amount = salary.NetSalaryCents/100.0; + Currency = salary.Budget.Organization.Currency.Code; + DateTime = DateTime.UtcNow; + FinancialAccountId = salary.Budget.Identity; + FinancialAccountName = salary.Budget.Name; + OrganizationId = salary.PayrollItem.OrganizationId; + OwnerPersonId = salary.PayrollItem.ReportsToPersonId; + OwnerPersonName = salary.PayrollItem.ReportsToPerson.Canonical; } } -} +} \ No newline at end of file diff --git a/Logic/Support/LogicServices.cs b/Logic/Support/LogicServices.cs index cda85db7..29d04cc5 100644 --- a/Logic/Support/LogicServices.cs +++ b/Logic/Support/LogicServices.cs @@ -8,15 +8,15 @@ namespace Swarmops.Logic.Support internal class LogicServices { /// - /// Determines if a string can be parsed as an Int32. + /// Determines if a string can be parsed as an Int32. /// /// 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) @@ -26,39 +26,39 @@ namespace Swarmops.Logic.Support } /// - /// Removes any non-digits from a string. + /// Removes any non-digits from a string. /// /// 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) { return string.Empty; } - var result = new StringBuilder(); + StringBuilder result = new StringBuilder(); foreach (char acter in input) { 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) { - var result = new List(); + 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 3feb385c..72df2b8e 100644 --- a/Logic/Support/ObjectOptionalData.cs +++ b/Logic/Support/ObjectOptionalData.cs @@ -6,59 +6,57 @@ using Swarmops.Database; namespace Swarmops.Logic.Support { - [Serializable] public class ObjectOptionalData : BasicObjectOptionalData { - private IHasIdentity forObject = null; - private ObjectOptionalData (BasicObjectOptionalData basic) + private IHasIdentity forObject; + + private ObjectOptionalData(BasicObjectOptionalData basic) : base(basic) { // empty ctor } - public static ObjectOptionalData FromBasic (BasicObjectOptionalData basic) - { - return new ObjectOptionalData(basic); - } - - public static ObjectOptionalData ForObject (IHasIdentity identifiableObject) - { - ObjectOptionalData thisObject = FromBasic(SwarmDb.GetDatabaseForReading().GetObjectOptionalData((IHasIdentity)identifiableObject)); - thisObject.forObject = identifiableObject; - return thisObject; - } - - public bool HasData (ObjectOptionalDataType dataType) - { - if (this.OptionalData.ContainsKey(dataType)) - { - return true; - } - else - { - return false; - } - } - public string this[ObjectOptionalDataType dataType] { get { - if (this.OptionalData.ContainsKey(dataType)) + if (OptionalData.ContainsKey(dataType)) { - return this.OptionalData[dataType]; + return OptionalData[dataType]; } return null; } set { - SwarmDb.GetDatabaseForWriting().SetObjectOptionalData((IHasIdentity)forObject, dataType, value); - this.OptionalData[dataType] = value; + SwarmDb.GetDatabaseForWriting().SetObjectOptionalData(this.forObject, dataType, value); + OptionalData[dataType] = value; } } + public static ObjectOptionalData FromBasic(BasicObjectOptionalData basic) + { + return new ObjectOptionalData(basic); + } + + public static ObjectOptionalData ForObject(IHasIdentity identifiableObject) + { + ObjectOptionalData thisObject = + FromBasic(SwarmDb.GetDatabaseForReading().GetObjectOptionalData(identifiableObject)); + thisObject.forObject = identifiableObject; + return thisObject; + } + + public bool HasData(ObjectOptionalDataType dataType) + { + if (OptionalData.ContainsKey(dataType)) + { + return true; + } + return false; + } + //static private IHasIdentity ConstructObject (ObjectType objectType, int objectId) //{ // switch (objectType) @@ -76,10 +74,9 @@ namespace Swarmops.Logic.Support // Optional data support - public string GetOptionalDataString (ObjectOptionalDataType key) + public string GetOptionalDataString(ObjectOptionalDataType key) { - - if (this.HasData(key)) + if (HasData(key)) { return this[key]; } @@ -87,17 +84,16 @@ namespace Swarmops.Logic.Support return string.Empty; } - public void SetOptionalDataString (ObjectOptionalDataType key, string value) + public void SetOptionalDataString(ObjectOptionalDataType key, string value) { - this.SetOptionalData(key, value); + SetOptionalData(key, value); } // All ints default to 0 - public int GetOptionalDataInt (ObjectOptionalDataType key) + public int GetOptionalDataInt(ObjectOptionalDataType key) { - - if (this.HasData(key)) + if (HasData(key)) { return Int32.Parse(this[key]); } @@ -105,17 +101,16 @@ namespace Swarmops.Logic.Support return 0; } - public void SetOptionalDataInt (ObjectOptionalDataType key, int value) + public void SetOptionalDataInt(ObjectOptionalDataType key, int value) { SetOptionalData(key, value.ToString()); } // All bools default to false - public bool GetOptionalDataBool (ObjectOptionalDataType key) + public bool GetOptionalDataBool(ObjectOptionalDataType key) { - - if (this.HasData(key)) + if (HasData(key)) { return (this[key] == "1" ? true : false); } @@ -123,21 +118,20 @@ 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"); } - public void SetOptionalData (ObjectOptionalDataType dataType, string data) + public void SetOptionalData(ObjectOptionalDataType dataType, string data) { - SwarmDb.GetDatabaseForWriting().SetObjectOptionalData((IHasIdentity)forObject, dataType, data); + SwarmDb.GetDatabaseForWriting().SetObjectOptionalData(this.forObject, dataType, data); - if (data == null && this.OptionalData.ContainsKey(dataType)) - this.OptionalData.Remove(dataType); + if (data == null && OptionalData.ContainsKey(dataType)) + OptionalData.Remove(dataType); else this[dataType] = data; } - } -} +} \ No newline at end of file diff --git a/Logic/Support/Optimizations.cs b/Logic/Support/Optimizations.cs index 01242f5f..0885f134 100644 --- a/Logic/Support/Optimizations.cs +++ b/Logic/Support/Optimizations.cs @@ -4,13 +4,13 @@ using Swarmops.Database; namespace Swarmops.Logic.Support { /// - /// This class contains one-off optimizations that don't fit anywhere. + /// This class contains one-off optimizations that don't fit anywhere. /// 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,7 +18,7 @@ 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); } diff --git a/Logic/Support/PWEvents.cs b/Logic/Support/PWEvents.cs index c5eb5a58..95cc442c 100644 --- a/Logic/Support/PWEvents.cs +++ b/Logic/Support/PWEvents.cs @@ -7,43 +7,43 @@ namespace Swarmops.Logic.Support { public class PWEvents { - public static int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, - int organizationId, - int geographyId, int affectedPersonId, int parameterInt, string parameterText) + 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, - geographyId, affectedPersonId, parameterInt, parameterText); + geographyId, affectedPersonId, parameterInt, parameterText); } - public static BasicPWEvent[] GetTopUnprocessedEvents () + public static BasicPWEvent[] GetTopUnprocessedEvents() { return SwarmDb.GetDatabaseForReading().GetTopUnprocessedEvents(); } - public static BasicPWEvent[] ForPerson (int personId) + public static BasicPWEvent[] ForPerson(int 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); } - public static BasicPWEvent[] ByType (EventType eventType) + public static BasicPWEvent[] ByType(EventType eventType) { return SwarmDb.GetDatabaseForReading().GetEventsOfType(eventType); } - public static void SetEventProcessed (int eventId) + public static void SetEventProcessed(int eventId) { SwarmDb.GetDatabaseForWriting().SetEventProcessed(eventId); } diff --git a/Logic/Support/PWLog.cs b/Logic/Support/PWLog.cs index 9094efa7..a68a4c4a 100644 --- a/Logic/Support/PWLog.cs +++ b/Logic/Support/PWLog.cs @@ -9,48 +9,50 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { // ReSharper disable InconsistentNaming - public class PWLog - // ReSharper restore InconsistentNaming + public class PWLog + // ReSharper restore InconsistentNaming { - public static void Write (DateTime dateTimeUtc, int actingPersonId, PWLogItem affectedItem, - int affectedItemId, - PWLogAction actionType, string actionDescription, string comment, - string changedField, string valueBefore, string valueAfter) + private static string hostIp = ""; //Used in batch programs + + 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(), - affectedItemId, actionType.ToString(), actionDescription, - changedField, valueBefore, valueAfter, comment, GetCurrentIp()); + affectedItemId, actionType.ToString(), actionDescription, + changedField, valueBefore, valueAfter, comment, GetCurrentIp()); } - public static void Write (DateTime dateTimeUtc, Person actingPerson, PWLogItem affectedItem, - int affectedItemId, - PWLogAction actionType, string actionDescription, string comment, - string changedField, string valueBefore, string valueAfter) + 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, - actionDescription, comment, changedField, valueBefore, valueAfter); + actionDescription, comment, changedField, valueBefore, valueAfter); } - public static void Write (Person actingPerson, PWLogItem affectedItem, int affectedItemId, - PWLogAction actionType, - string actionDescription, string comment, string changedField, string valueBefore, - string valueAfter) + 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, - actionDescription, comment, changedField, valueBefore, valueAfter); + actionDescription, comment, changedField, valueBefore, valueAfter); } - public static void Write (Person actingPerson, PWLogItem affectedItem, int affectedItemId, - PWLogAction actionType, - string actionDescription, string comment) + public static void Write(Person actingPerson, PWLogItem affectedItem, int affectedItemId, + PWLogAction actionType, + string actionDescription, string comment) { Write(DateTime.UtcNow, actingPerson.Identity, affectedItem, affectedItemId, actionType, - actionDescription, comment, string.Empty, string.Empty, string.Empty); + actionDescription, comment, string.Empty, string.Empty, string.Empty); } - public static void Write (int actingPersonId, PWLogItem affectedItem, int affectedItemId, - PWLogAction actionType, - string actionDescription, string comment) + public static void Write(int actingPersonId, PWLogItem affectedItem, int affectedItemId, + PWLogAction actionType, + string actionDescription, string comment) { if (actingPersonId > 0 && comment == "") { @@ -58,20 +60,22 @@ namespace Swarmops.Logic.Support { comment = "Action done by " + Person.FromIdentity(actingPersonId).Name; } - catch { } + catch + { + } } Write(DateTime.UtcNow, actingPersonId, affectedItem, affectedItemId, actionType, - actionDescription, comment, string.Empty, string.Empty, string.Empty); + actionDescription, comment, string.Empty, string.Empty, string.Empty); } - public static void Write (PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, - string actionDescription, string comment) + public static void Write(PWLogItem affectedItem, int affectedItemId, PWLogAction actionType, + string actionDescription, string comment) { Write(DateTime.UtcNow, 0, affectedItem, affectedItemId, actionType, - actionDescription, comment, string.Empty, string.Empty, string.Empty); + actionDescription, comment, string.Empty, string.Empty, string.Empty); } - private static string GetCurrentIp () + private static string GetCurrentIp() { try { @@ -98,115 +102,135 @@ namespace Swarmops.Logic.Support } return hostIp; } - } - 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()); + return SwarmDb.GetDatabaseForReading() + .CheckLogEntry(affectedItemType.ToString(), affectedItemId, actionType.ToString()); } - public static BasicPWLog[] GetLatestEvents (PWLogItem affectedItemType, DateTime beforeDate, int[] affectedIds, PWLogAction[] actionTypes) + public static BasicPWLog[] GetLatestEvents(PWLogItem affectedItemType, DateTime beforeDate, int[] affectedIds, + PWLogAction[] actionTypes) { - List actionTypeList = new List(); - foreach (var at in actionTypes) + foreach (PWLogAction at in actionTypes) actionTypeList.Add(at.ToString()); - return SwarmDb.GetDatabaseForReading().GetLatestEvents(affectedItemType.ToString(), beforeDate, affectedIds, actionTypeList.ToArray()); + return SwarmDb.GetDatabaseForReading() + .GetLatestEvents(affectedItemType.ToString(), beforeDate, affectedIds, actionTypeList.ToArray()); } - - private static string hostIp = "";//Used in batch programs } public enum PWLogAction { /// - /// Undefined. Do not use. + /// Undefined. Do not use. /// Undefined = 0, + /// - /// A new member has joined on his/her own accord. + /// A new member has joined on his/her own accord. /// MemberJoin, + /// - /// A new member was added by an officer. + /// A new member was added by an officer. /// MemberAdd, + /// - /// A new membership was added to an existing member. + /// A new membership was added to an existing member. /// MembershipAdd, + /// - /// A membership was removed. + /// A membership was removed. /// MembershipRemove, + /// - /// A membership was transferred to another org. + /// A membership was transferred to another org. /// MembershipTransfer, + /// - /// A member has been removed from the roster. + /// A member has been removed from the roster. /// MemberLost, + /// - /// An activist has joined. + /// An activist has joined. /// ActivistJoin, + /// - /// An activist was lost. + /// An activist was lost. /// ActivistLost, + /// - /// Personal data was changed. + /// Personal data was changed. /// PersonFieldChange, + /// - /// Part of systems tests. Do not use. + /// Part of systems tests. Do not use. /// SystemTest, + /// - /// A member was reminded to renew. + /// A member was reminded to renew. /// MembershipRenewReminder, + /// - /// A membership was renewed. + /// A membership was renewed. /// MembershipRenewed, + /// - /// A role (lead, admin, etc.) was assigned. + /// A role (lead, admin, etc.) was assigned. /// RoleAssigned, + /// - /// A role was removed. + /// A role was removed. /// RoleDeleted, + /// - /// Person created (usually for debug purposes). + /// Person created (usually for debug purposes). /// PersonCreated, + /// - /// Mail account changes + /// Mail account changes /// MailAccountChanged, + /// - /// Changes in External Identities + /// Changes in External Identities /// ExtAccountChanged, + /// - /// A membership is requested to be renewed. + /// A membership is requested to be renewed. /// MembershipRenewalRequest, + /// - /// Logged info about a failure + /// Logged info about a failure /// Failure, + /// - /// SMS message Handled + /// SMS message Handled /// SMSHandled, + /// - /// Starting Impersonation of other user + /// Starting Impersonation of other user /// StartImpersonation } diff --git a/Logic/Support/Persistence.cs b/Logic/Support/Persistence.cs index 3573fe6b..2f05658f 100644 --- a/Logic/Support/Persistence.cs +++ b/Logic/Support/Persistence.cs @@ -7,9 +7,9 @@ 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 { diff --git a/Logic/Support/PilotInstallationIds.cs b/Logic/Support/PilotInstallationIds.cs index 40f6e7ac..42ef4ba8 100644 --- a/Logic/Support/PilotInstallationIds.cs +++ b/Logic/Support/PilotInstallationIds.cs @@ -2,16 +2,22 @@ { public class PilotInstallationIds { - static public string PiratePartySE - { get { return "d7588903-5fd0-40cf-a5b1-9af7a722cb6e"; } } + public static string PiratePartySE + { + get { return "d7588903-5fd0-40cf-a5b1-9af7a722cb6e"; } + } - static public string DevelopmentSandbox - { get { return "a8187d16-d913-4ddc-a3d5-214f7c14aac5"; } } + public static string DevelopmentSandbox + { + get { return "a8187d16-d913-4ddc-a3d5-214f7c14aac5"; } + } - static public string SwarmopsLive - { get { return "db8f4ade-07f2-4f4f-a1c7-c9da91f93ea9"; }} + public static string SwarmopsLive + { + get { return "db8f4ade-07f2-4f4f-a1c7-c9da91f93ea9"; } + } - static public bool IsPilot(string installationId) + public static bool IsPilot(string installationId) { string thisInstallationId = Persistence.Key["SwarmopsInstallationId"]; if (installationId == thisInstallationId) @@ -22,6 +28,4 @@ return false; } } - - -} +} \ No newline at end of file diff --git a/Logic/Support/PluralBase.cs b/Logic/Support/PluralBase.cs index d0ee25a8..1457d62f 100644 --- a/Logic/Support/PluralBase.cs +++ b/Logic/Support/PluralBase.cs @@ -1,28 +1,13 @@ - - using System.Collections.Generic; using Swarmops.Basic.Interfaces; namespace Swarmops.Logic.Support { - public class PluralBase: List, IHasIdentities - where TPlural: PluralBase, new() - where TBasic: IHasIdentity - where TSingular: IHasIdentity + public class PluralBase : List, IHasIdentities + where TPlural : PluralBase, new() + where TBasic : IHasIdentity + where TSingular : IHasIdentity { - static public TPlural FromArray (TBasic[] basicArray) - { - var result = new TPlural {Capacity = basicArray.Length*11/10}; - - foreach (TBasic basic in basicArray) - { - result.Add((TSingular) SingularFactory.FromBasic(basic)); - } - - return result; - } - - public int[] Identities { get @@ -38,18 +23,30 @@ namespace Swarmops.Logic.Support } } - - static public TPlural FromSingle (TSingular singular) + public static TPlural FromArray(TBasic[] basicArray) { - var result = new TPlural(); + TPlural result = new TPlural {Capacity = basicArray.Length*11/10}; + + foreach (TBasic basic in basicArray) + { + result.Add((TSingular) SingularFactory.FromBasic(basic)); + } + + return result; + } + + + public static TPlural FromSingle(TSingular singular) + { + TPlural result = new TPlural(); result.Add(singular); return result; } - static public TPlural FromSingle (TBasic basic) + public static TPlural FromSingle(TBasic basic) { - var result = new TPlural(); + TPlural result = new TPlural(); result.Add((TSingular) SingularFactory.FromBasic(basic)); @@ -57,7 +54,6 @@ namespace Swarmops.Logic.Support } - public static TPlural LogicalOr(TPlural set1, TPlural set2) { // If either set is invalid, return the other @@ -75,7 +71,7 @@ namespace Swarmops.Logic.Support // Build table, eliminating duplicates - var table = new Dictionary(); + Dictionary table = new Dictionary(); foreach (TSingular singular in set1) { @@ -89,7 +85,7 @@ namespace Swarmops.Logic.Support // Assemble result - var result = new TPlural(); + TPlural result = new TPlural(); foreach (TSingular singular in table.Values) { @@ -100,7 +96,6 @@ namespace Swarmops.Logic.Support } - public static TPlural LogicalAnd(TPlural set1, TPlural set2) { // If either set is invalid, return the other @@ -116,7 +111,7 @@ namespace Swarmops.Logic.Support return set1; } - var set2Lookup = new Dictionary(); + Dictionary set2Lookup = new Dictionary(); // Build set2's lookup table @@ -127,7 +122,7 @@ namespace Swarmops.Logic.Support // Build result - var result = new TPlural(); + TPlural result = new TPlural(); foreach (TSingular singular in set1) { if (set2Lookup.ContainsKey(singular.Identity)) @@ -139,13 +134,13 @@ namespace Swarmops.Logic.Support return result; } - public new void Remove (TSingular objectToRemove) + public new void Remove(TSingular objectToRemove) { - for (int index = 0; index < this.Count; index++) + for (int index = 0; index < Count; index++) { if (this[index].Identity == objectToRemove.Identity) { - this.RemoveAt(index); + RemoveAt(index); index--; } } diff --git a/Logic/Support/QuotedPrintable.cs b/Logic/Support/QuotedPrintable.cs index 28632f7b..022b69d0 100644 --- a/Logic/Support/QuotedPrintable.cs +++ b/Logic/Support/QuotedPrintable.cs @@ -5,29 +5,29 @@ using System.Text.RegularExpressions; namespace Swarmops.Logic.Support { - /// - /// Provide encoding and decoding of Quoted-Printable. + /// Provide encoding and decoding of Quoted-Printable. /// public class QuotedPrintable { - public QuotedPrintable (Encoding encoding) - { - _encoding = encoding; - } - - Encoding _encoding = Encoding.Default; /// - /// // so including the = connection, the length will be 76 + /// // so including the = connection, the length will be 76 /// private const int RFC_1521_MAX_CHARS_PER_LINE = 75; + private readonly Encoding _encoding = Encoding.Default; + + public QuotedPrintable(Encoding encoding) + { + this._encoding = encoding; + } + /// - /// Return quoted printable string with 76 characters per line. + /// Return quoted printable string with 76 characters per line. /// /// /// - public string Encode (string textToEncode) + public string Encode(string textToEncode) { if (textToEncode == null) throw new ArgumentNullException(); @@ -35,7 +35,7 @@ namespace Swarmops.Logic.Support 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(); @@ -47,19 +47,19 @@ namespace Swarmops.Logic.Support } /// - /// Return quoted printable to be used in mail headers, if encoding is necessary + /// Return quoted printable to be used in mail headers, if encoding is necessary /// /// /// - public String EncodeMailHeaderString (string textToEncode) + public String EncodeMailHeaderString(string textToEncode) { String encChars = EncodeString(textToEncode); String displayName = ""; if (encChars != textToEncode) { displayName = "=?"; - displayName += _encoding.BodyName; - displayName +="?Q?" + encChars.Replace(" ", "_") + "?="; + displayName += this._encoding.BodyName; + displayName += "?Q?" + encChars.Replace(" ", "_") + "?="; } else displayName = textToEncode; @@ -67,16 +67,16 @@ namespace Swarmops.Logic.Support } /// - /// Return quoted printable string, all in one line. + /// Return quoted printable string, all in one line. /// /// /// - public string EncodeString (string textToEncode) + public string EncodeString(string textToEncode) { if (textToEncode == null) throw new ArgumentNullException(); - byte[] bytes = _encoding.GetBytes(textToEncode); + byte[] bytes = this._encoding.GetBytes(textToEncode); StringBuilder builder = new StringBuilder(); foreach (byte b in bytes) { @@ -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(); @@ -128,7 +128,7 @@ namespace Swarmops.Logic.Support return builder.ToString(); } - private string HexDecoderEvaluator (Match m) + private string HexDecoderEvaluator(Match m) { if (String.IsNullOrEmpty(m.Value)) return null; @@ -141,20 +141,20 @@ namespace Swarmops.Logic.Support bytes[i] = Convert.ToByte(captures[i].Value, 16); } - return _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, new MatchEvaluator(HexDecoderEvaluator)); + return re.Replace(line, HexDecoderEvaluator); } - public string Decode (string encodedText) + public string Decode(string encodedText) { if (encodedText == null) throw new ArgumentNullException(); @@ -174,6 +174,5 @@ namespace Swarmops.Logic.Support return HexDecoder(builder.ToString()); } } - } -} +} \ No newline at end of file diff --git a/Logic/Support/SerializableDictionary.cs b/Logic/Support/SerializableDictionary.cs index 2166cd1d..215032ba 100644 --- a/Logic/Support/SerializableDictionary.cs +++ b/Logic/Support/SerializableDictionary.cs @@ -1,9 +1,10 @@ using System.Collections.Generic; +using System.Xml; +using System.Xml.Schema; using System.Xml.Serialization; 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")] @@ -11,15 +12,16 @@ namespace Swarmops.Logic.Support : Dictionary, IXmlSerializable { #region IXmlSerializable Members - public System.Xml.Schema.XmlSchema GetSchema() + + public XmlSchema GetSchema() { return null; } - public void ReadXml(System.Xml.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,19 +29,19 @@ namespace Swarmops.Logic.Support if (wasEmpty) return; - while (reader.NodeType != System.Xml.XmlNodeType.EndElement) + while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); - TKey key = (TKey)keySerializer.Deserialize(reader); + TKey key = (TKey) keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); - TValue value = (TValue)valueSerializer.Deserialize(reader); + TValue value = (TValue) valueSerializer.Deserialize(reader); reader.ReadEndElement(); - this.Add(key, value); + Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); @@ -47,12 +49,12 @@ namespace Swarmops.Logic.Support reader.ReadEndElement(); } - public void WriteXml(System.Xml.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 this.Keys) + foreach (TKey key in Keys) { writer.WriteStartElement("item"); @@ -68,6 +70,7 @@ namespace Swarmops.Logic.Support writer.WriteEndElement(); } } + #endregion } -} +} \ No newline at end of file diff --git a/Logic/Support/SingularFactory.cs b/Logic/Support/SingularFactory.cs index 6b5e53c5..835d4a51 100644 --- a/Logic/Support/SingularFactory.cs +++ b/Logic/Support/SingularFactory.cs @@ -12,74 +12,74 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { /// - /// This class supports the PluralBase foundation. Mirroring FromBasic() here is the - /// price we pay to get FromArray(), FromSingle(), LogicalOr() etc in all the plural - /// classes. + /// This class supports the PluralBase foundation. Mirroring FromBasic() here is the + /// price we pay to get FromArray(), FromSingle(), LogicalOr() etc in all the plural + /// classes. /// internal class SingularFactory { - static public object FromBasic(IHasIdentity basic) + public static object FromBasic(IHasIdentity basic) { string argumentType = basic.GetType().ToString(); switch (argumentType) { - // ----- Is there any way to make self-writing code here through replication or similar, so - // ----- that every case doesn't need to be listed? + // ----- Is there any way to make self-writing code here through replication or similar, so + // ----- that every case doesn't need to be listed? - // ------------ COMMUNICATION CLASSES ------------ + // ------------ 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 ---------- + // ----------- 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); 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); 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); @@ -88,57 +88,54 @@ namespace Swarmops.Logic.Support 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); - // ------------ GOVERNANCE CLASSES ------------ + // ------------ 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); + case "Swarmops.Basic.Types.Governance.BasicMotion": + return Motion.FromBasic((BasicMotion) basic); case "Swarmops.Basic.Types.Governance.BasicMotionAmendment": - return MotionAmendment.FromBasic((BasicMotionAmendment)basic); + return MotionAmendment.FromBasic((BasicMotionAmendment) basic); - // ------------ PARLEY/ACTIVISM CLASSES ------------ + // ------------ PARLEY/ACTIVISM CLASSES ------------ case "Swarmops.Basic.Types.BasicExternalActivity": 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 ---------------- + // ------------------ FAIL ---------------- default: throw new NotImplementedException("Unimplemented argument type in SingularFactory: " + argumentType); - } - - } } -} +} \ No newline at end of file diff --git a/Logic/Support/SwarmopsLog.cs b/Logic/Support/SwarmopsLog.cs index 6c6e37b0..92d34bfe 100644 --- a/Logic/Support/SwarmopsLog.cs +++ b/Logic/Support/SwarmopsLog.cs @@ -5,7 +5,7 @@ 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(); @@ -20,4 +20,4 @@ namespace Swarmops.Logic.Support return SwarmopsLogEntry.FromIdentityAggressive(logEntryId); } } -} +} \ No newline at end of file diff --git a/Logic/Support/SwarmopsLogEntry.cs b/Logic/Support/SwarmopsLogEntry.cs index 32e124e7..deeee9ce 100644 --- a/Logic/Support/SwarmopsLogEntry.cs +++ b/Logic/Support/SwarmopsLogEntry.cs @@ -5,30 +5,31 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { - public class SwarmopsLogEntry: BasicSwarmopsLogEntry + 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); } - public static SwarmopsLogEntry FromIdentity (int swarmopsLogEntryId) + public static SwarmopsLogEntry FromIdentity(int 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); @@ -45,15 +46,16 @@ namespace Swarmops.Logic.Support return entry; } - public void CreateAffectedObject (IHasIdentity affectedObject) + public void CreateAffectedObject(IHasIdentity affectedObject) { string className = affectedObject.GetType().ToString(); int dotIndex = className.LastIndexOf('.'); className = className.Substring(dotIndex + 1); // assumes there's always at least one dot in a class name - - SwarmDb.GetDatabaseForWriting().CreateSwarmopsLogEntryAffectedObject(this.Identity, className, affectedObject.Identity); + + SwarmDb.GetDatabaseForWriting() + .CreateSwarmopsLogEntryAffectedObject(Identity, className, affectedObject.Identity); } } -} +} \ No newline at end of file diff --git a/Logic/Support/TemporaryIdentity.cs b/Logic/Support/TemporaryIdentity.cs index 438be844..d621fc7b 100644 --- a/Logic/Support/TemporaryIdentity.cs +++ b/Logic/Support/TemporaryIdentity.cs @@ -3,26 +3,24 @@ using Swarmops.Database; namespace Swarmops.Logic.Support { - public class TemporaryIdentity: IHasIdentity + public class TemporaryIdentity : IHasIdentity { - public TemporaryIdentity (int temporaryId) + private readonly int temporaryId; + + public TemporaryIdentity(int temporaryId) { this.temporaryId = temporaryId; } - static public TemporaryIdentity GetNew() - { - return new TemporaryIdentity (SwarmDb.GetDatabaseForWriting().GetTemporaryIdentity()); // This is actually an Insert, not a Select - } - - private int temporaryId; - public int Identity { - get - { - return temporaryId; - } + get { return this.temporaryId; } + } + + public static TemporaryIdentity GetNew() + { + 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 2f5b4c79..368df5d6 100644 --- a/Logic/Support/UrlTranslations.cs +++ b/Logic/Support/UrlTranslations.cs @@ -4,7 +4,7 @@ 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); @@ -12,18 +12,15 @@ namespace Swarmops.Logic.Support { return true; } - else - { - return false; - } + return false; } - public static void Set (string originalUrl, string translatedUrl) + public static void Set(string originalUrl, string translatedUrl) { SwarmDb.GetDatabaseForWriting().SetUrlTranslation(originalUrl, translatedUrl); } - public static string[] GetUntranslated (int maxCount) + public static string[] GetUntranslated(int maxCount) { return SwarmDb.GetDatabaseForReading().GetUntranslatedUrls(maxCount); } diff --git a/Logic/Swarm/Activists.cs b/Logic/Swarm/Activists.cs index 6dbb50aa..b6cb87dd 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; } @@ -23,13 +23,10 @@ namespace Swarmops.Logic.Swarm { get { return this.personIds.Length; } } - + public int[] Identities { - get - { - return personIds; - } + get { return this.personIds; } } public People People @@ -42,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); } - public static Activists FromGeography (Geography geography) + public static Activists FromGeography(Geography geography) { Geographies geographies = geography.GetTree(); return new Activists(SwarmDb.GetDatabaseForReading().GetActivistPersonIds(geographies.Identities)); } - public void SendPhoneMessage (string message) + public void SendPhoneMessage(string message) { VerifyPeoplePopulated(); @@ -81,7 +78,7 @@ namespace Swarmops.Logic.Swarm } } - public void SendNotice (string subject, string body) + public void SendNotice(string subject, string body) { VerifyPeoplePopulated(); @@ -92,7 +89,7 @@ namespace Swarmops.Logic.Swarm } - private void VerifyPeoplePopulated () + private void VerifyPeoplePopulated() { if (this.people == null) { diff --git a/Logic/Swarm/AuditedPerson.cs b/Logic/Swarm/AuditedPerson.cs index 5c6202a3..f9df1d05 100644 --- a/Logic/Swarm/AuditedPerson.cs +++ b/Logic/Swarm/AuditedPerson.cs @@ -5,152 +5,126 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class AuditedPerson + public class AuditedPerson { - public static implicit operator Person (AuditedPerson a) - { - return a.person; - } + private readonly Person person; + private string actionDescr = ""; + private Person executor; - - public static AuditedPerson FromPerson (Person person) - { - return new AuditedPerson(person); - } - - public static AuditedPerson FromPerson (Person person, Person executor, string actionDescr) - { - AuditedPerson ap= new AuditedPerson(person); - ap.SetAudit(executor, actionDescr); - return ap; - } - - protected AuditedPerson (Person person) + protected AuditedPerson(Person person) { this.person = person; this.executor = null; this.actionDescr = ""; } - public void SetAudit (Person executor, string actionDescr) - { - this.executor = executor; - this.actionDescr = actionDescr; - } - - protected void AuditField (string field, string oldVal, string newVal) - { - if (executor != null && (""+oldVal).Trim() != (""+newVal).Trim()) - { - PWLog.Write(executor, PWLogItem.Person, this.person.Identity, PWLogAction.PersonFieldChange, actionDescr, "", field, ""+oldVal, ""+newVal); - } - } - public virtual string Name { - get { return person.Name; } + get { return this.person.Name; } set { AuditField("Name", Name, value); - person.Name = value; + this.person.Name = value; } } public virtual string Street { - get { return person.Street; } + get { return this.person.Street; } set { AuditField("Street", Street, value); - person.Street = value; + this.person.Street = value; } } public virtual string PostalCode { - get { return person.PostalCode; } + get { return this.person.PostalCode; } set { AuditField("PostalCode", PostalCode, value); - person.PostalCode = value; + this.person.PostalCode = value; } } public virtual string City { - get { return person.CityName; } + get { return this.person.CityName; } set { AuditField("City", City, value); - person.CityName = value; + this.person.CityName = value; } } public virtual Country Country { - get { return person.Country; } + get { return this.person.Country; } set { - AuditField("Country", Country == null ? "" : Country.Identity.ToString(), value == null ? "" : value.Identity.ToString()); - person.Country = value; + AuditField("Country", Country == null ? "" : Country.Identity.ToString(), + value == null ? "" : value.Identity.ToString()); + this.person.Country = value; } } public virtual Geography Geography { - get { return person.Geography; } + get { return this.person.Geography; } set { - AuditField("Geography", Geography == null ? "" : Geography.Identity.ToString(), value == null ? "" : value.Identity.ToString()); - person.Geography = value; + AuditField("Geography", Geography == null ? "" : Geography.Identity.ToString(), + value == null ? "" : value.Identity.ToString()); + this.person.Geography = value; } } public virtual string Email { - get { return person.Mail; } + get { return this.person.Mail; } set { AuditField("Email", Email, value); - person.Mail = value; + this.person.Mail = value; } } public virtual string Phone { - get { return person.Phone; } + get { return this.person.Phone; } set { AuditField("Phone", Phone, value); - person.Phone = value; + this.person.Phone = value; } } public virtual DateTime Birthdate { - get { return person.Birthdate; } + get { return this.person.Birthdate; } set { AuditField("Birthdate", Birthdate.ToString(), value.ToString()); - person.Birthdate = value; + this.person.Birthdate = value; } } public virtual PersonGender Gender { - get { return person.Gender; } + get { return this.person.Gender; } set { AuditField("Gender", Gender.ToString(), value.ToString()); - person.Gender = value; + this.person.Gender = value; } } @@ -159,145 +133,173 @@ namespace Swarmops.Logic.Swarm public virtual string PartyEmail { - get { return person.PartyEmail; } + get { return this.person.PartyEmail; } set { AuditField("PartyEmail", PartyEmail, value); - person.PartyEmail = value; + this.person.PartyEmail = value; } } public virtual string BankName { - get { return person.BankName; } + get { return this.person.BankName; } set { AuditField("BankName", BankName, value); - person.BankName = value; + this.person.BankName = value; } } public virtual string BankAccount { - get { return person.BankAccount; } + get { return this.person.BankAccount; } set { AuditField("BankAccount", BankAccount, value); - person.BankAccount = value; + this.person.BankAccount = value; } } public virtual string BankClearing { - get { return person.BankClearing; } + get { return this.person.BankClearing; } set { AuditField("BankClearing", BankClearing, value); - person.BankClearing = value; + this.person.BankClearing = value; } } [Obsolete("Use NationalIdNumber instead")] public virtual string PersonalNumber { - get { return person.PersonalNumber; } + get { return this.person.PersonalNumber; } set { AuditField("PersonalNumber", PersonalNumber, value); - person.PersonalNumber = value; + this.person.PersonalNumber = value; } } public virtual bool MailUnreachable { - get { return person.MailUnreachable; } + get { return this.person.MailUnreachable; } set { AuditField("MailUnreachable", MailUnreachable.ToString(), value.ToString()); - person.MailUnreachable = value; + this.person.MailUnreachable = value; } } public virtual bool LimitMailToLatin1 { - get { return person.LimitMailToLatin1; } + get { return this.person.LimitMailToLatin1; } set { AuditField("LimitMailToLatin1", LimitMailToLatin1.ToString(), value.ToString()); - person.LimitMailToLatin1 = value; + this.person.LimitMailToLatin1 = value; } } public virtual bool LimitMailToText { - get { return person.LimitMailToText; } + get { return this.person.LimitMailToText; } set { AuditField("LimitMailToText", LimitMailToText.ToString(), value.ToString()); - person.LimitMailToText = value; + this.person.LimitMailToText = value; } } public virtual bool NeverMail { - get { return person.NeverMail; } + get { return this.person.NeverMail; } set { AuditField("NeverMail", NeverMail.ToString(), value.ToString()); - person.NeverMail = value; + this.person.NeverMail = value; } } public virtual bool EMailIsInvalid { - get { return person.EMailIsInvalid; } + get { return this.person.EMailIsInvalid; } set { AuditField("EMailIsInvalid", EMailIsInvalid.ToString(), value.ToString()); - person.EMailIsInvalid = value; + this.person.EMailIsInvalid = value; } } public virtual string Handle { - get { return person.Handle; } + get { return this.person.Handle; } set { AuditField("Handle", Handle, value); - person.Handle = value; + this.person.Handle = value; } } public virtual int SwedishForumAccountId { - get { return person.SwedishForumAccountId; } + get { return this.person.SwedishForumAccountId; } set { AuditField("SwedishForumAccountId", SwedishForumAccountId.ToString(), value.ToString()); - person.SwedishForumAccountId = value; + this.person.SwedishForumAccountId = value; + } + } + + public static implicit operator Person(AuditedPerson a) + { + return a.person; + } + + + public static AuditedPerson FromPerson(Person person) + { + return new AuditedPerson(person); + } + + public static AuditedPerson FromPerson(Person person, Person executor, string actionDescr) + { + AuditedPerson ap = new AuditedPerson(person); + ap.SetAudit(executor, actionDescr); + return ap; + } + + public void SetAudit(Person executor, string actionDescr) + { + this.executor = executor; + this.actionDescr = actionDescr; + } + + 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, + this.actionDescr, "", field, "" + oldVal, "" + newVal); } } - public virtual void SetPassword (string newPassword) + public virtual void SetPassword(string newPassword) { AuditField("SetPassword", "oldpassword", "newpassword"); - person.SetPassword(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); - person.SetSubscription(newsletterFeedId, subscribe); + this.person.SetSubscription(newsletterFeedId, subscribe); } - - - private Person executor = null; - private string actionDescr = ""; - private Person person; } -} +} \ No newline at end of file diff --git a/Logic/Swarm/ChurnData.cs b/Logic/Swarm/ChurnData.cs index c09c3e72..019928fb 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) { - var result = new ChurnData(); + 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; @@ -47,49 +47,51 @@ namespace Swarmops.Logic.Swarm /// - /// Call this when one or more memberships have expired for a person. + /// Call this when one or more memberships have expired for a person. /// /// 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)); + return + 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 6f86250e..9aa384ca 100644 --- a/Logic/Swarm/ChurnDataPoint.cs +++ b/Logic/Swarm/ChurnDataPoint.cs @@ -8,11 +8,11 @@ namespace Swarmops.Logic.Swarm { } - 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); } diff --git a/Logic/Swarm/DashboardTodo.cs b/Logic/Swarm/DashboardTodo.cs index 8df4e9bb..d8cb0e7c 100644 --- a/Logic/Swarm/DashboardTodo.cs +++ b/Logic/Swarm/DashboardTodo.cs @@ -16,4 +16,4 @@ Orange, Red } -} +} \ No newline at end of file diff --git a/Logic/Swarm/DashboardTodos.cs b/Logic/Swarm/DashboardTodos.cs index 46e47530..c602543c 100644 --- a/Logic/Swarm/DashboardTodos.cs +++ b/Logic/Swarm/DashboardTodos.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Swarmops.Logic.App_GlobalResources; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; @@ -7,9 +8,9 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class DashboardTodos: List + public class DashboardTodos : List { - public static DashboardTodos ForPerson (Person person, Organization organization) + public static DashboardTodos ForPerson(Person person, Organization organization) { DashboardTodos result = new DashboardTodos(); @@ -25,7 +26,6 @@ namespace Swarmops.Logic.Swarm } - private void AddReceiptValidations(Person person, Organization organization) { if (!person.HasAccess(new Access(organization, AccessAspect.Financials, AccessType.Write))) @@ -46,23 +46,21 @@ namespace Swarmops.Logic.Swarm if (claims.Count > 1) { - todo.Description = String.Format(App_GlobalResources.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(App_GlobalResources.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"; - this.Add(todo); + Add(todo); } - - - // TODO: Refactor the attest-X functions into one function with minimal differences @@ -75,7 +73,7 @@ namespace Swarmops.Logic.Swarm if (person.Identity == 1) { - isPersonOrgAdmin = true; // TODO: Make more advanced, obviously + isPersonOrgAdmin = true; // TODO: Make more advanced, obviously } foreach (ExpenseClaim claim in claims) @@ -105,20 +103,22 @@ namespace Swarmops.Logic.Swarm if (expenseClaimIds.Count > 0) { DashboardTodo todo = new DashboardTodo(); - + if (expenseClaimIds.Count > 1) { - todo.Description = String.Format(App_GlobalResources.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(App_GlobalResources.Logic_Swarm_DashboardTodos.Attest_ExpenseClaim_One, expenseClaimIds[0]); + 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"; - this.Add(todo); + Add(todo); } } @@ -131,7 +131,7 @@ namespace Swarmops.Logic.Swarm if (person.Identity == 1) { - isPersonOrgAdmin = true; // TODO: Make more advanced, obviously + isPersonOrgAdmin = true; // TODO: Make more advanced, obviously } foreach (CashAdvance advance in advances) @@ -165,17 +165,19 @@ namespace Swarmops.Logic.Swarm if (cashAdvanceIds.Count > 1) { - todo.Description = String.Format(App_GlobalResources.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(App_GlobalResources.Logic_Swarm_DashboardTodos.Attest_CashAdvance_One, cashAdvanceIds[0]); + 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"; - this.Add(todo); + Add(todo); } } @@ -192,11 +194,11 @@ namespace Swarmops.Logic.Swarm todoNormal.Url = todoUrgent.Url = - todoOverdue.Url = "/Pages/v5/Financial/PayOutMoney.aspx"; + todoOverdue.Url = "/Pages/v5/Financial/PayOutMoney.aspx"; todoNormal.Icon = todoUrgent.Icon = - todoOverdue.Icon = "/Images/PageIcons/iconshock-money-envelope-16px.png"; + todoOverdue.Icon = "/Images/PageIcons/iconshock-money-envelope-16px.png"; int payoutCount = 0; int urgentPayoutCount = 0; @@ -224,33 +226,31 @@ namespace Swarmops.Logic.Swarm if (payoutCount > 0) { todoNormal.Description = payoutCount > 1 - ? String.Format(App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_Many, - payoutCount) - : App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_One; - this.Add(todoNormal); + ? String.Format(Logic_Swarm_DashboardTodos.Payout_Many, + payoutCount) + : Logic_Swarm_DashboardTodos.Payout_One; + Add(todoNormal); } if (overduePayoutCount > 0) { todoOverdue.Description = overduePayoutCount > 1 - ? String.Format(App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_Overdue_Many, - payoutCount) - : App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_Overdue_One; + ? String.Format(Logic_Swarm_DashboardTodos.Payout_Overdue_Many, + payoutCount) + : Logic_Swarm_DashboardTodos.Payout_Overdue_One; todoOverdue.Urgency = TodoUrgency.Red; - this.Add(todoOverdue); + Add(todoOverdue); } if (urgentPayoutCount > 0) { todoUrgent.Description = overduePayoutCount > 1 - ? String.Format(App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_Urgent_Many, - payoutCount) - : App_GlobalResources.Logic_Swarm_DashboardTodos.Payout_Urgent_One; + ? String.Format(Logic_Swarm_DashboardTodos.Payout_Urgent_Many, + payoutCount) + : Logic_Swarm_DashboardTodos.Payout_Urgent_One; todoUrgent.Urgency = TodoUrgency.Yellow; - this.Add(todoUrgent); + Add(todoUrgent); } } - - } -} +} \ No newline at end of file diff --git a/Logic/Swarm/ExternalActivities.cs b/Logic/Swarm/ExternalActivities.cs index 65b9a0c1..44452c48 100644 --- a/Logic/Swarm/ExternalActivities.cs +++ b/Logic/Swarm/ExternalActivities.cs @@ -8,43 +8,46 @@ namespace Swarmops.Logic.Swarm { public class ExternalActivities : PluralBase { - public static ExternalActivities ForOrganization (Organization organization) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetExternalActivities(organization)); - } - - public static ExternalActivities ForOrganization (Organization organization, SortOrder sort, int count) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetExternalActivitiesSorted(sort.ToString(), count, organization)); - } - public enum SortOrder { Unknown = 0, + /// - /// By date/time of the activism, newest first + /// By date/time of the activism, newest first /// DateDescending, + /// - /// By date/time of the upload, newest first + /// By date/time of the upload, newest first /// CreationDateDescending } - public void Sort (SortOrder order) + public static ExternalActivities ForOrganization(Organization organization) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetExternalActivities(organization)); + } + + public static ExternalActivities ForOrganization(Organization organization, SortOrder sort, int count) + { + return + FromArray(SwarmDb.GetDatabaseForReading() + .GetExternalActivitiesSorted(sort.ToString(), count, organization)); + } + + public void Sort(SortOrder order) { switch (order) { case SortOrder.DateDescending: - this.Sort(ExternalActivity.CompareDateDescending); + Sort(ExternalActivity.CompareDateDescending); break; case SortOrder.CreationDateDescending: - this.Sort(ExternalActivity.CompareCreationDateDescending); + Sort(ExternalActivity.CompareCreationDateDescending); break; default: throw new NotImplementedException("Unimplemented sort order"); } - } } -} +} \ No newline at end of file diff --git a/Logic/Swarm/ExternalActivity.cs b/Logic/Swarm/ExternalActivity.cs index 5b961c76..012a8fb5 100644 --- a/Logic/Swarm/ExternalActivity.cs +++ b/Logic/Swarm/ExternalActivity.cs @@ -6,45 +6,47 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.Swarm { - public class ExternalActivity: BasicExternalActivity + public class ExternalActivity : BasicExternalActivity { - private ExternalActivity (BasicExternalActivity basic): base (basic) + private ExternalActivity(BasicExternalActivity basic) : base(basic) { // empty private ctor } - public static ExternalActivity FromBasic (BasicExternalActivity basic) + public Geography Geography + { + get { return Geography.FromIdentity(GeographyId); } + } + + public static ExternalActivity FromBasic(BasicExternalActivity basic) { return new ExternalActivity(basic); } - public static ExternalActivity FromIdentity (int externalActivityId) + public static ExternalActivity FromIdentity(int externalActivityId) { return FromBasic(SwarmDb.GetDatabaseForReading().GetExternalActivity(externalActivityId)); } - public static ExternalActivity Create (Organization organization, Geography geograpy, ExternalActivityType type, DateTime date, string description, Person createdByPerson) + 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, - date, type, description, - createdByPerson.Identity)); - } - - public Geography Geography - { - get { return Geography.FromIdentity(this.GeographyId); } + 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 -System.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 -System.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 a749531b..e8e6122c 100644 --- a/Logic/Swarm/ExternalIdentity.cs +++ b/Logic/Swarm/ExternalIdentity.cs @@ -8,10 +8,9 @@ namespace Swarmops.Logic.Swarm { public class ExternalIdentity : BasicExternalIdentity { - private Person attachedToPerson; - private ExternalIdentity (BasicExternalIdentity basic) + private ExternalIdentity(BasicExternalIdentity basic) : base(basic) { } @@ -19,96 +18,91 @@ namespace Swarmops.Logic.Swarm public new int ExternalIdentityIdentity { - get - { - return base.ExternalIdentityIdentity; - } + get { return base.ExternalIdentityIdentity; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + throw new InvalidOperationException( + "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } public new string ExternalSystem { - get - { - return base.ExternalSystem; - } + get { return base.ExternalSystem; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + throw new InvalidOperationException( + "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } + public new string UserID { - get - { - return base.UserID; - } + get { return base.UserID; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + throw new InvalidOperationException( + "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } + public new string Password { - get - { - return base.Password; - } + get { return base.Password; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + throw new InvalidOperationException( + "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } + public Person AttachedToPerson { get { - if (attachedToPerson == null) - attachedToPerson = Person.FromIdentity(base.AttachedToPersonID); - return attachedToPerson; + if (this.attachedToPerson == null) + this.attachedToPerson = Person.FromIdentity(base.AttachedToPersonID); + return this.attachedToPerson; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + throw new InvalidOperationException( + "Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); } } + public new ExternalIdentityType TypeOfAccount { - get - { - return base.TypeOfAccount; - } + get { return base.TypeOfAccount; } private set { - throw new InvalidOperationException("Do not set individual fields of ExternalIdentity separately. Use SetExternalIdentity() method."); + 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); } - public static ExternalIdentity FromIdentity (int externalIdentityId) + public static ExternalIdentity FromIdentity(int 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)); } - public static ExternalIdentity FromPersonIdAndType (int persId, ExternalIdentityType type) + public static ExternalIdentity FromPersonIdAndType(int persId, ExternalIdentityType 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); @@ -120,28 +114,25 @@ namespace Swarmops.Logic.Swarm } return retlist; - } - public ExternalIdentity SetExternalIdentity (string ExternalSystem, - string UserID, - string Password, - int AttachedToPerson, - ExternalIdentityType TypeOfAccount) + public ExternalIdentity SetExternalIdentity(string ExternalSystem, + string UserID, + string Password, + int AttachedToPerson, + ExternalIdentityType TypeOfAccount) { return FromBasic(SwarmDb.GetDatabaseForWriting().SetExternalIdentity( - this.Identity, TypeOfAccount, ExternalSystem, + Identity, TypeOfAccount, ExternalSystem, UserID, Password, AttachedToPerson)); - - - } - public static ExternalIdentity CreateExternalIdentity (string ExternalSystem, - string UserID, - string Password, - int AttachedToPerson, - ExternalIdentityType TypeOfAccount) + + public static ExternalIdentity CreateExternalIdentity(string ExternalSystem, + string UserID, + string Password, + int AttachedToPerson, + ExternalIdentityType TypeOfAccount) { try { @@ -149,13 +140,10 @@ namespace Swarmops.Logic.Swarm 0, TypeOfAccount, ExternalSystem, UserID, Password, AttachedToPerson)); } - catch(Exception ex) + catch (Exception ex) { throw new Exception("Failed to create ExternalIdentity", ex); } - - } - } -} +} \ No newline at end of file diff --git a/Logic/Swarm/Interfaces.cs b/Logic/Swarm/Interfaces.cs index 20110da5..76764f13 100644 --- a/Logic/Swarm/Interfaces.cs +++ b/Logic/Swarm/Interfaces.cs @@ -4,4 +4,4 @@ { void SetOwner(Person newOwner); } -} +} \ No newline at end of file diff --git a/Logic/Swarm/Membership.cs b/Logic/Swarm/Membership.cs index 76c14c86..87764248 100644 --- a/Logic/Swarm/Membership.cs +++ b/Logic/Swarm/Membership.cs @@ -14,10 +14,10 @@ namespace Swarmops.Logic.Swarm { public static readonly int GracePeriod = 28; private Organization organization; - private Person person; private BasicMembershipPaymentStatus paymentStatus; + private Person person; - private Membership (BasicMembership basic) + private Membership(BasicMembership basic) : base(basic) { } @@ -55,9 +55,9 @@ namespace Swarmops.Logic.Swarm { if (base.Expires != value) { - if (this.PersonId > 0 && this.OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) + if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) { - ChurnData.LogRetention(this.PersonId, this.OrganizationId, base.Expires); + ChurnData.LogRetention(PersonId, OrganizationId, base.Expires); } SwarmDb.GetDatabaseForWriting().SetMembershipExpires(Identity, value); base.Expires = value; @@ -65,44 +65,12 @@ namespace Swarmops.Logic.Swarm } } - public void SetPaymentStatus (MembershipPaymentStatus status, DateTime dateTime) - { - SwarmDb.GetDatabaseForWriting().SetMembershipPaymentStatus(Identity, status, dateTime); - LoadPaymentStatus(); - paymentStatus.Status = status; - paymentStatus.StatusDateTime = dateTime; - } - - private void LoadPaymentStatus () - { - if (paymentStatus == null) - { - paymentStatus = SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatus(this.Identity); - } - } - - - //Optimization metod, loadMultiple in one call - public static void LoadPaymentStatuses (Memberships mss) - { - Dictionary statuses = - SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatuses(mss.Identities); - foreach (Membership ms in mss) - { - if (ms.paymentStatus == null && statuses.ContainsKey(ms.Identity)) - { - ms.paymentStatus = statuses[ms.Identity]; - } - } - } - - public MembershipPaymentStatus PaymentStatus { get { LoadPaymentStatus(); - return paymentStatus.Status; + return this.paymentStatus.Status; } private set { @@ -119,7 +87,7 @@ namespace Swarmops.Logic.Swarm get { LoadPaymentStatus(); - return paymentStatus.StatusDateTime; + return this.paymentStatus.StatusDateTime; } private set { @@ -130,8 +98,39 @@ namespace Swarmops.Logic.Swarm } } + public void SetPaymentStatus(MembershipPaymentStatus status, DateTime dateTime) + { + SwarmDb.GetDatabaseForWriting().SetMembershipPaymentStatus(Identity, status, dateTime); + LoadPaymentStatus(); + this.paymentStatus.Status = status; + this.paymentStatus.StatusDateTime = dateTime; + } - public static Membership FromBasic (BasicMembership basic) + private void LoadPaymentStatus() + { + if (this.paymentStatus == null) + { + this.paymentStatus = SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatus(Identity); + } + } + + + //Optimization metod, loadMultiple in one call + public static void LoadPaymentStatuses(Memberships mss) + { + Dictionary statuses = + SwarmDb.GetDatabaseForReading().GetMembershipPaymentStatuses(mss.Identities); + foreach (Membership ms in mss) + { + if (ms.paymentStatus == null && statuses.ContainsKey(ms.Identity)) + { + ms.paymentStatus = statuses[ms.Identity]; + } + } + } + + + public static Membership FromBasic(BasicMembership basic) { return new Membership(basic); } @@ -151,24 +150,25 @@ namespace Swarmops.Logic.Swarm 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); 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); } - public static Membership Import (Person person, Organization organization, DateTime memberSince, - DateTime expires) + public static Membership Import(Person person, Organization organization, DateTime memberSince, + DateTime expires) { return - FromIdentity(SwarmDb.GetDatabaseForWriting().ImportMembership(person.Identity, organization.Identity, memberSince, - expires)); + 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) { @@ -197,12 +197,12 @@ namespace Swarmops.Logic.Swarm if (personRole.OrganizationId == OrganizationId) { PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, - personRole.OrganizationId, personRole.GeographyId, - Person.Identity, (int)personRole.Type, - string.Empty); + personRole.OrganizationId, personRole.GeographyId, + Person.Identity, (int) personRole.Type, + string.Empty); PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, - "Role " + personRole.Type.ToString() + " of " + personRole.Geography.Name + - " was deleted with membership.", string.Empty); + "Role " + personRole.Type + " of " + personRole.Geography.Name + + " was deleted with membership.", string.Empty); personRole.Delete(); } } @@ -210,15 +210,15 @@ 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 (!this.Person.MemberOfWithInherited(personRole.Organization)) + if (!Person.MemberOfWithInherited(personRole.Organization)) { PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, - personRole.OrganizationId, personRole.GeographyId, - Person.Identity, (int)personRole.Type, - string.Empty); + personRole.OrganizationId, personRole.GeographyId, + Person.Identity, (int) personRole.Type, + string.Empty); PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, - "Role " + personRole.Type.ToString() + " of " + personRole.Geography.Name + - " was deleted with membership of all suborgs.", string.Empty); + "Role " + personRole.Type + " of " + personRole.Geography.Name + + " was deleted with membership of all suborgs.", string.Empty); personRole.Delete(); } } @@ -238,15 +238,15 @@ namespace Swarmops.Logic.Swarm PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.MemberLost, - eventSource.ToString() + ":" + description, string.Empty); - PWEvents.CreateEvent(src, EventType.LostMember, actingPersonId, this.OrganizationId, Person.GeographyId, - Person.Identity, 0, OrganizationId.ToString()); + eventSource + ":" + description, string.Empty); + 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 && this.OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) + if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) { - ChurnData.LogChurn(this.PersonId, this.OrganizationId); + ChurnData.LogChurn(PersonId, OrganizationId); } SwarmDb.GetDatabaseForWriting().TerminateMembership(Identity); base.Active = false; @@ -260,9 +260,9 @@ namespace Swarmops.Logic.Swarm { try { - if (person.IsSubscribing(newsletterFeedId)) + if (this.person.IsSubscribing(newsletterFeedId)) { - person.SetSubscription(newsletterFeedId, false); + this.person.SetSubscription(newsletterFeedId, false); } } catch (Exception) diff --git a/Logic/Swarm/MembershipEvent.cs b/Logic/Swarm/MembershipEvent.cs index 80e338a7..05d95579 100644 --- a/Logic/Swarm/MembershipEvent.cs +++ b/Logic/Swarm/MembershipEvent.cs @@ -25,8 +25,8 @@ namespace Swarmops.Logic.Swarm this.Gender = PersonGender.Unknown; } - public MembershipEvent (DateTime dateTime, int personId, int organizationId, int geographyId, int birthYear, - PersonGender gender, int deltaCount) + public MembershipEvent(DateTime dateTime, int personId, int organizationId, int geographyId, int birthYear, + PersonGender gender, int deltaCount) { this.DateTime = dateTime; this.PersonId = personId; diff --git a/Logic/Swarm/MembershipEvents.cs b/Logic/Swarm/MembershipEvents.cs index 51444657..4a5420a0 100644 --- a/Logic/Swarm/MembershipEvents.cs +++ b/Logic/Swarm/MembershipEvents.cs @@ -26,9 +26,9 @@ namespace Swarmops.Logic.Swarm BasicPerson[] allPeople = SwarmDb.GetDatabaseForReading().GetAllPeople(); - var geoLookup = new Dictionary(); - var genderLookup = new Dictionary(); - var birthYearLookup = new Dictionary(); + Dictionary geoLookup = new Dictionary(); + Dictionary genderLookup = new Dictionary(); + Dictionary birthYearLookup = new Dictionary(); foreach (BasicPerson person in allPeople) { @@ -43,7 +43,7 @@ namespace Swarmops.Logic.Swarm // Third phase - for every membership, generate one or two membership events - var result = new MembershipEvents(); + MembershipEvents result = new MembershipEvents(); foreach (BasicMembership membership in allMemberships) { @@ -59,29 +59,29 @@ namespace Swarmops.Logic.Swarm } result.Add(new MembershipEvent(membership.MemberSince, membership.PersonId, membership.OrganizationId, - geographyId, birthYear, gender, 1)); + geographyId, birthYear, gender, 1)); if (!membership.Active) { - var 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. // To solve this, make sure they are more than five seconds apart. - if (((DateTime) membership.DateTerminated).Date == membership.MemberSince.Date) + if (membership.DateTerminated.Date == membership.MemberSince.Date) // First simple check { - if ((((DateTime) 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); } } - result.Add(new MembershipEvent((DateTime) membership.DateTerminated + safetyDelta, - membership.PersonId, membership.OrganizationId, geographyId, - birthYear, gender, -1)); + result.Add(new MembershipEvent(membership.DateTerminated + safetyDelta, + membership.PersonId, membership.OrganizationId, geographyId, + birthYear, gender, -1)); } } @@ -93,16 +93,16 @@ namespace Swarmops.Logic.Swarm } - public static MembershipEvents FromXml (string xml) + public static MembershipEvents FromXml(string xml) { - var serializer = new XmlSerializer(typeof (MembershipEvents)); + XmlSerializer serializer = new XmlSerializer(typeof (MembershipEvents)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); byte[] xmlBytes = Encoding.Default.GetBytes(xml); stream.Write(xmlBytes, 0, xmlBytes.Length); stream.Position = 0; - var result = (MembershipEvents) serializer.Deserialize(stream); + MembershipEvents result = (MembershipEvents) serializer.Deserialize(stream); stream.Close(); return result; @@ -111,9 +111,9 @@ namespace Swarmops.Logic.Swarm public string ToXml() { - var serializer = new XmlSerializer(typeof (MembershipEvents)); + XmlSerializer serializer = new XmlSerializer(typeof (MembershipEvents)); - var stream = new MemoryStream(); + MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, this); byte[] xmlBytes = stream.GetBuffer(); @@ -125,13 +125,13 @@ 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) { return -1; } - else if (x.DateTime > y.DateTime) + if (x.DateTime > y.DateTime) { return 1; } diff --git a/Logic/Swarm/Memberships.cs b/Logic/Swarm/Memberships.cs index 4b1a83c9..a0a2d2b8 100644 --- a/Logic/Swarm/Memberships.cs +++ b/Logic/Swarm/Memberships.cs @@ -10,9 +10,14 @@ namespace Swarmops.Logic.Swarm { public class Memberships : List { - public static Memberships FromArray (BasicMembership[] basicArray) + public int[] Identities { - var result = new Memberships(); + get { return LogicServices.ObjectsToIdentifiers(ToArray()); } + } + + public static Memberships FromArray(BasicMembership[] basicArray) + { + Memberships result = new Memberships(); result.Capacity = basicArray.Length*11/10; foreach (BasicMembership basic in basicArray) @@ -22,11 +27,6 @@ namespace Swarmops.Logic.Swarm return result; } - - public int[] Identities - { - get { return LogicServices.ObjectsToIdentifiers(ToArray()); } - } /* @@ -35,29 +35,29 @@ 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}); } - public static int GetMemberCountForOrganizations (int[] organizationIds) + public static int GetMemberCountForOrganizations(int[] 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); } - public static int GetMemberCountForOrganizationSince (int orgId, DateTime sinceDateTime) + public static int GetMemberCountForOrganizationSince(int orgId, DateTime sinceDateTime) { return SwarmDb.GetDatabaseForReading().GetMembershipCountForOrganizationsSince(new[] {orgId}, sinceDateTime); } - public static int GetMemberCountForOrganizations (Organizations organizations) + public static int GetMemberCountForOrganizations(Organizations organizations) { - var idArray = new List(); + List idArray = new List(); foreach (Organization organization in organizations) { @@ -67,12 +67,12 @@ namespace Swarmops.Logic.Swarm return GetMemberCountForOrganizations(idArray.ToArray()); } - public Memberships RemoveToMatchAuthority (Geography personGeography, Authority authority) + public Memberships RemoveToMatchAuthority(Geography personGeography, Authority 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) { @@ -82,12 +82,12 @@ namespace Swarmops.Logic.Swarm return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organization)); } - public static Memberships ForOrganization (Organization organization) + public static Memberships ForOrganization(Organization organization) { return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organization, DatabaseCondition.ActiveTrue)); } - public static Memberships ForOrganizations (Organizations organizations, bool includeTerminated) + public static Memberships ForOrganizations(Organizations organizations, bool includeTerminated) { if (!includeTerminated) { @@ -97,37 +97,40 @@ namespace Swarmops.Logic.Swarm return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organizations)); } - public static Memberships ForOrganizations (Organizations organizations) + public static Memberships ForOrganizations(Organizations organizations) { return FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(organizations, DatabaseCondition.ActiveTrue)); } - public static Memberships GetExpiring (Organization organization, DateTime dateExpiry) + public static Memberships GetExpiring(Organization organization, DateTime dateExpiry) { return GetExpiring(organization, dateExpiry, dateExpiry); } - public static Memberships GetExpired (Organization organization) + public static Memberships GetExpired(Organization organization) { return FromArray(SwarmDb.GetDatabaseForReading().GetExpiringMemberships(organization, DateTime.MinValue, - DateTime.Now)); + 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)); + return + 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)); + return + 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); } - } } \ No newline at end of file diff --git a/Logic/Swarm/OfficerChain.cs b/Logic/Swarm/OfficerChain.cs index 84471158..529be934 100644 --- a/Logic/Swarm/OfficerChain.cs +++ b/Logic/Swarm/OfficerChain.cs @@ -2,31 +2,31 @@ using Swarmops.Logic.Structure; namespace Swarmops.Logic.Swarm { - public class OfficerChain: People + public class OfficerChain : People { - private OfficerChain (People original, int organizationId) + private readonly int organizationId; + + private OfficerChain(People original, int organizationId) { - this.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 = People.FromIdentities(concernedPeopleId); + People concernedPeople = FromIdentities(concernedPeopleId); 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) + foreach (Person person in this) { person.SendOfficerNotice(subject, body, this.organizationId); } } - - private readonly int organizationId; } -} +} \ No newline at end of file diff --git a/Logic/Swarm/Parley.cs b/Logic/Swarm/Parley.cs index 78ba09e8..88a4e4ee 100644 --- a/Logic/Swarm/Parley.cs +++ b/Logic/Swarm/Parley.cs @@ -9,41 +9,13 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class Parley: BasicParley, IAttestable + public class Parley : BasicParley, IAttestable { - private Parley (BasicParley basic): base (basic) + private Parley(BasicParley basic) : base(basic) { // empty pvt ctor } - public static Parley FromBasic (BasicParley basic) - { - return new Parley(basic); - } - - public static Parley FromIdentity (int parleyId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParley(parleyId)); - } - - 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, - -(budgetInitial.Identity), name, geography.Identity, - description, informationUrl, startDate, endDate, - budgetCents, guaranteeCents, attendanceFeeCents)); - - 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) - { - return ParleyOption.Create(this, description, amountCents); - } - public ParleyOptions Options { get { return ParleyOptions.ForParley(this); } @@ -54,28 +26,14 @@ namespace Swarmops.Logic.Swarm get { return ParleyAttendees.ForParley(this); } } - public ParleyAttendee CreateAttendee (string firstName, string lastName, string email, bool asGuest) - { - Person newAttendee = Person.Create(firstName + "|" + lastName, email, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, - this.Organization.DefaultCountry.Code, DateTime.Now, PersonGender.Unknown); - - return ParleyAttendee.Create(this, newAttendee, asGuest); - } - public Organization Organization { - get { return Structure.Organization.FromIdentity(this.OrganizationId); } + get { return Organization.FromIdentity(OrganizationId); } } public Person Person { - get { return Person.FromIdentity(this.PersonId); } - } - - public FinancialAccount Budget - { - get { return FinancialAccount.FromIdentity(this.BudgetId); } + get { return Person.FromIdentity(PersonId); } } public decimal BudgetDecimal @@ -95,16 +53,13 @@ namespace Swarmops.Logic.Swarm public new bool Open { - get - { - return base.Open; - } + get { return base.Open; } set { if (base.Open != value) { base.Open = value; - SwarmDb.GetDatabaseForWriting().SetParleyOpen(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetParleyOpen(Identity, value); } } } @@ -122,144 +77,13 @@ namespace Swarmops.Logic.Swarm } } - #region Implementation of IAttestable - - public void Attest(Person attester) - { - if (this.Attested) - { - return; - } - - // If needed, create new account for parley - - FinancialAccount ourBudget; - FinancialAccount parentBudget; - int year = DateTime.Today.Year; - - if (base.BudgetId < 0) // no account created yet - { - ourBudget = FinancialAccount.Create(this.Budget.Organization, - "Conf: " + this.Name, - FinancialAccountType.Cost, - this.Budget); - - parentBudget = this.Budget; - - base.BudgetId = ourBudget.Identity; - ourBudget.Owner = this.Person; - SwarmDb.GetDatabaseForWriting().SetParleyBudget(this.Identity, ourBudget.Identity); - } - else - { - // The budget has been created already - we should already be initialized. Verify this - // by checking that we were already attested once. - - if (!this.AttestedOnce) - { - throw new InvalidOperationException( - "Budget exists despite parley not having been attested. This should not be possible."); - } - - ourBudget = this.Budget; - parentBudget = this.ParentBudget; - } - - ourBudget.SetBudgetCents(DateTime.Today.Year, -this.BudgetCents); - parentBudget.SetBudgetCents(DateTime.Today.Year, - parentBudget.GetBudgetCents(year) + this.BudgetCents); // cost budgets are negative - - // Reserve the guarantee money - - FinancialTransaction guaranteeFundsTx = FinancialTransaction.Create(this.OrganizationId, DateTime.Now, - "Conference #" + - this.Identity.ToString() + " Guarantee"); - guaranteeFundsTx.AddRow(this.Budget, -this.GuaranteeCents, attester); - guaranteeFundsTx.AddRow(this.Budget.Parent, this.GuaranteeCents, attester); - - // Finally, set as attested - - PWEvents.CreateEvent( - EventSource.PirateWeb, EventType.ParleyAttested, attester.Identity, - this.OrganizationId, 0, 0, this.Identity, string.Empty); - - base.Attested = true; - SwarmDb.GetDatabaseForWriting().SetParleyAttested(this.Identity, true); - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Attestation, - FinancialDependencyType.Parley, this.Identity, - DateTime.Now, attester.Identity, (double)(this.GuaranteeDecimal)); - - - } - - public void Deattest(Person deattester) - { - throw new NotImplementedException(); - /* - base.Attested = false; - SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, - FinancialDependencyType.Parley, this.Identity, - DateTime.Now, deattester.Identity, (double)(this.GuaranteeDecimal+this.BudgetDecimal));*/ - - // TODO: Remove budget, remove financial account, set unattested - - // this.BudgetId = this.Budget.ParentIdentity; - - } - - - public FinancialAccount ParentBudget - { - get - { - // If the financial account for this parley is uninitialized, the BudgetId of base is negative to indicate that. - - if (base.BudgetId < 0) - { - return FinancialAccount.FromIdentity(-base.BudgetId); - } - else - { - return Budget.Parent; - } - } - } - - - #endregion - - public void CloseBudget(Person closingPerson) - { - Int64 remainingFunds = -this.Budget.GetDeltaCents(this.CreatedDateTime, DateTime.Now); - - FinancialTransaction transaction = FinancialTransaction.Create(this.OrganizationId, - DateTime.Now, - "Closing conference #" + this.Identity); - transaction.AddRow(this.Budget, remainingFunds, closingPerson); - transaction.AddRow(this.Budget.Parent, -remainingFunds, closingPerson); - } - - public void CancelBudget() - { - int year = DateTime.Today.Year; - - // Adjust budgets. (NB: Cost budgets are negative, but the bookkeeping cost funds are positive. Some sign reversal is necessary.) - - if (this.BudgetId > 0) // Budget attested and allocated - { - this.Budget.Parent.SetBudgetCents(year, - this.Budget.Parent.GetBudgetCents(year) - this.BudgetCents); // cost budgets are negative - this.Budget.SetBudgetCents(year, 0); - } - } - private bool AttestedOnce { get { BasicFinancialValidation[] validations = SwarmDb.GetDatabaseForReading().GetFinancialValidations(FinancialDependencyType.Parley, - this.Identity); + Identity); foreach (BasicFinancialValidation validation in validations) { @@ -272,5 +96,173 @@ namespace Swarmops.Logic.Swarm return false; } } + + #region Implementation of IAttestable + + public FinancialAccount ParentBudget + { + get + { + // If the financial account for this parley is uninitialized, the BudgetId of base is negative to indicate that. + + if (base.BudgetId < 0) + { + return FinancialAccount.FromIdentity(-base.BudgetId); + } + return this.Budget.Parent; + } + } + + public void Attest(Person attester) + { + if (Attested) + { + return; + } + + // If needed, create new account for parley + + FinancialAccount ourBudget; + FinancialAccount parentBudget; + int year = DateTime.Today.Year; + + if (base.BudgetId < 0) // no account created yet + { + ourBudget = FinancialAccount.Create(Budget.Organization, + "Conf: " + Name, + FinancialAccountType.Cost, + Budget); + + parentBudget = Budget; + + base.BudgetId = ourBudget.Identity; + ourBudget.Owner = Person; + SwarmDb.GetDatabaseForWriting().SetParleyBudget(Identity, ourBudget.Identity); + } + else + { + // The budget has been created already - we should already be initialized. Verify this + // by checking that we were already attested once. + + if (!AttestedOnce) + { + throw new InvalidOperationException( + "Budget exists despite parley not having been attested. This should not be possible."); + } + + ourBudget = Budget; + parentBudget = ParentBudget; + } + + 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, + "Conference #" + + Identity + " Guarantee"); + guaranteeFundsTx.AddRow(Budget, -GuaranteeCents, attester); + guaranteeFundsTx.AddRow(Budget.Parent, GuaranteeCents, attester); + + // Finally, set as attested + + 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, + FinancialDependencyType.Parley, Identity, + DateTime.Now, attester.Identity, (double) (GuaranteeDecimal)); + } + + public void Deattest(Person deattester) + { + throw new NotImplementedException(); + /* + base.Attested = false; + SwarmDb.GetDatabaseForWriting().CreateFinancialValidation(FinancialValidationType.Deattestation, + FinancialDependencyType.Parley, this.Identity, + DateTime.Now, deattester.Identity, (double)(this.GuaranteeDecimal+this.BudgetDecimal));*/ + + // TODO: Remove budget, remove financial account, set unattested + + // this.BudgetId = this.Budget.ParentIdentity; + } + + #endregion + + public FinancialAccount Budget + { + get { return FinancialAccount.FromIdentity(BudgetId); } + } + + public static Parley FromBasic(BasicParley basic) + { + return new Parley(basic); + } + + public static Parley FromIdentity(int parleyId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetParley(parleyId)); + } + + 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, + -(budgetInitial.Identity), name, geography.Identity, + description, informationUrl, startDate, endDate, + budgetCents, guaranteeCents, attendanceFeeCents)); + + 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) + { + return ParleyOption.Create(this, description, amountCents); + } + + public ParleyAttendee CreateAttendee(string firstName, string lastName, string email, bool asGuest) + { + 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); + } + + public void CloseBudget(Person closingPerson) + { + Int64 remainingFunds = -Budget.GetDeltaCents(CreatedDateTime, DateTime.Now); + + FinancialTransaction transaction = FinancialTransaction.Create(OrganizationId, + DateTime.Now, + "Closing conference #" + Identity); + transaction.AddRow(Budget, remainingFunds, closingPerson); + transaction.AddRow(Budget.Parent, -remainingFunds, closingPerson); + } + + public void CancelBudget() + { + int year = DateTime.Today.Year; + + // Adjust budgets. (NB: Cost budgets are negative, but the bookkeeping cost funds are positive. Some sign reversal is necessary.) + + if (BudgetId > 0) // Budget attested and allocated + { + Budget.Parent.SetBudgetCents(year, + Budget.Parent.GetBudgetCents(year) - BudgetCents); // cost budgets are negative + Budget.SetBudgetCents(year, 0); + } + } } -} +} \ No newline at end of file diff --git a/Logic/Swarm/ParleyAttendee.cs b/Logic/Swarm/ParleyAttendee.cs index 34276bdd..4fb8d607 100644 --- a/Logic/Swarm/ParleyAttendee.cs +++ b/Logic/Swarm/ParleyAttendee.cs @@ -7,33 +7,13 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class ParleyAttendee: BasicParleyAttendee + public class ParleyAttendee : BasicParleyAttendee { - private ParleyAttendee (BasicParleyAttendee basic): base(basic) + private ParleyAttendee(BasicParleyAttendee basic) : base(basic) { // empty pvt ctor } - public static ParleyAttendee FromBasic (BasicParleyAttendee basic) - { - return new ParleyAttendee(basic); - } - - public static ParleyAttendee FromIdentity (int parleyAttendeeId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyAttendee(parleyAttendeeId)); - } - - public static ParleyAttendee Create (Parley parley, Person person, bool asGuest) - { - return FromIdentity(SwarmDb.GetDatabaseForWriting().CreateParleyAttendee(parley.Identity, person.Identity, asGuest)); - } - - public void AddOption (ParleyOption option) - { - SwarmDb.GetDatabaseForWriting().AddParleyAttendeeOption(this.Identity, option.Identity); - } - public ParleyOptions Options { get { return ParleyOptions.ForParleyAttendee(this); } @@ -41,7 +21,7 @@ namespace Swarmops.Logic.Swarm public Parley Parley { - get { return Parley.FromIdentity(this.ParleyId); } + get { return Parley.FromIdentity(ParleyId); } } public new bool Active @@ -51,7 +31,7 @@ namespace Swarmops.Logic.Swarm { if (value != base.Active) { - SwarmDb.GetDatabaseForWriting().SetParleyAttendeeActive(this.Identity, value); + SwarmDb.GetDatabaseForWriting().SetParleyAttendeeActive(Identity, value); base.Active = value; } } @@ -59,7 +39,7 @@ namespace Swarmops.Logic.Swarm public Person Person { - get { return Person.FromIdentity(this.PersonId); } + get { return Person.FromIdentity(PersonId); } } public OutboundInvoice Invoice @@ -67,25 +47,47 @@ namespace Swarmops.Logic.Swarm get { return OutboundInvoice.FromIdentity(base.OutboundInvoiceId); } } + public static ParleyAttendee FromBasic(BasicParleyAttendee basic) + { + return new ParleyAttendee(basic); + } + + public static ParleyAttendee FromIdentity(int parleyAttendeeId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyAttendee(parleyAttendeeId)); + } + + public static ParleyAttendee Create(Parley parley, Person person, bool asGuest) + { + return + FromIdentity(SwarmDb.GetDatabaseForWriting() + .CreateParleyAttendee(parley.Identity, person.Identity, asGuest)); + } + + public void AddOption(ParleyOption option) + { + SwarmDb.GetDatabaseForWriting().AddParleyAttendeeOption(Identity, option.Identity); + } + public void SendInvoice() { DateTime invoiceDue = DateTime.Today.AddDays(14); - DateTime maxInvoiceDue = this.Parley.StartDate.AddDays(-10); + DateTime maxInvoiceDue = Parley.StartDate.AddDays(-10); if (invoiceDue > maxInvoiceDue) { invoiceDue = maxInvoiceDue; } - OutboundInvoice invoice = OutboundInvoice.Create(this.Parley.Organization, this.Parley.Person, invoiceDue, - this.Parley.Budget, this.Person.Name, this.Person.Mail, - string.Empty, - this.Parley.Organization.DefaultCountry.Currency, true, - string.Empty); + 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 " + this.Parley.Name, this.Parley.AttendanceFeeCents); // TODO: Localize + invoice.AddItem("Deltagarkostnad " + Parley.Name, Parley.AttendanceFeeCents); // TODO: Localize - ParleyOptions options = this.Options; + ParleyOptions options = Options; foreach (ParleyOption option in options) { @@ -96,11 +98,11 @@ namespace Swarmops.Logic.Swarm // Create the financial transaction with rows FinancialTransaction transaction = - FinancialTransaction.Create(this.Parley.OrganizationId, DateTime.Now, - "Outbound Invoice #" + invoice.Identity + " to " + this.Person.Name); + FinancialTransaction.Create(Parley.OrganizationId, DateTime.Now, + "Outbound Invoice #" + invoice.Identity + " to " + Person.Name); - transaction.AddRow(this.Parley.Organization.FinancialAccounts.AssetsOutboundInvoices, invoice.AmountCents, null); - transaction.AddRow(this.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 @@ -109,15 +111,15 @@ namespace Swarmops.Logic.Swarm // Create the event for PirateBot-Mono to send off mails PWEvents.CreateEvent(EventSource.PirateWeb, EventType.OutboundInvoiceCreated, - this.PersonId, this.Parley.OrganizationId, 1, this.PersonId, - invoice.Identity, string.Empty); + PersonId, Parley.OrganizationId, 1, PersonId, + invoice.Identity, string.Empty); // Update the attendee as invoiced base.Invoiced = true; base.OutboundInvoiceId = invoice.Identity; - SwarmDb.GetDatabaseForWriting().SetParleyAttendeeInvoiced(this.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 82904d0e..1e8575cd 100644 --- a/Logic/Swarm/ParleyAttendees.cs +++ b/Logic/Swarm/ParleyAttendees.cs @@ -4,11 +4,11 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class ParleyAttendees: PluralBase + public class ParleyAttendees : PluralBase { - public static ParleyAttendees ForParley (Parley parley) + public static ParleyAttendees ForParley(Parley 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 edea8e81..48367b6f 100644 --- a/Logic/Swarm/ParleyOption.cs +++ b/Logic/Swarm/ParleyOption.cs @@ -4,31 +4,33 @@ using Swarmops.Database; namespace Swarmops.Logic.Swarm { - public class ParleyOption: BasicParleyOption + public class ParleyOption : BasicParleyOption { - private ParleyOption (BasicParleyOption basic): base (basic) + private ParleyOption(BasicParleyOption basic) : base(basic) { // empty pvt ctor } - public static ParleyOption FromBasic (BasicParleyOption basic) - { - return new ParleyOption(basic); - } - - public static ParleyOption FromIdentity (int parleyOptionId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyOption(parleyOptionId)); - } - - public static ParleyOption Create (Parley parley, string description, Int64 amountCents) - { - return FromIdentity(SwarmDb.GetDatabaseForWriting().CreateParleyOption(parley.Identity, description, amountCents)); - } - public decimal AmountDecimal { get { return AmountCents/100.0m; } } + + public static ParleyOption FromBasic(BasicParleyOption basic) + { + return new ParleyOption(basic); + } + + public static ParleyOption FromIdentity(int parleyOptionId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetParleyOption(parleyOptionId)); + } + + public static ParleyOption Create(Parley parley, string description, Int64 amountCents) + { + return + 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 2a58b530..4c36bd3a 100644 --- a/Logic/Swarm/ParleyOptions.cs +++ b/Logic/Swarm/ParleyOptions.cs @@ -4,33 +4,30 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class ParleyOptions: PluralBase + public class ParleyOptions : PluralBase { - public static ParleyOptions ForParley (Parley parley) + public static ParleyOptions ForParley(Parley parley) { 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)); } - else - { - 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); return FromIdentities(parleyOptionIds); } - public static ParleyOptions FromIdentities (int[] identities) + public static ParleyOptions FromIdentities(int[] identities) { ParleyOptions result = new ParleyOptions(); @@ -42,4 +39,4 @@ namespace Swarmops.Logic.Swarm return result; } } -} +} \ No newline at end of file diff --git a/Logic/Swarm/Parleys.cs b/Logic/Swarm/Parleys.cs index 3c870ee4..f7f6ac24 100644 --- a/Logic/Swarm/Parleys.cs +++ b/Logic/Swarm/Parleys.cs @@ -6,42 +6,8 @@ using Swarmops.Logic.Support; namespace Swarmops.Logic.Swarm { - public class Parleys: PluralBase + public class Parleys : PluralBase { - public static Parleys ForOrganization (Organization organization) - { - return ForOrganization(organization, false); - } - - public static Parleys ForOrganization (Organization organization, bool includeClosed) - { - if (includeClosed) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization)); - } - else - { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization, DatabaseCondition.OpenTrue)); - } - } - - public static Parleys ForOwner (Person person) - { - return ForOwner(person, false); - } - - public static Parleys ForOwner (Person person, bool includeClosed) - { - if (includeClosed) - { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(person)); - } - else - { - return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(person, DatabaseCondition.OpenTrue)); - } - } - public Parleys WhereUnattested { get @@ -53,8 +19,32 @@ namespace Swarmops.Logic.Swarm } } + public static Parleys ForOrganization(Organization organization) + { + return ForOrganization(organization, false); + } + public static Parleys ForOrganization(Organization organization, bool includeClosed) + { + if (includeClosed) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization)); + } + return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(organization, DatabaseCondition.OpenTrue)); + } + public static Parleys ForOwner(Person person) + { + return ForOwner(person, false); + } + public static Parleys ForOwner(Person person, bool includeClosed) + { + if (includeClosed) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetParleys(person)); + } + 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 2a83db66..4c459d0e 100644 --- a/Logic/Swarm/PaymentCode.cs +++ b/Logic/Swarm/PaymentCode.cs @@ -7,39 +7,39 @@ namespace Swarmops.Logic.Swarm { public class PaymentCode : BasicPaymentCode { - private PaymentCode (BasicPaymentCode basic) + private PaymentCode(BasicPaymentCode basic) : base(basic) { // empty } - public static PaymentCode CreateFromPhone (string phoneNumber) + public static PaymentCode CreateFromPhone(string phoneNumber) { return Create(phoneNumber, 0); } - public static PaymentCode CreateFromPerson (Person person) + public static PaymentCode CreateFromPerson(Person person) { return CreateFromPerson(person.Identity); } - public static PaymentCode CreateFromPerson (int personId) + public static PaymentCode CreateFromPerson(int personId) { return Create(string.Empty, personId); } - public static PaymentCode FromBasic (BasicPaymentCode basic) + public static PaymentCode FromBasic(BasicPaymentCode basic) { return new PaymentCode(basic); } - public static PaymentCode FromCode (string paymentCode) + public static PaymentCode FromCode(string 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; @@ -65,17 +65,17 @@ namespace Swarmops.Logic.Swarm } - public void Claim (Person claimingPerson) + public void Claim(Person claimingPerson) { Claim(claimingPerson.Identity); } - public void Claim (int claimingPersonId) + public void Claim(int claimingPersonId) { SwarmDb.GetDatabaseForWriting().ClaimPaymentCode(Identity, claimingPersonId); } - private static string CreateRandomCode (int length) + private static string CreateRandomCode(int length) { return Authentication.CreateRandomPassword(length); } diff --git a/Logic/Swarm/People.cs b/Logic/Swarm/People.cs index 10110a29..74876104 100644 --- a/Logic/Swarm/People.cs +++ b/Logic/Swarm/People.cs @@ -16,9 +16,9 @@ namespace Swarmops.Logic.Swarm get { return LogicServices.ObjectsToIdentifiers(ToArray()); } } - public static People FromMemberships (Memberships memberships) + public static People FromMemberships(Memberships memberships) { - var personIds = new List(); + List personIds = new List(); foreach (Membership membership in memberships) { @@ -28,14 +28,14 @@ namespace Swarmops.Logic.Swarm return FromIdentities(personIds.ToArray()); } - public static People FromIdentities (int[] personIds) + public static People FromIdentities(int[] personIds) { if (personIds.Length > 500) { // If over fivehundred identities are requested, we won't pass the array to // SQL Server. Rather, we'll get ALL the people and parse the list ourselves. - var lookup = new Dictionary(); + Dictionary lookup = new Dictionary(); foreach (int key in personIds) { @@ -43,7 +43,7 @@ namespace Swarmops.Logic.Swarm } BasicPerson[] basicArray = SwarmDb.GetDatabaseForReading().GetAllPeople(); - var result = new People(); + People result = new People(); for (int index = 0; index < basicArray.Length; index++) { @@ -55,18 +55,15 @@ namespace Swarmops.Logic.Swarm return result; } - else - { - return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeople(personIds)); - } + return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeople(personIds)); } - public static People GetAll () + public static People GetAll() { return People.FromArray(SwarmDb.GetDatabaseForReading().GetAllPeople()); } - public static People FromNamePattern (string namePattern) + public static People FromNamePattern(string namePattern) { if (namePattern.Trim().Length < 3) { @@ -76,12 +73,12 @@ namespace Swarmops.Logic.Swarm 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)); } - public static People FromEmailPattern (string emailPattern) + public static People FromEmailPattern(string emailPattern) { // Remove any injection codes emailPattern = emailPattern.Replace("%", String.Empty).Trim(); @@ -96,7 +93,7 @@ namespace Swarmops.Logic.Swarm 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(); @@ -111,7 +108,7 @@ namespace Swarmops.Logic.Swarm 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(); @@ -126,19 +123,18 @@ namespace Swarmops.Logic.Swarm 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 null; // If no valid search string was supplied } - public static People FromEmail (string email) + public static People FromEmail(string email) { if (email.Length > 0) { @@ -148,7 +144,7 @@ namespace Swarmops.Logic.Swarm 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) @@ -163,8 +159,8 @@ namespace Swarmops.Logic.Swarm return set1; } - var result = new People(); - var set2Lookup = new Dictionary(); + People result = new People(); + Dictionary set2Lookup = new Dictionary(); // Build set2's lookup table @@ -186,7 +182,7 @@ namespace Swarmops.Logic.Swarm 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) @@ -203,7 +199,7 @@ namespace Swarmops.Logic.Swarm // Build table, eliminating duplicates - var table = new Dictionary(); + Dictionary table = new Dictionary(); foreach (Person person in set1) { @@ -221,7 +217,7 @@ namespace Swarmops.Logic.Swarm // Assemble result, without any nulls in the original sets - var result = new People(); + People result = new People(); foreach (Person person in table.Values) { @@ -231,21 +227,21 @@ namespace Swarmops.Logic.Swarm return result; } - public People LogicalAnd (People set2) + public People LogicalAnd(People set2) { return LogicalAnd(this, set2); } - public People LogicalOr (People set2) + public People LogicalOr(People set2) { return LogicalOr(this, set2); } - public People Filter (Predicate match) + public People Filter(Predicate match) { People retlist = new People(); - this.ForEach(delegate(Person p) + ForEach(delegate(Person p) { if (match(p)) retlist.Add(p); @@ -265,7 +261,7 @@ namespace Swarmops.Logic.Swarm { return FromOrganizationAndGeography(organization, geography); } - else if (pattern.Length < 3) + if (pattern.Length < 3) { // too short pattern! Return empty set. return new People(); @@ -273,7 +269,8 @@ namespace Swarmops.Logic.Swarm // First, get list of people in the geography, then filter on memberships - BasicPerson[] candidates = SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern(geoTree.Identities, pattern); + BasicPerson[] candidates = + SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern(geoTree.Identities, pattern); return FilterByMembership(candidates, organization); } @@ -295,7 +292,6 @@ namespace Swarmops.Logic.Swarm private static People FilterByMembership(BasicPerson[] candidates, Organization organization) { - // Get the organization tree Organizations orgTree = organization.GetTree(); @@ -304,7 +300,7 @@ namespace Swarmops.Logic.Swarm // that has at least one membership in an organization in the lookup table, // add that person to the final result. - var lookup = new Dictionary(); + Dictionary lookup = new Dictionary(); foreach (Organization org in orgTree) { @@ -316,7 +312,7 @@ namespace Swarmops.Logic.Swarm Dictionary> memberships = SwarmDb.GetDatabaseForReading().GetMembershipsForPeople(LogicServices.ObjectsToIdentifiers(candidates)); - var result = new People(); + People result = new People(); foreach (BasicPerson basicPerson in candidates) { @@ -342,7 +338,7 @@ namespace Swarmops.Logic.Swarm return result; } - public static People FromGeography (int geographyId) + public static People FromGeography(int geographyId) { Geographies geoTree = Geography.FromIdentity(geographyId).GetTree(); @@ -350,7 +346,7 @@ namespace Swarmops.Logic.Swarm BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies(geoTree.Identities); - var result = new People(); + People result = new People(); foreach (BasicPerson basicPerson in people) { @@ -360,22 +356,20 @@ namespace Swarmops.Logic.Swarm return result; } - public static People FromSingle (Person person) + public static People FromSingle(Person person) { - var result = new People(); + People result = new People(); result.Add(person); return result; } - - - public static People FromArray (Person[] personArray) + public static People FromArray(Person[] personArray) { - var result = new People(); + People result = new People(); - result.Capacity = personArray.Length * 11 / 10; + result.Capacity = personArray.Length*11/10; foreach (Person person in personArray) { result.Add(person); @@ -384,11 +378,11 @@ namespace Swarmops.Logic.Swarm return result; } - public static People FromArray (BasicPerson[] personArray) + public static People FromArray(BasicPerson[] personArray) { - var result = new People(); + People result = new People(); - result.Capacity = personArray.Length * 11 / 10; + result.Capacity = personArray.Length*11/10; foreach (BasicPerson basic in personArray) { result.Add(Person.FromBasic(basic)); @@ -398,32 +392,34 @@ namespace Swarmops.Logic.Swarm } - public static People FromOptionalData (ObjectOptionalDataType dataType, string data) + public static People FromOptionalData(ObjectOptionalDataType dataType, string data) { - return People.FromIdentities(SwarmDb.GetDatabaseForReading().GetObjectsByOptionalData(ObjectType.Person, dataType, data)); + return + 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)); } - public static People FromPhoneNumber (string countryCode, string phoneNumber) + public static People FromPhoneNumber(string countryCode, string phoneNumber) { return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromPhoneNumber(countryCode, phoneNumber)); } - public People GetVisiblePeopleByAuthority (Authority authority) + public People GetVisiblePeopleByAuthority(Authority authority) { 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(); @@ -455,14 +451,14 @@ namespace Swarmops.Logic.Swarm return result; } - public People RemoveUnique () + public People RemoveUnique() { BasicPerson[] arrayToFilter = ToArray(); BasicPerson[] filtered = Authorization.FilterUniquePeople(arrayToFilter); return FromArray(filtered); } - public People RemoveUnlisted () + public People RemoveUnlisted() { BasicPerson[] arrayToFilter = ToArray(); BasicPerson[] filtered = Authorization.FilterUnlistedPeople(arrayToFilter); @@ -482,16 +478,16 @@ namespace Swarmops.Logic.Swarm } }*/ - public static People FromNewsletterFeed (int feedId) + public static People FromNewsletterFeed(int feedId) { int[] subscriberIds = SwarmDb.GetDatabaseForReading().GetSubscribersForNewsletterFeed(2); return FromIdentities(subscriberIds); } - public new void Remove (Person personToRemove) + public new void Remove(Person personToRemove) { - for (int index = 0; index < this.Count; index++) + for (int index = 0; index < Count; index++) { if (this[index].Identity == personToRemove.Identity) { @@ -502,14 +498,14 @@ namespace Swarmops.Logic.Swarm } - public static Dictionary GetPeopleGeographies () + public static Dictionary GetPeopleGeographies() { return SwarmDb.GetDatabaseForReading().GetPeopleGeographies(); } - public static People FromIdentities (int[] personIds, bool preserveOrder) + public static People FromIdentities(int[] personIds, bool preserveOrder) { - People set = People.FromIdentities(personIds); + People set = FromIdentities(personIds); if (preserveOrder == false) { diff --git a/Logic/Swarm/Person.cs b/Logic/Swarm/Person.cs index 673c768e..dea6944e 100644 --- a/Logic/Swarm/Person.cs +++ b/Logic/Swarm/Person.cs @@ -10,6 +10,7 @@ using Swarmops.Basic.Types; using Swarmops.Database; using Swarmops.Database.Attributes; using Swarmops.Logic.Communications; +using Swarmops.Logic.DashboardTasks; using Swarmops.Logic.Security; using Swarmops.Logic.Special.Mail; using Swarmops.Logic.Special.Sweden; @@ -23,9 +24,10 @@ namespace Swarmops.Logic.Swarm public class Person : BasicPerson, IComparable, IHasIdentity { private readonly IHandleProvider handleProvider; + private ObjectOptionalData _optionalData; private Dictionary subscriptions; - protected Person (BasicPerson basic) + protected Person(BasicPerson basic) : base(basic) { // Today, we set the Swedish handle provider. This can be changed as desired. @@ -33,17 +35,17 @@ namespace Swarmops.Logic.Swarm this.handleProvider = new SwedishForumHandleProvider(); } - private ObjectOptionalData _optionalData; private ObjectOptionalData OptionalData { get { - if (_optionalData == null) + if (this._optionalData == null) { - Person p = (Person)this; - _optionalData = ObjectOptionalData.ForObject(p); //Added cast, otherwise it fails for subclasses + Person p = this; + this._optionalData = ObjectOptionalData.ForObject(p); + //Added cast, otherwise it fails for subclasses } - return _optionalData; + return this._optionalData; } } @@ -107,46 +109,6 @@ namespace Swarmops.Logic.Swarm } - protected int ResolveGeography () - { - if (base.CountryId == 0) - { - base.GeographyId = 1; - SwarmDb.GetDatabaseForWriting().SetPersonGeography(this.Identity, 1); - return 1; // root geography, if no country set - } - - Structure.Cities cities = Cities.FromPostalCode(this.PostalCode, base.CountryId); - City city = null; - - if (cities.Count == 0) - { - try - { - city = Structure.City.FromName(this.CityName, this.CountryId); - } - catch (ArgumentException) - { - // ignore - } - } - else - { - city = cities[0]; // This may be adjusted manually, but will work in 99.9% of cases - } - - if (city == null) - { - base.GeographyId = Country.FromIdentity(base.CountryId).GeographyId; - return base.GeographyId; - } - - base.GeographyId = city.GeographyId; - SwarmDb.GetDatabaseForWriting().SetPersonGeography(this.Identity, base.GeographyId); - return city.GeographyId; - } - - public virtual Geography Geography { get @@ -265,7 +227,7 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.CryptoRevocation, value); } } - [Obsolete ("Use NationalIdNumber instead")] + [Obsolete("Use NationalIdNumber instead")] public virtual string PersonalNumber { get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.PersonalNumber); } @@ -296,20 +258,6 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BitIdLoginAddress, value); } } - public static Person FromBitIdAddress(string address) - { - People candidates = People.FromOptionalData(ObjectOptionalDataType.BitIdLoginAddress, address); - - if (candidates.Count == 1) - { - return candidates[0]; - } - - throw new ArgumentException("Zero or several candidates"); - } - - - public virtual bool MailUnreachable { @@ -392,301 +340,6 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataBool(ObjectOptionalDataType.EMailIsInvalid, value); } } - - #region IComparable Members - - // TODO: Is same name really a match for equality for Person? /JL - public int CompareTo (object obj) - { - var otherPerson = (Person)obj; - - return String.Compare(Name, otherPerson.Name); - } - - #endregion - - public static Person FromIdentity(int personId) - { - return FromBasic(SwarmDb.GetDatabaseForReading().GetPerson(personId)); - } - - public static Person FromIdentityAggressive(int personId) - { - return FromBasic(SwarmDb.GetDatabaseForWriting().GetPerson(personId)); // Note "for writing". Intentional. Queries master db and bypasses replication lag. - } - - public Authority GetAuthority() - { - return Authorization.GetPersonAuthority(Identity); - } - - public Memberships GetMemberships (bool includeTerminated) - { - if (!includeTerminated) - { - return GetMemberships(); - } - - return Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this)); - } - - public Memberships GetMemberships () - { - return Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this, DatabaseCondition.ActiveTrue)); - } - - - /// - /// Returns the most recent membership for an org wich is active or terminated within the grace period - /// - /// For exired, number of days to add to allow it to be returned - /// - /// - public Membership GetRecentMembership (int gracePeriod, int orgId) - { - List orgIdList = new List(); - orgIdList.Add(orgId); - Memberships mss = GetRecentMemberships(orgIdList, gracePeriod); - foreach (Membership ms in mss) - { - if (ms.OrganizationId == orgId) - return ms; - } - return null; - } - - /// - /// Returns most recent membership for each org wich is active or terminated within the grace period - /// - /// For exired, number of days to add to allow it to be returned - /// - public Memberships GetRecentMemberships (int gracePeriod) - { - List orgIdList = new List(); - return GetRecentMemberships(orgIdList, gracePeriod); - } - - /// - /// Returns most recent membership for each org wich is active or terminated within the grace period - /// - /// 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) - { - List orgIdList = new List(orgs.Identities); - return GetRecentMemberships(orgIdList, gracePeriod); - } - - /// - /// Returns most recent membership for each org wich is active or terminated within the grace period - /// - /// 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) - { - Memberships memberships = this.GetMemberships(true); - Dictionary collectMembers = new Dictionary(); - - 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 (membership.Active) - { - collectMembers[membership.OrganizationId] = membership; - } - else if (membership.DateTerminated.AddDays(gracePeriod) > DateTime.Today) - { - if (!collectMembers.ContainsKey(membership.OrganizationId) - || collectMembers[membership.OrganizationId].Active == false) - { - collectMembers[membership.OrganizationId] = membership; - } - } - } - } - - Memberships collectedMS = new Memberships(); - collectedMS.AddRange(collectMembers.Values); - - if (collectedMS.Count > 0) - { //sort to get most recent first - collectedMS.Sort(delegate(Membership ms1, Membership ms2) - { - if (ms1.Active && ms1.Active != ms2.Active) - return -1; // active before terminated - else if (ms1.Active != ms2.Active) - return 1;// active before terminated - else if (ms1.Active) - return ms1.Expires.CompareTo(ms2.Expires); // active with lowest expiry - else - return ms2.DateTerminated.CompareTo(ms1.DateTerminated); // terminated with latest terminationdate - }); - } - - return collectedMS; - } - - internal static Person FromBasic (BasicPerson basic) - { - return new Person(basic); - } - - public static Person Create (string name, string email, string password, string phone, string street, - string postal, string city, string countryCode, DateTime dateOfBirth, - PersonGender gender) - { - BasicCountry country = null; - - if (countryCode.Length > 0) - { - country = Structure.Country.FromCode(countryCode); - } - - // Clean data - - while (name.Contains(" ")) - { - name = name.Replace(" ", " "); - } - - name = name.Trim(); - email = email.ToLower().Trim(); - phone = LogicServices.CleanNumber(phone); - postal = postal.Replace(" ", "").Trim(); - - int personId = SwarmDb.GetDatabaseForWriting().CreatePerson(name, email, phone, street, postal, city, - country == null? 0: country.Identity, dateOfBirth, gender); - - - // Resolve the geography - - Person newPerson = Person.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); - } - else - { - newPerson.PasswordHash = string.Empty; // if no password, prevent matching to anything - } - - // Return the finished Person object - - return newPerson; - } - - public Membership AddMembership (Organization organization, DateTime expires) - { - return AddMembership(organization.Identity, expires); - } - - public Membership AddMembership (int organizationId, DateTime expires) - { - return Membership.Create(Identity, organizationId, expires); - } - - private bool? HasExplicitSubscription (int newsletterFeedId) - { - if (null == this.subscriptions) - { - this.subscriptions = SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForSubscriber(PersonId); - } - - if (this.subscriptions.ContainsKey(newsletterFeedId)) - { - return this.subscriptions[newsletterFeedId]; - } - else - { - return null; - } - } - - public bool IsSubscribing (int newsletterFeedId) - { - bool? subscription = HasExplicitSubscription(newsletterFeedId); - if (subscription != null) - { - return (bool)subscription; - } - else - { - try - { //Added try catch, throws exception on nonexisting feed id - NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); - return feed.DefaultSubscribed; - } - catch - { - return false; - } - } - } - - public virtual void SetSubscription (int newsletterFeedId, bool subscribe) - { - bool? subscription = HasExplicitSubscription(newsletterFeedId); - if (subscription != null && subscription != subscribe) - { - SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); - } - else - { - NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); - if (subscribe != feed.DefaultSubscribed) - { - SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); - } - } - this.subscriptions[newsletterFeedId] = subscribe; - } - - - public void DeleteSubscriptionData () - { - SwarmDb.GetDatabaseForWriting().DeletePersonNewsletterSubscriptions(Identity); - } - - - /// - /// Sends a phone text message to the person's mobile phone. - /// - public void SendPhoneMessage (string message) - { - // HACK: This currently only works for Swedish people. - try - { - PhoneMessageTransmitter.Send(Phone, message); - // SwarmDb.GetDatabase().LogTransmittedPhoneMessage(Identity, Phone, message); - } - catch (Exception ex) - { - throw new Exception("Failed to send phone message:[" + message + "]\r\nto person [#" + Identity.ToString() + "]:\r\n" + ex.Message, ex); - } - } - - - public virtual void SetPassword (string newPassword) - { - string hash = Authentication.GenerateNewPasswordHash(Identity, newPassword); - SwarmDb.GetDatabaseForWriting().SetPersonPasswordHash(Identity, hash); - base.PasswordHash = hash; - } - - public new string PasswordHash { get { return base.PasswordHash; } @@ -703,133 +356,6 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PersonTempPasswordStore, value); } } - - private void SendNotice (string subject, string body, int organizationId, bool asOfficer) - { - 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, (int)OutboundMailRecipient.RecipientType.Person); - SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount(mailId, 1); - SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved(mailId); - SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup(mailId); - } - - 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); - } - - public void SendOfficerNotice (string subject, string body, int organizationId) - { - SendNotice(subject, body, organizationId, true); - } - - - public void SendOfficerNotice (TypedMailTemplate mailtempl, int organizationId) - { - SendNotice(mailtempl, organizationId, true); - } - - public void SendNotice (TypedMailTemplate mailtempl, int organizationId) - { - SendNotice(mailtempl, organizationId, false); - } - - public void SendNotice (TypedMailTemplate mailtempl, int organizationId, bool asOfficer) - { - OutboundMail mail = mailtempl.CreateFunctionalOutboundMail( - asOfficer ? MailAuthorType.PirateWeb : MailAuthorType.Service, - OutboundMail.PriorityNormal, Organization.FromIdentity(organizationId), - Geography.Root, DateTime.Now); - mail.AddRecipient(this, asOfficer); - mail.SetRecipientCount(1); - mail.SetResolved(); - mail.SetReadyForPickup(); - } - - - public void CreateActivist (bool isPublic, bool isConfirmed) - { - SwarmDb.GetDatabaseForWriting().CreateActivist(Identity, isPublic, isConfirmed); - } - - public void TerminateActivist () - { - SwarmDb.GetDatabaseForWriting().TerminateActivist(Identity); - } - - public PersonRole AddRole (RoleType roleType, Organization organization, Geography geography) - { - return AddRole(roleType, organization.Identity, geography.Identity); - } - - public PersonRole AddRole (RoleType roleType, int organizationId, int geographyId) - { - return PersonRole.Create(Identity, roleType, organizationId, geographyId); - } - - - - public string CreatePPMailAddress () - { - // TODO: Handle different mail domains based on organisation of person. - - string name = this.Name.Trim(); - name = RemoveDiacritics(name); - name = name.ToLower(); - name = name.Replace("æ", "ae"); - //change all non valid chars to '.' - Regex re = new Regex(@"[^-a-z0-9\.]", RegexOptions.IgnoreCase); - name = re.Replace(name, "."); - - while (name.Contains("..")) - name = name.Replace("..", "."); - - return name + "@piratpartiet.se"; - } - - private static string RemoveDiacritics (string stIn) - { - // Doesn't account for æ, but strips everything else conceivable - - string stFormD = stIn.Normalize(NormalizationForm.FormD); - StringBuilder sb = new StringBuilder(); - - for (int ich = 0; ich < stFormD.Length; ich++) - { - UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]); - if (uc != UnicodeCategory.NonSpacingMark) - { - sb.Append(stFormD[ich]); - } - } - - return (sb.ToString().Normalize(NormalizationForm.FormC)); - } - - - public string CreateUniquePPMailAddress () - { - string newAddress = this.CreatePPMailAddress(); - newAddress = MailServerDatabase.FindFreeAccount(newAddress); - return newAddress; - } - - public bool ValidatePassword (string oldpassword) - { - return Authentication.ValidatePassword(this, oldpassword); - } - - public string HexIdentifier () - { - string identifier = String.Format("{0:X4}", Identity); - char[] array = identifier.ToCharArray(); - Array.Reverse(array); - return new string(array); - } - public string Initials { get @@ -860,36 +386,33 @@ namespace Swarmops.Logic.Swarm // make best guesses: - if (base.CountryId != 0 && this.Country != null && !string.IsNullOrEmpty(this.Country.Culture)) + if (base.CountryId != 0 && Country != null && !string.IsNullOrEmpty(Country.Culture)) { - return this.Country.Culture; + return Country.Culture; } //not set, make a guess... - foreach (Membership ms in this.GetMemberships(false)) + foreach (Membership ms in GetMemberships(false)) { try { return ms.Organization.DefaultCountry.Culture; } - catch { } + catch + { + } } return CultureInfo.InvariantCulture.Name; } set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PreferredCulture, value); } - - } - public string Canonical // On the canonical format "Rick Falkvinge (#1)" + public string Canonical // On the canonical format "Rick Falkvinge (#1)" { - get - { - return Name + " (#" + Identity.ToString() + ")"; - } + get { return Name + " (#" + Identity + ")"; } } public Image Portrait @@ -913,82 +436,8 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.PortraitPhotographer, value); } } - public bool MemberOf (Organization organization) - { - return MemberOf (organization.Identity ); - } - - public bool MemberOf (int orgId) - { - Memberships memberships = this.GetMemberships(); - - foreach (Membership membership in memberships) - { - if (membership.OrganizationId == orgId) - { - return true; - } - } - - return false; - } - - public bool MemberOfWithInherited (int orgId) - { - Memberships memberships = this.GetMemberships(); - foreach (Membership membership in memberships) - { - if (membership.Organization.IsOrInherits(orgId)) - { - return true; - } - } - return false; - } - - public bool MemberOfWithInherited (Organization org) - { - return MemberOfWithInherited(org.Identity ); - - } - - /* --- not used, commented out for usage of hardcoded org ids - public int NationalPartyOrg (bool onlyIfMember) - { - //TODO: Implement a flag in Organization - int[] partyOrgs = new int[] { Organization.PPSEid, Organization.PPDKid, Organization.PPFIid }; - foreach (int orgId in partyOrgs) - { - if (this.MemberOf(orgId)) - { - return orgId; - } - } - - //no, wasnt a member, try by country - if (!onlyIfMember) - { - foreach (int orgId in partyOrgs) - { - try - { - Organization org = Organization.FromIdentity(orgId); - if (this.Country.Code == org.DefaultCountry.Code) - { - return orgId; - } - } - catch { } - } - } - //didn't find any - return 0; - - } */ - - // ReSharper disable InconsistentNaming public string TShirtSize - // ReSharper restore InconsistentNaming + // ReSharper restore InconsistentNaming { get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.TShirtSize); } set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.TShirtSize, value); } @@ -1006,11 +455,6 @@ namespace Swarmops.Logic.Swarm set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BlogUrl, value); } } - public DashboardTasks.Tasks GetTasksForOrganization(Organization organization) - { - return Logic.DashboardTasks.Tasks.ForPersonOrganization(this, organization); - } - public string Formal { get { return FirstName[0] + " " + LastName; } @@ -1048,7 +492,7 @@ namespace Swarmops.Logic.Swarm { get { - string email = this.Mail.Trim().ToLowerInvariant(); + string email = Mail.Trim().ToLowerInvariant(); string md5 = MD5.Hash(email); @@ -1056,22 +500,571 @@ namespace Swarmops.Logic.Swarm } } - public string GetAvatarLink (int pixelSize) - { - return string.Format("http://www.gravatar.com/avatar/{0}.jpg?s={1}&d=mm", this.MailMD5, pixelSize); - } - - public string GetSecureAvatarLink (int pixelSize) - { - return GetAvatarLink(pixelSize).Replace("http://www", "https://secure"); - } - public static int NobodyId { get { return 0; } } - public bool HasAccess (Access access) + #region IComparable Members + + // TODO: Is same name really a match for equality for Person? /JL + public int CompareTo(object obj) + { + Person otherPerson = (Person) obj; + + return String.Compare(Name, otherPerson.Name); + } + + #endregion + + protected int ResolveGeography() + { + if (base.CountryId == 0) + { + base.GeographyId = 1; + SwarmDb.GetDatabaseForWriting().SetPersonGeography(Identity, 1); + return 1; // root geography, if no country set + } + + Cities cities = Cities.FromPostalCode(PostalCode, base.CountryId); + City city = null; + + if (cities.Count == 0) + { + try + { + city = City.FromName(CityName, CountryId); + } + catch (ArgumentException) + { + // ignore + } + } + else + { + city = cities[0]; // This may be adjusted manually, but will work in 99.9% of cases + } + + if (city == null) + { + base.GeographyId = Country.FromIdentity(base.CountryId).GeographyId; + return base.GeographyId; + } + + base.GeographyId = city.GeographyId; + SwarmDb.GetDatabaseForWriting().SetPersonGeography(Identity, base.GeographyId); + return city.GeographyId; + } + + public static Person FromBitIdAddress(string address) + { + People candidates = People.FromOptionalData(ObjectOptionalDataType.BitIdLoginAddress, address); + + if (candidates.Count == 1) + { + return candidates[0]; + } + + throw new ArgumentException("Zero or several candidates"); + } + + public static Person FromIdentity(int personId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetPerson(personId)); + } + + public static Person FromIdentityAggressive(int personId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetPerson(personId)); + // Note "for writing". Intentional. Queries master db and bypasses replication lag. + } + + public Authority GetAuthority() + { + return Authorization.GetPersonAuthority(Identity); + } + + public Memberships GetMemberships(bool includeTerminated) + { + if (!includeTerminated) + { + return GetMemberships(); + } + + return Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this)); + } + + public Memberships GetMemberships() + { + return + Memberships.FromArray(SwarmDb.GetDatabaseForReading().GetMemberships(this, DatabaseCondition.ActiveTrue)); + } + + + /// + /// Returns the most recent membership for an org wich is active or terminated within the grace period + /// + /// For exired, number of days to add to allow it to be returned + /// + /// + public Membership GetRecentMembership(int gracePeriod, int orgId) + { + List orgIdList = new List(); + orgIdList.Add(orgId); + Memberships mss = GetRecentMemberships(orgIdList, gracePeriod); + foreach (Membership ms in mss) + { + if (ms.OrganizationId == orgId) + return ms; + } + return null; + } + + /// + /// Returns most recent membership for each org wich is active or terminated within the grace period + /// + /// For exired, number of days to add to allow it to be returned + /// + public Memberships GetRecentMemberships(int gracePeriod) + { + List orgIdList = new List(); + return GetRecentMemberships(orgIdList, gracePeriod); + } + + /// + /// Returns most recent membership for each org wich is active or terminated within the grace period + /// + /// 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) + { + List orgIdList = new List(orgs.Identities); + return GetRecentMemberships(orgIdList, gracePeriod); + } + + /// + /// Returns most recent membership for each org wich is active or terminated within the grace period + /// + /// 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) + { + Memberships memberships = GetMemberships(true); + Dictionary collectMembers = new Dictionary(); + + 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 (membership.Active) + { + collectMembers[membership.OrganizationId] = membership; + } + else if (membership.DateTerminated.AddDays(gracePeriod) > DateTime.Today) + { + if (!collectMembers.ContainsKey(membership.OrganizationId) + || collectMembers[membership.OrganizationId].Active == false) + { + collectMembers[membership.OrganizationId] = membership; + } + } + } + } + + Memberships collectedMS = new Memberships(); + collectedMS.AddRange(collectMembers.Values); + + if (collectedMS.Count > 0) + { + //sort to get most recent first + 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 collectedMS; + } + + internal static Person FromBasic(BasicPerson basic) + { + return new Person(basic); + } + + public static Person Create(string name, string email, string password, string phone, string street, + string postal, string city, string countryCode, DateTime dateOfBirth, + PersonGender gender) + { + BasicCountry country = null; + + if (countryCode.Length > 0) + { + country = Country.FromCode(countryCode); + } + + // Clean data + + while (name.Contains(" ")) + { + name = name.Replace(" ", " "); + } + + name = name.Trim(); + email = email.ToLower().Trim(); + phone = LogicServices.CleanNumber(phone); + postal = postal.Replace(" ", "").Trim(); + + 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 + newPerson.ResolveGeography(); + + // Generate the salted password hash and set it + + if (password.Length > 0) + { + newPerson.PasswordHash = Authentication.GenerateNewPasswordHash(personId, password); + } + else + { + newPerson.PasswordHash = string.Empty; // if no password, prevent matching to anything + } + + // Return the finished Person object + + return newPerson; + } + + public Membership AddMembership(Organization organization, DateTime expires) + { + return AddMembership(organization.Identity, expires); + } + + public Membership AddMembership(int organizationId, DateTime expires) + { + return Membership.Create(Identity, organizationId, expires); + } + + private bool? HasExplicitSubscription(int newsletterFeedId) + { + if (null == this.subscriptions) + { + this.subscriptions = SwarmDb.GetDatabaseForReading().GetNewsletterFeedsForSubscriber(PersonId); + } + + if (this.subscriptions.ContainsKey(newsletterFeedId)) + { + return this.subscriptions[newsletterFeedId]; + } + return null; + } + + public bool IsSubscribing(int newsletterFeedId) + { + bool? subscription = HasExplicitSubscription(newsletterFeedId); + if (subscription != null) + { + return (bool) subscription; + } + try + { + //Added try catch, throws exception on nonexisting feed id + NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); + return feed.DefaultSubscribed; + } + catch + { + return false; + } + } + + public virtual void SetSubscription(int newsletterFeedId, bool subscribe) + { + bool? subscription = HasExplicitSubscription(newsletterFeedId); + if (subscription != null && subscription != subscribe) + { + SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); + } + else + { + NewsletterFeed feed = NewsletterFeed.FromIdentity(newsletterFeedId); + if (subscribe != feed.DefaultSubscribed) + { + SwarmDb.GetDatabaseForWriting().SetNewsletterSubscription(PersonId, newsletterFeedId, subscribe); + } + } + this.subscriptions[newsletterFeedId] = subscribe; + } + + + public void DeleteSubscriptionData() + { + SwarmDb.GetDatabaseForWriting().DeletePersonNewsletterSubscriptions(Identity); + } + + + /// + /// Sends a phone text message to the person's mobile phone. + /// + public void SendPhoneMessage(string message) + { + // HACK: This currently only works for Swedish people. + try + { + PhoneMessageTransmitter.Send(Phone, message); + // SwarmDb.GetDatabase().LogTransmittedPhoneMessage(Identity, Phone, message); + } + catch (Exception ex) + { + throw new Exception( + "Failed to send phone message:[" + message + "]\r\nto person [#" + Identity + "]:\r\n" + ex.Message, + ex); + } + } + + + public virtual void SetPassword(string newPassword) + { + 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) + { + 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, + (int) OutboundMailRecipient.RecipientType.Person); + SwarmDb.GetDatabaseForWriting().SetOutboundMailRecipientCount(mailId, 1); + SwarmDb.GetDatabaseForWriting().SetOutboundMailResolved(mailId); + SwarmDb.GetDatabaseForWriting().SetOutboundMailReadyForPickup(mailId); + } + + 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); + } + + public void SendOfficerNotice(string subject, string body, int organizationId) + { + SendNotice(subject, body, organizationId, true); + } + + + public void SendOfficerNotice(TypedMailTemplate mailtempl, int organizationId) + { + SendNotice(mailtempl, organizationId, true); + } + + public void SendNotice(TypedMailTemplate mailtempl, int organizationId) + { + SendNotice(mailtempl, organizationId, false); + } + + public void SendNotice(TypedMailTemplate mailtempl, int organizationId, bool asOfficer) + { + OutboundMail mail = mailtempl.CreateFunctionalOutboundMail( + asOfficer ? MailAuthorType.PirateWeb : MailAuthorType.Service, + OutboundMail.PriorityNormal, Organization.FromIdentity(organizationId), + Geography.Root, DateTime.Now); + mail.AddRecipient(this, asOfficer); + mail.SetRecipientCount(1); + mail.SetResolved(); + mail.SetReadyForPickup(); + } + + + public void CreateActivist(bool isPublic, bool isConfirmed) + { + SwarmDb.GetDatabaseForWriting().CreateActivist(Identity, isPublic, isConfirmed); + } + + public void TerminateActivist() + { + SwarmDb.GetDatabaseForWriting().TerminateActivist(Identity); + } + + public PersonRole AddRole(RoleType roleType, Organization organization, Geography geography) + { + return AddRole(roleType, organization.Identity, geography.Identity); + } + + public PersonRole AddRole(RoleType roleType, int organizationId, int geographyId) + { + return PersonRole.Create(Identity, roleType, organizationId, geographyId); + } + + + public string CreatePPMailAddress() + { + // TODO: Handle different mail domains based on organisation of person. + + string name = Name.Trim(); + name = RemoveDiacritics(name); + name = name.ToLower(); + name = name.Replace("æ", "ae"); + //change all non valid chars to '.' + Regex re = new Regex(@"[^-a-z0-9\.]", RegexOptions.IgnoreCase); + name = re.Replace(name, "."); + + while (name.Contains("..")) + name = name.Replace("..", "."); + + return name + "@piratpartiet.se"; + } + + private static string RemoveDiacritics(string stIn) + { + // Doesn't account for æ, but strips everything else conceivable + + string stFormD = stIn.Normalize(NormalizationForm.FormD); + StringBuilder sb = new StringBuilder(); + + for (int ich = 0; ich < stFormD.Length; ich++) + { + UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]); + if (uc != UnicodeCategory.NonSpacingMark) + { + sb.Append(stFormD[ich]); + } + } + + return (sb.ToString().Normalize(NormalizationForm.FormC)); + } + + + public string CreateUniquePPMailAddress() + { + string newAddress = CreatePPMailAddress(); + newAddress = MailServerDatabase.FindFreeAccount(newAddress); + return newAddress; + } + + public bool ValidatePassword(string oldpassword) + { + return Authentication.ValidatePassword(this, oldpassword); + } + + public string HexIdentifier() + { + string identifier = String.Format("{0:X4}", Identity); + char[] array = identifier.ToCharArray(); + Array.Reverse(array); + return new string(array); + } + + public bool MemberOf(Organization organization) + { + return MemberOf(organization.Identity); + } + + public bool MemberOf(int orgId) + { + Memberships memberships = GetMemberships(); + + foreach (Membership membership in memberships) + { + if (membership.OrganizationId == orgId) + { + return true; + } + } + + return false; + } + + public bool MemberOfWithInherited(int orgId) + { + Memberships memberships = GetMemberships(); + foreach (Membership membership in memberships) + { + if (membership.Organization.IsOrInherits(orgId)) + { + return true; + } + } + return false; + } + + public bool MemberOfWithInherited(Organization org) + { + return MemberOfWithInherited(org.Identity); + } + + /* --- not used, commented out for usage of hardcoded org ids + public int NationalPartyOrg (bool onlyIfMember) + { + //TODO: Implement a flag in Organization + int[] partyOrgs = new int[] { Organization.PPSEid, Organization.PPDKid, Organization.PPFIid }; + foreach (int orgId in partyOrgs) + { + if (this.MemberOf(orgId)) + { + return orgId; + } + } + + //no, wasnt a member, try by country + if (!onlyIfMember) + { + foreach (int orgId in partyOrgs) + { + try + { + Organization org = Organization.FromIdentity(orgId); + if (this.Country.Code == org.DefaultCountry.Code) + { + return orgId; + } + } + catch { } + } + } + //didn't find any + return 0; + + } */ + + // ReSharper disable InconsistentNaming + + public Tasks GetTasksForOrganization(Organization organization) + { + return Tasks.ForPersonOrganization(this, organization); + } + + public string GetAvatarLink(int pixelSize) + { + return string.Format("http://www.gravatar.com/avatar/{0}.jpg?s={1}&d=mm", MailMD5, pixelSize); + } + + public string GetSecureAvatarLink(int pixelSize) + { + return GetAvatarLink(pixelSize).Replace("http://www", "https://secure"); + } + + public bool HasAccess(Access access) { if (access == null) { @@ -1090,7 +1083,8 @@ namespace Swarmops.Logic.Swarm } else if (access.Type == AccessType.Read) { - ids = access.Organization.Parameters.TemporaryAccessListWrite + " " + access.Organization.Parameters.TemporaryAccessListRead; // Write access implies read access + ids = access.Organization.Parameters.TemporaryAccessListWrite + " " + + access.Organization.Parameters.TemporaryAccessListRead; // Write access implies read access } @@ -1099,7 +1093,7 @@ namespace Swarmops.Logic.Swarm foreach (string idString in idStrings) { - if (Int32.Parse(idString) == this.Identity) + if (Int32.Parse(idString) == Identity) { return true; } @@ -1108,6 +1102,4 @@ namespace Swarmops.Logic.Swarm return false; } } -} - - \ No newline at end of file +} \ No newline at end of file diff --git a/Logic/Swarm/PersonRole.cs b/Logic/Swarm/PersonRole.cs index 836242ba..73429695 100644 --- a/Logic/Swarm/PersonRole.cs +++ b/Logic/Swarm/PersonRole.cs @@ -13,16 +13,18 @@ namespace Swarmops.Logic.Swarm { } - 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)); + return + FromIdentityAggressive(SwarmDb.GetDatabaseForWriting() + .CreateRole(personId, roleType, organizationId, nodeId)); } - public static PersonRole FromBasic (BasicPersonRole basic) + public static PersonRole FromBasic(BasicPersonRole basic) { return new PersonRole(basic); } @@ -34,7 +36,8 @@ namespace Swarmops.Logic.Swarm 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 diff --git a/Logic/Swarm/RoleLookup.cs b/Logic/Swarm/RoleLookup.cs index 96825fe3..088c01d6 100644 --- a/Logic/Swarm/RoleLookup.cs +++ b/Logic/Swarm/RoleLookup.cs @@ -9,7 +9,7 @@ namespace Swarmops.Logic.Swarm { private readonly Dictionary lookup; - internal RoleLookup (Roles initialSet) + internal RoleLookup(Roles initialSet) { this.lookup = new Dictionary(); @@ -37,7 +37,7 @@ namespace Swarmops.Logic.Swarm } } - public static RoleLookup FromOrganization (int organizationId) + public static RoleLookup FromOrganization(int organizationId) { Roles roles = Roles.FromArray(SwarmDb.GetDatabaseForReading().GetRolesForOrganization(organizationId)); @@ -45,20 +45,21 @@ namespace Swarmops.Logic.Swarm 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); } - public static RoleLookup FromGeographyAndOrganization (Geography geography, Organization organization) + public static RoleLookup FromGeographyAndOrganization(Geography geography, Organization organization) { return FromGeographyAndOrganization(geography.Identity, organization.Identity); } - public static RoleLookup FromOrganization (Organization organization) + public static RoleLookup FromOrganization(Organization organization) { return FromOrganization(organization.Identity); } diff --git a/Logic/Swarm/Roles.cs b/Logic/Swarm/Roles.cs index 91a1e954..2636afbb 100644 --- a/Logic/Swarm/Roles.cs +++ b/Logic/Swarm/Roles.cs @@ -10,11 +10,11 @@ namespace Swarmops.Logic.Swarm { public class Roles : List { - public static Roles FromArray (BasicPersonRole[] basicArray) + public static Roles FromArray(BasicPersonRole[] basicArray) { - var result = new Roles(); + Roles result = new Roles(); - result.Capacity = basicArray.Length * 11 / 10; + result.Capacity = basicArray.Length*11/10; foreach (BasicPersonRole basic in basicArray) { result.Add(PersonRole.FromBasic(basic)); @@ -24,41 +24,42 @@ namespace Swarmops.Logic.Swarm } /// - /// Gets a list of person IDs that should be notified of something happening in the org. - /// Defaults to collecting Local roles with Permission.CanSeePeople + /// Gets a list of person IDs that should be notified of something happening in the org. + /// Defaults to collecting Local roles with Permission.CanSeePeople /// /// 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)); } /// - /// Gets a list of person IDs that should be notified of something happening in the org. + /// Gets a list of person IDs that should be notified of something happening in the org. /// /// The organization where something happened. /// 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(); int[] nodeIds = nodeLine.Identities; - var peopleTable = new Dictionary(); + Dictionary peopleTable = new Dictionary(); foreach (Organization org in orgLine) { - BasicPersonRole[] upwardPersonRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, - nodeIds); + BasicPersonRole[] upwardPersonRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, + nodeIds); foreach (BasicPersonRole role in upwardPersonRoles) { - if (Array.IndexOf(roleTypes, role.Type) > -1) { peopleTable[role.PersonId] = true; @@ -68,7 +69,7 @@ namespace Swarmops.Logic.Swarm // Assemble result - var result = new List(); + List result = new List(); foreach (int personId in peopleTable.Keys) { @@ -80,9 +81,9 @@ namespace Swarmops.Logic.Swarm /// - /// Gets a list of person IDs that are officers in the org/geography combo. + /// 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; @@ -98,12 +99,13 @@ namespace Swarmops.Logic.Swarm nodeIds = new int[0]; } - var peopleTable = new Dictionary(); + Dictionary peopleTable = new Dictionary(); foreach (Organization org in orgTree) { - BasicPersonRole[] downwardPersonRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, - nodeIds); + BasicPersonRole[] downwardPersonRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeographies(org.Identity, + nodeIds); foreach (BasicPersonRole role in downwardPersonRoles) { @@ -113,7 +115,7 @@ namespace Swarmops.Logic.Swarm // Assemble result - var result = new List(); + List result = new List(); foreach (int personId in peopleTable.Keys) { @@ -123,7 +125,7 @@ namespace Swarmops.Logic.Swarm 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; @@ -132,7 +134,7 @@ namespace Swarmops.Logic.Swarm int[] orgIds; orgTree = Organization.FromIdentity(organizationId).GetTree(); - orgIds=orgTree.Identities; + orgIds = orgTree.Identities; if (geographyId > 0) { @@ -144,31 +146,33 @@ 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); } - 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); } - public static Person GetLocalLead (Organization organization, Geography geography) + public static Person GetLocalLead(Organization organization, Geography geography) { return GetLocalLead(organization.Identity, geography.Identity); } public static Person GetLocalLead(int organizationId, int geographyId) { - BasicPersonRole[] personRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); + BasicPersonRole[] personRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); foreach (BasicPersonRole role in personRoles) { @@ -181,9 +185,10 @@ namespace Swarmops.Logic.Swarm 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); + BasicPersonRole[] personRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganization(organization.Identity); foreach (BasicPersonRole role in personRoles) { @@ -196,14 +201,15 @@ namespace Swarmops.Logic.Swarm 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); } public static People GetLocalDeputies(int organizationId, int geographyId) { - BasicPersonRole[] personRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); + BasicPersonRole[] personRoles = + SwarmDb.GetDatabaseForReading().GetRolesForOrganizationGeography(organizationId, geographyId); People result = new People(); foreach (BasicPersonRole role in personRoles) @@ -218,16 +224,16 @@ namespace Swarmops.Logic.Swarm } - public static People GetActivists (Organization organization, Geography geography) + public static People GetActivists(Organization organization, Geography geography) { - var people = new People(); + People people = new People(); // Expensive op: BasicPersonRole[] basicPersonRoles = SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(organization.GetTree().Identities, - geography.GetTree().Identities); + geography.GetTree().Identities); - var lookup = new Dictionary(); + Dictionary lookup = new Dictionary(); foreach (BasicPersonRole basicRole in basicPersonRoles) { if (basicRole.Type == RoleType.LocalActive || basicRole.Type == RoleType.LocalLead || diff --git a/Logic/Swarm/Volunteer.cs b/Logic/Swarm/Volunteer.cs index b9a03e97..289db2ff 100644 --- a/Logic/Swarm/Volunteer.cs +++ b/Logic/Swarm/Volunteer.cs @@ -11,33 +11,33 @@ namespace Swarmops.Logic.Swarm { #region Creation and Construction - private Volunteer () + private Volunteer() : base(0, 0, 0, DateTime.MinValue, false, DateTime.MinValue, string.Empty) { } - private Volunteer (BasicVolunteer 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)); } - public static Volunteer FromBasic (BasicVolunteer basic) + public static Volunteer FromBasic(BasicVolunteer 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); } - public static Volunteer Create (int personId, int ownerPersonId) + public static Volunteer Create(int personId, int ownerPersonId) { return FromIdentity(SwarmDb.GetDatabaseForWriting().CreateVolunteer(personId, ownerPersonId)); } @@ -120,25 +120,28 @@ namespace Swarmops.Logic.Swarm public VolunteerRoles Roles { - get { return VolunteerRoles.FromArray(SwarmDb.GetDatabaseForReading().GetVolunteerRolesByVolunteer(Identity)); } + get + { + 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); } - 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); } - public void Close (string comments) + public void Close(string comments) { SwarmDb.GetDatabaseForWriting().CloseVolunteer(Identity, comments); } - private void PopulateCache () + private void PopulateCache() { if (this.person == null) { @@ -164,33 +167,32 @@ namespace Swarmops.Logic.Swarm } - /// - /// Assign the volunteer to a suitable owner will try to assign to ElectoralCircuit lead - /// If that is not possible it will go to district lead + /// Assign the volunteer to a suitable owner will try to assign to ElectoralCircuit lead + /// If that is not possible it will go to district lead /// /// /// /// /// 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 { - this.Owner = defaultOwner; + Owner = defaultOwner; Geography volonteerGeography = geo; //Move up to target geography level //GeographyLevel targetLevel = GeographyLevel.ElectoralCircuit; - GeographyLevel targetLevel = GeographyLevel.District; //This will never hit bcse Districts ar not properly defined + GeographyLevel targetLevel = GeographyLevel.District; + //This will never hit bcse Districts ar not properly defined while (!(volonteerGeography.AtLevel(targetLevel)) - && (volonteerGeography.ParentGeographyId != 0) - && (volonteerGeography.ParentGeographyId != stopGeography) - ) + && (volonteerGeography.ParentGeographyId != 0) + && (volonteerGeography.ParentGeographyId != stopGeography) + ) { volonteerGeography = volonteerGeography.Parent; } @@ -201,7 +203,7 @@ namespace Swarmops.Logic.Swarm { // Move "geography" up to district, wich are next below country, if no lead was found at the target level while ((volonteerGeography.ParentGeographyId != 0) - && (volonteerGeography.ParentGeographyId != stopGeography) + && (volonteerGeography.ParentGeographyId != stopGeography) ) { volonteerGeography = volonteerGeography.Parent; @@ -212,7 +214,7 @@ namespace Swarmops.Logic.Swarm //Found anyone? otherwise leave default Owner. if (localLead != null) { - this.Owner = localLead; + Owner = localLead; } } catch (Exception) diff --git a/Logic/Swarm/VolunteerRole.cs b/Logic/Swarm/VolunteerRole.cs index 491418ca..bcdab34f 100644 --- a/Logic/Swarm/VolunteerRole.cs +++ b/Logic/Swarm/VolunteerRole.cs @@ -6,7 +6,7 @@ namespace Swarmops.Logic.Swarm { public class VolunteerRole : BasicVolunteerRole { - private VolunteerRole (BasicVolunteerRole basic) : + private VolunteerRole(BasicVolunteerRole basic) : base(basic) { } @@ -16,17 +16,17 @@ namespace Swarmops.Logic.Swarm 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); } - public static VolunteerRole FromIdentity (int identity) + public static VolunteerRole FromIdentity(int 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 4db44149..bfda178c 100644 --- a/Logic/Swarm/VolunteerRoles.cs +++ b/Logic/Swarm/VolunteerRoles.cs @@ -5,9 +5,9 @@ namespace Swarmops.Logic.Swarm { public class VolunteerRoles : List { - public static VolunteerRoles FromArray (BasicVolunteerRole[] basicArray) + public static VolunteerRoles FromArray(BasicVolunteerRole[] basicArray) { - var result = new VolunteerRoles(); + VolunteerRoles result = new VolunteerRoles(); result.Capacity = basicArray.Length*11/10; foreach (BasicVolunteerRole basic in basicArray) diff --git a/Logic/Swarm/Volunteers.cs b/Logic/Swarm/Volunteers.cs index b865d4d8..1cfe6569 100644 --- a/Logic/Swarm/Volunteers.cs +++ b/Logic/Swarm/Volunteers.cs @@ -16,9 +16,9 @@ namespace Swarmops.Logic.Swarm return FromArray(SwarmDb.GetDatabaseForReading().GetOpenVolunteers()); } - public static Volunteers FromArray (BasicVolunteer[] basicArray) + public static Volunteers FromArray(BasicVolunteer[] basicArray) { - var result = new Volunteers(); + Volunteers result = new Volunteers(); result.Capacity = basicArray.Length*11/10; foreach (BasicVolunteer basic in basicArray) @@ -29,17 +29,17 @@ namespace Swarmops.Logic.Swarm return result; } - public static Volunteers FromSingle (Volunteer volunteer) + public static Volunteers FromSingle(Volunteer volunteer) { - var volunteers = new Volunteers(); + Volunteers volunteers = new Volunteers(); volunteers.Add(volunteer); return volunteers; } - public void Remove (Volunteers volunteersToRemove) + public void Remove(Volunteers volunteersToRemove) { - var identityLookup = new Dictionary(); + Dictionary identityLookup = new Dictionary(); foreach (Volunteer volunteer in volunteersToRemove) { @@ -65,7 +65,7 @@ namespace Swarmops.Logic.Swarm } } - public new void Remove (Volunteer volunteerToRemove) + public new void Remove(Volunteer volunteerToRemove) { Remove(FromSingle(volunteerToRemove)); } @@ -76,10 +76,10 @@ namespace Swarmops.Logic.Swarm // It's possible to write it more optimized, and build the DataSet by hand, but that takes // around 100 LoC. - var serializer = new XmlSerializer(typeof (Volunteers)); - var sw = new StringWriter(); + XmlSerializer serializer = new XmlSerializer(typeof (Volunteers)); + StringWriter sw = new StringWriter(); serializer.Serialize(sw, this); - var ds = new DataSet(); + DataSet ds = new DataSet(); ds.ReadXml(sw.ToString()); return ds; diff --git a/Utility/BotCode/ActivityMailer.cs b/Utility/BotCode/ActivityMailer.cs index 91e74eb7..a7646f9d 100644 --- a/Utility/BotCode/ActivityMailer.cs +++ b/Utility/BotCode/ActivityMailer.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.Configuration; -using System.Net.Mail; -using System.Web; -using Swarmops.Logic.Structure; -using Swarmops.Logic.Swarm; namespace Swarmops.Utility.BotCode { @@ -94,7 +88,6 @@ namespace Swarmops.Utility.BotCode } } } */ - } } -} +} \ No newline at end of file diff --git a/Utility/BotCode/BallotComposer.cs b/Utility/BotCode/BallotComposer.cs index 31cf68d2..affdaa32 100644 --- a/Utility/BotCode/BallotComposer.cs +++ b/Utility/BotCode/BallotComposer.cs @@ -8,81 +8,81 @@ namespace Swarmops.Utility.BotCode { public class BallotComposer { + private Dictionary defectionsLookup; + private Dictionary geographicLists; + private MeetingElectionCandidates rawElectionResult; + /// - /// Minimum fraction of either gender. Can be in the range 0.0 -- 0.5. + /// Minimum fraction of either gender. Can be in the range 0.0 -- 0.5. /// public double GenderQuota { get; set; } /// - /// Sets the output from the election count, i.e. the Schulze output. + /// Sets the output from the election count, i.e. the Schulze output. /// public MeetingElectionCandidates RawElectionResult { set { - rawElectionResult = value; - geographicLists = new Dictionary(); + this.rawElectionResult = value; + this.geographicLists = new Dictionary(); } } - private MeetingElectionCandidates rawElectionResult; - /// - /// Sets the geographies for which to construct ballots. + /// Sets the geographies for which to construct ballots. /// public Geographies BallotGeographies { set; get; } /// - /// Gets the final result. + /// Gets the final result. /// public Dictionary FinalBallots { get; private set; } - private Dictionary geographicLists; public MeetingElectionCandidates QuotedMasterList { get; private set; } - private Dictionary defectionsLookup; - public int[] DefectedPersonIds { set { - defectionsLookup = new Dictionary(); + this.defectionsLookup = new Dictionary(); foreach (int defectedPersonId in value) { - defectionsLookup[defectedPersonId] = true; + this.defectionsLookup[defectedPersonId] = true; } } } - + public void ComposeBallots(BallotCompositionMethod method) { FinalBallots = new Dictionary(); - QuotedMasterList = GenerateBallot(rawElectionResult, -1, BallotCompositionMethod.Unmixed); - if (geographicLists.Count == 0) + QuotedMasterList = GenerateBallot(this.rawElectionResult, -1, BallotCompositionMethod.Unmixed); + if (this.geographicLists.Count == 0) { GenerateGeographicLists(); } foreach (Geography ballotGeography in BallotGeographies) { - FinalBallots[ballotGeography.Identity] = GenerateBallot(geographicLists[ballotGeography.Identity], 22, - method); + FinalBallots[ballotGeography.Identity] = GenerateBallot(this.geographicLists[ballotGeography.Identity], + 22, + method); } } - public bool CandidatePersonIdDefected (int personId) + public bool CandidatePersonIdDefected(int personId) { - return defectionsLookup.ContainsKey(personId); + return this.defectionsLookup.ContainsKey(personId); } private void GenerateGeographicLists() { - foreach (MeetingElectionCandidate candidate in rawElectionResult) + foreach (MeetingElectionCandidate candidate in this.rawElectionResult) { foreach (Geography ballotGeography in BallotGeographies) { @@ -90,20 +90,20 @@ namespace Swarmops.Utility.BotCode { // This candidate is under this particular geography, so add to list - if (!geographicLists.ContainsKey(ballotGeography.Identity)) + if (!this.geographicLists.ContainsKey(ballotGeography.Identity)) { - geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates(); + this.geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates(); } - geographicLists[ballotGeography.Identity].Add(candidate); + this.geographicLists[ballotGeography.Identity].Add(candidate); } } } } - - private MeetingElectionCandidates GenerateBallot (MeetingElectionCandidates rawList, int candidateCount, BallotCompositionMethod method) + private MeetingElectionCandidates GenerateBallot(MeetingElectionCandidates rawList, int candidateCount, + BallotCompositionMethod method) { MeetingElectionCandidates result = new MeetingElectionCandidates(); Dictionary takenCandidates = new Dictionary(); @@ -117,7 +117,7 @@ namespace Swarmops.Utility.BotCode for (int rawIndex = 0; rawIndex < rawList.Count; rawIndex++) { - if (this.CandidatePersonIdDefected(rawList [rawIndex].PersonId)) + if (CandidatePersonIdDefected(rawList[rawIndex].PersonId)) { takenCandidates[rawIndex] = true; } @@ -136,15 +136,15 @@ 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, - rawList); + int rawListIndex = FindCandidateIndex(QuotedMasterList[masterPosition - 1].InternalPollCandidateId, + rawList); if (rawListIndex >= 0 && !takenCandidates.ContainsKey(rawListIndex)) { @@ -188,8 +188,8 @@ namespace Swarmops.Utility.BotCode // fall outside of bounds (33% or 66%). If so, ignore the quota if it is not obtainable. PersonGender oppositeGender = (candidateGender == PersonGender.Male - ? PersonGender.Female - : PersonGender.Male); + ? PersonGender.Female + : PersonGender.Male); double alternateMaleQuota = CalculateListMaleQuota(result, oppositeGender); @@ -214,18 +214,17 @@ namespace Swarmops.Utility.BotCode result.Add(rawList[nextCandidateIndex]); takenCandidates[nextCandidateIndex] = true; - } return result; } - private static int FindCandidateIndex (int candidateId, MeetingElectionCandidates list) + private static int FindCandidateIndex(int candidateId, MeetingElectionCandidates list) { for (int index = 0; index < list.Count; index++) { - if (list [index].Identity == candidateId) + if (list[index].Identity == candidateId) { return index; } @@ -233,9 +232,10 @@ namespace Swarmops.Utility.BotCode return -1; } - - private static double CalculateListMaleQuota (MeetingElectionCandidates candidates, PersonGender nextCandidateGender) + + private static double CalculateListMaleQuota(MeetingElectionCandidates candidates, + PersonGender nextCandidateGender) { if (candidates.Count < 1) { @@ -261,26 +261,26 @@ namespace Swarmops.Utility.BotCode } - private static int GetNextSpecificGenderCandidate (MeetingElectionCandidates candidates, - Dictionary takenCandidates, PersonGender desiredGender) + 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 + index++; // potential out-of-range exception here, if there aren't enough candidates } return index; } /// - /// Gets the position of the master list to use for this position on the local list. + /// Gets the position of the master list to use for this position on the local list. /// /// 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) { @@ -309,7 +309,7 @@ namespace Swarmops.Utility.BotCode if (method == BallotCompositionMethod.InterleavedTenNational) { - if ((currentPosition % 2 == 1) && currentPosition < 20) + if ((currentPosition%2 == 1) && currentPosition < 20) { return (currentPosition/2 + 1); } @@ -319,30 +319,33 @@ namespace Swarmops.Utility.BotCode throw new NotImplementedException("Unimplemented method"); } - } public enum BallotCompositionMethod { /// - /// FxCop directive - unused + /// FxCop directive - unused /// Unknown = 0, + /// - /// The national top ten names are the top ten on all geographic ballots. + /// The national top ten names are the top ten on all geographic ballots. /// TopTenNational, + /// - /// The national top five names are the top ten on all geographic ballots. + /// The national top five names are the top ten on all geographic ballots. /// TopFiveNational, + /// - /// Odd positions 1..19 are the national top ten names on all geographic ballots. + /// Odd positions 1..19 are the national top ten names on all geographic ballots. /// InterleavedTenNational, + /// - /// No top national names; only names from this district. + /// No top national names; only names from this district. /// Unmixed } -} +} \ No newline at end of file diff --git a/Utility/BotCode/BlogTop50Scraper.cs b/Utility/BotCode/BlogTop50Scraper.cs index 367f5890..d1a2d45b 100644 --- a/Utility/BotCode/BlogTop50Scraper.cs +++ b/Utility/BotCode/BlogTop50Scraper.cs @@ -25,7 +25,7 @@ namespace Swarmops.Utility.BotCode { string scrapeData = string.Empty; - HttpWebRequest request = (HttpWebRequest) HttpWebRequest.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()) diff --git a/Utility/BotCode/BlogWatcher.cs b/Utility/BotCode/BlogWatcher.cs index cafbb662..93277619 100644 --- a/Utility/BotCode/BlogWatcher.cs +++ b/Utility/BotCode/BlogWatcher.cs @@ -7,14 +7,7 @@ namespace Swarmops.Utility.BotCode { public class BlogWatcher { - public class ReaderException : Exception - { - public ReaderException (string message, Exception innerException) - : base(message, innerException) - { } - } - - public static void Run () + public static void Run() { // Get keywords. Read Knuff. Parse. Store. @@ -26,9 +19,9 @@ namespace Swarmops.Utility.BotCode // Read the RSS URL into memory, then feed RssReader from a MemoryStream - HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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(); + HttpWebResponse resp = (HttpWebResponse) request.GetResponse(); RssReader reader = new RssReader(resp.GetResponseStream()); try @@ -79,13 +72,21 @@ namespace Swarmops.Utility.BotCode } } - private static void PingCreeper (string referringUrl) + private static void PingCreeper(string referringUrl) { - HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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; request.GetResponse().GetResponseStream().Close(); } + + public class ReaderException : Exception + { + public ReaderException(string message, Exception innerException) + : base(message, innerException) + { + } + } } } \ No newline at end of file diff --git a/Utility/BotCode/BotLog.cs b/Utility/BotCode/BotLog.cs index f8580672..3a33860d 100644 --- a/Utility/BotCode/BotLog.cs +++ b/Utility/BotCode/BotLog.cs @@ -6,7 +6,7 @@ namespace Swarmops.Utility.BotCode { public class BotLog { - static public void Write (int generation, string code, string message) + public static void Write(int generation, string code, string message) { string line = string.Empty; @@ -27,7 +27,7 @@ namespace Swarmops.Utility.BotCode LogWrite(line); } - static private void LogWrite (string message) + private static void LogWrite(string message) { DateTime now = DateTime.Now; @@ -40,4 +40,4 @@ namespace Swarmops.Utility.BotCode } } } -} +} \ No newline at end of file diff --git a/Utility/BotCode/EventProcessor.cs b/Utility/BotCode/EventProcessor.cs index 5e833395..2576d170 100644 --- a/Utility/BotCode/EventProcessor.cs +++ b/Utility/BotCode/EventProcessor.cs @@ -1,21 +1,5 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.Net.Mail; -using System.Text; -using Swarmops.Basic; -using Swarmops.Basic.Enums; -using Swarmops.Basic.Types; -using Swarmops.Logic.Communications; -using Swarmops.Logic.Financial; -using Swarmops.Logic.Governance; -using Swarmops.Logic.Security; -using Swarmops.Logic.Special.Mail; -using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; -using Swarmops.Logic.Swarm; -using Swarmops.Utility.Financial; -using Swarmops.Utility.Mail; +using System.IO; namespace Swarmops.Utility.BotCode { @@ -24,7 +8,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)] - public static void Run () + public static void Run() { /* BasicPWEvent[] events = PWEvents.GetTopUnprocessedEvents(); @@ -207,16 +191,13 @@ namespace Swarmops.Utility.BotCode } - internal static bool RunningOnLinux () + internal static bool RunningOnLinux() { - if (System.IO.Path.DirectorySeparatorChar == '/') + if (Path.DirectorySeparatorChar == '/') { return true; } - else - { - return false; - } + return false; } /* diff --git a/Utility/BotCode/HeartBeater.cs b/Utility/BotCode/HeartBeater.cs index f8da88bd..cfb53dba 100644 --- a/Utility/BotCode/HeartBeater.cs +++ b/Utility/BotCode/HeartBeater.cs @@ -1,33 +1,55 @@ using System; using System.IO; +using System.Text; using Swarmops.Logic.Support; namespace Swarmops.Utility.BotCode { public class HeartBeater { - static private HeartBeater instance = null; - static private object lockObject = new object(); + private static HeartBeater instance; + private static readonly object lockObject = new object(); - private bool FlagRestartRequested = false; + private bool FlagRestartRequested; private DateTime lastBeat = DateTime.MinValue; private string lastFilename = ""; - - public void Beat () + public bool WasKilled { - Beat(lastFilename); + get { return this.FlagRestartRequested; } } - public void Beat (string filename) + public static HeartBeater Instance + { + get + { + if (instance == null) + { + lock (lockObject) + { + if (instance == null) + instance = new HeartBeater(); + } + } + return instance; + } + } + + + public void Beat() + { + Beat(this.lastFilename); + } + + public void Beat(string filename) { lock (lockObject) { - lastFilename = filename; + this.lastFilename = filename; } - if ((DateTime.Now.Subtract(lastBeat).TotalSeconds > 10) - && (this.FlagRestartRequested == false)) + if ((DateTime.Now.Subtract(this.lastBeat).TotalSeconds > 10) + && (this.FlagRestartRequested == false)) { try { @@ -41,55 +63,32 @@ namespace Swarmops.Utility.BotCode } else { - this.SuggestRestart(); + SuggestRestart(); throw new Exception("Failed to update HeartBeat"); } } catch (Exception e) { - this.SuggestRestart(); + SuggestRestart(); throw new Exception("Failed to update HeartBeat", e); } } } - public void SuggestRestart () + public void SuggestRestart() { if (!File.Exists("./piratebotexit.flag")) File.Create("./piratebotexit.flag"); this.FlagRestartRequested = true; } - public bool WasKilled + public static void writeFile(string sPath, string content) { - get { return (this.FlagRestartRequested == true); } - } - - public static HeartBeater Instance - { - get - { - - if (instance == null) - { - lock (lockObject) - { - if (instance == null) - instance = new HeartBeater(); - } - - } - return instance; - } - } - static public void writeFile (string sPath, string content) - { - StreamWriter writeStream = new StreamWriter(new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite), System.Text.Encoding.Default); + StreamWriter writeStream = new StreamWriter(new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite), + Encoding.Default); writeStream.Write(content); writeStream.Close(); } - - } -} +} \ No newline at end of file diff --git a/Utility/BotCode/InternalPollMaintenance.cs b/Utility/BotCode/InternalPollMaintenance.cs index 0d6016ae..f034683f 100644 --- a/Utility/BotCode/InternalPollMaintenance.cs +++ b/Utility/BotCode/InternalPollMaintenance.cs @@ -8,13 +8,13 @@ namespace Swarmops.Utility.BotCode { public class InternalPollMaintenance { - static public void Run() + public static void Run() { MeetingElections polls = MeetingElections.GetAll(); foreach (MeetingElection poll in polls) { - Console.Write("Looking at poll #" + poll.Identity.ToString() + "..."); + Console.Write("Looking at poll #" + poll.Identity + "..."); if (DateTime.Now > poll.VotingCloses) { @@ -28,7 +28,8 @@ namespace Swarmops.Utility.BotCode 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); + Person.FromIdentity(1) + .SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId); ReportPollResults(poll, false); } @@ -41,89 +42,86 @@ namespace Swarmops.Utility.BotCode { try { + // Poll should be OPEN. + Console.Write("after opendatetime " + poll.VotingOpens.ToString("yyyy-MM-dd HH:mm") + "..."); - // Poll should be OPEN. - - Console.Write("after opendatetime " + poll.VotingOpens.ToString("yyyy-MM-dd HH:mm") + "..."); - - if (!poll.VotingOpen) - { - Console.WriteLine("OPENING for " + poll.Organization.Name + ":"); - - // Populate voters, then open for voting - - Organizations orgTree = poll.Organization.GetTree(); - - Memberships memberships = Memberships.ForOrganizations(orgTree); - - Dictionary dupeCheck = new Dictionary(); - - int count = 0; - - foreach (Membership membership in memberships) + if (!poll.VotingOpen) { - Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count, memberships.Count, membership.PersonId); + Console.WriteLine("OPENING for " + poll.Organization.Name + ":"); - if (!membership.Active) - { - continue; // paranoid programming - } + // Populate voters, then open for voting - if (!membership.Organization.IsOrInherits(poll.Organization)) - { - continue; // more paranoid programming - } + Organizations orgTree = poll.Organization.GetTree(); - if (!dupeCheck.ContainsKey(membership.PersonId)) + Memberships memberships = Memberships.ForOrganizations(orgTree); + + Dictionary dupeCheck = new Dictionary(); + + int count = 0; + + foreach (Membership membership in memberships) { - if (membership.Person.GeographyId == 0) + Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count, + memberships.Count, membership.PersonId); + + if (!membership.Active) { - // It's a trap! - - Console.Write(" GEOGRAPHY ZERO, ignoring\r\n"); + continue; // paranoid programming } - else + + if (!membership.Organization.IsOrInherits(poll.Organization)) { + continue; // more paranoid programming + } - Geography geo = membership.Person.Geography; - - if (geo.Inherits(poll.GeographyId) || geo.Identity == poll.GeographyId) + if (!dupeCheck.ContainsKey(membership.PersonId)) + { + if (membership.Person.GeographyId == 0) { - poll.AddVoter(membership.Person); - dupeCheck[membership.PersonId] = true; + // It's a trap! + + Console.Write(" GEOGRAPHY ZERO, ignoring\r\n"); + } + else + { + Geography geo = membership.Person.Geography; + + if (geo.Inherits(poll.GeographyId) || geo.Identity == poll.GeographyId) + { + poll.AddVoter(membership.Person); + dupeCheck[membership.PersonId] = true; + } } } } + + Console.WriteLine(" done."); + Console.Write(" - opening poll..."); + + poll.VotingOpen = true; + + 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); + + Console.WriteLine(" done."); } + else + { + Console.WriteLine(" already open, no action."); - Console.WriteLine(" done."); - Console.Write(" - opening poll..."); - - poll.VotingOpen = true; - - Console.WriteLine(" done."); - Console.Write("Sending notices... "); - - string body = "Electoral roll for poll \"" + poll.Name + "\" primed. " + - dupeCheck.Count.ToString() + " 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); - - Console.WriteLine(" done."); - } - else - { - Console.WriteLine(" already open, no action."); - - // Report intermediate results to owner - - ReportPollResults(poll, true); - } + // Report intermediate results to owner + ReportPollResults(poll, true); + } } catch (Exception exception) { @@ -131,13 +129,12 @@ namespace Swarmops.Utility.BotCode throw exception; } - } } } - static private void ReportPollResults (MeetingElection poll, bool stillOpen) + private static void ReportPollResults(MeetingElection poll, bool stillOpen) { SchulzeProcessor processor = new SchulzeProcessor(); @@ -167,10 +164,13 @@ 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); + 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 = new int[] { 1 , poll.CreatedByPersonId }; // Send to Rick too while stabilizing functionality -- remove as soon as Rick is running in any poll + int[] recipients = {1, poll.CreatedByPersonId}; + // 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; @@ -179,8 +179,6 @@ namespace Swarmops.Utility.BotCode Person.FromIdentity(personId).SendNotice( subject, body, poll.OrganizationId); } - } - } -} +} \ No newline at end of file diff --git a/Utility/BotCode/InternalPollRandomizer.cs b/Utility/BotCode/InternalPollRandomizer.cs index 3b891195..9b08d321 100644 --- a/Utility/BotCode/InternalPollRandomizer.cs +++ b/Utility/BotCode/InternalPollRandomizer.cs @@ -5,9 +5,8 @@ namespace Swarmops.Utility.BotCode public class InternalPollRandomizer { // Randomizes the order of candidates on the open polls. - static public void Run() + public static void Run() { - // TODO: Foreach open poll... MeetingElectionCandidates candidates = MeetingElectionCandidates.ForPoll(MeetingElection.Primaries2010); @@ -18,4 +17,4 @@ namespace Swarmops.Utility.BotCode } } } -} +} \ No newline at end of file diff --git a/Utility/BotCode/MailProcessor.cs b/Utility/BotCode/MailProcessor.cs index c3df3a6c..a28eb334 100644 --- a/Utility/BotCode/MailProcessor.cs +++ b/Utility/BotCode/MailProcessor.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Configuration; +using System.Diagnostics; using System.IO; using System.Net.Mail; using System.Net.Mime; @@ -19,54 +20,66 @@ namespace Swarmops.Utility.BotCode public class MailProcessor { #region Exception declarations - public class RemoveRecipientException : Exception - { - public RemoveRecipientException (string message, Exception innerException) - : base(message, innerException) - { } - } public class IgnoreRecipientException : Exception { - public IgnoreRecipientException (string message, Exception innerException) + public IgnoreRecipientException(string message, Exception innerException) : base(message, innerException) - { } + { + } } public class InvalidRecipientException : IgnoreRecipientException { - public InvalidRecipientException (string message, Exception innerException) + public InvalidRecipientException(string message, Exception innerException) : base(message, innerException) - { } - } - - public class RetryRecipientException : Exception - { - public RetryRecipientException (string message, Exception innerException) - : base(message, innerException) - { } - } - public class ReportAndRetryRecipientException : RetryRecipientException - { - public ReportAndRetryRecipientException (string message, Exception innerException) - : base(message, innerException) - { } + { + } } public class InvalidSenderException : Exception { - public InvalidSenderException (string message, Exception innerException) + public InvalidSenderException(string message, Exception innerException) : base(message, innerException) - { } + { + } } + + public class RemoveRecipientException : Exception + { + public RemoveRecipientException(string message, Exception innerException) + : base(message, innerException) + { + } + } + + public class ReportAndRetryRecipientException : RetryRecipientException + { + public ReportAndRetryRecipientException(string message, Exception innerException) + : base(message, innerException) + { + } + } + + public class RetryRecipientException : Exception + { + public RetryRecipientException(string message, Exception innerException) + : base(message, innerException) + { + } + } + #endregion - static QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8); - static QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1")); - static Dictionary QuotedPrintableEncoder = InitQpDictionary(); + private static readonly QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8); + private static readonly QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1")); + private static readonly Dictionary QuotedPrintableEncoder = InitQpDictionary(); + private static int mailQueueSize; + private static readonly Object lockObject = new Object(); #region Static initialisation - static private Dictionary InitQpDictionary () + + private static Dictionary InitQpDictionary() { Dictionary qp = new Dictionary(); qp[Encoding.UTF8] = qpUTF8; @@ -76,7 +89,7 @@ namespace Swarmops.Utility.BotCode #endregion - public static void Run () + public static void Run() { // If there is mail in the outbound mail queue, do not add more. (This is a primitive // protection against dupes. Better will come that doesn't force idle time like this.) @@ -103,7 +116,6 @@ namespace Swarmops.Utility.BotCode foreach (OutboundMail mail in mails) { - // If we have already processed past our limit, return for now. if (maxBatchSize < 1) { @@ -118,8 +130,8 @@ namespace Swarmops.Utility.BotCode // Yes! Mark it as started and mail our author. mail.StartProcessDateTime = DateTime.Now; - if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail - || mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag + if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail + || mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag { string mailBody = string.Empty; @@ -133,17 +145,17 @@ namespace Swarmops.Utility.BotCode // If we are debugging, and stepping through this program, avoid the misery of many simultaneous threads. - if (System.Diagnostics.Debugger.IsAttached) + if (Debugger.IsAttached) { batchSize = 1; // Do NOT multithread while debugging } while (true) { - if (!System.Diagnostics.Debugger.IsAttached) + if (!Debugger.IsAttached) { HeartBeater.Instance.Beat(); - //Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging. + //Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging. } OutboundMailRecipients recipients = mail.GetNextRecipientBatch(batchSize); @@ -156,16 +168,19 @@ namespace Swarmops.Utility.BotCode mail.SetProcessed(); - if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail - || mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag + if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail + || mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail) + // TODO: Set special flag { - string body = "Your mail has completed transmitting to " + mail.RecipientCount.ToString("#,##0") + + string body = "Your mail has completed transmitting to " + + mail.RecipientCount.ToString("#,##0") + " intended recipients. Out of these, " + mail.RecipientsFail.ToString("#,##0") + " failed because of invalid, empty, or otherwise bad e-mail addresses. These people have not received your message.\r\n"; - new Mail.MailTransmitter( + new MailTransmitter( Strings.MailSenderName, Strings.MailSenderAddress, - "Mail transmission completed: " + mail.Title, body, Person.FromIdentity(mail.AuthorPersonId), + "Mail transmission completed: " + mail.Title, body, + Person.FromIdentity(mail.AuthorPersonId), true).Send(); } @@ -176,165 +191,154 @@ namespace Swarmops.Utility.BotCode break; //the while loop } - else + List sendInProgress = new List(); + List waitHandlesList = new List(); + foreach (OutboundMailRecipient recipient in recipients) { - List sendInProgress = new List(); - List waitHandlesList = new List(); - foreach (OutboundMailRecipient recipient in recipients) + // Skip known invalid mail addresses + if (recipient.Person != null + && (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable)) { - // Skip known invalid mail addresses - if (recipient.Person != null - && (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable)) - { - lock (lockObject) - { - recipient.Delete(); - recipient.OutboundMail.IncrementFailures(); - } - - continue; - } - - // Start the transmission process, asynchronously - lock (lockObject) { - MailTransmissionDelegate asyncTransmitter = new MailTransmissionDelegate(TransmitOneMail); - MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState(); - asyncState.dlgt = asyncTransmitter; - asyncState.recipient = recipient; - IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, new AsyncCallback(MailSent), asyncState); - sendInProgress.Add(asyncResult); - waitHandlesList.Add(asyncResult.AsyncWaitHandle); - mailQueueSize++; + recipient.Delete(); + recipient.OutboundMail.IncrementFailures(); } - System.Threading.Thread.Sleep(25); // Allow some time + continue; } - // now wait for them to finish; - int numberStillExecuting = sendInProgress.Count; - int numberExecutingLast = numberStillExecuting + 1; - DateTime lastProgress = DateTime.Now; + // Start the transmission process, asynchronously - - while (numberStillExecuting > 0) + lock (lockObject) { - WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true); - lock (lockObject) + MailTransmissionDelegate asyncTransmitter = TransmitOneMail; + MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState(); + asyncState.dlgt = asyncTransmitter; + asyncState.recipient = recipient; + IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, MailSent, asyncState); + sendInProgress.Add(asyncResult); + waitHandlesList.Add(asyncResult.AsyncWaitHandle); + mailQueueSize++; + } + + Thread.Sleep(25); // Allow some time + } + + // now wait for them to finish; + int numberStillExecuting = sendInProgress.Count; + int numberExecutingLast = numberStillExecuting + 1; + DateTime lastProgress = DateTime.Now; + + + while (numberStillExecuting > 0) + { + WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true); + lock (lockObject) + { + numberStillExecuting = 0; + waitHandlesList = new List(); + + for (int i = 0; i < sendInProgress.Count; ++i) { - numberStillExecuting = 0; - waitHandlesList = new List(); + IAsyncResult iares = sendInProgress[i]; + MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) iares.AsyncState; - for (int i = 0; i < sendInProgress.Count; ++i) + if (asyncState.dlgt != null) { - IAsyncResult iares = sendInProgress[i]; - MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)iares.AsyncState; - - if (asyncState.dlgt != null) + if (!asyncState.callbackCompleted) { - if (!asyncState.callbackCompleted) + waitHandlesList.Add(iares.AsyncWaitHandle); + numberStillExecuting++; + } + else + { + //Just finalised + if (asyncState.exception != null) { - waitHandlesList.Add(iares.AsyncWaitHandle); - numberStillExecuting++; - } - else - { - //Just finalised - if (asyncState.exception != null) + if (asyncState.exception is RetryRecipientException) { - if (asyncState.exception is RetryRecipientException) + //Failed in sending due to some reason that can clear up by itself. + asyncState.dlgt = null; + } + else + { + //Make sure recipient is deleted + try { - //Failed in sending due to some reason that can clear up by itself. - asyncState.dlgt = null; + asyncState.recipient.Delete(); + + // if RemoveRecipientException everything went ok except for the removal + if (asyncState.exception is RemoveRecipientException) + asyncState.recipient.OutboundMail.IncrementSuccesses(); + + asyncState.dlgt = null; // mark as done; + mailQueueSize--; } - else + catch { - //Make sure recipient is deleted - try - { - asyncState.recipient.Delete(); - - // if RemoveRecipientException everything went ok except for the removal - if (asyncState.exception is RemoveRecipientException) - asyncState.recipient.OutboundMail.IncrementSuccesses(); - - asyncState.dlgt = null; // mark as done; - mailQueueSize--; - - } - catch - { //Keep looping until recipient removed - numberStillExecuting++; - } + //Keep looping until recipient removed + numberStillExecuting++; } } } } } } + } - if (numberExecutingLast != numberStillExecuting) - lastProgress = DateTime.Now; + if (numberExecutingLast != numberStillExecuting) + lastProgress = DateTime.Now; - numberExecutingLast = numberStillExecuting; + numberExecutingLast = numberStillExecuting; - if (lastProgress.AddSeconds(60 * 2) < DateTime.Now) + if (lastProgress.AddSeconds(60*2) < DateTime.Now) + { + // since last change, something must have hanged + lock (lockObject) { - // since last change, something must have hanged - lock (lockObject) - { - mailQueueSize = -1000; - } - throw new Exception("Timeout in MailProcessor"); + mailQueueSize = -1000; } + throw new Exception("Timeout in MailProcessor"); } } } } } - internal class MailTransmissionAsyncState - { - internal MailTransmissionDelegate dlgt = null; - internal Exception exception = null; - internal OutboundMailRecipient recipient = null; - internal bool callbackCompleted = false; - } - internal delegate OutboundMailRecipient MailTransmissionDelegate (OutboundMailRecipient recipient); - - - internal static OutboundMailRecipient TransmitOneMail (OutboundMailRecipient recipient) + internal static OutboundMailRecipient TransmitOneMail(OutboundMailRecipient recipient) { try { // If the mail address in illegal format, do not try to send anything: if (!Formatting.ValidateEmailFormat(recipient.EmailPerson.Email.Trim())) { - string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" + - recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; + string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + + "], mail [" + + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, null); } // If the mail address is marked as unreachable, do not try to send anything if (recipient.Person != null && recipient.Person.MailUnreachable) { - string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" + - recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; + string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + + "], mail [" + + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, null); } // If the mail address is marked as unreachable, do not try to send anything if (recipient.Person != null && recipient.Person.NeverMail) { - string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" + - recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; + string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + + "], mail [" + + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new IgnoreRecipientException(msg, null); } - // Otherwise, let's start processing OutboundMail mail = recipient.OutboundMail; @@ -384,35 +388,39 @@ namespace Swarmops.Utility.BotCode try { message.From = new MailAddress(mail.Author.PartyEmail, - qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"), - currentEncoding); + qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + + ")"), + currentEncoding); if (mail.Author.Identity == 1) { //TODO: Create alternative party mail optional data field, or organization chairman (based on roles) differently // Ugly hack message.From = new MailAddress("rick.falkvinge@piratpartiet.se", - qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"), - currentEncoding); + qp.EncodeMailHeaderString(mail.Author.Name + " (" + + mail.Organization.MailPrefixInherited + ")"), + currentEncoding); } } catch (Exception ex) { - throw new InvalidSenderException("Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId).ToString() + ";" + mail.Author.PartyEmail, ex); + throw new InvalidSenderException( + "Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId) + ";" + + mail.Author.PartyEmail, ex); } - } else { try { FunctionalMail.AddressItem aItem = mail.Organization.GetFunctionalMailAddressInh(mail.AuthorType); - message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name), - currentEncoding); + message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name), + currentEncoding); } catch (Exception ex) { - throw new InvalidSenderException("Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int)mail.AuthorType).ToString(), ex); + throw new InvalidSenderException( + "Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int) mail.AuthorType), ex); } } @@ -422,13 +430,16 @@ namespace Swarmops.Utility.BotCode try { message.To.Add(new MailAddress(recipient.Person.PartyEmail, - qp.EncodeMailHeaderString(recipient.Person.Name + " (" + mail.Organization.MailPrefixInherited + ")"), - currentEncoding)); + qp.EncodeMailHeaderString(recipient.Person.Name + " (" + + mail.Organization.MailPrefixInherited + ")"), + currentEncoding)); } catch (FormatException e) { - string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity.ToString() + "], mail [" + - recipient.Person.PartyEmail + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; + string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity + + "], mail [" + + recipient.Person.PartyEmail + "]\r\nwill not send mail:" + + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, e); } } @@ -437,13 +448,15 @@ namespace Swarmops.Utility.BotCode try { message.To.Add(new MailAddress(recipient.EmailPerson.Email, - qp.EncodeMailHeaderString(recipient.EmailPerson.Name), - currentEncoding)); + qp.EncodeMailHeaderString(recipient.EmailPerson.Name), + currentEncoding)); } catch (FormatException e) { - string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" + - recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; + string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + + "], mail [" + + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, e); } } @@ -485,7 +498,9 @@ namespace Swarmops.Utility.BotCode } catch (Exception ex) { - throw new RemoveRecipientException("TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); + throw new RemoveRecipientException( + "TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + + " will not retry.\n", ex); } } message.BodyEncoding = currentEncoding; @@ -512,9 +527,13 @@ namespace Swarmops.Utility.BotCode } } if (text == "") - throw new RemoveRecipientException("Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); - else if (html == "" || ex != null) - throw new RemoveRecipientException("Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); + throw new RemoveRecipientException( + "Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + + " will not retry.\n", ex); + if (html == "" || ex != null) + throw new RemoveRecipientException( + "Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + + " will not retry.\n", ex); ContentType textContentType = new ContentType(MediaTypeNames.Text.Plain); textContentType.CharSet = currentEncoding.BodyName; @@ -567,10 +586,10 @@ namespace Swarmops.Utility.BotCode string smtpServer = ConfigurationManager.AppSettings["SmtpServer"]; - if (System.Diagnostics.Debugger.IsAttached) + if (Debugger.IsAttached) { - System.Diagnostics.Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email); - System.Threading.Thread.Sleep(200); //simulate delay + Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email); + Thread.Sleep(200); //simulate delay } @@ -592,7 +611,7 @@ namespace Swarmops.Utility.BotCode { // Temporary error (SMTP 4xx). Try again. - System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available + Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e); } @@ -604,18 +623,22 @@ namespace Swarmops.Utility.BotCode recipients.Add(address.Address); } - ExceptionMail.Send(new ArgumentException("Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " + String.Join(", ", recipients.ToArray()), e)); + ExceptionMail.Send( + new ArgumentException( + "Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " + + String.Join(", ", recipients.ToArray()), e)); if (mail.AuthorType == MailAuthorType.Person) { try { - mail.Author.SendOfficerNotice("Failed recipient(s): " + String.Join(", ", recipients.ToArray()), - "Some recipients failed inexplicably in a mail from you.", 1); + mail.Author.SendOfficerNotice( + "Failed recipient(s): " + String.Join(", ", recipients.ToArray()), + "Some recipients failed inexplicably in a mail from you.", 1); } catch (Exception ex) { - throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId.ToString(), ex); + throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId, ex); } } } @@ -624,28 +647,26 @@ namespace Swarmops.Utility.BotCode } catch (InvalidRecipientException ex) { - throw ex; } catch (RetryRecipientException ex) { - System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure + Thread.Sleep(2000); + // Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure throw ex; } catch (Exception ex) { throw ex; } - } - internal static void MailSent (IAsyncResult result) + internal static void MailSent(IAsyncResult result) { lock (lockObject) { - - MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)result.AsyncState; + MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) result.AsyncState; MailTransmissionDelegate asyncTransmitter = asyncState.dlgt; OutboundMailRecipient recipient = asyncState.recipient; try @@ -667,7 +688,7 @@ namespace Swarmops.Utility.BotCode catch (ReportAndRetryRecipientException e) { asyncState.exception = e; - System.Diagnostics.Debug.WriteLine(e.ToString()); + Debug.WriteLine(e.ToString()); ExceptionMail.Send(e, true); } catch (RetryRecipientException e) @@ -696,13 +717,13 @@ namespace Swarmops.Utility.BotCode catch (Exception ex) { // Return this exception in asyncState since it is important to stop flooding. - asyncState.exception = new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex); + asyncState.exception = + new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex); ExceptionMail.Send(asyncState.exception, true); //Report the secondary exception } - - System.Diagnostics.Debug.WriteLine(e.ToString()); + Debug.WriteLine(e.ToString()); ExceptionMail.Send(e, true); } @@ -710,7 +731,14 @@ namespace Swarmops.Utility.BotCode } } - private static int mailQueueSize; - private static Object lockObject = new Object(); + internal class MailTransmissionAsyncState + { + internal bool callbackCompleted = false; + internal MailTransmissionDelegate dlgt = null; + internal Exception exception = null; + internal OutboundMailRecipient recipient = null; + } + + internal delegate OutboundMailRecipient MailTransmissionDelegate(OutboundMailRecipient recipient); } } \ No newline at end of file diff --git a/Utility/BotCode/MailResolver.cs b/Utility/BotCode/MailResolver.cs index 5e16c4c5..c929a2b8 100644 --- a/Utility/BotCode/MailResolver.cs +++ b/Utility/BotCode/MailResolver.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Swarmops.Basic.Enums; using Swarmops.Logic.Communications; using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; using Swarmops.Logic.Swarm; using Swarmops.Utility.Mail; @@ -11,7 +10,7 @@ namespace Swarmops.Utility.BotCode { public class MailResolver { - public static void Run () + public static void Run() { OutboundMail mail = OutboundMail.GetFirstUnresolved(); @@ -32,7 +31,7 @@ namespace Swarmops.Utility.BotCode switch (mail.MailType) { - case (int)TypedMailTemplate.TemplateType.MemberMail: + case (int) TypedMailTemplate.TemplateType.MemberMail: // All members at this org and geography People people = People.FromOrganizationAndGeography(mail.Organization, mail.Geography); @@ -43,7 +42,7 @@ namespace Swarmops.Utility.BotCode } break; - case (int)TypedMailTemplate.TemplateType.OfficerMail: + case (int) TypedMailTemplate.TemplateType.OfficerMail: // All officers at this org and geography int[] officers = Roles.GetAllDownwardRoles(mail.OrganizationId, mail.GeographyId); downwardCount = officers.Length; @@ -55,7 +54,7 @@ namespace Swarmops.Utility.BotCode default: throw new InvalidOperationException("Unhandled mail mode; can't resolve mail id " + - mail.Identity.ToString()); + mail.Identity); } int[] upwardIds = Roles.GetAllUpwardRoles(mail.OrganizationId, mail.GeographyId); @@ -155,19 +154,18 @@ namespace Swarmops.Utility.BotCode mailBody += "Transmissions will begin " + (mail.ReleaseDateTime < DateTime.Now - ? "immediately" - : - "in " + (mail.ReleaseDateTime - DateTime.Now).Minutes.ToString() + - " minutes") + ".\r\n"; + ? "immediately" + : "in " + (mail.ReleaseDateTime - DateTime.Now).Minutes + + " minutes") + ".\r\n"; new MailTransmitter( "PirateWeb", "noreply@pirateweb.net", - "Mail resolved: " + mail.Title + " (" + countTotal.ToString() + " recipients)", mailBody, + "Mail resolved: " + mail.Title + " (" + countTotal + " recipients)", mailBody, Person.FromIdentity(mail.AuthorPersonId), true).Send(); } - static private People ApplySubscription (People input, int feedId) + private static People ApplySubscription(People input, int feedId) { People output = new People(); @@ -183,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 @@ -192,7 +190,7 @@ namespace Swarmops.Utility.BotCode orgLine.Reverse(); // Start at the most local org - Dictionary orgMailedLookup = new Dictionary(); + Dictionary orgMailedLookup = new Dictionary(); int delay = 0; string result = string.Empty; @@ -215,7 +213,8 @@ namespace Swarmops.Utility.BotCode try { lead = Roles.GetLocalLead(org, geo); - orgMailedLookup[org.Identity] = true; // Make sure that the chairman doesn't mail at a lower level + orgMailedLookup[org.Identity] = true; + // Make sure that the chairman doesn't mail at a lower level } catch (ArgumentException) { @@ -226,7 +225,7 @@ namespace Swarmops.Utility.BotCode // 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. // Try to mail from chairman rather than the local lead. - + try { orgMailedLookup[org.Identity] = true; @@ -257,16 +256,16 @@ 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)); + + 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} (", - org.NameShort, geoName, lead.Canonical); + org.NameShort, geoName, lead.Canonical); if (delay == 0) { result += "sent now"; diff --git a/Utility/BotCode/Mappery.cs b/Utility/BotCode/Mappery.cs index d34f8372..bf573353 100644 --- a/Utility/BotCode/Mappery.cs +++ b/Utility/BotCode/Mappery.cs @@ -1,18 +1,13 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using Swarmops.Basic.Enums; -using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; -using Swarmops.Logic.Swarm; namespace Swarmops.Utility.BotCode { public class Mappery { + public Dictionary OrgColorLookup; // ugly way to transfer data to delegate + [Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)] public static void CreateUngPiratUptakeMap() { @@ -106,8 +101,6 @@ namespace Swarmops.Utility.BotCode Persistence.Key["OrgUptakeMap-2"] = regex.Replace(svg, matchEvaluator);*/ } - - public Dictionary OrgColorLookup; // ugly way to transfer data to delegate /* public string UPUptakeLookupReplacer (Match match) { @@ -127,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)); + Convert.ToInt32(b*255), Convert.ToInt32(b*255)); } float fMax, fMid, fMin; diff --git a/Utility/BotCode/MediaWatcher.cs b/Utility/BotCode/MediaWatcher.cs index 9c0bd51d..7cab3128 100644 --- a/Utility/BotCode/MediaWatcher.cs +++ b/Utility/BotCode/MediaWatcher.cs @@ -7,13 +7,7 @@ namespace Swarmops.Utility.BotCode { public class MediaWatcher { - public class ReaderException : Exception - { - public ReaderException (string message, Exception innerException) - : base(message, innerException) - { } - } - public static void Run () + public static void Run() { // Get keywords. Read Frisim. Parse. Store. @@ -27,10 +21,10 @@ namespace Swarmops.Utility.BotCode // Read the RSS URL into memory, then feed RssReader from a MemoryStream - HttpWebRequest request = (HttpWebRequest) HttpWebRequest.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(); + HttpWebResponse resp = (HttpWebResponse) request.GetResponse(); RssReader reader = new RssReader(resp.GetResponseStream()); try @@ -60,5 +54,13 @@ namespace Swarmops.Utility.BotCode } } } + + public class ReaderException : Exception + { + public ReaderException(string message, Exception innerException) + : base(message, innerException) + { + } + } } } \ No newline at end of file diff --git a/Utility/BotCode/NewsletterChecker.cs b/Utility/BotCode/NewsletterChecker.cs index a3be9eb0..9bba0295 100644 --- a/Utility/BotCode/NewsletterChecker.cs +++ b/Utility/BotCode/NewsletterChecker.cs @@ -1,31 +1,20 @@ using System; using System.Collections.Generic; -using NRss; -using Swarmops.Logic.Communications; -using Swarmops.Logic.Special.Sweden; -using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; -using Swarmops.Logic.Swarm; namespace Swarmops.Utility.BotCode { public class NewsletterChecker { - const int ForumIdTestPost = 262;//vBulletin, old forum was 326; - const int ForumIdNewsletter = 342; //vBulletin, old forum was 69; + private const int ForumIdTestPost = 262; //vBulletin, old forum was 326; + private const int ForumIdNewsletter = 342; //vBulletin, old forum was 69; - public class ReaderException : Exception - { - public ReaderException (string message, Exception innerException) - : base(message, innerException) - { } - } - static Dictionary feedErrorSignaled = new Dictionary(); + private static Dictionary feedErrorSignaled = new Dictionary(); [Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)] public static void Run() - {/* + { +/* //TODO: This list should reside in database/by organisation and possibly geography. CheckOneBlog("http://rickfalkvinge.se/feed", 1); @@ -33,6 +22,15 @@ namespace Swarmops.Utility.BotCode CheckOneBlog("http://opassande.se/index.php/feed/", 367); CheckOneBlog("http://www.annatroberg.com/feed/", 11443);*/ } + + public class ReaderException : Exception + { + public ReaderException(string message, Exception innerException) + : base(message, innerException) + { + } + } + /* private static void CheckOneBlog (string readerFeedUrl, int personId) { diff --git a/Utility/BotCode/PressReleaseChecker.cs b/Utility/BotCode/PressReleaseChecker.cs index 6ff3af99..aa6098b4 100644 --- a/Utility/BotCode/PressReleaseChecker.cs +++ b/Utility/BotCode/PressReleaseChecker.cs @@ -13,20 +13,19 @@ 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)] - public static void Run () + public static void Run() { throw new NotImplementedException(); - + //TODO: This list should reside in database/by organisation and possibly geography. /* CheckOneFeed("http://press.piratpartiet.se/feed", "PPSE", Organization.PPSEid); CheckOneFeed("http://presscenter.ungpirat.se/feed", "UPSE", Organization.UPSEid); */ - } - 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); @@ -46,7 +45,6 @@ namespace Swarmops.Utility.BotCode } else { - try { highWaterMark = DateTime.Parse(highWaterMarkString); @@ -55,7 +53,9 @@ namespace Swarmops.Utility.BotCode { HeartBeater.Instance.SuggestRestart(); 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.ToString(), ex); + "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; @@ -95,7 +95,8 @@ namespace Swarmops.Utility.BotCode catch (Exception ex) { throw new Exception( - "Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" + newStoredHighWaterString + "'", ex); + "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) @@ -117,9 +118,8 @@ namespace Swarmops.Utility.BotCode } else if (category.Name == "Uncategorized") { - continue; } - else + else { try { @@ -133,7 +133,8 @@ namespace Swarmops.Utility.BotCode } 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)); } } } @@ -172,7 +173,6 @@ namespace Swarmops.Utility.BotCode } - // Send press release //TODO: hardcoded geo ... using World @@ -186,7 +186,7 @@ namespace Swarmops.Utility.BotCode pressreleasemail.pOrgName = org.MailPrefixInherited; if (allReporters) { - pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE + pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE } else if (international) { @@ -197,7 +197,8 @@ namespace Swarmops.Utility.BotCode pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories); } - OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, OutboundMail.PriorityHighest, org, geo); + OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, + OutboundMail.PriorityHighest, org, geo); int recipientCount = 0; foreach (Reporter recipient in reporters) @@ -227,14 +228,16 @@ namespace Swarmops.Utility.BotCode } 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 { reader.Close(); } } - private static string Blog2Mail (string text) + + private static string Blog2Mail(string text) { return text. Replace("

", "

"). @@ -246,6 +249,5 @@ namespace Swarmops.Utility.BotCode Replace("—", "--"). Replace("…", "..."); } - } } \ No newline at end of file diff --git a/Utility/BotCode/RosterHousekeeping.cs b/Utility/BotCode/RosterHousekeeping.cs index 2dd89220..0e550901 100644 --- a/Utility/BotCode/RosterHousekeeping.cs +++ b/Utility/BotCode/RosterHousekeeping.cs @@ -1,18 +1,13 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; -using Swarmops.Basic; using Swarmops.Basic.Enums; using Swarmops.Basic.Types; -using Swarmops.Database; using Swarmops.Logic.Communications; -using Swarmops.Logic.DataObjects; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Support; using Swarmops.Logic.Swarm; -using Swarmops.Utility.Mail; namespace Swarmops.Utility.BotCode { @@ -21,7 +16,7 @@ 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(); StringBuilder result = new StringBuilder(); @@ -61,8 +56,8 @@ namespace Swarmops.Utility.BotCode { csvResultList.Add( String.Format("{0},{1},{2},{3:yyyy-MMM-dd},{4}", - person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate, - person.IsMale ? "Male" : "Female")); + person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate, + person.IsMale ? "Male" : "Female")); } string[] csvResults = csvResultList.ToArray(); @@ -80,7 +75,7 @@ namespace Swarmops.Utility.BotCode // This should run daily. - public static void RemindAllExpiries () + public static void RemindAllExpiries() { throw new NotImplementedException(); @@ -97,7 +92,7 @@ namespace Swarmops.Utility.BotCode [Obsolete("Generalize and localize this function.", true)] - public static void RemindExpiriesMail () + public static void RemindExpiriesMail() { // Get expiring @@ -120,7 +115,7 @@ namespace Swarmops.Utility.BotCode foreach (Membership membership in memberships) { - if (membership.OrganizationId % 7 != weekDayInteger) + if (membership.OrganizationId%7 != weekDayInteger) { continue; } @@ -132,9 +127,9 @@ namespace Swarmops.Utility.BotCode 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); + PWLogAction.MembershipRenewReminder, + "Mail was sent to " + membership.Person.Mail + + " reminding to renew membership in " + membership.Organization.Name + ".", string.Empty); Console.Write("."); @@ -150,11 +145,11 @@ namespace Swarmops.Utility.BotCode catch (Exception x) { string logText = "FAILED sending mail to " + membership.Person.Mail + - " for reminder of pending renewal in " + membership.Organization.Name + "."; + " for reminder of pending renewal in " + membership.Organization.Name + "."; failedReminders.Add(membership.Person.Canonical); PWLog.Write(PWLogItem.Person, membership.PersonId, - PWLogAction.MembershipRenewReminder, - logText, string.Empty); + PWLogAction.MembershipRenewReminder, + logText, string.Empty); ExceptionMail.Send(new Exception(logText, x)); } } @@ -204,7 +199,7 @@ namespace Swarmops.Utility.BotCode // This should run daily, suggested right after midnight. - public static void ChurnExpiredMembers () + public static void ChurnExpiredMembers() { Organizations organizations = Organizations.GetAll(); @@ -231,8 +226,9 @@ namespace Swarmops.Utility.BotCode if (personRole.OrganizationId == membership.OrganizationId) { PWEvents.CreateEvent(EventSource.PirateBot, EventType.DeletedRole, person.Identity, - personRole.OrganizationId, personRole.GeographyId, person.Identity, (int)personRole.Type, - string.Empty); + personRole.OrganizationId, personRole.GeographyId, person.Identity, + (int) personRole.Type, + string.Empty); personRole.Delete(); } } @@ -257,7 +253,7 @@ namespace Swarmops.Utility.BotCode { foreach (Membership personMembership in membershipsToDelete) { - membershipsIds += "," + personMembership.MembershipId.ToString(); + membershipsIds += "," + personMembership.MembershipId; } membershipsIds = membershipsIds.Substring(1); string expiredMemberships = ""; @@ -267,7 +263,6 @@ namespace Swarmops.Utility.BotCode { expiredMemberships += ", " + personMembership.Organization.Name; } - } expiredMemberships += ". "; expiredmail.pMemberships = expiredMemberships.Substring(2).Trim(); @@ -275,9 +270,9 @@ namespace Swarmops.Utility.BotCode //TODO: URL for renewal, recieving end of this is NOT yet implemented... // intended to recreate the memberships in MID - string tokenBase = person.PasswordHash + "-" + membership.Expires.Year.ToString(); + string tokenBase = person.PasswordHash + "-" + membership.Expires.Year; string stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" + - person.Identity.ToString() + + person.Identity + "&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8) + "&MID=" + membershipsIds; @@ -304,7 +299,7 @@ namespace Swarmops.Utility.BotCode } [Obsolete("Generalize and localize this functionality.", true)] - internal static void RemindExpiries (DateTime dateExpiry) + internal static void RemindExpiries(DateTime dateExpiry) { Organizations orgs = Organizations.GetAll(); @@ -320,20 +315,21 @@ namespace Swarmops.Utility.BotCode { 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); + 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) + internal static void RemindExpiriesSms(DateTime dateExpiry, string message) { throw new NotImplementedException(); @@ -375,7 +371,7 @@ namespace Swarmops.Utility.BotCode } - internal static bool SendReminderSms (Person person, string message) + internal static bool SendReminderSms(Person person, string message) { bool result = false; @@ -384,7 +380,7 @@ namespace Swarmops.Utility.BotCode person.SendPhoneMessage(message); result = true; } - // ignore exceptions + // ignore exceptions catch (Exception) { } @@ -393,7 +389,7 @@ namespace Swarmops.Utility.BotCode } [Obsolete("Generalize and localize this function.", true)] - public static void SendReminderMail (Membership membership) + public static void SendReminderMail(Membership membership) { /* // First, determine the organization template to use. Prioritize a long ancestry. @@ -494,7 +490,7 @@ namespace Swarmops.Utility.BotCode }*/ } - public static void TimeoutVolunteers () + public static void TimeoutVolunteers() { Volunteers volunteers = Volunteers.GetOpen(); DateTime threshold = DateTime.Today.AddDays(-30); @@ -521,6 +517,5 @@ namespace Swarmops.Utility.BotCode // Deleted a ton of special cases here, see file history if you need to copy code for reminding people to change org - } } \ No newline at end of file diff --git a/Utility/BotCode/SalaryProcessor.cs b/Utility/BotCode/SalaryProcessor.cs index 2d182a0b..23ea2156 100644 --- a/Utility/BotCode/SalaryProcessor.cs +++ b/Utility/BotCode/SalaryProcessor.cs @@ -9,7 +9,7 @@ namespace Swarmops.Utility.BotCode { public class SalaryProcessor { - static public void Run() + public static void Run() { DateTime today = DateTime.Today; @@ -17,7 +17,7 @@ namespace Swarmops.Utility.BotCode 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 @@ -31,14 +31,13 @@ namespace Swarmops.Utility.BotCode Payroll payroll = Payroll.GetAll(); DateTime payday = new DateTime(today.Year, today.Month, 25); - Dictionary salariesTotalPerBudget = new Dictionary(); + Dictionary salariesTotalPerBudget = new Dictionary(); foreach (PayrollItem payrollItem in payroll) { Salary salary = Salary.Create(payrollItem, payday); PWEvents.CreateEvent(EventSource.PirateBot, EventType.SalaryCreated, 0, payrollItem.OrganizationId, - 0, payrollItem.Person.Identity, salary.Identity, string.Empty); - + 0, payrollItem.Person.Identity, salary.Identity, string.Empty); } } @@ -65,4 +64,4 @@ namespace Swarmops.Utility.BotCode transaction.Dependency = salary; }*/ } -} +} \ No newline at end of file diff --git a/Utility/BotCode/SchulzeProcessor.cs b/Utility/BotCode/SchulzeProcessor.cs index 2f05f02f..46933e72 100644 --- a/Utility/BotCode/SchulzeProcessor.cs +++ b/Utility/BotCode/SchulzeProcessor.cs @@ -5,13 +5,18 @@ using Swarmops.Logic.Governance; namespace Swarmops.Utility.BotCode { /// - /// This class computes a Condorcet/Single-Transferable-Vote result according to the Schulze Method. + /// This class computes a Condorcet/Single-Transferable-Vote result according to the Schulze Method. /// public class SchulzeProcessor { + private List candidateIds; + private Dictionary indexOfCandidateId; + private int[,] linkStrengthXtoY; + private int[,] preferenceXtoY; public MeetingElectionVotes Votes { set; private get; } public MeetingElectionCandidates Candidates { set; private get; } + public MeetingElectionCandidates FinalOrder { get; private set; } public void Process() { @@ -35,13 +40,13 @@ namespace Swarmops.Utility.BotCode Console.Write("Creating list of candidates and index lookup..."); - candidateIds = new List(); - indexOfCandidateId = new Dictionary(); + this.candidateIds = new List(); + this.indexOfCandidateId = new Dictionary(); int index = 0; foreach (MeetingElectionCandidate candidate in Candidates) { - candidateIds.Add(candidate.Identity); - indexOfCandidateId[candidate.Identity] = index; + this.candidateIds.Add(candidate.Identity); + this.indexOfCandidateId[candidate.Identity] = index; index++; } @@ -61,7 +66,8 @@ namespace Swarmops.Utility.BotCode // At the end of the iteration, we set all the NOT-checked-off candidates as inferior to those // checked off (as they were not voted for). - preferenceXtoY = new int[candidateIds.Count,candidateIds.Count]; // huuuuuge matrix for 1000+ candidates, zero inited + this.preferenceXtoY = new int[this.candidateIds.Count, this.candidateIds.Count]; + // huuuuuge matrix for 1000+ candidates, zero inited int count = 1; @@ -73,14 +79,15 @@ namespace Swarmops.Utility.BotCode Dictionary candidateIdSeen = new Dictionary(); int[] voteCandidateIds = vote.SelectedCandidateIdsInOrder; - + foreach (int candidateId in voteCandidateIds) { // for each candidate, record all previously iterated as superior for this vote: foreach (int previousCandidateId in candidateIdSeen.Keys) { - preferenceXtoY[indexOfCandidateId[previousCandidateId], indexOfCandidateId[candidateId]]++; + this.preferenceXtoY[ + this.indexOfCandidateId[previousCandidateId], this.indexOfCandidateId[candidateId]]++; } // check this candidate off as iterated @@ -92,7 +99,7 @@ namespace Swarmops.Utility.BotCode // superior to the candidates NOT on the votes cast. Iterate through all the candidates to find which ones // were not mentioned. - foreach (int candidateId in candidateIds) + foreach (int candidateId in this.candidateIds) { if (!candidateIdSeen.ContainsKey(candidateId)) { @@ -100,7 +107,8 @@ namespace Swarmops.Utility.BotCode foreach (int voteCandidateId in voteCandidateIds) { - preferenceXtoY[indexOfCandidateId[voteCandidateId], indexOfCandidateId[candidateId]]++; + this.preferenceXtoY[ + this.indexOfCandidateId[voteCandidateId], this.indexOfCandidateId[candidateId]]++; } } } @@ -118,29 +126,28 @@ namespace Swarmops.Utility.BotCode // // http://en.wikipedia.org/wiki/Schulze_method - linkStrengthXtoY = new int[candidateIds.Count,candidateIds.Count]; + this.linkStrengthXtoY = new int[this.candidateIds.Count, this.candidateIds.Count]; // First part of magic. Establish the direction of pairwise defeats. I think. Console.WriteLine("Calculating link strengths."); - for (int outerIndex = 0; outerIndex < candidateIds.Count; outerIndex++) + for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++) { - Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex+1, candidateIds.Count); + Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count); - for (int innerIndex = 0; innerIndex < candidateIds.Count; innerIndex++) + for (int innerIndex = 0; innerIndex < this.candidateIds.Count; innerIndex++) { if (innerIndex == outerIndex) { continue; } - if (preferenceXtoY[outerIndex, innerIndex] > preferenceXtoY[innerIndex, outerIndex]) + if (this.preferenceXtoY[outerIndex, innerIndex] > this.preferenceXtoY[innerIndex, outerIndex]) { - linkStrengthXtoY[outerIndex, innerIndex] = preferenceXtoY[outerIndex, innerIndex]; + this.linkStrengthXtoY[outerIndex, innerIndex] = this.preferenceXtoY[outerIndex, innerIndex]; } // else set to zero, but this is handled by the framework on initialization - } } @@ -148,29 +155,28 @@ namespace Swarmops.Utility.BotCode // Second part of magic, an O(n^3) algorithm. In the famous words of Alfred E. Neuman: Yecch! - for (int outerIndex = 0; outerIndex < candidateIds.Count; outerIndex++) + for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++) { - Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, candidateIds.Count); + Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count); - for (int middleIndex = 0; middleIndex < candidateIds.Count; middleIndex++) + for (int middleIndex = 0; middleIndex < this.candidateIds.Count; middleIndex++) { if (outerIndex == middleIndex) { continue; } - for (int innerIndex = 0; innerIndex < candidateIds.Count; innerIndex++) + for (int innerIndex = 0; innerIndex < this.candidateIds.Count; innerIndex++) { - if (outerIndex == innerIndex || middleIndex == innerIndex) { continue; } - linkStrengthXtoY[middleIndex, innerIndex] = - Math.Max(linkStrengthXtoY[middleIndex, innerIndex], - Math.Min(linkStrengthXtoY[middleIndex, outerIndex], - linkStrengthXtoY[outerIndex, innerIndex])); + this.linkStrengthXtoY[middleIndex, innerIndex] = + Math.Max(this.linkStrengthXtoY[middleIndex, innerIndex], + Math.Min(this.linkStrengthXtoY[middleIndex, outerIndex], + this.linkStrengthXtoY[outerIndex, innerIndex])); } } } @@ -186,7 +192,7 @@ namespace Swarmops.Utility.BotCode MeetingElectionCandidates result = new MeetingElectionCandidates(); Dictionary candidateAdded = new Dictionary(); - int candidatesRemaining = candidateIds.Count; + int candidatesRemaining = this.candidateIds.Count; int count = 1; @@ -213,15 +219,17 @@ namespace Swarmops.Utility.BotCode { allSuperior = true; - for (int compareCandidateIndex = 0; compareCandidateIndex < candidateIds.Count; compareCandidateIndex++) + for (int compareCandidateIndex = 0; + compareCandidateIndex < this.candidateIds.Count; + compareCandidateIndex++) { if (candidateAdded.ContainsKey(compareCandidateIndex)) { continue; } - if (linkStrengthXtoY[winningCandidateIndex, compareCandidateIndex] < - linkStrengthXtoY[compareCandidateIndex,winningCandidateIndex]) + if (this.linkStrengthXtoY[winningCandidateIndex, compareCandidateIndex] < + this.linkStrengthXtoY[compareCandidateIndex, winningCandidateIndex]) { // the compareCandidateIndex had a greater link strength, so jump there and take it as // a new potential winner, restarting the comparison @@ -235,7 +243,8 @@ namespace Swarmops.Utility.BotCode // We have the winning candidate among the not-yet-ranked candidates: - MeetingElectionCandidate candidate = MeetingElectionCandidate.FromIdentity(candidateIds[winningCandidateIndex]); + MeetingElectionCandidate candidate = + MeetingElectionCandidate.FromIdentity(this.candidateIds[winningCandidateIndex]); candidateAdded[winningCandidateIndex] = true; result.Add(candidate); @@ -249,19 +258,12 @@ namespace Swarmops.Utility.BotCode } - private int[,] preferenceXtoY; - private int[,] linkStrengthXtoY; - private List candidateIds; - private Dictionary indexOfCandidateId; - - public MeetingElectionCandidates FinalOrder { get; private set; } - - 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. - if (finalOrderIndex >= FinalOrder.Count -1) + if (finalOrderIndex >= FinalOrder.Count - 1) { return 0; } @@ -269,12 +271,12 @@ namespace Swarmops.Utility.BotCode int candidateIdX = FinalOrder[finalOrderIndex].Identity; int candidateIdY = FinalOrder[finalOrderIndex + 1].Identity; - int indexX = indexOfCandidateId[candidateIdX]; - int indexY = indexOfCandidateId[candidateIdY]; + int indexX = this.indexOfCandidateId[candidateIdX]; + int indexY = this.indexOfCandidateId[candidateIdY]; - int distance = preferenceXtoY[indexX, indexY] - preferenceXtoY[indexY, indexX]; + int distance = this.preferenceXtoY[indexX, indexY] - this.preferenceXtoY[indexY, indexX]; return distance; } } -} +} \ No newline at end of file diff --git a/Utility/BotCode/TurnaroundTracker.cs b/Utility/BotCode/TurnaroundTracker.cs index c5e65fb9..2657c6de 100644 --- a/Utility/BotCode/TurnaroundTracker.cs +++ b/Utility/BotCode/TurnaroundTracker.cs @@ -1,9 +1,4 @@ using System; -using Swarmops.Database; -using Swarmops.Logic.Communications; -using Swarmops.Logic.Special.Sweden; -using Swarmops.Logic.Structure; -using Swarmops.Logic.Support; namespace Swarmops.Utility.BotCode { @@ -86,6 +81,7 @@ namespace Swarmops.Utility.BotCode Persistence.Key[persistenceKey] = lastDeltaId.ToString();*/ } + /* public static void Housekeeping() { @@ -106,4 +102,4 @@ namespace Swarmops.Utility.BotCode } }*/ } -} +} \ No newline at end of file diff --git a/Utility/BotCode/UpdateStatsCache.cs b/Utility/BotCode/UpdateStatsCache.cs index a3515133..d04ba369 100644 --- a/Utility/BotCode/UpdateStatsCache.cs +++ b/Utility/BotCode/UpdateStatsCache.cs @@ -2,7 +2,7 @@ namespace Swarmops.Utility.BotCode { public class UpdateStatsCache { - static public void Run() + public static void Run() { BotLog.Write(1, "UpdateStatsCache", "Entering (obsoleted does nothing"); @@ -11,14 +11,15 @@ namespace Swarmops.Utility.BotCode BotLog.Write(1, "UpdateStatsCache", "Exiting"); } - private static void UpdateBallotDistroData () + private static void UpdateBallotDistroData() { //Empty method now this is done from the web app. } - private static void ObsoletedUpdateBallotDistroData () + private static void ObsoletedUpdateBallotDistroData() { #region Obsoleted commented code + //BotLog.Write(2, "BallotDistroData", "Entering"); //BotLog.Write(2, "BallotDistroData", "Getting geographic voter counts..."); @@ -175,12 +176,9 @@ namespace Swarmops.Utility.BotCode //BotLog.Write(2, "BallotDistroData", "Done collecting election day data."); - - //BotLog.Write(2, "BallotDistroData", "Aggregating per electoral circuit."); - //// This is not very optimized, but it runs only once per hour and //// has easy-to-follow logic. @@ -234,7 +232,8 @@ namespace Swarmops.Utility.BotCode //Persistence.Key["BallotCoverage-SE"] = coverageData.ToXml(); //BotLog.Write(2, "BallotDistroData", "Exiting"); + #endregion } } -} +} \ No newline at end of file diff --git a/Utility/Communications/CommsTransmitterMail.cs b/Utility/Communications/CommsTransmitterMail.cs index 6fa428b4..df08005a 100644 --- a/Utility/Communications/CommsTransmitterMail.cs +++ b/Utility/Communications/CommsTransmitterMail.cs @@ -8,7 +8,7 @@ using Swarmops.Logic.Swarm; namespace Swarmops.Utility.Communications { - public class CommsTransmitterMail: ICommsTransmitter + public class CommsTransmitterMail : ICommsTransmitter { // To be implemented @@ -32,7 +32,8 @@ namespace Swarmops.Utility.Communications try { - mail.From = new MailAddress(comm[CommRenderPart.SenderMail], comm[CommRenderPart.SenderName], Encoding.UTF8); + mail.From = new MailAddress(comm[CommRenderPart.SenderMail], comm[CommRenderPart.SenderName], + Encoding.UTF8); mail.To.Add(new MailAddress(person.Mail, person.Name)); } catch (ArgumentException e) @@ -54,13 +55,14 @@ namespace Swarmops.Utility.Communications if (now > _cacheReloadTime) { - smtpServer = _smtpServerCache = Persistence.Key ["SmtpServer"]; + smtpServer = _smtpServerCache = Persistence.Key["SmtpServer"]; _cacheReloadTime = now.AddMinutes(5); } if (string.IsNullOrEmpty(smtpServer)) { - smtpServer = "192.168.80.204"; // For development use only - invalidate cache instead of this, forcing re-reload + smtpServer = "192.168.80.204"; + // For development use only - invalidate cache instead of this, forcing re-reload _cacheReloadTime = DateTime.MinValue; } @@ -78,6 +80,5 @@ namespace Swarmops.Utility.Communications throw new OutboundCommTransmitException("Cannot send mail to " + person.Mail, e); } } - } -} +} \ No newline at end of file diff --git a/Utility/ExceptionMail.cs b/Utility/ExceptionMail.cs index a0f82238..94a17160 100644 --- a/Utility/ExceptionMail.cs +++ b/Utility/ExceptionMail.cs @@ -8,12 +8,12 @@ namespace Swarmops.Utility { public class ExceptionMail { - public static void Send (Exception e) + public static void Send(Exception e) { - ExceptionMail.Send(e, false); + Send(e, false); } - public static void Send (Exception e, bool logOnly) + public static void Send(Exception e, bool logOnly) { try { @@ -26,8 +26,8 @@ namespace Swarmops.Utility if (!logOnly) { new MailTransmitter(Strings.MailSenderName, Strings.MailSenderAddress, - "Swarmops EXCEPTION!", - e.ToString(), People.FromIdentities(new int[] { 1 }), false).Send(); + "Swarmops EXCEPTION!", + e.ToString(), People.FromIdentities(new[] {1}), false).Send(); } } } diff --git a/Utility/Financial/PaymentGroupMapper.cs b/Utility/Financial/PaymentGroupMapper.cs index 97327304..12ebbc95 100644 --- a/Utility/Financial/PaymentGroupMapper.cs +++ b/Utility/Financial/PaymentGroupMapper.cs @@ -21,7 +21,8 @@ namespace Swarmops.Utility.Financial { foreach (FinancialTransaction tx in unbalancedTransactions) { - if (group.Open && tx.Description.EndsWith(group.Tag.Substring(4)) && tx.DateTime.Date == group.DateTime.Date && tx.Rows.AmountCentsTotal == group.AmountCents) + if (group.Open && tx.Description.EndsWith(group.Tag.Substring(4)) && + tx.DateTime.Date == group.DateTime.Date && tx.Rows.AmountCentsTotal == group.AmountCents) { // Match! @@ -34,4 +35,4 @@ namespace Swarmops.Utility.Financial } } } -} +} \ No newline at end of file diff --git a/Utility/Financial/PaypalImporter.cs b/Utility/Financial/PaypalImporter.cs index f8749a49..b6bdc566 100644 --- a/Utility/Financial/PaypalImporter.cs +++ b/Utility/Financial/PaypalImporter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; @@ -14,7 +15,8 @@ namespace Swarmops.Utility.Financial { if (!data.StartsWith("Date\t Time\t Time Zone\t Name\t Type")) { - 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."); + 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"); } @@ -35,7 +37,8 @@ namespace Swarmops.Utility.Financial 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); + mailBody += String.Format("Tx modified: {0,9:N0}\r\n", + stats.ModifiedTransactionCount - stats.ImportedTransactionCount); runningPerson.SendNotice("PayPal file imported", mailBody, organization.Identity); } @@ -72,7 +75,7 @@ namespace Swarmops.Utility.Financial // DEBUG -- REMOVE WHEN DEPLOYING - if (System.Diagnostics.Debugger.IsAttached) + if (Debugger.IsAttached) { Console.WriteLine("New Row -----"); @@ -86,8 +89,9 @@ namespace Swarmops.Utility.Financial 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.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(",", "")); @@ -99,25 +103,6 @@ namespace Swarmops.Utility.Financial } - protected class ImportResult - { - public double CurrentBalance; - public List Rows; - } - - protected class ImportedRow - { - public DateTime DateTime; - public string HashBase; - public string SuppliedTransactionId; - public double CurrentBalance; - public Int64 AmountCentsNet; - public Int64 AmountCentsGross; - public Int64 FeeCents; - public string Comment; - } - - protected static string StripQuotes(string input) { if (input.StartsWith("\"")) @@ -134,21 +119,14 @@ namespace Swarmops.Utility.Financial } - protected class ImportStats - { - public int ProcessedTransactionCount; - public int ModifiedTransactionCount; - public int ImportedTransactionCount; - } - - - protected static ImportStats ProcessImportedData(ImportResult import, Organization organization, Person importingPerson) + protected static ImportStats ProcessImportedData(ImportResult import, Organization organization, + Person importingPerson) { FinancialAccount payPalAccount = organization.FinancialAccounts.AssetsPaypal; FinancialAccount bankFees = organization.FinancialAccounts.CostsBankFees; FinancialAccount donations = organization.FinancialAccounts.IncomeDonations; - int autoDepositLimit = 1000; // TODO: Get from organization parameters + int autoDepositLimit = 1000; // TODO: Get from organization parameters int autoWithdrawalLimit = 0; ImportStats result = new ImportStats(); @@ -170,7 +148,9 @@ namespace Swarmops.Utility.Financial if (string.IsNullOrEmpty(importKey)) { - string hashKey = row.HashBase + row.Comment + (row.AmountCentsNet / 100.0).ToString(CultureInfo.InvariantCulture) + row.CurrentBalance.ToString(CultureInfo.InvariantCulture) + + 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"); importKey = SHA1.Hash(hashKey).Replace(" ", ""); @@ -195,16 +175,15 @@ namespace Swarmops.Utility.Financial try { 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, - payPalAccount.Identity, amountCents, - row.Comment, importKey, - importingPerson.Identity); + payPalAccount.Identity, amountCents, + row.Comment, importKey, + importingPerson.Identity); result.ImportedTransactionCount++; if (transaction == null) @@ -225,7 +204,7 @@ namespace Swarmops.Utility.Financial if (amountCents < 0) { - if ((-amountCents) < autoWithdrawalLimit * 100) + if ((-amountCents) < autoWithdrawalLimit*100) { // Book against autoWithdrawal account. @@ -241,7 +220,7 @@ namespace Swarmops.Utility.Financial nominalTransaction[bankFees.Identity] = -row.FeeCents; nominalTransaction[donations.Identity] = -row.AmountCentsGross; } - else if (amountCents < autoDepositLimit * 100) + else if (amountCents < autoDepositLimit*100) { // Book against autoDeposit account. @@ -261,5 +240,29 @@ namespace Swarmops.Utility.Financial return result; } + protected class ImportResult + { + public double CurrentBalance; + public List Rows; + } + + protected class ImportStats + { + public int ImportedTransactionCount; + public int ModifiedTransactionCount; + public int ProcessedTransactionCount; + } + + protected class ImportedRow + { + public Int64 AmountCentsGross; + public Int64 AmountCentsNet; + public string Comment; + public double CurrentBalance; + public DateTime DateTime; + public Int64 FeeCents; + public string HashBase; + public string SuppliedTransactionId; + } } } \ No newline at end of file diff --git a/Utility/Financial/PaysonImporter.cs b/Utility/Financial/PaysonImporter.cs index 0fe52f72..233a4103 100644 --- a/Utility/Financial/PaysonImporter.cs +++ b/Utility/Financial/PaysonImporter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; using System.Web; @@ -16,13 +17,15 @@ namespace Swarmops.Utility.Financial { if (!data.StartsWith("\r\n\r\n\r\n