public void serializeToJSON(Message message) { // Look into the message collection for duplicates MessageCollection collection = loadFile(_connectionPath); // add message to collection or throw error switch (message.MessageType) { case "S": if (collection.SMSList.ContainsKey(message.Header)) { throw new Exception($"{message.Header} message not saved: the database already contains the message."); } SMS sms = (SMS)message; collection.SMSList.Add(message.Header, sms); break; case "E": Email email = (Email)message; if (email.EmailType == "SEM") { if (collection.SEMList.ContainsKey(message.Header)) { throw new Exception($"{message.Header} message not saved: the database already contains the message."); } SEM sem = (SEM)email; collection.SEMList.Add(message.Header, sem); } else if (email.EmailType == "SIR") { if (collection.SIRList.ContainsKey(message.Header)) { throw new Exception($"{message.Header} message not saved: the database already contains the message."); } SIR sir = (SIR)email; collection.SIRList.Add(message.Header, sir); } break; case "T": if (collection.TweetList.ContainsKey(message.Header)) { throw new Exception($"{message.Header} message not saved: the database already contains the message."); } Tweet tweet = (Tweet)message; collection.TweetList.Add(message.Header, tweet); break; default: break; } string jsonString = JsonSerializer.Serialize(collection, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); File.WriteAllText(ConnectionPath, jsonString); }
private void UpdateTextBoxes() { IdTextBox = _message.Id; TypeTextBox = _message.Type.ToString(); SenderTextBox = _message.Sender; ContentTextBox = _message.Content; if (_message.Type == MessageType.Email) { Email email = (Email)_message; SubjectTextBox = email.Subject; if (!email.IsSIR) { IsSIRTextBox = "No"; SportCentreCodeVisibility = false; NatureOfIncidentVisibility = false; } else { IsSIRTextBox = "Yes"; SIR sir = (SIR)email; SportCentreCodeTextBox = sir.IncidentDetails.SportCentreCode; NatureOfIncidentTextBox = sir.IncidentDetails.NatureOfIncident; } } else { SubjectVisibility = false; IsSIRVisibility = false; SportCentreCodeVisibility = false; NatureOfIncidentVisibility = false; } }
public void SIRTest() { string message = @"09-09-09 Theft My message"; SIR testSIR = new SIR("", "", "ETEST2", "*****@*****.**", "TESTSUBJECT", message, false); }
private void Confirm_SIREmail_Button_Click(object sender, RoutedEventArgs e) { if (ValidateSIREmail()) { string currentID = id.Text; // Gets id from textbox. if (currentID.Length < 9) { // Forces message ID to be 9 characters. string zeros = String.Concat(Enumerable.Repeat("0", 9 - currentID.Length)); currentID = zeros + currentID; } currentID = "E" + currentID; // Makes sure E is added to the message ID for email type. // Collects incident type from drop down menu. ComboBoxItem cmb = (ComboBoxItem)incidentTypeCombo.SelectedItem; string subject = "SIR " + System.DateTime.Now.ToString("dd/MM/yy"); string messageBody = "Cent Code: " + centerCode1.Text + "-" + centerCode2.Text + "-" + centerCode3.Text + " " + "Nature of Incident: " + cmb.Content + " " + messageTextbox.Text; subject += String.Concat(Enumerable.Repeat(" ", 20 - subject.Length)); // Creates SIR email objects to be used later. SIR sir = new SIR(currentID + " " + emailTextbox.Text + " " + subject + messageBody); MessageHolder.currentEmailID++; MessageHolder.AddMessage(currentID, sir); // Confirmation message for user. MessageBox.Show("SIR Email Added!\n" + "Message ID: " + currentID + "\nEmail: " + emailTextbox.Text + "\nSubject: " + subject + "\nIncident: " + cmb.Content + "\nMessage: " + messageTextbox.Text); } }
public void AddToSirList_AddingCorrectSir_ShouldAdd() { Processor processor = new Processor(); SIR message = new SIR("E000000000", "*****@*****.**", "SIR 02/07/1995", "99-99-99", "Theft", "http:\\\\mywebsite.com"); Message processedMessage = processor.ProcessMessage(message); Assert.AreEqual(1, processor.SirList.Count); }
private SIR ProcessSIR(SIR message) { message.Text = SobstituteURL(message.Text); //Add To SIR string[] sirObject = { message.SortCode, message.IncidentType }; SirList.Add(sirObject); return(message); }
/// <summary> /// Attempts to process the message. Throws errors according to the invalid insertions. /// </summary> private void ProcessMessageButtonClick() { try { // Delete any leftover error from process messave MessageErrorTextBlock = string.Empty; OnChanged(nameof(MessageErrorTextBlock)); // Clean any leftover error from saved messages SaveMessageErrorTextBlock = string.Empty; OnChanged(nameof(SaveMessageErrorTextBlock)); // Process the message var message = processor.ProcessMessage(validator.ValidateMessage(MessageHeaderTextBox, MessageBodyTextBox)); // Retain an instance of the last processed message so we can save it later currentMessage = message; // Update lists UpdateLists(message); // Display message in a separate component ProcessedMessageHeaderTextBox = message.Header; ProcessedMessageSenderTextBox = message.Sender; ProcessedMessageTextTextBox = message.Text; OnChanged(nameof(ProcessedMessageHeaderTextBox)); OnChanged(nameof(ProcessedMessageTextTextBox)); OnChanged(nameof(ProcessedMessageSenderTextBox)); // If SIR display appropriate fields, else display "N/A" if (message.MessageType == "E") { Email email = (Email)message; // Display subject ProcessedMessageSubjectTextBox = email.Subject; OnChanged(nameof(ProcessedMessageSubjectTextBox)); if (email.EmailType == "SIR") { SIR sir = (SIR)email; ProcessedMessageSortCodeTextBox = sir.SortCode; ProcessedMessageIncidentTypeTextBox = sir.IncidentType; OnChanged(nameof(ProcessedMessageSortCodeTextBox)); OnChanged(nameof(ProcessedMessageIncidentTypeTextBox)); } else { // Assign Empty Fields ProcessedMessageSortCodeTextBox = string.Empty; ProcessedMessageIncidentTypeTextBox = string.Empty; OnChanged(nameof(ProcessedMessageSortCodeTextBox)); OnChanged(nameof(ProcessedMessageIncidentTypeTextBox)); } } } catch (Exception ex) { MessageErrorTextBlock = ex.Message.ToString(); OnChanged(nameof(MessageErrorTextBlock)); } }
public void analyseMessage(String inputHead, String inputBody) { header = inputHead; body = inputBody; try { Match match = idPattern.Match(header); } catch (System.ArgumentOutOfRangeException e) { System.Console.WriteLine(e.Message); throw new System.ArgumentOutOfRangeException("Error in Header \n Must contain a Character and Nine Digits"); } Char id = header[0]; switch (id) { case 'E': Email newMsg = new Email(header, body); control.Serialiser.serialiseToFile(newMsg); newMsg.analyseMessage(); output = newMsg; if (SIR.checkIfSir(newMsg)) { SIR.populateIncidents(); SIR sir = new SIR(newMsg); output = sir; } // MESSAGE_LIST.Add(output); break; case 'S': SMS newSMSMsg = new SMS(header, body); newSMSMsg.analyseMessage(); control.Serialiser.serialiseToFile(newSMSMsg); output = newSMSMsg; //MESSAGE_LIST.Add(output); break; case 'T': Tweet newTweetMsg = new Tweet(header, body); control.Serialiser.serialiseToFile(newTweetMsg); newTweetMsg.analyseMessage(); output = newTweetMsg; //MESSAGE_LIST.Add(output); break; default: throw new ArgumentOutOfRangeException("Error in ID"); } MESSAGE_LIST.Add(output); control.Serialiser.serialiseToFile(output); }
static void Complete(string filePath, int population, ISeeder seeder) { var random = new Random(0); var paths = new Paths(new Complete(random, population)); var state = new State(population, false, 0.0f); var sir = SIR.Study(paths, state, seeder, 100); sir.Save(filePath, $"# Complete graph of size {population} with seeding {seeder.Description}"); }
static void Complete(string filePath, float discard) { var random = new Random(0); var population = 1000; var paths = new Paths(new Complete(random, population)); var state = new State(population, true, discard); var sir = SIR.Study(paths, state, new FirstOne(), 100); sir.Save(filePath, $"# Complete graph of size {population} discarding {100 * discard}%"); }
public void JSONOutTest() { string SIRmessage = @"09-09-09 Theft My message"; Sms testSMS = new Sms("STEST3", "34958748", "TESTMESSAGE", true); Email testEmail = new Email("ETEST4", "*****@*****.**", "TESTSUBJECT", "TESTMESSAGE", true); Tweet testTweet = new Tweet("TTEST2", "@TEST", "TESTMESSAGE", true); SIR testSIR = new SIR("", "", "ETEST5", "*****@*****.**", "TESTSUBJECT", SIRmessage, true); }
public void SIRNOITest() { string expectedException = "Please provide a valid nature of incident on the second line of the message."; try { string SIRmessage = @"09-09-09 I'M NOT A VALID NATURE OF INCIDENT! My message"; SIR testSIR = new SIR("", "", "ETEST12", "*****@*****.**", "TESTSUBJECT", SIRmessage, false); } catch (Exception ex) { Assert.AreEqual(ex.Message, expectedException); } }
public void SIRSortCodeTest() { string expectedException = "Please include a valid sort code on the first line of the message."; try { string SIRmessage = @"I'M NOT A SORT CODE! Theft My message"; SIR testSIR = new SIR("", "", "ETEST11", "*****@*****.**", "TESTSUBJECT", SIRmessage, false); } catch (Exception ex) { Assert.AreEqual(ex.Message, expectedException); } }
private SIR ProcessSIR(SIR message) { message.Text = SobstituteURL(message.Text); //Add To SIR string sirObject = message.SortCode + " " + message.IncidentType; if (SirList.ContainsKey(sirObject.ToString())) { SirList[sirObject.ToString()] += 1; } else { SirList.Add(sirObject.ToString(), 1); } return(message); }
/// <summary> /// Updates the mention, trend or SIR lists according to the message type. /// </summary> /// <param name="message"></param> private void UpdateLists(Message message) { // Update the relevant lists switch (message.MessageType) { case "E": URLList.Clear(); foreach (var item in processor.QuarantinedLinks) { URLList.Add("Link: " + item.Key.ToString() + "\nCount: " + item.Value.ToString()); } Email email = (Email)message; if (email.EmailType == "SIR") { SIRList.Clear(); SIR sir = (SIR)email; // Loop through SIRList and Add new instances foreach (var item in processor.SirList) { SIRList.Add("Sort Code: " + item.Key.ToString() + "\nCount: " + item.Value.ToString()); } } break; case "T": MentionList.Clear(); TrendList.Clear(); foreach (var item in processor.MentionsList) { MentionList.Add("Mention: " + item.Key.ToString() + "\nCount: " + item.Value.ToString()); } foreach (var item in processor.TrendingList) { TrendList.Add("Trend: " + item.Key.ToString() + "\nCount : " + item.Value.ToString()); } break; default: break; } }
public Message ProcessMessage(Message message) { switch (message.MessageType) { case "S": SMS sms = new SMS(message.Header, message.Sender, message.Text); sms = ProcessSMS(sms); return(sms); case "E": Email email = (Email)message; if (email.EmailType == "SEM") { SEM sem = (SEM)email; sem = ProcessSEM(sem); return(sem); } else if (email.EmailType == "SIR") { SIR sir = (SIR)email; sir = ProcessSIR(sir); return(sir); } else { throw new Exception("Email type not recognized, please make sure you have a valid email type."); } case "T": Tweet tweet = new Tweet(message.Header, message.Sender, message.Text); tweet = ProcessTweet(tweet); return(tweet); default: throw new Exception("Incorrect message type"); } }
//sends messages, checks validation and writes messages on a .csv file private void SendButtonClick() { //lists that hold text found in the text List <string> hashtags = new List <string>(); List <string> mentions = new List <string>(); List <string> quarantined = new List <string>(); List <string> sirs = new List <string>(); Abbreviations abbreviations = new Abbreviations(); //Check if textboxes are empty if (string.IsNullOrWhiteSpace(HeaderTextBox) || (string.IsNullOrWhiteSpace(BodyTextBox))) { MessageBox.Show("Please fill in the header and body textboxes appropriately", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } //Check if the message is an Sms with validations else if ((HeaderTextBox[0] == 'S') && (HeaderTextBox.Length == 10)) { for (int id = 1; id < HeaderTextBox.Length; id++) { if (!char.IsDigit(HeaderTextBox[id])) { MessageBox.Show("Message Id should contain only numbers.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } int findspace = BodyTextBox.IndexOf(" "); string stopAt; //space found then write twitter sender id and continue with message if (findspace > 0) { stopAt = BodyTextBox.Substring(0, findspace); string sms_sender = stopAt; //check for a valid mobile phone number string phoneNumber = @"^(\+[0-9]{15})$"; if (!Regex.IsMatch(sms_sender, phoneNumber) && (sms_sender.Length < 15)) { MessageBox.Show("SMS message body must begin with the senders international phone number.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } //Assign sms sender and body to strings string sms_body = BodyTextBox.Substring(16); //check text length if ((sms_body.Length <= 140) && (sms_body.Length > 0)) { sms_body = abbreviations.ExpandSMS(sms_body); // create new sms message Sms message = new Sms() { Header = HeaderTextBox, Sender = sms_sender, Body = sms_body, MType = "Sms" }; //Save sms message to Json format SaveToFile save = new SaveToFile(); var smslist = save.LoadJsonSms(); smslist.Add(message); string resultJson = JsonConvert.SerializeObject(smslist); File.WriteAllText("sms.json", resultJson); //check if json file exists if (!File.Exists("sms.json")) { MessageBox.Show("Error while saving\n" + save.ErrorCode); } else { MessageBox.Show("Sms Message Send and saved", "Success", MessageBoxButton.OK); save = null; } //prints message MessageBox.Show($"Message type: {message.MType}" + $"\nMessageID: {message.Header}" + $"\nSender: {message.Sender}" + $"\nText: {message.Body}", "Your" + message.MType + "message have been send", MessageBoxButton.OK); } else { MessageBox.Show("Sms text must be up to 140 characters long or empty!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Sms body should start with a valid international phone number", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } //check if it is a Twitter message with validations else if ((HeaderTextBox[0] == 'T') && (HeaderTextBox.Length == 10)) { for (int id = 1; id < HeaderTextBox.Length; id++) { //valid messageID? if (!char.IsDigit(HeaderTextBox[id])) { MessageBox.Show("Message Id type letter must be followed by 9 numberic characters. Please try again!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } //checks if the sender twitterID is typed first in body if (BodyTextBox[0] == '@') { int findspace = BodyTextBox.IndexOf(" "); string stopAt; //space found then write twitter sender id and continue with message if (findspace > 0) { stopAt = BodyTextBox.Substring(0, findspace); string tweet_sender_id = stopAt; string tweetid = @"^@?(\w){1,15}$"; if (Regex.IsMatch(tweet_sender_id, tweetid)) { int space = BodyTextBox.IndexOf(" "); string tweet_body = BodyTextBox.Substring(space + 1); if ((tweet_body.Length <= 140) && (tweet_body.Length > 0)) { tweet_body = abbreviations.ExpandTweet(tweet_body); //save any mentions found in tweet body to a list foreach (Match match in Regex.Matches(input: tweet_body, pattern: @"(?<!\w)@\w+")) { mentions.Add(match.Value); File.AppendAllText("mentions.csv", match.Value + Environment.NewLine); } //save any hashtags found in tweet body to a list foreach (Match match in Regex.Matches(input: tweet_body, pattern: @"(?<!\w)#\w+")) { hashtags.Add(match.Value); File.AppendAllText("hashtags.csv", match.Value + Environment.NewLine); } //add new twitter message Tweet message = new Tweet() { Header = HeaderTextBox, Sender = tweet_sender_id, Body = tweet_body, MType = "Tweet" }; //Save file to Json format SaveToFile save = new SaveToFile(); var tweetlist = save.LoadJsonTweet(); tweetlist.Add(message); string resultJson = JsonConvert.SerializeObject(tweetlist); File.WriteAllText("tweet.json", resultJson); //check if json file exists if (!File.Exists("tweet.json")) { MessageBox.Show("Error while saving\n" + save.ErrorCode); } else { MessageBox.Show("Tweet Message Send and saved", "Success", MessageBoxButton.OK); save = null; } //print message MessageBox.Show($"Message type: {message.MType}" + $"\nMessageID: {message.Header}" + $"\nSender: {message.Sender}" + $"\nText: {message.Body}", "Your" + message.MType + "message have been send", MessageBoxButton.OK); //print hashtag list and mention list var hashtagslist = string.Join(Environment.NewLine, hashtags); MessageBox.Show("Trending List:" + Environment.NewLine + hashtagslist, "Hashtag List", MessageBoxButton.OK, MessageBoxImage.Asterisk); var mentionslist = string.Join(Environment.NewLine, mentions); MessageBox.Show("Mention List:" + Environment.NewLine + mentionslist, "Mention List", MessageBoxButton.OK, MessageBoxImage.Asterisk); } else { MessageBox.Show("Tweet text must be no longer than 140 characters and cant be empty!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Tweet Body must begin with your Twitter ID. @ followed by maximum 15 characters", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Please allow a space after your TwitterID!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Tweet Body must begin with senders TwitterID. (ex. @AlexAn) ", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } //check for email validations else if ((HeaderTextBox[0] == 'E') && (HeaderTextBox.Length == 10)) { for (int id = 1; id < HeaderTextBox.Length; id++) { //check if the 9 characters are digits if (!char.IsDigit(HeaderTextBox[id])) { MessageBox.Show("Message Id should contain only numbers.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } int findspace = BodyTextBox.IndexOf(" "); int findFullStop = BodyTextBox.IndexOf(". "); string stopAtFullStop; string stopAt; //space found then write email address and continue with subject if (findspace > 0) { stopAt = BodyTextBox.Substring(0, findspace); string sender_email = stopAt; if (IsValidEmail(sender_email)) { if (findFullStop > 0) { stopAtFullStop = BodyTextBox.Substring(findspace, findFullStop - findspace); string email_subject = stopAtFullStop; string SIRPattern = "^ +[S|s]+[I|i]+[R|r]+ \\d{2}/\\d{2}/\\d{2}$"; if ((Regex.IsMatch(email_subject, SIRPattern)) && (email_subject.Length <= 20)) { string bodyStartAtFullStop = BodyTextBox.Substring(findFullStop + 1); string email_body = bodyStartAtFullStop; if ((email_body.Length <= 1029) && (email_body.Length > 0)) { foreach (Match match in Regex.Matches(input: email_body, pattern: @"\b\d\d-\d\d-\d\d\b|\bTheft\b")) { sirs.Add(match.Value); File.AppendAllText("sir.csv", match.Value + Environment.NewLine); } // add links found to a list foreach (Match match in Regex.Matches(input: email_body, pattern: @"\b(?:https?://|www\.)\S+\b")) { quarantined.Add(match.Value); File.AppendAllText("quarantined.csv", match.Value + Environment.NewLine); } //replace links found within email body email_body = Regex.Replace(email_body, @"\b(?:https?://|www\.)\S+\b", "<URL Quarantined>"); //creates new email message SIR message = new SIR() { Header = HeaderTextBox, Sender = sender_email, Subject = email_subject, Body = email_body, MType = "SIR" }; //Save email message to json SaveToFile save = new SaveToFile(); var sirlist = save.LoadJsonSir(); sirlist.Add(message); string resultJson = JsonConvert.SerializeObject(sirlist); File.WriteAllText("sir.json", resultJson); //check if file exists if (!File.Exists("sir.json")) { MessageBox.Show("Error while saving\n" + save.ErrorCode); } else { MessageBox.Show("SIR Message Send and saved", "Success", MessageBoxButton.OK); save = null; } //print message MessageBox.Show($"Message type: {message.MType}" + $"\nMessageID: {message.Header}" + $"\nSender: {message.Sender}" + $"\nMessage Subject:{message.Subject}" + $"\nText:{message.Body}", "Your" + message.MType + "message have been send", MessageBoxButton.OK); //print quarantined URLs var quarantinedlist = string.Join(Environment.NewLine, quarantined); MessageBox.Show("Quarantined urls List:" + Environment.NewLine + quarantinedlist, "Quarantined URL(s) added to the List", MessageBoxButton.OK, MessageBoxImage.Asterisk); var sirs_list = string.Join(Environment.NewLine, sirs); MessageBox.Show("Sir List:" + Environment.NewLine + sirs_list, "Sir List", MessageBoxButton.OK, MessageBoxImage.Asterisk); } else { MessageBox.Show("SIR Body text must be no longer than 1028 characters!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else if (email_subject.Length <= 20) { string bodyStartAtFullStop = BodyTextBox.Substring(findFullStop + 1); string email_body = bodyStartAtFullStop; if (email_body.Length <= 1029) { // add links found to a list foreach (Match match in Regex.Matches(input: email_body, pattern: @"\b(?:https?://|www\.)\S+\b")) { quarantined.Add(match.Value); File.AppendAllText("quarantined.csv", match.Value + Environment.NewLine); } //replace links found within email body email_body = Regex.Replace(email_body, @"\b(?:https?://|www\.)\S+\b", "<URL Quarantined>"); //creates new email message Email message = new Email() { Header = HeaderTextBox, Sender = sender_email, Subject = email_subject, Body = email_body, MType = "Email" }; //Save file to Json format SaveToFile save = new SaveToFile(); var emaillist = save.LoadJsonEmail(); emaillist.Add(message); string resultJson = JsonConvert.SerializeObject(emaillist); File.WriteAllText("email.json", resultJson); //check if file exists if (!File.Exists("email.json")) { MessageBox.Show("Error while saving\n" + save.ErrorCode); } else { MessageBox.Show("Email Message Send and saved", "Success", MessageBoxButton.OK); save = null; } //print message MessageBox.Show($"Message type: {message.MType}" + $"\nMessageID: {message.Header}" + $"\nSender: {message.Sender}" + $"\nMessage Subject:{message.Subject}" + $"\nText:{message.Body}", "Your" + message.MType + "message have been send", MessageBoxButton.OK); //print quarantined URLs var quarantinedlist = string.Join(Environment.NewLine, quarantined); MessageBox.Show("Quarantined urls List:" + Environment.NewLine + quarantinedlist, "Quarantined URLs List", MessageBoxButton.OK, MessageBoxImage.Asterisk); } else { MessageBox.Show("Email Body text must be no longer than 1028 characters!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Email Subject must be no longer than 20 characters!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Please mind that subject should be less than 20 characters long, and remember to seperate subject and message with a full stop and a space!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Email Body must begin with a valid Email address.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Email Body must begin with a valid Email address followed by a space.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("MessageID is not valid. Please enter a valid messageID maximum 10 characters long.\n" + "First character will indicate the message type and the rest must be numeric characters.\n" + "ex. S123456789 for SMS, T876543210 for Tweets, E147258360 for Emails!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } }
//Method to add an object of type SIR to the observable collection SIRlist. public static void addSir(SIR sirList) { SIRlist.Add(sirList); }
private void emailsubmit_Click(object sender, RoutedEventArgs e) { //Create new instance of the email class. Email email = new Email(); //Retrieve the email message header from the startup window. email.messageHeader = ((MainWindow)Application.Current.MainWindow).emailid.messageHeader; email.Sender = senderemail.Text; email.messageText = emailmsg.Text; email.Subject = subject.Text; //creates a list input of type string which contains each word in the email message as a seperate entry. List <string> input = new List <string>(email.messageText.Split(null)); //creates a list inputsubject of type string which contatins each word in the subject as a seperate entry. List <string> inputsubject = new List <string>(email.Subject.Split(null)); //Creates new instance of the observable collection SIRlist. ObservableCollection <SIR> SIRlist = new ObservableCollection <SIR>(); //If email is valid add email to the list emails. if (email.Sender.Contains('@') && email.Sender.Contains('.')) { emails.Add(email); } int counter = input.Count; for (int i = 0; i < email.messageText.Length; i++) { if (counter == i) { break; } //This checks for any links contained within the email and replaces them with the required quarentine message. if (input[i].Contains("https://") || input[i].Contains("http://") || input[i].Contains("www.")) { string url = input.ToString(); url = "<" + "URL Quarantined" + ">"; input.Insert(i + 1, url); input.RemoveAt(i); emaillstbox.Items.Add(string.Join("", input)); } } bool hasdate = false; for (int i = 0; i < email.Subject.Length; i++) { //Checks if the email is a significant incident report and that it contains the date of the incident within the email subject try { if (inputsubject.Contains("SIR")) { DateTime.Parse(inputsubject[1]); hasdate = true; } } catch { } } //If the email subject contains "SIR" followed by a valid date then the SIR sortcode and incident is saved. if (hasdate == true) { SIR sir = new SIR(); sir.sortCode = input[2]; bool hassix = false; if (input.Count == 7) { sir.incidentName = input[6]; hassix = true; emaillstbox.Items.Add(string.Join(" ", input)); } if (hassix == false) { //For any incident that contains 2 words it will correctly identify this and display the whole incident name. if (input[7].Equals("Attack") || input[7].Equals("Theft") || input[7].Equals("Abuse") || input[7].Equals("Threat") || input[7].Equals("Incident") || input[7].Equals("Loss")) { sir.incidentName = input[6].ToString() + " " + input[7].ToString(); emaillstbox.Items.Add(string.Join(" ", input)); } } //Adds the incedent report to the SIR list. Methods.addSir(sir); //Displays the observable collection SIRlist in the datagrid. datagrid.ItemsSource = Methods.getsir(); //Appends the email to the JSON file "output.json" Email serealise = new Email(); serealise.messageHeader = ((MainWindow)Application.Current.MainWindow).emailid.messageHeader; serealise.Sender = senderemail.Text; serealise.messageText = string.Join(" ", input.ToArray()); using (StreamWriter writer = File.AppendText(@"output.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, serealise); } } }
public Message AddNewMessage(RawMessage message) { if (message.IsValid()) { // New Message and Message Type Message newMessage = GetMessageWithType(message); if (newMessage != null) { // Id newMessage.Id = message.Header; // Sender and Content var(sender, content) = ExtractSenderAndContent(message.Body); newMessage.Sender = sender; newMessage.Content = content; // type-specific functions switch (newMessage.Type) { case MessageType.Email: Email email = (Email)newMessage; email.SetSubjectContentAndSIRflag(); // remaining Email properties var quarantinedUrls = email.SterilizeContentFromUrls(); _statisticsService.AddQuarantinedUrls(quarantinedUrls); if (email.IsSIR) { SIR sir = (SIR)newMessage; sir.SetSportCentreCodeAndNatureOfIncident(); // remaining SIR properties _statisticsService.AddSIRs(sir.IncidentDetails); } break; case MessageType.Sms: Sms sms = (Sms)newMessage; sms.SanitizeContent(_dataProvider.ImportAbbreviations()); break; case MessageType.Tweet: Tweet tweet = (Tweet)newMessage; tweet.SanitizeContent(_dataProvider.ImportAbbreviations()); tweet.CheckContentForHashtagsAndMentions(); if (tweet.Hashtags != null && tweet.Hashtags.Count > 0) { _statisticsService.AddHashtags(tweet.Hashtags); } if (tweet.Mentions != null && tweet.Mentions.Count > 0) { _statisticsService.AddMentions(tweet.Mentions); } break; } ; // export msg to a file if (_dataProvider.ExportMessage(newMessage)) { _statisticsService.UpdateStatistics(); // return fully-processed message to the ViewModel return(newMessage); } } } return(null); }