예제 #1
0
        public async Task HostProviderRegistry_GetProvider_ProviderSpecified_ReturnsProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { ProviderOverride = "provider3" }
            };
            var registry = new HostProviderRegistry(context);
            var input    = new InputArguments(new Dictionary <string, string>());

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.Id).Returns("provider1");
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider2Mock.Setup(x => x.Id).Returns("provider2");
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.Id).Returns("provider3");
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider3Mock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(provider3Mock.Object, result);
        }
        /// <summary>
        /// Initializes a new instance of the Yandex.Money.Api.Sdk.Interfaces.IHttpClient interface.
        /// </summary>
        /// <param name="hostProvider">an instance of IHostProvider implementation</param>
        /// <param name="auth">an instance of IAuthenticator implementation</param>
        public DefaultHttpPostClient(IHostProvider hostProvider, IAuthenticator auth)
        {
            _hostProvider = hostProvider;
            _authenticator = auth;

            Init();
        }
예제 #3
0
 public IUnitTestElementCriterion Apply(
     IUnitTestElementCriterion criterion,
     IUnitTestSession session,
     IHostProvider hostProvider)
 {
     return(criterion);
 }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultHttpPostClient"/> class.
        /// </summary>
        /// <param name="hostProvider">Instance of IHostProvider. If not specified, default one will be used.</param>
        /// <param name="auth">Instance of IAuthenticator. If not specified request will not use authentication.</param>
        public DefaultHttpPostClient([CanBeNull] IHostProvider hostProvider, [CanBeNull] IAuthenticator auth)
        {
            _hostProvider  = hostProvider ?? new DefaultHostsProvider();
            _authenticator = auth;

            Init();
        }
예제 #5
0
        public async Task HostProviderRegistry_GetProvider_Auto_MultipleValidProvidersMultipleLevels_ReturnsFirstHighestRegistered()
        {
            var            context  = new TestCommandContext();
            var            registry = new HostProviderRegistry(context);
            var            remote   = new Uri("https://example.com");
            InputArguments input    = CreateInputArguments(remote);

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();
            var provider4Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider4Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);

            registry.Register(provider1Mock.Object, HostProviderPriority.Low);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider3Mock.Object, HostProviderPriority.High);
            registry.Register(provider4Mock.Object, HostProviderPriority.Low);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(provider3Mock.Object, result);
        }
예제 #6
0
        public async Task HostProviderRegistry_GetProvider_UnknownProviderSpecified_ReturnsFirstSupportedProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { ProviderOverride = "provider42" }
            };
            var            registry = new HostProviderRegistry(context);
            var            remote   = new Uri("https://example.com");
            InputArguments input    = CreateInputArguments(remote);

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.Id).Returns("provider1");
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.Id).Returns("provider2");
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.Id).Returns("provider3");
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider3Mock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(provider2Mock.Object, result);
        }
예제 #7
0
        public async Task HostProviderRegistry_GetProvider_Auto_HasProviders_DynamicMatch_SetsProviderGlobalConfig_HostWithPath()
        {
            var            context  = new TestCommandContext();
            var            registry = new HostProviderRegistry(context);
            var            remote   = new Uri("https://example.com/alice/repo.git/");
            InputArguments input    = CreateInputArguments(remote);

            string providerId = "myProvider";
            string configKey  = string.Format(CultureInfo.InvariantCulture,
                                              "{0}.https://example.com/alice/repo.git.{1}", // expect any trailing slash to be removed
                                              Constants.GitConfiguration.Credential.SectionName,
                                              Constants.GitConfiguration.Credential.Provider);

            var providerMock = new Mock <IHostProvider>();

            providerMock.Setup(x => x.Id).Returns(providerId);
            providerMock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            providerMock.Setup(x => x.IsSupported(It.IsAny <HttpResponseMessage>())).Returns(true);

            registry.Register(providerMock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(providerMock.Object, result);
            Assert.True(context.Git.Configuration.Global.TryGetValue(configKey, out IList <string> config));
            Assert.Equal(1, config.Count);
            Assert.Equal(providerId, config[0]);
        }
        protected override async Task ExecuteInternalAsync(InputArguments input, IHostProvider provider)
        {
            ICredential credential = await provider.GetCredentialAsync(input);

            var output = new Dictionary <string, string>();

            // Echo protocol, host, and path back at Git
            if (input.Protocol != null)
            {
                output["protocol"] = input.Protocol;
            }
            if (input.Host != null)
            {
                output["host"] = input.Host;
            }
            if (input.Path != null)
            {
                output["path"] = input.Path;
            }

            // Return the credential to Git
            output["username"] = credential.Account;
            output["password"] = credential.Password;

            // Write the values to standard out
            Context.Streams.Out.WriteDictionary(output);
        }
예제 #9
0
        public void HostProviderRegistry_GetProvider_UnknownProviderSpecified_ReturnsFirstSupportedProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { ProviderOverride = "provider42" }
            };
            var registry = new HostProviderRegistry(context);
            var input    = new InputArguments(new Dictionary <string, string>());

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.Id).Returns("provider1");
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.Id).Returns("provider2");
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.Id).Returns("provider3");
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, provider2Mock.Object, provider3Mock.Object);

            IHostProvider result = registry.GetProvider(input);

            Assert.Same(provider2Mock.Object, result);
        }
예제 #10
0
        public async Task HostProviderRegistry_GetProvider_AutoLegacyAuthoritySpecified_ReturnsFirstSupportedProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { LegacyAuthorityOverride = Constants.AuthorityIdAuto }
            };
            var            registry = new HostProviderRegistry(context);
            var            remote   = new Uri("https://example.com");
            InputArguments input    = CreateInputArguments(remote);

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityA" });
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityB", "authorityC" });
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityD" });
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider3Mock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(provider2Mock.Object, result);
        }
예제 #11
0
        public async Task HostProviderRegistry_GetProvider_LegacyAuthoritySpecified_ReturnsProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { LegacyAuthorityOverride = "authorityB" }
            };
            var registry = new HostProviderRegistry(context);
            var input    = new InputArguments(new Dictionary <string, string>());

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityA" });
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityB", "authorityC" });
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider3Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityD" });
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider3Mock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(provider2Mock.Object, result);
        }
예제 #12
0
        public async Task HostProviderRegistry_GetProvider_Auto_HasProviders_StaticMatch_DoesNotSetProviderGlobalConfig()
        {
            var            context  = new TestCommandContext();
            var            registry = new HostProviderRegistry(context);
            var            remote   = new Uri("https://example.com");
            InputArguments input    = CreateInputArguments(remote);

            string providerId = "myProvider";
            string configKey  = string.Format(CultureInfo.InvariantCulture,
                                              "{0}.https://example.com.{1}",
                                              Constants.GitConfiguration.Credential.SectionName,
                                              Constants.GitConfiguration.Credential.Provider);

            var providerMock = new Mock <IHostProvider>();

            providerMock.Setup(x => x.Id).Returns(providerId);
            providerMock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);

            registry.Register(providerMock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            Assert.Same(providerMock.Object, result);
            Assert.False(context.Git.Configuration.Global.TryGetValue(configKey, out _));
        }
예제 #13
0
        public async Task HostProviderRegistry_GetProvider_Auto_NetworkProbe_ReturnsSupportedProvider()
        {
            var            context   = new TestCommandContext();
            var            registry  = new HostProviderRegistry(context);
            var            remoteUri = new Uri("https://provider2.onprem.example.com");
            InputArguments input     = CreateInputArguments(remoteUri);

            var provider1Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <HttpResponseMessage>())).Returns(false);

            var provider2Mock = new Mock <IHostProvider>();

            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <HttpResponseMessage>())).Returns(true);

            var responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Headers = { { "X-Provider2", "true" } }
            };

            var httpHandler = new TestHttpMessageHandler();

            httpHandler.Setup(HttpMethod.Head, remoteUri, responseMessage);
            context.HttpClientFactory.MessageHandler = httpHandler;

            registry.Register(provider1Mock.Object, HostProviderPriority.Normal);
            registry.Register(provider2Mock.Object, HostProviderPriority.Normal);

            IHostProvider result = await registry.GetProviderAsync(input);

            httpHandler.AssertRequest(HttpMethod.Head, remoteUri, 1);
            Assert.Same(provider2Mock.Object, result);
        }
        internal async Task ExecuteAsync()
        {
            Context.Trace.WriteLine($"Start '{Name}' command...");

            // Parse standard input arguments
            // git-credential treats the keys as case-sensitive; so should we.
            IDictionary <string, string> inputDict = await Context.Streams.In.ReadDictionaryAsync(StringComparer.Ordinal);

            var input = new InputArguments(inputDict);

            // Validate minimum arguments are present
            EnsureMinimumInputArguments(input);

            // Set the remote URI to scope settings to throughout the process from now on
            Context.Settings.RemoteUri = input.GetRemoteUri();

            // Determine the host provider
            Context.Trace.WriteLine("Detecting host provider for input:");
            Context.Trace.WriteDictionarySecrets(inputDict, new [] { "password" }, StringComparer.OrdinalIgnoreCase);
            IHostProvider provider = await _hostProviderRegistry.GetProviderAsync(input);

            Context.Trace.WriteLine($"Host provider '{provider.Name}' was selected.");

            await ExecuteInternalAsync(input, provider);

            Context.Trace.WriteLine($"End '{Name}' command...");
        }
	    /// <summary>
        /// Initializes a new instance of the <see cref="DefaultHttpPostClient"/> class.
        /// </summary>
        /// <param name="hostProvider">Instance of IHostProvider. If not specified, default one will be used.</param>
        /// <param name="auth">Instance of IAuthenticator. If not specified request will not use authentication.</param>
        public DefaultHttpPostClient([CanBeNull] IHostProvider hostProvider, [CanBeNull] IAuthenticator auth)
        {
            _hostProvider = hostProvider ?? new DefaultHostsProvider();
            _authenticator = auth;

            Init();
        }
예제 #16
0
        public void Register(IHostProvider hostProvider, HostProviderPriority priority)
        {
            EnsureArgument.NotNull(hostProvider, nameof(hostProvider));

            if (StringComparer.OrdinalIgnoreCase.Equals(hostProvider.Id, Constants.ProviderIdAuto))
            {
                throw new ArgumentException(
                          $"A host provider cannot be registered with the ID '{Constants.ProviderIdAuto}'",
                          nameof(hostProvider));
            }

            if (hostProvider.SupportedAuthorityIds.Any(y => StringComparer.OrdinalIgnoreCase.Equals(y, Constants.AuthorityIdAuto)))
            {
                throw new ArgumentException(
                          $"A host provider cannot be registered with the legacy authority ID '{Constants.AuthorityIdAuto}'",
                          nameof(hostProvider));
            }

            if (!_hostProviders.TryGetValue(priority, out ICollection <IHostProvider> providers))
            {
                providers = new List <IHostProvider>();
                _hostProviders[priority] = providers;
            }

            providers.Add(hostProvider);
        }
예제 #17
0
        public void HostProviderRegistry_GetProvider_AutoLegacyAuthoritySpecified_ReturnsFirstSupportedProvider()
        {
            var context = new TestCommandContext
            {
                Settings = { LegacyAuthorityOverride = Constants.AuthorityIdAuto }
            };
            var registry = new HostProviderRegistry(context);
            var input    = new InputArguments(new Dictionary <string, string>());

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityA" });
            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            provider2Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityB", "authorityC" });
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.SupportedAuthorityIds).Returns(new[] { "authorityD" });
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);

            registry.Register(provider1Mock.Object, provider2Mock.Object, provider3Mock.Object);

            IHostProvider result = registry.GetProvider(input);

            Assert.Same(provider2Mock.Object, result);
        }
예제 #18
0
        /// <summary>
        /// Initializes a new instance of the Yandex.Money.Api.Sdk.Interfaces.IHttpClient interface.
        /// </summary>
        /// <param name="hostProvider">an instance of IHostProvider implementation</param>
        /// <param name="auth">an instance of IAuthenticator implementation</param>
        public DefaultHttpPostClient(IHostProvider hostProvider, IAuthenticator auth)
        {
            _hostProvider  = hostProvider;
            _authenticator = auth;

            Init();
        }
예제 #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleElasticClient" /> class with
 /// the specified configuration.
 /// </summary>
 /// <param name="config">The configuration to use.</param>
 /// <param name="tracer">The tracer to use, if null defaults to the global tracer.</param>
 public SimpleElasticClient(ClientOptions config, ITracer tracer)
 {
     _tracer       = tracer ?? GlobalTracer.Instance;
     _client       = config.HttpClient ?? _defaultClient.Value;
     _log          = config.Logger ?? NullLogger.Instance;
     _jsonSettings = DefaultJsonSettings;
     _hostProvider = config.HostProvider ?? throw new ArgumentNullException($"{nameof(ClientOptions.HostProvider)} cannot be null", nameof(config));
 }
예제 #20
0
        private bool TryRenderIframeFromKnownProviders(Uri uri, bool isSchemaRelative, HtmlRenderer renderer, LinkInline linkInline)
        {
            IHostProvider foundProvider = null;
            string        iframeUrl     = null;

            foreach (var provider in Options.Hosts)
            {
                if (!provider.TryHandle(uri, isSchemaRelative, out iframeUrl))
                {
                    continue;
                }
                foundProvider = provider;
                break;
            }

            if (foundProvider == null)
            {
                return(false);
            }

            var htmlAttributes = GetHtmlAttributes(linkInline);

            renderer.Write("<iframe src=\"");
            renderer.WriteEscapeUrl(iframeUrl);
            renderer.Write("\"");

            if (!string.IsNullOrEmpty(Options.Width))
            {
                htmlAttributes.AddPropertyIfNotExist("width", Options.Width);
            }

            if (!string.IsNullOrEmpty(Options.Height))
            {
                htmlAttributes.AddPropertyIfNotExist("height", Options.Height);
            }

            if (!string.IsNullOrEmpty(Options.Class))
            {
                htmlAttributes.AddClass(Options.Class);
            }

            if (!string.IsNullOrEmpty(foundProvider.Class))
            {
                htmlAttributes.AddClass(foundProvider.Class);
            }

            htmlAttributes.AddPropertyIfNotExist("frameborder", "0");
            if (foundProvider.AllowFullScreen)
            {
                htmlAttributes.AddPropertyIfNotExist("allowfullscreen", null);
            }
            renderer.WriteAttributes(htmlAttributes);
            renderer.Write("></iframe>");

            return(true);
        }
        public void RegisterProvider(IHostProvider provider, HostProviderPriority priority)
        {
            _providerRegistry.Register(provider, priority);

            // If the provider is also a configurable component, add that to the configuration service
            if (provider is IConfigurableComponent configurableProvider)
            {
                _configurationService.AddComponent(configurableProvider);
            }
        }
예제 #22
0
        public FormMain()
        {
            InitializeComponent();

            m_HostsProvider = new HostProvider();
            quickSwitchToolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(quickSwitchToolStripMenuItem_DropDownItemClicked);
            foreach (var host in m_HostsProvider.GetHostFiles())
            {
                listHosts.Items.Add(host);
                quickSwitchToolStripMenuItem.DropDownItems.Add(host);
            }

            Text = string.Format("{1} - v.{0}", typeof(FormMain).Assembly.GetName().Version, Resources.HostsSwitcher);
        }
예제 #23
0
        public void RegisterProvider(IHostProvider provider, HostProviderPriority priority)
        {
            _providerRegistry.Register(provider, priority);

            // If the provider is also a configurable component, add that to the configuration service
            if (provider is IConfigurableComponent configurableProvider)
            {
                _configurationService.AddComponent(configurableProvider);
            }

            // If the provider has custom commands to offer then create them here
            if (provider is ICommandProvider cmdProvider)
            {
                ProviderCommand providerCommand = cmdProvider.CreateCommand();
                _providerCommands.Add(providerCommand);
            }
        }
예제 #24
0
        public async Task HostProviderRegistry_GetProvider_Auto_NetworkProbe_NoNetwork_ReturnsLastProvider()
        {
            var context   = new TestCommandContext();
            var registry  = new HostProviderRegistry(context);
            var remoteUri = new Uri("https://provider2.onprem.example.com");
            var input     = new InputArguments(
                new Dictionary <string, string>
            {
                ["protocol"] = remoteUri.Scheme,
                ["host"]     = remoteUri.Host
            }
                );

            var highProviderMock = new Mock <IHostProvider>();

            highProviderMock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(false);
            highProviderMock.Setup(x => x.IsSupported(It.IsAny <HttpResponseMessage>())).Returns(false);
            registry.Register(highProviderMock.Object, HostProviderPriority.Normal);

            var lowProviderMock = new Mock <IHostProvider>();

            lowProviderMock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            registry.Register(lowProviderMock.Object, HostProviderPriority.Low);

            var responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Headers = { { "X-Provider2", "true" } }
            };

            var httpHandler = new TestHttpMessageHandler
            {
                SimulateNoNetwork = true,
            };

            httpHandler.Setup(HttpMethod.Head, remoteUri, responseMessage);
            context.HttpClientFactory.MessageHandler = httpHandler;

            IHostProvider result = await registry.GetProviderAsync(input);

            httpHandler.AssertRequest(HttpMethod.Head, remoteUri, 1);
            Assert.Same(lowProviderMock.Object, result);
        }
예제 #25
0
        public IConsole CreateOutputConsole(bool requirePowerShellHost)
        {
            if (_console == null)
            {
                var serviceProvider = ServiceLocator.GetInstance <IServiceProvider>();
                var outputWindow    = (IVsOutputWindow)serviceProvider.GetService(typeof(SVsOutputWindow));
                Debug.Assert(outputWindow != null);

                _console = new OutputConsole(outputWindow);
            }

            // only instantiate the PS host if necessary (e.g. when package contains PS script files)
            if (requirePowerShellHost && _console.Host == null)
            {
                IHostProvider hostProvider = GetPowerShellHostProvider();
                _console.Host = hostProvider.CreateHost(async: false);
            }

            return(_console);
        }
예제 #26
0
        public void HostProviderRegistry_GetProvider_Auto_MultipleValidProviders_ReturnsFirstRegistered()
        {
            var context  = new TestCommandContext();
            var registry = new HostProviderRegistry(context);
            var input    = new InputArguments(new Dictionary <string, string>());

            var provider1Mock = new Mock <IHostProvider>();
            var provider2Mock = new Mock <IHostProvider>();
            var provider3Mock = new Mock <IHostProvider>();

            provider1Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider2Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);
            provider3Mock.Setup(x => x.IsSupported(It.IsAny <InputArguments>())).Returns(true);

            registry.Register(provider1Mock.Object, provider2Mock.Object, provider3Mock.Object);

            IHostProvider result = registry.GetProvider(input);

            Assert.Same(provider1Mock.Object, result);
        }
예제 #27
0
        public void RegisterProvider(IHostProvider provider, HostProviderPriority priority)
        {
            _providerRegistry.Register(provider, priority);

            // If the provider is also a configurable component, add that to the configuration service
            if (provider is IConfigurableComponent configurableProvider)
            {
                _configurationService.AddComponent(configurableProvider);
            }

            // If the provider has custom commands to offer then create them here
            if (provider is ICommandProvider cmdProvider)
            {
                ProviderCommand providerCommand = cmdProvider.CreateCommand();
                _providerCommands.Add(providerCommand);
            }

            // If the provider exposes custom diagnostics use them
            if (provider is IDiagnosticProvider diagnosticProvider)
            {
                IEnumerable <IDiagnostic> providerDiagnostics = diagnosticProvider.GetDiagnostics();
                _diagnostics.AddRange(providerDiagnostics);
            }
        }
예제 #28
0
        public FormMain()
        {
            InitializeComponent();

            m_HostsProvider = new HostProvider();
            quickSwitchToolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(quickSwitchToolStripMenuItem_DropDownItemClicked);

            Text = string.Format("Hosts Switcher - v.{0}", typeof(FormMain).Assembly.GetName().Version);

            listLocked = true;
            if (File.Exists(appSettingsFilePath))
            {
                profiles     = HostsProfile.readFromXML(appSettingsFilePath);
                currentHosts = HostsProfile.getCurrentProfile(profiles);
            }
            else
            {
                List <HostsProfile> profiles = new List <HostsProfile>();
                currentHosts = new HostsProfile();
                profiles.Add(currentHosts);
                HostsProfile.writeToSettingsXML(profiles);
            }
            initializeListView();

            selectedProfile = currentHosts;
            customizeHosts(selectedProfile);
            updateListBox();
            listView1.ItemChecked += new ItemCheckedEventHandler(listView_CheckedChanged);



            listView1.CheckBoxes            = true;
            listView1.SubItemClicked       += new ListViewEx.SubItemEventHandler(listView1_SubItemClicked);
            listView1.SubItemEndEditing    += new ListViewEx.SubItemEndEditingEventHandler(listView1_SubItemEndEditing);
            listView1.DoubleClickActivation = false;
        }
예제 #29
0
        public async Task <IHostProvider> GetProviderAsync(InputArguments input)
        {
            IHostProvider provider;

            //
            // Try and locate a specified provider
            //
            if (_context.Settings.ProviderOverride is string providerId)
            {
                _context.Trace.WriteLine($"Host provider override was set id='{providerId}'");

                if (!StringComparer.OrdinalIgnoreCase.Equals(Constants.ProviderIdAuto, providerId))
                {
                    provider = _hostProviders
                               .SelectMany(x => x.Value)
                               .FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Id, providerId));

                    if (provider is null)
                    {
                        _context.Trace.WriteLine($"No host provider was found with ID '{providerId}'.. falling back to auto-detection.");
                        _context.Streams.Error.WriteLine($"warning: a host provider override was set but no such provider '{providerId}' was found. Falling back to auto-detection.");
                    }
                    else
                    {
                        return(provider);
                    }
                }
            }
            //
            // Try and locate a provider by supported authorities
            //
            else if (_context.Settings.LegacyAuthorityOverride is string authority)
            {
                _context.Trace.WriteLine($"Host provider authority override was set authority='{authority}'");
                _context.Streams.Error.WriteLine("warning: the `credential.authority` and `GCM_AUTHORITY` settings are deprecated.");
                _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAuthorityDeprecated} for more information.");

                if (!StringComparer.OrdinalIgnoreCase.Equals(Constants.AuthorityIdAuto, authority))
                {
                    provider = _hostProviders
                               .SelectMany(x => x.Value)
                               .FirstOrDefault(x => x.SupportedAuthorityIds.Contains(authority, StringComparer.OrdinalIgnoreCase));

                    if (provider is null)
                    {
                        _context.Trace.WriteLine($"No host provider was found with authority '{authority}'.. falling back to auto-detection.");
                        _context.Streams.Error.WriteLine($"warning: a supported authority override was set but no such provider supporting authority '{authority}' was found. Falling back to auto-detection.");
                    }
                    else
                    {
                        return(provider);
                    }
                }
            }

            //
            // Auto-detection
            // Perform auto-detection network probe and remember the result
            //
            _context.Trace.WriteLine("Performing auto-detection of host provider.");

            var uri = input.GetRemoteUri();

            if (uri is null)
            {
                throw new Exception("Unable to detect host provider without a remote URL");
            }

            var probeTimeout = TimeSpan.FromMilliseconds(_context.Settings.AutoDetectProviderTimeout);

            _context.Trace.WriteLine($"Auto-detect probe timeout is {probeTimeout.TotalSeconds} ms.");

            HttpResponseMessage probeResponse = null;

            async Task <IHostProvider> MatchProviderAsync(HostProviderPriority priority)
            {
                if (_hostProviders.TryGetValue(priority, out ICollection <IHostProvider> providers))
                {
                    _context.Trace.WriteLine($"Checking against {providers.Count} host providers registered with priority '{priority}'.");

                    // Try matching using the static Git input arguments first (cheap)
                    if (providers.TryGetFirst(x => x.IsSupported(input), out IHostProvider match))
                    {
                        return(match);
                    }

                    // Try matching using the HTTP response from a query to the remote URL (expensive).
                    // The user may have disabled this feature with a zero or negative timeout for performance reasons.
                    // We only probe the remote once and reuse the same response for all providers.
                    if (probeTimeout.TotalMilliseconds > 0)
                    {
                        if (probeResponse is null)
                        {
                            _context.Trace.WriteLine("Querying remote URL for host provider auto-detection.");

                            using (HttpClient client = _context.HttpClientFactory.CreateClient())
                            {
                                client.Timeout = probeTimeout;

                                try
                                {
                                    probeResponse = await client.HeadAsync(uri);
                                }
                                catch (TaskCanceledException)
                                {
                                    _context.Streams.Error.WriteLine($"warning: auto-detection of host provider took too long (>{probeTimeout.TotalMilliseconds}ms)");
                                    _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAutoDetect} for more information.");
                                }
                                catch (Exception ex)
                                {
                                    // The auto detect probing failed for some other reason.
                                    // We don't particular care why, but we should not crash!
                                    _context.Streams.Error.WriteLine($"warning: failed to probe '{uri}' to detect provider");
                                    _context.Streams.Error.WriteLine($"warning: {ex.Message}");
                                    _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAutoDetect} for more information.");
                                }
                            }
                        }

                        if (providers.TryGetFirst(x => x.IsSupported(probeResponse), out match))
                        {
                            return(match);
                        }
                    }
                }

                return(null);
            }

            // Match providers starting with the highest priority
            IHostProvider match = await MatchProviderAsync(HostProviderPriority.High) ??
                                  await MatchProviderAsync(HostProviderPriority.Normal) ??
                                  await MatchProviderAsync(HostProviderPriority.Low) ??
                                  throw new Exception("No host provider available to service this request.");

            // If we ended up making a network call then set the host provider explicitly
            // to avoid future calls!
            if (probeResponse != null)
            {
                IGitConfiguration gitConfig = _context.Git.GetConfiguration();
                var keyName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}",
                                            Constants.GitConfiguration.Credential.SectionName, uri.ToString().TrimEnd('/'),
                                            Constants.GitConfiguration.Credential.Provider);

                try
                {
                    _context.Trace.WriteLine($"Remembering host provider for '{uri}' as '{match.Id}'...");
                    gitConfig.Set(GitConfigurationLevel.Global, keyName, match.Id);
                }
                catch (Exception ex)
                {
                    _context.Trace.WriteLine("Failed to set host provider!");
                    _context.Trace.WriteException(ex);

                    _context.Streams.Error.WriteLine("warning: failed to remember result of host provider detection!");
                    _context.Streams.Error.WriteLine($"warning: try setting this manually: `git config --global {keyName} {match.Id}`");
                }
            }

            return(match);
        }
 /// <summary>
 /// Execute the command using the given <see cref="InputArguments"/> and <see cref="IHostProvider"/>.
 /// </summary>
 /// <param name="input">Input arguments of the current Git credential query.</param>
 /// <param name="provider">Host provider for the current <see cref="InputArguments"/>.</param>
 /// <returns>Awaitable task for the command execution.</returns>
 protected abstract Task ExecuteInternalAsync(InputArguments input, IHostProvider provider);
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     throw new System.NotImplementedException();
 }
예제 #32
0
 public bool IsSupported(IHostProvider hostProvider)
 {
     throw new NotImplementedException();
 }
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     return myProvider.Strategy;
 }
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     return new DoNothingRunStrategy();
 }
예제 #35
0
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider, IUnitTestElement element)
 {
     return this.runStrategy;
 }
예제 #36
0
 public bool IsSupported(IHostProvider hostProvider)
 {
     return true;
 }
 public HostProviderDescriptorWrapper(IHostProvider provider, IHostProviderDescriptor wrappedDescriptor)
 {
     this.Provider = provider;
     this.wrappedDescriptor = wrappedDescriptor;
 }
예제 #38
0
 public bool IsSupported(IHostProvider hostProvider)
 {
     return hostProvider.ID.Equals(WellKnownHostProvidersIds.DebugProviderId);
 }
예제 #39
0
 public bool IsSupported(IHostProvider hostProvider)
 {
     return(true);
 }
예제 #40
0
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     return Services.RunStrategy;
 }
 public bool IsSupported(IHostProvider hostProvider)
 {
     return hostProvider is ProcessHostProvider || hostProvider is DebugHostProvider;
 }
예제 #42
0
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     return(Services.RunStrategy);
 }
예제 #43
0
 public IUnitTestRunStrategy GetRunStrategy(IHostProvider hostProvider)
 {
     return this.runStrategy;
 }