public async Task ProcessReceivedMessagesAsync()
        {
            if (_packetMessagesReceived.Count() > 0)
            {
                bool updateBulletinList = false;
                foreach (PacketMessage packetMessageOutpost in _packetMessagesReceived)
                {
                    FormControlBase formControl = new MessageControl();
                    // test for packet form!!
                    PacketMessage pktMsg = new PacketMessage()
                    {
                        BBSName       = packetMessageOutpost.BBSName,
                        TNCName       = packetMessageOutpost.TNCName,
                        MessageSize   = packetMessageOutpost.MessageSize,
                        MessageNumber = packetMessageOutpost.MessageNumber,
                        ReceivedTime  = packetMessageOutpost.ReceivedTime,
                        CreateTime    = DateTime.Now,
                        Area          = packetMessageOutpost.Area,
                        // Save the original message for post processing (tab characters are lost in the displayed message)
                        MessageBody   = packetMessageOutpost.MessageBody,
                        MessageState  = MessageState.Locked,
                        MessageOpened = false,
                        MessageOrigin = MessageOriginHelper.MessageOrigin.Received,
                    };
                    string[] msgLines = packetMessageOutpost.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);
                    // Check if base64 encoded
                    int  startOfMessage  = 0;
                    int  startOfMessage1 = 0;
                    int  startOfMessage2 = 0;
                    int  endOfMessage    = 0;
                    bool dateFound       = false;
                    bool subjectFound    = false;
                    for (int k = 0; k < msgLines.Length; k++)
                    {
                        if (msgLines[k].StartsWith("Date:"))
                        {
                            dateFound       = true;
                            startOfMessage1 = k + 1;
                        }
                        if (msgLines[k].StartsWith("Subject:"))
                        {
                            subjectFound    = true;
                            startOfMessage2 = k + 1;
                        }
                        if (dateFound && subjectFound)
                        {
                            break;
                        }
                    }
                    startOfMessage = Math.Max(startOfMessage1, startOfMessage2);
                    endOfMessage   = msgLines.Length - 1;
                    try
                    {
                        // Process encoded message
                        string message = "";
                        for (int j = startOfMessage; j <= endOfMessage; j++)
                        {
                            message += msgLines[j];
                        }
                        const string outpostEncodedMarker = "!B64!";
                        if (message.StartsWith(outpostEncodedMarker))
                        {
                            message = message.Substring(outpostEncodedMarker.Length);
                        }
                        byte[] messageText   = Convert.FromBase64String(message);
                        string decodedString = Encoding.UTF8.GetString(messageText);

                        List <string> msgLinesList = msgLines.ToList();
                        msgLinesList.RemoveRange(startOfMessage, endOfMessage - startOfMessage + 1);
                        string[] decodedMsgLines = decodedString.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
                        msgLinesList.InsertRange(startOfMessage, decodedMsgLines);
                        msgLines = msgLinesList.ToArray();
                        _logHelper.Log(LogLevel.Info, "This message was an encoded message");
                    }
                    catch (FormatException)
                    {
                        // Not an encoded message
                        //_logHelper.Log(LogLevel.Info, "Not an encoded message");
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        _logHelper.Log(LogLevel.Error, "Argument out of range");
                    }
                    bool toFound = false;
                    subjectFound = false;
                    string prefix = "";
                    for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
                    {
                        if (msgLines[i].StartsWith("From:"))
                        {
                            pktMsg.MessageFrom = NormalizeEmailField(msgLines[i].Substring(6));
                        }
                        else if (!toFound && msgLines[i].StartsWith("To:"))
                        {
                            pktMsg.MessageTo = NormalizeEmailField(msgLines[i].Substring(4));
                            toFound          = true;
                        }
                        else if (msgLines[i].StartsWith("Cc:"))
                        {
                            pktMsg.MessageTo += (", " + msgLines[i].Substring(4));
                            while (msgLines[i + 1].Length == 0)
                            {
                                i++;
                            }
                            if (msgLines[i + 1][0] == ' ')
                            {
                                pktMsg.MessageTo += msgLines[i + 1].TrimStart(new char[] { ' ' });
                            }
                        }
                        else if (!subjectFound && msgLines[i].StartsWith("Subject:"))
                        {
                            pktMsg.Subject = msgLines[i].Substring(9);
                            if (pktMsg.Subject[3] == '-')
                            {
                                prefix = pktMsg.Subject.Substring(0, 3);
                            }
                            //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                            subjectFound = true;
                        }
                        else if (msgLines[i].StartsWith("Date:"))
                        {
                            pktMsg.JNOSDate = DateTime.Parse(msgLines[i].Substring(10, 21));
                        }

                        else if (msgLines[i].StartsWith("# FORMFILENAME:"))
                        {
                            string html     = ".html";
                            string formName = msgLines[i].Substring(16).TrimEnd(new char[] { ' ' });
                            formName           = formName.Substring(0, formName.Length - html.Length);
                            pktMsg.PacFormName = formName;

                            formControl = FormsViewModel.CreateFormControlInstance(pktMsg.PacFormName);
                            if (formControl is null)
                            {
                                _logHelper.Log(LogLevel.Error, $"Form {pktMsg.PacFormName} not found");
                                await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            pktMsg.SenderMessageNumber = FormControlBase.GetOutpostValue(msgLines[i + 1]);
                            pktMsg.FormProvider        = FormProviders.PacForm; // TODO update with real provider
                            //pktMsg.FormProvider = formControl.FormProvider;    // TODO update with real provider
                            break;
                        }
                        else if (msgLines[i].StartsWith("#T:"))
                        {
                            string[] fileNameString = msgLines[i].Split(new char[] { ' ', '.' }, StringSplitOptions.RemoveEmptyEntries);
                            string   formName       = fileNameString[1];
                            formName.Trim();
                            pktMsg.PacFormName = formName;

                            formControl = FormsViewModel.CreateFormControlInstance(pktMsg.PacFormName);
                            if (formControl is null)
                            {
                                _logHelper.Log(LogLevel.Error, $"Form {pktMsg.PacFormName} not found");
                                await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            pktMsg.SenderMessageNumber = FormControlBase.GetOutpostValue(msgLines[i + 2]);
                            pktMsg.FormProvider        = FormProviders.PacItForm;
                            break;
                        }
                    }

                    //pktMsg.MessageNumber = GetMessageNumberPacket();		// Filled in BBS connection
                    pktMsg.PacFormType = formControl.PacFormType;
                    //pktMsg.PacFormName = formControl.GetPacFormName();
                    pktMsg.PacFormName     = formControl.FormControlName;
                    pktMsg.FormControlType = formControl.FormControlType;
                    pktMsg.FormFieldArray  = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines, pktMsg.FormProvider);
                    //if (pktMsg.ReceivedTime != null)
                    //{
                    //	DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                    //}
                    if (!pktMsg.CreateFileName())
                    {
                        _logHelper.Log(LogLevel.Error, $"Error in Create FileName(), {pktMsg.MessageNumber}, {pktMsg.PacFormType}");
                        throw new Exception();
                    }

                    AddressBook.Instance.UpdateLastUsedBBS(pktMsg.MessageFrom, prefix);
                    _logHelper.Log(LogLevel.Info, $"Message number {pktMsg.MessageNumber} received");

                    // If the received message is a delivery confirmation, update receivers message number in the original sent message
                    if (!string.IsNullOrEmpty(pktMsg.Subject) && pktMsg.Subject.Contains("DELIVERED:"))
                    {
                        await ProcessMessagesMarkedDeliveredAsync(pktMsg);
                    }
                    pktMsg.Save(SharedData.ReceivedMessagesFolder.Path);

                    if (!string.IsNullOrEmpty(pktMsg.Area))
                    {
                        updateBulletinList |= true;     // Does this work with xscevent

                        if (pktMsg.Area.ToLower() == "xscperm")
                        {
                            if (pktMsg.Subject.ToLower().Contains("scco packet frequencies"))
                            {
                                await BBSDefinitions.CreateFromBulletinAsync(pktMsg);
                            }
                            else if (pktMsg.Subject.ToLower().Contains("scco packet tactical calls"))
                            {
                                await TacticalCallsigns.CreatePacketTacticalCallsignsFromBulletinAsync(pktMsg);
                            }
                        }
                    }

                    // Do printing if requested
                    if (!string.IsNullOrEmpty(pktMsg.Subject) && !pktMsg.Subject.Contains("DELIVERED:") &&
                        string.IsNullOrEmpty(pktMsg.Area) && SettingsViewModel.Instance.PrintReceivedMessages)
                    {
                        _logHelper.Log(LogLevel.Info, $"Message number {pktMsg.MessageNumber} to be printed");

                        pktMsg.Save(SharedData.PrintMessagesFolder.Path);

                        SettingsViewModel settingsViewModel = SettingsViewModel.Instance;

                        PrintQueue.Instance.AddToPrintQueue(pktMsg.FileName, settingsViewModel.ReceivedCopyNamesAsArray());

                        // Test
                        await PrintQueue.Instance.PrintToDestinationsAsync();

                        //await Singleton<PrintQueue>.Instance.BackgroundPrintingTrigger.RequestAsync();
                    }
                }
                //RefreshDataGrid();      // Display newly added messages
                if (updateBulletinList)
                {
                    await MainViewModel.Instance.UpdateDownloadedBulletinsAsync();
                }
            }
        }
Пример #2
0
        public void CreatePacketMessageFromMessageAsync(ref PacketMessage pktMsg)
        {
            FormControlBase formControl = new MessageControl();

            // test for packet form!!
            //pktMsg.PacFormType = PacForms.Message;
            //pktMsg.PacFormName = "SimpleMessage";
            // Save the original message for post processing (tab characters are lost in the displayed message)
            string[] msgLines = pktMsg.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);

            bool subjectFound = false;

            for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
            {
                if (msgLines[i].StartsWith("Date:"))
                {
                    string startpos = new string(new char[] { 'D', 'a', 't', 'e', ':', ' ' });
                    pktMsg.JNOSDate        = DateTime.Parse(msgLines[i].Substring(startpos.Length));
                    pktMsg.JNOSDateDisplay = $"{pktMsg.JNOSDate.Month:d2}/{pktMsg.JNOSDate.Date:d2}/{pktMsg.JNOSDate.Year - 2000:d2} {pktMsg.JNOSDate.Hour:d2}:{pktMsg.JNOSDate.Minute:d2}";
                }
                else if (msgLines[i].StartsWith("From:"))
                {
                    pktMsg.MessageFrom = msgLines[i].Substring(6);
                }
                else if (msgLines[i].StartsWith("To:"))
                {
                    pktMsg.MessageTo = msgLines[i].Substring(4);
                }
                else if (msgLines[i].StartsWith("Cc:"))
                {
                    pktMsg.MessageTo += (", " + msgLines[i].Substring(4));
                    while (msgLines[i + 1].Length == 0)
                    {
                        i++;
                    }
                    if (msgLines[i + 1][0] == ' ')
                    {
                        pktMsg.MessageTo += msgLines[i + 1].TrimStart(new char[] { ' ' });
                    }
                }
                else if (!subjectFound && msgLines[i].StartsWith("Subject:"))
                {
                    pktMsg.Subject = msgLines[i].Substring(9);
                    //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                    subjectFound = true;
                }
                else if (msgLines[i].StartsWith("# FORMFILENAME:"))
                {
                    string html     = ".html";
                    string formName = msgLines[i].Substring(16).TrimEnd(new char[] { ' ' });
                    formName           = formName.Substring(0, formName.Length - html.Length);
                    pktMsg.PacFormType = formName;

                    formControl = Views.FormsPage.CreateFormControlInstance(pktMsg.PacFormType);
                    if (formControl == null)
                    {
                        //await Utilities.ShowMessageDialogAsync($"Form {pktMsg.PacFormName} not found");
                        log.Error($"Form {pktMsg.PacFormName} not found");
                        return;
                    }
                    break;
                }
            }
            pktMsg.PacFormName = formControl.PacFormFileName;
            //pktMsg.PacFormType = formControl.PacFormType;
            //pktMsg.MessageNumber = packetMessage.MessageNumber;
            pktMsg.FormFieldArray = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines);
            //pktMsg.ReceivedTime = packetMessage.ReceivedTime;
            pktMsg.CreateFileName();
            string fileFolder = Views.MainPage._receivedMessagesFolder.Path;

            pktMsg.Save(fileFolder);

            //log.Info($"Message number {pktMsg.MessageNumber} received");
            LogHelper(LogLevel.Info, $"Message number {pktMsg.MessageNumber} converted and saved");

            // If the received message is a delivery confirmation, update receivers message number in the original sent message
            //if (!string.IsNullOrEmpty(pktMsg.Subject) && pktMsg.Subject.Contains("DELIVERED:"))
            //{
            //	var formField = pktMsg.FormFieldArray.FirstOrDefault(x => x.ControlName == "messageBody");
            //	if (formField.ControlContent.Contains("!LMI!"))
            //	{
            //		string[] searchStrings = new string[] { "Subject: ", "was delivered on ", "Recipient's Local Message ID: " };
            //		DateTime receiveTime = DateTime.Now;
            //		string receiversMessageId = "", sendersMessageId = "";
            //		var messageLines = formField.ControlContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            //		foreach (string line in messageLines)
            //		{
            //			if (line.Contains(searchStrings[0]))
            //			{
            //				int indexOfUnderscore = line.IndexOf('_');
            //				int indexOfDelivered = line.IndexOf(searchStrings[0]);
            //				if (indexOfUnderscore >= 0)
            //				{
            //					sendersMessageId = line.Substring(indexOfDelivered + searchStrings[0].Length, indexOfUnderscore - (indexOfDelivered + searchStrings[0].Length));
            //				}
            //			}
            //			else if (line.Contains(searchStrings[1]))
            //			{
            //				int indexOfDeliveryTime = line.IndexOf(searchStrings[1]);
            //				if (indexOfDeliveryTime >= 0)
            //				{
            //					string s = line.Substring(indexOfDeliveryTime + searchStrings[1].Length);
            //					receiveTime = DateTime.Parse(s);
            //				}
            //			}
            //			else if (line.Contains(searchStrings[2]))
            //			{
            //				receiversMessageId = line.Substring(line.IndexOf(searchStrings[2]) + searchStrings[2].Length);
            //			}
            //		}

            //		List<string> fileTypeFilter = new List<string>() { ".xml" };
            //		QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

            //		// Get the files in the user's archive folder
            //		StorageFileQueryResult results = MainPage._sentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
            //		// Iterate over the results
            //		IReadOnlyList<StorageFile> files = await results.GetFilesAsync();
            //		foreach (StorageFile file in files)
            //		{
            //			// Update sent form with receivers message number and receive time
            //			if (file.Name.Contains(sendersMessageId))
            //			{
            //				PacketMessage message = PacketMessage.Open(file);
            //				if (packetMessage.MessageNumber == sendersMessageId)
            //				{
            //					formField = packetMessage.FormFieldArray.FirstOrDefault(x => x.ControlName == "receiverMsgNo");
            //					if (formField != null)
            //					{
            //						formField.ControlContent = receiversMessageId;
            //					}
            //					packetMessage.ReceivedTime = receiveTime;
            //					if (receiveTime != null)
            //					{
            //						packetMessage.ReceivedTimeDisplay = $"{receiveTime.Month:d2}/{receiveTime.Date:d2}/{receiveTime.Year - 2000:d2} {receiveTime.Hour:d2}:{receiveTime.Minute:d2}";
            //					}
            //					packetMessage.Save(MainPage._sentMessagesFolder.Path);
            //					break;
            //				}
            //			}
            //		}
            //	}
            //}

            return;
        }
        public async Task CreatePacketMessageFromMessageAsync(PacketMessage pktMsg)
        {
            FormControlBase formControl = new MessageControl();

            // test for packet form!!
            //pktMsg.PacFormType = PacForms.Message;
            //pktMsg.PacFormName = "SimpleMessage";
            // Save the original message for post processing (tab characters are lost in the displayed message)
            string[] msgLines = pktMsg.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);

            bool subjectFound = false;

            for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
            {
                if (msgLines[i].StartsWith("Date:"))
                {
                    string startpos = "Date: ";
                    bool   success  = DateTime.TryParse(msgLines[i].Substring(startpos.Length), out DateTime JNOSDate);
                    pktMsg.JNOSDate = (success ? JNOSDate : (DateTime?)null);
                }
                else if (msgLines[i].StartsWith("From:"))
                {
                    pktMsg.MessageFrom = msgLines[i].Substring(6);
                }
                else if (msgLines[i].StartsWith("To:"))
                {
                    pktMsg.MessageTo = msgLines[i].Substring(4);
                }
                else if (msgLines[i].StartsWith("Cc:"))
                {
                    pktMsg.MessageTo += (", " + msgLines[i].Substring(4));
                    while (msgLines[i + 1].Length == 0)
                    {
                        i++;
                    }
                    if (msgLines[i + 1][0] == ' ')
                    {
                        pktMsg.MessageTo += msgLines[i + 1].TrimStart(new char[] { ' ' });
                    }
                }
                else if (!subjectFound && msgLines[i].StartsWith("Subject:"))
                {
                    pktMsg.Subject = msgLines[i].Substring(9);
                    //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                    subjectFound = true;
                }
                else if (msgLines[i].StartsWith("# FORMFILENAME:"))
                {
                    string html     = ".html";
                    string formName = msgLines[i].Substring(16).TrimEnd(new char[] { ' ' });
                    formName           = formName.Substring(0, formName.Length - html.Length);
                    pktMsg.PacFormName = formName;

                    formControl = FormsViewModel.CreateFormControlInstance(pktMsg.PacFormName);
                    if (formControl is null)
                    {
                        _logHelper.Log(LogLevel.Error, $"Form {pktMsg.PacFormName} not found");
                        await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {pktMsg.PacFormName} not found");

                        return;
                    }
                    break;
                    //    pktMsg.FormProviderIndex = 0;
                }
            }

            //formControl.FormProvider = FormProviders.PacForm;
            pktMsg.FormProvider    = FormProviders.PacForm;     // TODO update with real provider
            pktMsg.FormControlType = formControl.FormControlType;

            //pktMsg.PacFormName = formControl.GetPacFormName();
            pktMsg.PacFormName    = formControl.FormControlName;
            pktMsg.FormFieldArray = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines, pktMsg.FormProvider);
            //pktMsg.ReceivedTime = packetMessage.ReceivedTime;
            if (!pktMsg.CreateFileName())
            {
                throw new Exception();
            }
            string fileFolder = SharedData.ReceivedMessagesFolder.Path;

            pktMsg.Save(fileFolder);

            _logHelper.Log(LogLevel.Info, $"Message number {pktMsg.MessageNumber} converted and saved");

            return;
        }
Пример #4
0
        public async void ProcessReceivedMessagesAsync()
        {
            if (_packetMessagesReceived.Count() > 0)
            {
                foreach (PacketMessage packetMessageOutpost in _packetMessagesReceived)
                {
                    FormControlBase formControl = new MessageControl();
                    // test for packet form!!
                    PacketMessage pktMsg = new PacketMessage()
                    {
                        //pktMsg.PacFormType = PacForms.Message;
                        PacFormName = "SimpleMessage",
                        BBSName     = packetMessageOutpost.BBSName,
                        TNCName     = packetMessageOutpost.TNCName,
                        MessageSize = packetMessageOutpost.MessageSize,
                        Area        = packetMessageOutpost.Area,
                        // Save the original message for post processing (tab characters are lost in the displayed message)
                        MessageBody = packetMessageOutpost.MessageBody,
                        //MessageReadOnly = true
                    };
                    string[] msgLines = packetMessageOutpost.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);

                    bool subjectFound = false;
                    for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
                    {
                        if (msgLines[i].StartsWith("Date:"))
                        {
                            pktMsg.JNOSDate        = DateTime.Parse(msgLines[i].Substring(10, 21));
                            pktMsg.JNOSDateDisplay = $"{pktMsg.JNOSDate.Month:d2}/{pktMsg.JNOSDate.Date:d2}/{pktMsg.JNOSDate.Year - 2000:d2} {pktMsg.JNOSDate.Hour:d2}:{pktMsg.JNOSDate.Minute:d2}";
                        }
                        else if (msgLines[i].StartsWith("From:"))
                        {
                            pktMsg.MessageFrom = msgLines[i].Substring(6);
                        }
                        else if (msgLines[i].StartsWith("To:"))
                        {
                            pktMsg.MessageTo = msgLines[i].Substring(4);
                        }
                        else if (msgLines[i].StartsWith("Cc:"))
                        {
                            pktMsg.MessageTo += (", " + msgLines[i].Substring(4));
                            while (msgLines[i + 1].Length == 0)
                            {
                                i++;
                            }
                            if (msgLines[i + 1][0] == ' ')
                            {
                                pktMsg.MessageTo += msgLines[i + 1].TrimStart(new char[] { ' ' });
                            }
                        }
                        else if (!subjectFound && msgLines[i].StartsWith("Subject:"))
                        {
                            pktMsg.Subject = msgLines[i].Substring(9);
                            //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                            subjectFound = true;
                        }
                        else if (msgLines[i].StartsWith("# FORMFILENAME:"))
                        {
                            string html     = ".html";
                            string formName = msgLines[i].Substring(16).TrimEnd(new char[] { ' ' });
                            formName           = formName.Substring(0, formName.Length - html.Length);
                            pktMsg.PacFormType = formName;

                            //formControl = Views.FormsPage.CreateFormControlInstanceFromFileName(pktMsg.PacFormName);
                            formControl = Views.FormsPage.CreateFormControlInstance(pktMsg.PacFormType);
                            if (formControl == null)
                            {
                                await Utilities.ShowMessageDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            break;
                        }
                    }

                    //pktMsg.MessageNumber = GetMessageNumberPacket();		// Filled in BBS connection
                    pktMsg.PacFormType    = formControl.PacFormType;
                    pktMsg.MessageNumber  = packetMessageOutpost.MessageNumber;
                    pktMsg.FormFieldArray = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines);
                    pktMsg.ReceivedTime   = packetMessageOutpost.ReceivedTime;
                    if (pktMsg.ReceivedTime != null)
                    {
                        DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                        pktMsg.ReceivedTimeDisplay = $"{dateTime.Month:d2}/{dateTime.Date:d2}/{dateTime.Year - 2000:d2} {dateTime.Hour:d2}:{dateTime.Minute:d2}";
                    }
                    if (pktMsg.ReceivedTime != null)
                    {
                        DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                        pktMsg.ReceivedTimeDisplay = $"{dateTime.Month:d2}/{dateTime.Date:d2}/{dateTime.Year - 2000:d2} {dateTime.Hour:d2}:{dateTime.Minute:d2}";
                    }
                    pktMsg.CreateFileName();
                    string fileFolder = Views.MainPage._receivedMessagesFolder.Path;
                    pktMsg.Save(fileFolder);

                    //log.Info($"Message number {pktMsg.MessageNumber} received");
                    LogHelper(LogLevel.Info, $"Message number {pktMsg.MessageNumber} received");

                    // If the received message is a delivery confirmation, update receivers message number in the original sent message
                    if (!string.IsNullOrEmpty(pktMsg.Subject) && pktMsg.Subject.Contains("DELIVERED:"))
                    {
                        var formField = pktMsg.FormFieldArray.FirstOrDefault(x => x.ControlName == "messageBody");
                        if (formField.ControlContent.Contains("!LMI!"))
                        {
                            string[] searchStrings = new string[] { "Subject: ", "was delivered on ", "Recipient's Local Message ID: " };
                            DateTime receiveTime = DateTime.Now;
                            string   receiversMessageId = "", sendersMessageId = "";
                            var      messageLines = formField.ControlContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string line in messageLines)
                            {
                                if (line.Contains(searchStrings[0]))
                                {
                                    int indexOfUnderscore = line.IndexOf('_');
                                    int indexOfDelivered  = line.IndexOf(searchStrings[0]);
                                    if (indexOfUnderscore >= 0)
                                    {
                                        sendersMessageId = line.Substring(indexOfDelivered + searchStrings[0].Length, indexOfUnderscore - (indexOfDelivered + searchStrings[0].Length));
                                    }
                                }
                                else if (line.Contains(searchStrings[1]))
                                {
                                    int indexOfDeliveryTime = line.IndexOf(searchStrings[1]);
                                    if (indexOfDeliveryTime >= 0)
                                    {
                                        string s = line.Substring(indexOfDeliveryTime + searchStrings[1].Length);
                                        receiveTime = DateTime.Parse(s);
                                    }
                                }
                                else if (line.Contains(searchStrings[2]))
                                {
                                    receiversMessageId = line.Substring(line.IndexOf(searchStrings[2]) + searchStrings[2].Length);
                                }
                            }

                            //DirectoryInfo diSentFolder = new DirectoryInfo(Views.MainPage._sentMessagesFolder.Path);
                            //foreach (FileInfo fi in diSentFolder.GetFiles())
                            List <string> fileTypeFilter = new List <string>()
                            {
                                ".xml"
                            };
                            //fileTypeFilter.Add(".xml");
                            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

                            // Get the files in the user's archive folder
                            StorageFileQueryResult results = MainPage._sentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
                            // Iterate over the results
                            IReadOnlyList <StorageFile> files = await results.GetFilesAsync();

                            foreach (StorageFile file in files)
                            {
                                // Update sent form with receivers message number and receive time
                                if (file.Name.Contains(sendersMessageId))
                                {
                                    PacketMessage packetMessage = PacketMessage.Open(file);
                                    if (packetMessage.MessageNumber == sendersMessageId)
                                    {
                                        formField = packetMessage.FormFieldArray.FirstOrDefault(x => x.ControlName == "receiverMsgNo");
                                        if (formField != null)
                                        {
                                            formField.ControlContent = receiversMessageId;
                                        }
                                        packetMessage.ReceivedTime = receiveTime;
                                        if (receiveTime != null)
                                        {
                                            packetMessage.ReceivedTimeDisplay = $"{receiveTime.Month:d2}/{receiveTime.Date:d2}/{receiveTime.Year - 2000:d2} {receiveTime.Hour:d2}:{receiveTime.Minute:d2}";
                                        }
                                        packetMessage.Save(MainPage._sentMessagesFolder.Path);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                //RefreshDataGrid();      // Display newly added messages
            }
        }