/// <summary>
 /// RunState constructor.
 /// </summary>
 /// <param name="modelState">Model state.</param>
 /// <param name="output">Output implementation.</param>
 public RunState(
     ModelState modelState,
     IOutput output)
 {
     this.ModelState = modelState;
     this.Output = output;
 }
        public static void ReadConfigReturn(TreeMgmtServerConfig c)
        {
            Condition.IsTrue(State == ModelState.Uninitialized);

            Config = c;
            State = ModelState.Initialized;
        }
Example #3
0
 protected void UpdateState(ModelState state, string message)
 {
     if (ModelStateUpdated != null)
     {
         ModelStateUpdated(this, new ModelStateEventArgs(state, message));
     }
 }
        public static void Disconnect()
        {
            Condition.IsTrue(State == ModelState.Connected);
            Condition.IsNull(Request);
            Condition.IsNotNull(Open);

            ModelHelper.Log(LogType.Requirement, "3.3.7.1 Handling Loss of a Connection");
            if (Config.IsLeasingSupported && Open.IsResilient)
            {
                ModelHelper.Log(LogType.Requirement,
                    "If any of the following conditions is satisfied, it indicates that the Open is to be preserved for reconnect. ");
                ModelHelper.Log(LogType.Requirement, "\tThe server supports leasing and Open.IsResilient is TRUE.");
                ModelHelper.Log(LogType.TestInfo, "The above conditions are met.");
                ModelHelper.Log(LogType.TestInfo, "The Open is preserved.");
            }
            else if (Open.IsDurable)
            {
                ModelHelper.Log(LogType.Requirement,
                    "If any of the following conditions is satisfied, it indicates that the Open is to be preserved for reconnect. ");
                ModelHelper.Log(LogType.Requirement, "\tOpen.OplockLevel is equal to SMB2_OPLOCK_LEVEL_BATCH and Open.OplockState is equal to Held, and Open.IsDurable is TRUE.");
                ModelHelper.Log(LogType.TestInfo, "The above conditions are met.");
                ModelHelper.Log(LogType.TestInfo, "The Open is preserved.");
            }
            else
            {
                ModelHelper.Log(LogType.Requirement, "If the Open is not to be preserved for reconnect, the server MUST close the Open as specified in section 3.3.4.17.");
                ModelHelper.Log(LogType.TestInfo, "The Open is closed.");
                Open = null;
            }

            State = ModelState.Disconnected;
        }
        public void ErrorsProperty()
        {
            // Arrange
            ModelState modelState = new ModelState();

            // Act & Assert
            Assert.NotNull(modelState.Errors);
        }
        private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) {
            if (!String.IsNullOrEmpty(error.ErrorMessage)) {
                return error.ErrorMessage;
            }
            if (modelState == null) {
                return null;
            }

            string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
            return String.Format(CultureInfo.CurrentCulture, GetInvalidPropertyValueResource(httpContext), attemptedValue);
        }
        private static ViewDataDictionary GetTextAreaViewDataWithErrors() {
            ViewDataDictionary viewData = new ViewDataDictionary { { "foo", "ViewDataFoo" } };
            viewData.Model = new { foo = "ViewItemFoo", bar = "ViewItemBar" };

            ModelState modelStateFoo = new ModelState();
            modelStateFoo.Errors.Add(new ModelError("foo error 1"));
            modelStateFoo.Errors.Add(new ModelError("foo error 2"));
            viewData.ModelState["foo"] = modelStateFoo;
            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { "AttemptedValueFoo" }, "AttemptedValueFoo");

            return viewData;
        }
        public static void ReadConfigReturn(ValidateNegotiateInfoConfig c)
        {
            Condition.IsTrue(State == ModelState.Uninitialized);
            Condition.IsNotNull(c);
            Config = c;
            State = ModelState.Initialized;

            Condition.IsTrue(Config.ValidateNegotiateInfoSupported ==
                             ValidateNegotiateInfoInServer.NotSupportValidateNegotiateInfo ||
                             Config.ValidateNegotiateInfoSupported ==
                             ValidateNegotiateInfoInServer.SupportValidateNegotiateInfo);
        }
Example #9
0
    public static bool Equal( ModelState a, ModelState b )
    {
        if ( System.Object.ReferenceEquals( a, b ) ) return true;
        if ( ( (object)a == null ) || ( (object)b == null ) ) return false;

        if ( a.ducked != b.ducked ) return false;
        if ( a.jumped != b.jumped ) return false;
        if ( a.onground != b.onground ) return false;
        if ( a.sleeping != b.sleeping ) return false;
        if ( a.waterLevel != b.waterLevel ) return false;
        if ( a.flinchLocation != b.flinchLocation ) return false;

        return true;
    }
Example #10
0
    public override void OnPropertyChanged(string propname)
    {
      if (_ModelState != Model.ModelState.New)
      {
        ModelState = Model.ModelState.Modified;
      }

      base.OnPropertyChanged(propname);

      //if (PropertyChanged != null)
      //{
      //  PropertyChanged(this, new PropertyChangedEventArgs(propname));
      //}
    }
Example #11
0
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
        public void ValueHelpersWithErrorsGetValueFromModelState()
        {
            // Arrange
            ViewDataDictionary<FooBarModel> viewDataWithErrors = new ViewDataDictionary<FooBarModel> { { "foo", "ViewDataFoo" } };
            viewDataWithErrors.Model = new FooBarModel() { foo = "ViewItemFoo", bar = "ViewItemBar" };
            viewDataWithErrors.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            ModelState modelStateFoo = new ModelState();
            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { "AttemptedValueFoo" }, "AttemptedValueFoo");
            viewDataWithErrors.ModelState["FieldPrefix.foo"] = modelStateFoo;

            ModelState modelStateFooBar = new ModelState();
            modelStateFooBar.Value = HtmlHelperTest.GetValueProviderResult(new string[] { "AttemptedValueFooBar" }, "AttemptedValueFooBar");
            viewDataWithErrors.ModelState["FieldPrefix"] = modelStateFooBar;

            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewDataWithErrors);

            // Act & Assert
            Assert.Equal("AttemptedValueFoo", helper.Value("foo").ToHtmlString());
            Assert.Equal("AttemptedValueFoo", helper.ValueFor(m => m.foo).ToHtmlString());
            Assert.Equal("AttemptedValueFooBar", helper.ValueForModel().ToHtmlString());
        }
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueResult };

        decimal actualValue = 0;
        try
        {

            if (bindingContext.ModelMetadata.DataTypeName == DataType.Currency.ToString())
                decimal.TryParse(valueResult.AttemptedValue, NumberStyles.Currency, null, out actualValue);
            else
                actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);

        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
        public HttpResponseMessage Post(int id, ScopeModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            var app = config.Applications.All.SingleOrDefault(x => x.ID == id);
            if (app == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            if (app.Scopes.Any(x => x.Name == model.Name))
            {
                ModelState.AddModelError("", "That Scope name is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            var scope = new Scope();
            scope.Name = model.Name;
            scope.DisplayName = model.DisplayName;
            scope.Description = model.Description;
            scope.Emphasize = model.Emphasize;

            app.Scopes.Add(scope);
            config.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, new {
                    scope.ID,
                    scope.Name,
                    scope.DisplayName,
                    scope.Description,
                    scope.Emphasize
                });
        }
        public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // 下列程式碼保護兩個因素碼不受暴力密碼破解攻擊。 
            // 如果使用者輸入不正確的代碼來表示一段指定的時間,則使用者帳戶 
            // 會有一段指定的時間遭到鎖定。 
            // 您可以在 IdentityConfig 中設定帳戶鎖定設定
            var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(model.ReturnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "代碼無效。");
                    return View(model);
            }
        }
Example #16
0
        public HttpResponseMessage Delete(int id, ServiceModel.DeleteThingViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            var thing = context.GetAll <DomainModel.Thing>()
                        .FirstOrDefault(u => u.Id == id);

            //rest spec says we should not throw an error in this case ( delete requests should be idempotent)
            if (thing == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Thing"));
            }


            var user = context.GetAll <DomainModel.User>()
                       .FirstOrDefault(u => u.Id == viewModel.DeletedById);

            if (user == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid user"));
            }


            if (thing.OwnerId != viewModel.DeletedById)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "A thing can only be removed by its owner."));
            }

            thing.Delete(user);
            context.SaveChanges();

            return(new HttpResponseMessage(HttpStatusCode.NoContent));
        }
        public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // 以下代码可以防范双重身份验证代码遭到暴力破解攻击。
            // 如果用户输入错误代码的次数达到指定的次数,则会将
            // 该用户帐户锁定指定的时间。
            // 可以在 IdentityConfig 中配置帐户锁定设置
            var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(model.ReturnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "代码无效。");
                    return View(model);
            }
        }
Example #18
0
        public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // The following code protects for brute force attacks against the two factor codes. 
            // If a user enters incorrect codes for a specified amount of time then the user account 
            // will be locked out for a specified amount of time. 
            // You can configure the account lockout settings in IdentityConfig
            var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(model.ReturnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid code.");
                    return View(model);
            }
        }
        public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
            if (user == null)
            {
                throw new InvalidOperationException($"Unable to load two-factor authentication user.");
            }

            var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine);

            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id);
                return LocalRedirect(returnUrl);
            }
            else if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
                return RedirectToPage("./Lockout");
            }
            else
            {
                _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id);
                ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
                return Page();
            }
        }  
        public ActionResult EditPost(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var studentToUpdate = db.Students.Find(id);
            if (TryUpdateModel(studentToUpdate, "",
               new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
            {
                try
                {
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                catch (RetryLimitExceededException  /* dex */)
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
            return View(studentToUpdate);
        }
Example #21
0
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            if(returnUrl == null)
            {
                returnUrl = "Home/Index";
            }
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation(1, "User logged in.");
                    return RedirectToLocal(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return View("Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Example #22
0
 public async Task<ActionResult> Edit(string id, string labelName, string email) {
     AppUser user = await UserManager.FindByIdAsync(id);
     if (user != null) {
         user.LabelName = labelName;
         user.Email = email;
         IdentityResult validEmail
             = await UserManager.UserValidator.ValidateAsync(user);
         if (!validEmail.Succeeded) {
             AddErrorsFromResult(validEmail);
         }
         //IdentityResult validPass = null;
         //if (password != null && password != string.Empty) {
         //    validPass
         //        = await UserManager.PasswordValidator.ValidateAsync(password);
         //    if (validPass.Succeeded) {
         //        user.PasswordHash =
         //            UserManager.PasswordHasher.HashPassword(password);
         //    } else {
         //        AddErrorsFromResult(validPass);
         //    }
         //}
         if (validEmail.Succeeded) {
             IdentityResult result = await UserManager.UpdateAsync(user);
             if (result.Succeeded) {
                 return RedirectToAction("Index");
             } else {
                 AddErrorsFromResult(result);
             }
         }
     }
     else
     {
         ModelState.AddModelError("", "User Not Found");
     }
     return View(user);
 }
Example #23
0
        public async Task<IActionResult> LogIn(LoginVM model)
        {
            if(ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(
                    model.Username, model.Password, isPersistent: model.RememberMe,
                    lockoutOnFailure: false);

                if(result.Succeeded)
                {
                    if(!string.IsNullOrEmpty(model.ReturnUrl) &&
                        Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            ModelState.AddModelError("", "Invalid username/password");
            return View(model);
        }
        public ActionResult Index(KeyConfigurationInputModel keys)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    keys.Update(this.ConfigurationRepository);
                    TempData["Message"] = "Update Successful";
                    return RedirectToAction("Index");
                }
                catch (ValidationException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
                catch
                {
                    ModelState.AddModelError("", "Error updating keys.");
                }
            }

            var vm = new KeyConfigurationViewModel(this.ConfigurationRepository.Keys);
            vm.Keys = keys;
            return View("Index", vm);
        }
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Email,
                    model.Password, model.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    return RedirectToLocal(returnUrl);
                }
                if (result.IsLockedOut)
                {
                    return View("Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Nieprawidłowa nazwa użytkownika lub hasło.");
                    return View(model);
                }
            }

            return View(model);
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // 這不會計算為帳戶鎖定的登入失敗
            // 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "登入嘗試失試。");
                    return View(model);
            }
        }
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var serviceType = await _context.ServiceTypes
            .Include(h => h.Histories)
            .FirstOrDefaultAsync(h => h.Id == id);

            if (serviceType == null)
            {
                return NotFound();
            }

            if (serviceType.Histories.Count > 0)
            {

                ModelState.AddModelError(string.Empty, "The pet Servicetype can´t be removed ");
                return RedirectToAction(nameof(Index));
            }

            try
            {
                _context.ServiceTypes.Remove(serviceType);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            catch (Exception ex)
            {

                ModelState.AddModelError(string.Empty, ex.ToString());
                return RedirectToAction(nameof(Index));
            }
        }
Example #28
0
 public IActionResult OnGet(string answer)
 {
     if (!dayValidation.HasAccess(door))
     {
         return RedirectToPage("Index", new { invalidDoor = door });
     }
     if (string.IsNullOrEmpty(answer))
     {
         return Page();
     }
     if (CompareHelper.AreEqual("train", answer))
     {
         Solved = true;
     }
     else if (CompareHelper.Contains(shapeNames, answer))
     {
         ModelState.AddModelError(string.Empty, $"Repeating the names is not the answer. We need to combine the shape and the number.");
     }
     else
     {
         ModelState.AddModelError(string.Empty, $"No, {answer} cannot be the solution.");
     }
     return Page();
 }
Example #29
0
 public ActionResult Edit(NhaCC sp)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var dao = new NhaCCDAO();
             var result = dao.Update(sp);
             if (result)
             {
                 return RedirectToAction("Index", "NhaCungCap");
             }
             else
             {
                 ModelState.AddModelError("", "Cập nhật thất bại!");
             }
         }
         return View("Index");
     }
     catch
     {
         return View();
     }
 }
Example #30
0
        public ActionResult DeleteConfirmed(int id)
        {
            //try
            //{
            ModelState.Remove("Password");
            ModelState.Remove("ConfirmPassword");

            if (ModelState.IsValid)
            {
                var user = UserManager.FindById(id);
                if (user == null)
                {
                    return(HttpNotFound());
                }

                var result = UserManager.Delete(user);
                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
            }

            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(View("ResetPasswordConfirmation"));
            }
            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(View("ResetPasswordConfirmation"));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(View(model));
        }
 public ActionResult Index(FormCollection form)
 {
     try
     {
         if (form["btnDelete"] != null)
         {
             var addressTypes = form.GetValues("chkDelete");
             if (addressTypes != null)
             {
                 foreach (var addressType in addressTypes)
                 {
                     var productId = Convert.ToInt32(addressType);
                     addressTypeProvider.DeleteAddressType(productId);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ModelState.AddModelError(String.Empty, ex.Message);
         Logger.ErrorException(ex.Message, ex);
     }
     return(RedirectToAction("Index"));
 }
        public async Task <IActionResult> Create(
            [Bind("Name,Photo_ID,Other_Requirements,Other_Requirements_Text,Appointments_Available,Appointments_Required,Additional_Comments,Last_Updated")] Organization organization)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(organization);

                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Create", "Contacts", new { id = organization.Id }));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }

            return(View(organization));
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // 这不会计入到为执行帐户锁定而统计的登录失败次数中
            // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "无效的登录尝试。");
                    return View(model);
            }
        }
Example #35
0
        public async Task <IActionResult> OnPostDeleteCategoryAsync()
        {
            await LoadCategories();

            if (string.IsNullOrEmpty(ExpenseFlow.AddOrDeleteCategory))
            {
                ModelState.AddModelError(nameof(ExpenseFlow.AddOrDeleteCategory), "Введите категорию товаров");
                return(Page());
            }

            var category = FlowCategories.FindByName(ExpenseFlow.AddOrDeleteCategory);

            if (category == null)
            {
                ModelState.AddModelError(nameof(ExpenseFlow.AddOrDeleteCategory), $"Нет такой категории \"{ExpenseFlow.AddOrDeleteCategory}\"");
            }
            else
            {
                FlowCategories.Remove(category);
                ExpenseFlow.Categories          = FlowCategories.Select(x => x.Id).ToCsvString();
                ExpenseFlow.AddOrDeleteCategory = string.Empty;
            }
            return(Page());
        }
Example #36
0
        public JsonResult AddSaleBargin(AddSaleBarginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string      userName = HttpContext.User.Identity.Name;
                SaleBargain bargain  = new SaleBargain()
                {
                    BargainItems = model.BargainItems,
                    //BargainSysUserKey = userName,
                    SaleContractId = model.SaleContractId
                };

                string errorMsg = string.Empty;
                //AppBusinessManager.Instance.AddOrUpdateSaleBargain(
                //   this.dxContext as ExtendedIdentityDbContext, bargain);

                if (!string.IsNullOrEmpty(errorMsg))
                {
                    ModelState.AddModelError(string.Empty, errorMsg);
                }
                //FIXED 添加销售还价逻辑
            }
            return(Json(this.GetModelStateErrors(ModelState)));
        }
        public ActionResult Create(FormCollection collection, ProductModel product, HttpPostedFileBase upload)
        {
            var errors = ModelState
                         .Where(x => x.Value.Errors.Count > 0)
                         .Select(x => new { x.Key, x.Value.Errors })
                         .ToArray();

            if (ModelState.IsValid)
            {
                if (upload != null)
                {
                    product.productImage = new byte[upload.ContentLength];
                    upload.InputStream.Read(product.productImage, 0, upload.ContentLength);
                }
                Context.ProductModelSet.Add(product);
                Context.SaveChanges();
                ViewBag.result         = "Product " + product.vendor + " " + product.productName + " Added Succesfully!";
                ViewBag.prodCategoryID = new SelectList(Context.ProductCategoryModelSet, "prodCategoryID", "categoryName", product.productID);

                return(RedirectToAction("ViewProducts", "Product"));
            }

            return(View(product));
        }
        public ActionResult Delete(string id, IFormCollection collection)
        {
            string storeLoc = TempData.Peek("adminLoc").ToString();

            try
            {
                // concurrent
                var foundProduct = _storeRepo.GetOneProduct(id);
                if (foundProduct == null)
                {
                    ModelState.AddModelError("", "Another admin has just deleted this product");
                    return(View());
                }

                _storeRepo.DeleteOneProduct(storeLoc, id);
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "error while trying to delete a product");
                ModelState.AddModelError("", "Trying to delete a product that does not exist");
                return(View());
            }
        }
Example #39
0
        public ActionResult Registration([Bind(Include = "FirstName,LastName,UserName,EmailID,Password,DateOfBirth")] User U)
        {
            if (ModelState.IsValid)
            {
                var EmailExist = IsEmailExist(U.EmailID);
                if (EmailExist)
                {
                    ModelState.AddModelError("EmailExist", "Email is aleardy Exist");
                    //@ViewBag.EmailExistMessage =  "Email is aleardy Exist"
                    return(View());
                }
                //1.2 generate ActivationCode
                U.ActivationCode = Guid.NewGuid();

                //1.3 Hashing Password
                U.Password = Crypto.Hash(U.Password);
                //U.ConfirmPassword = Crypto.Hash(U.ConfirmPassword);

                //1.4
                U.IsEmailVerified = false;

                //1.5 save data in the database
                DB.Database.ExecuteSqlCommand(@"insert into users (FirstName,LastName,UserName,EmailID,Password,DateOfBirth,IsEmailVerified,ActivationCode) Values (@firstName,@lastName,@userName,@email,@password, @birthDay,@isEmailVerified,@activationCode) ", new SqlParameter("firstName", U.FirstName), new SqlParameter("lastName", U.LastName), new SqlParameter("userName", U.UserName), new SqlParameter("email", U.EmailID), new SqlParameter("password", U.Password), new SqlParameter("birthDay", U.DateOfBirth), new SqlParameter("isEmailVerified", U.IsEmailVerified), new SqlParameter("activationCode", U.ActivationCode));
                DB.SaveChanges();

                //1.6 send verfication email
                SendValidationLinkEmail(U.EmailID, U.ActivationCode.ToString());

                return(RedirectToAction("Congratolation"));
            }
            else
            {
                ViewBag.InvalidMessage = " invalid model or invalid request";
                return(View());
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);

                if (result.Succeeded)
                {
                    var user = await userManager.FindByNameAsync(model.Email);

                    if (await userManager.IsInRoleAsync(user, "AccountExecutive"))
                    {
                        return(RedirectToAction("Index", "CustomerExecutive"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "CashierTeller"));
                    }
                }

                ModelState.AddModelError(string.Empty, "Invalid login attempt");
            }
            return(View(model));
        }
Example #42
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
        public ActionResult SaveEngInfo(Engineer aEngineer)
        {
            if (ModelState.IsValid)
            {
                bool isExist = db.Engineers.Any(x => x.engEmail == aEngineer.engEmail);

                if (isExist == true)
                {
                    ModelState.AddModelError("engEmail", "Already Exist");
                    return View(aEngineer);
                }
                EngineerBLL AEngineerBll = new EngineerBLL();

                ViewBag.Message = AEngineerBll.SaveEngProfile(aEngineer);
                return RedirectToAction("Index");

            }
            else
                return View(aEngineer);
            
       

            //return View(aEngineer);
        }
        public void ValueHelpersEncodeValue()
        {
            // Arrange
            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { "foo", @"ViewDataFoo <"">" } };
            viewData.Model = new FooBarModel { foo = @"ViewItemFoo <"">" };

            ModelState modelStateFoo = new ModelState();
            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { @"AttemptedValueBar <"">" }, @"AttemptedValueBar <"">");
            viewData.ModelState["bar"] = modelStateFoo;

            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewData);

            // Act & Assert
            Assert.Equal("&lt;{ foo = ViewItemFoo &lt;&quot;>, bar = (null) }", helper.ValueForModel("<{0}").ToHtmlString());
            Assert.Equal("&lt;ViewDataFoo &lt;&quot;>", helper.Value("foo", "<{0}").ToHtmlString());
            Assert.Equal("&lt;ViewItemFoo &lt;&quot;>", helper.ValueFor(m => m.foo, "<{0}").ToHtmlString());
            Assert.Equal("AttemptedValueBar &lt;&quot;>", helper.ValueFor(m => m.bar).ToHtmlString());
        }
        public void EnumDropDownListForWithErrorsAndValue()
        {
            // Arrange
            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);
            ModelState modelState = new ModelState
            {
                Errors = { new ModelError("WithDisplay error 1"), new ModelError("WithDisplay error 2"), },
                Value = new ValueProviderResult(new string[] { "1", }, "1", null),
            };
            viewData.ModelState["WithDisplay"] = modelState;

            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);

            // Act
            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,
                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);

            // Assert
            Assert.Equal(
                "<select baz=\"BazObjValue\" class=\"input-validation-error\" id=\"WithDisplay\" name=\"WithDisplay\">" +
                "<option value=\"0\">First</option>" + Environment.NewLine +
                "<option selected=\"selected\" value=\"1\">Second</option>" + Environment.NewLine +
                "<option value=\"2\">Third</option>" + Environment.NewLine +
                "<option value=\"3\">Fourth</option>" + Environment.NewLine +
                "</select>",
                html.ToHtmlString());
        }
Example #46
0
        private static ViewDataDictionary GetHiddenViewDataWithErrors() {
            ViewDataDictionary viewData = new ViewDataDictionary { { "foo", "ViewDataFoo" } };
            ModelState modelStateFoo = new ModelState();
            modelStateFoo.Errors.Add(new ModelError("foo error 1"));
            modelStateFoo.Errors.Add(new ModelError("foo error 2"));
            viewData.ModelState["foo"] = modelStateFoo;
            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult("AttemptedValueFoo", "AttemptedValueFoo");

            return viewData;
        }
Example #47
0
        // RADIO
        private static ViewDataDictionary GetRadioButtonViewData() {
            ViewDataDictionary viewData = new ViewDataDictionary { { "foo", "ViewDataFoo" } };
            viewData.Model = new { foo = "ViewItemFoo", bar = "ViewItemBar" };
            ModelState modelState = new ModelState();
            modelState.Value = HtmlHelperTest.GetValueProviderResult("ViewDataFoo", "ViewDataFoo");
            viewData.ModelState["foo"] = modelState;

            return viewData;
        }
        public void IsValidPropertyReturnsFalseIfErrors()
        {
            // Arrange
            ModelState errorState = new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("quux", "quux") };
            errorState.Errors.Add("some error");
            ModelStateDictionary dictionary = new ModelStateDictionary()
            {
                { "foo", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("bar", "bar") } },
                { "baz", errorState }
            };

            // Act
            bool isValid = dictionary.IsValid;

            // Assert
            Assert.False(isValid);
        }
        public static void SetupConnection(ModelDialectRevision clientMaxDialect)
        {
            Condition.IsTrue(state == ModelState.Initialized);
            Condition.IsNull(request);

            negotiateDialect = ModelHelper.DetermineNegotiateDialect(clientMaxDialect, config.MaxSmbVersionSupported);

            if ((negotiateDialect == DialectRevision.Smb21 || ModelUtility.IsSmb3xFamily(negotiateDialect))
                && config.IsMultiCreditSupportedOnServer)
            {
                ModelHelper.Log(
                    LogType.Requirement,
                    "3.3.5.4: If the common dialect is SMB 2.1 or 3.x dialect family and the underlying connection is either TCP port 445 or RDMA," +
                    "Connection.SupportsMultiCredit MUST be set to TRUE; otherwise, it MUST be set to FALSE.");
                ModelHelper.Log(
                    LogType.TestInfo,
                    "Common dialect is {0} and server implementation {1} multicredit", negotiateDialect,
                    config.IsMultiCreditSupportedOnServer ? "supports" : "does not support");

                isMultiCreditSupported = true;

                ModelHelper.Log(
                    LogType.TestInfo,
                    "Connection.SupportsMultiCredit is set to TRUE");
            }
            else
            {
                isMultiCreditSupported = false;

                ModelHelper.Log(
                    LogType.TestInfo,
                    "Connection.SupportsMultiCredit is set to FALSE");
            }

            state = ModelState.Connected;
        }
        public static void SetupConnection(ModelDialectRevision maxSmbVersionClientSupported, ClientSupportsEncryptionType clientSupportsEncryptionType)
        {
            Condition.IsTrue(state == ModelState.Initialized);
            Condition.IsNull(request);

            negotiateDialect = ModelHelper.DetermineNegotiateDialect(maxSmbVersionClientSupported, config.MaxSmbVersionSupported);

            Connection_ClientCapabilities_SMB2_GLOBAL_CAP_ENCRYPTION = (clientSupportsEncryptionType == ClientSupportsEncryptionType.ClientSupportsEncryption) ? true : false;

            if (ModelUtility.IsSmb3xFamily(negotiateDialect) && clientSupportsEncryptionType == ClientSupportsEncryptionType.ClientSupportsEncryption)
            {
                ModelHelper.Log(LogType.Requirement,
                    "3.3.5.4: The Capabilities field MUST be set to a combination of zero or more of the following bit values, as specified in section 2.2.4:");
                ModelHelper.Log(LogType.Requirement,
                    "\tSMB2_GLOBAL_CAP_ENCRYPTION if Connection.Dialect belongs to the SMB 3.x dialect family, the server supports encryption, " +
                    "and SMB2_GLOBAL_CAP_ENCRYPTION is set in the Capabilities field of the request.");

                // Encrpytion Model only applies to server that supports encryption.
                ModelHelper.Log(LogType.TestInfo,
                    "Connection.Dialect is {0}, the server supports encryption and SMB2_GLOBAL_CAP_ENCRYPTION is set. " +
                    "So SMB2_GLOBAL_CAP_ENCRYPTION bit is set in Capabilities field.", negotiateDialect);
                Connection_ServerCapabilities_SMB2_GLOBAL_CAP_ENCRYPTION = true;
            }

            state = ModelState.Connected;
        }
        public static void ExpectDisconnect()
        {
            Condition.IsTrue(state == ModelState.Connected);
            Condition.IsTrue(expectDisconnection);

            state = ModelState.Disconnected;
            acceptingCondition = true;
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            ModelState modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
            {
                try
                {

                    // Tries to figure out how many decimal characters we have after the decimal separator.
                    string value = valueResult.AttemptedValue;

                    int decimals = 0;

                    // Make sure it will break the checking right after discovering how many decimal characters there is after the decimal character. 
                    while (true)
                    {

                        if (value[value.Length - 3] == ',' || value[value.Length - 3] == '.')
                        {
                            decimals = 2;
                            break;
                        }

                        if (value[value.Length - 4] == ',' || value[value.Length - 4] == '.')
                        {
                            decimals = 3;
                            break;
                        }

                        if (value[value.Length - 5] == ',' || value[value.Length - 5] == ',')
                        {
                            decimals = 4;
                            break;
                        }

                        break;
                    }


                    // Replace all special characters in order to make the proper conversion from the string to the decimal.
                    string final_value;

                    final_value = value.Replace(",", "").Replace(".", "");

                    // Insert the decimal character at the correct position given the ammount of decimal characters we retrieved.
                    final_value = final_value.Insert(final_value.Length - decimals, ".");

                    // Converts the actual decimal.
                    actualValue = Convert.ToDecimal(final_value, CultureInfo.InvariantCulture);
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

            return actualValue;
        }
        private static ViewDataDictionary<FooBarModel> GetViewDataWithErrors()
        {
            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { "foo", "ViewDataFoo" } };
            viewData.Model = new FooBarModel { foo = "ViewItemFoo", bar = "ViewItemBar" };

            ModelState modelStateFoo = new ModelState();
            modelStateFoo.Errors.Add(new ModelError("foo error 1"));
            modelStateFoo.Errors.Add(new ModelError("foo error 2"));
            viewData.ModelState["foo"] = modelStateFoo;
            modelStateFoo.Value = new ValueProviderResult(new string[] { "Bravo", "Charlie" }, "Bravo", CultureInfo.InvariantCulture);

            return viewData;
        }
        public void DisplayTextFor_IgnoresModelStateEntry()
        {
            // Arrange
            var model = new OverriddenToStringModel("Model value")
            {
                Name = "Property value",
            };
            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model)
            {
                { "Name", "View data dictionary value" },
            };
            viewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult(
                rawValue: new string[] { "Attempted name value" },
                attemptedValue: "Attempted name value",
                culture: CultureInfo.InvariantCulture);
            viewData.ModelState["FieldPrefix.Name"] = modelState;

            var helper = MvcHelper.GetHtmlHelper(viewData);

            // Act
            MvcHtmlString result = helper.DisplayTextFor(m => m.Name);

            // Assert
            Assert.Equal("Property value", result.ToHtmlString());
        }
 private static ViewDataDictionary<ValidationModel> GetViewDataWithModelErrors(string prefix)
 {
     ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();
     viewData.TemplateInfo.HtmlFieldPrefix = prefix;
     ModelState modelStateFoo = new ModelState();
     ModelState modelStateBar = new ModelState();
     ModelState modelStateBaz = new ModelState();
     modelStateFoo.Errors.Add(new ModelError("foo error <1>"));
     modelStateFoo.Errors.Add(new ModelError("foo error 2"));
     modelStateBar.Errors.Add(new ModelError("bar error <1>"));
     modelStateBar.Errors.Add(new ModelError("bar error 2"));
     viewData.ModelState[prefix + ".foo"] = modelStateFoo;
     viewData.ModelState[prefix + ".bar"] = modelStateBar;
     viewData.ModelState[prefix + ".baz"] = modelStateBaz;
     viewData.ModelState.SetModelValue(prefix + ".quux", new ValueProviderResult(null, "quuxValue", null));
     viewData.ModelState.AddModelError(prefix + ".quux", new InvalidOperationException("Some error text."));
     return viewData;
 }
 private static ViewDataDictionary<ValidationModel> GetViewDataWithModelAndPropertyErrors()
 {
     ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();
     ModelState modelStateFoo = new ModelState();
     ModelState modelStateBar = new ModelState();
     ModelState modelStateBaz = new ModelState();
     modelStateFoo.Errors.Add(new ModelError("foo error <1>"));
     modelStateFoo.Errors.Add(new ModelError("foo error 2"));
     modelStateBar.Errors.Add(new ModelError("bar error <1>"));
     modelStateBar.Errors.Add(new ModelError("bar error 2"));
     viewData.ModelState["foo"] = modelStateFoo;
     viewData.ModelState["bar"] = modelStateBar;
     viewData.ModelState["baz"] = modelStateBaz;
     viewData.ModelState.SetModelValue("quux", new ValueProviderResult(null, "quuxValue", null));
     viewData.ModelState.AddModelError("quux", new InvalidOperationException("Some error text."));
     viewData.ModelState.AddModelError(String.Empty, "Something is wrong.");
     viewData.ModelState.AddModelError(String.Empty, "Something else is also wrong.");
     return viewData;
 }
        public static void ExpectDisconnect()
        {
            Condition.IsTrue(state == ModelState.Connected);

            state = ModelState.Disconnected;
        }
        public static void SetupConnection(ModelSessionSecurityContext securityContext)
        {
            Condition.IsTrue(State == ModelState.Initialized);
            Condition.IsFalse(Session_TreeConnectExist);

            State = ModelState.Connected;
            Session_TreeConnectExist = false;
            Session_SecurityContext = securityContext;
        }
        public static void ReadConfigReturn(CreditMgmtConfig c)
        {
            Condition.IsTrue(state == ModelState.Uninitialized);
            Condition.IsNotNull(c);

            Condition.IsTrue(
                c.MaxSmbVersionSupported == ModelDialectRevision.Smb2002
                || c.MaxSmbVersionSupported == ModelDialectRevision.Smb21
                || c.MaxSmbVersionSupported == ModelDialectRevision.Smb30
                || c.MaxSmbVersionSupported == ModelDialectRevision.Smb302);

            negotiateDialect = DialectRevision.Smb2Unknown;
            config = c;
            request = null;
            state = ModelState.Initialized;
            acceptingCondition = false;
        }
        public static void ReadConfigReturn(EncryptionConfig c)
        {
            Condition.IsTrue(state == ModelState.Uninitialized);
            Condition.IsNotNull(c);

            negotiateDialect = DialectRevision.Smb2Unknown;
            // Force SE to expand Config.MaxSmbVersionServerSupported
            Condition.IsTrue(c.MaxSmbVersionSupported == ModelDialectRevision.Smb2002 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb21 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb30 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb302);
            config = c;

            request = null;
            state = ModelState.Initialized;
        }