/// <summary>
        /// Generate PDF document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BtnPDF_Click(object sender, EventArgs e)
        {
            string PDFPath = TFormLettersTools.GeneratePDFFromHTML(FHtmlDoc,
                                                                   TAppSettingsManager.GetValue("Server.PathData") + Path.DirectorySeparatorChar +
                                                                   "reports");

            lblLoadStatus.Text = Catalog.GetString("Generated PDF Document: ") + PDFPath;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="APaymentNum"></param>
        /// <param name="ALedgerNumber"></param>
        public void PrintRemittanceAdvice(Int32 APaymentNum, Int32 ALedgerNumber)
        {
            FLedgerNumber = ALedgerNumber;

            txtPaymentNum.NumberValueInt = APaymentNum;
            AccountsPayableTDS PaymentDetails = TRemote.MFinance.AP.WebConnectors.LoadAPPayment(ALedgerNumber, APaymentNum);

            if (PaymentDetails.AApPayment.Rows.Count == 0) // unable to load this payment..
            {
                lblLoadStatus.Text = String.Format(Catalog.GetString("Error - can't load Payment number {0}."), APaymentNum);
                return;
            }

            SortedList <string, List <string> > FormValues = new SortedList <string, List <string> >();

            //
            // load my own country code, so I don't print it on letters to my own country.
            //
            string LocalCountryCode = TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetCountryCodeFromSiteLedger();

            //
            // These are the fields that I will pull out of the TDS...
            //
            FormValues.Add("SupplierName", new List <string>());
            FormValues.Add("SupplierAddress", new List <string>());
            FormValues.Add("PaymentDate", new List <string>());
            FormValues.Add("OurReference", new List <string>());
            FormValues.Add("InvoiceDate", new List <string>());
            FormValues.Add("InvoiceNumber", new List <string>());
            FormValues.Add("InvoiceAmount", new List <string>());
            FormValues.Add("TotalPayment", new List <string>());

            FormValues["SupplierName"].Add(PaymentDetails.PPartner[0].PartnerShortName);

            if (PaymentDetails.PLocation[0].CountryCode == LocalCountryCode)
            {
                PaymentDetails.PLocation[0].CountryCode = ""; // Don't print country code it it's the same as my own.
            }

            FormValues["SupplierAddress"].Add(Calculations.DetermineLocationString(PaymentDetails.PLocation[0],
                                                                                   Calculations.TPartnerLocationFormatEnum.plfHtmlLineBreak));

            String DatePattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;

            DatePattern = "dd MMMM yyyy"; // The long pattern above is no good in UK, although it might be OK in other cultures...

            FormValues["PaymentDate"].Add(PaymentDetails.AApPayment[0].PaymentDate.Value.ToString(DatePattern));
            FormValues["OurReference"].Add(PaymentDetails.AApSupplier[0].OurReference);

            foreach (AApDocumentRow Row in PaymentDetails.AApDocument.Rows)
            {
                FormValues["InvoiceDate"].Add(Row.DateIssued.ToString(DatePattern));
                FormValues["InvoiceNumber"].Add(Row.DocumentCode);
                FormValues["InvoiceAmount"].Add(Row.TotalAmount.ToString("n2") + " " + PaymentDetails.AApSupplier[0].CurrencyCode);
            }

            FormValues["TotalPayment"].Add(PaymentDetails.AApPayment[0].Amount.ToString("n2") + " " + PaymentDetails.AApSupplier[0].CurrencyCode);

            String TemplateFilename = TAppSettingsManager.GetValue("Formletters.Path") + "\\ApRemittanceAdvice.html";

            if (!File.Exists(TemplateFilename))
            {
                lblLoadStatus.Text = String.Format(Catalog.GetString("Error - unable to load HTML template from {0}"), TemplateFilename);
                return;
            }

            FHtmlDoc = TFormLettersTools.PrintSimpleHTMLLetter(TemplateFilename, FormValues);

            System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
            bool printerInstalled = printDocument.PrinterSettings.IsValid;

            if (!printerInstalled)
            {
                lblLoadStatus.Text = Catalog.GetString("There is no printer, so printing is not possible");
                return;
            }

            FGfxPrinter = new TGfxPrinter(printDocument, TGfxPrinter.ePrinterBehaviour.eFormLetter);
            try
            {
                TPrinterHtml htmlPrinter = new TPrinterHtml(FHtmlDoc,
                                                            TAppSettingsManager.GetValue("Formletters.Path"),
                                                            FGfxPrinter);
                FGfxPrinter.Init(eOrientation.ePortrait, htmlPrinter, eMarginType.ePrintableArea);
                this.ppvLetters.InvalidatePreview();
                this.ppvLetters.Document = FGfxPrinter.Document;
                this.ppvLetters.Zoom     = 1;
                // GfxPrinter.Document.EndPrint += new PrintEventHandler(this.EndPrint);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            btnPDF.Visible  = true;
            btnCopy.Visible = true;

            lblLoadStatus.Text = "";
        }
        /// <summary>
        /// Print a receipt for each gift (one page for each donor) in the batch
        /// </summary>
        /// <param name="AGiftTDS"></param>
        public void PrintGiftBatchReceipts(GiftBatchTDS AGiftTDS)
        {
            AGiftBatchRow GiftBatchRow = AGiftTDS.AGiftBatch[0];

            DataView GiftView = new DataView(AGiftTDS.AGift);

            //AGiftTDS.AGift.DefaultView.RowFilter
            GiftView.RowFilter = String.Format("{0}={1} and {2}={3}",
                                               AGiftTable.GetLedgerNumberDBName(), GiftBatchRow.LedgerNumber,
                                               AGiftTable.GetBatchNumberDBName(), GiftBatchRow.BatchNumber);
            String       ReceiptedDonorsList             = "";
            List <Int32> ReceiptedGiftTransactions       = new List <Int32>();
            SortedList <Int64, AGiftTable> GiftsPerDonor = new SortedList <Int64, AGiftTable>();

            foreach (DataRowView rv in GiftView)
            {
                AGiftRow GiftRow = (AGiftRow)rv.Row;
                bool     ReceiptEachGift;
                String   ReceiptLetterFrequency;
                bool     EmailGiftStatement;
                bool     AnonymousDonor;

                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerReceiptingInfo(
                    GiftRow.DonorKey,
                    out ReceiptEachGift,
                    out ReceiptLetterFrequency,
                    out EmailGiftStatement,
                    out AnonymousDonor);

                if (ReceiptEachGift)
                {
                    // I want to print a receipt for this gift,
                    // but if there's already one queued for this donor,
                    // I'll add this gift onto the existing receipt.

                    if (!GiftsPerDonor.ContainsKey(GiftRow.DonorKey))
                    {
                        GiftsPerDonor.Add(GiftRow.DonorKey, new AGiftTable());
                    }

                    AGiftRow NewRow = GiftsPerDonor[GiftRow.DonorKey].NewRowTyped();
                    DataUtilities.CopyAllColumnValues(GiftRow, NewRow);
                    GiftsPerDonor[GiftRow.DonorKey].Rows.Add(NewRow);
                } // if receipt required
            }     // foreach gift

            String HtmlDoc = "";

            OpenFileDialog DialogOpen = new OpenFileDialog();

            if (Directory.Exists(TAppSettingsManager.GetValue("Formletters.Path")))
            {
                DialogOpen.InitialDirectory = TAppSettingsManager.GetValue("Formletters.Path");
            }

            DialogOpen.Filter           = Catalog.GetString("HTML file (*.html)|*.html;*.htm");
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title            = Catalog.GetString("Select the template for the gift receipt");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string HTMLTemplateFilename = DialogOpen.FileName;

            foreach (Int64 DonorKey in GiftsPerDonor.Keys)
            {
                String        DonorShortName;
                TPartnerClass DonorClass;
                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(DonorKey, out DonorShortName, out DonorClass);
                DonorShortName = Calculations.FormatShortName(DonorShortName, eShortNameFormat.eReverseShortname);

                string HtmlPage = TRemote.MFinance.Gift.WebConnectors.PrintGiftReceipt(
                    GiftBatchRow.CurrencyCode,
                    DonorShortName,
                    DonorKey,
                    DonorClass,
                    GiftsPerDonor[DonorKey],
                    HTMLTemplateFilename
                    );

                TFormLettersTools.AttachNextPage(ref HtmlDoc, HtmlPage);
                ReceiptedDonorsList += (DonorShortName + "\r\n");

                foreach (AGiftRow GiftRow in GiftsPerDonor[DonorKey].Rows)
                {
                    ReceiptedGiftTransactions.Add(GiftRow.GiftTransactionNumber);
                }
            }

            TFormLettersTools.CloseDocument(ref HtmlDoc);

            if (ReceiptedGiftTransactions.Count > 0)
            {
                TFrmReceiptControl.PreviewOrPrint(HtmlDoc);

                if (MessageBox.Show(
                        Catalog.GetString(
                            "Press OK if receipts to these recipients were printed correctly.\r\nThe gifts will be marked as receipted.\r\n") +
                        ReceiptedDonorsList,

                        Catalog.GetString("Receipt Printing"),
                        MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    foreach (Int32 Trans in ReceiptedGiftTransactions)
                    {
                        TRemote.MFinance.Gift.WebConnectors.MarkReceiptsPrinted(
                            GiftBatchRow.LedgerNumber,
                            GiftBatchRow.BatchNumber,
                            Trans);
                    }
                }
            }
        }
Exemple #4
0
        public static string PrintReceipts(int ALedgerNumber, DataTable AGiftTbl, string AHTMLTemplateFilename)
        {
            string         HtmlDoc     = "";
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            SortedList <Int64, AGiftTable>    GiftsPerDonor = new SortedList <Int64, AGiftTable>();
            SortedList <Int64, TempDonorInfo> DonorInfo     = new SortedList <Int64, TempDonorInfo>();

            try
            {
                string LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);

                foreach (DataRow Row in AGiftTbl.Rows)
                {
                    String SqlQuery = "SELECT DISTINCT " +
                                      "a_date_entered_d AS DateEntered," +
                                      "p_partner_short_name_c AS Donor," +
                                      "p_donor_key_n AS DonorKey," +
                                      "p_partner_class_c AS DonorClass," +
                                      "a_reference_c AS Reference, " +
                                      "a_currency_code_c AS GiftCurrency " +
                                      "FROM PUB_a_gift LEFT JOIN PUB_p_partner on PUB_a_gift.p_donor_key_n = PUB_p_partner.p_partner_key_n " +
                                      "LEFT JOIN PUB_a_gift_batch ON PUB_a_gift.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i AND PUB_a_gift.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i "
                                      +
                                      "WHERE PUB_a_gift.a_ledger_number_i=" + ALedgerNumber +
                                      " AND PUB_a_gift.a_batch_number_i=" + Row["BatchNumber"] +
                                      " AND PUB_a_gift.a_gift_transaction_number_i=" + Row["TransactionNumber"];

                    DataRow TempRow = DBAccess.GDBAccessObj.SelectDT(SqlQuery, "UnreceiptedGiftsTbl", Transaction).Rows[0];

                    Int64 DonorKey = Convert.ToInt64(TempRow["DonorKey"]);
                    //
                    // I need to merge any rows that have the same donor.
                    //

                    if (!GiftsPerDonor.ContainsKey(DonorKey))
                    {
                        GiftsPerDonor.Add(DonorKey, new AGiftTable());
                        DonorInfo.Add(DonorKey, new TempDonorInfo());
                    }

                    TempDonorInfo DonorRow = DonorInfo[DonorKey];
                    DonorRow.DonorShortName = TempRow["Donor"].ToString();
                    DonorRow.DonorClass     = SharedTypes.PartnerClassStringToEnum(TempRow["DonorClass"].ToString());
                    DonorRow.GiftCurrency   = TempRow["GiftCurrency"].ToString();
                    DonorRow.DateEntered    = Convert.ToDateTime(TempRow["DateEntered"]);

                    AGiftRow GiftRow = GiftsPerDonor[DonorKey].NewRowTyped();
                    GiftRow.LedgerNumber          = ALedgerNumber;
                    GiftRow.BatchNumber           = Convert.ToInt32(Row["BatchNumber"]);
                    GiftRow.GiftTransactionNumber = Convert.ToInt32(Row["TransactionNumber"]);
                    GiftRow.Reference             = TempRow["Reference"].ToString();
                    GiftRow.DateEntered           = Convert.ToDateTime(TempRow["DateEntered"]);
                    GiftsPerDonor[DonorKey].Rows.Add(GiftRow);
                } // foreach Row

                foreach (Int64 DonorKey in GiftsPerDonor.Keys)
                {
                    TempDonorInfo DonorRow = DonorInfo[DonorKey];
                    string        PageHtml = FormatHtmlReceipt(
                        DonorRow.DonorShortName,
                        DonorKey,
                        DonorRow.DonorClass,
                        DonorRow.GiftCurrency,
                        LocalCountryCode,
                        GiftsPerDonor[DonorKey],
                        AHTMLTemplateFilename,
                        Transaction);

                    TFormLettersTools.AttachNextPage(ref HtmlDoc, PageHtml);
                } // foreach DonorKey

                TFormLettersTools.CloseDocument(ref HtmlDoc);
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            return(HtmlDoc);
        }
Exemple #5
0
        public static string CreateAnnualGiftReceipts(Int32 ALedgerNumber,
                                                      DateTime AStartDate,
                                                      DateTime AEndDate,
                                                      string AHTMLTemplate,
                                                      bool ADeceasedFirst = false,
                                                      string AExtract     = null,
                                                      Int64 ADonorKey     = 0)
        {
            TLanguageCulture.LoadLanguageAndCulture();

            // get BaseCurrency
            System.Type  typeofTable    = null;
            TCacheable   CachePopulator = new TCacheable();
            ALedgerTable LedgerTable    = (ALedgerTable)CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.LedgerDetails,
                                                                                         "",
                                                                                         false,
                                                                                         ALedgerNumber,
                                                                                         out typeofTable);
            string BaseCurrency = LedgerTable[0].BaseCurrency;

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            try
            {
                // get the local country code
                string    LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);
                DataTable donorkeys        = new DataTable();
                string    SqlStmt          = "";

                if (ADonorKey != 0)
                {
                    TPartnerClass Class;
                    string        ShortName;
                    TPartnerServerLookups.GetPartnerShortName(ADonorKey, out ShortName, out Class);

                    donorkeys.Columns.Add(new DataColumn("DonorKey"));
                    donorkeys.Columns.Add(new DataColumn("DonorName"));
                    DataRow SingleRow = donorkeys.NewRow();
                    SingleRow[0] = ADonorKey;
                    SingleRow[1] = ShortName;

                    donorkeys.Rows.Add(SingleRow);
                }
                else
                {
                    SortedList <string, string> Defines = new SortedList <string, string>();

                    if (!string.IsNullOrEmpty(AExtract))
                    {
                        Defines.Add("BYEXTRACT", string.Empty);
                    }

                    // first get all donors in the given date range
                    SqlStmt = TDataBase.ReadSqlFile("Gift.ReceiptPrinting.GetDonors.sql", Defines);

                    OdbcParameter[] parameters = new OdbcParameter[4];
                    parameters[0]       = new OdbcParameter("LedgerNumber", OdbcType.Int);
                    parameters[0].Value = ALedgerNumber;
                    parameters[1]       = new OdbcParameter("StartDate", OdbcType.Date);
                    parameters[1].Value = AStartDate;
                    parameters[2]       = new OdbcParameter("EndDate", OdbcType.Date);
                    parameters[2].Value = AEndDate;
                    parameters[3]       = new OdbcParameter("Extract", OdbcType.VarChar);
                    parameters[3].Value = AExtract;

                    donorkeys = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "DonorKeys", Transaction, parameters);

                    // put deceased partner's at the front (still sorted alphabetically)
                    if (ADeceasedFirst)
                    {
                        // create a new datatable with same structure as donorkeys
                        DataTable temp = donorkeys.Clone();
                        temp.Clear();

                        // add deceased donors to the temp table and delete from donorkeys
                        for (int i = 0; i < donorkeys.Rows.Count; i++)
                        {
                            if (SharedTypes.StdPartnerStatusCodeStringToEnum(donorkeys.Rows[i][2].ToString()) == TStdPartnerStatusCode.spscDIED)
                            {
                                temp.Rows.Add((object[])donorkeys.Rows[i].ItemArray.Clone());
                                donorkeys.Rows[i].Delete();
                            }
                        }

                        // add remaining partners to temp table
                        donorkeys.AcceptChanges();
                        temp.Merge(donorkeys);

                        donorkeys = temp;
                    }
                }

                string ResultDocument = "";
                SqlStmt = TDataBase.ReadSqlFile("Gift.ReceiptPrinting.GetDonationsOfDonor.sql");

                foreach (DataRow donorrow in donorkeys.Rows)
                {
                    Int64  donorKey  = Convert.ToInt64(donorrow[0]);
                    string donorName = donorrow[1].ToString();

                    OdbcParameter[] parameters = new OdbcParameter[4];
                    parameters[0]       = new OdbcParameter("LedgerNumber", OdbcType.Int);
                    parameters[0].Value = ALedgerNumber;
                    parameters[1]       = new OdbcParameter("StartDate", OdbcType.Date);
                    parameters[1].Value = AStartDate;
                    parameters[2]       = new OdbcParameter("EndDate", OdbcType.Date);
                    parameters[2].Value = AEndDate;
                    parameters[3]       = new OdbcParameter("DonorKey", OdbcType.BigInt);
                    parameters[3].Value = donorKey;

                    // TODO: should we print each gift detail, or just one row per gift?
                    DataTable donations = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "Donations", Transaction, parameters);

                    if (donations.Rows.Count > 0)
                    {
                        string letter = FormatLetter(donorKey, donorName, donations, BaseCurrency, AHTMLTemplate, LocalCountryCode, Transaction);

                        if (TFormLettersTools.AttachNextPage(ref ResultDocument, letter))
                        {
                            // TODO: store somewhere that the receipt has been printed?
                            // TODO also store each receipt with the donor in document management, and in contact management?
                        }
                    }
                }

                TFormLettersTools.CloseDocument(ref ResultDocument);

                return(ResultDocument);
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
        }
Exemple #6
0
        public static string FormatHtmlReceipt(
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            String AGiftCurrency,
            string ALocalCountryCode,
            AGiftTable AGiftsThisDonor,
            string AHTMLTemplateFilename,
            TDBTransaction ATransaction)
        {
            SortedList <string, List <string> > FormValues = new SortedList <string, List <string> >();

            // These are the fields that can be printed in the letter:
            FormValues.Add("AdresseeShortName", new List <string>());
            FormValues.Add("AdresseeTitle", new List <string>());
            FormValues.Add("AdresseeFirstName", new List <string>());
            FormValues.Add("AdresseeFamilyName", new List <string>());
            FormValues.Add("AdresseeStreetAddress", new List <string>());
            FormValues.Add("AdresseeAddress3", new List <string>());
            FormValues.Add("AdresseeCity", new List <string>());
            FormValues.Add("AdresseePostCode", new List <string>());
            FormValues.Add("AdresseeCountry", new List <string>());
            FormValues.Add("FormattedAddress", new List <string>());

            FormValues.Add("DateToday", new List <string>());

            FormValues.Add("DateEntered", new List <string>());
            FormValues.Add("GiftAmount", new List <string>());
            FormValues.Add("GiftCurrency", new List <string>());
            FormValues.Add("GiftTxd", new List <string>());
            FormValues.Add("RecipientShortName", new List <string>());
            FormValues.Add("MotivationDetail", new List <string>());
            FormValues.Add("Reference", new List <string>());
            FormValues.Add("DonorComment", new List <string>());

            FormValues.Add("GiftTotalAmount", new List <string>());
            FormValues.Add("GiftTotalCurrency", new List <string>());
            FormValues.Add("TxdTotal", new List <string>());
            FormValues.Add("NonTxdTotal", new List <string>());


            // Donor Name:
            FormValues["AdresseeShortName"].Add(ADonorShortName);

            if (ADonorClass == TPartnerClass.PERSON)
            {
                PPersonTable Tbl = PPersonAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else if (ADonorClass == TPartnerClass.FAMILY)
            {
                PFamilyTable Tbl = PFamilyAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else
            {
                FormValues["AdresseeFamilyName"].Add(ADonorShortName);
            }

            FormValues["DateToday"].Add(DateTime.Now.ToString("dd MMMM yyyy"));

            // Donor Adress:
            PLocationTable        Location;
            PPartnerLocationTable PartnerLocation;
            string CountryName;
            string EmailAddress;

            if (TAddressTools.GetBestAddress(ADonorKey, out Location, out PartnerLocation, out CountryName, out EmailAddress, ATransaction))
            {
                PLocationRow LocRow = Location[0];
                FormValues["AdresseeStreetAddress"].Add(LocRow.StreetName);
                FormValues["AdresseeAddress3"].Add(LocRow.Address3);
                FormValues["AdresseeCity"].Add(LocRow.City);
                FormValues["AdresseePostCode"].Add(LocRow.PostalCode);

                if (LocRow.CountryCode != ALocalCountryCode)  // Don't add the Donor's country if it's also my country:
                {
                    FormValues["AdresseeCountry"].Add(CountryName);
                }
                else
                {
                    LocRow.CountryCode = "";
                }

                FormValues["FormattedAddress"].Add(Calculations.DetermineLocationString(LocRow,
                                                                                        Calculations.TPartnerLocationFormatEnum.plfHtmlLineBreak));
            }

            decimal GiftTotal   = 0;
            decimal TxdTotal    = 0;
            decimal NonTxdTotal = 0;

            // Details per gift:
            foreach (AGiftRow GiftRow in AGiftsThisDonor.Rows)
            {
                String           DateEntered   = GiftRow.DateEntered.ToString("dd MMM yyyy");
                String           GiftReference = GiftRow.Reference;
                AGiftDetailTable DetailTbl     = AGiftDetailAccess.LoadViaAGift(
                    GiftRow.LedgerNumber, GiftRow.BatchNumber, GiftRow.GiftTransactionNumber, ATransaction);

                foreach (AGiftDetailRow DetailRow in DetailTbl.Rows)
                {
                    FormValues["Reference"].Add(GiftReference);
                    FormValues["DateEntered"].Add(DateEntered);
                    GiftReference = "";                         // Date and Reference are one-per-gift, not per detail
                    DateEntered   = "";                         // so if this gift has several details, I'll blank the subsequent lines.

                    string DonorComment = "";
                    FormValues["GiftAmount"].Add(StringHelper.FormatUsingCurrencyCode(DetailRow.GiftTransactionAmount, AGiftCurrency));
                    FormValues["GiftCurrency"].Add(AGiftCurrency);
                    FormValues["MotivationDetail"].Add(DetailRow.MotivationDetailCode);
                    GiftTotal += DetailRow.GiftTransactionAmount;

                    if (DetailRow.TaxDeductible)
                    {
                        FormValues["GiftTxd"].Add("Y");
                        TxdTotal += DetailRow.GiftTransactionAmount;
                    }
                    else
                    {
                        FormValues["GiftTxd"].Add(" ");
                        NonTxdTotal += DetailRow.GiftTransactionAmount;
                    }

                    // Recipient Short Name:
                    PPartnerTable RecipientTbl = PPartnerAccess.LoadByPrimaryKey(DetailRow.RecipientKey, ATransaction);

                    if (RecipientTbl.Rows.Count > 0)
                    {
                        String ShortName = Calculations.FormatShortName(RecipientTbl[0].PartnerShortName, eShortNameFormat.eReverseShortname);
                        FormValues["RecipientShortName"].Add(ShortName);
                    }

                    if (DetailRow.CommentOneType == "Donor")
                    {
                        DonorComment += DetailRow.GiftCommentOne;
                    }

                    if (DetailRow.CommentTwoType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentTwo;
                    }

                    if (DetailRow.CommentThreeType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentThree;
                    }

                    if (DonorComment != "")
                    {
                        DonorComment = "Comment: " + DonorComment;
                    }

                    FormValues["DonorComment"].Add(DonorComment);
                } // foreach GiftDetail
            }     // foreach Gift

            FormValues["GiftTotalAmount"].Add(StringHelper.FormatUsingCurrencyCode(GiftTotal, AGiftCurrency));
            FormValues["GiftTotalCurrency"].Add(AGiftCurrency);
            FormValues["TxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(TxdTotal, AGiftCurrency));
            FormValues["NonTxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(NonTxdTotal, AGiftCurrency));

            return(TFormLettersTools.PrintSimpleHTMLLetter(AHTMLTemplateFilename, FormValues));
        }
        /// send an email to the applicant and the registration office
        public static bool SendEmail(Int64 APartnerKey, string ACountryCode, TApplicationFormData AData, string APDFFilename)
        {
            string FileName = TFormLettersTools.GetRoleSpecificFile(TAppSettingsManager.GetValue("Formletters.Path"),
                                                                    "ApplicationReceivedEmail",
                                                                    AData.registrationcountrycode,
                                                                    AData.formsid,
                                                                    "html");

            string HTMLText      = string.Empty;
            string SenderAddress = string.Empty;
            string BCCAddress    = string.Empty;
            string EmailSubject  = string.Empty;

            if (!File.Exists(FileName))
            {
                HTMLText = "<html><body>" + String.Format("Cannot find file {0}", FileName) + "</body></html>";
            }
            else
            {
                StreamReader r = new StreamReader(FileName);
                SenderAddress = r.ReadLine();
                BCCAddress    = r.ReadLine();
                EmailSubject  = r.ReadLine();
                HTMLText      = r.ReadToEnd();
                r.Close();
            }

            if (!SenderAddress.StartsWith("From: "))
            {
                throw new Exception("missing From: line in the Email template " + FileName);
            }

            if (!BCCAddress.StartsWith("BCC: "))
            {
                throw new Exception("missing BCC: line in the Email template " + FileName);
            }

            if (!EmailSubject.StartsWith("Subject: "))
            {
                throw new Exception("missing Subject: line in the Email template " + FileName);
            }

            SenderAddress = SenderAddress.Substring("From: ".Length);
            BCCAddress    = BCCAddress.Substring("BCC: ".Length);
            EmailSubject  = EmailSubject.Substring("Subject: ".Length);

            HTMLText = TJsonTools.ReplaceKeywordsWithData(AData.RawData, HTMLText);
            HTMLText = HTMLText.Replace("#HTMLRAWDATA", TJsonTools.DataToHTMLTable(AData.RawData));

            // load the language file for the specific country
            Catalog.Init(ACountryCode, ACountryCode);

            // send email
            TSmtpSender emailSender = new TSmtpSender();

            MailMessage msg = new MailMessage(SenderAddress,
                                              AData.email,
                                              EmailSubject,
                                              HTMLText);

            msg.Attachments.Add(new Attachment(APDFFilename, System.Net.Mime.MediaTypeNames.Application.Octet));
            msg.Bcc.Add(BCCAddress);

            if (!emailSender.SendMessage(msg))
            {
                TLogging.Log("There has been a problem sending the email to " + AData.email);
                return(false);
            }

            return(true);
        }
        /// create PDF
        public static string GeneratePDF(Int64 APartnerKey, string ACountryCode, TApplicationFormData AData, out string ADownloadIdentifier)
        {
            string FileName = TFormLettersTools.GetRoleSpecificFile(TAppSettingsManager.GetValue("Formletters.Path"),
                                                                    "ApplicationPDF",
                                                                    AData.registrationcountrycode,
                                                                    AData.formsid,
                                                                    "html");

            string HTMLText = string.Empty;

            if (!File.Exists(FileName))
            {
                HTMLText = "<html><body>" + String.Format("Cannot find file {0}", FileName) + "</body></html>";
            }
            else
            {
                StreamReader r = new StreamReader(FileName);
                HTMLText = r.ReadToEnd();
                r.Close();
            }

            if ((AData.existingpartnerkey != null) && AData.existingpartnerkey.StartsWith("If you cannot find it"))
            {
                AData.RawData            = AData.RawData.Replace(AData.existingpartnerkey, "N/A");
                AData.existingpartnerkey = "";
            }

            if (AData.groupwish == null)
            {
                Regex regex = new Regex(@"^.*#GROUPWISH.*$", RegexOptions.Multiline);
                HTMLText = regex.Replace(HTMLText, "");
            }

            HTMLText = TJsonTools.ReplaceKeywordsWithData(AData.RawData, HTMLText);

            HTMLText = HTMLText.Replace("#DATE", StringHelper.DateToLocalizedString(DateTime.Today));
            HTMLText = HTMLText.Replace("#FORMLETTERPATH", TAppSettingsManager.GetValue("Formletters.Path"));
            HTMLText = HTMLText.Replace("#REGISTRATIONID", StringHelper.FormatStrToPartnerKeyString(APartnerKey.ToString()));
            HTMLText = HTMLText.Replace("#PHOTOPARTICIPANT", TAppSettingsManager.GetValue("Server.PathData") +
                                        Path.DirectorySeparatorChar + "photos" +
                                        Path.DirectorySeparatorChar + APartnerKey.ToString() + ".jpg");

            HTMLText = HTMLText.Replace("#HTMLRAWDATA", TJsonTools.DataToHTMLTable(AData.RawData));

            PrintDocument doc = new PrintDocument();

            TPdfPrinter  pdfPrinter  = new TPdfPrinter(doc, TGfxPrinter.ePrinterBehaviour.eFormLetter);
            TPrinterHtml htmlPrinter = new TPrinterHtml(HTMLText,
                                                        String.Empty,
                                                        pdfPrinter);

            pdfPrinter.Init(eOrientation.ePortrait, htmlPrinter, eMarginType.ePrintableArea);

            string pdfPath = TAppSettingsManager.GetValue("Server.PathData") + Path.DirectorySeparatorChar +
                             "pdfs";

            if (!Directory.Exists(pdfPath))
            {
                Directory.CreateDirectory(pdfPath);
            }

            string pdfFilename = pdfPath + Path.DirectorySeparatorChar + APartnerKey.ToString() + ".pdf";

            pdfPrinter.SavePDF(pdfFilename);

            string downloadPath = TAppSettingsManager.GetValue("Server.PathData") + Path.DirectorySeparatorChar +
                                  "downloads";

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }

            // Create a link file for this PDF
            ADownloadIdentifier = TPatchTools.GetMd5Sum(pdfFilename);
            StreamWriter sw = new StreamWriter(downloadPath + Path.DirectorySeparatorChar + ADownloadIdentifier + ".txt");

            sw.WriteLine("pdfs");
            sw.WriteLine(Path.GetFileName(pdfFilename));
            sw.Close();

            return(pdfFilename);
        }