4

I am using a Lightswitch HTML "Create New data" screen facing the internet for people to submit Job Application data into a database. When they press the "Save" button the data saves but there is no way for the applicant to tell if their data was saved. The data entry screen just goes away. Is there a way to notify the applicant that their application is received by popping up a message box, sending an email, or both?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mark
  • 520
  • 1
  • 6
  • 18
  • can you not fire a message back from the database insert query – Toxide82 Mar 06 '17 at 09:18
  • are you using just Javascript for your code or C# behind aswell to do certain parts? If its just JavaScript, you can add in all the validation there and ensure that certain bits of information are present. And an email receipt is possible, I will add below: – Crezzer7 Mar 06 '17 at 10:20

1 Answers1

3

yes it is possible to send an email once the data has been inserted into the system. The first thing to do is to create 2 tables (ill write in SQL for this example, but using the LightSwitch build in tables also work)

Step 1 - Create the data tables that control the emails

CREATE TABLE Setting (SettingID INT IDENTITY (1,1) NOT NULL,
SettingName VARCHAR(11),
SettingValue VARCHAR(5))

ALTER TABLE Setting ADD CONSTRAINT SettingID_PK PRIMARY KEY (SettingID)

CREATE TABLE Message (MessageID INT IDENTITY (1,1) NOT NULL,
NameFrom VARCHAR (100), --EMAIL SERVER NAME
EmailFrom VARCHAR (100), --EMAIL A
NameTo VARCHAR (100), --SUBJECT
EmailTo VARCHAR (100), -- EMAIL B
EmailMessage VARCHAR (1500), --MESSAGE
EmailCreated DATETIMEOFFSET)

ALTER TABLE Message ADD CONSTRAINT MessageID_PK PRIMARY KEY (MessageID)

--INSERT THIS INTO SETTINGS TO ALLOW THE SYSTEM TO SEND EMAILS
INSERT INTO SETTING VALUES ('SendEmails', 'true')

Step 2 - Edit the Web.config file under the Server node

underneath your application name in the Web.config file, add the following code (usually between line 25-30) below these 2 lines:

<add key="ApplicationCulture" value="en-US" />
<add key="Microsoft.LightSwitch.DefaultClientName" value="HTMLClient" />

the code:

<add key="SMTPSendingName" value="MAIL HEADER" />
<add key="SMTPSendingEmailAddress" value="EMAIL TO SEND CONFIRMATION FROM" />
<add key="SMTPServer" value="mail.YOURSERVER.com" />
<add key="SMTPUserID" value="" />
<add key="SMTPPassword" value="" />
<add key="SMTPPort" value="25" />
<add key="SMTPSSL" value="false" />

Step 3 - Create a MailHelper.cs file within your datasource (as shown below): enter image description here

and add this code (make sure you add the References files and set "Copy Local" to True:

using System.Net;
using System.Net.Mail;
using System.Configuration;
using System;

namespace LightSwitchApplication.DataSources.ProjectHandlerThreeData
{
    internal class MailHelper
    {

        public SmtpClient objSmtpClient { get; set; }
        private string _SMTPSendingEmailAddress { get; set; }
        private string _SMTPServer { get; set; }
        private string _SMTPUserId { get; set; }
        private string _SMTPPassword { get; set; }
        private int _SMTPPort { get; set; }
        private bool _SMTPSSL { get; set; }

        private string _MailFromName { get; set; }
        private string _MailToEmail { get; set; }
        private string _MailToName { get; set; }
        private string _MailSubject { get; set; }
        private string _MailBody { get; set; }

        public MailHelper(
            string SendFromName, string SendToEmail,
            string SendToName, string Subject,
            string Body) 
{
            _MailFromName = SendFromName;
            _MailToEmail = SendToEmail;
            _MailToName = SendToName;
            _MailSubject = Subject;
            _MailBody = Body;


            _SMTPSendingEmailAddress = Convert.ToString(ConfigurationManager.AppSettings["SMTPSendingEmailAddress"]);
            _SMTPServer = Convert.ToString(ConfigurationManager.AppSettings["SMTPServer"]);
            _SMTPUserId = Convert.ToString(ConfigurationManager.AppSettings["SMTPUserID"]);
            _SMTPPassword = Convert.ToString(ConfigurationManager.AppSettings["SMTPPassword"]);
            _SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
            _SMTPSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTPSSL"]);

            objSmtpClient = new SmtpClient(_SMTPServer, _SMTPPort);
        }

        public void SendMail()
        {
            MailMessage mail = new MailMessage();

            System.Net.Mail.MailAddress mailFrom =
                new System.Net.Mail.MailAddress(_SMTPSendingEmailAddress, _MailFromName);

            System.Net.Mail.MailAddress mailTo =
                new System.Net.Mail.MailAddress(_MailToEmail, _MailToName);


            var _with1 = mail;
            _with1.From = mailFrom;
            _with1.To.Add(mailTo);
            _with1.Subject = _MailSubject;
            _with1.Body = _MailBody;


            objSmtpClient.EnableSsl = _SMTPSSL;

            objSmtpClient.Credentials =
                new NetworkCredential(_SMTPUserId, _SMTPPassword);

            objSmtpClient.SendAsync(mail, mail.To);
        }

     }
}

Step 4 - Add code to the Message table (open up the Messages table, click on the Write Code button at the top of the screen, and select Messages_Inserted

now add this code:

 try
            {
                var EmailSetting = Settings.Where(x => x.SettingName == "SendEmails").FirstOrDefault();
                if (EmailSetting != null)
                {
                    if (EmailSetting.SettingValue.ToLower() == "true")
                    {

                        string strSubject = "MAIL HEADER";
                        string strMessage = String.Format("{0}",
                            "TEXT AT TOP OF EMAIL IF REQUIRED")
                                            + Environment.NewLine + Environment.NewLine;
                        strMessage = strMessage + String.Format("{0}",
                            entity.EmailMessage) + Environment.NewLine;

                        // Create the MailHelper class created in the Server project.
                        MailHelper mailHelper =
                            new MailHelper(
                                entity.NameFrom,
                                entity.EmailTo,
                                entity.NameTo,
                                strSubject,
                                strMessage);

                        // Send Email
                        mailHelper.SendMail();

                    }
                    else
                    {
                    }
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }

And Check these references are present at the top:

using System.Configuration;
using System.Net.Mail;
using LightSwitchApplication.DataSources.YOURDATASOURCE;

Finally, add this code to your table on the INSERTED part of the code like the messages table above

//email a save receipt to the person who added the data
            Message objMessage = new Message();
            objMessage.NameFrom = Convert.ToString(ConfigurationManager.AppSettings["SMTPSendingName"]);
            objMessage.EmailFrom = Convert.ToString(ConfigurationManager.AppSettings["SMTPSendingEmailAddress"]);
            objMessage.NameTo = "Details Successfully Saved"; //SUBJECT
            objMessage.EmailTo = "emailto@email.com"; 
            objMessage.EmailMessage =
                string.Format("The Following User has successfully been Added: " +
                              "\nErrorID: " + entity.ErrorID +
                              "\nBy User: " + entity.StaffTable.Staffname +
                              "\nDate Reported:" + DateTime.Now.ToString(" dd.MM.yy") +
                              "\n\nError Details: " + entity.Message);

I have left my code in above with the Error information to show how to format the email and display more information. I hope this helps :) If there are any errors let me know and ill help to solve it, it will most likely be an assembly reference I have missed.

A little bit extra

on your add screens, make sure you add this code if you are using JavaScript validation:

on the screen created event, add this code. This will disable the CTRL + S function which is activated. (This is required on each screen):

myapp.AddEditScreen.created = function (screen) {
  $(window).one("pagechange", function (e, data) {
        var $page = $("#" + screen.details._pageId);
        var $button = $page.find(".msls-save-button");
        $button.removeClass("msls-save-button");
    });
};

secondly, add this to any variable (click on Edit PostRender Code). This code will hide the default save, delete, cancel buttons so your validation cannot be bipassed

$("[data-ls-tap='tap:{data.shell.discardCommand.command}']").hide();
$("[data-ls-tap='tap:{data.shell.saveCommand.command}']").hide();
$("[data-ls-tap='tap:{data.shell.okCommand.command}']").hide();
$("[data-ls-tap='tap:{data.shell.cancelCommand.command}']").hide();

Original Code for mail from here (a sample project can be downloaded also): http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/2224/Sending-Asynchronous-Emails-Using-LightSwitch-HTML-Client.aspx

Crezzer7
  • 2,265
  • 6
  • 32
  • 63
  • Crezzer7, I am finding this helpful. Thank you. I have successfully followed most of your instructions. Here are some questions: At the bottom of step 4 you say to make sure the this using statement (among others) is present. using LightSwitchApplication.DataSources.YOURDATASOURCE; What is the YOURDATASOURCE supposed to be. In my application the only available item available is application data. So it reads like this: using LightSwitchApplication.DataSources.ApplicationData; – Mark Mar 06 '17 at 15:59
  • The second question is in the “Finally” step. You indicate the that the code should be added “your table”. What table is “your table”. Is it just more code in INSERTED part the “messages” table? – Mark Mar 06 '17 at 16:00
  • your first comment for: LightSwitchApplication.DataSources.YOURDATASOURCE. you are correct in assuming that it should be ApplicationData – Crezzer7 Mar 06 '17 at 16:09
  • secondly, by your table I mean which ever table you want an email from, confirming the data has been saved. so for example if you had a table staff, you would add the code from finally into the Staff_Inserted code block, which you can generate like you did on Step 4. I have pasted a link at the bottom which is where I started – Crezzer7 Mar 06 '17 at 16:10
  • Crezzer7, As you indicated in the "Finally", there are some errors with the ErrorID and Message in the Messages_Inserted code – Mark Mar 07 '17 at 16:46
  • SEE HERE : string.Format("The Following User has successfully been Added: " + "\nErrorID: " + entity.ErrorID + "\nBy User: " + entity.RecruitEmailAddress + "\nDate Reported:" + DateTime.Now.ToString(" dd.MM.yy") + "\n\nError Details: " + entity.Message); – Mark Mar 07 '17 at 16:48
  • AND HERE: Severity Code Description Line Suppression State Error CS1061 'Recruit' does not contain a definition for 'ErrorID' and no extension method 'ErrorID' accepting a first argument of type 'Recruit' could be found (are you missing a using directive or an assembly reference?) 67 Active – Mark Mar 07 '17 at 16:50
  • AND HERE: AND HERE: Severity Code Description Line Suppression State Error CS1061 'Recruit' does not contain a definition for 'Message' and no extension method 'Message' accepting a first argument of type 'Recruit' could be found (are you missing a using directive or an assembly reference?) 70 Active – Mark Mar 07 '17 at 16:50
  • you haven't got a sample of the project I can download to see what's going on by any change? – Crezzer7 Mar 07 '17 at 16:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/137465/discussion-between-crezzer7-and-mark). – Crezzer7 Mar 07 '17 at 17:00