Beispiel #1
0
        public ActionResult ReserveShowdata(string empsn = "", string empdept = "")
        {
            string role = Session["SessionRole"].ToString();

            if (role == "Manage")
            {
                empdept = Session["SessionEmpDept"].ToString();
            }
            FormViewModel VMList = new FormViewModel();

            VMList.ECSdata = (from R in db.RecordData
                              join E in db.EmpData on R.EmpID equals E.EmpID
                              where R.RecordState == "已預約" && R.Disable == "N" &&
                              (!string.IsNullOrEmpty(empdept) ? E.EmpDept == empdept : true) &&
                              (!string.IsNullOrEmpty(empsn) ? E.EmpSN == empsn : true)
                              orderby R.RecordNumber descending /*降冪排序*/
                              select new ECSViewModel
            {
                RecordNumber = R.RecordNumber,
                EmpID = E.EmpID,
                EmpSN = E.EmpSN,
                EmpDept = E.EmpDept,
                EmpName = E.EmpName,
                TimeLend = R.TimeLend,
                UseDay = R.UseDay
            }).ToList();
            VMList.IsSuccess = true;
            if (VMList.ECSdata.Count == 0)
            {
                VMList.IsSuccess = false;
                VMList.Msg       = "No Data.";
            }
            return(PartialView(VMList));
        }
Beispiel #2
0
        public override object GetContent(object model)
        {
            securityService.CreateAccessContext();

            if (FormId > 0)
            {
                SubmissionService subSrv = new SubmissionService(new CatfishDbContext());

                Form form = subSrv.CreateSubmissionForm(
                    FormId,
                    EnforceLists,
                    ShuffleBlocks,
                    ShuffleQuestions,
                    QuestionStepOption,
                    QuestionPartsStepOption);

                if (EnableReferenceCodes)
                {
                    Random rand = new Random();
                    form.ReferenceCode = DateTime.Now.ToString("yyMMdd-HHmmss-") + rand.Next(1000, 10000);
                }

                FormViewModel = new FormViewModel()
                {
                    Form         = form,
                    ItemId       = 0,
                    MaxImageSize = MaxPixelLength
                };
            }

            return(base.GetContent(model));
        }
        public void AddNewPostNullImgTest()
        {
            var data = _dataPosts();

            AdminController controller = new AdminController(
                MoqGenerator.GetMockRepository(data, _dataCategories()).Object,
                MoqGenerator.GetImageManager().Object,
                MoqGenerator.GetHttpContextServiec().Object);

            FormViewModel model = new FormViewModel
            {
                Post = _newPost(),
                Img  = null
            };

            var result = controller.Save(model);

            Assert.IsInstanceOfType(result, typeof(ViewResult));

            var viewResult      = result as ViewResult;
            var redirectedModel = viewResult.Model as NewPostViewModel;

            Assert.AreEqual(viewResult.ViewName, "PostForge");
            Assert.AreEqual(redirectedModel.Post.ID, 33);
        }
        private TemplateViewModel CreateFormAndTemplateWithSampleField()
        {
            FormViewModel formViewModel = new FormViewModel();

            formViewModel.Title = "Required Form Name";
            Template template = _formManager.CreateNewFormAndTemplate(formViewModel);

            Assert.IsNotNull(template);

            TemplateViewModel templateViewModel = _formManager.FindTemplateToEdit(template.TemplateID);

            FormCollection fieldCollection;
            IDictionary <string, string> fields;

            CeateFieldForm(1, out fieldCollection, out fields);

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            templateViewModel = _formManager.FindTemplateToEdit(template.TemplateID);
            Assert.IsNotNull(templateViewModel.Fields);
            Assert.AreEqual(1, templateViewModel.Fields.Count);

            templateViewModel.Entries = _formManager.HasSubmissions(templateViewModel).ToList();
            Assert.AreEqual(0, templateViewModel.Entries.Count);
            return(templateViewModel);
        }
 public IActionResult CreateAuction(FormViewModel model)
 {
     if (model.bid <= 0)
     {
         TempData["bid_error"] = "Starting bid must be higher than 0!";
         return(View("newauction"));
     }
     if (model.end_date <= DateTime.Now)
     {
         TempData["date_error"] = "Only future dates!";
         return(View("newauction"));
     }
     if (ModelState.IsValid)
     {
         Product newProduct = new Product {
             name        = model.name,
             description = model.description,
             end_date    = model.end_date,
             bid         = model.bid,
             sellerid    = (int)HttpContext.Session.GetInt32("current_userid")
         };
         _context.products.Add(newProduct);
         _context.SaveChanges();
         return(RedirectToAction("Dashboard"));
     }
     return(View("newauction"));
 }
Beispiel #6
0
        public FormViewModel Get(int id)
        {
            var form = new FormViewModel();

            using (var db = new FormContext())
            {
                form = db.Forms.AsQueryable().Where(f => f.FormId == id).Select(s => new FormViewModel
                {
                    FormId    = s.FormId,
                    Name      = s.Name,
                    Questions = s.Questions.OrderBy(q => q.Order).Select(q => new FormQuestion
                    {
                        QuestionId = q.QuestionId,
                        Order      = q.Order,
                        Name       = q.Name,
                        Label      = q.Label,
                        Type       = q.Type,
                        Options    = q.Options.OrderBy(o => o.OptionId).Select(o => new FormOption {
                            OptionId = o.OptionId, Label = o.Label, Value = o.Value
                        }).ToList()
                    }).ToList()
                }
                                                                                ).FirstOrDefault();
            }
            return(form);
        }
Beispiel #7
0
        public ActionResult ReturnShowdata(string cardid = "", string empdept = "")
        {
            FormViewModel ReturnList = new FormViewModel();
            string        role       = Session["SessionRole"].ToString();

            if (role == "Manage")
            {
                empdept = Session["SessionEmpDept"].ToString();
            }
            ReturnList.ECSdata = (from R in db.RecordData
                                  join E in db.EmpData on R.EmpID equals E.EmpID
                                  join C in db.CardData on R.CardID equals C.CardID
                                  where R.RecordState == "已借用" && (!string.IsNullOrEmpty(cardid) ? R.CardID == cardid : true) &&
                                  (!string.IsNullOrEmpty(empdept) ? E.EmpDept == empdept : true)
                                  orderby R.RecordNumber descending /*降冪排序*/
                                  select new ECSViewModel
            {
                CardName = C.CardName,
                CardID = C.CardID,
                EmpID = E.EmpID,
                EmpDept = E.EmpDept,
                EmpName = E.EmpName,
                TimeLend = R.TimeLend,
                UseDay = R.UseDay,
                RecordNumber = R.RecordNumber
            }).ToList();
            ReturnList.IsSuccess = true;
            if (ReturnList.ECSdata.Count == 0)
            {
                ReturnList.IsSuccess = false;
                ReturnList.Msg       = "No Data.";
            }
            return(PartialView(ReturnList));
        }
Beispiel #8
0
        public void CreateQuestionGeneric(FormViewModel _formViewModel, List <QuestionCreateViewModel> _listQuestionCreateViewModel)
        {
            FormViewModel formViewModel = _formViewModel;
            List <QuestionCreateViewModel> listQuestionCreateViewModel = _listQuestionCreateViewModel;

            if (listQuestionCreateViewModel == null)
            {
                return;
            }

            foreach (var questionCreateViewModel in listQuestionCreateViewModel)
            {
                ElementViewModel elementViewModel = new ElementViewModel
                {
                    Name        = questionCreateViewModel.ElementViewModel.Name,
                    Description = questionCreateViewModel.ElementViewModel.Description
                };
                // elementBL.Create(elementViewModel); // ???

                QuestionViewModel questionViewModel = new QuestionViewModel
                {
                    Name      = questionCreateViewModel.QuestionViewModel.Name,
                    FormId    = formBL.GetId(formViewModel),
                    ElementId = elementBL.GetId(elementViewModel)
                };
                questionBL.Create(questionViewModel);
                int questionId = questionBL.GetId(questionViewModel);

                foreach (var answerViewModel in questionCreateViewModel.AnswerViewModel)
                {
                    AnswerViewModel answerVM = new AnswerViewModel
                    {
                        Name       = answerViewModel.Name,
                        QuestionId = questionId
                    };
                    answerBL.Create(answerVM);
                }

                foreach (var attributeViewModel in questionCreateViewModel.AttributeViewModel)
                {
                    attributeVM = new AttributeViewModel
                    {
                        Name        = attributeViewModel.Name,
                        DisplayName = attributeViewModel.DisplayName,
                        QuestionId  = questionId
                    };
                    attributeBL.Create(attributeVM);
                }

                foreach (var attributeResultViewModel in questionCreateViewModel.AttributeResultViewModel)
                {
                    AttributeResultViewModel attributeResult = new AttributeResultViewModel
                    {
                        Value       = attributeResultViewModel.Value,
                        AttributeId = attributeBL.GetId(attributeVM)
                    };
                    attributeResultBL.Create(attributeResult);
                }
            }
        }
Beispiel #9
0
        public ActionResult Save(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new FormViewModel
                {
                    Customer        = customer,
                    MembershipTypes = _dbContext.MembershipTypes.ToList()
                };
                return(View("Form", viewModel));
            }

            if (customer.Id == 0)
            {
                _dbContext.Customers.Add(customer);
            }
            else
            {
                var customerInDb = _dbContext.Customers.Single(c => c.Id == customer.Id);
                //TryUpdateModel(customerInDb); //this updates all object properties
                customerInDb.Name      = customer.Name;
                customerInDb.BirthDate = customer.BirthDate;
                customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
                customerInDb.MembershipTypeId         = customer.MembershipTypeId;
            }
            _dbContext.SaveChanges();
            return(RedirectToAction("Index", "Customer"));
        }
        //Connect form to customer
        public ActionResult EditCustomer(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Customer customer = customerRepository.Customers.FirstOrDefault(g => g.CustomerID == id);
            Contact  contact  = contactRepository.Contacts.FirstOrDefault(c => c.ContactID == id);

            if (customer == null)
            {
                return(HttpNotFound());
            }

            FormViewModel formViewModel = new FormViewModel
            {
                GetCustomerViewModel = new CustomerViewModel
                {
                    CustomerID  = customer.CustomerID,
                    PhoneNumber = customer.PhoneNumber
                },

                GetContactViewModel = new ContactViewModel
                {
                    ContactID = contact.ContactID,
                    FirstName = contact.FirstName,
                    LastName  = contact.LastName,
                    PostCode  = contact.PostCode,
                    Email     = contact.Email
                }
            };

            return(View(formViewModel));
        }
        /// <summary>
        /// 自由表单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fid"></param>
        /// <param name="tn"></param>
        /// <param name="frm"></param>
        /// <returns></returns>
        public IActionResult FreeFormView(string fid, string tn = "", string frm = "")
        {
            if (frm == "")
            {
                //jqgrid弹出窗口,统一设置为这个值,frmname即为frm-tablename
                frm = "jqgriddataform";
            }
            bool hasScroll = true;

            if (Request.Query.ContainsKey("noscroll"))
            {
                hasScroll = false;
            }
            //var tn = Request.Query["tn"];
            FormViewModel fd = new FormViewModel();

            fd.FormId = frm;
            QuerySet sq = new QuerySet();

            sq.TableName = tn;

            sq.InitWhere = "Fid=@Fid";
            sq.Parameters.Add(new Parameter("Fid", fid));


            fd.QueryOption = sq;
            fd.TableName   = tn;
            ViewBag.Scroll = hasScroll;
            return(View(fd));
        }
        public async Task <IActionResult> Edit(FormViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(NotFound());
            }
            try
            {
                model.UserId = (await userManager.GetUserAsync(User)).Id;

                foreach (var question in model.MultipleChoiceQuestions)
                {
                    foreach (var desc in question.OptionsDescriptions)
                    {
                        var optionModel = new MultipleChoiceOptionViewModel();
                        optionModel.OptionDescription = desc;
                        question.Options.Add(optionModel);
                    }
                }

                this.toastNotification.AddSuccessToastMessage("Form was successfully created");
                await this.formServices.CreateFormAsync(model.MapFrom());
            }
            catch (Exception)
            {
                this.toastNotification.AddErrorToastMessage("Something went wrong... Please try again!");
            }

            return(RedirectToAction("ListForms"));
        }
Beispiel #13
0
        public ActionResult Edit(long id)
        {
            var frm = formService.GetForm(id);

            if (frm != null)
            {
                var formViewModel = new FormViewModel();
                formViewModel.Id                  = frm.Id;
                formViewModel.FormName            = frm.FormName;
                formViewModel.Description         = frm.Description;
                formViewModel.ClosingDescription  = frm.ClosingDescription;
                formViewModel.EmailTo             = frm.EmailTo;
                formViewModel.EmailCc             = frm.EmailCc;
                formViewModel.EmailBcc            = frm.EmailBcc;
                formViewModel.FormFields          = frm.FormFields;
                formViewModel.GoogleAnalyticsCode = frm.GoogleAnalyticsCode;
                formViewModel.IsPublished         = frm.IsPublished;
                formViewModel.AddedBy             = frm.AddedBy;
                formViewModel.AddedDate           = frm.AddedDate;
                formViewModel.ModifiedBy          = frm.ModifiedBy;
                formViewModel.ModifiedDate        = frm.ModifiedDate;
                ViewBag.Forms      = new SelectList(formService.GetForms(), "Id", "FormName");
                ViewBag.FormFields = new SelectList(formFieldService.GetFormFields(), "Id", "Name");
                return(View(formViewModel));
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult Save(FormViewModel formData)
        {
            if (formData == null)
            {
                return(RedirectToAction("NewPost"));
            }

            var model = new NewPostViewModel()
            {
                Categories = _unitOfWork.Categories.GetAll()
                             .Select(Mapper.Map <Category, CategoryDto>).ToList(),
                Post = formData.Post,
                Img  = formData.Img
            };

            if (!ModelState.IsValid)
            {
                return(View("PostForge", model));
            }

            formData.Post.Img = _imageManager.SaveImage(formData.Img,
                                                        _contextService.GetMapPath(_path));

            if (formData.Post.Img == null)
            {
                return(View("PostForge", model));
            }

            _unitOfWork.Posts.Add(Mapper.Map <PostDto, Post>(formData.Post));
            _unitOfWork.Complete();

            return(RedirectToAction("Index", "Post"));
        }
Beispiel #15
0
        /// <summary>
        /// Populates the return form.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var queryStringValue = Request.QueryString.Value ?? string.Empty;
            var queryString      = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(queryStringValue);
            var viewModel        = new FormViewModel();

            if (queryString.ContainsKey(StandardAuthorizationResponseNames.AccessTokenName))
            {
                viewModel.AccessToken = queryString[StandardAuthorizationResponseNames.AccessTokenName];
            }

            if (queryString.ContainsKey(StandardAuthorizationResponseNames.AuthorizationCodeName))
            {
                viewModel.AuthorizationCode = queryString[StandardAuthorizationResponseNames.AuthorizationCodeName];
            }

            if (queryString.ContainsKey(StandardAuthorizationResponseNames.IdTokenName))
            {
                viewModel.IdToken = queryString[StandardAuthorizationResponseNames.IdTokenName];
            }

            if (queryString.ContainsKey(StandardAuthorizationResponseNames.StateName))
            {
                viewModel.State = queryString[StandardAuthorizationResponseNames.StateName];
            }

            if (queryString.ContainsKey("redirect_uri"))
            {
                viewModel.RedirectUri = queryString["redirect_uri"];
            }

            return(Ok(viewModel));
        }
        public JsonResult FreshCoupon(FormViewModel model)
        {
            var isEqual = couponRepository.Coupons.Any(x => x.CouponNumber == model.GetTransactionViewModel.CouponNumber); //true if coupon exists on list of coupons

            if (!isEqual)
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }

            var isInUse = couponRepository.Coupons.FirstOrDefault(x => x.CouponNumber == model.GetTransactionViewModel.CouponNumber).CouponUsed; //true if cupon already used

            if (isInUse == true)
            {
                int transId = 0;
                var coupon  = couponRepository.Coupons.FirstOrDefault(x => x.CouponNumber == model.GetTransactionViewModel.CouponNumber).TransactionID; //checks for transaction paired to coupon
                var trans   = model.GetTransactionViewModel;
                if (trans != null)
                {
                    transId = trans.TransactionID;
                }

                if (coupon != transId) //check if used coupon is already assigned to this customer
                {
                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
            }

            return(Json(true, JsonRequestBehavior.AllowGet));
        }
        public JsonResult SaveForm(FormDesginViewModel form)
        {
            if (!ModelState.IsValid)
            {
                return(Json(Utils.ParseError(ModelState.Values)));
            }

            if (Session["MenuId"] != null && Session["MenuId"].ToString().Length > 0 && form.MenuId == null)
            {
                form.MenuId = int.Parse(Session["MenuId"].ToString());
            }
            _hrUnitOfWork.PagesRepository.ApplyFormDesignChanges(CompanyId, form);

            var errors = SaveChanges(Language);

            if (errors.Count() > 0)
            {
                string message = errors.First().errors.First().message;
                return(Json(message));
            }
            else
            {
                FormViewModel formvm = new FormViewModel();
                string        key    = CompanyId + form.ObjectName + form.Version + Language;
                formvm = _hrUnitOfWork.PagesRepository.GetFormInfo(CompanyId, form.ObjectName, form.Version, Language, Session["RoleId"]?.ToString());

                if (_hrUnitOfWork.PagesRepository.CacheManager.IsSet(key))
                {
                    _hrUnitOfWork.PagesRepository.CacheManager.Remove(key);
                }

                _hrUnitOfWork.PagesRepository.CacheManager.Set(key, formvm, 0);
            }
            return(Json("OK"));
        }
        public ActionResult RedeemPrize(FormViewModel model)
        {
            var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();

            foreach (var item in errors)
            {
                Debug.WriteLine(item.Key + " : " + item.Errors);
            }
            if (ModelState.IsValid)
            {
                Transaction transaction = new Transaction
                {
                    CouponNumber      = model.GetTransactionViewModel.CouponNumber,
                    CustomerID        = model.GetTransactionViewModel.CustomerID,
                    PrizeID           = model.GetTransactionViewModel.PrizeID,
                    PrizeRecieved     = true,
                    TransactionDate   = model.GetTransactionViewModel.TransactionDate,
                    TransactionID     = model.GetTransactionViewModel.TransactionID,
                    TransactionNumber = model.GetTransactionViewModel.TransactionNumber,
                    TransactionValue  = model.GetTransactionViewModel.TransactionValue
                };

                transactionRepository.ConfirmPrize(transaction.TransactionID);

                TempData["message"] = string.Format("{0} is saved", model.GetCustomerViewModel.PhoneNumber);
                return(RedirectToAction("TransactionList"));
            }
            else
            {
                return(View("RedeemPrize", model));
            }
        }
Beispiel #19
0
        public ActionResult FormSubmissionAcknowledgement(string message)
        {
            FormViewModel viewModel = new FormViewModel();

            viewModel.Acknowledgement = message;
            return(View("FormSubmissionAcknowledgement", viewModel));
        }
        public ActionResult EditCustomer(FormViewModel model)
        {
            if (ModelState.IsValid)
            {
                Customer customer = new Customer
                {
                    CustomerID  = model.GetCustomerViewModel.CustomerID,
                    PhoneNumber = model.GetCustomerViewModel.PhoneNumber
                };

                Contact contact = new Contact
                {
                    ContactID = model.GetContactViewModel.ContactID,
                    FirstName = model.GetContactViewModel.FirstName,
                    LastName  = model.GetContactViewModel.LastName,
                    PostCode  = model.GetContactViewModel.PostCode,
                    Email     = model.GetContactViewModel.Email
                };

                customerRepository.SaveCustomer(customer);
                contactRepository.SaveContact(contact, customer);

                TempData["message"] = string.Format("{0} is saved", model.GetCustomerViewModel.PhoneNumber);
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View("EditCustomer", model));
            }
        }
Beispiel #21
0
        public ActionResult Index(FormViewModel data)
        {
            if (ModelState.IsValid)
            {
                var searchModel = new SearchViewModel {
                    amount = data.Amount, duration = data.Duration, type = data.Type
                };
                Search searchObj = _mapper.Map <Search>(searchModel);
                _searchRepository.Add(searchObj);
                if (_searchRepository.Save())
                {
                    var result = _providerRepository.GetProviders(data.Amount, data.Duration, data.Type);
                    if (result == null)
                    {
                        Session["result"] = null;
                        return(RedirectToAction("Providers"));
                    }
                    var providerList = _mapper.Map <List <ProviderViewModel> >(result);
                    Session["result"] = providerList;
                    Session["search"] = searchModel;
                    return(RedirectToAction("Providers"));
                }

                return(View());
            }
            else
            {
                return(View());
            }
        }
Beispiel #22
0
        public IActionResult GetAllStatementForms(int id, [FromServices] IIoTManager ioTManager)
        {
            List <Form> forms = _formManager.GetAllStatementForms(id).ToList();

            List <FormViewModel> formViewModels = new List <FormViewModel>();

            foreach (Form form in forms)
            {
                IotLink       iotLink       = ioTManager.GetIoTLinkByForm(form);
                FormViewModel formViewModel = new FormViewModel()
                {
                    Title     = form.Title,
                    FormId    = form.FormId,
                    Questions = new List <FormQuestionViewModel>(),
                    IotLink   = iotLink
                };

                FormQuestionViewModel question = new FormQuestionViewModel()
                {
                    Question = form.Questions[0].QuestionString
                };

                formViewModel.Questions.Add(question);
                formViewModels.Add(formViewModel);
            }

            return(Ok(formViewModels));
        }
        public async Task Create(FormViewModel model)
        {
            if (!ModelState.IsValid)
            {
                NotFound();
            }
            try
            {
                model.UserId = (await userManager.GetUserAsync(User)).Id;

                var createOptionsForMultipleChoiceQuestion = new Parser();

                if (createOptionsForMultipleChoiceQuestion.MapMultipleQuestionsWithOptions(model))
                {
                    var formDto = model.MapFrom();
                    var newForm = await this.formServices.CreateFormAsync(formDto);

                    newForm.MapFrom();

                    RedirectToAction("Index", "Home");
                }
                else
                {
                    this.toastNotification.AddErrorToastMessage("Something went wrong... Please try again!");
                }
            }
            catch (Exception)
            {
                NotFound();
            }
        }
Beispiel #24
0
        private void OnFormSelected(object sender, FormViewModel e)
        {
            FormViewModel = e;

            _form              = e.Form;
            _form.OnFormEvent += NameForm_OnFormEvent;
        }
        public async Task <IActionResult> Answer(FormViewModel form)
        {
            if (!ModelState.IsValid)
            {
                return(NotFound());
            }
            try
            {
                var validator   = new DataValidator();
                var formIsValid = validator.ValidateAnswer(form);

                if (formIsValid)
                {
                    this.toastNotification.AddSuccessToastMessage("Form was successfully answered");
                    var isAnswerSaved = await this.formServices.CreateAnswer(form.MapFrom());
                }
                else
                {
                    this.toastNotification.AddErrorToastMessage("You missed answering some required questions. Please review your answers again.");
                    return(RedirectToAction("Answer", "Form", new { id = form.Id }));
                }
            }
            catch (Exception)
            {
                this.toastNotification.AddErrorToastMessage("Something went wrong... Please try again!");
                return(RedirectToAction("Answer", "Form", new { id = form.Id }));
            }
            return(RedirectToAction("Index", "Home"));
        }
Beispiel #26
0
        public IActionResult FormPage(FormViewModel form)
        {
            //This is adding the appointment to the database and deleting the time.  We chose to delete the time for the simplicity of this assignment.  Since there are no CRUD requirements, we figured this would be faster and easier.
            if (ModelState.IsValid)
            {
                Appointment newAppointment = new Appointment();

                newAppointment.AppointmentTime = new System.DateTime(form.Year, form.Month, form.Day, form.Hour, 0, 0);
                newAppointment.GroupName       = form.appointment.GroupName;
                newAppointment.GroupSize       = form.appointment.GroupSize;
                newAppointment.Email           = form.appointment.Email;
                newAppointment.Phone           = form.appointment.Phone;

                context.Appointments.Add(newAppointment);

                context.AvailableTimes.Remove(context.AvailableTimes.Find(form.TimeId));

                context.SaveChanges();

                return(View("Confirmation", new ConfirmationViewModel
                {
                    Year = newAppointment.AppointmentTime.Year,
                    Month = newAppointment.AppointmentTime.Month,
                    Hour = newAppointment.AppointmentTime.Hour,
                    Day = newAppointment.AppointmentTime.Day
                }));
            }
            else
            {
                return(View());
            }
        }
Beispiel #27
0
        public JsonResult CreateNewForm(FormViewModel form)
        {
            ModelState.Remove("Id");
            TryValidateModel(form);

            if (ModelState.IsValid)
            {
                form.Status = (int)EntityStatusType.Current;
                if (form.Id > 0)
                {
                    return(EditForm(form));
                }

                using (var adminUow = DependencyResolver.Current.GetService <IAdminUnitOfWork>())
                {
                    adminUow.FormRepository.CreateNewForm(form);
                    adminUow.Commit();
                }
                var result = new List <string> {
                    "success", form.StudyId.ToString(CultureInfo.InvariantCulture)
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
            return(Json("Form submission error. Please check all required fields", JsonRequestBehavior.AllowGet));
        }
Beispiel #28
0
        public FormViewModel GetSavedForm(int formId, int respondentId)
        {
            var form = new FormViewModel();

            using (var db = new FormContext())
            {
                var respondent = db.Respondents.AsQueryable().Where(r => r.RespondentId == respondentId).FirstOrDefault();
                form = db.Forms.AsQueryable().Where(f => f.FormId == formId).Select(s => new FormViewModel
                {
                    FormId = s.FormId,
                    Name   = s.Name,
                    RespondentFirstName    = respondent.FirstName,
                    RespondentLastName     = respondent.LastName,
                    RespondentEmailAddress = respondent.EmailAddress,
                    Questions = s.Questions.OrderBy(q => q.QuestionId).Select(q => new FormQuestion
                    {
                        QuestionId = q.QuestionId,
                        Name       = q.Name,
                        Label      = q.Label,
                        Type       = q.Type,
                        Value      = db.Responses.Where(r => r.QuestionId == q.QuestionId && r.RespondentId == respondent.RespondentId).Select(ss => ss.Value).FirstOrDefault(),
                        Options    = q.Options.OrderBy(o => o.OptionId).Select(o => new FormOption {
                            Label = o.Label, Value = o.Value
                        }).ToList()
                    }).ToList()
                }
                                                                                    ).FirstOrDefault();
            }
            return(form);
        }
        public ActionResult CouponRegister(FormViewModel model)
        {
            if (ModelState.IsValid)
            {
                Transaction transaction = new Transaction
                {
                    TransactionID     = model.GetTransactionViewModel.TransactionID,
                    CustomerID        = model.GetTransactionViewModel.CustomerID,
                    PrizeID           = model.GetTransactionViewModel.PrizeID,
                    CouponNumber      = model.GetTransactionViewModel.CouponNumber,
                    TransactionNumber = model.GetTransactionViewModel.TransactionNumber,
                    TransactionValue  = model.GetTransactionViewModel.TransactionValue,
                    TransactionDate   = model.GetTransactionViewModel.TransactionDate
                };

                couponRepository.RedeemCoupon(transaction);
                transactionRepository.AddTransaction(transaction);

                TempData["message"] = string.Format("{0} is saved", model.GetTransactionViewModel.TransactionNumber);
                return(RedirectToAction("TransactionList"));
            }
            else
            {
                return(View("CouponRegister", model));
            }
        }
Beispiel #30
0
        public static FormViewModel ToModel(this IForm form)
        {
            var formVm = new FormViewModel
            {
                Code            = form.Code,
                CreatedBy       = form.CreatedBy,
                CreatedOn       = form.CreatedOn,
                Description     = form.Description,
                Directions      = form.Directions,
                IsDoubleChecked = form.IsDoubleChecked,
                FormTypeId      = form.FormTypeId,
                Header          = form.Header,
                Id                 = form.Id,
                IsActive           = form.IsActive,
                IsFilledBySubject  = form.IsFilledBySubject,
                LayoutTypeId       = form.LayoutTypeId,
                Name               = form.Name,
                ShowTotalScore     = form.ShowTotalScore,
                SortOrder          = form.SortOrder,
                Status             = form.Status,
                StudyId            = form.StudyId,
                Title              = form.Title,
                Trailer            = form.Trailer,
                UpdatedBy          = form.UpdatedBy,
                UpdatedOn          = form.UpdatedOn,
                NotifyOnChange     = form.NotifyOnChange,
                NotifyOnCompletion = form.NotifyOnCompletion
            };

            return(formVm);
        }
        public void GivenModelBecomeValid_WhenCommandFires_ThenCanExecuteReturnsTrue()
        {
            Assert.IsFalse(formViewModel.Edit.CanExecute(null));

            formViewModel.Text = "hello";
            formViewModel.Title = "My name is  ";

            Assert.IsTrue(formViewModel.Edit.CanExecute(null));

            formViewModel = new FormViewModel();
        }
        public void InvalidViewModelRaisesErrors()
        {
            var viewModel = new FormViewModel()
                                {
                                    Text = "2",
                                    Title = "This cant be true"
                                };

            var result = provider.Validate(viewModel);

            Assert.That(!result.IsModelValid(), "Model should be invalid but it's not");
            Assert.That(result.GetErrorCount() == 2, "There should be 2 errors");
        }
 /// <summary>
 /// Validates the form model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="modelState">State of the model.</param>
 public static void ValidateForm(FormViewModel model, ModelStateDictionary modelState)
 {
     if (model.ShowSubmitButton && String.IsNullOrEmpty(model.SubmitButtonText))
     {
         modelState.AddModelError(PropertyName.For<FormViewModel>(item => item.SubmitButtonText),
             ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(FormViewModel),
             PropertyName.For<FormViewModel>(item => item.SubmitButtonText), "required", null));
     }
     if (model.ShowResetButton && String.IsNullOrEmpty(model.ResetButtonText))
     {
         modelState.AddModelError(PropertyName.For<FormViewModel>(item => item.ResetButtonText),
              ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(FormViewModel),
              PropertyName.For<FormViewModel>(item => item.ResetButtonText), "required", null));
     }
 }
        /// <summary>
        /// Reads from view data.
        /// </summary>
        /// <param name="formViewModel">The field view model.</param>
        /// <param name="viewData">The view data.</param>
        private static void ReadFromViewData(FormViewModel formViewModel, ViewDataDictionary viewData)
        {
            Assert.ArgumentNotNull(formViewModel, nameof(formViewModel));
              Assert.ArgumentNotNull(viewData, nameof(viewData));

              for (int i = 0; i < formViewModel.Sections.Count; ++i)
              {
            var section = formViewModel.Sections[i];
            for (int j = 0; j < section.Fields.Count; ++j)
            {
              var field = section.Fields[j];

              string viewDataKey = $"{formViewModel.ClientId}.Sections[{i}].Fields[{j}].Value";
              if (viewData.ModelState.ContainsKey(viewDataKey))
              {
            var conditions = field.GetConditions();
            if (!string.IsNullOrEmpty(conditions))
            {
              RulesManager.RunRules(field.GetConditions(), new RuleContextModel(field, formViewModel, viewData.ModelState[viewDataKey]));
            }
              }
            }
              }
        }
        public virtual ActionResult New(FormViewModel form)
        {
            FormsHelper.ValidateForm(form, ModelState);
            if (ModelState.IsValid)
            {
                var newForm = form.MapTo(new Form{UserId = this.CorePrincipal() != null ? this.CorePrincipal().PrincipalId : (long?)null});
                if (formsService.Save(newForm))
                {
                    permissionService.SetupDefaultRolePermissions(OperationsHelper.GetOperations<FormOperations>(), typeof(Form), newForm.Id);
                    Success(HttpContext.Translate("Messages.Success", String.Empty));
                    return RedirectToAction(FormsMVC.Forms.Edit(newForm.Id));
                }
            }

            Error(HttpContext.Translate("Messages.ValidationError", String.Empty));

            form.AllowManage = true;
            return View("New", form);
        }
Beispiel #36
0
 public FormView(FormViewModel viewModel)
     : base(viewModel)
 {
     InitializeComponent();
 }
        public virtual ActionResult Save(FormViewModel model)
        {
            if (ModelState.IsValid)
            {
                var form = new Form();
                if (model.Id > 0)
                {
                     form = _formsService.Find(model.Id);

                     if (form == null || !_permissionService.IsAllowed((Int32)FormOperations.Manage, this.CorePrincipal(), typeof(Form), form.Id, IsFormOwner(form), PermissionOperationLevel.Object))
                     {
                         throw new HttpException((int)HttpStatusCode.NotFound, "Not Found");
                     }
                }
                else
                {
                    form.UserId = this.CorePrincipal() != null ? this.CorePrincipal().PrincipalId : (long?) null;
                }

                if (_formsService.Save(model.MapTo(form)))
                {
                    return RedirectToAction(FormsMVC.Forms.ShowAll());
                }
            }

            return View("Admin/EditForm", model);
        }
Beispiel #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RuleContextModel"/> class.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="form">The form.</param>
 /// <param name="modelState">State of the model.</param>
 public RuleContextModel(FieldViewModel model, FormViewModel form, ModelState modelState)
 {
     this.Model = model;
       this.Form = form;
       this.ModelState = modelState;
 }
Beispiel #39
0
 /// <summary>
 /// Creates a view model for the specified form, layout, and template.
 /// </summary>
 /// <param name="formId">
 /// The form ID.
 /// </param>
 /// <param name="layoutId">
 /// The layout ID.
 /// </param>
 /// <param name="templateId">
 /// The template ID.
 /// </param>
 /// <param name="page">
 /// The current Umbraco page.
 /// </param>
 /// <returns>
 /// The view model.
 /// </returns>
 /// <remarks>
 /// This model is used to render a form.
 /// </remarks>
 public static FormViewModel GetFormViewModel(Guid? formId, Guid? layoutId,
     Guid? templateId, IPublishedContent page)
 {
     var model = new FormViewModel()
     {
         FormDefinition = DefinitionHelper.GetFormDefinition(formId),
         LayoutDefinition = DefinitionHelper.GetLayoutDefinition(layoutId),
         TemplatePath = DefinitionHelper.GetTemplatePath(templateId),
         PageId = page.Id
     };
     return model;
 }
 public void SetUp()
 {
     formViewModel = new FormViewModel();
     command = new ValidationQuery(null);
     command.SetViewModel(formViewModel);
 }
Beispiel #41
0
 public void SetUp()
 {
     viewModel = new FormViewModel();
     subscriber = new PropertySubscriber<FormViewModel>(viewModel);
 }
        public virtual ActionResult ChangeLanguage(long formId, String culture)
        {
            var form = formsService.Find(formId);

            if (form == null || !permissionService.IsAllowed((Int32)FormOperations.View, this.CorePrincipal(), typeof(Form), form.Id, IsFormOwner(form), PermissionOperationLevel.Object))
            {
                throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
            }

            bool allowManage = permissionService.IsAllowed((Int32)FormOperations.Manage, this.CorePrincipal(),
                                                        typeof(Form), form.Id, IsFormOwner(form),
                                                        PermissionOperationLevel.Object);

            FormViewModel model = new FormViewModel {AllowManage = allowManage}.MapFrom(form);
            model.SelectedCulture = culture;

            //get locale
            var localeService = ServiceLocator.Current.GetInstance<IFormLocaleService>();
            FormLocale locale = localeService.GetLocale(formId, culture);

            if (locale!=null)
                model.MapLocaleFrom(locale);

            return PartialView("EditForm", model);
        }
        public virtual ActionResult Save(FormViewModel model)
        {
            FormsHelper.ValidateForm(model, ModelState);
            if (ModelState.IsValid)
            {
                var form = formsService.Find(model.Id);

                if (form == null || !permissionService.IsAllowed((Int32)FormOperations.Manage, this.CorePrincipal(), typeof(Form), form.Id, IsFormOwner(form), PermissionOperationLevel.Object))
                {
                    throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
                }

                if (formsService.Save(model.MapTo(form)))
                {
                    //save locale
                    var localeService = ServiceLocator.Current.GetInstance<IFormLocaleService>();
                    FormLocale locale = localeService.GetLocale(form.Id, model.SelectedCulture);
                    locale = model.MapLocaleTo(locale ?? new FormLocale{Form = form});

                    localeService.Save(locale);

                    Success(HttpContext.Translate("Messages.SuccessFormSubmit",
                                                                ResourceHelper.GetControllerScope(this)));
                    return RedirectToAction(FormsMVC.Forms.Edit(model.Id));
                }
            }
            else
            {
                Error(HttpContext.Translate("Messages.ValidationError",
                                                                ResourceHelper.GetControllerScope(this)));
            }

            model.AllowManage = true;

            return View("Edit", model);
        }
        public virtual ActionResult ShowFormElements(long formId)
        {
            var form = formsService.Find(formId);

            if (form == null || !permissionService.IsAllowed((Int32)FormOperations.View, this.CorePrincipal(), typeof(Form), form.Id, IsFormOwner(form), PermissionOperationLevel.Object))
            {
                throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
            }

            IList<GridColumnViewModel> columns = new List<GridColumnViewModel>
                                                     {
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = HttpContext.Translate("Title", ResourceHelper.GetControllerScope(this)), 
                                                                 Sortable = false,
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = HttpContext.Translate("Type", ResourceHelper.GetControllerScope(this)), 
                                                                 Sortable = false,
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = HttpContext.Translate("Required", ResourceHelper.GetControllerScope(this)), 
                                                                 Sortable = false,
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Width = 50,
                                                                 Sortable = false
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Width = 10,
                                                                 Sortable = false
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = "Id", 
                                                                 Sortable = false, 
                                                                 Hidden = true
                                                             }
                                                     };
            var model = new GridViewModel
            {
                DataUrl = Url.Action("FormElementsDynamicGridData", "Forms", new { formId = form.Id}),
                DefaultOrderColumn = "Title",
                GridTitle = HttpContext.Translate("GridTitle", ResourceHelper.GetControllerScope(this)),//"Form Elements",
                Columns = columns,
                IsRowNotClickable = true
            };
            
            bool allowManage = permissionService.IsAllowed((Int32) FormOperations.Manage, this.CorePrincipal(),
                                                            typeof (Form), form.Id, IsFormOwner(form),
                                                            PermissionOperationLevel.Object);

            ViewData["Form"] = new FormViewModel {Id = form.Id, AllowManage = allowManage};

            return View("FormElements", model);
        }