Exemple #1
0
        public static object GetDynamicViewModel(string Menu, FormsViewModel FormsViewModel)
        {
            object FormsDataViewModel = FormsViewModel.info;

            switch (Menu)
            {
            case "DOAA":
                FormsDataViewModel = FormsViewModel.info;
                break;

            case "ADIR":
            case "DOSW":
                FormsDataViewModel = FormsViewModel.info2;
                break;

            case "LIBFORM":
                FormsDataViewModel = FormsViewModel.libInfo;
                break;

            default:
                break;
            }

            return(FormsDataViewModel);
        }
        public ActionResult LoadEmpData(string EmpNo, string DataCaptYM, bool isFromSave)
        {
            SessionManager.DataCaptYR = Convert.ToInt32(DataCaptYM);
            FormsViewModel dOAA1ViewModel = new FormsViewModel();

            dOAA1ViewModel.GetDOAA1Data(Convert.ToInt32(DataCaptYM), Menu.DOFAPEER.ToString());
            string MenuPartial = FormCommonMethods.GetMenuPartial(Menu.DOFAPEER.ToString());

            if (!string.IsNullOrEmpty(EmpNo))
            {
                dOAA1ViewModel.dofaPeerViewModel.DofaPeerData = dOAA1ViewModel.dofaPeerViewModel.DofaPeerData.Where(a => a.empNo.Equals(Convert.ToInt32(EmpNo))).ToList();
                dOAA1ViewModel.dofaPeerViewModel.EmpNo        = Convert.ToInt32(EmpNo);
            }

            if (dOAA1ViewModel.dofaPeerViewModel.DofaPeerData.Count() <= 0)
            {
                DofaPeer dofaPeer = new DofaPeer();
                dofaPeer.empNo  = Convert.ToInt32(EmpNo);
                dofaPeer.PeerNo = 1;
                dOAA1ViewModel.dofaPeerViewModel.DofaPeerData.Add(dofaPeer);
            }
            object DataObject = FormCommonMethods.GetDynamicViewModel(Menu.DOFAPEER.ToString(), dOAA1ViewModel);

            if (isFromSave)
            {
                TempData["isSaveSuccessfully"]  = true;
                TempData["isFailedToSentEmail"] = false;
            }
            return(PartialView(MenuPartial, DataObject));
        }
        public IActionResult Details(Guid id)
        {
            var getAnalysis = _analysisStore.GetById(id);

            var getAnalysisDetails = new FormsViewModel()
            {
                StrategyUsed    = getAnalysis.StrategyPicked,
                TradingCriteria = getAnalysis.TradingCriteria,
                ExitStrategy    = getAnalysis.ExitStrategy,
                TradingTrend    = getAnalysis.TradingTrend,
                AcceptanceType  = getAnalysis.AcceptanceType,
                RewardRatio     = getAnalysis.RewardRatio,
                DescribeTrade   = getAnalysis.DescribeTrade,
                PairPicked      = getAnalysis.PairPicked,
                MentalState     = getAnalysis.MentalState,
                TradeStatus     = getAnalysis.TradeStatus,
                TradeOutcome    = getAnalysis.TradeOutcome,
                TimeOfTrade     = getAnalysis.TimeOfTrade,
                ExplainTrade    = getAnalysis.ExplainTrade,
                Note            = getAnalysis.Note,
                MetDailyGoal    = getAnalysis.MetDailyGoal
            };

            return(View(getAnalysisDetails));
        }
        public static FormsViewModel ToViewModel(this FormsModel entity)
        {
            if (entity == null)
            {
                return(null);
            }
            var model = new FormsViewModel
            {
                ContactFormsID         = entity.ContactFormsID,
                ContactID              = entity.ContactID,
                AssessmentID           = entity.AssessmentID,
                ResponseID             = entity.ResponseID,
                ServiceRecordingID     = entity.ServiceRecordingID,
                ServiceRecordingVoidID = entity.ServiceRecordingVoidID,
                IsVoided         = entity.IsVoided,
                UserID           = entity.UserID,
                ProviderName     = entity.ProviderName,
                DocumentStatusID = entity.DocumentStatusID,
                ModifiedOn       = entity.ModifiedOn,
                ServiceStartDate = entity.ServiceStartDate,
                ServiceEndDate   = entity.ServiceEndDate
            };

            return(model);
        }
        public MainWindow()
        {
            InitializeComponent();

            m_viewModel      = new FormsViewModel();
            this.DataContext = m_viewModel;
        }
        public static FormsModel ToModel(this FormsViewModel model)
        {
            if (model == null)
            {
                return(null);
            }
            var entity = new FormsModel
            {
                ContactFormsID         = model.ContactFormsID,
                ContactID              = model.ContactID,
                AssessmentID           = model.AssessmentID,
                ServiceRecordingID     = model.ServiceRecordingID,
                ServiceRecordingVoidID = model.ServiceRecordingVoidID,
                IsVoided         = model.IsVoided,
                ResponseID       = model.ResponseID,
                UserID           = model.UserID,
                ProviderName     = model.ProviderName,
                DocumentStatusID = model.DocumentStatusID,
                ModifiedOn       = model.ModifiedOn,
                ServiceStartDate = model.ServiceStartDate,
                ServiceEndDate   = model.ServiceEndDate
            };

            return(entity);
        }
Exemple #7
0
        public IActionResult GetJson(JsonFileViewModel fileModel)
        {
            if (ModelState.IsValid)
            {
                IFormFile formFile = fileModel.FileJson;

                if (formFile != null && formFile.Length > 0)
                {
                    Form form = fileSerializer.ReadJson(formFile);

                    if (form != null)
                    {
                        FormsViewModel formModel = new FormsViewModel
                        {
                            Form = form
                        };

                        return(View("GenerateForm", formModel));
                    }
                }

                ModelState.AddModelError("", "Uploaded file is empty or null.");
                return(View(fileModel));
            }
            return(View(fileModel));
        }
Exemple #8
0
        /// <summary>
        /// Updates the Forms.
        /// </summary>
        /// <param name="FormsModel">The Forms model.</param>
        /// <returns>Response&lt;FormsViewModel&gt;.</returns>
        public Response <FormsViewModel> UpdateIntakeForms(FormsViewModel FormsModel)
        {
            string apiUrl   = baseRoute + "UpdateIntakeForms";
            var    response = communicationManager.Put <FormsModel, Response <FormsModel> >(FormsModel.ToModel(), apiUrl);

            return(response.ToViewModel());
        }
Exemple #9
0
        // GET: Form
        public ActionResult Index()
        {
            FormsViewModel formsViewModel = new FormsViewModel();

            formsViewModel.Forms = AppUtils.LoadForms();

            return(View(formsViewModel));
        }
        public ActionResult OnDofaDeptChange(int DataCaptYM, string EmpDept, string DeptId)
        {
            FormsViewModel viewModel = new FormsViewModel();

            SessionManager.DataCaptYR = DataCaptYM;
            SessionManager.DeptID     = DeptId;
            viewModel.GetMultiDataByMenuID(DataCaptYM, "DOFA", EmpDept);
            return(PartialView("DOFAFormPartial", viewModel.dofaViewModel));
        }
        public ActionResult Save(FormsViewModel viewModel)
        {
            context.DForm.Add(viewModel.DataForm);
            var dataCity = viewModel.ListofCity.Find(x => x.Id == viewModel.DataForm.City);

            context.SaveChanges();

            return(RedirectToAction("SecondView", new { bookingId = viewModel.DataForm.Id, cityName = dataCity.Name }));
        }
Exemple #12
0
        public ActionResult SaveUpdateFormData(CommonSaveUpdateProp data)
        {
            FormsViewModel formsViewModel = new FormsViewModel();
            object         objectData     = data.formData;
            string         action         = data.action;
            string         menu           = data.menu;
            bool           IsSuccess      = formsViewModel.SaveUpdateFormData(objectData, action, menu);

            TempData["isSaveSuccessfully"] = IsSuccess;
            return(Json(new { status = IsSuccess }, JsonRequestBehavior.AllowGet));
        }
Exemple #13
0
        public ActionResult ADIRForm(string DataCaptYM)
        {
            FormsViewModel dOAA1ViewModel = new FormsViewModel();
            int            dataCaptYM     = 0;

            int.TryParse(DataCaptYM, out dataCaptYM);
            dOAA1ViewModel.GetDOAA1Data(dataCaptYM, DataAccess.Enum.Menu.ADIR.ToString());
            ViewBag.Message = Convert.ToString(TempData["Message"]);
            ViewBag.Status  = Convert.ToBoolean(TempData["Status"]);
            return(View(dOAA1ViewModel));
        }
Exemple #14
0
        public async Task <FormsViewModel> Get(int formId)
        {
            var formCategoryAssignment = await _context.FormsCategoryAssignments
                                         .Where(c => c.FormId == formId)
                                         .Include(f => f.FormsInfo)
                                         .Include(c => c.Categories)
                                         .FirstOrDefaultAsync();

            var questions = await _context.QuestionsFormAssignments
                            .Where(qfa => qfa.FormId == formId)
                            .Include(q => q.Questions)
                            .ThenInclude(qt => qt.QuestionTypes)
                            .ToListAsync();

            var options = await _context.OptionsQuestionAssignmnents
                          .Where(oqa => oqa.FormId == formId)
                          .Include(o => o.Options)
                          .ToListAsync();

            //Save fetched data to FormsViewModel
            var form = new FormsViewModel
            {
                Questions        = new List <QuestionsViewModel>(),
                CategoryId       = formCategoryAssignment.CategoryId,
                CategoryName     = formCategoryAssignment.Categories.CategoryName,
                DestinationEmail = formCategoryAssignment.FormsInfo.DestinationEmail,
                FormName         = formCategoryAssignment.FormsInfo.FormName,
                IsAnonymous      = formCategoryAssignment.FormsInfo.IsAnonymous
            };

            foreach (var fetchedQuestion in questions)
            {
                var question = new QuestionsViewModel
                {
                    QuestionName         = fetchedQuestion.Questions.QuestionName,
                    QuestionOrderNum     = fetchedQuestion.QuestionOrderNum,
                    QuestionType         = fetchedQuestion.Questions.QuestionTypes.QuestionType,
                    QuestionTypeOrderNum = fetchedQuestion.QuestionTypeOrderNum,
                    Options = new List <OptionsViewModel>()
                };

                foreach (var fetchedOption in options.Where(o => o.QuestionOrderNum == question.QuestionOrderNum))
                {
                    var option = new OptionsViewModel
                    {
                        OptionName     = fetchedOption.Options.OptionName,
                        OptionOrderNum = fetchedOption.OptionOrderNum
                    };
                    question.Options.Add(option);
                }
                form.Questions.Add(question);
            }
            return(form);
        }
        public ActionResult DFNPForm(string DataCaptYM)
        {
            FormsViewModel viewModel  = new FormsViewModel();
            int            dataCaptYM = 0;

            int.TryParse(DataCaptYM, out dataCaptYM);
            viewModel.GetMultiDataByMenuID(dataCaptYM, Menu.DFNP.ToString());
            ViewBag.Message = Convert.ToString(TempData["Message"]);
            ViewBag.Status  = Convert.ToBoolean(TempData["Status"]);
            return(View(viewModel));
        }
Exemple #16
0
        public static object GetDynamicViewModel(string Menu, FormsViewModel FormsViewModel)
        {
            object FormsDataViewModel = FormsViewModel.info;

            switch (Menu)
            {
            case "DOAA":
                FormsDataViewModel = FormsViewModel.info;
                break;

            case "ADIR":
            case "DOSW":
                FormsDataViewModel = FormsViewModel.info2;
                break;

            case "LIBFORM":
                FormsDataViewModel = FormsViewModel.libInfo;
                break;

            case "DOFA":
                FormsDataViewModel = FormsViewModel.dofaViewModel;
                break;

            case "SRICFA":
                FormsDataViewModel = FormsViewModel.sricFAViewModel;
                break;

            case "SRIC":
                FormsDataViewModel = FormsViewModel.sricDeptViewModel;
                break;

            case "DOFAPEER":
                FormsDataViewModel = FormsViewModel.dofaPeerViewModel;
                break;

            case "TPDEPT":
                FormsDataViewModel = FormsViewModel.tpDeptViewModel;
                break;

            case "INFRA":
                FormsDataViewModel = FormsViewModel.infraViewModel;
                break;

            case "DFNP":
                FormsDataViewModel = FormsViewModel.dfnpViewModel;
                break;

            default:
                break;
            }

            return(FormsDataViewModel);
        }
Exemple #17
0
        public ActionResult OnDAtaCaptYMChange(int DataCaptYM, string Menu, string DeptId)
        {
            FormsViewModel dOAA1ViewModel = new FormsViewModel();

            SessionManager.DataCaptYR = DataCaptYM;
            SessionManager.DeptID     = DeptId;
            dOAA1ViewModel.GetDOAA1Data(DataCaptYM, Menu);
            string MenuPartial = FormCommonMethods.GetMenuPartial(Menu);
            object DataObject  = FormCommonMethods.GetDynamicViewModel(Menu, dOAA1ViewModel);

            return(PartialView(MenuPartial, DataObject));
        }
        public ActionResult SaveSricFAFormData(SricFaRequestViewModel data)
        {
            string              msg                 = string.Empty;
            FormsViewModel      formsViewModel      = new FormsViewModel();
            string              action              = data.action;
            string              menu                = data.menu;
            string              needModificationMSG = data.needModificationMSG;
            Tuple <bool, bool?> IsSuccess           = formsViewModel.SaveUpdateFormData(data.formData, action, menu, needModificationMSG, out msg);

            TempData["isSaveSuccessfully"] = IsSuccess.Item1;
            if (IsSuccess.Item2 != null)
            {
                TempData["isFailedToSentEmail"] = !IsSuccess.Item2;
            }
            return(Json(new { status = IsSuccess.Item1, msg = msg }, JsonRequestBehavior.AllowGet));
        }
Exemple #19
0
        public IActionResult PostForm(FormsViewModel model)
        {
            var id          = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value;
            var currentUser = _traderStore.GetAll().FirstOrDefault(u => u.TraderId == Guid.Parse(id));

            if (model == null)
            {
                // return Ok(new AuthResponse { Errror = "Formm did not get submitted" });
            }

            try
            {
                var createForm = new Form()
                {
                    AcceptanceType  = model.AcceptanceType,
                    DescribeTrade   = model.DescribeTrade,
                    ExitStrategy    = model.ExitStrategy,
                    ExplainTrade    = model.ExplainTrade,
                    MentalState     = model.MentalState,
                    MetDailyGoal    = model.MetDailyGoal,
                    PairPicked      = model.PairPicked,
                    RewardRatio     = model.RewardRatio,
                    StrategyPicked  = model.StrategyUsed,
                    TradingCriteria = model.TradingCriteria,
                    TradingTrend    = model.TradingTrend,
                    TraderId        = currentUser.TraderId,
                    TimeOfTrade     = model.TimeOfTrade,
                    Note            = model.Note,
                    TradeOutcome    = model.TradeOutcome,
                    TradeStatus     = model.TradeStatus

                                      //  DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
                                      // DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:tt")
                };
                _formDataStore.Post(createForm);
            }
            catch (Exception)
            {
                //throw;
                // return BadRequest(new AuthResponse { Errror = "form not created" });
            }
            return(RedirectToAction("index", "analysis"));
        }
Exemple #20
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.Parameter is null)
            {
                ViewModel.PopulateEmptyForm = true;
                return;
            }

            ViewModel.PopulateEmptyForm = false;

            string packetMessagePath = e.Parameter as string;
            //PacketMessage packetMessage = PacketMessage.OpenAsync(packetMessagePath);
            PacketMessage packetMessage = PacketMessage.Open(packetMessagePath);

            if (packetMessage != null)
            {
                packetMessage.MessageOpened = true;
                string directory = Path.GetDirectoryName(packetMessagePath);
                if (packetMessage.PacFormName.Contains("213RR"))
                {
                    webViewPivot.SelectedIndex = 1;
                }
                else if (packetMessage.PacFormName.Contains("213"))
                {
                    webViewPivot.SelectedIndex = 0;
                }
                else
                {
                    webViewPivot.SelectedIndex = 2;
                }

                FormControlBase formControl = FormsViewModel.CreateFormControlInstance(packetMessage.PacFormName);

                ConvertFromOutpost(ref packetMessage, ref formControl);
            }
        }
        public ActionResult ReportsForm(string DataCaptYM)
        {
            FormsViewModel vm = new FormsViewModel();

            return(View(vm));
        }
 public void FormsViewModel_GetIntance()
 {
     Assert.NotNull(FormsViewModel.GetInstance());
 }
 public void SetUp()
 {
     _pageservice = new Mock <IPageService>();
     _viewModel   = new FormsViewModel(_pageservice.Object);
 }
        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();
            }
        }
        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();
                }
            }
        }
        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;
        }
Exemple #27
0
 public FormsPage()
 {
     BindingContext = FormsViewModel.GetInstance();
     _viewModel.UpdateFormsList();
     InitializeComponent();
 }
 public Response <FormsViewModel> AddIntakeForms(FormsViewModel FormsModel)
 {
     return(_IntakeFormsRepository.AddIntakeForms(FormsModel));
 }
 public Response <FormsViewModel> UpdateIntakeForms(FormsViewModel FormsModel)
 {
     return(_IntakeFormsRepository.UpdateIntakeForms(FormsModel));
 }
        // GET: Project
        public ActionResult Index()
        {
            FormsViewModel forms = new FormsViewModel();

            return(View(forms));
        }