private void buttonAddModel_Click(object sender, EventArgs e)
        {
            var viewControl = new AddModelControl();

            viewControl.Dock = DockStyle.Fill;
            var dialog = new GeneralForm();

            dialog.Text = "Добавяне на модел";
            dialog.Size = viewControl.Size;

            dialog.Controls.Add(viewControl);
            viewControl.BringToFront();

            var res = dialog.ShowDialog();

            if (res == DialogResult.OK)
            {
                var item = new CarModelHelper
                {
                    ModelName    = viewControl.CarModelName,
                    CreationDate = viewControl.CreationDate
                };

                comboBoxModel.Items.Add(item);
                comboBoxModel.SelectedItem = item;
            }
        }
Example #2
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            var dialogPb = new PictureBox();

            dialogPb.Image = currentImage.Value;
            dialogPb.Size  = currentImage.Value.Size;

            var panel = new Panel();

            panel.AutoScroll = true;
            panel.HorizontalScroll.Visible = true;
            panel.Dock             = DockStyle.Fill;
            panel.ContextMenuStrip = new ContextMenuStrip();
            panel.ContextMenuStrip.Items.Add("Принтиране", Properties.Resources.print_button, Panel_ContextMenu_ItemClick);
            panel.Controls.Add(dialogPb);


            var dialog = new GeneralForm();

            dialog.panel1.Visible = false;
            dialog.WindowState    = FormWindowState.Maximized;
            //dialog.TopMost = true;

            dialog.Controls.Add(panel);
            panel.BringToFront();
            dialogPb.BringToFront();

            dialog.ShowDialog();
        }
 public CreateVisitorForm(GeneralForm f, BizVisitor v)
 {
     visitor = new ExhibitionVisitor();
     InitializeComponent();
     visitor = context.ExhibitionVisitors.Where(vi => vi.BarCode == v.vBarcode).Select(s => s).FirstOrDefault();
     cmb_exhebition.DataSource    = context.Exhibits.Where(vi => vi.Name != "none").Select(s => s).ToList();
     cmb_exhebition.DisplayMember = "Name";
     cmb_exhebition.ValueMember   = "Id";
     need_print            = false;
     create_form           = f;
     txb_lname.Text        = v.vLastName;
     txb_fname.Text        = v.vFirstName;
     txb_pathronim.Text    = v.vPathronim;
     txb_company.Text      = v.vConpany;
     txb_position.Text     = v.vPosition;
     txb_email.Text        = v.vEmail;
     cb_description.Text   = v.vDescription;
     txb_city.Text         = v.vCity;
     txb_raport.Text       = v.vRaport;
     txb_phone_work.Text   = v.vPhoneWork;
     txb_phone_mobile.Text = v.vPhoneMobile;
     if (v.vStatus == "fact")
     {
         v.vStatus = "factcorrect";
     }
     if (v.vStatus == "newfact")
     {
         v.vStatus = "newfactcorrect";
     }
     //		context.SaveChanges();
     ///		this.Refresh();
 }
Example #4
0
 private void btn_Giris_Click(object sender, EventArgs e)
 {
     try
     {
         Kullanicilar user = new Kullanicilar();
         user.KullaniciAdi = txt_KullaniciAdi.Text;
         user.Sifre        = txt_Sifre.Text;
         string md5 = Tools.CreateMD5(user.Sifre);
         if (string.IsNullOrEmpty(user.KullaniciAdi) || string.IsNullOrEmpty(md5))
         {
             throw new ValidationException("Kullanıcı Adı ve Şifre Boş Geçilemez !");
         }
         user.Sifre = md5;
         var result = UsersController.UserAdminLogin(user);
         LoginForm._session       = ERoles.Admin.ToString();
         LoginForm._userIdSession = result.KullaniciId;
         GeneralForm gf = new GeneralForm();
         gf.Show();
         this.Hide();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Hata Meydana Geldi !", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
 public CreateVisitorForm(GeneralForm f, PharmaVisitor v)
 {
     visitor = new ExhibitionVisitor();
     InitializeComponent();
     visitor = context.ExhibitionVisitors.Where(vi => vi.BarCode == v.pBarcode).Select(s => s).FirstOrDefault();
     cmb_exhebition.DataSource    = context.Exhibits.Where(vi => vi.Name != "none").Select(s => s).ToList();
     cmb_exhebition.DisplayMember = "Name";
     cmb_exhebition.ValueMember   = "Id";
     need_print                   = false;
     create_form                  = f;
     txb_lname.Text               = v.pSurName;
     txb_fname.Text               = v.pForName;
     txb_pathronim.Text           = " ";
     txb_company.Text             = v.pConpany;
     txb_position.Text            = v.pJobTitle;
     txb_email.Text               = v.pRowNumber;
     cb_description.DataSource    = context.Descriptions.Select(s => s).ToList();
     cb_description.DisplayMember = "Name";
     cb_description.ValueMember   = "Id";
     cb_description.Text          = v.pDescription;
     txb_city.Text                = " ";
     txb_raport.Text              = " ";
     txb_phone_work.Text          = " ";
     txb_phone_mobile.Text        = v.pCustomerNo;
     if (v.pStatus == "fact")
     {
         v.pStatus = "factcorrect";
     }
     if (v.pStatus == "newfact")
     {
         v.pStatus = "newfactcorrect";
     }
     //		context.SaveChanges();
     ///		this.Refresh();
 }
Example #6
0
 public CreatePharmaVisitorForm(GeneralForm f, PharmaVisitor v)
 {
     visitor = new ExhibitionVisitor();
     InitializeComponent();
     visitor = context.ExhibitionVisitors.Where(vi => vi.BarCode == v.pBarcode).Select(s => s).FirstOrDefault();
     cmb_exhebition.DataSource    = context.Exhibits.Where(vi => vi.Name != "none").Select(s => s).ToList();
     cmb_exhebition.DisplayMember = "Name";
     cmb_exhebition.ValueMember   = "Id";
     need_print                   = false;
     create_form                  = f;
     txb_lname.Text               = v.pSurName;
     txb_fname.Text               = v.pForName;
     txb_company.Text             = v.pConpany;
     txb_position.Text            = v.pJobTitle;
     txb_row_number.Text          = v.pRowNumber;
     txb_customerno.Text          = v.pCustomerNo;
     cb_description.DataSource    = context.Descriptions.Select(s => s).ToList();
     cb_description.DisplayMember = "Name";
     cb_description.ValueMember   = "Id";
     cb_description.Text          = v.pDescription;
     txb_payment_status.Text      = v.pPaymentStatus;
     txb_payment_comment.Text     = v.pPaymentComment;
     if (v.pStatus == "fact")
     {
         v.pStatus = "factcorrect";
     }
     if (v.pStatus == "newfact")
     {
         v.pStatus = "newfactcorrect";
     }
 }
Example #7
0
 public СhoiceForm(GeneralForm form, BizVisitor visitor)
 {
     InitializeComponent();
     g_form           = form;
     this.visitor     = context.ExhibitionVisitors.Where(v => v.BarCode == visitor.vBarcode).Select(s => s).FirstOrDefault();
     this.biz_visitor = visitor;
 }
        private void buttonAddMaker_Click(object sender, EventArgs e)
        {
            var viewControl = new AddMakerControl();

            viewControl.Entity = EntityService.GetEntities();
            viewControl.Dock   = DockStyle.Fill;
            var dialog = new GeneralForm();

            dialog.Text = "Добавяне на марка";
            dialog.Size = viewControl.Size;

            dialog.Controls.Add(viewControl);
            viewControl.BringToFront();

            var res = dialog.ShowDialog();

            if (res == DialogResult.OK)
            {
                var item = new CarMakerHelper
                {
                    Name   = viewControl.CarMakerName,
                    Models = new List <CarModelHelper>()
                };

                comboBox1.Items.Add(item);
                comboBox1.SelectedItem = item;
            }
        }
Example #9
0
        public Obj Initialize(GeneralForm form)
        {
            WindowObject = form;

            DiscordToolTip.SetToolTip(WindowObject.DiscordIcon, "Перейти в Discord");

            return(this);
        }
 public CreateVisitorForm(GeneralForm f)
 {
     visitor = new ExhibitionVisitor();
     InitializeComponent();
     cmb_exhebition.DataSource    = context.Exhibits.Where(v => v.Name != "none").Select(s => s).ToList();
     cmb_exhebition.DisplayMember = "Name";
     cmb_exhebition.ValueMember   = "Id";
     need_print  = false;
     create_form = f;
     cb_description.DataSource    = context.Descriptions.Select(s => s).ToList();
     cb_description.DisplayMember = "Name";
     cb_description.ValueMember   = "Id";
     cb_description.Text          = "ИТ-компания";
 }
Example #11
0
        public IActionResult General()
        {
            var model = new GeneralForm
            {
                SiteName              = _settingsKeeper.GetSetting("SiteName").Value,
                SiteDescription       = _settingsKeeper.GetSetting("SiteDescription").Value,
                SiteUrl               = _settingsKeeper.GetSetting("SiteUrl").Value,
                EnableRegistration    = bool.Parse(_settingsKeeper.GetSetting("EnableRegistration").Value),
                NumberOfUpdatesToShow = byte.Parse(_settingsKeeper.GetSetting("NumberOfUpdatesToShow").Value),
                SiteFooter            = _settingsKeeper.GetSetting("SiteFooterCode").Value,
                SiteSideBar           = _settingsKeeper.GetSetting("SiteSideBar").Value,
                SiteAboutPage         = _settingsKeeper.GetSetting("SiteAboutPage").Value
            };

            return(View("GeneralSettings", model));
        }
Example #12
0
        public async Task <IActionResult> General(GeneralForm generalForm)
        {
            if (ModelState.IsValid)
            {
                var tasks    = new Task[9];
                var manifest = new ManifestBuilder
                {
                    ShortName = generalForm.SiteName,
                    Name      = generalForm.SiteName,
                    Icons     = new[]
                    {
                        new ManifestBuilder.Icon
                        {
                            Src   = "assets/icon.png",
                            Type  = "image/png",
                            Sizes = "512x512"
                        }
                    },
                    ThemeColor      = "#FFF",
                    BackgroundColor = "#FFF",
                    GcmSenderId     = "103953800507"
                };

                tasks[0] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteName", generalForm.SiteName));
                tasks[1] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteDescription", generalForm.SiteDescription));
                tasks[2] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteUrl", generalForm.SiteUrl));
                tasks[3] = Task.Run(async() => await _settingsKeeper.AddSettings("EnableRegistration", generalForm.EnableRegistration.ToString()));
                tasks[4] = Task.Run(async() => await _settingsKeeper.AddSettings("NumberOfUpdatesToShow", generalForm.NumberOfUpdatesToShow.ToString()));
                tasks[5] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteFooterCode", generalForm.SiteFooter ?? string.Empty));
                tasks[6] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteSideBar", generalForm.SiteSideBar ?? string.Empty));
                tasks[7] = Task.Run(async() => await _settingsKeeper.AddSettings("SiteAboutPage", generalForm.SiteAboutPage ?? string.Empty));
                tasks[8] = Task.Run(async() => await manifest.BuildManifest(_webHostEnvironment));

                TempData["Error"] = false;

                await Task.WhenAll(tasks);
            }
            else
            {
                TempData["Error"] = true;
            }

            return(RedirectToAction("General"));
        }
        public ActionResult Help()
        {
            mLogger.Debug("* * *  ResultsController:Help method  * * *");

            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            GeneralForm amt = new GeneralForm();

            amt.formId = SessionHelper.SessionForm.formId;

            return(View("~/Views/Home/Help.cshtml", amt));
        }
Example #14
0
 public СhoiceForm(GeneralForm form, ExhibitionVisitor visitor)
 {
     InitializeComponent();
     g_form                   = form;
     this.visitor             = visitor;
     this.biz_visitor         = new BizVisitor();
     biz_visitor.vId          = visitor.Id;
     biz_visitor.vLastName    = visitor.LastName;
     biz_visitor.vFirstName   = visitor.FirstName;
     biz_visitor.vPathronim   = visitor.Pathronim;
     biz_visitor.vConpany     = context.Companies.Where(c => c.Id == visitor.CompanyId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vPosition    = context.Positions.Where(p => p.Id == visitor.PositionId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vDescription = context.Descriptions.Where(d => d.Id == visitor.DescriptionId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vPhoneMobile = visitor.PhoneNumber;
     biz_visitor.vPhoneWork   = visitor.WorkPhone;
     biz_visitor.vEmail       = visitor.Email;
     biz_visitor.vRegDate     = visitor.DateCreated.ToString();
     biz_visitor.vExhibit     = context.Exhibits.Where(e => e.Id == visitor.ExhibitId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vRaport      = context.Raports.Where(r => r.Id == visitor.RaportId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vCity        = context.Cities.Where(c => c.Id == visitor.CityId).Select(s => s.Name).FirstOrDefault();
     biz_visitor.vStatus      = visitor.Status;
     biz_visitor.vBarcode     = visitor.BarCode;
 }
        /*  This method validates the SIS templates in Views/Templates/SIS
         *
         *
         */
        private bool ValidateFormResult(def_FormResults fr, TemplateItems amt = null)
        {
            // * * * OT 3-15-16 completed form results need to be validated on every save (Bug 13110)
            //// * * * OT 1-4-16   form results that are already marked as completed get to skip validation
            //if (fr.formStatus == (byte)FormResults_formStatus.COMPLETED)
            //    return true;

            if (amt == null)
            {
                amt = new GeneralForm();
            }

            //retrieve all responses for this formResult, by def_ItemVariable identifier
            List <ValuePair> allResponses = CommonExport.GetDataByFormResultId(fr.formResultId);

            //pass the response data through generic validation (meta-data driven validation)
            def_Forms frm = formsRepo.GetFormById(fr.formId);

            string[]         ItemVariableSuffixesToSkip = { "Notes", "portantTo", "portantFor", "cl_age", "int_id" };
            SharedValidation sv      = new SharedValidation(allResponses);
            bool             invalid = sv.DoGenericValidation(formsRepo, amt, frm, ItemVariableSuffixesToSkip);

            //pass the response data through one-off validation (rules that can't be encoded into meta-data)
            //populate amt.valdiationMessages in the process
            amt.validationMessages = new List <string>();
            if (SisOneOffValidation.RunOneOffValidation(formsRepo, frm, fr.EnterpriseID.Value, allResponses, amt))
            {
                invalid = true;
            }

            if (invalid)
            {
                return(false);
            }

            //  Mark the FormResult as Complete
            new Assessments(formsRepo).AssessmentComplete(fr);// formsRepo.FormResultComplete(fr);

            // Insert status log indicating assessment has been marked complete
            if (SessionHelper.IsVentureMode == false)
            {
                ReviewStatus.AssessmentIsCompleted(formsRepo, fr);

                if (WebServiceActivity.IsWebServiceEnabled())
                {
                    WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.COMPLETE, "formResultId=" + fr.formResultId.ToString());
                }
            }

            // Populate the hidden Venture Version field upon validation

            if (SessionHelper.IsVentureMode == true)
            {
                string ventureVersion = SessionHelper.Read <string>("venture_version");

                if (ventureVersion != null)
                {
                    Updates.AddField(formsRepo, Updates.SIS_HIDDEN, fr, Updates.VENTURE_VERSION, ventureVersion);
                }
            }

            return(true);
        }
Example #16
0
        /// <summary>
        /// 显示选择工作表的窗口
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="multiSelect">是否允许多选</param>
        /// <param name="selects">被选中的工作表索引</param>
        /// <returns></returns>
        public System.Windows.Forms.DialogResult ShowSelectWorksheet(System.Windows.Forms.IWin32Window owner, bool multiSelect, Core.ListDictionary <int> selects)
        {
            if (_excel == null)
            {
                return(System.Windows.Forms.DialogResult.Cancel);
            }
            #region wiondow code
            Core.GeneralForm gf = new GeneralForm();
            System.Windows.Forms.ListView     listView1;
            System.Windows.Forms.ColumnHeader columnHeader1;
            System.Windows.Forms.Button       button1;
            System.Windows.Forms.Button       button2;

            listView1     = new System.Windows.Forms.ListView();
            columnHeader1 = new System.Windows.Forms.ColumnHeader();
            button1       = new System.Windows.Forms.Button();
            button2       = new System.Windows.Forms.Button();
            gf.SuspendLayout();
            //
            // listView1
            //
            listView1.CheckBoxes = multiSelect;
            listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
                columnHeader1
            });
            listView1.Location = new System.Drawing.Point(12, 12);
            listView1.Name     = "listView1";
            listView1.Size     = new System.Drawing.Size(373, 253);
            listView1.TabIndex = 3;
            listView1.UseCompatibleStateImageBehavior = false;
            listView1.View = System.Windows.Forms.View.Details;
            //
            // columnHeader1
            //
            columnHeader1.Text  = "现存的工作表";
            columnHeader1.Width = 260;
            //
            // button1
            //
            button1.Location = new System.Drawing.Point(218, 278);
            button1.Name     = "button1";
            button1.Size     = new System.Drawing.Size(75, 23);
            button1.TabIndex = 1;
            button1.Text     = "确定";
            button1.UseVisualStyleBackColor = true;
            button1.Click += delegate
            {
                if (multiSelect)
                {
                    foreach (System.Windows.Forms.ListViewItem item in listView1.Items)
                    {
                        if (item.Checked)
                        {
                            selects.Add(item.Index + 1);
                        }
                    }
                }
                else
                {
                    selects.Add(listView1.SelectedItems[0].Index + 1);
                }
                if (selects.Count <= 0)
                {
                    System.Windows.Forms.MessageBox.Show(owner, "至少要选择一张工作表", "选择工作表", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    return;
                }
                gf.DialogResult = System.Windows.Forms.DialogResult.OK;
            };
            //
            // button2
            //
            button2.DialogResult            = System.Windows.Forms.DialogResult.Cancel;
            button2.Location                = new System.Drawing.Point(310, 278);
            button2.Name                    = "button2";
            button2.Size                    = new System.Drawing.Size(75, 23);
            button2.TabIndex                = 2;
            button2.Text                    = "取消";
            button2.UseVisualStyleBackColor = true;
            button2.Click                  += delegate
            {
                gf.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                gf.Close();
            };
            //
            // Form1
            //
            gf.AcceptButton        = button1;
            gf.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            gf.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
            gf.CancelButton        = button2;
            gf.FormBorderStyle     = System.Windows.Forms.FormBorderStyle.FixedDialog;
            gf.ClientSize          = new System.Drawing.Size(400, 309);
            gf.Controls.Add(button2);
            gf.Controls.Add(button1);
            gf.Controls.Add(listView1);
            gf.MaximizeBox   = false;
            gf.MinimizeBox   = false;
            gf.Name          = "Form1";
            gf.ShowInTaskbar = false;
            gf.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            gf.Text          = "现存的工作表";
            gf.ResumeLayout(false);
            gf.Shown += delegate
            {
                for (int i = 1; i <= _excel.WorksheetCount; i++)
                {
                    listView1.Items.Add(_excel.WorksheetName(i));
                }
            };
            #endregion
            return(gf.ShowDialog(owner));
        }
Example #17
0
 public void GetGeneralForm(GeneralForm g)
 {
     this.generalform2 = g;
 }
        public ActionResult Template(int?sectionIdOverride = null, List <string> validationMessages = null)
        {
            mLogger.Debug("* * *  ResultsController:Template method  * * *");

            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            if (Session["form"] != null && !string.IsNullOrWhiteSpace(Session["form"].ToString()))
            {
                int formId = SessionHelper.SessionForm.formId;
                formId = int.Parse(Session["form"].ToString());
                def_Forms frm = formsRepo.GetFormById(formId);
                SessionHelper.SessionForm.formId         = formId;
                SessionHelper.SessionForm.formIdentifier = frm.identifier;
                var oldFrmResult = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);
                var newFrmResult = formsRepo.GetFormResultsByFormSubject(formId, oldFrmResult.subject).OrderByDescending(f => f.dateUpdated);
                if (newFrmResult.Any())
                {
                    // use most recent form result
                    SessionHelper.SessionForm.formResultId = newFrmResult.FirstOrDefault().formResultId;
                }

                Session["form"] = null;
                int part = int.Parse(Session["part"].ToString());
                SessionHelper.SessionForm.partId = part;
            }

            SessionForm sessionForm = SessionHelper.SessionForm;

            // set language ID in session based on meta-data (default to English) + other session vars
            CultureInfo   ci      = Thread.CurrentThread.CurrentUICulture;
            string        isoName = (ci == null) ? "en" : ci.TwoLetterISOLanguageName.ToLower();
            def_Languages lang    = formsRepo.GetLanguageByTwoLetterISOName(isoName);

            if (lang == null)
            {
                throw new Exception("could not find def_Language entry for iso code \"" + isoName + "\"");
            }
            else
            {
                sessionForm.langId = lang.langId;
            }



            // This is the master or top level sectionId, there can be mulitple subSections below this section.
            // The subSections will be in the SectionItems
            string sectionId = (sectionIdOverride == null) ? Request["sectionId"] as string : sectionIdOverride.ToString();

            mLogger.Debug("* * *  Results Template sectionId: {0}", sectionId);
            Session["section"] = sectionId;
            def_Sections sctn = formsRepo.GetSectionById(Convert.ToInt32(sectionId));

            sessionForm.sectionId = sctn.sectionId;

            // Create a new Assessments Model Template (AMT) that is used by the .cshtml template (Razor code)
            TemplateItems amt;

            if (sctn.href != null && (sctn.href.EndsWith("spprtNeedsScale.cshtml") || sctn.href.EndsWith("excptnlMedSpprtNeed.cshtml")))
            {
                amt = new QuestionListForm();
            }
            else
            {
                amt = new GeneralForm();
            }


            amt.thisSection   = sctn;
            amt.thisSectionId = sctn.sectionId;
            amt.formsRepo     = formsRepo;
            amt.formResultId  = sessionForm.formResultId;
            amt.currentUser   = SessionHelper.LoginInfo.LoginID;

            //amt.items = new List<def_Items>();
            amt.subSections = new List <def_Sections>();
            amt.fldLabels   = new Dictionary <string, string>();
            amt.itmPrompts  = new Dictionary <string, string>();
            amt.rspValues   = new Dictionary <string, string>();
            mLogger.Debug("* * *  ResultsController:Template sessionForm.formResultId: {0}", sessionForm.formResultId);
            def_FormResults fr = formsRepo.GetFormResultById(sessionForm.formResultId);

            mLogger.Debug("* * *  ResultsController:Template fr.formResultId: {0}", fr.formResultId);

            if (fr != null)
            {
                if (fr.formStatus == (byte)FormResults_formStatus.IN_PROGRESS)
                {
                    amt.inProgress = true;
                }
                if (fr.formStatus == (byte)FormResults_formStatus.NEW)
                {
                    amt.newAssmnt = true;
                }
            }



            //Start: added for enhancement Bug 13663 to be refactored

            amt.updatedDate = fr.dateUpdated;

            amt.formStatus = fr.formStatus;

            int statusMasterId = 0;

            def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(fr.formId);

            if (statusMaster != null)
            {
                statusMasterId = statusMaster.statusMasterId;

                def_StatusDetail statusdetails = formsRepo.GetStatusDetailBySortOrder(statusMasterId, fr.formStatus);

                amt.formSatusText = statusdetails.def_StatusText
                                    .Where(sd => sd.EnterpriseID == 8 && sd.langId == 1)
                                    .Select(z => z.displayText)
                                    .FirstOrDefault();
            }
            else
            {
                //This is used as currently we are showing In Progress for all items which do not have status
                amt.formSatusText = "In Progress";
            }

            amt.CanUserChangeStatus = true;

            if (UAS_Business_Functions.hasPermission(PermissionConstants.ASSIGNED, PermissionConstants.ASSMNTS))
            {
                amt.CanUserChangeStatus = false;
            }
            else if (amt.formSatusText.ToLower() == "needs review" || amt.formSatusText.ToLower().Contains("approved"))
            {
                if (!UAS_Business_Functions.hasPermission(PermissionConstants.APPROVE, PermissionConstants.ASSMNTS))
                {
                    amt.CanUserChangeStatus = false;
                }
            }
            else if (amt.formId == 18)
            {
                amt.CanUserChangeStatus = false;
            }



            var    formType    = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "C1_FormType");
            string formVariant = string.Empty;

            if (formType != null && formType.rspValue != null && formType.rspValue != String.Empty)
            {
                formVariant          = formType.rspValue;
                amt.FormVariantTitle = formVariant;
            }
            else
            {
                formsEntities context = new Assmnts.formsEntities();

                amt.FormVariantTitle = context.def_FormVariants
                                       .Where(fv => fv.formID == fr.formId)
                                       .Select(fv => fv.title)
                                       .FirstOrDefault();
            }

            //get the subject id from form result id
            if (fr.subject != null)
            {
                int subject = (int)fr.subject;

                var elgEndDate = formsRepo.GetResponseVariablesBySubjectForm(subject, 18, "C1_ProgramEligibleEndDate");

                string endDate = elgEndDate != null ? elgEndDate.rspValue : string.Empty;

                amt.EligibilityEnddate = endDate;

                amt.formResultUser = authClient.GetUserDisplay(subject);

                amt.clientId = authClient.GetExistingAdapIdentifier(amt.formResultUser.UserID, 8);
            }



            //End: added for enhancement Bug 13663 to be refactored


            amt.formId = sessionForm.formId;

            formsRepo.SortSectionItems(sctn);                   // This is both loading and sorting the SectionItems.

            // Get the Items in the SubSections *** NOTE: this only goes ONE level deep ***  Should be made recursive for unlimited levels !!!
            // amt.sections = new List<def_Sections>();
            foreach (def_SectionItems sctnItm in sctn.def_SectionItems.OrderBy(si => si.order))
            {
                if (sctnItm.subSectionId.GetValueOrDefault(0) == 0 || sctnItm.display == false)
                {
                    continue;
                }
                // def_Sections subSctns = sctnItm.def_SubSections.def_Sections;
                def_Sections subSctns = formsRepo.GetSubSectionById(sctnItm.subSectionId);

                //do not add notes section to the section list, (if there is a notes item, it will later be set as amt.notesItem)
                if (subSctns.multipleItemsPerPage == false)
                {
                    continue;
                }

                formsRepo.SortSectionItems(subSctns);                       // Load and sort the SectionItems
                amt.subSections.Add(subSctns);
                // GetItemLabelsResponses(fr.formResultId, amt, formsRepo.GetSectionItems(sctnItm.def_SubSections.def_Sections));
            }

            // RRB 5/28/15 *** This is only necessary for the Profile screens
            //             *** Getting and sorting the SectionItems above is only necessary for Question forms
            //             ***   In fact, it may duplicate what is being done in the templates
            formsRepo.GetItemListIncludingSubSections(sctn, amt);
            //GetItemListIncludingSubSections(sctn, amt);

            // Get the Notes items
            formsRepo.GetItemListForNotes(sctn, amt);

            formsRepo.GetItemLabelsResponses(fr.formResultId, amt, amt.items);

            //determine whether or not this user will be shown itemvariable identifiers as tooltips
            //TODO this is a DEV mode only thing
            amt.showItemVariableIdentifiersAsTooltips = Convert.ToBoolean(ConfigurationManager.AppSettings["showItemVariableIdentifiersAsTooltips"]);            // true;//new UAS.Business.UAS_Business_Functions().hasPermission(7,"assmnts");

            //save response values in session variable to later determine which ones were modified
            ////List<string> keysToClear = new List<string>();
            ////foreach (string key in Session.Keys)
            ////    if (key.StartsWith("frmOriginal___"))
            ////        keysToClear.Add(key);
            ////foreach (string key in keysToClear)
            ////    Session.Remove(key);
            //DateTime oneHourFromNow = DateTime.Now.AddHours(1);
            //foreach (string key in amt.rspValues.Keys)
            //{
            //Response.Cookies["frmOriginal___" + key].Value = amt.rspValues[key];
            //Response.Cookies["frmOriginal___" + key].Expires = oneHourFromNow;
            //}

            mLogger.Debug("* * *  AFTER GetItemLabelsResponses amt.items.Count: {0}", amt.items.Count);

            mLogger.Debug("* * *  amt.rspValues.Count (Total): {0}", amt.rspValues.Count);

            //populate required and readonly dictionaries
            amt.fldRequired = new Dictionary <string, bool>();
            amt.fldReadOnly = new Dictionary <string, bool>();
            List <def_SectionItems> siList = formsRepo.GetSectionItemsBySectionIdEnt(sctn.sectionId, SessionHelper.LoginStatus.EnterpriseID);

            if (amt.items != null)
            {
                foreach (def_Items itm in amt.items)
                {
                    if (amt.fldRequired.ContainsKey(itm.identifier))
                    {
                        throw new Exception("Found duplicate item identifier \"" + itm.identifier + "\"");
                    }
                    def_SectionItems si = siList.FirstOrDefault(s => (!s.subSectionId.HasValue && s.itemId == itm.itemId));

                    amt.fldRequired.Add(itm.identifier, (si == null) ? false : si.requiredForm);
                    amt.fldReadOnly.Add(itm.identifier, (si == null) ? false : si.readOnly);
                }
            }

            amt.isProfile = false;

            string[] uriSegments      = sctn.href.Split('/');
            string   templateFileName = uriSegments[uriSegments.Count() - 1];

            switch (templateFileName)
            {
            case "idprof1.cshtml":
            case "idprof2.cshtml":
            case "idprof2_Child.cshtml":
                if (mLogger.IsDebugEnabled)
                {
                    mLogger.Debug("showing section item identifiers:");
                    foreach (def_SectionItems si in siList)
                    {
                        mLogger.Debug("\t{0}", si.def_Items.identifier);
                    }
                }
                amt.notesItem            = siList.Single(si => si.def_Items.identifier.EndsWith("PageNotes_item")).def_Items;
                sessionForm.templateType = TemplateType.StdSectionItems;
                amt.isProfile            = true;
                break;

            default:                                // "SIS/section1a":     Default to the item list
                sessionForm.templateType = TemplateType.MultipleCommonItems;
                break;
            }

            // Setup the Previous / Next screens
            amt.prevScreenTitle = amt.prevScreenHref = String.Empty;
            amt.nextScreenTitle = amt.nextScreenHref = String.Empty;

            def_Parts prt = formsRepo.GetPartById(Convert.ToInt32(Session["part"]));



            List <def_Sections> partSections = formsRepo.GetSectionsInPart(prt);

            mLogger.Debug("* * *  ResultsController:Template method  * * * partSections.Count: {0}", partSections.Count);

            //get a list of parts in the current form

            def_Forms        form          = formsRepo.GetFormById(amt.formId);
            List <def_Parts> partsInForm   = formsRepo.GetFormParts(form);
            List <int>       partIdsInForm = partsInForm.Select(p => p.partId).ToList();
            // List<def_Parts> partsInForm = formsRepo.getFormParts(fr.def_Forms);



            //these variables will be assigned int he loop below
            int currentSectionIndex = 0;
            int prevSectionIndex    = 0;
            int nextSectionIndex    = 0;

            //start by assuming the previous and next section will be in the same part
            int currentPartId = (prt == null) ? sessionForm.partId : prt.partId;

            amt.thisPartId = currentPartId;

            amt.navPartId = currentPartId.ToString();
            int prevPartId = currentPartId;
            int nextPartId = currentPartId;

            //in a special cases one of these will be set to true
            bool veryFirst = false;
            bool veryLast  = false;

            bool foundSectionId = false;

            //iterate through possible section ids
            for (int idx = 0; idx < partSections.Count; idx++)
            {
                if (partSections[idx].sectionId == sessionForm.sectionId)
                {
                    //found the current section id, start with some assumptions about previous and next section ids
                    foundSectionId      = true;
                    currentSectionIndex = idx;
                    prevSectionIndex    = idx - 1;
                    nextSectionIndex    = idx + 1;

                    //we may have to link to the last section of the previous part
                    if (prevSectionIndex < 0)
                    {
                        //special case where we're on the first section of the first part
                        if (partIdsInForm.IndexOf(prt.partId) == 0)                        //currentPartId == 1)
                        {
                            //veryFirst = true;
                            int partIndexInForm = partsInForm.Count();
                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - 1]);
                            prevPartId       = partsInForm[partIndexInForm - 1].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                        else
                        {
                            int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm - i;
                                    break;
                                }
                            }

                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[listIndex]);
                            prevPartId       = partsInForm[listIndex].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                    }

                    // Oliver - same here the PartSections are ordered - just use the first one in the List.
                    // you can press F12 in Visual Studio and it will take you to the method.
                    // Data/Concrete/FormsRepository line 200
                    // The defined Interfaces are in Data/Abstract/IFormsRepository.cs

                    //we may have to link to he first section of the next part
                    if (nextSectionIndex > (partSections.Count - 1))
                    {
                        int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                        if (partIndexInForm == (partsInForm.Count() - 1))                          //formsRepo.GetPartById(nextPartId) == null)
                        {
                            //veryLast = true;
                            nextPartId       = partsInForm[0].partId;
                            nextSectionIndex = 0;
                        }
                        else
                        {
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partsInForm.Count() - 1 - partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm + i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm + i;
                                    break;
                                }
                            }

                            nextPartId       = partsInForm[listIndex].partId;
                            nextSectionIndex = 0;
                        }
                    }

                    break;
                }
            }

            if (!foundSectionId)
            {
                string msg = "current section id (" + sessionForm.sectionId + ") could not be found.\r\nListing candidates: (identifier / sectionId)";
                foreach (def_Sections sct in partSections)
                {
                    msg += (sct == null) ? "null" : ("\r\n" + sct.identifier + " / " + sct.sectionId);
                }
                throw new Exception(msg);
            }

            //print some debugging info
            if (mLogger.IsDebugEnabled)
            {
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryFirst ? "this is the very first part/section" : "prevPartId: " + prevPartId.ToString() +
                               ", prevSectionIndex: " + prevSectionIndex.ToString()));
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryLast ? "this is the very last part/section" : "nextPartId: " + nextPartId.ToString() +
                               ", nextSectionIndex: " + nextSectionIndex.ToString()));
            }
            if (partSections.Count > 0)
            {
                int    idxPeriod      = prt.identifier.IndexOf('.');
                string partShortTitle = (idxPeriod < 0) ? prt.identifier : prt.identifier.Substring(0, idxPeriod);
                // amt.thisScreenCaption = partShortTitle + " - " + partSections[thisIdx].identifier;
                amt.thisScreenCaption = partShortTitle + " - " + partSections[currentSectionIndex].identifier;
                amt.thisScreenTitle   = partSections[currentSectionIndex].title;

                if (!veryFirst)
                {
                    List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(formsRepo.GetPartById(prevPartId));
                    amt.prevScreenTitle     = prevPartSections[prevSectionIndex].title;
                    amt.prevScreenPartId    = prevPartId.ToString();
                    amt.prevScreenSectionId = prevPartSections[prevSectionIndex].sectionId.ToString();
                    amt.prevScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.prevScreenSectionId;
                    //if (prevPartId != currentPartId)
                    //    amt.previousScreenHref = "Parts?formResultId=" + formsRepo.GetPartById(prevPartId).partId.ToString() + amt.previousScreenHref;
                }

                if (!veryLast)
                {
                    def_Parts tempPart = formsRepo.GetPartById(nextPartId);
                    if (tempPart != null)
                    {
                        List <def_Sections> tempPartSections = formsRepo.GetSectionsInPart(tempPart);
                        amt.nextScreenTitle     = tempPartSections[nextSectionIndex].title;
                        amt.nextScreenPartId    = nextPartId.ToString();
                        amt.nextScreenSectionId = tempPartSections[nextSectionIndex].sectionId.ToString();
                        amt.nextScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.nextScreenSectionId;
                    }
                }
            }

            //pass a NavMenu model as a field in this items Model
            sessionForm.formIdentifier = form.identifier;
            amt.navMenuModel           = getNavMenuModel(sessionForm, amt);


            //Start: added for enhancement Bug 13663 to be refactored
            amt.navMenuModel.formResultUser      = amt.formResultUser;
            amt.navMenuModel.clientId            = amt.clientId;
            amt.navMenuModel.formSatusText       = amt.formSatusText;
            amt.navMenuModel.EligibilityEnddate  = amt.EligibilityEnddate;
            amt.navMenuModel.FormVariantTitle    = amt.FormVariantTitle;
            amt.navMenuModel.updatedDate         = amt.updatedDate;
            amt.navMenuModel.CanUserChangeStatus = amt.CanUserChangeStatus;
            amt.navMenuModel.formResultId        = amt.formResultId;
            //End: added for enhancement Bug 13663 to be refactored



            amt.ventureMode = SessionHelper.IsVentureMode;

            //special case for reports sections
            if ((sctn.identifier.EndsWith("Report") /*&& (Request["ignoreValidation"] as string) == null*/) ||
                sctn.href.Equals("~/Views/Templates/SIS/reportErrors.cshtml")
                )
            {
                if (!ValidateFormResult(fr, amt))
                {
                    return(View("~/Views/Templates/SIS/reportErrors.cshtml", amt));
                }
            }

            //add messages to the mdoel if necessary
            amt.validationMessages = validationMessages;             //validationMessages from method params, normally null

            //add a message to the model if necessary
            string message = Request["message"] as string;

            if (message != null)
            {
                if (amt.validationMessages == null)
                {
                    amt.validationMessages = new List <string>();
                }
                amt.validationMessages.Add(message);
            }

            // *** RRB 10/27/15 - added to fix problems with Venture and to be more efficient.
            if (!SessionHelper.IsVentureMode)
            {
                if (templateFileName.Equals("reportOptions.cshtml"))
                {
                    amt.reportOptions = AJBoggs.Sis.Reports.SisReportOptions.BuildPdfReportOptions(fr.EnterpriseID);
                }
            }

            // * * * OT 3/24/16 - for SIS supplemental questions, pre-populate sis_s41f with some item prompts from section 1A
            //  Don't do anything if there is already a response for sis_s41f
            //  (Bug 13132, #4 in description)
            if (sctn.identifier == "SQ" && amt.rspValues.ContainsKey("sis_s41f") && String.IsNullOrWhiteSpace(amt.rspValues["sis_s41f"]))
            {
                amt.rspValues["sis_s41f"] = String.Empty;

                //iterate through all section 1A items
                int          itmCount         = 0;
                bool         isSisCAssessment = fr.def_Forms.identifier.Equals("SIS-C");
                def_Sections sct1A            = formsRepo.GetSectionByIdentifier(isSisCAssessment ? "SIS-C 1A" : "SIS-A 1A");
                formsRepo.SortSectionItems(sct1A);
                foreach (def_SectionItems si in sct1A.def_SectionItems)
                {
                    def_Sections subSct = formsRepo.GetSubSectionById(si.subSectionId);
                    formsRepo.SortSectionItems(subSct);
                    foreach (def_SectionItems subSi in subSct.def_SectionItems)
                    {
                        //for items that have an itemVariable with suffix "_ExMedSupport", check if that itemVariable have a response of "2"
                        def_Items itm = subSi.def_Items;
                        itmCount++;
                        def_ItemVariables exMedSupIv = itm.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_ExMedSupport")).FirstOrDefault();
                        if (exMedSupIv != null)
                        {
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, exMedSupIv.itemVariableId);
                            if (rv != null && !String.IsNullOrWhiteSpace(rv.rspValue) && rv.rspValue == "2")
                            {
                                //append the item prompt to the pre-populated response for sis_s41f
                                amt.rspValues["sis_s41f"] += itmCount + ". " + itm.prompt + "\n";
                            }
                        }
                    }
                }
            }

            // *** OT 11/23/15 - added as test for Bug 12910 - Comparison: what changed from last approved application?
            //if we're on the ADAP form...
            if (form.identifier.Contains("ADAP"))
            {
                //get the previous formresult
                int?sortOrder = formsRepo.GetStatusDetailByMasterIdentifier(1, "CANCELLED").sortOrder;
                int userId    = fr.subject.HasValue ? fr.subject.Value : -1;
                if (userId < 1)
                {
                    mLogger.Warn("subject < 1 for form result having formResultId = {0}.", fr.formResultId);
                }
                // * * * OT 1-19-16 added stipulation that "prevRes" is not the current formResult "fr"
                def_FormResults prevRes = null;
                if (sortOrder.HasValue && userId > 0)
                {
                    prevRes = formsRepo.GetEntities <def_FormResults>(
                        x => x.formId == fr.formId &&
                        x.formResultId != fr.formResultId &&
                        x.subject == userId &&
                        x.formStatus != sortOrder)
                              .OrderByDescending(x => x.dateUpdated)
                              .FirstOrDefault();
                }
                // * * * OT 1-19-16 in order to duplicate existing behavior and avoid crashes,
                // default to using the current formResult as the previous if no others are applicable
                if (prevRes == null)
                {
                    prevRes = fr;
                }

                List <string> remainingIdentifiers = amt.rspValues.Keys.ToList();

                IList <def_ItemResults> previousItemResults = formsRepo.GetItemResults(prevRes.formResultId);
                foreach (def_ItemResults ir in previousItemResults)
                {
                    foreach (def_ResponseVariables rv in ir.def_ResponseVariables)
                    {
                        if (rv.def_ItemVariables == null)
                        {
                            continue;
                        }

                        remainingIdentifiers.Remove(rv.def_ItemVariables.identifier);
                        string rspValue = HttpUtility.HtmlDecode(rv.rspValue);

                        amt.rspValues.Add("PREVIOUS_" + rv.def_ItemVariables.identifier, rspValue);
                    }
                }

                //populate amt with empty responses for fields Bmissing from previous formResult
                foreach (string ident in remainingIdentifiers)
                {
                    amt.rspValues.Add("PREVIOUS_" + ident, "");
                }
            }

            SessionHelper.ResponseValues = amt.rspValues;

            //Displays save message
            ViewBag.Notify        = "";
            ViewBag.NotifyMessage = "";
            if (Session["IsPageLoad"] != null)
            {
                if (!(bool)Session["IsPageLoad"])
                {
                    if (TempData["Savemsg"] != null && TempData["SavemsgHeader"] != null)
                    {
                        if (TempData["Savemsg"].ToString() != "" && TempData["SavemsgHeader"].ToString() != "")
                        {
                            ViewBag.Notify        = TempData["SavemsgHeader"].ToString();
                            ViewBag.NotifyMessage = TempData["Savemsg"].ToString();
                        }
                    }
                }
            }


            TempData["SavemsgHeader"] = "";
            TempData["Savemsg"]       = "";
            return(View(sctn.href, amt));
        }