ソースを参照

Moved soem of EmailUtils into InABox.Wpf

Kenric Nugteren 1 年間 前
コミット
07fe17b569

+ 1 - 0
prs.desktop/Panels/Jobs/DocumentSets/JobDocumentSetMilestoneTasks.cs

@@ -9,6 +9,7 @@ using Comal.Classes;
 using InABox.Clients;
 using InABox.Core;
 using InABox.DynamicGrid;
+using InABox.Wpf;
 using InABox.WPF;
 using NPOI.SS.Formula.Functions;
 using Syncfusion.UI.Xaml.Charts;

+ 1 - 3
prs.desktop/Panels/Jobs/DocumentSets/JobDocumentSetTree.xaml.cs

@@ -87,11 +87,9 @@ namespace PRSDesktop
         
         public String SearchText { get; set; }
 
-        private Dictionary<Guid,MileStoneType> _types = null;
+        private Dictionary<Guid, MileStoneType> _types = null;
         private CoreTable _milestones = null;
         public CoreTable Data { get; private set; } = null;
-
-        private CoreTable _files = null;
         
         private bool _hidesuperceded = false;
         private bool _flatlist = false;

+ 2 - 2
prs.desktop/Panels/PanelHost.cs

@@ -262,9 +262,9 @@ public class PanelHost : IPanelHost
     {
         if (CurrentPanel is null)
             return new List<ReportExportDefinition>() { new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
-                            EmailUtils.DoEmailReport)};
+                            PRSEmailUtils.DoEmailReport)};
         else
-            return EmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
+            return PRSEmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
     }
 
     public static PanelAction CreateReportAction(ReportTemplate template, Func<Selection, DataModel> getDataModel)

+ 4 - 3
prs.desktop/Panels/Users/UserGrid.cs

@@ -10,6 +10,7 @@ using InABox.Clients;
 using InABox.Core;
 using InABox.DynamicGrid;
 using InABox.Mail;
+using InABox.Wpf;
 using InABox.WPF;
 using NPOI.SS.Formula.Functions;
 using PRS.Shared;
@@ -67,7 +68,7 @@ namespace PRSDesktop
             return true;
         }
 
-        private void CreateLink(User user, string ioslink, string androidlink, string URLs)
+        private static void CreateLink(User user, string ioslink, string androidlink, string URLs)
         {
             if (string.IsNullOrWhiteSpace(ioslink))
                 return;
@@ -82,8 +83,8 @@ namespace PRSDesktop
             string toEncrypt = URLs + "," + user.UserID + "," + user.Password + "," + DateTime.Now.AddMinutes(expiry);
             string encrypted = Encryption.Encrypt(toEncrypt, "logindetailslink", true);
 
-            ioslink = ioslink + encrypted;
-            androidlink = androidlink + encrypted;
+            ioslink += encrypted;
+            androidlink += encrypted;
 
             string emailcontent = "Please ensure PRS Mobile is closed, then choose a link below:" + Environment.NewLine + Environment.NewLine +
                 "For Apple devices, click this link: " + ioslink + Environment.NewLine + Environment.NewLine

+ 24 - 25
prs.desktop/Utils/DataModelUtils.cs

@@ -4,39 +4,38 @@ using InABox.Core;
 using Scriban;
 using Scriban.Runtime;
 
-namespace PRSDesktop
+namespace PRSDesktop;
+
+public static class DataModelUtils
 {
-    public static class DataModelUtils
+    public static string ParseTemplate(DataModel model, string data)
     {
-        public static string ParseTemplate(DataModel model, string data)
-        {
-            if (string.IsNullOrWhiteSpace(data))
-                return "";
+        if (string.IsNullOrWhiteSpace(data))
+            return "";
 
-            var template = Template.Parse(data);
-            if (template.HasErrors) throw new Exception(string.Join("\n", template.Messages));
+        var template = Template.Parse(data);
+        if (template.HasErrors) throw new Exception(string.Join("\n", template.Messages));
 
-            var templatecontext = new TemplateContext
-            {
-                MemberRenamer = member => member.Name
-            };
+        var templatecontext = new TemplateContext
+        {
+            MemberRenamer = member => member.Name
+        };
 
-            var so = new ScriptObject();
-            ScriptObjectExtensions.Import(so, "string.to_base64", new Func<byte[], string>(b => Convert.ToBase64String(b)));
+        var so = new ScriptObject();
+        ScriptObjectExtensions.Import(so, "string.to_base64", new Func<byte[], string>(b => Convert.ToBase64String(b)));
 
-            foreach (var (key, table) in model.ModelTables)
+        foreach (var (key, table) in model.ModelTables)
+        {
+            var objects = new List<object>();
+            if (table.Type is not null)
             {
-                var objects = new List<object>();
-                if (table.Type is not null)
-                {
-                    foreach (var tablerow in table.Table.Rows)
-                        objects.Add(tablerow.ToObject(table.Type));
-                }
-                so.Add(key, objects);
+                foreach (var tablerow in table.Table.Rows)
+                    objects.Add(tablerow.ToObject(table.Type));
             }
-
-            templatecontext.PushGlobal(so);
-            return template.Render(templatecontext);
+            so.Add(key, objects);
         }
+
+        templatecontext.PushGlobal(so);
+        return template.Render(templatecontext);
     }
 }

+ 69 - 211
prs.desktop/Utils/EmailUtils.cs

@@ -19,239 +19,97 @@ using MessageBox = System.Windows.Forms.MessageBox;
 using Comal.Classes;
 using TextBox = System.Windows.Controls.TextBox;
 using InABox.Wpf.Reports;
+using InABox.Wpf;
 
-namespace PRSDesktop
-{
-    public class EmailUtils
-    {   
-        /// <summary>
-         /// Creates and opens an email with the default email app - selected by the user.
-         /// This method is for emails with a PDF attachment. Provide the file name and data.
-         /// Optionally provide from, subject and body.
-         /// If from is not provided, an attempt will be made to find the User's email address - if empty it will throw an error (cannot be empty)
-         /// </summary>
-         /// <param name="attachmentname"></param>
-         /// <param name="attachmentdata"></param>
-         /// <param name="from"></param>
-         /// <param name="subject"></param>
-         /// <param name="body"></param>
-        public static void CreateEMLFile(string attachmentname, byte[] attachmentdata, string from = "", string subject = "", string body = "", string to = "")
-        {
-            var message = CreateMessage(from, subject, body, to);
-
-            message = AddAttachment(message, attachmentname, attachmentdata);
-
-            OpenEmail(message, attachmentname);
-        }
-        
-        /// <summary>
-        /// Creates and opens an email with the default email app - selected by the user.
-        /// This method is for emails with multiple PDF attachments. Provide the a Dictionary of names and byte arrays
-        /// Optionally provide from, subject and body.
-        /// If from is not provided, an attempt will be made to find the User's email address - if empty it will throw an error (cannot be empty)
-        /// </summary>
-        /// <param name="attachmentname"></param>
-        /// <param name="attachmentdata"></param>
-        /// <param name="from"></param>
-        /// <param name="subject"></param>
-        /// <param name="body"></param>
-        public static void CreateEMLFile(Dictionary<string,byte[]> attachments, string from = "", string subject = "", string body = "", string to = "")
-        {
-            var message = CreateMessage(from, subject, body, to);
-
-            foreach (var key in attachments.Keys)
-                AddAttachment(message, key, attachments[key]);
-
-            OpenEmail(message);
-        }
-
-        /// <summary>
-        /// Creates and opens an email with the default email app - selected by the user.
-        /// This method is for emails with no attachments.
-        /// Optionally provide from, subject and body.
-        /// If from is not provided, an attempt will be made to find the User's email address - if empty it will throw an error (cannot be empty)
-        /// </summary>
-        /// <param name="from"></param>
-        /// <param name="subject"></param>
-        /// <param name="body"></param>
-
-        public static void CreateEMLFile(string from = "", string subject = "", string body = "")
-        {
-            var message = CreateMessage(from, subject, body);
-
-            OpenEmail(message, "Message from " + from);
-        }
-
-        private static void OpenEmail(MailMessage message, string name = null)
-        {
-            var filename = Path.Combine(
-                Path.GetTempPath(), 
-                Path.ChangeExtension(String.IsNullOrWhiteSpace(name) ? Guid.NewGuid().ToString() : name, ".eml")
-            );
+namespace PRSDesktop;
 
-            using (var filestream = File.Open(filename, FileMode.Create))
-            {
-                var binaryWriter = new BinaryWriter(filestream);
-                //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
-                binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
-
-                var assembly = typeof(SmtpClient).Assembly;
-                var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter")!;
-
-                // Get reflection info for MailWriter contructor
-                var mailWriterConstructor =
-                    mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(Stream), typeof(bool) }, null)!;
-
-                // Construct MailWriter object with our FileStream
-                var mailWriter = mailWriterConstructor.Invoke(new object[] { filestream, true });
-
-                // Get reflection info for Send() method on MailMessage
-                var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic)!;
-
-                sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
-
-                // Finally get reflection info for Close() method on our MailWriter
-                var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic)!;
-
-                // Call close method
-                closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
-            }
-
-            // Open the file with the default associated application registered on the local machine
-            Process.Start(new ProcessStartInfo(filename) { UseShellExecute = true });
-        }
-
-        private static MailMessage CreateMessage(string from, string subject, string body, string to = "")
-        {
-            if (string.IsNullOrWhiteSpace(to))
-                to = "example@outlook.com.au";
-            if (string.IsNullOrWhiteSpace(from))
-                from = GetAddressFromUser();
-            if (string.IsNullOrWhiteSpace(subject))
-                subject = "Enter subject";
-            if (string.IsNullOrWhiteSpace(body))
-                body = "Enter message";
-            var message = new MailMessage(from, to, subject, body);
-            message.IsBodyHtml = false;
-
-            return message;
-        }
-
-        private static string GetAddressFromUser()
-        {
-            CoreTable table = new Client<User>().Query(new Filter<User>(x => x.ID).IsEqualTo(ClientFactory.UserGuid)
-                , new Columns<User>(x => x.EmailAddress));
-            User user = table.Rows.FirstOrDefault().ToObject<User>();
-
-            if (!string.IsNullOrWhiteSpace(user.EmailAddress))
-                return user.EmailAddress;
-            else
-                MessageBox.Show("Current User Email Address is blank - please fill in (Human Resources -> User Accounts -> Choose your User -> Email Settings -> Email Address", "Error");
-
-            return "";
-
-        }
-
-        private static MailMessage AddAttachment(MailMessage message, string attachmentname, byte[] attachmentdata)
-        {
-            var attachment = Path.Combine(
-                Path.GetTempPath(), 
-                String.IsNullOrWhiteSpace(Path.GetExtension(attachmentname)) 
-                    ? Path.ChangeExtension(attachmentname, ".pdf") 
-                    : attachmentname 
-            );
-            File.WriteAllBytes(attachment, attachmentdata);
-
-            message.Attachments.Add(new Attachment(attachment));
-
-            return message;
-        }
+public class PRSEmailUtils
+{
+    public static IEnumerable<ReportExportDefinition> CreateTemplateDefinitions(DataModel model)
+    {
+        var templates = new Client<DataModelTemplate>().Query(new Filter<DataModelTemplate>(x => x.Model).IsEqualTo(model.Name)
+            .And(x => x.Visible).IsEqualTo(true));
 
-        public static IEnumerable<ReportExportDefinition> CreateTemplateDefinitions(DataModel model)
+        if (templates.Rows.Any())
         {
-            var templates = new Client<DataModelTemplate>().Query(new Filter<DataModelTemplate>(x => x.Model).IsEqualTo(model.Name)
-                .And(x => x.Visible).IsEqualTo(true));
-
-            if (templates.Rows.Any())
+            List<ReportExportDefinition> list = new List<ReportExportDefinition>();
+            foreach (CoreRow row in templates.Rows)
             {
-                List<ReportExportDefinition> list = new List<ReportExportDefinition>();
-                foreach (CoreRow row in templates.Rows)
+                Action<DataModel, byte[]> action = new Action<DataModel, byte[]>((model, data) =>
                 {
-                    Action<DataModel, byte[]> action = new Action<DataModel, byte[]>((model, data) =>
-                    {
-                        DoEmailAction(model, data, row.Get<DataModelTemplate, string>(x => x.Name));
-                    });
-                    list.Add(
-                        new ReportExportDefinition(
-                            "Email Report",
-                            ImageUtils.CreatePreviewWindowButtonContent(row.Get<DataModelTemplate, string>(x => x.Name),PRSDesktop.Resources.emailreport), 
-                            ReportExportType.PDF, 
-                            action));
-                }
-                return list;
-            }
-            else
-                return new List<ReportExportDefinition>() 
-                { 
+                    DoEmailAction(model, data, row.Get<DataModelTemplate, string>(x => x.Name));
+                });
+                list.Add(
                     new ReportExportDefinition(
                         "Email Report",
-                        ImageUtils.CreatePreviewWindowButtonContent("Email",PRSDesktop.Resources.emailreport), 
-                        ReportExportType.PDF,
-                            DoEmailReport)
-                };
+                        ImageUtils.CreatePreviewWindowButtonContent(row.Get<DataModelTemplate, string>(x => x.Name),PRSDesktop.Resources.emailreport), 
+                        ReportExportType.PDF, 
+                        action));
+            }
+            return list;
         }
+        else
+            return new List<ReportExportDefinition>() 
+            { 
+                new ReportExportDefinition(
+                    "Email Report",
+                    ImageUtils.CreatePreviewWindowButtonContent("Email",PRSDesktop.Resources.emailreport), 
+                    ReportExportType.PDF,
+                        DoEmailReport)
+            };
+    }
 
-        private static void DoEmailAction(DataModel model, byte[] data, string templateName)
-        {
-            var template = new Client<DataModelTemplate>().Query(new Filter<DataModelTemplate>(x => x.Name).IsEqualTo(templateName)).Rows.FirstOrDefault();
+    private static void DoEmailAction(DataModel model, byte[] data, string templateName)
+    {
+        var template = Client.Query(new Filter<DataModelTemplate>(x => x.Name).IsEqualTo(templateName))
+            .ToObjects<DataModelTemplate>().First();
 
-            ParseTemplateAndCreateEmail(template, model, data);
-        }
+        ParseTemplateAndCreateEmail(template, model, data);
+    }
 
-        private static void ParseTemplateAndCreateEmail(CoreRow row, DataModel model, byte[] data)
-        {
-            var to = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.To)).Replace("\n", "").Replace("\r", "");
-            var Subject = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.Subject)).Replace("\n", "").Replace("\r", "");
-            var attachmentName = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.AttachmentName)).Replace("\n", "").Replace("\r", "");
-            var body = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.Template));
+    private static void ParseTemplateAndCreateEmail(DataModelTemplate template, DataModel model, byte[] data)
+    {
+        var to = DataModelUtils.ParseTemplate(model, template.To).Replace("\n", "").Replace("\r", "");
+        var Subject = DataModelUtils.ParseTemplate(model, template.Subject).Replace("\n", "").Replace("\r", "");
+        var attachmentName = DataModelUtils.ParseTemplate(model, template.AttachmentName).Replace("\n", "").Replace("\r", "");
+        var body = DataModelUtils.ParseTemplate(model, template.Template);
 
-            if (string.IsNullOrWhiteSpace(attachmentName))
-                attachmentName = model.Name;
-            EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, Subject, body, to);
-        }
+        if (string.IsNullOrWhiteSpace(attachmentName))
+            attachmentName = model.Name;
+        EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, Subject, body, to);
+    }
 
-        public static void DoEmailReport(DataModel model, byte[] data)
+    public static void DoEmailReport(DataModel model, byte[] data)
+    {
+        string attachmentName = DetermineName(model);
+        EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, "Emailing report for " + attachmentName);
+    }
+
+    private static string DetermineName(DataModel model)
+    {
+        string title = model.Name;
+        if (model.HasTable<Requisition>())
         {
-            string attachmentName = DetermineName(model);
-            EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, "Emailing report for " + attachmentName);
+            CoreTable table = model.GetTable<Requisition>();
+            title = title + " - " + table.Rows.FirstOrDefault().Get<Requisition, string>(x => x.Title);
         }
-
-        private static string DetermineName(DataModel model)
+        else if (model.HasTable<PurchaseOrder>())
         {
-            string title = model.Name;
-            if (model.HasTable<Requisition>())
+            title = "Purchase Order ";
+            CoreTable table = model.GetTable<PurchaseOrder>();
+            if (table.Rows.Count == 1)
+                title += table.Rows.FirstOrDefault().Get<PurchaseOrder, string>(x => x.PONumber);
+            else if (table.Rows.Count > 1)
             {
-                CoreTable table = model.GetTable<Requisition>();
-                title = title + " - " + table.Rows.FirstOrDefault().Get<Requisition, string>(x => x.Title);
-            }
-            else if (model.HasTable<PurchaseOrder>())
-            {
-                title = "Purchase Order ";
-                CoreTable table = model.GetTable<PurchaseOrder>();
-                if (table.Rows.Count == 1)
-                    title += table.Rows.FirstOrDefault().Get<PurchaseOrder, string>(x => x.PONumber);
-                else if (table.Rows.Count > 1)
+                foreach (CoreRow row in table.Rows)
                 {
-                    foreach (CoreRow row in table.Rows)
-                    {
-                        title = title + row.Get<PurchaseOrder, string>(x => x.PONumber) + ", ";
-                    }
-                    title = title.Substring(0, title.Length - 2);
+                    title = title + row.Get<PurchaseOrder, string>(x => x.PONumber) + ", ";
                 }
+                title = title.Substring(0, title.Length - 2);
             }
-
-            return title;
         }
 
+        return title;
     }
+
 }