public void Validate(ModelStateDictionary modelState, string prefix, decimal? totalMarks)
        {
            if (string.IsNullOrWhiteSpace(this.Surname))
            {
                modelState.AddModelError(prefix + ".Surname", "Surname cannot be blank.");
            }

            if (string.IsNullOrWhiteSpace(this.Forenames))
            {
                modelState.AddModelError(prefix + ".Forenames", "Forenames cannot be blank.");
            }

            if (!this.Result.HasValue)
            {
                return;
            }

            if (this.Result < 0)
            {
                modelState.AddModelError(prefix + ".Result", "Result must be a positive number.");
            }

            if (totalMarks.HasValue && this.Result > totalMarks)
            {
                modelState.AddModelError(prefix + ".Result", "Result cannot be greater than the total marks.");
            }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            var options = actionContext.ActionArguments.Where(p => p.Value is ODataQueryOptions).Select(p => p.Value).OfType<ODataQueryOptions>().FirstOrDefault();

            if (options == null)
            {
                return;
            }

            var modelDictionary = new ModelStateDictionary();

            if (options.Skip != null)
            {
                if (options.Skip.Value < MinSkipValue)
                {
                    modelDictionary.AddModelError("Skip", String.Format("Value must be greater than or equal {0}", MinSkipValue));
                }
            }

            if (options.Top != null)
            {
                if (options.Top.Value < MinTopValue)
                {
                    modelDictionary.AddModelError("Top", String.Format("Value must be greater than or equal {0}", MinTopValue));
                }
            }

            if (modelDictionary.Count > 0)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelDictionary);
            }
        }
예제 #3
0
        public void Validate(ModelStateDictionary mdlState)
        {
            base.Validate();

            foreach (var tags in _nameTags)
            {
                var error = tags.Value.ValidationError;
                if (error != null)
                {
                    var strError = string.Join(", ", error.Errors);
                    if (!string.IsNullOrWhiteSpace(strError))
                    {
                        if (tags.Value is DataObjectViewModel)
                        {
                            // Special case DatObject: remove any key
                            mdlState.AddModelError("", strError);
                        }
                        else
                        {
                            mdlState.AddModelError(tags.Key, strError);
                        }
                    }
                }
            }
        }
예제 #4
0
        public void StartRegistrationForFamilyMember(int id, ModelStateDictionary modelState)
        {
            modelState.Clear(); // ensure we pull form fields from our model, not MVC's
            HistoryAdd("Register");
            int index = List.Count - 1;
            var p = LoadExistingPerson(id, index);

            if(p.NeedsToChooseClass())
                return;

            p.ValidateModelForFind(modelState, id, selectFromFamily: true);
            if (!modelState.IsValid)
                return;

            List[index] = p;

            if (p.ManageSubscriptions() && p.Found == true)
                return;

            if (p.org != null && p.Found == true)
            {
                if (!SupportMissionTrip)
                    p.IsFilled = p.org.RegLimitCount(DbUtil.Db) >= p.org.Limit;
                if (p.IsFilled)
                    modelState.AddModelError(this.GetNameFor(mm => mm.List[List.IndexOf(p)].Found),
                        "Sorry, but registration is filled.");
                if (p.Found == true)
                    p.FillPriorInfo();
                return;
            }
            if (p.org == null && p.ComputesOrganizationByAge())
                modelState.AddModelError(this.GetNameFor(mm => mm.List[id].Found), p.NoAppropriateOrgError);
        }
예제 #5
0
        public void WriteXml_WritesValidXml()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key2", "Test Error 3");
            var serializableError = new SerializableError(modelState);
            var outputStream = new MemoryStream();

            // Act
            using (var xmlWriter = XmlWriter.Create(outputStream))
            {
                var dataContractSerializer = new DataContractSerializer(typeof(SerializableErrorWrapper));
                dataContractSerializer.WriteObject(xmlWriter, new SerializableErrorWrapper(serializableError));
            }
            outputStream.Position = 0;
            var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd();

            // Assert
            var expectedContent =
                TestPlatformHelper.IsMono ?
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error xmlns:i=\"" +
                    "http://www.w3.org/2001/XMLSchema-instance\"><key1>Test Error 1 Test Error 2</key1>" +
                    "<key2>Test Error 3</key2></Error>" :
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<Error><key1>Test Error 1 Test Error 2</key1><key2>Test Error 3</key2></Error>";

            Assert.Equal(expectedContent, res);
        }
예제 #6
0
        public void AddModelError_WithErrorString_AddsTooManyModelErrors_WhenMaxErrorsIsReached()
        {
            // Arrange
            var expected = "The maximum number of allowed model errors has been reached.";
            var dictionary = new ModelStateDictionary
            {
                MaxAllowedErrors = 5
            };
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), nameof(string.Length));
            dictionary.AddModelError("key1", "error1");
            dictionary.AddModelError("key2", new Exception(), metadata);
            dictionary.AddModelError("key3", new Exception(), metadata);
            dictionary.AddModelError("key4", "error4");
            dictionary.AddModelError("key5", "error5");

            // Act and Assert
            Assert.True(dictionary.HasReachedMaxErrors);
            Assert.Equal(5, dictionary.ErrorCount);
            var error = Assert.Single(dictionary[string.Empty].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
            Assert.Equal(expected, error.Exception.Message);

            // TooManyModelErrorsException added instead of key5 error.
            Assert.DoesNotContain("key5", dictionary.Keys);
        }
예제 #7
0
		public void Validate(ModelStateDictionary modelStateDictionary, IUserService userService, string ip)
		{
			if (!IsCoppa)
				modelStateDictionary.AddModelError("IsCoppa", Resources.MustBe13);
			if (!IsTos)
				modelStateDictionary.AddModelError("IsTos", Resources.MustAcceptTOS);
			userService.IsPasswordValid(Password, modelStateDictionary);
			if (Password != PasswordRetype)
				modelStateDictionary.AddModelError("PasswordRetype", Resources.RetypeYourPassword);
			if (String.IsNullOrWhiteSpace(Name))
				modelStateDictionary.AddModelError("Name", Resources.NameRequired);
			else if (userService.IsNameInUse(Name))
				modelStateDictionary.AddModelError("Name", Resources.NameInUse);
			if (String.IsNullOrWhiteSpace(Email))
				modelStateDictionary.AddModelError("Email", Resources.EmailRequired);
			else
				if (!Email.IsEmailAddress())
					modelStateDictionary.AddModelError("Email", Resources.ValidEmailAddressRequired);
				else if (Email != null && userService.IsEmailInUse(Email))
					modelStateDictionary.AddModelError("Email", Resources.EmailInUse);
			if (Email != null && userService.IsEmailBanned(Email))
				modelStateDictionary.AddModelError("Email", Resources.EmailBanned);
			if (userService.IsIPBanned(ip))
				modelStateDictionary.AddModelError("Email", Resources.IPBanned);
		}
예제 #8
0
 public static bool IsValidBooleanField(ModelStateDictionary modelState, string display, string field, string value, bool required = false)
 {
     bool ret = false;
     bool result;
     if (value.IsNullOrEmpty())
     {
         if (required)
         {
             modelState.AddModelError(field, "กรุณาใส่" + display);
         }
         else
         {
             ret = true;
         }
     }
     else if (!bool.TryParse(value, out result))
     {
         modelState.AddModelError(field, display + "มีค่าไม่ถูกต้อง");
     }
     else
     {
         ret = true;
     }
     return ret;
 }
        public void WithModelStateForShouldThrowExceptionWhenModelStateHasSameErrors()
        {
            Test.AssertException<ModelErrorAssertionException>(
                () =>
                {
                    var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors();
                    var modelState = new ModelStateDictionary();
                    modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647.");
                    modelState.AddModelError("RequiredString", "The RequiredString field is required.");

                    MyController<MvcController>
                        .Instance()
                        .Calling(c => c.BadRequestWithModelState(requestModelWithErrors))
                        .ShouldReturn()
                        .BadRequest()
                        .WithModelStateError(modelStateError => modelStateError
                            .For<RequestModel>()
                            .ContainingErrorFor(m => m.Integer).ThatEquals("The field Integer 1 must be between 1 and 2147483647.")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).BeginningWith("The RequiredString")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).EndingWith("required.")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).Containing("field")
                            .AndAlso()
                            .ContainingNoErrorFor(m => m.NonRequiredString));
                },
                "When calling BadRequestWithModelState action in MvcController expected error message for key Integer to be 'The field Integer 1 must be between 1 and 2147483647.', but instead found 'The field Integer must be between 1 and 2147483647.'.");
        }
예제 #10
0
        public static void ValidateCreditCardInfo(ModelStateDictionary modelState, PaymentForm pf)
        {
            if (pf.SavePayInfo && pf.CreditCard.HasValue() && pf.CreditCard.StartsWith("X"))
                return;

            if (!ValidateCard(pf.CreditCard, pf.SavePayInfo))
            {
                modelState.AddModelError("CreditCard", "The card number is invalid.");
            }
            if (!pf.Expires.HasValue())
            {
                modelState.AddModelError("Expires", "The expiration date is required.");
                return;
            }

            var exp = DbUtil.NormalizeExpires(pf.Expires);
            if (exp == null)
                modelState.AddModelError("Expires", "The expiration date format is invalid (MMYY).");

            if (!pf.CVV.HasValue())
            {
                modelState.AddModelError("CVV", "The CVV is required.");
                return;
            }

            var cvvlen = pf.CVV.GetDigits().Length;
            if (cvvlen < 3 || cvvlen > 4)
                modelState.AddModelError("CVV", "The CVV must be a 3 or 4 digit number.");
        }
        public void Validate(ModelStateDictionary modelState, string modelPrefix, decimal? totalMarks)
        {
            if (!this.IsSet)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(this.Grade))
            {
                modelState.AddModelError(modelPrefix + ".Grade", "Grade is required.");
            }

            if (!this.MinResult.HasValue)
            {
                modelState.AddModelError(modelPrefix + ".MinResult", "Minium required result is required.");
            }
            else
            {
                if (this.MinResult < 0)
                {
                    modelState.AddModelError(modelPrefix + ".MinResult", "Min result cannot be negative.");
                }

                if (totalMarks.HasValue && this.MinResult > totalMarks)
                {
                    modelState.AddModelError(modelPrefix + ".MinResult", "Min result must be less than total marks.");
                }
            }
        }
예제 #12
0
 public static bool IsValidEmailField(ModelStateDictionary modelState, string display, string field, string value, int maxLength, bool required = false)
 {
     bool ret = false;
     if (value.IsNullOrEmpty())
     {
         if (required)
         {
             modelState.AddModelError(field, "กรุณาใส่" + display);
         }
         else
         {
             ret = true;
         }
     }
     else if (value.Length > maxLength)
     {
         modelState.AddModelError(field, string.Format("{0}ต้องมีความยาวไม่เกิน {1} ตัวอักษร", display, maxLength));
     }
     else if (!new EmailAddressAttribute().IsValid(value))
     {
         modelState.AddModelError(field, string.Format("{0}มีรูปแบบไม่ถูกต้อง", display));
     }
     else
     {
         ret = true;
     }
     return ret;
 }
예제 #13
0
        public SignUpViewModel SignUp(SignUpActionData actionData)
        {
            var viewModel = new SignUpViewModel();

            var modelStates = new ModelStateDictionary();

            foreach (var reason in actionData.RegistrationFailureReasons) {
                switch (reason) {
                    case RegistrationFailureReason.UsernameNotAvailable:
                        modelStates.AddModelError("username", GetRegistrationFailureReasonText(RegistrationFailureReason.UsernameNotAvailable));
                        break;
                    case RegistrationFailureReason.PasswordsDoNotMatch:
                        modelStates.AddModelError("passwordConfirmation", GetRegistrationFailureReasonText(RegistrationFailureReason.PasswordsDoNotMatch));
                        break;
                    case RegistrationFailureReason.EmailsDoNotMatch:
                        modelStates.AddModelError("email", GetRegistrationFailureReasonText(RegistrationFailureReason.EmailsDoNotMatch));
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            IEnumerable<string> errors = actionData.RegistrationFailureReasons.Select(GetRegistrationFailureReasonText);
            viewModel.Errors = errors;
            viewModel.ModelState = modelStates;
            return viewModel;
        }
예제 #14
0
파일: Payments.cs 프로젝트: rossspoon/bvcms
 public static void ValidateBankAccountInfo(ModelStateDictionary ModelState, string Routing, string Account)
 {
     if (!checkABA(Routing))
         ModelState.AddModelError("Routing", "invalid routing number");
     if (!Account.HasValue())
         ModelState.AddModelError("Account", "need account number");
     else if (!Account.StartsWith("X") && Account.Length <= 4)
         ModelState.AddModelError("Account", "please enter entire account number with any leading zeros");
 }
예제 #15
0
        public static void HandleErrorDict(ModelStateDictionary stateDictionary, Dictionary<string, string> validationsDictionary)
        {
            if (validationsDictionary.Any()) {
                stateDictionary.AddModelError(String.Empty, "Please review and correct the noted errors.");
            }

            foreach (KeyValuePair<string, string> valuePair in validationsDictionary) {
                stateDictionary.AddModelError(valuePair.Key, valuePair.Value);
            }
        }
예제 #16
0
        public static void ValidateBankAccountInfo(ModelStateDictionary modelState, string routing, string account)
        {
            if (!CheckABA(routing))
                modelState.AddModelError("Routing", "The routing number is invalid.");

            if (!account.HasValue())
                modelState.AddModelError("Account", "The account number is invalid.");
            else if (!account.StartsWith("X") && account.Length <= 4)
                modelState.AddModelError("Account", "Please enter entire account number with any leading zeros.");
        }
예제 #17
0
        public static void DomainValidationErrors(this DomainValidationException ve, ModelStateDictionary modelState)
        {
            modelState.AddModelError("", ve.Message);
            ValidationResultInfo vri = ve.ValidationResult;
            List<ValidationResult> vrs = vri.Results;
            foreach (ValidationResult vr in vrs)
            {

                modelState.AddModelError("", vr.ErrorMessage);
            }
        }
예제 #18
0
        /// <summary>
        /// Validates and parses a FormFile into an Image, adding any errors into modelState.
        /// </summary>
        /// <param name="formFile">The uploaded Http file.</param>
        /// <param name="modelState">The view ModelState containing errors.</param>
        /// <param name="fieldName">The display name of field to display in errors.</param>
        /// <param name="maxFileSizeMb">The maximum file size in MB, or null.</param>
        /// <returns>The image if FormFile is valid, otherwise null.</returns>
        public async Task <Image <Rgba32>?> ProcessAsImageAsync(IFormFile?formFile, ModelStateDictionary?modelState = null, string fieldName = "Image", int?maxFileSizeMb = null)
        {
            modelState.CheckNotNull(nameof(modelState));
            if (maxFileSizeMb != null && maxFileSizeMb <= 0)
            {
                throw new ArgumentOutOfRangeException(string.Format(CultureInfo.InvariantCulture, Res.ValueMustBeNullOrPositive, nameof(maxFileSizeMb)));
            }

            if (formFile == null)
            {
                modelState?.AddModelError("",
                                          string.Format(CultureInfo.InvariantCulture, Res.FieldRequired, fieldName));
                return(null);
            }

            var fileName = Path.GetFileName(formFile.FileName);

            if (formFile.Length == 0)
            {
                modelState?.AddModelError(formFile.Name,
                                          string.Format(CultureInfo.InvariantCulture, Res.FileIsEmpty, fieldName, fileName));
            }
            else if (formFile.Length > maxFileSizeMb * 1024 * 1024)
            {
                modelState?.AddModelError(formFile.Name,
                                          string.Format(CultureInfo.InvariantCulture, Res.FileExceedsMaxSize, fieldName, fileName, maxFileSizeMb));
            }
            else
            {
                // Check file extension (must be JPG, GIF or PNG).
                if (fileName == null || !ValidExtensions.Any(x => fileName.EndsWith(x, StringComparison.InvariantCultureIgnoreCase)))
                {
                    modelState?.AddModelError(formFile.Name,
                                              string.Format(CultureInfo.InvariantCulture, Res.FileIsNotValidImage, fieldName, fileName));
                }
                else
                {
                    // Ensure file is valid.
                    try
                    {
                        var result = await Task.Run(() => Image.Load(formFile.OpenReadStream())).ConfigureAwait(false);

                        return(result);
                    }
                    catch (NotSupportedException)
                    {
                        modelState?.AddModelError(formFile.Name,
                                                  string.Format(CultureInfo.InvariantCulture, Res.FileIsNotValidImage, fieldName, fileName));
                    }
                }
            }
            return(null);
        }
예제 #19
0
        private void CheckFields(ref ModelStateDictionary modelStateDictionary)
        {
            if (String.IsNullOrEmpty(Subject))
            {
                modelStateDictionary.AddModelError(BaseCache.SubjectField, String.Format(ValidationResource.Global_Required_ErrorMessage, FieldResource.Global_EmailSubject_Name));
                return;
            }

            if (String.IsNullOrEmpty(Body))
            {
                modelStateDictionary.AddModelError(BaseCache.BodyField, String.Format(ValidationResource.Global_Required_ErrorMessage, FieldResource.Global_EmailBody_Name));
            }
        }
        internal void ValidateFields(ProjectModel model, ModelStateDictionary modelState)
        {
            if (model.Name == "" || model.Name == null) {
                modelState.AddModelError("NameRequired", "Name is Required");
            }

            if (model.Code == "" || model.Code == null) {
                modelState.AddModelError("CodeRequired", "Code is Required");
            }

            if (model.Budget == 0) {
                modelState.AddModelError("BudgetRequired", "Budget is Required");
            }
        }
예제 #21
0
        internal void ValidateFields(SignInModel model, ModelStateDictionary modelState)
        {
            if (model.Password == "" || model.Password == null) {
                modelState.AddModelError("PasswordRequired", "Password is Required");
            }

            if (model.Username == "" || model.Username == null) {
                modelState.AddModelError("UsernameRequired", "Username is Required");
            }

            if (!model.Username.IsEmail()) {
                modelState.AddModelError("EmailRequired", "Username must be in email form");
            }
        }
        public void WithModelStateShouldNotThrowExceptionWhenModelStateHasSameErrors()
        {
            var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors();
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647.");
            modelState.AddModelError("RequiredString", "The RequiredString field is required.");

            MyController<MvcController>
                .Instance()
                .Calling(c => c.BadRequestWithModelState(requestModelWithErrors))
                .ShouldReturn()
                .BadRequest()
                .WithModelStateError(modelState);
        }
        public bool UpdateProfileFromValues(ModelStateDictionary errors)
        {
            if (ProfileValues.All(x => String.IsNullOrWhiteSpace(x.Data.Value)))
            {
                ProfileManager.DeleteProfile(Username);
                return true;
            }

            var profile = ProfileBase.Create(Username);
            for (int i = 0; i < ProfileValues.Length; i++)
            {
                var prop = ProfileBase.Properties[ProfileValues[i].Data.Name];
                try
                {
                    if (String.IsNullOrWhiteSpace(ProfileValues[i].Data.Value) && 
                        prop.PropertyType.IsValueType)
                    {
                        errors.AddModelError("profileValues[" + i + "].value", string.Format(Resources.UserProfileViewModel.RequiredProperty, prop.Name));
                    }
                    else
                    {
                        object val = Convert.ChangeType(ProfileValues[i].Data.Value, prop.PropertyType);
                        profile.SetPropertyValue(prop.Name, val!=null ? val.ToString() : string.Empty);
                    }
                }
                catch (FormatException ex)
                {
                    errors.AddModelError("profileValues[" + i + "].value", string.Format(Resources.UserProfileViewModel.ErrorConvertingPropertyValueEx, prop.Name, ex.Message));
                }
                catch (Exception)
                {
                    errors.AddModelError("profileValues[" + i + "].value", string.Format(Resources.UserProfileViewModel.ErrorConvertingPropertyValueType, prop.Name, prop.PropertyType.Name));
                }
            }

            if (errors.IsValid)
            {
                try
                {
                    profile.Save();
                }
                catch (Exception ex)
                {
                    errors.AddModelError("", "Error updating profile.");
                    Tracing.Error(ex.Message);
                }
            }

            return errors.IsValid;
        }
예제 #24
0
        /// <summary>
        /// Saves the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="modelState">The validation information.</param>
        /// <returns>The file path.</returns>
        public static async Task <string> SaveFile(IFormFile file, ModelStateDictionary modelState)
        {
            const string emptyFileErrorMessage = "The file is empty.";
            const string destFolder            = "wwwroot";

            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            if (file.Length == 0)
            {
                modelState?.AddModelError(file.Name, emptyFileErrorMessage);
            }
            else
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), destFolder, file.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                    await file.CopyToAsync(stream);

                return(path);
            }

            return(string.Empty);
        }
 public void PassErrorsToMvcModelState(ModelStateDictionary modelState)
 {
     foreach (var eMsg in ErrorMessages)
     {
         modelState.AddModelError(eMsg.Key, eMsg.Value);
     }
 }
예제 #26
0
파일: Currency.cs 프로젝트: MulderFox/Main
        private void ValidateExchangeRate(ref ModelStateDictionary modelStateDictionary)
        {
            if (ExchangeRateToCZK >= 0)
                return;

            modelStateDictionary.AddModelError(BaseCache.ExchangeRateToCZKField, String.Format(ValidationResource.Global_RangeNumberPositive_ErrorMessage, FieldResource.Currency_ExchangeRateToCZK_Name));
        }
예제 #27
0
파일: Currency.cs 프로젝트: MulderFox/Main
        private void ValidateUniqueCurrency(IEnumerable<Currency> otherCurrencies, ref ModelStateDictionary modelStateDictionary)
        {
            if (otherCurrencies.All(oc => oc.CurrencyType != CurrencyType))
                return;

            modelStateDictionary.AddModelError(BaseCache.CurrencyTypeField, String.Format(ValidationResource.Global_OwnUnique_ErrorMessage, FieldResource.Global_Currency_Name));
        }
예제 #28
0
        public ModelStateDictionary SendEmails(DefaultContext db)
        {
            var modelStateDictionary = new ModelStateDictionary();
            UserProfile[] userProfiles = UserProfileCache.GetIndex(db);
            bool success = true;
            foreach (UserProfile userProfile in userProfiles.Where(up => !String.IsNullOrEmpty(up.Email1)))
            {
                bool partialSuccess = Mail.SendEmail(userProfile.Email1, Subject, Body, true, true);
                if (partialSuccess)
                {
                    string logMessage = String.Format("Email for user {0} with address {1} was successfully sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetLog(logMessage);
                }
                else
                {
                    string errorMessage = String.Format("Email for user {0} with address {1} was not sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetErrorLog(errorMessage);
                }

                success &= partialSuccess;
            }

            if (!success)
            {
                modelStateDictionary.AddModelError(BaseCache.EmptyField, ValidationResource.BulkMail_SomeEmailWasNotSent_ErrorMessage);
            }

            return modelStateDictionary;
        }
예제 #29
0
 public static void AddErrorsToModelState(ModelStateDictionary modelState, IEnumerable<ValidationError> errors, string parameterName)
 {
     foreach(ValidationError invalidValue in errors)
     {
         modelState.AddModelError(parameterName + "." + invalidValue.PropertyPath, invalidValue.Message);
     }
 }
        public async Task InvalidModelStateResult_WritesHttpError()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = CreateServices();

            var stream = new MemoryStream();
            httpContext.Response.Body = stream;

            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var modelState = new ModelStateDictionary();
            modelState.AddModelError("product.Name", "Name is required.");

            var expected =
                "{\"Message\":\"The request is invalid.\"," +
                "\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";

            var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content);
            }
        }
        public void Validate_SimpleType_MaxErrorsReached()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)"test";

            modelState.MaxAllowedErrors = 1;
            modelState.AddModelError("other.Model", "error");
            modelState.SetModelValue("parameter", "test", "test");
            validationState.Add(model, new ValidationStateEntry() { Key = "parameter" });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, "parameter", model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, string.Empty, "parameter");

            var entry = modelState["parameter"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
예제 #32
0
 public static void MapBrokenRules(ModelStateDictionary modelState, Csla.Core.BusinessBase businessObject)
 {
     foreach (var brokenRule in businessObject.BrokenRulesCollection)
     {
         modelState.AddModelError(brokenRule.Property, brokenRule.Description);
     }
 }
예제 #33
0
 private static bool CheckFormFileNotNull([NotNullWhen(true)] IFormFile?formFile, ModelStateDictionary?modelState, string fieldName)
 {
     if (formFile == null)
     {
         modelState?.AddModelError("", string.Format(CultureInfo.InvariantCulture, "{0} is required.", fieldName));
         return(false);
     }
     return(true);
 }
예제 #34
0
        public static bool IsImage(this IFormFile postedFile, IOptions <PhotoConfig> photoConfig, ModelStateDictionary modelState = null)
        {
            if (postedFile.ContentType.ToLower() != "image/jpg" &&
                postedFile.ContentType.ToLower() != "image/jpeg" &&
                postedFile.ContentType.ToLower() != "image/pjpeg" &&
                postedFile.ContentType.ToLower() != "image/gif" &&
                postedFile.ContentType.ToLower() != "image/x-png" &&
                postedFile.ContentType.ToLower() != "image/png")
            {
                modelState?.AddModelError("ImageName", "Incorrect image format");
                return(false);
            }
            if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".png" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".gif" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
            {
                modelState?.AddModelError("ImageName", "Incorrect image format");
                return(false);
            }

            try
            {
                if (!postedFile.OpenReadStream().CanRead)
                {
                    modelState?.AddModelError("ImageName", "Image can not be read");
                    return(false);
                }
                if (postedFile.Length < photoConfig.Value.MinSize)
                {
                    modelState?.AddModelError("ImageName", "Image size is too small");
                    return(false);
                }
                if (postedFile.Length > photoConfig.Value.MaxSize)
                {
                    modelState?.AddModelError("ImageName", "Image size is too big");
                    return(false);
                }

                var buffer = new byte[photoConfig.Value.MinSize];
                postedFile.OpenReadStream().Read(buffer, 0, photoConfig.Value.MinSize);
                var content = System.Text.Encoding.UTF8.GetString(buffer);
                if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                                  RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
                {
                    modelState?.AddModelError("ImageName", "Wrong image format");
                    return(false);
                }
            }
            catch (Exception)
            {
                modelState?.AddModelError("ImageName", "There is an error with your file");
                return(false);
            }
            postedFile.OpenReadStream().Position = 0;

            return(true);
        }
예제 #35
0
 private void ValidateReadOnlyProperties(ModelStateDictionary?modelState)
 {
     // assumes presence means value is true!
     foreach (var property in _members.Where(x => x.HasAttribute <ReadOnlyAttribute>()))
     {
         if (_changed.Contains(property.Name))
         {
             modelState?.AddModelError(property.Name, $"ApplyTo is attempting to change '{property.Name}' to '{_reads[_data, property.Name]}', but it is defined as read only.");
         }
     }
 }
 public static void AddModelError <TModel>(this ModelStateDictionary modelState, Expression <Func <TModel, Object> > expression, String format, params Object[] args)
 {
     modelState.AddModelError(GetExpressionText(expression), String.Format(format, args));
 }
예제 #37
0
 public static void AddModelError(this ModelStateDictionary modelState, string message)
 {
     modelState.AddModelError("", message);
 }
예제 #38
0
        public void StartRegistrationForFamilyMember(int id, ModelStateDictionary modelState)
        {
            modelState.Clear(); // ensure we pull form fields from our model, not MVC's
            HistoryAdd("Register");
            int index = List.Count - 1;
            var p     = LoadExistingPerson(id, index);

            if (p.NeedsToChooseClass())
            {
                modelState.AddModelError("fammember-" + p.PeopleId, "Please make selection above");
                return;
            }
            if (p.ComputesOrganizationByAge())
            {
                if (p.org == null)
                {
                    modelState.AddModelError("fammember-" + p.PeopleId, "No Appropriate Org");
                    return;
                }
            }
            List[index] = p;

            p.ValidateModelForFind(modelState, id, selectFromFamily: true);
            if (!modelState.IsValid)
            {
                return;
            }

            if (p.ManageSubscriptions() && p.Found == true)
            {
                return;
            }

            if (p.org != null && p.Found == true)
            {
                if (!SupportMissionTrip)
                {
                    p.IsFilled = p.org.RegLimitCount(DbUtil.Db) >= p.org.Limit;
                }

                if (p.IsFilled)
                {
                    modelState.AddModelError(this.GetNameFor(mm => mm.List[List.IndexOf(p)].Found),
                                             "Sorry, but registration is filled.");
                }

                if (p.IsCommunityGroup() && DbUtil.Db.Setting("RestrictCGSignupsTo24Hrs"))
                {
                    if (!p.CanRegisterInCommunityGroup(DateTime.Today.AddDays(-1)))
                    {
                        var message = DbUtil.Db.Setting("RestrictCGSignupsTo24HrsMessage", "Sorry, but you cannot register for multiple community groups on the same day.");
                        modelState.AddModelError(this.GetNameFor(mm => mm.List[List.IndexOf(p)].Found), message);
                    }
                }

                if (p.Found == true)
                {
                    p.FillPriorInfo();
                }

                return;
            }
            if (p.org == null && p.ComputesOrganizationByAge())
            {
                modelState.AddModelError(this.GetNameFor(mm => mm.List[id].Found), p.NoAppropriateOrgError);
            }
        }
예제 #39
0
        public void ValidateModelForFind(ModelStateDictionary ModelState, OnlineRegModel m, int i, bool selectfromfamily = false)
        {
            IsValidForContinue = true; // true till proven false
            if (UserSelectsOrganization())
            {
                if ((classid ?? 0) == 0)
                {
                    var          nameclassid             = Parent.GetNameFor(mm => mm.List[i].classid);
                    const string pleaseChooseAGroupEvent = "please choose a group/event";
                    if (IsFamily)
                    {
                        ModelState.AddModelError(nameclassid, pleaseChooseAGroupEvent);
                    }
                    else
                    {
                        ModelState.AddModelError(nameclassid, pleaseChooseAGroupEvent);
                    }
                    IsValidForExisting = ModelState.IsValid;
                    return;
                }
            }
            var dobname   = Parent.GetNameFor(mm => mm.List[i].DateOfBirth);
            var foundname = Parent.GetNameFor(mm => mm.List[i].Found);

            if (IsFamily)
            {
                foundname = "fammember-" + PeopleId;
            }
            if (!PeopleId.HasValue)
            {
                ValidBasic(ModelState, i);
            }
            if (ComputesOrganizationByAge() && !birthday.HasValue)
            {
                ModelState.AddModelError(dobname, "birthday required");
            }
            var minage = DbUtil.Db.Setting("MinimumUserAge", "16").ToInt();

            if (orgid == Util.CreateAccountCode && age < minage)
            {
                ModelState.AddModelError(dobname, "must be {0} to create account".Fmt(minage));
            }
            if (!IsFamily && (!EmailAddress.HasValue() || !Util.ValidEmail(EmailAddress)))
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].EmailAddress), "Please specify a valid email address.");
            }
            if (ModelState.IsValid)
            {
                Found = person != null;
                if (count == 1)
                {
                    AddressLineOne = person.PrimaryAddress;
                    City           = person.PrimaryCity;
                    State          = person.PrimaryState;
                    ZipCode        = person.PrimaryZip;
                    gender         = person.GenderId;
                    married        = person.MaritalStatusId == 2 ? 2 : 1;

                    if (!person.EmailAddress.HasValue() &&
                        (ManageSubscriptions() ||
                         orgid == Util.CreateAccountCode ||
                         OnlineGiving() ||
                         ManageGiving() ||
                         OnlinePledge()
                        ))
                    {
                        ModelState.AddModelError(foundname, "No Email Address on record");
                        NotFoundText       = @"<strong>No Email Address on Record</strong><br/>
We have found your record but we have no email address for you.<br/>
This means that we cannot proceed until we have that to protect your data.<br/>
Please call the church to resolve this before we can complete your information.";
                        IsValidForContinue = false;
                    }
                    else if (ComputesOrganizationByAge() && org == null)
                    {
                        var msg = NoAppropriateOrgError ?? "Sorry, no approprate org";
                        if (selectfromfamily)
                        {
                            ModelState.AddModelError("age-" + person.PeopleId, msg);
                        }
                        else
                        {
                            ModelState.AddModelError(dobname, msg);
                        }
                        IsValidForContinue = false;
                    }
                    else if (MemberOnly() && person.MemberStatusId != MemberStatusCode.Member)
                    {
                        ModelState.AddModelError(foundname, "Sorry, must be a member of church");
                        if (setting.UseBootstrap)
                        {
                            NotFoundText = @"<strong>Sorry, must be a member of this church</strong>";
                        }
                        IsValidForContinue = false;
                    }
                    else if (org != null)
                    {
                        var om = org.OrganizationMembers.SingleOrDefault(mm => mm.PeopleId == PeopleId);
                        if (org.RegistrationTypeId == RegistrationTypeCode.CreateAccount)
                        {
#if DEBUG
#else
                            if (person.Users.Count() > 0)
                            {
                                ModelState.AddModelError(foundname, "You already have an account");
                                IsValidForContinue = false;
                            }
                            if (!Util.ValidEmail(person.EmailAddress))
                            {
                                ModelState.AddModelError(foundname, "You must have a valid email address on record");
                                NotFoundText       = @"We have found your record but we do not have a valid email for you.<br/>
For your protection, we cannot continue to create an account.<br />
We can't use the one you enter online here since we can't be sure this is you.<br />
Please call the church to resolve this before we can complete your account.<br />";
                                IsValidForContinue = false;
                            }
#endif
                        }
                        else if (om != null && org.IsMissionTrip == true &&
                                 !Parent.SupportMissionTrip &&
                                 om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == "Sender") &&
                                 !om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == "Goer"))
                        {
                            IsValidForContinue = true;
                        }
                        else if (om != null && setting.AllowReRegister == false &&
                                 om.Organization.RegistrationTypeId != RegistrationTypeCode.ChooseVolunteerTimes &&
                                 !Parent.SupportMissionTrip)
                        {
                            ModelState.AddModelError(foundname, "This person is already registered");
                            if (setting.UseBootstrap || Parent.UseBootstrap)
                            {
                                NotFoundText = @"<strong>This person is already registered</strong>";
                            }
                            CancelText         = "Regiser a different person";
                            IsValidForContinue = false;
                        }
                        else if (setting.ValidateOrgIds.Count > 0)
                        {
                            var reqmemberids = setting.ValidateOrgIds.Where(ii => ii > 0).ToList();
                            if (reqmemberids.Count > 0)
                            {
                                if (!person.OrganizationMembers.Any(mm => reqmemberids.Contains(mm.OrganizationId)))
                                {
                                    ModelState.AddModelError(foundname, "Must be member of specified organization");
                                    if (setting.UseBootstrap)
                                    {
                                        NotFoundText = @"<strong>Must be a member of specified organization to register</strong>";
                                    }
                                    IsValidForContinue = false;
                                }
                            }
                            var reqnomemberids = setting.ValidateOrgIds.Where(ii => ii < 0).ToList();
                            if (reqnomemberids.Count > 0)
                            {
                                if (person.OrganizationMembers.Any(mm => reqnomemberids.Contains(-mm.OrganizationId)))
                                {
                                    ModelState.AddModelError(foundname, "Must not be a member of specified organization");
                                    if (setting.UseBootstrap)
                                    {
                                        NotFoundText = @"<strong>Must not be a member of specified organization to register</strong>";
                                    }
                                    IsValidForContinue = false;
                                }
                            }
                        }
                    }
                    if (m.List.Count(ii => ii.PeopleId == PeopleId) > 1)
                    {
                        ModelState.AddModelError(foundname, "Person already in Pending Registration");
                        CancelText = "Regiser a different person";
                        if (setting.UseBootstrap)
                        {
                            NotFoundText = @"<strong>Person already in Pending Registration</strong>";
                        }
                        IsValidForContinue = false;
                    }
                }
                else if (count > 1)
                {
                    ModelState.AddModelError(foundname, "More than one match, sorry");
                    NotFoundText       = @"<strong>MORE THAN ONE MATCH</strong><br />
We have found more than one record that matches your information
This is an unexpected error and we don't know which one is you.
Please call the church to resolve this before we can complete your registration.";
                    IsValidForContinue = false;
                }
                else if (count == 0)
                {
                    ModelState.AddModelError(foundname, "record not found");
                    NotFoundText = @" <strong>RECORD NOT FOUND</strong><br />
                            We were not able to find you in our database. Please check the information you entered.
                            <ul>
                                <li>If everything looks good, select ""New Profile""</li>
                                <li>If you make a correction, select ""Search Again""</li>
                            </ul>";
                }
            }
            ValidateBirthdayRange(ModelState, i);
            IsValidForExisting = ModelState.IsValid;
        }
예제 #40
0
        public virtual async Task <UserLoginResult> TryRegister(
            RegisterViewModel model,
            ModelStateDictionary modelState,
            HttpContext httpContext,
            IHandleCustomRegistration customRegistration
            )
        {
            var          template    = new LoginResultTemplate();
            IUserContext userContext = null;

            var userName = !string.IsNullOrWhiteSpace(model.Username) ? model.Username : await UserManager.SuggestLoginNameFromEmail(UserManager.Site.Id, model.Email);

            var userNameAvailable = await UserManager.LoginIsAvailable(Guid.Empty, userName);

            if (!userNameAvailable)
            {
                userName = await UserManager.SuggestLoginNameFromEmail(UserManager.Site.Id, model.Email);
            }

            var user = new SiteUser
            {
                SiteId          = UserManager.Site.Id,
                UserName        = userName,
                Email           = model.Email,
                FirstName       = model.FirstName,
                LastName        = model.LastName,
                DisplayName     = model.DisplayName,
                LastLoginUtc    = DateTime.UtcNow,
                BrowserKey      = Guid.NewGuid().ToString(),
                AccountApproved = UserManager.Site.RequireApprovalBeforeLogin ? false : true
            };

            await customRegistration.ProcessUserBeforeCreate(user, httpContext);


            if (model.DateOfBirth.HasValue)
            {
                user.DateOfBirth = model.DateOfBirth.Value;
            }

            if (!string.IsNullOrWhiteSpace(UserManager.Site.RegistrationAgreement))
            {
                if (model.AgreeToTerms)
                {
                    user.AgreementAcceptedUtc = DateTime.UtcNow;
                }
            }

            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                template.User = user;
                template.IsNewUserRegistration = true;
                await LoginRulesProcessor.ProcessAccountLoginRules(template);
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    if (!string.IsNullOrWhiteSpace(error.Description) && error.Description.IndexOf("Email") > -1 && error.Description.IndexOf("is already taken") > -1)
                    {
                        //asp identity is returning an error message like "Email someaddress@somedomain is alreaady taken"
                        // this is account disclosure and we don't want that so return a more generic error message
                        //modelState.AddModelError(string.Empty, "Provided email address not accepted, please try again with a different email address.");
                        // even the above message would give a clue so don't add anything, the user still sees message "Invalid registration attempt."
                    }
                    else
                    {
                        modelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }


            if (template.RejectReasons.Count == 0 &&
                user != null &&
                template.SignInResult == SignInResult.Failed && // failed is initial state, could have been changed to lockedout
                result.Errors.Count <IdentityError>() == 0
                )
            {
                await SignInManager.SignInAsync(user, isPersistent : false);

                template.SignInResult = SignInResult.Success;
            }

            if (template.User != null)
            {
                userContext = new UserContext(template.User);
            }

            return(new UserLoginResult(
                       template.SignInResult,
                       template.RejectReasons,
                       userContext,
                       template.IsNewUserRegistration,
                       template.MustAcceptTerms,
                       template.NeedsAccountApproval,
                       template.NeedsEmailConfirmation,
                       template.EmailConfirmationToken,
                       template.NeedsPhoneConfirmation
                       ));
        }
예제 #41
0
 public void AddErrors(ModelStateDictionary modelState,
                       string error = "An unexpected error occured. Please try again later.")
 {
     modelState.AddModelError("", error);
 }
 public static void AddModelError <TModel>(this ModelStateDictionary modelState, Expression <Func <TModel, Object> > expression, String message)
 {
     modelState.AddModelError(GetExpressionText(expression), message);
 }
예제 #43
0
 public static void AddToModelState(this DispatcherException ex, ModelStateDictionary modelStateDictionary)
 {
     modelStateDictionary.AddModelError("", ex.Message);
 }
        public static void CleanModelErrors <TModel>(this Controller controller)
        {
            Type containerType = typeof(TModel);
            //Save the old modelstate
            var oldModelState = new ModelStateDictionary();

            foreach (KeyValuePair <string, ModelStateEntry> modelState in controller.ModelState)
            {
                string propertyName = modelState.Key;
                foreach (ModelError error in modelState.Value.Errors)
                {
                    bool exists = oldModelState.Any(
                        m => m.Key == propertyName && m.Value.Errors.Any(e => e.ErrorMessage == error.ErrorMessage));

                    //add the inline message if it doesnt already exist
                    if (!exists)
                    {
                        oldModelState.AddModelError(propertyName, error.ErrorMessage);
                    }
                }
            }

            //Clear the model state ready for refill
            controller.ModelState.Clear();

            foreach (KeyValuePair <string, ModelStateEntry> modelState in oldModelState)
            {
                //Get the property name
                string propertyName = modelState.Key;

                //Get the validation attributes
                PropertyInfo propertyInfo             = string.IsNullOrWhiteSpace(propertyName) ? null : containerType.GetPropertyInfo(propertyName);
                List <ValidationAttribute> attributes = propertyInfo == null
                    ? null
                    : propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), false).ToList <ValidationAttribute>();

                //Get the display name
                var displayNameAttribute =
                    propertyInfo?.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault() as DisplayNameAttribute;
                var displayAttribute =
                    propertyInfo?.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
                string displayName = displayNameAttribute != null ? displayNameAttribute.DisplayName :
                                     displayAttribute != null ? displayAttribute.Name : propertyName;

                foreach (ModelError error in modelState.Value.Errors)
                {
                    string title       = string.IsNullOrWhiteSpace(propertyName) ? error.ErrorMessage : null;
                    string description = !string.IsNullOrWhiteSpace(propertyName) ? error.ErrorMessage : null;

                    if (error.ErrorMessage.Like("The value * is not valid for *."))
                    {
                        title       = "There's a problem with your values.";
                        description = "The value here is invalid.";
                    }

                    if (attributes != null && attributes.Any())
                    {
                        ValidationAttribute attribute = attributes.FirstOrDefault(a => a.FormatErrorMessage(displayName) == error.ErrorMessage);
                        if (attribute != null)
                        {
                            string             validatorKey = $"{containerType.Name}.{propertyName}:{attribute.GetType().Name.TrimSuffix("Attribute")}";
                            CustomErrorMessage customError  = CustomErrorMessages.GetValidationError(validatorKey);
                            if (customError != null)
                            {
                                title       = attribute.FormatError(customError.Title, displayName);
                                description = attribute.FormatError(customError.Description, displayName);
                            }
                        }
                    }

                    //add the summary message if it doesnt already exist
                    if (!string.IsNullOrWhiteSpace(title) &&
                        !controller.ModelState.Any(m => m.Key == "" && m.Value.Errors.Any(e => e.ErrorMessage == title)))
                    {
                        controller.ModelState.AddModelError("", title);
                    }

                    //add the inline message if it doesnt already exist
                    if (!string.IsNullOrWhiteSpace(description) &&
                        !string.IsNullOrWhiteSpace(propertyName) &&
                        !controller.ModelState.Any(
                            m => m.Key.EqualsI(propertyName) && m.Value.Errors.Any(e => e.ErrorMessage == description)))
                    {
                        controller.ModelState.AddModelError(propertyName, description);
                    }
                }
            }
        }
예제 #45
0
        internal void ValidateModelForNew(ModelStateDictionary ModelState, bool checkaddress)
        {
            if (!First.HasValue())
            {
                ModelState.AddModelError("name", "first name required");
            }

            if (!Last.HasValue())
            {
                ModelState.AddModelError("name", "last name required");
            }

            if (!birthday.HasValue && dob.NotEqual("na"))
            {
                ModelState.AddModelError("dob", "valid birthday (or \"na\")");
            }

            var d = Phone.GetDigits().Length;

            if (d != 7 && d < 10 && Phone.NotEqual("na"))
            {
                ModelState.AddModelError("phone", "7 or 10+ digits (or \"na\")");
            }

            int count = 0;
            var pids  = DbUtil.Db.FindPerson(First, Last, birthday, Email, Phone.GetDigits());

            if (pids.Any())
            {
                ModelState.AddModelError("name", "name/dob already exists in db");
            }

            if (!Util.ValidEmail(Email) && Email.NotEqual("na"))
            {
                ModelState.AddModelError("email", "valid email address (or \"na\")");
            }

            if (Gender.Value == "99")
            {
                ModelState.AddModelError("gender", "specify gender");
            }

            if (Marital.Value == "99")
            {
                ModelState.AddModelError("marital", "specify marital status");
            }

            if (checkaddress)
            {
                if (!Address.HasValue())
                {
                    ModelState.AddModelError("address", "address required (or \"na\")");
                }

                bool addrok = (City.HasValue() && State.Value.HasValue()) ||
                              Zip.HasValue() ||
                              (City.Equal("na") && State.Value.Equal("na") && Zip.Equal("na"));
                if (!addrok)
                {
                    ModelState.AddModelError("zip", "city/state required or zip required (or \"na\" in all)");
                }

                if (ModelState.IsValid &&
                    Address.NotEqual("na") && City.NotEqual("na") && State.Value.NotEqual("na") &&
                    (Country.Value.Equal("United States") || !Country.Value.HasValue()))
                {
                    var r = AddressVerify.LookupAddress(Address, Address2, City, State.Value, Zip);
                    if (r.Line1 != "error")
                    {
                        if (!r.found)
                        {
                            ModelState.AddModelError("zip",
                                                     r.address +
                                                     ", if your address will not validate, change the country to 'USA, Not Validated'");
                            return;
                        }
                        if (r.Line1 != Address)
                        {
                            ModelState.AddModelError("address", "address changed from '{0}'".Fmt(Address));
                            Address = r.Line1;
                        }
                        if (r.Line2 != (Address2 ?? ""))
                        {
                            ModelState.AddModelError("address2", "address2 changed from '{0}'".Fmt(Address2));
                            Address2 = r.Line2;
                        }
                        if (r.City != (City ?? ""))
                        {
                            ModelState.AddModelError("city", "city changed from '{0}'".Fmt(City));
                            City = r.City;
                        }
                        if (r.State != (State.Value ?? ""))
                        {
                            ModelState.AddModelError("state", "state changed from '{0}'".Fmt(State));
                            State.Value = r.State;
                        }
                        if (r.Zip != (Zip ?? ""))
                        {
                            ModelState.AddModelError("zip", "zip changed from '{0}'".Fmt(Zip));
                            Zip = r.Zip;
                        }
                    }
                }
            }
        }
예제 #46
0
 /// <summary>
 /// Add ErroMessage to ModelState
 /// </summary>
 /// <param name="modelState"></param>
 /// <param name="errorMessage"></param>
 public static void AddValidationError(this ModelStateDictionary modelState, string errorMessage)
 {
     modelState.AddModelError(KEY, errorMessage);
 }
예제 #47
0
        public static async Task <string> ProcessFormFile(IFormFile formFile,
                                                          ModelStateDictionary modelState)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(FileUpload).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

            if (property != null)
            {
                var displayAttribute =
                    property.GetCustomAttribute(typeof(DisplayAttribute))
                    as DisplayAttribute;

                if (displayAttribute != null)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Use Path.GetFileName to obtain the file name, which will
            // strip any path information passed as part of the
            // FileName property. HtmlEncode the result in case it must
            // be returned in an error message.
            var fileName = WebUtility.HtmlEncode(
                Path.GetFileName(formFile.FileName));

            // Check the file length and don't bother attempting to
            // read it if the file contains no content. This check
            // doesn't catch files that only have a BOM as their
            // content, so a content length check is made later after
            // reading the file's content to catch a file that only
            // contains a BOM.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) is empty.");
            }
            else if (formFile.Length > 1048576)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB.");
            }
            else
            {
                try
                {
                    string fileContents;

                    // The StreamReader is created to read files that are UTF-8 encoded.
                    // If uploads require some other encoding, provide the encoding in the
                    // using statement. To change to 32-bit encoding, change
                    // new UTF8Encoding(...) to new UTF32Encoding().
                    using (var ms = new MemoryStream())
                    {
                        formFile.CopyTo(ms);
                        ImageToArray img = new ImageToArray();
                        await img.request_AIAsync(ms);
                    }
                }
                catch (Exception ex)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"The {fieldDisplayName}file ({fileName}) upload failed. " +
                                             $"Please contact the Help Desk for support. Error: {ex.Message}");
                    // Log the exception
                }
            }

            return(fileName);
        }
예제 #48
0
        public void ValidateModelForNew(ModelStateDictionary ModelState, int i)
        {
            var dobname     = Parent.GetNameFor(mm => mm.List[i].DateOfBirth);
            var foundname   = Parent.GetNameFor(mm => mm.List[i].Found);
            var isnewfamily = whatfamily == 3;

            ValidBasic(ModelState, i);
            DateTime dt;

            if (RequiredDOB() && DateOfBirth.HasValue() && !Util.BirthDateValid(bmon, bday, byear, out dt))
            {
                ModelState.AddModelError(dobname, "birthday invalid");
            }
            else if (!birthday.HasValue && RequiredDOB())
            {
                ModelState.AddModelError(dobname, "birthday required");
            }
            if (birthday.HasValue && NoReqBirthYear() == false && birthday.Value.Year == Util.SignalNoYear)
            {
                ModelState.AddModelError(dobname, "BirthYear is required");
                IsValidForNew = false;
                return;
            }

            var minage = DbUtil.Db.Setting("MinimumUserAge", "16").ToInt();

            if (orgid == Util.CreateAccountCode && age < minage)
            {
                ModelState.AddModelError(dobname, "must be {0} to create account".Fmt(minage));
            }

            if (ComputesOrganizationByAge() && GetAppropriateOrg() == null)
            {
                ModelState.AddModelError(dobname, NoAppropriateOrgError);
            }

            ValidateBirthdayRange(ModelState, i);
            int n = 0;

            if (Phone.HasValue() && Phone.GetDigits().Length >= 10)
            {
                n++;
            }
            if (ShowAddress && HomePhone.HasValue() && HomePhone.GetDigits().Length >= 10)
            {
                n++;
            }

            if (RequiredPhone() && n == 0)
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].Phone), "cell or home phone required");
            }

            if (HomePhone.HasValue() && HomePhone.GetDigits().Length > 20)
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].HomePhone), "homephone too long");
            }

            if (EmailAddress.HasValue())
            {
                EmailAddress = EmailAddress.Trim();
            }
            if (!EmailAddress.HasValue() || !Util.ValidEmail(EmailAddress))
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].EmailAddress), "Please specify a valid email address.");
            }
            if (isnewfamily)
            {
                if (!AddressLineOne.HasValue() && RequiredAddr())
                {
                    ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].AddressLineOne), "address required.");
                }
                if (RequiredZip() && AddressLineOne.HasValue())
                {
                    var addrok = City.HasValue() && State.HasValue();
                    if (ZipCode.HasValue())
                    {
                        addrok = true;
                    }
                    if (!addrok)
                    {
                        ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].ZipCode), "zip required (or \"na\")");
                    }

                    if (ModelState.IsValid && AddressLineOne.HasValue() &&
                        (Country == "United States" || !Country.HasValue()))
                    {
                        var r = AddressVerify.LookupAddress(AddressLineOne, AddressLineTwo, City, State, ZipCode);
                        if (r.Line1 != "error")
                        {
                            if (r.found == false)
                            {
                                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].ZipCode), r.address + ", to skip address check, Change the country to USA, Not Validated");
                                ShowCountry = true;
                                return;
                            }
                            if (r.Line1 != AddressLineOne)
                            {
                                AddressLineOne = r.Line1;
                            }
                            if (r.Line2 != (AddressLineTwo ?? ""))
                            {
                                AddressLineTwo = r.Line2;
                            }
                            if (r.City != (City ?? ""))
                            {
                                City = r.City;
                            }
                            if (r.State != (State ?? ""))
                            {
                                State = r.State;
                            }
                            if (r.Zip != (ZipCode ?? ""))
                            {
                                ZipCode = r.Zip;
                            }
                        }
                    }
                }
            }

            if (!gender.HasValue && RequiredGender())
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].gender), "Please specify gender");
            }
            if (!married.HasValue && RequiredMarital())
            {
                ModelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].married), "Please specify marital status");
            }

            if (MemberOnly())
            {
                ModelState.AddModelError(foundname, "Sorry, must be a member of church");
            }
            else if (org != null && setting.ValidateOrgIds.Count > 0)
            {
                ModelState.AddModelError(foundname, "Must be member of specified organization");
            }

            IsValidForNew      = ModelState.IsValid;
            IsValidForContinue = ModelState.IsValid;
        }
예제 #49
0
        public void ValidateModelForOther(ModelStateDictionary modelState, int i)
        {
            if (Parent.SupportMissionTrip)
            {
                OtherOK = modelState.IsValid;
                return;
            }
            if (RecordFamilyAttendance())
            {
                OtherOK = true;
                return;
            }
            foreach (var ask in setting.AskItems)
            {
                switch (ask.Type)
                {
                case "AskEmContact":
                    if (!emcontact.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].emcontact), "emergency contact required");
                    }
                    if (!emphone.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].emphone), "emergency phone # required");
                    }
                    break;

                case "AskInsurance":
                    if (!insurance.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].insurance), "insurance carrier required");
                    }
                    if (!policy.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].policy), "insurance policy # required");
                    }
                    break;

                case "AskDoctor":
                    if (!doctor.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].doctor), "Doctor's name required");
                    }
                    if (!docphone.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].docphone), "Doctor's phone # required");
                    }
                    break;

                case "AskTylenolEtc":
                    if (!tylenol.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].tylenol), "please indicate");
                    }
                    if (!advil.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].advil), "please indicate");
                    }
                    if (!maalox.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].maalox), "please indicate");
                    }
                    if (!robitussin.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].robitussin), "please indicate");
                    }
                    break;

                case "AskSize":
                    if (shirtsize == "0")
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].shirtsize), "please select a shirt size");
                    }
                    break;

                case "AskCoaching":
                    if (!coaching.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].coaching), "please indicate");
                    }
                    break;

                case "AskSMS":
                    if (!sms.HasValue)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].sms), "please indicate");
                    }
                    break;

                case "AskDropdown":
                    string desc;
                    string namedd = Parent.GetNameFor(mm => mm.List[i].option[ask.UniqueId]);
                    var    sgi    = ((AskDropdown)ask).SmallGroupChoice(option);
                    if (sgi == null || !sgi.SmallGroup.HasValue())
                    {
                        modelState.AddModelError(namedd, "please select an option");
                    }
                    else if (((AskDropdown)ask).IsSmallGroupFilled(GroupTags, option, out desc))
                    {
                        modelState.AddModelError(namedd, "limit reached for " + desc);
                    }
                    break;

                case "AskParents":
                    if (!mname.HasValue() && !fname.HasValue())
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].fname), "please provide either mother or father name");
                    }
                    else
                    {
                        string mfirst, mlast;
                        Util.NameSplit(mname, out mfirst, out mlast);
                        if (mname.HasValue() && !mfirst.HasValue())
                        {
                            modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].mname), "provide first and last names");
                        }
                        string ffirst, flast;
                        Util.NameSplit(fname, out ffirst, out flast);
                        if (fname.HasValue() && !ffirst.HasValue())
                        {
                            modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].fname), "provide first and last names");
                        }
                    }
                    break;

                case "AskTickets":
                    if ((ntickets ?? 0) == 0)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].ntickets), "please enter a number of tickets");
                    }
                    break;

                case "AskYesNoQuestions":
                    var ynname = Parent.GetNameFor(mm => mm.List[i]);
                    for (int n = 0; n < ((AskYesNoQuestions)ask).list.Count; n++)
                    {
                        var a = ((AskYesNoQuestions)ask).list[n];
                        if (YesNoQuestion == null || !YesNoQuestion.ContainsKey(a.SmallGroup))
                        {
                            modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].YesNoQuestion[a.SmallGroup]), "please select yes or no");
                        }
                    }
                    break;

                case "AskExtraQuestions":
                    var eq = (AskExtraQuestions)ask;
                    if (setting.AskVisible("AnswersNotRequired") == false)
                    {
                        for (int n = 0; n < eq.list.Count; n++)
                        {
                            var a = eq.list[n];
                            if (ExtraQuestion == null || !ExtraQuestion[eq.UniqueId].ContainsKey(a.Question) ||
                                !ExtraQuestion[eq.UniqueId][a.Question].HasValue())
                            {
                                modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].ExtraQuestion[eq.UniqueId][a.Question]), "please give some answer");
                            }
                        }
                    }
                    break;

                case "AskCheckboxes":
                    string namecb = Parent.GetNameFor(mm => mm.List[i].Checkbox[ask.UniqueId]);
                    var    cb     = ((AskCheckboxes)ask);
                    if (cb.Max > 0 && cb.CheckboxItemsChosen(Checkbox).Count() > cb.Max)
                    {
                        modelState.AddModelError(namecb, "Max of {0} exceeded".Fmt(cb.Max));
                    }
                    else if (cb.Min > 0 && (Checkbox == null || Checkbox.Count < cb.Min))
                    {
                        modelState.AddModelError(namecb, "Min of {0} required".Fmt(cb.Min));
                    }
                    break;

                case "AskGradeOptions":
                    if (gradeoption == "00")
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].gradeoption), "please select a grade option");
                    }
                    break;
                }
            }
            var totalAmount = TotalAmount();

            if (setting.Deposit > 0)
            {
                if (!paydeposit.HasValue)
                {
                    modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].paydeposit), "please indicate");
                }
                else
                {
                    var amountToPay = AmountToPay();
                    if (paydeposit == true && amountToPay > totalAmount)
                    {
                        modelState.AddModelError(Parent.GetNameFor(mm => mm.List[i].paydeposit),
                                                 "Cannot use deposit since total due is less");
                    }
                }
            }
            if (OnlineGiving() && totalAmount <= 0)
            {
                modelState.AddModelError("form", "Gift amount required");
            }

            OtherOK = modelState.IsValid;
        }
        public virtual IPurchaseOrder PlaceOrder(ICart cart, ModelStateDictionary modelState, CheckoutViewModel checkoutViewModel)
        {
            try
            {
                if (cart.Properties[Constant.Quote.ParentOrderGroupId] != null)
                {
                    var orderLink = int.Parse(cart.Properties[Constant.Quote.ParentOrderGroupId].ToString());
                    if (orderLink != 0)
                    {
                        var quoteOrder = _orderRepository.Load <IPurchaseOrder>(orderLink);
                        if (quoteOrder.Properties[Constant.Quote.QuoteStatus] != null)
                        {
                            checkoutViewModel.QuoteStatus = quoteOrder.Properties[Constant.Quote.QuoteStatus].ToString();
                            if (quoteOrder.Properties[Constant.Quote.QuoteStatus].ToString().Equals(Constant.Quote.RequestQuotationFinished))
                            {
                                _ = DateTime.TryParse(quoteOrder.Properties[Constant.Quote.QuoteExpireDate].ToString(),
                                                      out var quoteExpireDate);
                                if (DateTime.Compare(DateTime.Now, quoteExpireDate) > 0)
                                {
                                    _orderRepository.Delete(cart.OrderLink);
                                    _orderRepository.Delete(quoteOrder.OrderLink);
                                    throw new InvalidOperationException("Quote Expired");
                                }
                            }
                        }
                    }
                }

                var processPayments   = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);
                var unsuccessPayments = processPayments.Where(x => !x.IsSuccessful);
                if (unsuccessPayments != null && unsuccessPayments.Any())
                {
                    throw new InvalidOperationException(string.Join("\n", unsuccessPayments.Select(x => x.Message)));
                }

                var processedPayments = cart.GetFirstForm().Payments.Where(x => x.Status.Equals(PaymentStatus.Processed.ToString()));

                if (!processedPayments.Any())
                {
                    // Return null in case there is no payment was processed.
                    return(null);
                }

                var totalProcessedAmount = processedPayments.Sum(x => x.Amount);
                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    throw new InvalidOperationException("Wrong amount");
                }

                var orderReference = cart.Properties["IsUsePaymentPlan"] != null && cart.Properties["IsUsePaymentPlan"].Equals(true) ? SaveAsPaymentPlan(cart) : _orderRepository.SaveAsPurchaseOrder(cart);
                var purchaseOrder  = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);
                _orderRepository.Delete(cart.OrderLink);

                cart.AdjustInventoryOrRemoveLineItems((item, validationIssue) => { });

                //Loyalty Program: Add Points and Number of orders
                _loyaltyService.AddNumberOfOrders();

                return(purchaseOrder);
            }
            catch (PaymentException ex)
            {
                modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + ex.Message);
            }
            catch (Exception ex)
            {
                modelState.AddModelError("", ex.Message);
            }

            return(null);
        }
예제 #51
0
 public void AddError(string key, string errorMessage)
 {
     _modelState.AddModelError(key, errorMessage);
 }
예제 #52
0
 public static void AddDuplicateErrorState(this ModelStateDictionary modelState)
 {
     modelState.AddModelError("", "Duplicate Data");
 }
예제 #53
0
        // **WARNING!**
        // In the following file processing methods, the file's content isn't scanned.
        // In most production scenarios, an anti-virus/anti-malware scanner API is
        // used on the file before making the file available to users or other
        // systems. For more information, see the topic that accompanies this sample
        // app.

        public static async Task <byte[]> ProcessFormFile <T>(IFormFile formFile,
                                                              ModelStateDictionary modelState, string[] permittedExtensions,
                                                              long sizeLimit)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(T).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".",
                                                                  StringComparison.Ordinal) + 1));

            if (property != null)
            {
                if (property.GetCustomAttribute(typeof(DisplayAttribute)) is
                    DisplayAttribute displayAttribute)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Don't trust the file name sent by the client. To display
            // the file name, HTML-encode the value.
            var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                formFile.FileName);

            // Check the file length. This check doesn't catch files that only have
            // a BOM as their content.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");

                return(new byte[0]);
            }

            if (formFile.Length > sizeLimit)
            {
                var megabyteSizeLimit = sizeLimit / 1048576;
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) exceeds " +
                                         $"{megabyteSizeLimit:N1} MB.");

                return(new byte[0]);
            }

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    await formFile.CopyToAsync(memoryStream);

                    // Check the content length in case the file's only
                    // content was a BOM and the content is actually
                    // empty after removing the BOM.
                    if (memoryStream.Length == 0)
                    {
                        modelState.AddModelError(formFile.Name,
                                                 $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");
                    }

                    if (!IsValidFileExtensionAndSignature(
                            formFile.FileName, memoryStream, permittedExtensions))
                    {
                        modelState.AddModelError(formFile.Name,
                                                 $"{fieldDisplayName}({trustedFileNameForDisplay}) file " +
                                                 "type isn't permitted or the file's signature " +
                                                 "doesn't match the file's extension.");
                    }
                    else
                    {
                        return(memoryStream.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) upload failed. " +
                                         $"Please contact the Help Desk for support. Error: {ex.HResult}");
                // Log the exception
            }

            return(new byte[0]);
        }
예제 #54
0
 public void AddModelError(string key, string message)
 {
     _modelState.AddModelError(key, message);
 }
        public void ValidateModel(ModelStateDictionary modelState, Int64 empid, Int64 projid)
        {
            try
            {
                ApplicationDBContext db = new ApplicationDBContext();

                if (this.ProjectEmpID == 0)
                {
                    var roleNameCount = db.ProjectEmployee.Where(x => x.ProjectID == ProjectID && x.EmployeeID == empid).Count();
                    if (roleNameCount != 0)
                    {
                        modelState.AddModelError("ProjectID", ResourceMessage.Alreadyexist);
                    }
                }
                else
                {
                    var roleNameCount = db.ProjectEmployee.Where(x => x.ProjectID == ProjectID && x.EmployeeID == empid && x.ProjectEmpID != ProjectEmpID).Count();
                    if (roleNameCount != 0)
                    {
                        modelState.AddModelError("ProjectID", ResourceMessage.Alreadyexist);
                    }
                }
                if (this.EndDate != null)
                {
                    var list = (from pm in db.ProjectMaster
                                where pm.ProjectID == projid
                                select new
                    {
                        pm.EndDate,
                    }).FirstOrDefault();

                    if (this.EndDate > list.EndDate)
                    {
                        modelState.AddModelError("EndDate", ResourceMessage.Enddateexceed);
                    }
                }
                if (this.StartDate != null)
                {
                    if (this.StartDate > this.EndDate)
                    {
                        modelState.AddModelError("StartDate", ResourceMessage.Startdate);
                    }
                }



                if (this.ProjectEmpID == 0)
                {
                    var sum = 0;
                    var inputedinvolvmentpercentage = this.InvPercentage;

                    var list = (from pe in db.ProjectEmployee.AsEnumerable()
                                where pe.EmployeeID == empid
                                select new
                    {
                        pe.ProjectID,
                        pe.InvPercentage,
                        StartDate = (pe.StartDate == null) ? DateTime.Now.Date : (pe.StartDate),
                        EndDate = (pe.EndDate == null) ? DateTime.Now.Date : (pe.EndDate)
                                  //StartDate = (pe.StartDate == null) ? null : (pe.StartDate),
                                  //EndDate = (pe.EndDate == null) ? null : (pe.EndDate)
                    }).AsEnumerable().Where(x => x.StartDate <= DateTime.Now.Date && x.EndDate >= (x.EndDate)).ToList();


                    if (list != null)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            sum = sum + (int)list[i].InvPercentage + (int)inputedinvolvmentpercentage;
                        }
                        if (sum > 100)
                        {
                            modelState.AddModelError("InvPercentage", ResourceMessage.Invpercexceed);
                        }
                    }
                }
                else
                {
                    var sum = 0;
                    var inputedinvolvmentpercentage = this.InvPercentage;

                    var list = (from pe in db.ProjectEmployee.AsEnumerable()
                                where pe.EmployeeID == empid
                                select new
                    {
                        pe.ProjectEmpID,
                        pe.ProjectID,
                        pe.InvPercentage,
                        StartDate = (pe.StartDate == null) ? DateTime.Now : (pe.StartDate),
                        EndDate = (pe.EndDate == null) ? DateTime.Now : (pe.EndDate)
                    }).AsEnumerable().Where(x => x.StartDate <= DateTime.Now.Date && x.EndDate >= (x.EndDate) && x.ProjectEmpID != ProjectEmpID).ToList();


                    if (list != null)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            sum = sum + (int)list[i].InvPercentage + (int)inputedinvolvmentpercentage;
                        }
                        if (sum > 100)
                        {
                            modelState.AddModelError("InvPercentage", ResourceMessage.Invpercexceed);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #56
0
        public static async Task <string> ProcessFormFile(IFormFile formFile,
                                                          ModelStateDictionary modelState)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(FileUpload).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

            if (property != null)
            {
                var displayAttribute =
                    property.GetCustomAttribute(typeof(DisplayAttribute))
                    as DisplayAttribute;

                if (displayAttribute != null)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Use Path.GetFileName to obtain the file name, which will
            // strip any path information passed as part of the
            // FileName property. HtmlEncode the result in case it must
            // be returned in an error message.
            var fileName = WebUtility.HtmlEncode(
                Path.GetFileName(formFile.FileName));

            if (formFile.ContentType.ToLower() != "text/plain")
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) must be a text file.");
            }

            // Check the file length and don't bother attempting to
            // read it if the file contains no content. This check
            // doesn't catch files that only have a BOM as their
            // content, so a content length check is made later after
            // reading the file's content to catch a file that only
            // contains a BOM.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) is empty.");
            }
            else if (formFile.Length > 1048576)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB.");
            }
            else
            {
                try
                {
                    string fileContents;

                    // The StreamReader is created to read files that are UTF-8 encoded.
                    // If uploads require some other encoding, provide the encoding in the
                    // using statement. To change to 32-bit encoding, change
                    // new UTF8Encoding(...) to new UTF32Encoding().
                    using (
                        var reader =
                            new StreamReader(
                                formFile.OpenReadStream(),
                                new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,
                                                 throwOnInvalidBytes: true),
                                detectEncodingFromByteOrderMarks: true))
                    {
                        fileContents = await reader.ReadToEndAsync();

                        // Check the content length in case the file's only
                        // content was a BOM and the content is actually
                        // empty after removing the BOM.
                        if (fileContents.Length > 0)
                        {
                            return(fileContents);
                        }
                        else
                        {
                            modelState.AddModelError(formFile.Name,
                                                     $"The {fieldDisplayName}file ({fileName}) is empty.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"The {fieldDisplayName}file ({fileName}) upload failed. " +
                                             $"Please contact the Help Desk for support. Error: {ex.Message}");
                    // Log the exception
                }
            }

            return(string.Empty);
        }
예제 #57
0
 /// <summary>
 /// Adds error message with empty key.
 /// </summary>
 /// <param name="state"></param>
 /// <param name="errorMessage"></param>
 public static void AddModelError(
     this ModelStateDictionary state,
     string errorMessage)
 {
     state.AddModelError(String.Empty, errorMessage);
 }
예제 #58
0
 public static ModelStateDictionary AddErrorToModelState(string code, string description, ModelStateDictionary modelState)
 {
     modelState.AddModelError(code, description);
     return(modelState);
 }
예제 #59
0
        internal void ValidateModelForNew(ModelStateDictionary ModelState, bool checkaddress)
        {
            if (!first.HasValue())
            {
                ModelState.AddModelError("name", "first name required");
            }

            if (!last.HasValue())
            {
                ModelState.AddModelError("name", "last name required");
            }

            if (!birthday.HasValue && dob.NotEqual("na"))
            {
                ModelState.AddModelError("dob", "valid birthday (or \"na\")");
            }

            var d = phone.GetDigits().Length;

            if (d != 7 && d < 10 && phone.NotEqual("na"))
            {
                ModelState.AddModelError("phone", "7 or 10+ digits (or \"na\")");
            }

            int count = 0;

            PeopleSearchModel.FindPerson(first, last, birthday ?? DateTime.MinValue, string.Empty, phone.GetDigits(),
                                         out count);
            if (count > 0)
            {
                ModelState.AddModelError("name", "name/dob already exists in db");
            }

            if (!Util.ValidEmail(email) && email.NotEqual("na"))
            {
                ModelState.AddModelError("email", "valid email address (or \"na\")");
            }

            if (gender == 99)
            {
                ModelState.AddModelError("gender", "specify gender");
            }

            if (marital == 99)
            {
                ModelState.AddModelError("marital", "specify marital status");
            }

            if (checkaddress)
            {
                if (!address.HasValue())
                {
                    ModelState.AddModelError("address", "address required (or \"na\")");
                }

                var addrok = false;
                if (city.HasValue() && state.HasValue())
                {
                    addrok = true;
                }
                if (zip.HasValue())
                {
                    addrok = true;
                }
                if (city.Equal("na") && state.Equal("na") && zip.Equal("na"))
                {
                    addrok = true;
                }
                if (!addrok)
                {
                    ModelState.AddModelError("zip", "city/state required or zip required (or \"na\" in all)");
                }

                if (ModelState.IsValid &&
                    address.NotEqual("na") && city.NotEqual("na") && state.NotEqual("na") &&
                    (country.Equal("United States") || !country.HasValue()))
                {
                    var r = AddressVerify.LookupAddress(address, address2, city, state, zip);
                    if (r.Line1 != "error")
                    {
                        if (!r.found)
                        {
                            ModelState.AddModelError("zip",
                                                     r.address +
                                                     ", if your address will not validate, change the country to 'USA, Not Validated'");
                            return;
                        }
                        if (r.Line1 != address)
                        {
                            ModelState.AddModelError("address", "address changed from '{0}'".Fmt(address));
                            address = r.Line1;
                        }
                        if (r.Line2 != (address2 ?? ""))
                        {
                            ModelState.AddModelError("address2", "address2 changed from '{0}'".Fmt(address2));
                            address2 = r.Line2;
                        }
                        if (r.City != (city ?? ""))
                        {
                            ModelState.AddModelError("city", "city changed from '{0}'".Fmt(city));
                            city = r.City;
                        }
                        if (r.State != (state ?? ""))
                        {
                            ModelState.AddModelError("state", "state changed from '{0}'".Fmt(state));
                            state = r.State;
                        }
                        if (r.Zip != (zip ?? ""))
                        {
                            ModelState.AddModelError("zip", "zip changed from '{0}'".Fmt(zip));
                            zip = r.Zip;
                        }
                    }
                }
            }
        }
예제 #60
0
 /// <summary>
 /// Adds the model state errors.
 /// </summary>
 /// <param name="exception">The exception.</param>
 /// <param name="modelState">State of the model.</param>
 public static void AddModelStateErrors(this Exception exception, ModelStateDictionary modelState)
 {
     modelState.AddModelError("_FORM", exception);
 }