using System; using System.Web; using DevExpress.XtraPrinting; using System.Collections.Generic; using System.IO; using System.Linq; using Neo.Afx.Security; using Neo.Afx.Services.Documents; using Neo.Afx.Services.Integration; using DevExpress.XtraRichEdit.API.Native; using Neo.Afx.Common; namespace Neo.LegitimateLicences.Web.AfxServices { public class TemplateDocumentGenerator : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.QueryString.Count == 0) return; bool documentTemplateIDInDateSource = false; var templateDocumentID = -1L; var dataSourceName = ""; var convertToPdf = false; if (!Int64.TryParse(context.Request.QueryString["templateDocumentID"], out templateDocumentID)) documentTemplateIDInDateSource = true; if (String.IsNullOrEmpty(context.Request.QueryString["dataSourceName"])) return; if (context.Request.QueryString["convertToPdf"] != null) if (!Boolean.TryParse(context.Request.QueryString["convertToPdf"], out convertToPdf)) return; dataSourceName = context.Request.QueryString["dataSourceName"].ToString(); var queryString = GetQueryString(); var entities = new List(); try { using (var dataStore = new SqlIntegrationStore()) { dataStore.Open(); entities = dataStore.GetDataEntities(dataSourceName, queryString).ToList(); } var docDb = new DocumentsDatabase(); var generatedDocumentBytes = new byte[0]; using (var srv = new DevExpress.XtraRichEdit.RichEditDocumentServer()) { DevExpress.XtraRichEdit.API.Native.Document doc = srv.Document; foreach (var entity in entities) { if (documentTemplateIDInDateSource) templateDocumentID = int.Parse(entity.Properties.Where(a => a.Key == "templatedocumentid").FirstOrDefault().Value); var templateFile = docDb.GetDocumentObject(templateDocumentID); if (templateFile == null) throw new Exception("Template document has not been upload and configured"); using (var stream = new MemoryStream(templateFile.Content)) { doc.AppendDocumentContent(stream); var targetPosition = doc.Sections.Last().Range.End; //add page break after each template, unless it's the last page if (entity != entities.Last()) { doc.InsertSection(targetPosition); var insertedSection = doc.GetSection(targetPosition); insertedSection.StartType = SectionStartType.NextPage; } } foreach (var p in entity.Properties) { // Try exact match first doc.ReplaceAll("{" + p.Key + "}", p.Value, DevExpress.XtraRichEdit.API.Native.SearchOptions.None); // Try lowercase match doc.ReplaceAll("{" + p.Key.ToLower() + "}", p.Value, DevExpress.XtraRichEdit.API.Native.SearchOptions.None); // Try uppercase match doc.ReplaceAll("{" + p.Key.ToUpper() + "}", p.Value, DevExpress.XtraRichEdit.API.Native.SearchOptions.None); } } doc.ReplaceAll("{Date_Now}", DateTime.Now.ToString("dd MM yyyy"), DevExpress.XtraRichEdit.API.Native.SearchOptions.None); using (var generatedocumentStream = new MemoryStream()) { if (convertToPdf) { var pdfOptions = new PdfExportOptions(); pdfOptions.DocumentOptions.Author = "Mark Jones"; pdfOptions.Compressed = false; pdfOptions.ImageQuality = PdfJpegImageQuality.Highest; srv.ExportToPdf(generatedocumentStream, pdfOptions); generatedDocumentBytes = new byte[generatedocumentStream.Length]; generatedDocumentBytes = generatedocumentStream.ToArray(); } else { doc.SaveDocument(generatedocumentStream, DevExpress.XtraRichEdit.DocumentFormat.OpenXml); generatedDocumentBytes = new byte[generatedocumentStream.Length]; generatedDocumentBytes = generatedocumentStream.ToArray(); } } } #region Push Data var fileName = DateTime.Now.ToString("ddMMyyyyhhmmss") + ".docx"; var contentType = (convertToPdf) ? "application/pdf" : "application/msword"; context.Response.ClearHeaders(); context.Response.ClearContent(); context.Response.AddHeader("Content-Length", generatedDocumentBytes.Length.ToString()); context.Response.ContentType = contentType; context.Response.Charset = "UTF-8"; context.Response.BinaryWrite(generatedDocumentBytes); context.Response.Flush(); context.Response.Clear(); #endregion } catch (Exception ex) { Dictionary additionalData = new Dictionary { { "templateDocumentID", templateDocumentID }, { "dataSourceName", dataSourceName }, { "convertToPdf", convertToPdf } }; var errorMessage = ErrorHelper.ProcessError(ex, "TemplateDocumentGenerator", "ProcessRequest", additionalData); throw ex; } } #region IsReusable public bool IsReusable { get { return false; } } #endregion #region GetQueryString public string GetQueryString() { var queryString = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString()); #region Add logged in user email and id to querystring for filtering if (string.IsNullOrEmpty(queryString)) { queryString = "Afx_LoggedInEmail=" + Neo.Afx.Security.UserProfile.Current.Email + "&Afx_LoggedInUserID=" + Neo.Afx.Security.UserProfile.Current.UserID; } else { if (queryString.ToLower().Contains("Afx_LoggedInEmail") || queryString.ToLower().Contains("Afx_LoggedInUserID")) { throw new System.Exception("Logged-In credentials can not be passed as parameters"); } queryString += "&Afx_LoggedInEmail=" + UserProfile.Current.Email + "&Afx_LoggedInUserID=" + UserProfile.Current.UserID; } #endregion return queryString; } #endregion } }