示例#1
0
        public static string PrintChildren(
            string AChildName,
            string ADonorName,
            bool AChildWithoutDonor,
            string APartnerStatus,
            string ASponsorshipStatus,
            string ASponsorAdmin,
            string ASortBy,
            string AReportLanguage)
        {
            SponsorshipFindTDSSearchResultTable table = FindChildren(AChildName, ADonorName, AChildWithoutDonor, APartnerStatus, ASponsorshipStatus, ASponsorAdmin, ASortBy);

            HtmlDocument HTMLDocument = HTMLTemplateProcessor.Table2Html(table, "Sponsorship/SponsoredChildrenList.html", AReportLanguage);

            string PDFFile = TFileHelper.GetTempFileName(
                "printchildrenlist",
                ".pdf");

            if (Html2Pdf.HTMLToPDF(HTMLDocument.DocumentNode.WriteTo(), PDFFile))
            {
                byte[] data   = System.IO.File.ReadAllBytes(PDFFile);
                string result = Convert.ToBase64String(data);
                System.IO.File.Delete(PDFFile);
                return(result);
            }

            return(String.Empty);
        }
示例#2
0
        /// <summary>
        /// Create a PDF file from the HTML
        /// </summary>
        public static bool HTMLToPDF(HtmlDocument html, string AOutputPDFFilename)
        {
            // export HTML including the CSS to a single file.
            string HTMLFile = TFileHelper.GetTempFileName(
                "htmlreport",
                ".html");

            string CSSContent = String.Empty;

            using (StreamReader sr = new StreamReader("/usr/local/openpetra/client/css/report.css"))
            {
                CSSContent = sr.ReadToEnd();
            }

            string BootstrapCSSContent = String.Empty;
            string cssBootstrap        = "/usr/local/openpetra/client/node_modules/bootstrap/dist/css/bootstrap.min.css";

            if (!File.Exists(cssBootstrap))
            {
                cssBootstrap = "/usr/local/openpetra/client/css/bootstrap.min.css";
            }

            using (StreamReader sr = new StreamReader(cssBootstrap))
            {
                BootstrapCSSContent = sr.ReadToEnd();
            }

            string BundledJSContent = string.Empty;

            using (StreamReader sr = new StreamReader("/usr/local/openpetra/client/dist/bundle.min.js"))
            {
                BundledJSContent = sr.ReadToEnd();
            }


            using (StreamWriter sw = new StreamWriter(HTMLFile))
            {
                string strhtml = html.DocumentNode.WriteTo().
                                 Replace("<link href=\"/css/report.css\" rel=\"stylesheet\">",
                                         "<style>" +
                                         BootstrapCSSContent + Environment.NewLine +
                                         CSSContent + "</style>" + Environment.NewLine +
                                         "<script>" + BundledJSContent + "</script>");
                sw.Write(strhtml);
                sw.Close();
            }

            Process process = new Process();

            process.StartInfo.FileName  = "/usr/local/bin/wkhtmltopdf";
            process.StartInfo.Arguments = HTMLFile + " " + AOutputPDFFilename;
            process.Start();
            process.WaitForExit();

            File.Delete(HTMLFile);

            return(true);
        }
示例#3
0
        /// get export path in the user directory. used eg. by GL Batch or Gift Batch export
        /// will create the directory if it does not exist yet.
        public static string GetExportPath()
        {
            string ExportPath = GetUserPath("OpenPetra.PathExport",
                                            GetUserPath("OpenPetra.PathTemp", "") + Path.DirectorySeparatorChar + "export");

            TFileHelper.CreateDirectory(ExportPath);

            return(ExportPath);
        }
        /// <summary>
        /// Create a PDF file from the HTML
        /// </summary>
        public static bool HTMLToPDF(HtmlDocument html, string AOutputPDFFilename)
        {
            // export HTML including the CSS to a single file.
            string HTMLFile = TFileHelper.GetTempFileName(
                "htmlreport",
                ".html");

            string CSSContent = String.Empty;

            // ApplicationDirectory points to eg. /home/openpetra/server/bin, we want /home/openpetra/
            string InstallPath = Path.GetFullPath(TAppSettingsManager.GetValue("ApplicationDirectory") + "/../../");

            using (StreamReader sr = new StreamReader(InstallPath + "client/css/report.css"))
            {
                CSSContent = sr.ReadToEnd();
            }

            string BootstrapCSSContent = String.Empty;

            using (StreamReader sr = new StreamReader(InstallPath + "bootstrap-4.0/bootstrap.min.css"))
            {
                BootstrapCSSContent = sr.ReadToEnd();
            }

            string BundledJSContent = string.Empty;

            using (StreamReader sr = new StreamReader(InstallPath + "bootstrap-4.0/bootstrap.bundle.min.js"))
            {
                BundledJSContent = sr.ReadToEnd();
            }


            using (StreamWriter sw = new StreamWriter(HTMLFile))
            {
                string strhtml = html.DocumentNode.WriteTo().
                                 Replace("<link href=\"/css/report.css\" rel=\"stylesheet\">",
                                         "<style>" +
                                         BootstrapCSSContent + Environment.NewLine +
                                         CSSContent + "</style>" + Environment.NewLine +
                                         "<script>" + BundledJSContent + "</script>");
                sw.Write(strhtml);
                sw.Close();
            }

            Process process = new Process();

            process.StartInfo.FileName  = TAppSettingsManager.GetValue("wkhtmltopdf.Path", "/usr/local/bin/wkhtmltopdf");
            process.StartInfo.Arguments = HTMLFile + " " + AOutputPDFFilename;
            process.Start();
            process.WaitForExit();

            File.Delete(HTMLFile);

            return(true);
        }
示例#5
0
        /// Download the result of the report as Excel File in base64 encoding
        public string DownloadExcel()
        {
            string ExcelFile = TFileHelper.GetTempFileName(
                FParameterList.Get("currentReport").ToString(),
                ".xls");

            if (ExportToExcelFile(ExcelFile))
            {
                byte[] data   = System.IO.File.ReadAllBytes(ExcelFile);
                string result = Convert.ToBase64String(data);
                System.IO.File.Delete(ExcelFile);
                return(result);
            }

            return(String.Empty);
        }
示例#6
0
        /// Download the result of the report as PDF File in base64 encoding
        public string DownloadPDF()
        {
            string PDFFile = TFileHelper.GetTempFileName(
                FParameterList.Get("currentReport").ToString(),
                ".pdf");

            if (PrintToPDF(PDFFile))
            {
                byte[] data   = System.IO.File.ReadAllBytes(PDFFile);
                string result = Convert.ToBase64String(data);
                System.IO.File.Delete(PDFFile);
                return(result);
            }

            return(String.Empty);
        }
示例#7
0
        private static string GetUserPath(string AVariableName, string ADefaultValue)
        {
            string result = TAppSettingsManager.GetValue(AVariableName, ADefaultValue);

            if (result.Length == 0)
            {
                return(result);
            }

            // on Windows, we cannot store the database in userappdata during installation, because
            // the setup has to be run as administrator.
            // therefore the first time the user starts Petra, we need to prepare his environment
            // see also http://www.vincenzo.net/isxkb/index.php?title=Vista_considerations#Best_Practices
            TFileHelper.CreateDirectory(result);

            return(Path.GetFullPath(result));
        }
示例#8
0
        public static string DownloadExcel(string AReportID, TDataBase ADataBase = null)
        {
            SReportResultRow Row = GetReportResult(AReportID, ADataBase);

            if (Row != null)
            {
                HtmlDocument HTMLDocument = new HtmlDocument();
                HTMLDocument.LoadHtml(Row.ResultHtml);

                string ExcelFile = TFileHelper.GetTempFileName(
                    AReportID,
                    ".xls");

                if (ExportToExcelFile(ExcelFile, HTMLDocument))
                {
                    byte[] data   = System.IO.File.ReadAllBytes(ExcelFile);
                    string result = Convert.ToBase64String(data);
                    System.IO.File.Delete(ExcelFile);
                    return(result);
                }
            }

            return(String.Empty);
        }
示例#9
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 = null;
            string      EmailBody   = "";

            AVerification = new TVerificationResultCollection();

            try
            {
                EmailSender = new TSmtpSender();

                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);
                }

                try
                {
                    EmailSender.SetSender(TUserDefaults.GetStringDefault("SmtpFromAccount"),
                                          TUserDefaults.GetStringDefault("SmtpDisplayName"));
                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");
                    EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                }
                catch (ESmtpSenderInitializeException e)
                {
                    AVerification.Add(new TVerificationResult(
                                          Catalog.GetString("Sending Email"),
                                          String.Format("{0}\n{1}", e.Message, Catalog.GetString("Check the Email tab in User Settings >> Preferences.")),
                                          CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION,
                                          TResultSeverity.Resv_Critical,
                                          new System.Guid()));

                    if (e.InnerException != null)
                    {
                        TLogging.Log("Email XML Report: " + e.InnerException);
                    }

                    return(false);
                }

                if (EmailBody == "")
                {
                    EmailBody = Catalog.GetString("OpenPetra report attached.");
                }

                if (EmailSender.SendEmail(
                        AEmailAddresses,
                        FParameterList.Get("currentReport").ToString(),
                        EmailBody,
                        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);
            } // try
            catch (ESmtpSenderInitializeException e)
            {
                AVerification.Add(new TVerificationResult(
                                      Catalog.GetString("Sending Email"),
                                      e.Message,
                                      CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION,
                                      TResultSeverity.Resv_Critical,
                                      new System.Guid()));

                if (e.InnerException != null)
                {
                    TLogging.Log("Email XML Report: " + e.InnerException);
                }

                return(false);
            }
            finally
            {
                if (EmailSender != null)
                {
                    EmailSender.Dispose();
                }
            }
        }
示例#10
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);
        }
示例#11
0
        public static bool UploadPhoto(
            Int64 APartnerKey,
            Int32 ALedgerNumber,
            byte[] APhoto,
            string APhotoFilename,
            out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = new TVerificationResultCollection();

            if (APartnerKey == -1)
            {
                return(false);
            }

            string         dummy       = "0";
            SponsorshipTDS CurrentEdit = GetChildDetails(APartnerKey, ALedgerNumber, true, out dummy);

            if (APhotoFilename.Length > 0)
            {
                string tempFileName = TFileHelper.GetTempFileName(
                    "photo",
                    Path.GetExtension(APhotoFilename));
                File.WriteAllBytes(tempFileName, APhoto);

                using (var srcImage = Image.FromFile(tempFileName))
                {
                    var newHeight = 256;
                    var newWidth  = (int)(srcImage.Width * ((float)newHeight / (float)srcImage.Height));

                    using (var newImage = new Bitmap(newWidth, newHeight))
                    {
                        using (var graphics = Graphics.FromImage(newImage))
                        {
                            graphics.SmoothingMode     = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));

                            using (var ms = new MemoryStream())
                            {
                                newImage.Save(ms, newImage.RawFormat);
                                CurrentEdit.PFamily[0].Photo = Convert.ToBase64String(ms.ToArray());
                            }

                            try
                            {
                                SponsorshipTDSAccess.SubmitChanges(CurrentEdit);
                                File.Delete(tempFileName);
                                return(true);
                            }
                            catch (Exception e)
                            {
                                TLogging.Log(e.ToString());
                                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                            }
                        }
                    }
                }

                File.Delete(tempFileName);
            }

            return(false);
        }
示例#12
0
        private static string GetTemplatePath(TModule AModule, TPrintUsing APrintApplication, string AFormName)
        {
            string ReturnValue = string.Empty;
            string msgTitle    = Catalog.GetString("Print");

#if USING_TEMPLATER
            PFormTable formTable = null;

            switch (AModule)
            {
            case TModule.mPartner:
                formTable = TRemote.MCommon.FormTemplates.WebConnectors.DownloadPartnerFormTemplate(AFormName, "99");
                break;

            case TModule.mPersonnel:
                formTable = TRemote.MCommon.FormTemplates.WebConnectors.DownloadPersonnelFormTemplate(AFormName, "99");
                break;

            case TModule.mFinance:
                formTable = TRemote.MCommon.FormTemplates.WebConnectors.DownloadFinanceFormTemplate("PRINTGRID", AFormName, "99");
                break;

            default:
                break;
            }

            if ((formTable != null) && (formTable.Rows.Count == 1))
            {
                // We got something from the DB
                PFormRow row        = (PFormRow)(formTable.Rows[0]);
                string   base64Text = row.TemplateDocument;

                // Work out the default file editing location for this template
                string uniqueFileName = row.FormCode + "_" + row.FormName + "_" + row.FormLanguage;
                string extension      = row.TemplateFileExtension.Length == 0 ? APrintApplication ==
                                        TPrintUsing.Excel ? "xlsx" : "docx" : row.TemplateFileExtension;
                string templateFileName = TFileHelper.GetDefaultTemporaryTemplatePath(uniqueFileName, extension);

                if (File.Exists(templateFileName))
                {
                    // delete the existing file
                    // If this fails it must already be open in the editor
                    Boolean showInUseMessage = false;
                    try
                    {
                        File.Delete(templateFileName);
                        System.Threading.Thread.Sleep(500);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        showInUseMessage = true;
                    }
                    catch (IOException)
                    {
                        showInUseMessage = true;
                    }

                    if (showInUseMessage)
                    {
                        string msg = Catalog.GetString("Cannot access the template file.  Maybe you already have it open in an editor?  ");
                        msg += Catalog.GetString("The file is: ");
                        msg += templateFileName;
                        msg += Environment.NewLine + Environment.NewLine;
                        msg += Catalog.GetString("Do you want to continue? Click Yes to try again or No to cancel.");

                        if (MessageBox.Show(msg, msgTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                        {
                            return(ReturnValue);
                        }
                    }
                }

                // Write the file
                string failMessage;

                if (TFileHelper.WriteBinaryFileConvertedFromBase64String(base64Text, templateFileName, out failMessage))
                {
                    // Succeeded in writing the file locally, so now we can open it ...
                    return(templateFileName);
                }
                else
                {
                    MessageBox.Show(failMessage, msgTitle);
                    return(ReturnValue);
                }
            }

            // So we did not get anything from the database.  Lets try the file system
            string tryPath = Path.Combine(TTemplaterAccess.GetFormLetterTemplateBaseDirectory(TModule.mPartner),
                                          AFormName + (APrintApplication == TPrintUsing.Excel ? ".xlsx" : ".docx"));

            if (File.Exists(tryPath))
            {
                // Use this one then
                return(tryPath);
            }
#endif
            // Did not find anything
            return(ReturnValue);
        }