public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("TDDIEpsilonScriptExecutionExceptionUnion"); oprot.WriteStructBegin(struc); TField field = new TField(); if (ValidationFailedException != null && __isset.ValidationFailedException) { field.Name = "ValidationFailedException"; field.Type = TType.Struct; field.ID = 1; oprot.WriteFieldBegin(field); ValidationFailedException.Write(oprot); oprot.WriteFieldEnd(); } if (EpsilonScriptExecutionException != null && __isset.EpsilonScriptExecutionException) { field.Name = "EpsilonScriptExecutionException"; field.Type = TType.Struct; field.ID = 2; oprot.WriteFieldBegin(field); EpsilonScriptExecutionException.Write(oprot); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } }
public void InvalidInputInSingleValidatorThrowsException() { var invalidValue = "lowercase_only"; var optionSettingItem = new OptionSettingItem("id", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = "^[A-Z]*$" } } } }; ValidationFailedException exception = null; // ACT try { optionSettingItem.SetValueOverride(invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); exception.Message.ShouldContain("[A-Z]*"); }
public override string ToString() { StringBuilder __sb = new StringBuilder("TDDIEpsilonScriptExecutionExceptionUnion("); bool __first = true; if (ValidationFailedException != null && __isset.ValidationFailedException) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("ValidationFailedException: "); __sb.Append(ValidationFailedException == null ? "<null>" : ValidationFailedException.ToString()); } if (EpsilonScriptExecutionException != null && __isset.EpsilonScriptExecutionException) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("EpsilonScriptExecutionException: "); __sb.Append(EpsilonScriptExecutionException == null ? "<null>" : EpsilonScriptExecutionException.ToString()); } __sb.Append(")"); return(__sb.ToString()); }
public void Constructor() { string targetName = "name"; string validation = "validation"; var exception = new ValidationFailedException(targetName, validation); Assert.AreEqual(targetName, exception.TargetName); Assert.AreEqual(validation, exception.Validation); }
public void GetObjectData() { var info = new SerializationInfo(typeof(ValidationFailedException), new FormatterConverter()); var context = new StreamingContext(); var exception = new ValidationFailedException("targetNameValue", "validationValue"); exception.GetObjectData(info, context); Assert.AreEqual("targetNameValue", info.GetString("targetName")); Assert.AreEqual("validationValue", info.GetString("validation")); }
/// <summary> /// Format service fault to be represented as <c>ServiceFault</c> /// </summary> /// <param name="failedValidation">Failed validation</param> /// <returns><c>ServiceFault</c></returns> private ServiceFault FormatServiceFault(ValidationFailedException failedValidation) { var validationErrors = from x in failedValidation.FailedValidations select x.ValidationErrors; var validationErrorsFlatten = validationErrors.SelectMany(x => x); var errors = from x in validationErrorsFlatten select x.ErrorMessage; var errorsCombined = String.Join(Environment.NewLine, errors); return(new ServiceFault { Error = errorsCombined }); }
public void GetObjectData_NullInfo() { var exception = new ValidationFailedException("asdf", "asdf"); try { exception.GetObjectData(null, new StreamingContext()); } catch (ArgumentNullException e) { Assert.AreEqual("info", e.ParamName); throw; } }
public void Constructor_EmptyName() { string targetName = string.Empty; string validation = "validation"; try { var exception = new ValidationFailedException(targetName, validation); } catch (ArgumentException e) { Assert.AreEqual("targetName", e.ParamName); throw; } }
public void SerializationConstructor() { var input = new ValidationFailedException("targetNameValue", "validationValue"); var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, input); stream.Seek(0, SeekOrigin.Begin); var output = (ValidationFailedException)formatter.Deserialize(stream); Assert.IsFalse(object.ReferenceEquals(input, output)); Assert.AreEqual(input.TargetName, output.TargetName); Assert.AreEqual(input.Validation, output.Validation); }
/// <summary> /// Validates the class data model; used prior to saving changes; /// </summary> /// <exception cref="ValidationFailedException"></exception> public virtual async Task ValidateAsync(DbContext dbCtx = null) { // Get validator class with config (validation criteria) var validators = GetValidators(); // If validator is not found then model is valid by default if (validators == null) { return; } var validationFailedException = new ValidationFailedException(); foreach (var validator in validators) { // Run fluend validation var result = validator.Validate(this); // If model is not valid then create exception response and throw generated exception if (!result.IsValid) { foreach (var error in result.Errors) { validationFailedException.ValidationErrors.Add( new ValidationError { Message = error.ErrorMessage, Code = error.ErrorCode, PropertyName = error.PropertyName, Info = error.FormattedMessagePlaceholderValues } ); } } } if (validationFailedException.ValidationErrors.Count > 0) { throw validationFailedException; } await ValidateAgainstDbAsync(dbCtx); }
/// <summary> /// validates the org slug for uniqueness /// </summary> /// <param name="dbCtx"></param> /// <returns></returns> protected override async Task ValidateAgainstDbAsync(DbContext dbCtx) { var slugTaken = !string.IsNullOrEmpty(Slug) && await dbCtx.Set <Organisation>().AnyAsync(o => o.Uuid != Uuid && o.Slug == Slug) || await dbCtx.Set <MapHiveUser>().AnyAsync(u => u.UserOrgId != Uuid && u.Slug == Slug); if (slugTaken) { var validationFailedException = new ValidationFailedException(); validationFailedException.ValidationErrors.Add(new ValidationError { Message = "Organisation slug already taken.", Code = "slug_taken", PropertyName = nameof(Slug) }); throw validationFailedException; } }
public void CustomValidatorMessagePropagatesToValidationException() { // ARRANGE var customValidationMessage = "Custom Validation Message: Testing!"; var invalidValue = 100; var optionSettingItem = new OptionSettingItem("id", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10, ValidationFailedMessage = customValidationMessage } } } }; ValidationFailedException exception = null; // ACT try { optionSettingItem.SetValueOverride(invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); exception.Message.ShouldEqual(customValidationMessage); } }
private void Validate <T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { optionSettingItem.SetValueOverride(value); } catch (ValidationFailedException e) { exception = e; } if (isValid) { exception.ShouldBeNull(); } else { exception.ShouldNotBeNull(); } }
public void ValidInputDoesNotThrowException() { var validValue = 8; var optionSettingItem = new OptionSettingItem("id", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10 } }, new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Required } } }; ValidationFailedException exception = null; // ACT try { optionSettingItem.SetValueOverride(validValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldBeNull(); }
public void InvalidInputInMultipleValidatorsThrowsException(string invalidValue) { var optionSettingItem = new OptionSettingItem("id", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Required }, new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10 } } } }; ValidationFailedException exception = null; // ACT try { optionSettingItem.SetValueOverride(invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); _output.WriteLine(exception.Message); }
/// <summary> /// validates the org slug for uniqueness /// </summary> /// <param name="dbCtx"></param> /// <returns></returns> protected override async Task ValidateAgainstDbAsync(DbContext dbCtx) { var validationFailedException = new ValidationFailedException(); if (await dbCtx.Set <MapHiveUser>().AnyAsync(u => u.Uuid != Uuid && u.Email == Email)) { throw Validation.Utils.GenerateValidationFailedException(nameof(Email), ValidationErrors.EmailInUse); } Organisation org = null; if (Uuid != default(Guid)) { org = await GetUserOrganisationAsync(dbCtx); } var slugTaken = !string.IsNullOrEmpty(Slug) && //another user with given slug exists await dbCtx.Set <MapHiveUser>().AnyAsync(u => u.Uuid != Uuid && u.Slug == Slug) //user has an org but there is another org with given slug || (org != null && await dbCtx.Set <Organisation>().AnyAsync(o => o.Uuid != org.Uuid && o.Slug == Slug)) //another org exists that has reserved the slug || (org == null && await dbCtx.Set <Organisation>().AnyAsync(o => o.Slug == Slug)); if (slugTaken) { validationFailedException.ValidationErrors.Add(new ValidationError { Message = "MapHiveUser slug already taken.", Code = "slug_taken", PropertyName = nameof(Slug) }); throw validationFailedException; } }
/// <summary> /// Gets result action. This helper method can simply controller's actions by writing less code. /// </summary> /// <typeparam name="TMvcModel">Mvc model that is used in view.</typeparam> /// <typeparam name="TBusinessModel">Business model of UI model.</typeparam> /// <param name="model">Model that is passed from UI to controller by post action</param> /// <param name="runSafelyValidAction">A func method that returns ActionResult and is used in RunSafely 'try' block</param> /// <param name="businessModel"></param> /// <param name="businessModelNotValidAction">Action to take when the business model is an istance of IValidator and is not valid</param> /// <param name="throwExOnBusinessValidationFails">If true, throws an exception when business model validation fails after businessModelNotValidAction action method is called. If this parameter is false, no exeption is thrown and businessModelNotValidAction is called.</param> /// <returns>Returns an ActionResult</returns> public ActionResult RunSafelyInAction <TMvcModel, TBusinessModel>(TMvcModel model, Action runSafelyValidAction, ref TBusinessModel businessModel, Action businessModelNotValidAction = null, bool throwExOnBusinessValidationFails = false) { ActionResult result = null; if (model is ITypeMapper <TBusinessModel> ) { businessModel = ((ITypeMapper <TBusinessModel>)model).ToType(); if (businessModel is IValidator) { IValidator businessModelValidator = (IValidator)businessModel; if (!businessModelValidator.IsValid()) { if (businessModelNotValidAction != null) { businessModelNotValidAction(); if (throwExOnBusinessValidationFails) { ValidationFailedException.Throw(typeof(TBusinessModel).Name); } } } else { if (businessModelValidator.Errors != null && businessModelValidator.Errors.Keys.Count > 0) { foreach (string eachKey in businessModelValidator.Errors.Keys) { this.ModelState.AddModelError(eachKey, businessModelValidator.Errors[eachKey]); } } } } if (ModelState.IsValid) { this.RunSafely(runSafelyValidAction, (ex) => { result = Exception(ex); }); } } //if (result is ExceptionResult) //{ // return result; //} //bool isAjaxRequest = this.CaterpillarMvcHttpRequest.IsAjaxRequest(); //DataType dataType = this.CaterpillarMvcHttpRequest.GetResponseType(); //switch (dataType) //{ // case DataType.Json: // JsonResultBase jrb = new JsonResultBase(); // jrb.Success(businessModel); // jrb.ClientSideAction = clientActionToactiontoTakeInClient; // result = Json(jrb, JsonRequestBehavior.AllowGet); // break; // case DataType.Html: // if (isAjaxRequest) // { // if (string.IsNullOrWhiteSpace(partialViewName)) // { // result = PartialView(businessModel); // } // else // { // result = PartialView(partialViewName, businessModel); // } // } // else // { // result = View(businessModel); // } // break; // case DataType.Text: // case DataType.Xml: // case DataType.NotSet: // default: // break; //} //return result; return(result); }
/// <summary> /// Creates an org owner account - creates a user profile, an organization for a user, ties all the bits and pieces together /// </summary> /// <param name="dbCtx"></param> /// <param name="input"></param> /// <param name="emailSender"></param> /// <returns></returns> public static async Task <AccountCreateOutput> CreateAccountAsync( MapHiveDbContext dbCtx, AccountCreateInput input, IEmailSender emailSender ) { var user = new MapHive.Core.DataModel.MapHiveUser() { Email = input.AccountDetails.Email, Slug = input.AccountDetails.Slug, Forename = input.AccountDetails.Forename, Surname = input.AccountDetails.Surname, Company = input.AccountDetails.Company, Department = input.AccountDetails.Department, ContactPhone = input.AccountDetails.ContactPhone }; //now the org object var orgNameDesc = string.IsNullOrEmpty(input.AccountDetails.Company) ? input.AccountDetails.Email + "-org" : input.AccountDetails.Company; var newOrg = new Organization { DisplayName = orgNameDesc, Description = orgNameDesc, Slug = Utils.Slug.GetOrgSlug(orgNameDesc, user.Slug + "-org"), //push to extra billing info? BillingExtraInfo = new SerializableDictionaryOfString { { nameof(input.AccountDetails.ContactPhone), input.AccountDetails.ContactPhone }, { nameof(input.AccountDetails.Email), input.AccountDetails.Email }, { "ContactPerson", $"{input.AccountDetails.Forename} {input.AccountDetails.Surname}" }, { nameof(input.AccountDetails.Street), input.AccountDetails.Street }, { nameof(input.AccountDetails.HouseNo), input.AccountDetails.HouseNo }, { nameof(input.AccountDetails.FlatNo), input.AccountDetails.FlatNo }, { nameof(input.AccountDetails.Postcode), input.AccountDetails.Postcode }, { nameof(input.AccountDetails.City), input.AccountDetails.City }, { nameof(input.AccountDetails.Country), input.AccountDetails.Country }, { nameof(input.AccountDetails.VatNumber), input.AccountDetails.VatNumber } }, LicenseOptions = new OrganizationLicenseOptions() }; //got the user and org, o need to validate them now in order to ensure they are creatable if (user.Slug == newOrg.Slug) { var ex = new ValidationFailedException(); ex.ValidationErrors.Add(new ValidationError { Message = $"MapHiveUser slug already taken: {user.Slug}", Code = "user_org_slug_duplicate", PropertyName = nameof(MapHiveUser.Slug) }); throw ex; } //validate user and org - both should throw if a slug is already taken await user.ValidateAsync(dbCtx); await newOrg.ValidateAsync(dbCtx); //prepare the email template tokens known at this stage, var tokens = new Dictionary <string, object> { { "UserName", $"{user.GetFullUserName()} ({user.Email})" }, { "Email", user.Email } }; //and create user var accountCreateOutput = await MapHive.Core.DataModel.MapHiveUser.CreateUserAccountAsync(dbCtx, user, emailSender, input.EmailAccount, input.EmailTemplate?.Prepare(tokens)); user = accountCreateOutput.User; //continue with the org setup //see what apps the client api wants to register var appIdentifiers = input.LicenseOptions.Keys.ToArray(); //get them... var apps = await dbCtx.Applications.Where(a => appIdentifiers.Contains(a.ShortName)).ToListAsync(); //always make sure to glue in the core apis and apps apps.AddRange( MapHive.Core.Defaults.Applications.GetDefaultOrgApps() ); foreach (var appShortName in input.LicenseOptions.Keys) { var app = apps.FirstOrDefault(a => a.ShortName == appShortName); if (app == null) { continue; } newOrg.LicenseOptions.Add( new OrganizationLicenseOption { LicensedObjectTypeUuid = app.TypeUuid, LicensedObjectUuid = app.Uuid, LicenseOptions = input.LicenseOptions[appShortName] } ); } //create an org with owner and register the specified apps //make sure though to use the collection that contains the the default org apps! await newOrg.CreateAsync(dbCtx, user, apps); //wire up user with his 'parent org' //this is so it is clear a user has his own org user.UserOrgId = newOrg.Uuid; await user.UpdateAsync(dbCtx); return(new AccountCreateOutput { EmailTemplate = input.EmailTemplate, VerificationKey = accountCreateOutput.VerificationKey, InitialPassword = accountCreateOutput.InitialPassword }); }