public async Task <ActionResult> Validate([FromBody] JwtToken jwtToken) { try { if (jwtToken?.Token == null) { throw new ArgumentNullException("No jwtToken provided"); } var validateCommand = new ValidateCommand(jwtToken.Token, NameConstants.AuthenticationServiceValidateCommand); bool isValid = await _commandPublisher.Publish <bool>(validateCommand); if (!isValid) { throw new UnauthorizedAccessException("Validation of JwtToken has failed!"); } } catch (TimeoutException) { _logger.LogError("ValidateCommand resulted in a TimeoutException."); return(StatusCode((int)HttpStatusCode.RequestTimeout, "Aanvraag kan niet worden verwerkt")); } catch (Exception) { return(Unauthorized()); } return(Ok()); }
public void Add(ToolStripItem[] toolStripItems, MenuItem[] menuItems, EventHandler clickDelegate, ValidateCommand validateDelegate) { _commands.Add(new Command(toolStripItems, menuItems, clickDelegate, validateDelegate)); }
public Command(ToolStripItem[] toolStripItems, MenuItem[] menuItems, Control[] controls, EventHandler clickDelegate, ValidateCommand validateDelegate) { _toolStripItems = toolStripItems; _menuItems = menuItems; _controls = controls; _validateCommandDelegate = validateDelegate; _clickCommandDelegate = clickDelegate; if (toolStripItems != null) { foreach (ToolStripItem item in toolStripItems) { item.Click += _clickCommandDelegate; } } if (controls != null) { foreach (Control control in controls) { control.Click += _clickCommandDelegate; } } if (menuItems != null) { foreach (MenuItem item in menuItems) { item.Click += _clickCommandDelegate; } } }
public Command(ToolStripItem[] toolStripItems, MenuItem[] menuItems, EventHandler clickDelegate, ValidateCommand validateDelegate) : this(toolStripItems, menuItems, null, clickDelegate, validateDelegate) { }
/// <summary> /// Validates the current changes in the TextBox. /// </summary> public void Validate() { var cancelRoutedEventArgs = new CancelRoutedEventArgs(ValidatingEvent); OnValidating(cancelRoutedEventArgs); if (cancelRoutedEventArgs.Cancel) return; RaiseEvent(cancelRoutedEventArgs); if (cancelRoutedEventArgs.Cancel) return; validating = true; var coercedText = CoerceTextForValidation(Text); SetCurrentValue(TextProperty, coercedText); BindingExpression expression = GetBindingExpression(TextProperty); if (expression != null) expression.UpdateSource(); ClearUndoStack(); var validatedArgs = new ValidationRoutedEventArgs<string>(ValidatedEvent, coercedText); OnValidated(); RaiseEvent(validatedArgs); if (ValidateCommand != null && ValidateCommand.CanExecute(ValidateCommandParameter)) ValidateCommand.Execute(ValidateCommandParameter); validating = false; }
public void TestProcessCommand_OnBootstrapperError() { // Preconditions Debug.Assert(managerMock != null); Debug.Assert(outputMock != null); Debug.Assert(bootstrapperMock != null); /* GIVEN */ bootstrapperMock .Setup(bootstrapper => bootstrapper.ComposeImports(It.IsAny <object>()))? .Throws(new InvalidOperationException()); var command = new ValidateCommand(managerMock.Object, outputMock.Object, bootstrapperMock.Object); var options = new ValidateOptions { IsVerbose = false, ConfigPath = Assembly.GetExecutingAssembly().Location }; /* WHEN */ var returnCode = command.Execute(options); /* THEN */ // We test if the command failed and returned code -1. Assert.AreEqual(failCode, returnCode); bootstrapperMock.Verify(bootstrapper => bootstrapper.ComposeImports(managerMock.Object), Times.Once); managerMock.Verify(manager => manager.LoadConfiguration(It.IsAny <FilePath>()), Times.Never); outputMock.Verify(output => output.PrintError(It.IsAny <InvalidOperationException>()), Times.Once); }
public async Task GivenAStorageAccountWithNoInitVerifyPushSucceeds() { using (var packagesFolder = new TestFolder()) using (var testContext = new AzureTestContext()) { await testContext.InitAsync(); var testPackage = new TestNupkg("packageA", "1.0.0"); var zipFile = testPackage.Save(packagesFolder.Root); // Skip init var result = await PushCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, new List <string>() { zipFile.FullName }, force : false, skipExisting : false, log : testContext.Logger); result &= await ValidateCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, testContext.Logger); result.Should().BeTrue(); await testContext.CleanupAsync(); } }
public async Task <int> Handle(ValidateCommand cmd) { this.Initialize(cmd); try { using var httpClient = new HttpClient(); var gatewayAutomation = new GatewayAutomation(httpClient, this.logicTokenProviderFactory, this.gatewayOptions); var validationResult = await gatewayAutomation.ValidateAsync(cmd.FolderPath).ConfigureAwait(false); if (validationResult.IsError) { foreach (var error in validationResult.Errors) { Console.WriteLine(error.ToString()); } } else { Console.WriteLine(validationResult.ValidatePublishingResult.ToString()); } return(!validationResult.IsError ? 0 : 1); } catch (RestException re) { Console.WriteLine(re.Message); return(1); } }
private void Validate() { var cancelRoutedEventArgs = new CancelRoutedEventArgs(ValidatingEvent); AssociatedObject.RaiseEvent(cancelRoutedEventArgs); if (cancelRoutedEventArgs.Cancel) { return; } BindingExpression expression = AssociatedObject.GetBindingExpression(TextBox.TextProperty); if (expression != null) { expression.UpdateSource(); } ClearUndoStack(); AssociatedObject.RaiseEvent(new RoutedEventArgs(ValidatedEvent)); if (ValidateCommand != null && ValidateCommand.CanExecute(ValidateCommandParameter)) { ValidateCommand.Execute(ValidateCommandParameter); } }
public CommandFactory(IPersister persister, ISecurityManager security, IVersionManager versionMaker, IEditUrlManager editUrlManager, IContentAdapterProvider adapters, StateChanger changer) { this.persister = persister; makeVersionOfMaster = On.Master(new MakeVersionCommand(versionMaker)); replaceMaster = new ReplaceMasterCommand(versionMaker); makeVersion = new MakeVersionCommand(versionMaker); useNewVersion = new UseNewVersionCommand(versionMaker); updateObject = new UpdateObjectCommand(); delete = new DeleteCommand(persister.Repository); showPreview = new RedirectToPreviewCommand(adapters); showEdit = new RedirectToEditCommand(editUrlManager); useMaster = new UseMasterCommand(); clone = new CloneCommand(); validate = new ValidateCommand(); this.security = security; save = new SaveCommand(persister); incrementVersionIndex = new IncrementVersionIndexCommand(versionMaker); draftState = new UpdateContentStateCommand(changer, ContentState.Draft); publishedState = new UpdateContentStateCommand(changer, ContentState.Published); saveActiveContent = new ActiveContentSaveCommand(); moveToPosition = new MoveToPositionCommand(); unpublishedDate = new EnsureNotPublishedCommand(); publishedDate = new EnsurePublishedCommand(); updateReferences = new UpdateReferencesCommand(); }
public async Task GivenAStorageAccountVerifyPushSucceeds() { using (var packagesFolder = new TestFolder()) using (var testContext = new AmazonS3TestContext()) { await testContext.InitAsync(); var testPackage = new TestNupkg("packageA", "1.0.0"); var zipFile = testPackage.Save(packagesFolder.Root); var result = await InitCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, enableCatalog : true, enableSymbols : true, log : testContext.Logger, token : CancellationToken.None); result &= await PushCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, new List <string>() { zipFile.FullName }, force : false, skipExisting : false, log : testContext.Logger); result &= await ValidateCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, testContext.Logger); result.Should().BeTrue(); await testContext.CleanupAsync(); } }
/// <summary> /// Validates the current changes in the TextBox. Does nothing is there are no changes. /// </summary> public void Validate() { if (IsReadOnly || !HasChangesToValidate || validating) { return; } var cancelRoutedEventArgs = new CancelRoutedEventArgs(ValidatingEvent); OnValidating(cancelRoutedEventArgs); if (cancelRoutedEventArgs.Cancel) { return; } RaiseEvent(cancelRoutedEventArgs); if (cancelRoutedEventArgs.Cancel) { return; } if (!IsTextCompatibleWithValueBinding(Text)) { var textBindingFailedArgs = new RoutedEventArgs(TextToSourceValueConversionFailedEvent); RaiseEvent(textBindingFailedArgs); // We allow this to continue through since it'll revert itself through later code. } validating = true; var coercedText = CoerceTextForValidation(Text); SetCurrentValue(TextProperty, coercedText); BindingExpression expression = GetBindingExpression(TextProperty); try { expression?.UpdateSource(); } catch (TargetInvocationException ex) when(ex.InnerException is InvalidCastException) { var textBindingFailedArgs = new RoutedEventArgs(TextToSourceValueConversionFailedEvent); RaiseEvent(textBindingFailedArgs); } ClearUndoStack(); var validatedArgs = new ValidationRoutedEventArgs <string>(ValidatedEvent, coercedText); OnValidated(); RaiseEvent(validatedArgs); if (ValidateCommand != null && ValidateCommand.CanExecute(ValidateCommandParameter)) { ValidateCommand.Execute(ValidateCommandParameter); } validating = false; HasChangesToValidate = false; }
public async Task Symbols_VerifyFilesExistAfterPush() { using (var testContext = new SleetTestContext()) { var context = testContext.SleetContext; context.SourceSettings.SymbolsEnabled = true; var testPackage = new TestNupkg("packageA", "1.0.0"); testPackage.Files.Clear(); testPackage.AddFile("lib/net45/SymbolsTestA.dll", TestUtility.GetResource("SymbolsTestAdll").GetBytes()); testPackage.AddFile("lib/net45/SymbolsTestA.pdb", TestUtility.GetResource("SymbolsTestApdb").GetBytes()); testPackage.AddFile("lib/net45/SymbolsTestB.dll", TestUtility.GetResource("SymbolsTestBdll").GetBytes()); testPackage.AddFile("lib/net45/SymbolsTestB.pdb", TestUtility.GetResource("SymbolsTestBpdb").GetBytes()); var zipFile = testPackage.Save(testContext.Packages); // run commands await InitCommand.InitAsync(context); // add package await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile.FullName }, false, false, context.Log); // validate var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log); validateOutput.Should().BeTrue(); } }
public void TestProcessCommand_Successful() { // Preconditions Debug.Assert(managerMock != null); Debug.Assert(outputMock != null); Debug.Assert(bootstrapperMock != null); /* GIVEN */ var command = new ValidateCommand(managerMock.Object, outputMock.Object, bootstrapperMock.Object); var options = new ValidateOptions { IsVerbose = false, ConfigPath = Assembly.GetExecutingAssembly().Location }; /* WHEN */ var returnCode = command.Execute(options); /* THEN */ // We test if the command was successful and returned code 0. Assert.AreEqual(successCode, returnCode); bootstrapperMock.Verify(bootstrapper => bootstrapper.ComposeImports(managerMock.Object), Times.Once); managerMock.Verify(manager => manager.LoadConfiguration(It.IsAny <FilePath>()), Times.Once); }
public CommandFactory(IPersister persister, ISecurityManager security, IVersionManager versionMaker, IEditUrlManager editUrlManager, IContentAdapterProvider adapters, StateChanger changer) { //this.persister = persister; //makeVersionOfMaster = On.Master(new MakeVersionCommand(versionMaker)); //showEdit = new RedirectToEditCommand(editUrlManager); //clone = new CloneCommand(); //unpublishedDate = new EnsureNotPublishedCommand(); // moved to StateChanger //ensurePublishedDate = new EnsurePublishedCommand(); // moved to StateChanger this.security = security; save = new SaveCommand(persister); delete = new DeleteCommand(persister.Repository); replaceMaster = new ReplaceMasterCommand(versionMaker); makeVersion = new MakeVersionCommand(versionMaker); useDraftCmd = new UseDraftCommand(versionMaker); saveOnPageVersion = new SaveOnPageVersionCommand(versionMaker); draftState = new UpdateContentStateCommand(changer, ContentState.Draft); publishedState = new UpdateContentStateCommand(changer, ContentState.Published); updateObject = new UpdateObjectCommand(); useMaster = new UseMasterCommand(); validate = new ValidateCommand(); saveActiveContent = new ActiveContentSaveCommand(); moveToPosition = new MoveToPositionCommand(); updateReferences = new UpdateReferencesCommand(); }
public async Task SubFeed_InitTwoFeedsDestroyOneVerifyFirst() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var cache2 = new LocalCache()) { var log = new TestLogger(); var settings = new LocalSettings(); var feedSettings = new FeedSettings(); var rootFeedA = UriUtility.CreateUri(target.Root, "feedA"); var rootFeedB = UriUtility.CreateUri(target.Root, "feedB"); var fileSystem = new PhysicalFileSystem(cache, rootFeedA, rootFeedA, feedSubPath: "feedA"); var fileSystem2 = new PhysicalFileSystem(cache2, rootFeedB, rootFeedB, feedSubPath: "feedB"); // Init feeds var success = await InitCommand.InitAsync(settings, fileSystem, feedSettings, log, CancellationToken.None); success &= await InitCommand.InitAsync(settings, fileSystem2, feedSettings, log, CancellationToken.None); // Destroy feed 2 success &= await DestroyCommand.Destroy(settings, fileSystem2, log, CancellationToken.None); // Validate feed 1 success &= await ValidateCommand.Validate(settings, fileSystem, log, CancellationToken.None); success.Should().BeTrue(); target.RootDirectory.GetFiles().Should().BeEmpty(); target.RootDirectory.GetDirectories().Select(e => e.Name).ShouldBeEquivalentTo(new[] { "feedA" }); } }
public async Task GivenAStorageAccountWithNoContainerVerifyPushSucceeds() { using (var packagesFolder = new TestFolder()) using (var testContext = new AmazonS3TestContext()) { // Skip creation and allow it to be done during push. testContext.CreateBucketOnInit = false; await testContext.InitAsync(); var testPackage = new TestNupkg("packageA", "1.0.0"); var zipFile = testPackage.Save(packagesFolder.Root); var result = await PushCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, new List <string>() { zipFile.FullName }, force : false, skipExisting : false, log : testContext.Logger); result &= await ValidateCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, testContext.Logger); result.Should().BeTrue(); await testContext.CleanupAsync(); } }
public async Task BadgeFile_VerifyBadgesUpdatedAfterDeleteAll() { // Arrange using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() { BadgesEnabled = true } }; // Initial packages var identities = new HashSet <PackageIdentity>() { new PackageIdentity("a", NuGetVersion.Parse("2.0.0")) }; foreach (var id in identities) { var testPackage = new TestNupkg(id.Id, id.Version.ToFullString()); var zipFile = testPackage.Save(packagesFolder.Root); } // Push await InitCommand.InitAsync(context); await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { packagesFolder.Root }, false, false, context.Log); // Remove await DeleteCommand.RunAsync(context.LocalSettings, context.Source, "a", "2.0.0", "test", true, context.Log); // Validate var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log); validateOutput.Should().BeTrue(); // read output var stablePath = Path.Combine(target.Root, "badges/v/a.svg"); var prePath = Path.Combine(target.Root, "badges/vpre/a.svg"); File.Exists(stablePath).Should().BeFalse(); File.Exists(prePath).Should().BeFalse(); var stablePathJson = Path.Combine(target.Root, "badges/v/a.json"); var prePathJson = Path.Combine(target.Root, "badges/vpre/a.json"); File.Exists(stablePathJson).Should().BeFalse(); File.Exists(prePathJson).Should().BeFalse(); } }
public async Task Symbols_AddSymbolsPackageWithNoValidSymbolsVerifyFeed() { using (var testContext = new SleetTestContext()) { var context = testContext.SleetContext; context.SourceSettings.SymbolsEnabled = true; var symbols = new Symbols(context); var packageIndex = new PackageIndex(context); var catalog = new Catalog(context); var autoComplete = new AutoComplete(context); var flatContainer = new FlatContainer(context); var registrations = new Registrations(context); var search = new Search(context); // Create package var pkgA = new TestNupkg("a", "1.0.0"); pkgA.Nuspec.IsSymbolPackage = true; var zip = pkgA.Save(testContext.Packages); var pkgInput = testContext.GetPackageInput(zip); // Init var success = await InitCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, enableCatalog : true, enableSymbols : true, log : testContext.SleetContext.Log, token : CancellationToken.None); // Push success &= await PushCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, new List <string>() { zip.FullName }, force : false, skipExisting : false, log : testContext.SleetContext.Log); // Validate success &= await ValidateCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, testContext.SleetContext.Log); success.Should().BeTrue(); // The nupkg should exist, but there should not be any assets added. (await symbols.GetSymbolsPackagesAsync()).Should().BeEmpty(); (await packageIndex.GetSymbolsPackagesAsync()).Should().NotBeEmpty(); // Verify nupkg exists var nupkgPath = Path.Combine(testContext.Target, "symbols", "packages", "a", "1.0.0", "a.1.0.0.symbols.nupkg"); File.Exists(nupkgPath).Should().BeTrue(); // Verify package details var detailsPath = Path.Combine(testContext.Target, "symbols", "packages", "a", "1.0.0", "package.json"); File.Exists(detailsPath).Should().BeTrue(); } }
public async Task AddRemove_AddAndDeletePackagesAsync() { // Arrange using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() { CatalogEnabled = true } }; var testPackage1 = new TestNupkg("packageA", "1.0.0"); var testPackage2 = new TestNupkg("packageA", "2.0.0"); var testPackage3 = new TestNupkg("packageB", "2.0.0"); var zipFile1 = testPackage1.Save(packagesFolder.Root); var zipFile2 = testPackage2.Save(packagesFolder.Root); var zipFile3 = testPackage3.Save(packagesFolder.Root); var toDelete = new List <PackageIdentity>() { new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), new PackageIdentity("packageB", NuGetVersion.Parse("2.0.0")) }; // Act // run commands await InitCommand.InitAsync(context); await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { packagesFolder.Root }, false, false, context.Log); await DeleteCommand.DeletePackagesAsync(context.LocalSettings, context.Source, toDelete, string.Empty, false, context.Log); var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log); // read outputs var packageIndex = new PackageIndex(context); var indexPackages = await packageIndex.GetPackagesAsync(); // Assert Assert.True(validateOutput); Assert.Equal(1, indexPackages.Count); Assert.Equal("packageA", indexPackages.First().Id); Assert.Equal("2.0.0", indexPackages.First().Version.ToNormalizedString()); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); ConfigureCommand.Initialize(this); ValidateCommand.Initialize(this); PackageCommand.Initialize(this); TestCommand.Initialize(this); PushCommand.Initialize(this); }
public void OnAuthorization_ShouldSucceed() { // Arrange ValidateCommand resultCommand = null; var commandPublisherMock = new Mock <ICommandPublisher>(MockBehavior.Strict); commandPublisherMock.Setup(x => x.Publish <bool>(It.IsAny <ValidateCommand>())).Returns(Task.FromResult(true)) .Callback <ValidateCommand>(cmd => { resultCommand = cmd; }); var serviceProviderMock = new Mock <IServiceProvider>(MockBehavior.Strict); serviceProviderMock.Setup(x => x.GetService(It.Is <Type>(y => y == typeof(ICommandPublisher)))).Returns(commandPublisherMock.Object); serviceProviderMock.Setup(x => x.GetService(It.Is <Type>(y => y == typeof(ILoggerFactory)))).Returns(new LoggerFactory()); StringValues headerDictionaryResult; var headerDictionaryMock = new Mock <IHeaderDictionary>(MockBehavior.Strict); headerDictionaryMock.Setup(x => x.TryGetValue("Authorization", out headerDictionaryResult)).Returns(true) .Callback(new TryGetValueCallback((string s, out StringValues sv) => sv = new StringValues("Bearer " + jwtStringWithRolesGebruikertAndKlantje))); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(x => x.Headers).Returns(headerDictionaryMock.Object); var httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(x => x.RequestServices).Returns(serviceProviderMock.Object); httpContextMock.Setup(x => x.Request).Returns(httpRequestMock.Object); // HttpContext isn't virtual; Can't mock AuthrizationFilterContex... var filterContext = new AuthorizationFilterContext( new ActionContext( httpContextMock.Object, new Microsoft.AspNetCore.Routing.RouteData(), new ActionDescriptor() ), new List <IFilterMetadata>() ); var jwtInRole = new JwtInRole("Gebruikert", "Klantje"); // Act jwtInRole.OnAuthorization(filterContext); // Assert commandPublisherMock.VerifyAll(); serviceProviderMock.VerifyAll(); headerDictionaryMock.VerifyAll(); Assert.IsNotNull(resultCommand); Assert.AreEqual(jwtStringWithRolesGebruikertAndKlantje, resultCommand.JwtToken); Assert.AreEqual(NameConstants.AuthenticationServiceValidateCommand, resultCommand.RoutingKey); }
private void sheetPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { // ReSharper disable once ExplicitCallerInfoArgument RaisePropertyChanged(nameof(IsModified)); ValidateCommand.ChangeCanExecute(); if (e.PropertyName == "Password") { CheckPasswordCommand.ChangeCanExecute(); } }
internal static async Task Execute(Client client) { ValidateCommand command = new ValidateCommand { Base64Xml = "Base64Xml" }; ValidateResponse result = await client.PeppolDocuments.ValidateAsync(command); Console.WriteLine($"Is valid: ", result.IsValid); }
public void OnAuthorization(AuthorizationFilterContext context) { ILoggerFactory loggerFactory = (ILoggerFactory)context.HttpContext.RequestServices.GetService(typeof(ILoggerFactory)); var logger = loggerFactory?.CreateLogger <JwtInRole>(); try { var commandPublisher = (ICommandPublisher)context.HttpContext.RequestServices.GetService(typeof(ICommandPublisher)); if (commandPublisher == null) { throw new NullReferenceException("Dependency injection of commandPublisher has failed"); } if (!new JwtHelper().GetJwtToken(context.HttpContext, out JwtSecurityToken jwtToken)) { throw new UnauthorizedAccessException("Incorrect or no JwtToken provided"); } // Do not even attempt to validate the jwtToken if user doesn't have the required role if (!IsAccessAllowed(jwtToken)) { throw new UnauthorizedAccessException("User doesn't have one of the required roles"); } var validateCommand = new ValidateCommand(jwtToken.RawData, NameConstants.AuthenticationServiceValidateCommand); if (!commandPublisher.Publish <bool>(validateCommand).Result) { throw new UnauthorizedAccessException("Validation of JwtToken has failed!"); } } catch (TimeoutException) { logger?.LogError("OnAuthorization resulted in a TimeoutException."); context.Result = new StatusCodeResult((int)HttpStatusCode.RequestTimeout); } catch (UnauthorizedAccessException ex) { logger?.LogDebug( "UnauthorizedAccessException occured during execution of OnAuthorization, it threw exception: {}. Inner exception: {}", ex.Message, ex.InnerException?.Message ); context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized); } catch (Exception ex) { logger?.LogError("OnAuthorization resulted in an internal server error."); logger?.LogDebug( "Exception occured during execution of OnAuthorization, it threw exception: {}. Inner exception: {}", ex.Message, ex.InnerException?.Message ); context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized); } }
public async Task SubFeed_InitMultipleFeedsVerifyDestroyDoesNotModifyOthers() { using (var packagesFolder = new TestFolder()) using (var testContext = new AzureTestContext()) using (var testContext2 = new AzureTestContext()) { // Use a subfeed for the filesystem var subFeedName = "testSubFeedA"; var subFeedName2 = "testSubFeedB"; var root = UriUtility.GetPath(testContext.Uri, subFeedName); var root2 = UriUtility.GetPath(testContext.Uri, subFeedName2); testContext.FileSystem = new AzureFileSystem(testContext.LocalCache, root, root, testContext.StorageAccount, testContext.ContainerName, feedSubPath: subFeedName); testContext2.FileSystem = new AzureFileSystem(testContext.LocalCache, root2, root2, testContext.StorageAccount, testContext.ContainerName, feedSubPath: subFeedName2); await testContext.InitAsync(); await testContext2.InitAsync(); var testPackage = new TestNupkg("packageA", "1.0.0"); var zipFile = testPackage.Save(packagesFolder.Root); var result = await InitCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, enableCatalog : true, enableSymbols : true, log : testContext.Logger, token : CancellationToken.None); result &= await InitCommand.RunAsync(testContext.LocalSettings, testContext2.FileSystem, enableCatalog : true, enableSymbols : true, log : testContext2.Logger, token : CancellationToken.None); // Destroy feed2 result &= await DestroyCommand.RunAsync(testContext.LocalSettings, testContext2.FileSystem, testContext2.Logger); // Validate feed1 result &= await ValidateCommand.RunAsync(testContext.LocalSettings, testContext.FileSystem, testContext.Logger); result.Should().BeTrue(); await testContext.CleanupAsync(); await testContext2.CleanupAsync(); } }
private static int Invoke(IFileSystem fileSystem, IProcessProxy processProxy, IConsole?console = null) { var command = new ValidateCommand() { Handler = new ValidateCommand.CommandHandler( MockEnvironmentProxy.Default, processProxy, fileSystem, MockLoggerFactory.CreateGenericLogger <ValidateCommand>()), }; return(command.Invoke("", console)); }
public void Execute_WithEmptyConfig_WillPrintEmptyConfig() { // Arrange ValidateCommand command = new ValidateCommand(false, "testpath"); testConfigHandler.Setup(m => m.LoadConfig("testpath")).Returns(testConfig.Object); // Act command.Execute(testConsole, testConfigHandler.Object, testFileSystem, testPathFormatter); // Assert Assert.IsTrue(testConsole.GetHistory().Contains("empty", System.StringComparison.OrdinalIgnoreCase)); }
public void ValidateCommand_AcceptsTargetFileWithSpaceInName() { // A minimal valid log file. string LogFileContents = @"{ ""$schema"": """ + SarifUtilities.SarifSchemaUri + @""", ""version"": ""2.0.0"", ""runs"": [ { ""tool"": { ""name"": ""TestTool"" }, ""results"": [] } ] }"; // A simple schema against which the log file successfully validates. // This way, we don't have to read the SARIF schema from disk to run this test. const string SchemaFileContents = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"" }"; // Here's the space: const string LogFileDirectory = @"c:\Users\John Smith\logs"; const string LogFileName = "example.sarif"; string logFilePath = Path.Combine(LogFileDirectory, LogFileName); const string SchemaFilePath = @"c:\schemas\SimpleSchemaForTest.json"; var mockFileSystem = new Mock <IFileSystem>(); mockFileSystem.Setup(x => x.DirectoryExists(LogFileDirectory)).Returns(true); mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]); mockFileSystem.Setup(x => x.GetFilesInDirectory(LogFileDirectory, LogFileName)).Returns(new string[] { logFilePath }); mockFileSystem.Setup(x => x.ReadAllText(logFilePath)).Returns(LogFileContents); mockFileSystem.Setup(x => x.ReadAllText(SchemaFilePath)).Returns(SchemaFileContents); var validateCommand = new ValidateCommand(mockFileSystem.Object); var options = new ValidateOptions { SchemaFilePath = SchemaFilePath, TargetFileSpecifiers = new string[] { logFilePath } }; int returnCode = validateCommand.Run(options); returnCode.Should().Be(0); }
public async Task Symbols_AddPackageWithNoSymbolsVerifyNotInIndex(string isSymbolsString) { var isSymbols = bool.Parse(isSymbolsString); using (var testContext = new SleetTestContext()) { var context = testContext.SleetContext; context.SourceSettings.SymbolsEnabled = true; // Create package var pkgA = new TestNupkg("a", "1.0.0"); pkgA.Files.Clear(); pkgA.Nuspec.IsSymbolPackage = isSymbols; var zip = pkgA.Save(testContext.Packages); var pkgInput = testContext.GetPackageInput(zip); // Init var success = await InitCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, enableCatalog : true, enableSymbols : true, log : testContext.SleetContext.Log, token : CancellationToken.None); // Push success &= await PushCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, new List <string>() { zip.FullName }, force : false, skipExisting : false, log : testContext.SleetContext.Log); // Validate success &= await ValidateCommand.RunAsync( testContext.SleetContext.LocalSettings, testContext.SleetContext.Source, testContext.SleetContext.Log); var service = new Symbols(context); var packages = new HashSet <PackageIdentity>(await service.GetPackagesAsync()); packages.UnionWith(await service.GetSymbolsPackagesAsync()); // Verify package does not show up in symbols index packages.Should().BeEmpty(); // Validate success.Should().BeTrue(); } }
public Command(ToolStripItem[] toolStripItems, MenuItem[] menuItems, Control[] controls, EventHandler clickDelegate, ValidateCommand validateDelegate) { _toolStripItems = toolStripItems; _menuItems = menuItems; _controls = controls; _validateCommandDelegate = validateDelegate; _clickCommandDelegate = clickDelegate; if (toolStripItems != null) foreach (ToolStripItem item in toolStripItems) { item.Click += _clickCommandDelegate; } if (controls != null) foreach (Control control in controls) { control.Click += _clickCommandDelegate; } if (menuItems != null) { foreach (MenuItem item in menuItems) { item.Click += _clickCommandDelegate; } } }
/* public void Add(Control[] controls, EventHandler clickDelegate, ValidateCommand validateDelegate) { _commands.Add(new Command(null, controls, clickDelegate, validateDelegate)); } */ public void Add(Control control, EventHandler clickDelegate, ValidateCommand validateDelegate) { _commands.Add(new Command(null, null, new[] {control}, clickDelegate, validateDelegate)); }
public void Add(Control control, ValidateCommand validateDelegate) { _commands.Add(new Command(null, null, new[] {control}, delegate { }, validateDelegate)); }