internal static void Seed(BillsPaymentSystemContext context, int count) { for (int i = 0; i < count; i++) { var firstName = TextGenerator.FirstName(); var user = new User() { FirstName = firstName, LastName = TextGenerator.LastName(), Email = EmailGenerator.NewEmail(firstName), Password = TextGenerator.Password(12) }; var result = new List <ValidationResult>(); if (AttributeValidator.IsValid(user, result)) { context.Users.Add(user); } else { Console.WriteLine(string.Join(Environment.NewLine, result)); } } context.SaveChanges(); }
internal static void Seed(BillsPaymentSystemContext context, int count, List <User> users) { for (int i = 0; i < count; i++) { var payment = new PaymentMethod() { User = users[IntGenerator.GenerateInt(0, users.Count - 1)], Type = PaymentType.BankAccount, BankAccount = new BankAccount() { BankAccountId = i, //Balance = PriceGenerator.GeneratePrice(), BankName = TextGenerator.FirstName() + "\'s Bank", SwiftCode = TextGenerator.Password(10) }, BankAccountId = i }; payment.BankAccount.Deposit(PriceGenerator.GeneratePrice()); var result = new List <ValidationResult>(); if (AttributeValidator.IsValid(payment, result)) { context.PaymentMethods.Add(payment); } else { Console.WriteLine(string.Join(Environment.NewLine, result)); } payment = new PaymentMethod() { User = users[IntGenerator.GenerateInt(0, users.Count - 1)], Type = PaymentType.CreditCard, CreditCard = new CreditCard() { CreditCardId = i, ExpirationDate = DateGenerator.FutureDate(), Limit = PriceGenerator.GeneratePrice(), //MoneyOwed = PriceGenerator.GeneratePrice() }, CreditCardId = i }; payment.CreditCard.Withdraw(PriceGenerator.GeneratePrice()); result = new List <ValidationResult>(); if (AttributeValidator.IsValid(payment, result)) { context.PaymentMethods.Add(payment); } else { Console.WriteLine(string.Join(Environment.NewLine, result)); } } context.SaveChanges(); }
public static string ImportOrders(FastFoodDbContext context, string xmlString) { var serializer = new XmlSerializer(typeof(dto_order_Xml[]), new XmlRootAttribute("Orders")); var dtos = (dto_order_Xml[])serializer.Deserialize(new StringReader(xmlString)); StringBuilder sb = new StringBuilder(); List <Order> ordersToBeAdded = new List <Order>(); Item[] menuItems = context.Items.ToArray(); foreach (var dto in dtos) { var newOrder = new Order(); try { newOrder.DateTime = DateTime.ParseExact(dto.DateTime, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); newOrder.Customer = dto.CustomerName; newOrder.Employee = context.Employees.FirstOrDefault(x => x.Name == dto.EmployeeName); newOrder.Type = Enum.Parse <OrderType>(dto.Type); foreach (var itemDto in dto.Items) { var item = menuItems.FirstOrDefault(x => x.Name == itemDto.Name); if (item is null) { throw new ArgumentException("Item not found!"); } newOrder.OrderItems.Add(new OrderItem() { Quantity = int.Parse(itemDto.QuantityINT), Item = item }); } if (newOrder.Employee is null || !AttributeValidator.IsValid(newOrder) || !newOrder.OrderItems.All(x => AttributeValidator.IsValid(x))) { throw new ArgumentException("Invalid DataMember!"); } ordersToBeAdded.Add(newOrder); sb.AppendLine(string.Format("Order for {0} on {1} added", dto.CustomerName, dto.DateTime)); } catch (Exception) { sb.AppendLine(FailureMessage); } } context.Orders.AddRange(ordersToBeAdded); context.SaveChanges(); return(sb.ToString().Trim()); }
public void Validate() { Errors = new List <string>(); var attrValErrors = AttributeValidator.Validate(Request); if (attrValErrors.Length > 0) { Errors.AddRange(attrValErrors); return; } Errors.AddRange(Request.ValidateConditionalAttributes()); }
public string[] Validate() { var errors = new List <string>(); if (Mode == TransportModeType.Truck || Mode == TransportModeType.PublicTransport || Mode == TransportModeType.PublicTransportTimeTable) { if (Type == RoutingType.Shortest) { errors.Add("When calculating Public Transport and Truck routes, always use fastest mode"); } } errors.AddRange(AttributeValidator.Validate(this)); return(errors.ToArray()); }
public void ItOnlyInvokesAttributeIfValueExists() { var app = new CommandLineApplication(); var arg = app.Argument("arg", "arg"); var validator = new AttributeValidator(new ThrowingValidationAttribute()); var factory = new CommandLineValidationContextFactory(app); var context = factory.Create(arg); Assert.Equal(ValidationResult.Success, validator.GetValidationResult(arg, context)); arg.Values.Add(null); Assert.Throws <InvalidOperationException>(() => validator.GetValidationResult(arg, context)); }
public async Task <ServiceResult> ServerLog(ServerEvent serverEvent) { var errors = AttributeValidator.Validation(serverEvent); if (errors.Count > 0) { return(new ServiceResult(false, errors)); } await _events.AddAsync(serverEvent); await _dbContext.SaveChangesAsync(); return(new ServiceResult(true)); }
public static string ImportItems(FastFoodDbContext context, string jsonString) { return(""); dto_item_Json[] resultsDTOs = JsonConvert.DeserializeObject <dto_item_Json[]>(jsonString); StringBuilder sb = new StringBuilder(); List <Item> itemsToBeAdded = new List <Item>(); foreach (var dto in resultsDTOs) { var newItem = new Item(); try { newItem.Name = dto.Name; newItem.Price = decimal.Parse(dto.Price); newItem.Category = context.Categories.FirstOrDefault(x => x.Name == dto.Category) ?? itemsToBeAdded.Select(x => x.Category).FirstOrDefault(x => x.Name == dto.Category); if (newItem.Category is null) { newItem.Category = new Category() { Name = dto.Category }; } bool ItemNameFree = context.Items.All(x => x.Name != dto.Name) && itemsToBeAdded.All(x => x.Name != dto.Name); if (!ItemNameFree || !AttributeValidator.IsValid(newItem, newItem.Category)) { throw new ArgumentException("Invalid DataMember!"); } itemsToBeAdded.Add(newItem); sb.AppendLine(string.Format(SuccessMessage, newItem.Name)); } catch (Exception) { sb.AppendLine(FailureMessage); } } context.Items.AddRange(itemsToBeAdded); context.SaveChanges(); return(sb.ToString().Trim()); }
private LuceneAttributes WriteLuceneDefaults(LuceneAttributes existing) { if (serverConfig.CacheSettings.LuceneSettings != null) { AttributeValidator.ValidateDefaultAnalyzer(Analyzer, GetDeployements(serverConfig.CacheSettings.LuceneSettings.Analyzers)); AttributeValidator.ValidateDefaultStopWords(StopWords, GetDeployements(serverConfig.CacheSettings.LuceneSettings.StopWordFiles)); AttributeValidator.ValidateDefaultPattern(Pattern, GetDeployements(serverConfig.CacheSettings.LuceneSettings.Patterns)); } AttributeValidator.ValidateDefaultTermVector(TermVector); AttributeValidator.ValidateDefaultLuceneType(LuceneType); existing.MergeFactor = MergeFactor; existing.LuceneType = LuceneType; existing.LuceneAnalyzer = Analyzer; existing.TermVector = TermVector; existing.Pattern = Pattern; existing.StopWords = StopWords; return(existing); }
public void ItExecutesValidationAttribute(Type attributeType, string validValue, string invalidValue) { var attr = (ValidationAttribute)Activator.CreateInstance(attributeType); var app = new CommandLineApplication(); var arg = app.Argument("arg", "arg"); var validator = new AttributeValidator(attr); var factory = new CommandLineValidationContextFactory(app); var context = factory.Create(arg); arg.Values.Add(validValue); Assert.Equal(ValidationResult.Success, validator.GetValidationResult(arg, context)); arg.Values.Clear(); arg.Values.Add(invalidValue); var result = validator.GetValidationResult(arg, context); Assert.NotNull(result); Assert.NotEmpty(result.ErrorMessage); }
private void CheckPassword() { //if a new user if (User.Id <= 0) { AttributeValidator.GetOnlyErrors(this).ToList().ForEach(x => Errors.Add(x)); OnPropertyChanged(nameof(Errors)); } else { if (((Password != null && Password.Length > 0) || ConfirmedPassword != null && ConfirmedPassword.Length > 0)) { AttributeValidator.GetOnlyErrors(this).ToList().ForEach(x => Errors.Add(x)); OnPropertyChanged(nameof(Errors)); } } }
private async Task OnSave(object obj) { if (User is null) { throw new NullReferenceException("User is null"); } Errors = User.Validate().ToList(); if (((Password != null && Password.Length > 0) || ConfirmedPassword != null && ConfirmedPassword.Length > 0)) { AttributeValidator.GetOnlyErrors(this).ToList().ForEach(x => Errors.Add(x)); User.Password = Password.GetStringValue(); OnPropertyChanged(nameof(Errors)); } if (Errors.Any()) { return; } var response = await _userManager.Update(User); if (!response.IsSuccess) { if (response.Message.Equals("Wrong current password", StringComparison.OrdinalIgnoreCase)) { Errors.Add(l10n.UserView.Errors.WrongCurrentPassword); } else { Errors.Add(l10n.Shared.Errors.InternalAppError); } OnPropertyChanged(nameof(Errors)); } }
public static string ImportEmployees(FastFoodDbContext context, string jsonString) { dto_employee_Json[] resultsDTOs = JsonConvert.DeserializeObject <dto_employee_Json[]>(jsonString); StringBuilder sb = new StringBuilder(); List <Employee> empsToBeAdded = new List <Employee>(); foreach (var dto in resultsDTOs) { Employee newEmp = new Employee(); try { newEmp.Age = int.Parse(dto.Age); newEmp.Name = dto.Name; newEmp.Position = context.Positions.FirstOrDefault(x => x.Name == dto.Position) ?? empsToBeAdded.Select(x => x.Position).FirstOrDefault(x => x.Name == dto.Position); if (newEmp.Position is null) { newEmp.Position = new Position() { Name = dto.Position }; } if (!AttributeValidator.IsValid(newEmp, newEmp.Position)) { throw new ArgumentException("Invalid DataMember!"); } empsToBeAdded.Add(newEmp); sb.AppendLine(string.Format(SuccessMessage, newEmp.Name)); } catch (Exception) { sb.AppendLine(FailureMessage); } } context.Employees.AddRange(empsToBeAdded); context.SaveChanges(); return(sb.ToString().Trim()); }
public virtual async Task <ServiceResult> UpdateAsync(TEntity entity) { var errors = AttributeValidator.Validation(entity); if (errors != null) { return(new ServiceResult(false, errors)); } try { EntityDbSet.Update(entity); await DbContext.SaveChangesAsync(); } catch (Exception ex) { return(new ServiceResult(false, "Database Error")); } return(new ServiceResult(true)); }
public void ItExecutesClassLevelValidationAttribute(Type attributeType, string validProp1Value, string validProp2Value, string invalidProp1Value, string invalidProp2Value) { var attr = (ValidationAttribute)Activator.CreateInstance(attributeType); var app = new CommandLineApplication <ClassLevelValidationApp>(); var validator = new AttributeValidator(attr); var factory = new CommandLineValidationContextFactory(app); var context = factory.Create(app); app.Model.Arg1 = validProp1Value; app.Model.Arg2 = validProp2Value; Assert.Equal(ValidationResult.Success, validator.GetValidationResult(app, context)); app.Model.Arg1 = invalidProp1Value; app.Model.Arg2 = invalidProp2Value; var result = validator.GetValidationResult(app, context); Assert.NotNull(result); Assert.NotEmpty(result.ErrorMessage); }
public IEnumerable <string> Validate() { return(AttributeValidator.GetOnlyErrors(this)); }
public string[] Validate() { return(AttributeValidator.Validate(this)); }
public static void Attribute(IElementWrapper wrapper, string attributeName, Expression <Func <string, bool> > expression, string failureMessage = null) { var attribute = new AttributeValidator(attributeName, expression, failureMessage); EvaluateValidator <UnexpectedElementStateException, IElementWrapper>(wrapper, attribute); }
private LuceneAttrib GetLuceneAttrib(string attribName, TypeDef classType) { PropertyDef pi = null; FieldDef fi = null; LuceneAttrib tempAttrib = new LuceneAttrib(); string dt = null; pi = classType.GetProperty(attribName); if (pi != null) { dt = pi.PropertyType.FullName; } if (pi == null) { fi = classType.GetField(attribName); if (fi != null) { dt = fi.FieldType.FullName; } } if (pi != null || fi != null) { AttributeValidator validator = new AttributeValidator(defaults); tempAttrib.Name = attribName; tempAttrib.ID = attribName; tempAttrib.Type = dt; tempAttrib.LuceneType = LuceneType; tempAttrib.LuceneAnalyzer = Analyzer; tempAttrib.TermVector = TermVector; tempAttrib.Pattern = Pattern; tempAttrib.StopWords = StopWords; if (!validator.ValidateTermVector(tempAttrib.TermVector)) { throw new Exception("Invalid Term Vector specified"); } System.Type currentType = System.Type.GetType(dt); if (!ValidateDataType(currentType)) { //TODO: [Mehreen] :Insert Khubsurti here so it can collectively throw one exception //_nonPrimitiveAttSpecified = true; //_unsupportedtypes += currentType.FullName + "\n"; throw new Exception("NCache only supports premitive types. Type " + currentType.FullName + " is not supported"); } else if (currentType == null) { //_nonPrimitiveAttSpecified = true; //_unsupportedtypes += "Unknown Type\n"; throw new Exception("NCache only supports premitive types. Type Unknown Type\n"); } else if (!validator.ValidateLuceneType(tempAttrib.LuceneType, currentType)) { throw new Exception("Can not create Lucene Index of type " + tempAttrib.LuceneType + " on data type " + currentType.FullName); } else if (tempAttrib.LuceneType == LuceneUtil.SPATIAL) { tempAttrib.SpaStrategy = SpatialStrategy != null ? SpatialStrategy : LuceneUtil.SpatialStrategy.BBOX; tempAttrib.SpaPrefixTree = SpatialPrefixTree != null ? SpatialPrefixTree : LuceneUtil.SpatialPrefixTre.GEOHASH; if (!AttributeValidator.ValidateSpatialStrategy(tempAttrib.SpaStrategy, tempAttrib.Name, tempAttrib.SpaPrefixTree, SpatialContext.GEO)) { throw new Exception("Spatial Startegy or Prefix Tree are not valid"); } } else if (tempAttrib.LuceneType == LuceneUtil.STRING) { if (serverConfig.CacheSettings.LuceneSettings != null) { if (!validator.ValidateAnalyzer(tempAttrib.LuceneAnalyzer, GetDeployements(serverConfig.CacheSettings.LuceneSettings.Analyzers))) { throw new Exception("Analyzer " + tempAttrib.LuceneAnalyzer + " is not deployed"); } if (!validator.ValidatePattern(tempAttrib.Pattern, GetDeployements(serverConfig.CacheSettings.LuceneSettings.Patterns))) { throw new Exception("Pattern " + tempAttrib.Pattern + " is not deployed"); } if (!validator.ValidateStopWords(tempAttrib.StopWords, GetDeployements(serverConfig.CacheSettings.LuceneSettings.StopWordFiles))) { throw new Exception("Pattern " + tempAttrib.StopWords + " is not deployed"); } } else { if (!validator.ValidateAnalyzer(tempAttrib.LuceneAnalyzer, null)) { throw new Exception("Analyzer " + tempAttrib.LuceneAnalyzer + " is not deployed"); } if (!validator.ValidatePattern(tempAttrib.Pattern, null)) { throw new Exception("Pattern " + tempAttrib.Pattern + " is not deployed"); } if (!validator.ValidateStopWords(tempAttrib.StopWords, null)) { throw new Exception("Pattern " + tempAttrib.StopWords + " is not deployed"); } } } } else { string message = "Invalid class attribute(s) specified '" + attribName + "'."; throw new Exception(message); } return(tempAttrib); }
public static void Attribute(this IOperationRunner <IElementWrapper> operationRunner, string attributeName, Expression <Func <string, bool> > expression, string failureMessage = null) { var Attribute = new AttributeValidator(attributeName, expression, failureMessage); operationRunner.Evaluate <UnexpectedElementStateException>(Attribute); }
public ForeignKeyAttribute(Type referenceTable) { var primaryKeyOfReferenceTable = AttributeValidator.PrimaryKeyAttributeValidate(referenceTable); ReferenceKeyProperty = primaryKeyOfReferenceTable; }