/// <summary>
        /// Gets called in regular intervals from a Timer in Class TTimedProcessing.
        /// </summary>
        /// <param name="ADBAccessObj">Instantiated DB Access object with opened DB connection.</param>
        /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param>
        public static void Process(TDataBase ADBAccessObj, bool ARunManually)
        {
            //At the moment this isn't ready for production use
            return;

#if TODO
            //TODO: create the gpg files from IntranetExport, with parameters for including finance or personnel

            string exportpath = TAppSettingsManager.GetValue("OpenPetra.PathExport");

            if (Directory.Exists(exportpath) == false)
            {
                TLogging.Log("Auto Export directory not found : " + exportpath);
                return;
            }

            //if there is a file there, send it
            bool foundfile = false;

            foreach (FileInfo fi in new DirectoryInfo(exportpath).GetFiles("*.gpg"))
            {
                foundfile = true;

                TLogging.Log("Emailing file: " + fi.FullName);
                //TODO: Get the name of the administrator from the system_defaults table
                bool result = new TSmtpSender().SendEmail("<*****@*****.**>",
                    "OpenPetra Server",
                    "<*****@*****.**>",
                    "Automatic Intranet Export",
                    "This is an automatic file upload from OpenPetra",
                    new string[] { fi.FullName });

                if (result)
                {
                    TLogging.Log("SMTP Server accepted file: " + fi.FullName);
                    fi.Delete();
                    //TODO: exception handler
                }
                else
                {
                    TLogging.Log("SMTP Server refused file: " + fi.FullName);
                }
            }

            if (!foundfile)
            {
                TLogging.Log("No file found to email");
            }
#endif
        }
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <returns>Status string that should be shown to the user</returns>
        public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
            TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32 SuccessfulCount = 0;
            String NoEmailAddr = "";
            String FailedAddresses = "";
            String SendReport = "";

            //
            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);

                    if (ReportStream.Position < 1000)
                    {
                        continue; // Don't send an empty report
                    }

                    ReportStream.Position = 0;

                    TUC_EmailPreferences.LoadEmailDefaults();
                    TSmtpSender EmailSender = new TSmtpSender(
                        TUserDefaults.GetStringDefault("SmtpHost"),
                        TUserDefaults.GetInt16Default("SmtpPort"),
                        TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                        TUserDefaults.GetStringDefault("SmtpUser"),
                        TUserDefaults.GetStringDefault("SmtpPassword"),
                        "");
                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo");

                    if (!EmailSender.FInitOk)
                    {
                        return String.Format(
                            Catalog.GetString(
                                "Failed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned : \"{0}\""),
                            EmailSender.FErrorStatus);
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        "*****@*****.**", //LinkedPartner["EmailAddress"]
                        ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport += String.Format(
                            Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."),
                            LinkedPartner["EmailAddress"],
                            EmailSender.FErrorStatus
                            );

                        FailedAddresses += ("\r\n    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n    " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount > 0)
            {
                SendReport +=
                    String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n";
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            FormUtils.WriteToStatusBar("");
            return SendReport;
        } // AutoEmailReports
Beispiel #3
0
        /// <summary>
        /// send report as email
        /// </summary>
        public Boolean SendEmail(string AEmailAddresses,
            bool AAttachExcelFile,
            bool AAttachCSVFile,
            bool AAttachPDF,
            bool AWrapColumn,
            out TVerificationResultCollection AVerification)
        {
            TSmtpSender EmailSender = new TSmtpSender();

            AVerification = new TVerificationResultCollection();

            if (!EmailSender.ValidateEmailConfiguration())
            {
                AVerification.Add(new TVerificationResult(
                        Catalog.GetString("Sending Email"),
                        Catalog.GetString("Missing configuration for sending emails. Please edit your server configuration file"),
                        CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION,
                        TResultSeverity.Resv_Critical,
                        new System.Guid()));
                return false;
            }

            List <string>FilesToAttach = new List <string>();

            if (AAttachExcelFile)
            {
                string ExcelFile = TFileHelper.GetTempFileName(
                    FParameterList.Get("currentReport").ToString(),
                    ".xlsx");

                if (ExportToExcelFile(ExcelFile))
                {
                    FilesToAttach.Add(ExcelFile);
                }
            }

            if (AAttachCSVFile)
            {
                string CSVFile = TFileHelper.GetTempFileName(
                    FParameterList.Get("currentReport").ToString(),
                    ".csv");

                if (ExportToCSVFile(CSVFile))
                {
                    FilesToAttach.Add(CSVFile);
                }
            }

            if (AAttachPDF)
            {
                string PDFFile = TFileHelper.GetTempFileName(
                    FParameterList.Get("currentReport").ToString(),
                    ".pdf");

                if (PrintToPDF(PDFFile, AWrapColumn))
                {
                    FilesToAttach.Add(PDFFile);
                }
            }

            if (FilesToAttach.Count == 0)
            {
                AVerification.Add(new TVerificationResult(
                        Catalog.GetString("Sending Email"),
                        Catalog.GetString("Missing any attachments, not sending the email"),
                        "Missing Attachments",
                        TResultSeverity.Resv_Critical,
                        new System.Guid()));
                return false;
            }

            // TODO use the email address of the user, from s_user
            if (EmailSender.SendEmail("<" + TAppSettingsManager.GetValue("Reports.Email.Sender") + ">",
                    "OpenPetra Reports",
                    AEmailAddresses,
                    FParameterList.Get("currentReport").ToString(),
                    Catalog.GetString("Please see attachment!"),
                    FilesToAttach.ToArray()))
            {
                foreach (string file in FilesToAttach)
                {
                    File.Delete(file);
                }

                return true;
            }

            AVerification.Add(new TVerificationResult(
                    Catalog.GetString("Sending Email"),
                    Catalog.GetString("Problem sending email"),
                    "server problems",
                    TResultSeverity.Resv_Critical,
                    new System.Guid()));

            return false;
        }
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <param name="ACalc"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ACostCentreFilter"></param>
        public void AutoEmailReports(TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32 SuccessfulCount = 0;
            String NoEmailAddr = "";
            String FailedAddresses = "";

            //
            // I need to find the email addresses for the linked partners I'm sending to.

            DataTable LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);

            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FPetraUtilsObject.WriteToStatusBar("Generate " + FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = FPetraUtilsObject.FFastReportsPlugin.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);
                    ReportStream.Position = 0;

                    TUC_EmailPreferences.LoadEmailDefaults();
                    TSmtpSender EmailSender;
                    try
                    {
                        EmailSender = new TSmtpSender(
                            TUserDefaults.GetStringDefault("SmtpHost"),
                            TUserDefaults.GetInt16Default("SmtpPort"),
                            TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                            TUserDefaults.GetStringDefault("SmtpUser"),
                            TUserDefaults.GetStringDefault("SmtpPassword"),
                            "");
                        EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                        EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo");
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(Catalog.GetString(
                                "Failed to set up the email server.\nPlease check the settings in Preferences / Email."),
                            Catalog.GetString("Auto-email to linked partners"));
                        return;
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        "*****@*****.**", //LinkedPartner["EmailAddress"]
                        FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        FailedAddresses += ("\r\n" + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n" + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            String SendReport = "";

            if (SuccessfulCount > 0)
            {
                SendReport += String.Format(Catalog.GetString("Reports emailed to {0} addresses."), SuccessfulCount) + "\r\n\r\n";
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("These Partners have no email addresses:") + NoEmailAddr + "\r\n\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            MessageBox.Show(SendReport, Catalog.GetString("Auto-email to linked partners"));
            FPetraUtilsObject.WriteToStatusBar("");
        } // AutoEmailReports
        }  // Load Hosa Report Data

        private Boolean LoadStewardshipReportData(TRptCalculator ACalc)
        {
            Dictionary <String, TVariant>paramsDictionary = InitialiseDictionary(ACalc);
            DataTable ReportTable = TRemote.MReporting.WebConnectors.GetReportDataTable("Stewardship", paramsDictionary);

            if (this.IsDisposed)
            {
                return false;
            }

            if (ReportTable == null)
            {
                FPetraUtilsObject.WriteToStatusBar("Report Cancelled.");
                return false;
            }

            MyFastReportsPlugin.RegisterData(ReportTable, "Stewardship");

            Boolean HasData = (ReportTable.Rows.Count > 0);

            if (!HasData)
            {
                FStatusMsg += Catalog.GetString("No Stewardship entries found for selected Run Number.");
            }

            TParameterList Params = ACalc.GetParameters();

            if ((!Params.Get("param_design_template").ToBool())
                && (rbtEmailStewardship.Checked))
            {
                TUC_EmailPreferences.LoadEmailDefaults();
                TSmtpSender EmailSender = new TSmtpSender(
                    TUserDefaults.GetStringDefault("SmtpHost"),
                    TUserDefaults.GetInt16Default("SmtpPort"),
                    TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                    TUserDefaults.GetStringDefault("SmtpUser"),
                    TUserDefaults.GetStringDefault("SmtpPassword"),
                    "");
                EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo");

                if (!EmailSender.FInitOk)
                {
                    FStatusMsg += String.Format(
                        Catalog.GetString(
                            "\r\nFailed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned: \"{0}\""),
                        EmailSender.FErrorStatus
                        );
                    return false;
                }

                String MyCostCentreCode = String.Format("{0:##00}00", FLedgerNumber);
                String PeriodEnd = Params.Get("param_end_date").ToDate().ToString("dd/MM/yyyy");
                Int32 RunNumber = Params.Get("param_cmbICHNumber").ToInt32();
                String CsvAttachment = String.Format("\"{0}\",{1},\"{2}\",{3},\"{4}\",{5}\n", // "OP:1",30/11/2014,\"0200\",09/12/2014,\"USD\",0"

                    "OP:1",                                     // software originator and version ID
                    PeriodEnd,
                    MyCostCentreCode,                           // Field Cost Centre Code
                    DateTime.Now.ToString("dd/MM/yyyy"),
                    FLedgerRow.BaseCurrency,                    // Stewardship Report CSV always in Base Currency
                    RunNumber                                   // Run number
                    );

                foreach (DataRow Row in ReportTable.Rows)
                {
                    CsvAttachment += String.Format("\"{0}\",{1},{2},{3}\n",
                        Row["CostCentreCode"].ToString(),
                        Convert.ToDecimal(Row["Income"]).ToString("0.00", CultureInfo.InvariantCulture),  // Stewardship Report CSV always in Base Currency
                        Convert.ToDecimal(Row["Expense"]).ToString("0.00", CultureInfo.InvariantCulture),
                        Convert.ToDecimal(Row["Xfer"]).ToString("0.00", CultureInfo.InvariantCulture)
                        );
                }

                String EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                EmailSender.AttachFromStream(new MemoryStream(Encoding.ASCII.GetBytes(CsvAttachment)), "Stewardship_" + MyCostCentreCode + ".csv");
                Boolean SentOk = EmailSender.SendEmail(
                    TUserDefaults.GetStringDefault("SmtpFromAccount"),
                    TUserDefaults.GetStringDefault("SmtpDisplayName"),
                    "*****@*****.**", //[email protected]
                    "Stewardship Report [" + MyCostCentreCode + "] Period end: " + PeriodEnd + " Run#: " + RunNumber,
                    EmailBody);

                if (SentOk)
                {
                    FStatusMsg += Catalog.GetString("\r\nStewardship report emailed to ICH.");
                }
                else
                {
                    FStatusMsg += Catalog.GetString("\r\nFailed to send Stewardship email to ICH.");
                }

                return false;
            }

            return HasData;
        } // Load Stewardship Report Data
        /// <summary>
        /// Gets called in regular intervals from a Timer in Class TTimedProcessing.
        /// </summary>
        /// <param name="ADBAccessObj">Already instatiated DB Access object with opened DB connection.</param>
        /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param>
        public static void Process(TDataBase ADBAccessObj, bool ARunManually)
        {
            TDBTransaction ReadWriteTransaction;
            bool NewTransaction;
            bool LastReminderDateAcquired;
            DateTime LastReminderDate;
            DataSet ReminderResultsDS;
            SSystemDefaultsRow SystemDefaultsDR;
            PPartnerReminderTable PartnerReminderDT;
            int ReminderFreqency;
            TDataBase DBAccessObj;

            if (TLogging.DebugLevel >= 6)
            {
                TLogging.Log("Entering TProcessPartnerReminders.Process...");
            }

            // TODO: it is quite ipossible at the moment to use ADBAccessObj instead of DBAccess.GDBAccessObj due to SubmitChanges etc
            //DBAccessObj = ADBAccessObj;
            DBAccessObj = DBAccess.GDBAccessObj;

            // SubmitChanges references a user
            TPetraIdentity PetraIdentity = new TPetraIdentity(
                "SYSADMIN", "", "", "", "", DateTime.MinValue,
                DateTime.MinValue, DateTime.MinValue, 0, -1, -1, false,
                false);

            UserInfo.GUserInfo = new TPetraPrincipal(PetraIdentity, null);

            ReadWriteTransaction = DBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                out NewTransaction);

            /*
             * This whole process must either succeed or fail, therefore the whole thing is in a try-catch.
             */
            try
            {
                /*
                 * Obtain date when PartnerReminders last ran. This is stored in a SystemDefault. If it doesn't exist already,
                 * a new SystemDefault with an ancient date is created for us.
                 */
                LastReminderDateAcquired = GetLastReminderDate(out LastReminderDate, out SystemDefaultsDR, ReadWriteTransaction);

                if (!LastReminderDateAcquired)
                {
                    TLogging.Log(
                        TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                        ": Could not send Partner Reminders because Petra couldn't create the required SystemDefault setting for the Last Reminder Date!");

                    DBAccessObj.RollbackTransaction();

                    return;
                }

                TSmtpSender Sender = new TSmtpSender();

                if (!Sender.FInitOk)
                {
                    TLogging.Log(
                        TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                        ": Could not send Partner Reminders because SMTP server didn't initialise.");

                    DBAccessObj.RollbackTransaction();
                    return;
                }

                // Retrieve all PartnerReminders we need to process.
                ReminderResultsDS = GetRemindersToProcess(LastReminderDate, out PartnerReminderDT,
                    DBAccessObj, ReadWriteTransaction);

                /*
                 * We now have a Typed DataTable with the PartnerReminders that we need to process.
                 * Iterate through the PartnerReminders, update data, and send an email for each PartnerReminder.
                 */
                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("_---------------------------------_");
                    TLogging.Log("PartnerReminders data before we start processing all PartnerReminders....");
                    TLogging.Log(ReminderResultsDS.GetXml().ToString());
                }

                foreach (PPartnerReminderRow PartnerReminderDR in PartnerReminderDT.Rows)
                {
                    if (TLogging.DebugLevel >= 4)
                    {
                        TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                                ": Processing Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey));
                    }

                    ReminderFreqency = (PartnerReminderDR.IsReminderFrequencyNull()) ? 0 : PartnerReminderDR.ReminderFrequency;

                    PartnerReminderDR.BeginEdit();
                    PartnerReminderDR.LastReminderSent = DateTime.Now.Date;
                    PartnerReminderDR.NextReminderDate = DateTime.Now.Date.AddDays(ReminderFreqency);

                    if (!PartnerReminderDR.IsEventDateNull())   // Reminder has an Event Date
                    {
                        if (PartnerReminderDR.NextReminderDate > PartnerReminderDR.EventDate)
                        {
                            if (TLogging.DebugLevel >= 5)
                            {
                                TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                                        ": Deactivating Reminder ID {0} for Partner {1} as its Event Date is in the past.",
                                        PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey));
                            }

                            PartnerReminderDR.ReminderActive = false;
                        }
                    }

                    if (TLogging.DebugLevel >= 4)
                    {
                        TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                                ": Sending email for Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey));
                    }

                    if (SendReminderEmail(PartnerReminderDR, ReadWriteTransaction, Sender))
                    {
                        // Accept the edit
                        if (TLogging.DebugLevel >= 4)
                        {
                            TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                                    ": Reminder ID {0} for Partner {1} accepted by SMTP server.", PartnerReminderDR.ReminderId,
                                    PartnerReminderDR.PartnerKey));
                        }

                        PartnerReminderDR.EndEdit();
                    }
                    else
                    {
                        // Cancel the edit
                        TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing +
                                ": Reminder ID {0} for Partner {1} REJECTED by SMTP server.", PartnerReminderDR.ReminderId,
                                PartnerReminderDR.PartnerKey));

                        PartnerReminderDR.CancelEdit();
                    }
                }

                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("_---------------------------------_");
                    TLogging.Log("PartnerReminders data after processing all PartnerReminders, before writing it to DB....");
                    TLogging.Log(PartnerReminderDT.DataSet.GetXml().ToString());
                }

                // Update all the changed PartnerReminder Rows
                PPartnerReminderAccess.SubmitChanges(PartnerReminderDT, ReadWriteTransaction);

                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("_---------------------------------_");
                }

                /*
                 * Update the SystemDefault that keeps track of when Partner Reminders last ran.
                 * (SystemDefaultsDR will point to the row we loaded earlier on, OR the row we added earlier on
                 * if there wasn't already a SystemDefault row.)
                 */
                UpdateLastReminderDate(SystemDefaultsDR, ReadWriteTransaction);

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }

                TLogging.LogAtLevel(1, TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " ran succesfully.");
            }
            catch (Exception Exc)
            {
                TLogging.Log(
                    TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " encountered an Exception:" + Environment.NewLine +
                    Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }
        }
        /// <summary>
        /// Sends a Reminder Email to a Partner.
        /// </summary>
        /// <param name="APartnerReminderDR">DataRow containing the Reminder data.</param>
        /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param>
        /// <param name="Sender">Already instantiated SMTP sender.</param>
        /// <returns>True if the sending of the Reminder Email succeeded, otherwise false.</returns>
        private static bool SendReminderEmail(PPartnerReminderRow APartnerReminderDR, TDBTransaction AReadWriteTransaction, TSmtpSender Sender)
        {
            string Subject = "";
            string Body = "";
            string Destination = APartnerReminderDR.EmailAddress;
            string PartnerShortName;
            char LF = Convert.ToChar(10);


            // Retrieve ShortName of the Partner to which the Reminder Email should be sent
            PartnerShortName = GetPartnerShortName(APartnerReminderDR.PartnerKey);

            // Format Email Recipient Address as per email RFC's
            if (!Destination.Trim().StartsWith("<"))
            {
                Destination = "<" + Destination;
            }

            if (!Destination.Trim().EndsWith(">"))
            {
                Destination = Destination + ">";
            }

            // Compose Email Subject
            Subject = String.Format("OpenPetra Reminder about {0}", PartnerShortName);

            /*
             * Compose Email Body
             */
            Body = string.Format("Partner: {0}   [{1:0000000000}]{2}", PartnerShortName, APartnerReminderDR.PartnerKey, LF);

            if (APartnerReminderDR.ContactId != 0)
            {
                Body += GetContactDetails(APartnerReminderDR.ContactId, AReadWriteTransaction);
            }

            Body += String.Format("Reason: {0}{1}", APartnerReminderDR.ReminderReason, LF);

            if (!APartnerReminderDR.IsEventDateNull())
            {
                Body += String.Format("Event Date: {0}{1}", StringHelper.DateToLocalizedString(APartnerReminderDR.EventDate), LF);
            }

            Body += String.Format("Comment: {0}{1}", APartnerReminderDR.Comment, LF);
            Body += String.Format("{0}Next Reminder: {1}{2}", LF, StringHelper.DateToLocalizedString(APartnerReminderDR.NextReminderDate), LF);

            if (APartnerReminderDR.ReminderActive == false)
            {
                Body += String.Format("This Reminder has now been disabled.{0}", LF);
            }

            // Send Email (this picks up the SMTPServer AppSetting from the Server Config File)
            return Sender.SendEmail(Destination, "OpenPetra Server", Destination, Subject, Body);
        }
        /// <summary>
        /// Performs the ICH code to generate Stewardship Calculation.
        ///  Relates to gi3100.p
        /// </summary>
        /// <param name="ALedgerNumber">ICH Ledger number</param>
        /// <param name="APeriodNumber">Period</param>
        /// <param name="AICHNumber">ICH Processing Number</param>
        /// <param name="ACurrencyType">Currency type: 1 = base, 2 = intl</param>
        /// <param name="AFileName">File name to process</param>
        /// <param name="AEmail">If true then send email</param>
        /// <param name="AVerificationResult">Error messaging</param>
        public static void GenerateStewardshipFile(int ALedgerNumber,
            int APeriodNumber,
            int AICHNumber,
            int ACurrencyType,
            string AFileName,
            bool AEmail,
            out TVerificationResultCollection AVerificationResult
            )
        {
            string CostCentre;
            decimal IncomeAmount = 0;
            decimal ExpenseAmount = 0;
            decimal XferAmount = 0;
            string Currency;

            string LedgerName;

            AVerificationResult = new TVerificationResultCollection();

            //Begin the transaction
            TDBTransaction DBTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                //Find the LedgerRow
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, DBTransaction);
                ALedgerRow LedgerRow = (ALedgerRow)LedgerTable.Rows[0];

                //Find the Partner Short Name
                PPartnerTable PartnerTable = PPartnerAccess.LoadByPrimaryKey(LedgerRow.PartnerKey, DBTransaction);
                PPartnerRow PartnerRow = (PPartnerRow)PartnerTable.Rows[0];

                LedgerName = PartnerRow.PartnerShortName;

                //Specify currency type
                if (ACurrencyType == MFinanceConstants.CURRENCY_BASE_NUM)
                {
                    Currency = LedgerRow.BaseCurrency;
                }
                else
                {
                    Currency = LedgerRow.IntlCurrency;
                }

                //Create table for conversion to XML and export to CSV
                AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber, APeriodNumber, DBTransaction);
                AAccountingPeriodRow AccountingPeriodRow = (AAccountingPeriodRow)AccountingPeriodTable.Rows[0];

                DateTime PeriodEndDate = AccountingPeriodRow.PeriodEndDate;
                string StandardCostCentre = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
                DateTime DateToday = DateTime.Today;

                //First four fields are constant for each row
                DataTable TableForExport = new DataTable();

                TableForExport.Columns.Add("PeriodEndDate", typeof(DateTime));
                TableForExport.Columns.Add("StandardCostCentre", typeof(string));
                TableForExport.Columns.Add("DateToday", typeof(DateTime));
                TableForExport.Columns.Add("Currency", typeof(string));
                TableForExport.Columns.Add("CostCentre", typeof(string));
                TableForExport.Columns.Add("Income", typeof(decimal));
                TableForExport.Columns.Add("Expense", typeof(decimal));
                TableForExport.Columns.Add("DirectTransfer", typeof(decimal));

                CostCentre = string.Empty;

                AIchStewardshipTable IchStewTable = new AIchStewardshipTable();
                AIchStewardshipRow TemplateRow = (AIchStewardshipRow)IchStewTable.NewRowTyped(false);

                TemplateRow.LedgerNumber = ALedgerNumber;
                TemplateRow.PeriodNumber = APeriodNumber;

                StringCollection operators = StringHelper.InitStrArr(new string[] { "=", "=" });

                AIchStewardshipTable IchStewardshipTable = AIchStewardshipAccess.LoadUsingTemplate(TemplateRow, operators, null, DBTransaction);
                AIchStewardshipRow IchStewardshipRow = null;

                for (int i = 0; i < IchStewardshipTable.Count; i++)
                {
                    IchStewardshipRow = (AIchStewardshipRow)IchStewardshipTable.Rows[i];

                    if ((AICHNumber == 0)
                        || (IchStewardshipRow.IchNumber == AICHNumber))
                    {
                        if ((CostCentre != string.Empty)
                            && (CostCentre != IchStewardshipRow.CostCentreCode))
                        {
                            if ((IncomeAmount != 0) || (ExpenseAmount != 0) || (XferAmount != 0))
                            {
                                DataRow DR = (DataRow)TableForExport.NewRow();

                                DR[0] = PeriodEndDate;
                                DR[1] = StandardCostCentre;
                                DR[2] = DateToday;
                                DR[3] = Currency;
                                DR[4] = CostCentre;
                                DR[5] = IncomeAmount;
                                DR[6] = ExpenseAmount;
                                DR[7] = XferAmount;

                                TableForExport.Rows.Add(DR);
                                TableForExport.AcceptChanges();
                            }

                            IncomeAmount = 0;
                            ExpenseAmount = 0;
                            XferAmount = 0;
                        }

                        if (ACurrencyType == MFinanceConstants.CURRENCY_BASE_NUM)
                        {
                            IncomeAmount += IchStewardshipRow.IncomeAmount;
                            ExpenseAmount += IchStewardshipRow.ExpenseAmount;
                            XferAmount += IchStewardshipRow.DirectXferAmount;
                        }
                        else
                        {
                            IncomeAmount += IchStewardshipRow.IncomeAmountIntl;
                            ExpenseAmount += IchStewardshipRow.ExpenseAmountIntl;
                            XferAmount += IchStewardshipRow.DirectXferAmountIntl;
                        }

                        CostCentre = IchStewardshipRow.CostCentreCode;
                    }
                }

                if ((CostCentre != string.Empty) && ((IncomeAmount != 0) || (ExpenseAmount != 0) || (XferAmount != 0)))
                {
                    DataRow DR = (DataRow)TableForExport.NewRow();

                    DR[0] = PeriodEndDate;
                    DR[1] = StandardCostCentre;
                    DR[2] = DateToday;
                    DR[3] = Currency;
                    DR[4] = CostCentre;
                    DR[5] = IncomeAmount;
                    DR[6] = ExpenseAmount;
                    DR[7] = XferAmount;

                    TableForExport.Rows.Add(DR);
                    TableForExport.AcceptChanges();
                }

                //Create the XMLDoc ready for export to CSV
                XmlDocument doc = TDataBase.DataTableToXml(TableForExport);

                TCsv2Xml.Xml2Csv(doc, AFileName);

                if (AEmail)
                {
                    string SenderAddress = TAppSettingsManager.GetValue("LocalFieldFinance.EmailAddress");
                    string EmailSubject = string.Format(Catalog.GetString("Stewardship File from {0}"), LedgerName);
                    string HTMLText = string.Empty;

                    string EmailAddress = GetICHEmailAddress(DBTransaction);

                    if (EmailAddress.Length == 0)
                    {
                        throw new Exception("No destination email addresses found!");
                    }

                    if (!File.Exists(AFileName))
                    {
                        HTMLText = "<html><body>" + String.Format(Catalog.GetString("Cannot find file {0}"), AFileName) + "</body></html>";
                    }
                    else
                    {
                        HTMLText = "<html><body>" + EmailSubject + ": " + Path.GetFileName(AFileName) + Catalog.GetString(" is attached.") +
                                   "</body></html>";
                    }

                    TSmtpSender SendMail = new TSmtpSender();

                    MailMessage msg = new MailMessage(SenderAddress,
                        EmailAddress,
                        EmailSubject,
                        HTMLText);

                    msg.Attachments.Add(new Attachment(AFileName));
                    //msg.Bcc.Add(BCCAddress);

                    SendMail.SendMessage(msg);
                }
            }
            catch (Exception Exp)
            {
                TLogging.Log(Exp.Message);
                TLogging.Log(Exp.StackTrace);

                throw;
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
        }