Example #1
0
        private void PrimeConnection(string uri)
        {
            if (redirectHost == null)
            {
                // www.daxformatter.com redirects request to another site.  HttpWebRequest does redirect with GET.  It fails, since the web service works only with POST
                // The following 2 requests are doing manual POST re-direct
                //var webRequestFactory = IoC.Get<WebRequestFactory>();
                var redirectRequest = (HttpWebRequest)WebRequest.Create(uri);
                redirectRequest.Proxy = ProxyCache.GetProxy(uri);

                redirectRequest.AllowAutoRedirect = false;
                redirectRequest.Timeout           = Preferences.Current.DaxFormatterRequestTimeout;
                try
                {
                    using (var netResponse = redirectRequest.GetResponse())
                    {
                        var redirectResponse = (HttpWebResponse)netResponse;
                        redirectUrl = redirectResponse.Headers["Location"];
                        var redirectUri = new Uri(redirectUrl);

                        // set the shared redirectHost variable
                        redirectHost = redirectUri.Host;
                    }
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// Creates a new instance of the ApiEdit class
        /// </summary>
        /// <param name="url">Path to scripts on server</param>
        /// <param name="usePHP5">Whether a .php5 extension is to be used</param>
        public ApiEdit(string url, bool usePHP5)
            : this()
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("Invalid URL specified", "url");
            }
            //if (!url.StartsWith("http://")) throw new NotSupportedException("Only editing via HTTP is currently supported");

            URL    = url;
            PHP5   = usePHP5;
            ApiURL = URL + "api.php" + (PHP5 ? "5" : "");
            Maxlag = 5;

            IWebProxy proxy;

            if (ProxyCache.TryGetValue(url, out proxy))
            {
                ProxySettings = proxy;
            }
            else
            {
                ProxySettings = WebRequest.GetSystemWebProxy();
                if (ProxySettings.IsBypassed(new Uri(url)))
                {
                    ProxySettings = null;
                }
                ProxyCache.Add(url, ProxySettings);
            }
        }
Example #3
0
        private void SaveSettings()
        {
            Preferences.Current.BackupLocation              = chkAutoBackup.Checked ? txtBackupPath.Text : string.Empty;
            Preferences.Current.CheckForUpdates             = chkAutoUpdate.Checked;
            Preferences.Current.FormulaFixup                = chkFixup.Checked;
            Preferences.Current.AllowUnsupportedPBIFeatures = chkAllowUnsupportedPBIFeatures.Checked;
            Preferences.Current.UseSemicolonsAsSeparators   = cmbSeparators.SelectedIndex == 1;
            Preferences.Current.BackgroundBpa               = chkBackgroundBpa.Checked;
            Preferences.Current.AnnotateDeploymentMetadata  = chkAnnotateDeploymentMetadata.Checked;

            Preferences.Current.IgnoreTimestamps                = chkIgnoreTimestamps.Checked;
            Preferences.Current.IgnoreInferredObjects           = chkIgnoreInfObjects.Checked;
            Preferences.Current.IgnoreInferredProperties        = chkIgnoreInfProps.Checked;
            Preferences.Current.SplitMultilineStrings           = chkSplitMultiline.Checked;
            Preferences.Current.SaveToFolder_PrefixFiles        = chkPrefixFiles.Checked;
            Preferences.Current.SaveToFolder_LocalPerspectives  = chkLocalPerspectives.Checked;
            Preferences.Current.SaveToFolder_LocalTranslations  = chkLocalTranslations.Checked;
            Preferences.Current.SaveToFolder_LocalRelationships = chkLocalRelationships.Checked;
            Preferences.Current.Copy_IncludeTranslations        = chkCopyIncludeTranslations.Checked;
            Preferences.Current.Copy_IncludePerspectives        = chkCopyIncludePerspectives.Checked;
            Preferences.Current.Copy_IncludeRLS = chkCopyIncludeRLS.Checked;
            Preferences.Current.Copy_IncludeOLS = chkCopyIncludeOLS.Checked;

            Preferences.Current.ProxyUseSystem         = chkSystemProxy.Checked;
            Preferences.Current.ProxyAddress           = txtProxyAddress.Text;
            Preferences.Current.ProxyUser              = txtProxyUser.Text;
            Preferences.Current.ProxyPasswordEncrypted = txtProxyPassword.Text.Encrypt();
            ProxyCache.ClearProxyCache();

            Preferences.Current.SaveToFolder_Levels = new HashSet <string>();
            SaveCheckedNodes(treeView1.Nodes, Preferences.Current.SaveToFolder_Levels);
        }
Example #4
0
        /// <summary>
        /// Creates a new instance of the ApiEdit class
        /// </summary>
        /// <param name="url">Path to scripts on server</param>
        /// <param name="usePHP5"></param>
        public ApiEdit(string url, bool usePHP5)
            : this()
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("Invalid URL specified", "url");
            }
            if (!url.StartsWith("http://"))
            {
                throw new NotSupportedException("Only editing via HTTP is currently supported");
            }

            URL    = url;
            PHP5   = usePHP5;
            Maxlag = 5;

            if (ProxyCache.ContainsKey(url))
            {
                ProxySettings = ProxyCache[url];
            }
            else
            {
                ProxySettings = WebRequest.GetSystemWebProxy();
                if (ProxySettings.IsBypassed(new Uri(url)))
                {
                    ProxySettings = null;
                }
                ProxyCache.Add(url, ProxySettings);
            }
        }
Example #5
0
        private string CallDaxFormatterMulti(string uri, List <string> dax, bool useSemicolonsAsSeparators, bool shortFormat, bool skipSpaceAfterFunctionName)
        {
            try
            {
                PrimeConnection(uri);
                var originalUri = new Uri(uri);
                var actualUri   = new UriBuilder(originalUri.Scheme, redirectHost, originalUri.Port, originalUri.PathAndQuery).ToString();

                var req = new DaxFormatterRequestMulti(useSemicolonsAsSeparators, shortFormat, skipSpaceAfterFunctionName)
                {
                    Dax = dax
                };

                var data = JsonConvert.SerializeObject(req, Formatting.Indented);

                var enc   = System.Text.Encoding.UTF8;
                var data1 = enc.GetBytes(data);

                // this should allow DaxFormatter to work through http 1.0 proxies
                // see: http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
                //System.Net.ServicePointManager.Expect100Continue = false;

                var wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(actualUri);
                wr.Proxy = ProxyCache.GetProxy(actualUri);

                wr.Timeout = Preferences.Current.DaxFormatterRequestTimeout;
                wr.Method  = "POST";
                wr.Accept  = "application/json, text/javascript, */*; q=0.01";
                wr.Headers.Add("Accept-Encoding", "gzip,deflate");
                wr.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                wr.ContentType            = "application/json; charset=UTF-8";
                wr.AutomaticDecompression = DecompressionMethods.GZip;

                string output = "";
                using (var strm = wr.GetRequestStream())
                {
                    strm.Write(data1, 0, data1.Length);

                    using (var resp = wr.GetResponse())
                    {
                        //var outStrm = new System.IO.Compression.GZipStream(resp.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                        var outStrm = resp.GetResponseStream();
                        using (var reader = new System.IO.StreamReader(outStrm))
                        {
                            output = reader.ReadToEnd().Trim();
                        }
                    }
                }

                return(output);
            }
            catch
            {
                throw;
            }
            finally
            {
            }
        }
        /// <summary>
        /// Creates a new instance of type <typeparamref name="T"/> that is intercepted with the behaviors in
        /// <paramref name="interceptionBehaviors"/>.
        /// </summary>
        /// <typeparam name="T">The type of the object to create.</typeparam>
        /// <param name="interceptionBehaviors">The interception behaviors for the new proxy.</param>
        /// <param name="constructorParameters">The arguments for the creation of the new instance.</param>
        /// <returns>An instance of a class compatible with <typeparamref name="T"/> that includes execution of the
        /// given <paramref name="interceptionBehaviors"/>.</returns>
        /// <exception cref="ArgumentNullException">when <paramref name="interceptor"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="interceptionBehaviors"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">when <paramref name="interceptor"/> cannot intercept
        /// <typeparamref name="T"/>.</exception>
        public static T NewInstance <T>(IInterceptionBehavior interceptionBehavior)
            where T : class
        {
            var proxy = ProxyCache <T> .Instance();

            ((IInterceptingProxy)proxy).AddInterceptionBehavior(interceptionBehavior);
            return(proxy);
        }
 public ProxyFactory(IProxyMethodBuilder proxyMethodBuilder)
 {
     if (proxyMethodBuilder == null)
     {
         throw new ArgumentNullException("proxyMethodBuilder");
     }
     ProxyMethodBuilder = proxyMethodBuilder;
     Cache = new ProxyCache();
 }
Example #8
0
        public void ProxyMainLogic_Process_SendDataToRealDistributor()
        {
            var queue = new QueueConfiguration(1, 1000);

            var server1   = new ServerId("localhost", 21171);
            var server2   = new ServerId("localhost", 21172);
            var server3   = new ServerId("localhost", 21173);
            var netconfig = new ConnectionConfiguration("testService", 10);

            TestHelper.OpenDistributorHost(server1, netconfig);
            TestHelper.OpenDistributorHost(server2, netconfig);

            var net = new ProxyNetModule(netconfig,
                                         new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout));
            var distributor = new ProxyDistributorModule(new AsyncProxyCache(TimeSpan.FromMinutes(100)), net, queue, server1,
                                                         new AsyncTasksConfiguration(TimeSpan.FromDays(1)),
                                                         new AsyncTasksConfiguration(TimeSpan.FromDays(1)));

            net.SetDistributor(distributor);

            var cache = new ProxyCache(TimeSpan.FromSeconds(20));
            var main  = new ProxyMainLogicModule(distributor, net, cache);

            net.Start();

            distributor.Start();

            distributor.SayIAmHere(server1);
            distributor.SayIAmHere(server2);
            distributor.SayIAmHere(server3);

            cache.Start();
            main.Start();

            const string hash = "";
            var          ev   = new InnerData(new Transaction("", ""));

            ev.Transaction = distributor.CreateTransaction(hash);
            ev.Transaction = distributor.CreateTransaction(hash);
            ev.Transaction = distributor.CreateTransaction(hash);

            ev.Transaction.Destination = new List <ServerId> {
                server1
            };

            bool res = main.Process(ev);

            var server = cache.Get(ev.Transaction.EventHash);

            Assert.IsNull(server);
            Assert.IsTrue(res);

            main.Dispose();
            distributor.Dispose();
            net.Dispose();
        }
Example #9
0
 public void Disconnect()
 {
     if (Connected)
     {
         Channel?.DisconnectAsync();
         Connected = false;
         Channel   = null;
         ProxyCache.Clear();
     }
 }
Example #10
0
 public ProxyMainLogicModule(ProxyDistributorModule distributorModule, IProxyNetModule net,
                             ProxyCache proxyCache)
 {
     Contract.Requires(distributorModule != null);
     Contract.Requires(net != null);
     Contract.Requires(proxyCache != null);
     _net         = net;
     _distributor = distributorModule;
     _cache       = proxyCache;
 }
Example #11
0
            internal T GetProxy <T>(T target, ILogger <InvokerDirectory> logger)
            {
                var invoker     = _invoker;
                var localTarget = target;
                var localLogger = logger;

                var proxy = _proxies.GetOrAdd(typeof(T), (type) => ProxyCache <T> .CreateProxy(localTarget, invoker, localLogger));

                return((T)proxy);
            }
Example #12
0
 public PKEventHandler(ProxyService proxy, ILogger logger, IMetrics metrics, DiscordShardedClient client, DbConnectionFactory connectionFactory, ILifetimeScope services, CommandTree tree, Scope sentryScope, ProxyCache cache)
 {
     _proxy             = proxy;
     _logger            = logger;
     _metrics           = metrics;
     _client            = client;
     _connectionFactory = connectionFactory;
     _services          = services;
     _tree        = tree;
     _sentryScope = sentryScope;
     _cache       = cache;
 }
Example #13
0
        /// <summary>
        /// Imports reomote service.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Import <T>() where T : class
        {
            if (ProxyCache.TryGetValue(typeof(T), out object service))
            {
                return(service as T);
            }

            T newService = _generator.CreateInterfaceProxyWithoutTarget <T>(Interceptor);

            ProxyCache[typeof(T)] = newService;

            return(newService);
        }
Example #14
0
        public void GetUserConfiguredProxyReturnsNullIfValueIsNotFoundInEnvironmentOrSettings()
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }
Example #15
0
        public void GetUserConfiguredProxyReturnsNullIfValueIsNotFoundInEnvironmentOrSettings()
        {
            // Arrange
            var settings = Mock.Of<ISettings>();
            var environment = Mock.Of<IEnvironmentVariableReader>();
            var proxyCache = new ProxyCache(settings, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }
Example #16
0
        public void GetUserConfiguredProxy_IgnoresNullOrEmptyHostValuesInSetting(string host)
        {
            // Arrange
            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy", false)).Returns(host);
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }
Example #17
0
        public static string GetUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Proxy   = ProxyCache.GetProxy(url);
            request.Timeout = 10000;
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(reader.ReadToEnd());
                    }
        }
        internal static void Initialize()
        {
            proxyCache         = new ProxyCache();
            credentialProvider = AddinManager.GetExtensionObjects <ICredentialProvider> (WebCredentialProvidersPath).FirstOrDefault();

            if (credentialProvider != null)
            {
                credentialProvider = new CachingCredentialProvider(credentialProvider);
            }
            else
            {
                LoggingService.LogWarning("No proxy credential provider was found");
                credentialProvider = new NullCredentialProvider();
            }
        }
Example #19
0
        public void GetUserConfiguredProxyIgnoresNullOrEmptyHostValuesInSetting(string host)
        {
            // Arrange
            var settings = new Mock<ISettings>(MockBehavior.Strict);
            settings.Setup(s => s.GetValue("config", "http_proxy")).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user")).Returns("user");
            settings.Setup(s => s.GetValue("config", "http_proxy.password")).Returns(_password);
            var environment = Mock.Of<IEnvironmentVariableReader>();
            var proxyCache = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }
        internal static void Initialize()
        {
            proxyCache = new ProxyCache();
            //credentialProvider = AddinManager.GetExtensionObjects<ICredentialProvider> (WebCredentialProvidersPath).FirstOrDefault ();
            credentialProvider = new MacProxyCredentialProvider();

            if (credentialProvider != null)
            {
                credentialProvider = new CachingCredentialProvider(credentialProvider);
            }
            else
            {
                Console.WriteLine("No proxy credential provider was found");
                credentialProvider = new NullCredentialProvider();
            }
        }
Example #21
0
        public void GetUserConfiguredProxyReadsCredentialsFromEnvironmentVariable(string input, string host, string username, string password)
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns(input);

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            AssertProxy(new { Host = host, User = username, Password = password }, proxy);
        }
Example #22
0
        public void GetUserConfiguredProxyReadsHostFromEnvironmentVariable()
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns("http://localhost:8081");

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Equal("http://localhost:8081/", proxy.Address.OriginalString);
        }
Example #23
0
        public void GetUserConfiguredProxyIgnoresEnvironmentVariableIfNotValid(string proxyValue)
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns(proxyValue);

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }
Example #24
0
        public void GetUserConfiguredProxy_ReadsHostFromEnvironmentVariable()
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns("http://localhost:8081");
            environment.Setup(s => s.GetEnvironmentVariable("no_proxy")).Returns("");

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy("http://localhost:8081/", null, null, proxy);
        }
Example #25
0
        public void GetUserConfiguredProxyReadsProxyValuesFromSettings()
        {
            // Arrange
            string host = "http://127.0.0.1";
            string user = "******";
            var settings = new Mock<ISettings>(MockBehavior.Strict);
            settings.Setup(s => s.GetValue("config", "http_proxy")).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user")).Returns(user);
            settings.Setup(s => s.GetValue("config", "http_proxy.password")).Returns(_password);
            var environment = Mock.Of<IEnvironmentVariableReader>();
            var proxyCache = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            AssertProxy(new { Host = host, User = user, Password = "******" }, proxy);
        }
Example #26
0
        public void GetUserConfiguredProxy_ReadsCredentialsFromEnvironmentVariable(string input, string host, string username, string password, string[] bypassedAddresses)
        {
            // Arrange
            var settings    = Mock.Of <ISettings>();
            var environment = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns(input);
            environment.Setup(s => s.GetEnvironmentVariable("no_proxy")).Returns(string.Join(",", bypassedAddresses));

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy(host, username, password, proxy);
            Assert.Equal(bypassedAddresses, proxy.BypassList);
        }
Example #27
0
        public void GetUserConfiguredProxyDoesNotSetProxyCredentialsIfNullOrEmptyInSettings()
        {
            // Arrange
            string host = "http://127.0.0.1";
            var settings = new Mock<ISettings>(MockBehavior.Strict);
            settings.Setup(s => s.GetValue("config", "http_proxy")).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user")).Returns<string>(null);
            settings.Setup(s => s.GetValue("config", "http_proxy.password")).Returns<string>(null);
            var environment = Mock.Of<IEnvironmentVariableReader>();
            var proxyCache = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Equal(host, proxy.Address.OriginalString);
            Assert.Null(proxy.Credentials);
        }
Example #28
0
        public void GetUserConfiguredProxy_IfNullOrEmptyInSettings_DoesNotSetProxyCredentials()
        {
            // Arrange
            var host     = "http://127.0.0.1";
            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetSection("config"))
            .Returns(new VirtualSettingSection("config",
                                               new AddItem("http_proxy", host)));

            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy(host, null, null, proxy);
        }
Example #29
0
        public void GetUserConfiguredProxyDoesNotSetProxyCredentialsIfNullOrEmptyInSettings()
        {
            // Arrange
            var host     = "http://127.0.0.1";
            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy", false)).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user", false)).Returns <string>(null);
            settings.Setup(s => s.GetValue("config", "http_proxy.password", false)).Returns <string>(null);
            settings.Setup(s => s.GetValue("config", "no_proxy", false)).Returns("");
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy(host, null, null, proxy);
        }
Example #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            logger.LogInformation("Starting up Proxy server {MachineName}", Environment.MachineName);

            app.UseRouting();
            app.UseEndpoints(endpoints => endpoints.MapMetrics());

            app.UseGrpcServer("0.0.0.0", 90)
            .MapService(ProxyCache.BindService(app.ApplicationServices.CreateScope().ServiceProvider.GetService <CachingService>()))
            .Start();



            app.GetGrpcPipelineBuilder()
            .UseExceptionHandler((context, ex) =>
            {
                logger.LogError(ex, "Error grpc service method: {Method} message: {Message}", context.Method, ex.Message);
            });
        }
Example #31
0
        public void GetUserConfiguredProxyReadsProxyValuesFromSettings()
        {
            // Arrange
            var host     = "http://127.0.0.1";
            var user     = "******";
            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy", false)).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user", false)).Returns(user);
            settings.Setup(s => s.GetValue("config", "http_proxy.password", false)).Returns(_password);
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            AssertProxy(new { Host = host, User = user, Password = "******" }, proxy);
        }
Example #32
0
        public void GetUserConfiguredProxyDoesNotSetProxyCredentialsIfNullOrEmptyInSettings()
        {
            // Arrange
            string host     = "http://127.0.0.1";
            var    settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy")).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user")).Returns <string>(null);
            settings.Setup(s => s.GetValue("config", "http_proxy.password")).Returns <string>(null);
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Equal(host, proxy.Address.OriginalString);
            Assert.Null(proxy.Credentials);
        }
Example #33
0
        static void Main(string[] args)
        {
            ProxyCache cache = new ProxyCache();
            URL        url   = new URL("electron://127.0.0.1:13187/");
            FileNode   node  = cache.GetProxy(url);

            string path = node.CreateDirectory("electron", "hailg");

            path = node.CreateDirectory("electron", path, "tieuchau");
            string filePath = node.CreateFile("muon chut.xxx", path, true);

            node.WriteChunk(filePath, new byte[] { 1, 2, 3, 4, 5, 6 });

            byte[] arr1 = node.ReadChunk(filePath, 0, 3);
            Console.WriteLine(arr1.Length);
            arr1 = node.ReadAll(filePath);
            Console.WriteLine(arr1.Length);

            Console.ReadLine();
        }
Example #34
0
        public void GetUserConfiguredProxy_OnWindows_ReadsCredentialsFromSettings()
        {
            // Arrange
            var host = "http://127.0.0.1";
            var user = "******";
            var encryptedPassword = EncryptionUtility.EncryptString("password");
            var settings          = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy", false)).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user", false)).Returns(user);
            settings.Setup(s => s.GetValue("config", "http_proxy.password", false)).Returns(encryptedPassword);
            settings.Setup(s => s.GetValue("config", "no_proxy", false)).Returns("");
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy(host, user, "password", proxy);
        }
Example #35
0
        public void GetUserConfiguredProxyReadsHostFromEnvironmentVariable()
        {
            // Arrange
            var settings = Mock.Of<ISettings>();
            var environment = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict);
            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns("http://localhost:8081");

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Equal("http://localhost:8081/", proxy.Address.OriginalString);
        }
Example #36
0
        public void GetUserConfiguredProxyReadsCredentialsFromEnvironmentVariable(string input, string host, string username, string password)
        {
            // Arrange
            var settings = Mock.Of<ISettings>();
            var environment = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict);
            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns(input);

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            AssertProxy(new { Host = host, User = username, Password = password }, proxy);
        }
Example #37
0
        public void GetUserConfiguredProxyIgnoresEnvironmentVariableIfNotValid(string proxyValue)
        {
            // Arrange
            var settings = Mock.Of<ISettings>();
            var environment = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict);
            environment.Setup(s => s.GetEnvironmentVariable("http_proxy")).Returns(proxyValue);

            var proxyCache = new ProxyCache(settings, environment.Object);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy();

            // Assert
            Assert.Null(proxy);
        }