public async Task BBSConnectAsync2()
        {
            (string bbsName, string tncName, string MessageFrom) = Utilities.GetProfileDataBBSStatusChecked();
            //BBSData bbs = PacketSettingsViewModel.Instance.BBSFromSelectedProfile;
            BBSData bbs = BBSDefinitions.Instance.BBSDataArray.Where(bBS => bBS.Name == bbsName).FirstOrDefault();
            //TNCDevice tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == tncName).FirstOrDefault();
            TNCDevice tncDevice = PacketSettingsViewModel.Instance.TNCFromSelectedProfile;

            //if (tncName.Contains(SharedData.EMail) && tncDevice is null)
            //{
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name.Contains(SharedData.EMail)).FirstOrDefault();
            //}

            _logHelper.Log(LogLevel.Info, "Start a new send/receive session");
            // Collect messages to be sent
            _packetMessagesToSend.Clear();
            List <string> fileTypeFilter = new List <string>()
            {
                ".xml"
            };
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

            // Get the files in the Outbox folder
            StorageFileQueryResult results = SharedData.UnsentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
            // Iterate over the results
            IReadOnlyList <StorageFile> unsentFiles = await results.GetFilesAsync();

            foreach (StorageFile file in unsentFiles)
            {
                // Add Outpost message format by Filling the MessageBody field in packetMessage.
                PacketMessage packetMessage = PacketMessage.Open(file.Path);
                if (packetMessage is null)
                {
                    _logHelper.Log(LogLevel.Error, $"Error opening message file {file.Path}");
                    continue;
                }

                // messages that are opened for editing will not be sent until editing is finished
                if (packetMessage.MessageState == MessageState.Edit)
                {
                    continue;
                }

                // Moved to send button processing
                //DateTime now = DateTime.Now;

                //var operatorDateField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorDate").FirstOrDefault();
                //if (operatorDateField != null)
                //{
                //    operatorDateField.ControlContent = $"{now.Month:d2}/{now.Day:d2}/{(now.Year):d4}";
                //}
                //var operatorTimeField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorTime").FirstOrDefault();
                //if (operatorTimeField != null)
                //    operatorTimeField.ControlContent = $"{now.Hour:d2}:{now.Minute:d2}";

                FormControlBase formControl = FormsViewModel.CreateFormControlInstance(packetMessage.PacFormName);
                if (formControl is null)
                {
                    _logHelper.Log(LogLevel.Error, $"Could not create an instance of {packetMessage.PacFormName}");
                    await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {packetMessage.PacFormName} not found");

                    continue;
                }
                packetMessage.MessageBody = formControl.CreateOutpostData(ref packetMessage);
                packetMessage.UpdateMessageSize();
                // Save updated message
                packetMessage.Save(SharedData.UnsentMessagesFolder.Path);

                _packetMessagesToSend.Add(packetMessage);
            }
            _logHelper.Log(LogLevel.Info, $"Send messages count: {_packetMessagesToSend.Count}");

            if (tncDevice.Name.Contains(PublicData.EMail) && _packetMessagesToSend.Count == 0)
            {
                return;
            }
            List <PacketMessage> messagesSentAsEMail = new List <PacketMessage>();

            // Send email messages
            foreach (PacketMessage packetMessage in _packetMessagesToSend)
            {
                //tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == packetMessage.TNCName).FirstOrDefault();
                //bbs = BBSDefinitions.Instance.BBSDataList.Where(bBS => bBS.Name == packetMessage.BBSName).FirstOrDefault();

                //TNCInterface tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                // Send as email if a TNC is not reachable, or if message is defined as an e-mail message
                if (tncDevice.Name.Contains(PublicData.EMail))
                {
                    try
                    {
                        // Mark message as sent by email
                        packetMessage.TNCName = tncDevice.Name;
                        //if (!tncDevice.Name.Contains(SharedData.EMail))
                        //{
                        //    packetMessage.TNCName = "E-Mail-" + PacketSettingsViewModel>.Instance.CurrentTNC.MailUserName;
                        //}

                        bool sendMailSuccess = await SendMessageViaEMailAsync(packetMessage);

                        if (sendMailSuccess)
                        {
                            packetMessage.MessageState = MessageState.Locked;
                            packetMessage.SentTime     = DateTime.Now;
                            packetMessage.MailUserName = SmtpClient.Instance.UserName;
                            _logHelper.Log(LogLevel.Info, $"Message sent via E-Mail: {packetMessage.MessageNumber}");

                            var file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMessage.FileName, CreationCollisionOption.OpenIfExists);

                            await file?.DeleteAsync();

                            // Do a save to ensure that updates are saved
                            packetMessage.Save(SharedData.SentMessagesFolder.Path);

                            //_packetMessagesToSend.Remove(packetMessage);
                            messagesSentAsEMail.Add(packetMessage);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logHelper.Log(LogLevel.Error, $"Error sending e-mail message {packetMessage.MessageNumber}");
                        string text = ex.Message;
                        continue;
                    }
                }
            }

            // Remove already processed E-Mail messages.
            foreach (PacketMessage packetMessage in messagesSentAsEMail)
            {
                _packetMessagesToSend.Remove(packetMessage);
            }

            // TODO check if TNC connected otherwise suggest send via email
            //if (_packetMessagesToSend.Count == 0)
            //{
            //    tncDevice = PacketSettingsViewModel>.Instance.CurrentTNC;

            //    (string bbsName, string tncName, string MessageFrom) = Utilities.GetProfileData();
            //    //string MessageFrom = from;
            //    BBSData MessageBBS = Singleton<PacketSettingsViewModel>.Instance.CurrentBBS;
            //    if (MessageBBS == null || !MessageBBS.Name.Contains("XSC") && !tncDevice.Name.Contains(SharedData.EMail))
            //    {
            //        //string bbsName = AddressBook.Instance.GetBBS(MessageFrom);
            //        bbs = BBSDefinitions.Instance.GetBBSFromName(bbsName);
            //    }
            //    else
            //    {
            //        bbs = Singleton<PacketSettingsViewModel>.Instance.CurrentBBS;
            //    }
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == tncName).FirstOrDefault();
            //}
            //else
            //{
            //    //tncDevice = Singleton<PacketSettingsViewModel>.Instance.CurrentTNC;
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == _packetMessagesToSend[0].TNCName).FirstOrDefault();
            //    bbs = BBSDefinitions.Instance.BBSDataList.Where(bBS => bBS.Name == _packetMessagesToSend[0].BBSName).FirstOrDefault();
            //    //Utilities.SetApplicationTitle(bbs.Name);
            //    //bbs = PacketSettingsViewModel>.Instance.CurrentBBS;
            //}

            //Utilities.SetApplicationTitle(bbs?.Name);

            if (!tncDevice.Name.Contains(PublicData.EMail))
            {
                ViewLifetimeControl viewLifetimeControl = await WindowManagerService.Current.TryShowAsStandaloneAsync("Connection Status", typeof(RxTxStatusPage));

                //RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.Height = RxTxStatusPage.rxtxStatusPage.RxTxStatusViewmodel.ViewControlHeight;
                //RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.Width = RxTxStatusPage.rxtxStatusPage.RxTxStatusViewmodel.ViewControlWidth;

                //bool success = RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.ResizeView();


                //return;     //Test

                PacketSettingsViewModel packetSettingsViewModel = PacketSettingsViewModel.Instance;

                //_tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                _tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaCommands, ref _packetMessagesToSend);

                // Collect remaining messages to be sent
                // Process files to be sent via BBS
                await _tncInterface.BBSConnectThreadProcAsync();

                // Close status window
                await RxTxStatusPage.Current._viewLifetimeControl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    //RxTxStatusPage.rxtxStatusPage.CloseStatusWindowAsync();
                    //RxTxStatusPage.Current.RxTxStatusViewmodel.CloseStatusWindowAsync();
                    RxTxStatViewModel.Instance.CloseStatusWindowAsync();
                });

                PacketSettingsViewModel.Instance.ForceReadBulletins = false;
                if (!string.IsNullOrEmpty(bbs?.Name))
                {
                    _logHelper.Log(LogLevel.Info, $"Disconnected from: {bbs?.ConnectName}. Connect time = {_tncInterface.BBSDisconnectTime - _tncInterface.BBSConnectTime}");
                }

                // Move sent messages from unsent folder to the Sent folder
                foreach (PacketMessage packetMsg in _tncInterface.PacketMessagesSent)
                {
                    try
                    {
                        _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} Sent");

                        StorageFile file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMsg.FileName, CreationCollisionOption.OpenIfExists);

                        await file.DeleteAsync();

                        // Do a save to ensure that updates from tncInterface.BBSConnect are saved
                        packetMsg.Save(SharedData.SentMessagesFolder.Path);
                    }
                    catch (FileNotFoundException)
                    {
                        _logHelper.Log(LogLevel.Error, $"File Not Found {packetMsg.FileName}");
                        continue;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        _logHelper.Log(LogLevel.Error, $"Unauthorized Access {packetMsg.FileName}");
                        continue;
                    }
                    if (string.IsNullOrEmpty(packetMsg.Area) && SettingsViewModel.Instance.PrintSentMessages)
                    {
                        // Do printing if requested
                        _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} to be printed");

                        packetMsg.Save(SharedData.PrintMessagesFolder.Path);

                        SettingsViewModel settingsViewModel = SettingsViewModel.Instance;
                        PrintQueue.Instance.AddToPrintQueue(packetMsg.FileName, settingsViewModel.SentCopyNamesAsArray());
                    }
                }
                _packetMessagesReceived = _tncInterface.PacketMessagesReceived;
                await ProcessReceivedMessagesAsync();

                /*
                 * ApplicationTrigger trigger = new ApplicationTrigger();
                 * var task = RxTxBackgroundTask.RegisterBackgroundTask(RxTxBackgroundTask.RxTxBackgroundTaskEntryPoint,
                 *                                                     RxTxBackgroundTask.ApplicationTriggerTaskName,
                 *                                                     trigger,
                 *                                                     null);
                 * task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
                 * task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                 *
                 *
                 * // Register a ApplicationTriggerTask.
                 * RxTxBackgroundTask rxTxBackgroundTask = new RxTxBackgroundTask(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                 *          rxTxBackgroundTask.Register();
                 * // Start backgroung task
                 * // Reset the completion status
                 * var settings = ApplicationData.Current.LocalSettings;
                 * settings.Values.Remove(BackgroundTaskSample.ApplicationTriggerTaskName);
                 *
                 * //Signal the ApplicationTrigger
                 * var result = await trigger.RequestAsync();
                 *
                 * ApplicationTriggerResult result = await rxTxBackgroundTask._applicationTrigger.RequestAsync();
                 * //            await Singleton<BackgroundTaskService>.Instance.HandleAsync(RxTxBackgroundTask);
                 * // RxTxBackgroundTask is finished
                 *
                 * if (_connectState == ConnectState.ConnectStateBBSConnect)
                 * {
                 *  await Utilities.ShowSingleButtonContentDialogAsync(_result, "Close", "BBS Connect Error");
                 *  //_result = "It appears that the radio is tuned to the wrong frequency,\nor the BBS was out of reach";
                 * }
                 *          else if (_connectState == ConnectState.ConnectStatePrepareTNCType)
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync("Unable to connect to the TNC.\nIs the TNC on?\nFor Kenwood; is the radio in \"packet12\" mode?", "Close", "BBS Connect Error");
                 *              //_result = "";
                 *          }
                 *          else if (_connectState == ConnectState.ConnectStateConverseMode)
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync($"Error sending FCC Identification - {Singleton<IdentityViewModel>.Instance.UserCallsign}.", "Close", "TNC Converse Error");
                 *              //_result = $"Error sending FCC Identification - { Singleton<IdentityViewModel>.Instance.UserCallsign}.";
                 *          }
                 *          //else if (e.Message.Contains("not exist"))
                 *          else if (e.GetType() == typeof(IOException))
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync("Looks like the USB or serial cable to the TNC is disconnected", "Close", "TNC Connect Error");
                 *              //_result = "Looks like the USB or serial cable to the TNC is disconnected";
                 *          }
                 *          else if (e.GetType() == typeof(UnauthorizedAccessException))
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync($"The COM Port ({_TncDevice.CommPort.Comport}) is in use by another application. ", "Close", "TNC Connect Error");
                 *              //_result = $"The COM Port ({_TncDevice.CommPort.Comport}) is in use by another application.";
                 *          }
                 *
                 *          PacketSettingsViewModel>.Instance.ForceReadBulletins = false;
                 *          if (!string.IsNullOrEmpty(bbs?.Name))
                 *          {
                 *              _logHelper.Log(LogLevel.Info, $"Disconnected from: {bbs?.ConnectName}. Connect time = {rxTxBackgroundTask.BBSDisconnectTime - rxTxBackgroundTask.BBSConnectTime}");
                 *          }
                 *
                 *          // Move sent messages from unsent folder to the Sent folder
                 *          foreach (PacketMessage packetMsg in rxTxBackgroundTask.PacketMessagesSent)
                 *          {
                 *              try
                 *              {
                 *                  _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} Sent");
                 *
                 *                  StorageFile file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMsg.FileName, CreationCollisionOption.OpenIfExists);
                 *                  await file.DeleteAsync();
                 *
                 *                  // Do a save to ensure that updates from tncInterface.BBSConnect are saved
                 *                  packetMsg.Save(SharedData.SentMessagesFolder.Path);
                 *              }
                 *              catch (Exception e)
                 *              {
                 *                  _logHelper.Log(LogLevel.Error, $"Exception {e.Message}");
                 *              }
                 *          }
                 *          _packetMessagesReceived = rxTxBackgroundTask.PacketMessagesReceived;
                 *          ProcessReceivedMessagesAsync();
                 *///_deviceFound = true;
                //try
                //{
                //    _serialPort = new SerialPort(Singleton<TNCSettingsViewModel>.Instance.CurrentTNCDevice.CommPort.Comport);
                //}
                //catch (IOException e)
                //{
                //    _deviceFound = false;
                //}
                //_serialPort.Close();
            }
        }