Пример #1
0
        private object ReverseObject(object src)
        {
            object      retVal = src;
            ProxyResult prs    = src as ProxyResult;

            if (prs != null)
            {
                var fx = new Func <string, IObjectProxy>(s =>
                {
                    IObjectProxy retObj = null;
                    if (!CustomProxy.IsProxyAvailable(prs.Type))
                    {
                        ObjectProxy proxy = CreateProxyInternal(s, prs.Type);
                        retObj            = proxy.ActLike <IObjectProxy>(prs.Type);
                    }
                    else
                    {
                        retObj = CustomProxy.GetCustomProxy(prs.Type, this, s);
                    }

                    return(retObj);
                });

                retVal = abandonnableProxies.AddOrUpdate(prs.UniqueName, fx, (s, o) => o ?? fx(s));
            }

            return(retVal);
        }
Пример #2
0
        /// <summary>
        /// Gets a value indicating if a proxy of the specified type can be generated and sets the generated proxy
        /// to the out parameter if it can.
        /// </summary>
        /// <param name="typeToProxy">The type to generate a proxy for.</param>
        /// <param name="fakeObject">The generated proxy must implement the IFakedProxy interface and this is the fake object
        /// that should be returned for the call to GetFakeObject().</param>
        /// <param name="argumentsForConstructor">Arguments to use for the constructor of the proxied type.</param>
        /// <returns>True if the proxy could be generated.</returns>
        /// <exception cref="ArgumentException">The arguments in argumentsForConstructor does not match any constructor
        /// of the proxied type.</exception>
        public ProxyResult GenerateProxy(Type typeToProxy, FakeObject fakeObject, IEnumerable<object> argumentsForConstructor)
        {
            ProxyResult result = null;

            if (!this.TryGenerateProxy(typeToProxy, fakeObject, argumentsForConstructor, out result))
            {
                result = new DynamicProxyResult(typeToProxy, string.Empty);
            }
            
            return result;
        }
Пример #3
0
        /// <summary>
        /// Gets a value indicating if a proxy of the specified type can be generated and sets the generated proxy
        /// to the out parameter if it can.
        /// </summary>
        /// <param name="typeToProxy">The type to generate a proxy for.</param>
        /// <param name="fakeObject">The generated proxy must implement the IFakedProxy interface and this is the fake object
        /// that should be returned for the call to GetFakeObject().</param>
        /// <param name="container">A fake object container the proxy generator can use to get arguments for constructor.</param>
        /// <returns>True if the proxy could be generated.</returns>
        /// <exception cref="ArgumentException">The arguments in argumentsForConstructor does not match any constructor
        /// of the proxied type.</exception>
        public ProxyResult GenerateProxy(Type typeToProxy, FakeObject fakeObject, IFakeObjectContainer container)
        {
            ProxyResult result = null;

            if (!this.TryGenerateProxy(typeToProxy, fakeObject, container, out result))
            {
                result = new DynamicProxyResult(typeToProxy, string.Empty);
            }
            
            return result;
        }
Пример #4
0
        private object PrepareProxyRequest(object obj)
        {
            object retVal = obj;
            var    packed = obj as TypedParam;
            var    proxy  = (packed?.GetValue(null) ?? obj) as IObjectProxy;

            if (proxy != null)
            {
                retVal = new ProxyResult {
                    UniqueName = proxy.ObjectName
                };
            }

            return(retVal);
        }
Пример #5
0
            /// <summary>
            /// Tries to generate a proxy for the specified type. If the type is an interface
            /// a proxy is generated and returned. If the type is a class the request will try
            /// to find the best suited constructor to use and resolve arguments to use with this constructor.
            /// </summary>
            /// <param name="typeToProxy">The type to proxy.</param>
            /// <param name="fakeObject">The fake object.</param>
            /// <param name="result">The result.</param>
            /// <returns>A value indicating if the proxy was generated or not.</returns>
            public bool TryGenerateProxy(Type typeToProxy, FakeObject fakeObject, out ProxyResult result)
            {
                if (!TypeCanBeProxied(typeToProxy))
                {
                    result = null;
                    return false;
                }

                if (typeToProxy.IsInterface)
                {
                    result = GenerateInterfaceProxy(typeToProxy, fakeObject);
                    return true;
                }

                return TryResolveConstructorAndGenerateProxy(typeToProxy, fakeObject, out result);
            }
        public async Task Should_not_match_any_rule()
        {
            var         matched = false;
            ProxyResult result  = null;

            _proxyOptions.Reporter = r => result = r;
            _rules.Add(new ProxyRule {
                Matcher  = (uri, context) => false,
                Modifier = (msg, user) => { matched = true; }
            });
            await _proxy.Invoke(_context);

            Assert.IsFalse(matched);
            Assert.IsNotNull(result);
            Assert.AreEqual(ProxyStatus.NotProxied, result.ProxyStatus);
            Assert.AreEqual(_request.Uri, result.OriginalUri);
        }
        public async Task Should_call_reporter_when_request_is_proxied()
        {
            var         targetUri = new Uri("http://myotherserver.com/api/user");
            ProxyResult result    = null;

            _rules.Add(new ProxyRule {
                Matcher  = (uri, context) => uri.AbsolutePath.Contains("api"),
                Modifier = (msg, user) => { msg.RequestUri = targetUri; }
            });
            _proxyOptions.Reporter = r => result = r;
            await _proxy.Invoke(_context);

            Assert.IsNotNull(result);
            Assert.AreEqual(ProxyStatus.Proxied, result.ProxyStatus);
            Assert.AreEqual(_request.Uri, result.OriginalUri);
            Assert.AreEqual(targetUri, result.ProxiedUri);
        }
Пример #8
0
        private ProxyResult GetBufferFor(object value, Type interfaceType, IIdentity owner)
        {
            ProxyResult r = new ProxyResult();
            string      proxyName;

            lock (extendedProxies)
            {
                nextProxyId++;
                proxyName = $"proxy_{nextProxyId}_{DateTime.Now.Ticks}_{interfaceType.Name}";
                extendedProxies.Add(proxyName, new ProxyWrapper {
                    Value = value, Owner = owner
                });
            }

            r.Type       = interfaceType;
            r.UniqueName = proxyName;
            return(r);
        }
Пример #9
0
        public ProxyResult <IEnumerable <RegionViewModel> > GetRegions(string searchString)
        {
            var regions = _appDbContext.Regions
                          .Where(x => x.RegionNameLong.Contains(searchString))
                          .ToList()
                          .Select(x =>

                                  new RegionViewModel
            {
                RegionId       = x.RegionId,
                RegionNameLong = x.RegionNameLong
            }
                                  )
                          .OrderBy(x => x.RegionNameLong.Length)
                          .ToList();

            return(ProxyResult <IEnumerable <RegionViewModel> > .Success(regions));
        }
Пример #10
0
        private object GenerateProxy(Type typeOfFake, IEnumerable <object> argumentsForConstructor)
        {
            var fakeObject = this.CreateFakeObject();

            ProxyResult result = null;

            if (argumentsForConstructor != null)
            {
                result = this.GenerateProxyWithArgumentsForConstructor(typeOfFake, argumentsForConstructor, fakeObject);
            }
            else
            {
                result = this.GenerateProxyWithoutArgumentsForConstructor(typeOfFake, fakeObject);
            }

            fakeObject.SetProxy(result);

            this.container.ConfigureFake(typeOfFake, result.Proxy);

            return(result.Proxy);
        }
        private object GenerateProxy(Type typeOfFake, IEnumerable <object> argumentsForConstructor)
        {
            var fake = this.fakeObjectFactory.Invoke();

            ProxyResult result = null;

            if (argumentsForConstructor != null)
            {
                if (!this.proxyGenerator.TryGenerateProxy(typeOfFake, fake, argumentsForConstructor, out result))
                {
                    throw new ArgumentException(ExceptionMessages.CanNotGenerateFakeMessage);
                }
            }
            else
            {
                if (!this.proxyGenerator.TryGenerateProxy(typeOfFake, fake, this.container, out result))
                {
                    throw new ArgumentException(ExceptionMessages.CanNotGenerateFakeMessage);
                }
            }

            fake.SetProxy(result);
            return(result.Proxy);
        }
        public static async Task <ProxyResult> StartAsync(TcpListener listener, bool requireAuth, bool expectCreds)
        {
            ProxyResult   result       = new ProxyResult();
            var           headers      = new Dictionary <string, string>();
            Socket        clientSocket = null;
            NetworkStream clientStream = null;
            StreamReader  clientReader = null;
            string        url          = null;
            string        method       = null;

            try
            {
                // Get and parse the incoming request.
                Func <Task> getAndReadRequest = async() => {
                    if (clientSocket != null)
                    {
                        clientSocket.Shutdown(SocketShutdown.Send);
                        clientSocket.Dispose();
                    }

                    clientSocket = await listener.AcceptSocketAsync().ConfigureAwait(false);

                    clientStream = new NetworkStream(clientSocket, ownsSocket: false);
                    clientReader = new StreamReader(clientStream, Encoding.ASCII);
                    headers.Clear();

                    var requestTokens = clientReader.ReadLine().Split(' ');
                    method = requestTokens[0];
                    url    = requestTokens[1];
                    string line;
                    while (!string.IsNullOrEmpty(line = clientReader.ReadLine()))
                    {
                        string[] headerParts = line.Split(':');
                        headers.Add(headerParts[0].Trim(), headerParts[1].Trim());
                    }
                };
                await getAndReadRequest().ConfigureAwait(false);

                // If we're expecting credentials, look for them, and if we didn't get them, send back
                // a 407 response. Optionally, process a new request that would expect credentials.
                if (requireAuth && !headers.ContainsKey("Proxy-Authorization"))
                {
                    // Send back a 407
                    await clientSocket.SendAsync(
                        new ArraySegment <byte>(Encoding.ASCII.GetBytes("HTTP/1.1 407 Proxy Auth Required\r\nProxy-Authenticate: Basic\r\n\r\n")),
                        SocketFlags.None).ConfigureAwait(false);

                    if (expectCreds)
                    {
                        // Wait for a new connection that should have an auth header this time and parse it.
                        await getAndReadRequest().ConfigureAwait(false);
                    }
                    else
                    {
                        // No credentials will be coming in a subsequent request.
                        return(default(ProxyResult));
                    }
                }

                // Store any auth header we may have for later comparison.
                string authValue;
                if (headers.TryGetValue("Proxy-Authorization", out authValue))
                {
                    result.AuthenticationHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Substring("Basic ".Length)));
                }

                if (method.Equals("CONNECT"))
                {
                    String[] tokens       = url.Split(':');
                    Socket   serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    await serverSocket.ConnectAsync(tokens[0], Int32.Parse(tokens[1])).ConfigureAwait(false);

                    NetworkStream serverStream = new NetworkStream(serverSocket);

                    // Send response to client and relay traffic in both directions.
                    await clientSocket.SendAsync(new ArraySegment <byte>(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n\r\n")),
                                                 SocketFlags.None).ConfigureAwait(false);

                    Task clientCopyTask = Task.Run(async delegate
                    {
                        byte[] buffer = new byte[8000];
                        int bytesRead;
                        while ((bytesRead = await clientStream.ReadAsync(buffer)) > 0)
                        {
                            await serverStream.WriteAsync(buffer, 0, bytesRead);
                        }
                        serverStream.Flush();
                        serverSocket.Shutdown(SocketShutdown.Send);
                    });
                    Task serverCopyTask = Task.Run(async delegate
                    {
                        byte[] buffer = new byte[8000];
                        int bytesRead;
                        while ((bytesRead = await serverStream.ReadAsync(buffer)) > 0)
                        {
                            await clientStream.WriteAsync(buffer, 0, bytesRead);
                        }
                        clientStream.Flush();
                        clientSocket.Shutdown(SocketShutdown.Send);
                    });
                    // Relay bidirectional data including close.
                    await Task.WhenAll(clientCopyTask, serverCopyTask).ConfigureAwait(false);

                    return(result);
                }

                // Forward the request to the server.
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
                using (HttpClient outboundClient = new HttpClient())
                    using (HttpResponseMessage response = await outboundClient.SendAsync(request).ConfigureAwait(false))
                    {
                        // Transfer the response headers from the server to the client.
                        var sb = new StringBuilder($"HTTP/{response.Version.ToString(2)} {(int)response.StatusCode} {response.ReasonPhrase}\r\n");
                        foreach (var header in response.Headers.Concat(response.Content.Headers))
                        {
                            sb.Append($"{header.Key}: {string.Join(", ", header.Value)}\r\n");
                        }
                        sb.Append("\r\n");
                        byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
                        await clientStream.WriteAsync(headerBytes, 0, headerBytes.Length).ConfigureAwait(false);

                        // Forward the content from the server, both to the client and to a memory stream which we'll use
                        // to return the data from the proxy.
                        var resultBody = new MemoryStream();
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        {
                            byte[] buffer    = new byte[0x1000];
                            int    bytesRead = 0;
                            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                await clientStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);

                                resultBody.Write(buffer, 0, bytesRead);
                            }
                        }

                        // Return the result
                        result.ResponseContent = resultBody.ToArray();
                        return(result);
                    }
            }
            finally
            {
                clientSocket.Shutdown(SocketShutdown.Send);
                clientSocket.Dispose();
                listener.Stop();
            }
        }
Пример #13
0
        /// <summary>
        /// Gets a value indicating if a proxy of the specified type can be generated and sets the generated proxy
        /// to the out parameter if it can.
        /// </summary>
        /// <param name="typeToProxy">The type to generate a proxy for.</param>
        /// <param name="fakeObject">The generated proxy must implement the IFakedProxy interface and this is the fake object
        /// that should be returned for the call to GetFakeObject().</param>
        /// <param name="container">A fake object container the proxy generator can use to get arguments for constructor.</param>
        /// <param name="generatedProxy">An object containing the proxy if generation was successful.</param>
        /// <returns>True if the proxy could be generated.</returns>
        /// <exception cref="ArgumentException">The arguments in argumentsForConstructor does not match any constructor
        /// of the proxied type.</exception>
        public bool TryGenerateProxy(Type typeToProxy, FakeObject fakeObject, IFakeObjectContainer container, out ProxyResult result)
        {
            if (typeToProxy.IsInterface)
            {
                result = GenerateInterfaceProxy(typeToProxy, fakeObject);
                return(true);
            }

            var argumentsForConstructor = this.ResolveConstructorArguments(typeToProxy, container);

            if (!TypeCanBeProxiedWithArgumentsForConstructor(typeToProxy, argumentsForConstructor))
            {
                result = null;
                return(false);
            }

            result = GenerateClassProxy(typeToProxy, argumentsForConstructor, fakeObject);
            return(true);
        }
Пример #14
0
        /// <summary>
        /// Gets a value indicating if a proxy of the specified type can be generated and sets the generated proxy
        /// to the out parameter if it can.
        /// </summary>
        /// <param name="typeToProxy">The type to generate a proxy for.</param>
        /// <param name="fakeObject">The generated proxy must implement the IFakedProxy interface and this is the fake object
        /// that should be returned for the call to GetFakeObject().</param>
        /// <param name="argumentsForConstructor">Arguments to use for the constructor of the proxied type.</param>
        /// <param name="generatedProxy">An object containing the proxy if generation was successful.</param>
        /// <returns>True if the proxy could be generated.</returns>
        /// <exception cref="ArgumentException">The arguments in argumentsForConstructor does not match any constructor
        /// of the proxied type.</exception>
        public bool TryGenerateProxy(Type typeToProxy, FakeObject fakeObject, IEnumerable <object> argumentsForConstructor, out ProxyResult result)
        {
            if (typeToProxy.IsInterface)
            {
                throw new ArgumentException(ExceptionMessages.ArgumentsForConstructorOnInterfaceType);
            }

            result = GenerateClassProxy(typeToProxy, argumentsForConstructor, fakeObject);
            return(true);
        }
        private ProxyResult GenerateProxyWithArgumentsForConstructor(Type typeOfFake, IEnumerable <object> argumentsForConstructor, FakeObject fake, ProxyResult result)
        {
            if (!this.proxyGenerator.TryGenerateProxy(typeOfFake, fake, argumentsForConstructor, out result))
            {
                ThrowCanNotGenerateFakeException(typeOfFake);
            }

            return(result);
        }
        private ProxyResult GenerateProxyWithoutArgumentsForConstructor(Type typeOfFake, FakeObject fake, ProxyResult result)
        {
            if (!this.proxyGenerator.TryGenerateProxy(typeOfFake, fake, this.container, out result))
            {
                ThrowCanNotGenerateFakeException(typeOfFake);
            }

            return(result);
        }
Пример #17
0
        private static async Task<ProxyResult> StartAsync(TcpListener listener, bool requireAuth, bool expectCreds)
        {
            ProxyResult result = new ProxyResult();
            var headers = new Dictionary<string, string>();
            Socket clientSocket = null;
            Stream clientStream = null;
            StreamReader clientReader = null;
            string url = null;
            try
            {
                // Get and parse the incoming request.
                Func<Task> getAndReadRequest = async () => {
                    clientSocket = await listener.AcceptSocketAsync().ConfigureAwait(false);
                    clientStream = new NetworkStream(clientSocket, ownsSocket: false);
                    clientReader = new StreamReader(clientStream, Encoding.ASCII);
                    headers.Clear();

                    url = clientReader.ReadLine().Split(' ')[1];
                    string line;
                    while (!string.IsNullOrEmpty(line = clientReader.ReadLine()))
                    {
                        string[] headerParts = line.Split(':');
                        headers.Add(headerParts[0].Trim(), headerParts[1].Trim());
                    }
                };
                await getAndReadRequest().ConfigureAwait(false);

                // If we're expecting credentials, look for them, and if we didn't get them, send back 
                // a 407 response. Optionally, process a new request that would expect credentials.
                if (requireAuth && !headers.ContainsKey("Proxy-Authorization"))
                {
                    // Send back a 407
                    await clientSocket.SendAsync(
                        new ArraySegment<byte>(Encoding.ASCII.GetBytes("HTTP/1.1 407 Proxy Auth Required\r\nProxy-Authenticate: Basic\r\n\r\n")),
                        SocketFlags.None).ConfigureAwait(false);
                    clientSocket.Shutdown(SocketShutdown.Send);
                    clientSocket.Dispose();

                    if (expectCreds)
                    {
                        // Wait for a new connection that should have an auth header this time and parse it.
                        await getAndReadRequest().ConfigureAwait(false);
                    }
                    else
                    {
                        // No credentials will be coming in a subsequent request.
                        return default(ProxyResult);
                    }
                }

                // Store any auth header we may have for later comparison.
                string authValue;
                if (headers.TryGetValue("Proxy-Authorization", out authValue))
                {
                    result.AuthenticationHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Substring("Basic ".Length)));
                }

                // Forward the request to the server.
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                foreach (var header in headers) request.Headers.Add(header.Key, header.Value);
                using (HttpClient outboundClient = new HttpClient())
                using (HttpResponseMessage response = await outboundClient.SendAsync(request).ConfigureAwait(false))
                {
                    // Transfer the response headers from the server to the client.
                    var sb = new StringBuilder($"HTTP/{response.Version.ToString(2)} {(int)response.StatusCode} {response.ReasonPhrase}\r\n");
                    foreach (var header in response.Headers.Concat(response.Content.Headers))
                    {
                        sb.Append($"{header.Key}: {string.Join(", ", header.Value)}\r\n");
                    }
                    sb.Append("\r\n");
                    byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
                    await clientStream.WriteAsync(headerBytes, 0, headerBytes.Length).ConfigureAwait(false);

                    // Forward the content from the server, both to the client and to a memory stream which we'll use
                    // to return the data from the proxy.
                    var resultBody = new MemoryStream();
                    using (Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                    {
                        byte[] buffer = new byte[0x1000];
                        int bytesRead = 0;
                        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            await clientStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                            resultBody.Write(buffer, 0, bytesRead);
                        }
                    }

                    // Return the result
                    result.ResponseContent = resultBody.ToArray();
                    return result;
                }
            }
            finally
            {
                clientSocket.Dispose();
                listener.Stop();
            }
        }
Пример #18
0
        public List <ProxyResult> InvokeService(Proxy Service, List <ProxyMember> Parameters)
        {
            List <ProxyResult> result = new List <ProxyResult>();

            var objService = Service.OutputAssembly.GetType(Service.ServiceName);
            var newobj     = Activator.CreateInstance(objService);
            var method     = objService.GetMethod(Service.MethodName);
            var retobj     = method.Invoke(newobj, MapParameters(method, Parameters));

            string retType = method.ReturnType.ToString().ToLower();

            if (retType.StartsWith("system."))
            {
                if (retType.EndsWith("[]"))
                {
                    ProxyResult member = new ProxyResult(retType);
                    foreach (var item in (Array)retobj)
                    {
                        member.Members.Add(new ProxyMember("Value", item.GetType(), item));
                    }
                    result.Add(member);
                }
                else if (retType == "system.void")
                {
                    return(result);
                }
                else
                {
                    ProxyResult member = new ProxyResult(retType);
                    member.Members.Add(new ProxyMember("Value", retobj.GetType(), retobj));
                    result.Add(member);
                }
            }
            else
            {
                if (retType.EndsWith("[]"))
                {
                    foreach (var item in (Array)retobj)
                    {
                        ProxyResult member = new ProxyResult(item.GetType());

                        foreach (var prop in item.GetType().GetProperties())
                        {
                            member.Members.Add(new ProxyMember(prop.Name, prop.PropertyType, prop.GetValue(item)));
                        }

                        result.Add(member);
                    }
                }
                else
                {
                    ProxyResult member = new ProxyResult(retType);
                    foreach (var prop in retobj.GetType().GetProperties())
                    {
                        member.Members.Add(new ProxyMember(prop.Name, prop.PropertyType, prop.GetValue(retobj)));
                    }
                    result.Add(member);
                }
            }

            return(result);
        }
Пример #19
0
            private bool TryResolveConstructorAndGenerateProxy(Type typeToProxy, FakeObject fakeObject, out ProxyResult result)
            {
                foreach (var constructor in GetUsableConstructors(typeToProxy))
                {
                    IEnumerable<object> resolvedArguments;

                    if (TryResolveConstructorArguments(constructor, out resolvedArguments))
                    {
                        try
                        {
                            result = GenerateClassProxy(typeToProxy, resolvedArguments, fakeObject);
                            return true;
                        }
                        catch (TargetInvocationException)
                        {

                        }
                    }
                }

                result = null;
                return false;
            }
Пример #20
0
        private async void btnCheck_Click(object sender, EventArgs e)
        {
            if (lvProxies.Items.Count <= 0)
            {
                return;
            }

            // Validity checks
            if (cbSSL.Checked)
            {
                if (!tbSSL.Text.StartsWith("https://"))
                {
                    MessageBox.Show("Please enter a valid HTTPS url to test!", "Form Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                try
                {
                    var url = new Uri(tbSSL.Text);
                }
                catch
                {
                    MessageBox.Show("Please enter a valid HTTPS url to test!", "Form Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            if (cbCustom.Checked)
            {
                //if (!tbCustom.Text.StartsWith("https://"))
                //{
                //    MessageBox.Show("Please enter a valid HTTPS url to test!", "Form Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    return;
                //}
                try
                {
                    var url = new Uri(tbCustom.Text);
                }
                catch
                {
                    MessageBox.Show("Please enter a valid custom url to test!", "Form Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            //UpdateStatus("Checking proxies...");
            btnCheck.Enabled = false;
            proxyChecked     = false;
            //   cmsRotator.Enabled = false;
            //  btnRotate.Enabled = false;


            var proxies = new List <ListViewItem>();

            foreach (ListViewItem item in lvProxies.Items)
            {
                proxies.Add(item);
            }

            var options = new ParallelOptions {
                MaxDegreeOfParallelism = 50
            };

            await Task.Run(() =>
            {
                try
                {
                    Parallel.ForEach(proxies, options, proxy =>
                    {
                        string[] prox = proxy.SubItems[1].Text.Split(new[] { ":" }, StringSplitOptions.None);
                        ProxyResult r = Checker.Checker.Check(
                            new WebProxy(prox[0], int.Parse(prox[1])),
                            int.Parse(prox[1]),
                            cbSSL.Checked ? tbSSL.Text : "",
                            cbCustom.Checked ? tbCustom.Text : ""
                            );

                        Invoke(new MethodInvoker(() =>
                        {
                            if (!r.Working || r.Speed > 10000)
                            {
                                //if (dead || (cbSlow.Checked && speed > 10000))
                                lvProxies.Items[proxy.Index].BackColor = Color.FromArgb(255, 207, 206);
                            }
                            else
                            {
                                lvProxies.Items[proxy.Index].SubItems[2].Text = r.Anonymity;
                                lvProxies.Items[proxy.Index].SubItems[3].Text = r.CountryInfo[1];

                                var countryCode = CountryInfo.GetCode(r.CountryInfo[1]);

                                if (!imageList.Images.Keys.Contains(countryCode))
                                {
                                    imageList.Images.Add(countryCode, Image.FromFile(@"Flags\" + countryCode + ".png"));
                                }
                                lvProxies.Items[proxy.Index].ImageKey = countryCode;

                                lvProxies.Items[proxy.Index].SubItems[4].Text = r.Speed + " ms";
                                if (cbSSL.Checked)
                                {
                                    lvProxies.Items[proxy.Index].SubItems[5].Text      = r.SSL ? "Yes" : "No";
                                    lvProxies.Items[proxy.Index].SubItems[5].ForeColor = r.SSL ? Color.DarkGreen : Color.Red;
                                }
                                else
                                {
                                    lvProxies.Items[proxy.Index].SubItems[5].Text = "N\\A";
                                }

                                if (cbCustom.Checked)
                                {
                                    lvProxies.Items[proxy.Index].SubItems[6].Text      = r.Custom ? "Yes" : "No";
                                    lvProxies.Items[proxy.Index].SubItems[6].ForeColor = r.Custom ? Color.DarkGreen : Color.Red;
                                }
                                else
                                {
                                    lvProxies.Items[proxy.Index].SubItems[6].Text = "N\\A";
                                }

                                lvProxies.Items[proxy.Index].BackColor = Color.FromArgb(202, 255, 202);
                            }
                        }));
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            });


            //lProxyCount.Text = "Loaded Proxies: " + lvProxies.Items.Count;
            //UpdateStatus("Finished checking proxies.");
            btnCheck.Enabled = true;
            proxyChecked     = true;
            //cmsRotator.Enabled = true;
            //btnRotate.Enabled = true;
        }
Пример #21
0
 /// <summary>
 /// Gets a value indicating if a proxy of the specified type can be generated and sets the generated proxy
 /// to the out parameter if it can.
 /// </summary>
 /// <param name="typeToProxy">The type to generate a proxy for.</param>
 /// <param name="fakeObject">The generated proxy must implement the IFakedProxy interface and this is the fake object
 /// that should be returned for the call to GetFakeObject().</param>
 /// <param name="container">A fake object container the proxy generator can use to get arguments for constructor.</param>
 /// <param name="generatedProxy">An object containing the proxy if generation was successful.</param>
 /// <returns>True if the proxy could be generated.</returns>
 /// <exception cref="ArgumentException">The arguments in argumentsForConstructor does not match any constructor
 /// of the proxied type.</exception>
 private bool TryGenerateProxy(Type typeToProxy, FakeObject fakeObject, IFakeObjectContainer container, out ProxyResult result)
 {
     var request = new ConstructorResolvingProxyGenerationRequest(container);
     return request.TryGenerateProxy(typeToProxy, fakeObject, out result);
 }