public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(_configuration) .WriteTo.Console(new JsonFormatter()) .Enrich.FromLogContext() .CreateLogger(); _logger.LogInformation("Starting service"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } RunSSHDeamon(lifetime, loggerFactory.CreateLogger("sshd")); var executor = ShellHelper.Executor.WithWorkingDirectory(_configuration.GetValue <string>("REPO_LOCATION")) .ForwardEnvVariable("GIT_SSH"); var gitValidationFlow = new GitValidationFlow { Validators = { (Patterns.Manifests, new CircularDependencyValidator()), (Patterns.JPad, new CompileJPadValidator()) } }; var minioConfig = _configuration.GetSection("Minio"); var storageClient = Policy.Handle <Exception>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))) .ExecuteAsync(() => MinioBucketStorage.GetOrCreateBucket(CreateMinioClient(minioConfig), minioConfig.GetValue("Bucket", "tweek-ruleset"))) .Result; var natsClient = new NatsPublisher(_configuration.GetSection("Nats").GetValue <string>("Endpoint")); var versionPublisher = natsClient.GetSubjectPublisher("version"); var repoSynchronizer = new RepoSynchronizer(executor.WithUser("git").CreateCommandExecutor("git")); var storageSynchronizer = new StorageSynchronizer(storageClient, executor.WithUser("git"), new Packer()); storageSynchronizer.Sync(repoSynchronizer.CurrentHead().Result, checkForStaleRevision: false).Wait(); RunIntervalPublisher(lifetime, versionPublisher, repoSynchronizer, storageSynchronizer); var syncActor = SyncActor.Create(storageSynchronizer, repoSynchronizer, natsClient, lifetime.ApplicationStopping, loggerFactory.CreateLogger("SyncActor")); app.UseRouter(router => { router.MapGet("validate", ValidationHandler.Create(executor, gitValidationFlow, loggerFactory.CreateLogger <ValidationHandler>())); router.MapGet("sync", SyncHandler.Create(syncActor, _syncPolicy)); router.MapGet("push", PushHandler.Create(syncActor)); router.MapGet("log", async(req, res, routedata) => _logger.LogInformation(req.Query["message"])); router.MapGet("health", async(req, res, routedata) => await res.WriteAsync(JsonConvert.SerializeObject(new { }))); router.MapGet("version", async(req, res, routedata) => await res.WriteAsync(Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion)); }); }
public static int SafeReadInteger(string paramName, string message, ValidationHandler validator) { if (ExternalValues == null && !string.IsNullOrEmpty(message)) { Console.WriteLine(message); } while (true) { string sValue = GetValue(paramName, message); try { int iValue = Int32.Parse(sValue); if (validator != null) { validator(iValue); } return(iValue); } catch (Exception ex) { if ((ex is ValidationException) || (ex is OverflowException) || (ex is FormatException)) { Console.WriteLine("ERROR: " + ex.Message); if (ExternalValues != null) { throw new InvalidOperationException(ex.Message, ex); } } throw ex; } } }
internal MethodWrapper(int targetProcessId, string dllPath, bool randomiseDllName, bool methodIsManualMap) { // Ensure the users operating system is supported ValidationHandler.ValidateOperatingSystem(); // Ensure the arguments passed in are valid if (targetProcessId <= 0 || string.IsNullOrWhiteSpace(dllPath)) { throw new ArgumentException("One or more of the arguments provided were invalid"); } if (randomiseDllName) { // Create a temporary DLL on disk var temporaryDllName = WrapperTools.GenerateRandomDllName(); var temporaryDllPath = WrapperTools.CreateTemporaryDll(temporaryDllName, File.ReadAllBytes(dllPath)); _propertyWrapper = methodIsManualMap ? new PropertyWrapper(targetProcessId, File.ReadAllBytes(temporaryDllPath)) : new PropertyWrapper(targetProcessId, temporaryDllPath); } else { _propertyWrapper = methodIsManualMap ? new PropertyWrapper(targetProcessId, File.ReadAllBytes(dllPath)) : new PropertyWrapper(targetProcessId, dllPath); } // Ensure the architecture of the DLL is valid ValidationHandler.ValidateDllArchitecture(_propertyWrapper); }
internal ExtensionWrapper(int targetProcessId, string dllPath, bool randomiseDllName) { // Ensure the users operating system is supported ValidationHandler.ValidateOperatingSystem(); // Ensure the arguments passed in are valid if (targetProcessId <= 0 || string.IsNullOrWhiteSpace(dllPath)) { throw new ArgumentException("One or more of the arguments provided were invalid"); } if (randomiseDllName) { // Assume the DLL is the newest file in the temporary directory var temporaryDirectoryInfo = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "Bleak")); var newestTemporaryFile = temporaryDirectoryInfo.GetFiles().OrderByDescending(file => file.LastWriteTime).First(); _propertyWrapper = new PropertyWrapper(targetProcessId, newestTemporaryFile.FullName); } else { _propertyWrapper = new PropertyWrapper(targetProcessId, dllPath); } ValidationHandler.ValidateDllArchitecture(_propertyWrapper); }
public void Should_throw_a_validation_exception_if_validator_is_found_and_Request_is_invalid( IRequestHandler <Request, Response> validationHandler, Request invalidRequest, Container Container, Exception exception ) { "Given an invalid Request" .Given(() => invalidRequest = new Request() { Name = null }); "And a Container" .And(() => Container = new Container()); "And an IValidator for the Request registered" .And(() => Container.Register <IValidator <Request>, RequestValidator>()); "And a ValidationHandler constructed with the Container" .And(() => validationHandler = new ValidationHandler <Request, Response>(Container, new RequestHandler())); "When handling the invalid Request" .When(() => exception = Record.Exception(() => validationHandler.Handle(invalidRequest))); "A ValidationException should be thrown" .Then(() => exception.Should().BeOfType <ValidationException>()); "And the error property should be 'Name'" .Then(() => exception.As <ValidationException>().Errors.Single().PropertyName.Should().Be("Name")); "And the error message should be 'Name cannot be null'" .Then(() => exception.As <ValidationException>().Errors.Single().ErrorMessage.Should().Be("Name cannot be null")); }
public IList <IError> ValidateXML(string xmlData, xsdDocument xsdDocumentType) { IList <IError> errorList = new List <IError>(); string errorHolder = string.Empty; ValidationHandler handler = new ValidationHandler(); try { XmlReaderSettings settings = GetXSD(xsdDocumentType); XmlReader xmlReader = XmlReader.Create(new StringReader(xmlData), settings); settings.ValidationEventHandler += new ValidationEventHandler(handler.HandleValidationError); using (XmlReader validatingReader = XmlReader.Create(new StringReader(xmlData), settings)) { while (validatingReader.Read()) { } } errorList = handler.ValidationErrors; } catch (Exception ex) { errorList.Add(new ValidationError() { errorMessage = ex.Message }); } return(errorList); }
public void Should_not_throw_a_validation_exception_if_validator_is_found_but_Request_is_valid( IRequestHandler <Request, Response> validationHandler, Request validRequest, Container Container, Exception exception ) { "Given a valid Request" .Given(() => validRequest = new Request() { Name = "A valid name" }); "And a Container" .And(() => Container = new Container()); "With an IValidator for the Request registered" .And(() => Container.Register <IValidator <Request>, RequestValidator>()); "And a ValidationHandler constructed with the Container" .And(() => validationHandler = new ValidationHandler <Request, Response>(Container, new RequestHandler())); "When handling the valid Request" .When(() => exception = Record.Exception(() => validationHandler.Handle(validRequest))); "A ValidationException should not be thrown" .When(() => exception.Should().BeNull()); }
public Injector(InjectionMethod injectionMethod, string processName, string dllPath, bool randomiseDllName = false) { // Ensure the users operating system is valid ValidationHandler.ValidateOperatingSystem(); // Ensure the arguments passed in are valid if (string.IsNullOrWhiteSpace(processName) || string.IsNullOrWhiteSpace(dllPath)) { throw new ArgumentException("One or more of the arguments provided were invalid"); } // Ensure a valid DLL exists at the provided path if (!File.Exists(dllPath) || Path.GetExtension(dllPath) != ".dll") { throw new ArgumentException("No DLL exists at the provided path"); } if (randomiseDllName) { // Create a temporary DLL on disk var temporaryDllPath = DllTools.CreateTemporaryDll(DllTools.GenerateRandomDllName(), File.ReadAllBytes(dllPath)); _injectionManager = new InjectionManager(injectionMethod, processName, temporaryDllPath); } else { _injectionManager = new InjectionManager(injectionMethod, processName, dllPath); } }
public void Handler_Shall_Pass_Validattion_to_next() { var validations = new Dictionary <ValidationTypes, IValidation>() { { ValidationTypes.Security, new SecurityValidation( ValidationResult.Valid, new DateTime(2019, 10, 1)) }, { ValidationTypes.Comfort, new ComfortValidation( ValidationResult.Valid, new DateTime(2019, 10, 1)) } }; IValidationRequest request = new ValidationRequest(validations); IHandler comfortHandler = new ValidationHandler <IValidationRequest, ComfortValidation>( request, new ComfortValidation(ValidationResult.OnReview, new DateTime(2019, 10, 1)), null); IHandler securityHandler = new ValidationHandler <IValidationRequest, SecurityValidation>( request, new SecurityValidation(ValidationResult.Valid, new DateTime(2019, 10, 1)), comfortHandler); securityHandler.Handle(); }
protected virtual async Task ReplaceEmailToUsernameOfInputIfNeeds(UserLoginInfo login) { if (!ValidationHandler.IsValidEmailAddress(login.UserNameOrEmailAddress)) { return; } var userByUsername = await _userManager.FindByNameAsync(login.UserNameOrEmailAddress); if (userByUsername != null) { return; } var userByEmail = await _userManager.FindByEmailAsync(login.UserNameOrEmailAddress); if (userByEmail == null) { return; } if (userByEmail.EmailConfirmed == false) { throw new UserFriendlyException("邮件未激活确认,无法使用邮件进行登录!"); } login.UserNameOrEmailAddress = userByEmail.UserName; }
public void Ensure_Context_Is_Validated() { var context = Tuple.Create("Name here", "Value here"); var contextDictionary = new Dictionary <object, object>(); contextDictionary.Add(context.Item1, context.Item2); var testContext = new TestContext(); testContext.KeyName = context.Item1; testContext.RunTimeType = typeof(string); testContext.Value = "Different Value"; var result = ValidationHandler.Validate(testContext, contextDictionary); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); testContext.RunTimeType = typeof(object); testContext.Value = context.Item2; //set back to original result = ValidationHandler.Validate(testContext, contextDictionary); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); contextDictionary.Remove(context.Item1); result = ValidationHandler.Validate(testContext, contextDictionary); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); }
internal MethodWrapper(string targetProcessName, byte[] dllBytes, bool randomiseDllName, bool methodIsManualMap) { // Ensure the users operating system is supported ValidationHandler.ValidateOperatingSystem(); // Ensure the arguments passed in are valid if (string.IsNullOrWhiteSpace(targetProcessName) || dllBytes is null || dllBytes.Length == 0) { throw new ArgumentException("One or more of the arguments provided were invalid"); } if (methodIsManualMap) { _propertyWrapper = new PropertyWrapper(targetProcessName, dllBytes); } else { // Create a temporary DLL on disk var temporaryDllName = randomiseDllName ? WrapperTools.GenerateRandomDllName() : WrapperTools.GenerateDllName(dllBytes); var temporaryDllPath = WrapperTools.CreateTemporaryDll(temporaryDllName, dllBytes); _propertyWrapper = new PropertyWrapper(targetProcessName, temporaryDllPath); } // Ensure the architecture of the DLL is valid ValidationHandler.ValidateDllArchitecture(_propertyWrapper); }
/// <summary> /// Initialize a new instance of the <see cref="App"/> class. /// </summary> /// <param name="appResourcesService">A service with access to local resources.</param> /// <param name="logger">A logger from the built in LoggingFactory.</param> /// <param name="dataService">A service with access to data storage.</param> /// <param name="processService">A service with access to the process.</param> /// <param name="pdfService">A service with access to the PDF generator.</param> /// <param name="profileService">A service with access to profile information.</param> /// <param name="registerService">A service with access to register information.</param> /// <param name="prefillService">A service with access to prefill mechanisms.</param> /// <param name="instanceService">A service with access to instances</param> /// <param name="settings">General settings</param> /// <param name="textService">A service with access to text</param> /// <param name="httpContextAccessor">A context accessor</param> public App( IAppResources appResourcesService, ILogger <App> logger, IData dataService, IProcess processService, IPDF pdfService, IProfile profileService, IRegister registerService, IPrefill prefillService, IInstance instanceService, IOptions <GeneralSettings> settings, IText textService, IHttpContextAccessor httpContextAccessor) : base( appResourcesService, logger, dataService, processService, pdfService, prefillService, instanceService, registerService, settings, profileService, textService, httpContextAccessor) { _logger = logger; _validationHandler = new ValidationHandler(httpContextAccessor); _dataProcessingHandler = new DataProcessingHandler(); _instantiationHandler = new InstantiationHandler(profileService, registerService); _pdfHandler = new PdfHandler(); }
public void Should_not_throw_a_validation_exception_if_validator_is_not_found_but_Request_in_invalid( IRequestHandler <Request, Response> validationHandler, Request invalidRequest, Container Container, Exception exception ) { "Given an invalid Request" .Given(() => invalidRequest = new Request() { Name = null }); "And a Container" .And(() => Container = new Container()); "With no validators registered" .And(() => { }); "And a ValidationHandler constructed with the Container" .And(() => validationHandler = new ValidationHandler <Request, Response>(Container, new RequestHandler())); "When handling the invalid Request" .When(() => exception = Record.Exception(() => validationHandler.Handle(invalidRequest))); "A ValidationException should not be thrown" .Then(() => exception.Should().BeNull()); }
private static Task HandleExceptionAsync(HttpContext context, Exception exception) { (int code, string error) = ValidationHandler.Handle(exception); context.Response.ContentType = "application/json"; context.Response.StatusCode = code; return(context.Response.WriteAsync(error)); }
/// <summary> /// Initialises an instance capable of managing memory in a specified remote process /// </summary> public MemoryModule(string processName) { ValidationHandler.ValidateOperatingSystem(); _memoryManager = new MemoryManager(processName); _patternScanner = new PatternScanner(_memoryManager); }
public StrategyValidator(ValidationOptions options) { if (options is null) { throw new ArgumentNullException(nameof(options)); } Handler = ValidationHandler.CreateByStrategy <TStrategy>(options); }
internal InjectionContext(InjectionMethod injectionMethod, int processId, byte[] dllBytes) { _injectionWrapper = new InjectionWrapper(injectionMethod, processId, dllBytes); // Ensure the architecture of the DLL is valid ValidationHandler.ValidateDllArchitecture(_injectionWrapper); }
internal InjectionContext(InjectionMethod injectionMethod, string processName, string dllPath) { _injectionWrapper = new InjectionWrapper(injectionMethod, processName, dllPath); // Ensure the architecture of the DLL is valid ValidationHandler.ValidateDllArchitecture(_injectionWrapper); }
public void Should_Compose_Validation() { var handler = new ValidationHandler() + new DataAnnotationsValidator(); var team = new Team { Division = "10", Coach = new Coach(), Players = new [] { new Player(), new Player { FirstName = "Cristiano", LastName = "Ronaldo", DOB = new DateTime(1985, 2, 5) }, new Player { FirstName = "Lionel" } } }; var outcome = P <IValidator>(handler).Validate(team); Assert.IsFalse(outcome.IsValid); Assert.AreSame(outcome, team.ValidationOutcome); CollectionAssert.AreEquivalent( new[] { "Name", "Division", "Coach", "Players" }, outcome.Culprits); Assert.AreEqual("The Name field is required.", outcome["Name"]); Assert.AreEqual("The Division must match U followed by age.", outcome["Division"]); var coach = outcome.GetOutcome("Coach"); Assert.IsFalse(coach.IsValid); Assert.AreSame(coach, team.Coach.ValidationOutcome); Assert.AreEqual("The FirstName field is required.", coach["FirstName"]); Assert.AreEqual("The LastName field is required.", coach["LastName"]); Assert.AreEqual("The License field is required.", coach["License"]); var players = outcome.GetOutcome("Players"); Assert.IsFalse(players.IsValid); CollectionAssert.AreEquivalent(new [] { "0", "2" }, players.Culprits); var player1 = players.GetOutcome("0"); Assert.AreSame(player1, team.Players[0].ValidationOutcome); Assert.AreEqual("The FirstName field is required.", player1["FirstName"]); Assert.AreEqual("The LastName field is required.", player1["LastName"]); Assert.AreEqual("The DOB field is required.", player1["DOB"]); Assert.IsNull(players.GetOutcome("1")); var player3 = players.GetOutcome("2"); Assert.AreSame(player3, team.Players[2].ValidationOutcome); Assert.AreEqual("", player3["FirstName"]); Assert.AreEqual("The LastName field is required.", player3["LastName"]); Assert.AreEqual("The DOB field is required.", player3["DOB"]); }
public async Task Should_Reject_Method_If_Invalid_Async() { var handler = new ValidationHandler() + new ManageTeamHandler() + new ValidateTeam(); var team = new Team(); var player = new Player(); await handler.ValidAsync(team).P <IManageTeam>().AddPlayer(player, team); }
public VerifyRulePackageValidator(VerifyRulePackage package) { if (package is null) { throw new ArgumentNullException(nameof(package)); } Handler = ValidationHandler.CreateByRulePackage(package); Name = "Shortcut Validator for 'VerifyRulePackage'"; }
public ValidationHandlerTests() { _handler = Mock.Of <IRequestHandler <Request, Unit> >(); _validatorFirst = Mock.Of <IValidator <Request> >(); _validatorSecond = Mock.Of <IValidator <Request> >(); _settings = Mock.Of <ValidationHandlerSettings>(); _sut = new ValidationHandler <Request, Unit>(new[] { _validatorFirst, _validatorSecond }, _settings, _handler); }
public StrategyValidator(IValidationStrategy strategy) { if (strategy is null) { throw new ArgumentNullException(nameof(strategy)); } Handler = ValidationHandler.CreateByStrategy(strategy); Name = $"Strategy Validator for '{strategy.GetType().GetFriendlyName()}'"; }
public void Ensure_Context_Handles_Nulls() { var testContext = new TestContext(); testContext.KeyName = "Name here"; testContext.RunTimeType = typeof(string); testContext.Value = "Value here"; var result = ValidationHandler.Validate(testContext, null); }
public QuerySourceBuilder <TDbContext, TDataItem> AddValidator( ValidationHandler <TDataItem> validator) { if (_validators == null) { _validators = new(); } _validators.Add(validator); return(this); }
public void Should_Reject_Operation_If_Invalid() { var handler = new ValidationHandler() + new DataAnnotationsValidator() + new RegistrationHandler(); var team = new Team(); P <IRegistration>(handler.Valid(team)).RegisterTeam(team); }
public void DataAttribute_Valid() { var obj = new UnitTestModel() { Name = "F#" }; var result = ValidationHandler.Validate(obj); Assert.IsNull(result); }
public void ValidationLoader_AttributeTest_Invalid() { var obj = new DomainObject17(); obj.ID = -5; var result = ValidationHandler.Validate(obj); Assert.IsNotNull(result); Assert.IsNotNull(result.FirstOrDefault(x => x.MemberNames.Any(y => y == "ID"))); }
public void Validate_BasicObject_Valid() { var obj = new BasicValidationObject() { StringProperty = "Some String", EmailProperty = "*****@*****.**", IntegerProperty = 3 }; var result = ValidationHandler.Validate(obj); Assert.IsTrue(result == null); }
public readonly ValidationHandler ValidationHandler; // Custom validation handler #endregion Fields #region Constructors public ColumnConfig(string Name, int Order, bool AllowEmpty, bool IsList, string ListSeparator, string Regex, ValidationHandler ValidationHandler, ReturnOrCreateHandler ReturnOrCreateHandler) { this.Name = Name; this.Order = Order; this.AllowEmpty = AllowEmpty; this.IsList = IsList; this.ListSeparator = ListSeparator; this.Regex = Regex; this.ValidationHandler = ValidationHandler; this.ReturnOrCreateHandler = ReturnOrCreateHandler; }
public FormField(MHTextEditWidget textEditWidget, TextWidget errorMessageWidget, ValidationHandler[] validationHandlers) { this.FieldEditWidget = textEditWidget; this.FieldErrorMessageWidget = errorMessageWidget; this.FieldValidationHandlers = validationHandlers; }
public ValidationHandlerNode(ValidationHandler handler) { _handler = handler; }