public void ClusterConnect()
 {
     while (Cluster == null)
     {
         try
         {
             Cluster = ProxyClient.Create <ICluster>(m_RemoteURI);
             if (!Information.IsNothing(Cluster))
             {
                 WorldServerConfiguration configuration = WorldServiceLocator._ConfigurationProvider.GetConfiguration();
                 if (Cluster.Connect(LocalURI, configuration.Maps.Select(_Closure_0024__._0024I13_002D0 ??= x => Conversions.ToUInteger(x)).ToList()))
                 {
                     break;
                 }
                 Cluster.Disconnect(LocalURI, configuration.Maps.Select(_Closure_0024__._0024I13_002D1 ??= x => Conversions.ToUInteger(x)).ToList());
             }
         }
         catch (Exception ex)
         {
             ProjectData.SetProjectError(ex);
             Exception e = ex;
             WorldServiceLocator._WorldServer.Log.WriteLine(LogType.FAILED, "Unable to connect to cluster. [{0}]", e.Message);
             ProjectData.ClearProjectError();
         }
         Cluster = null;
         Thread.Sleep(3000);
     }
     WorldServiceLocator._WorldServer.Log.WriteLine(LogType.SUCCESS, "Contacted cluster [{0}]", m_RemoteURI);
 }
Example #2
0
 public void SetProxy(ProxyType proxyType, string proxy)
 {
     if (proxyType != ProxyType.Http)
     {
         _proxyClient = ProxyClient.Parse(proxyType, proxy);
     }
 }
Example #3
0
        static void Worker(string combo)
        {
            try
            {
                Variables.proxyIndex = Variables.proxyIndex >= Variables.proxies.Length ? 0 : Variables.proxyIndex;
                var proxy       = Variables.proxies[Variables.proxyIndex];
                var credentials = combo.Split(new char[] { ':', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);
                using (var req = new HttpRequest()
                {
                    KeepAlive = true,
                    IgnoreProtocolErrors = true,
                    Proxy = ProxyClient.Parse(proxyType, proxy)
                })
                {
                    req.Proxy.ConnectTimeout            = proxyTimeout;
                    req.SslCertificateValidatorCallback = (RemoteCertificateValidationCallback)Delegate.Combine(req.SslCertificateValidatorCallback,
                                                                                                                new RemoteCertificateValidationCallback((object obj, X509Certificate cert, X509Chain ssl, SslPolicyErrors error) => (cert as X509Certificate2).Verify()));

                    string check = req.Post("https://portalapi.afterpay.com/portal/consumers/auth/reset/check-email-option-eligibility", "{\"email\":\"" + credentials[0] + "\"}", "application/json").ToString();
                    if (check.Contains("shouldDisableEmailOption\" : false") || check.Contains("shouldDisableEmailOption\" : true"))
                    {
                        Variables.Valid++;
                        Variables.Checked++;
                        Variables.cps++;
                        lock (Variables.WriteLock)
                        {
                            Variables.remove(combo);
                            if (Config.kekr_UI == "LOG")
                            {
                                Console.WriteLine($"[+] {combo}", Color.Green);
                            }
                            File.AppendAllText(Variables.results + "Registered.txt", combo + Environment.NewLine);
                        }
                    }
                    else if (check.Contains("not_found"))
                    {
                        Variables.Invalid++;
                        Variables.Checked++;
                        Variables.cps++;
                        lock (Variables.WriteLock)
                        {
                            Variables.remove(combo);
                            File.AppendAllText(Variables.results + "Not Registered.txt", combo + Environment.NewLine);
                        }
                    }
                    else
                    {
                        Variables.combos.Enqueue(combo);
                        Variables.proxyIndex++;
                        Variables.Errors++;
                    }
                }
            }
            catch
            {
                Variables.combos.Enqueue(combo);
                Variables.proxyIndex++;
                Variables.Errors++;
            }
        }
Example #4
0
 protected void FinishConfig()
 {
     if (Config.Proxy != null)
     {
         Proxy = Config.Proxy.CreateProxyClient();
     }
 }
Example #5
0
        private ProxyClient RandomProxy()
        {
            string proxy = _proxies[_random.Next(_proxies.Length)];

            ProxyType type = ProxyType.HTTP;

            if (_proxyType.ToLower() == "http")
            {
                type = ProxyType.HTTP;
            }
            else if (_proxyType.ToLower() == "socks4")
            {
                type = ProxyType.Socks4;
            }
            else if (_proxyType.ToLower() == "socks5")
            {
                type = ProxyType.Socks5;
            }

            bool result = ProxyClient.TryParse(type, proxy, out ProxyClient client);

            if (result)
            {
                return(client);
            }
            else
            {
                return(null);
            }
        }
Example #6
0
 public void SetProxy(ProxyClient proxyClient)
 {
     if (proxyClient?.Type != ProxyType.Http)
     {
         _proxyClient = proxyClient;
     }
 }
        private void GetTicket_Click(object sender, EventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    var NMP = Helper.Proxy();

                    if (NMP.Length > 0)
                    {
                        var proxyClient = ProxyClient.Parse(ProxyType.Http, NMP);
                        req.Proxy       = proxyClient;
                    }

                    req.AddHeader("Accept", "application/json");
                    req.AddHeader("Authorization", string.Format("Bearer {0}", Helper.token(MyStrings.AutoLogin, Form1.token)));
                    string text = req.Get("https://edge.qiwi.com/payment-history/v2/persons/" + PNum.Text + "/payments?rows=10", null).ToString();
                    req.Close();

                    myjs.RootObject newQiwi = JsonConvert.DeserializeObject <myjs.RootObject>(text);

                    richTextBox1.Text += "<Чеки>" + Environment.NewLine;
                    foreach (var ck in newQiwi.data)
                    {
                        richTextBox1.Text += $"ID операции: {ck.trmTxnId}\r\nСтатус: {ck.statusText}\r\nСумма: {ck.sum.amount} {ck.sum.MSC()}\r\nТип: {ck.MS() + ck.mcomment()}\r\n----------------------\r\n";
                    }
                });
            }
            catch (Exception ex)
            {
                File.WriteAllText(MyStrings.MFolder + "Log " + DateTime.Now + ".txt", ex.ToString());
            }
        }
        /// <summary>
        /// Deliver to distribution.
        /// </summary>
        private PluginExecutionResult DeliverToDistribution()
        {
            PluginExecutionResult result = new PluginExecutionResult(PluginResult.Passed);

            UpdateStatus("Deliver to Distribution");

            _runtimeOriginator = _activityData.SendToDistribution.Originator;
            _runtimeRecipients = new Collection <string>()
            {
                _activityData.SendToDistribution.DistributionTitle
            };

            SetRuntimeData();
            PopulateExecutionControls();

            foreach (var doc in _runtimeDocumentPaths)
            {
                foreach (var recipient in _runtimeRecipients)
                {
                    // Lock the document pool so that we don't get conflicts with other users.
                    ExecutionServices.CriticalSection.Run(new LocalLockToken("LocalDocument", new TimeSpan(0, 5, 0), new TimeSpan(0, 5, 0)), () =>
                    {
                        ProxyClient.DeliverToDistribution(_pluginExecutionData.Servers.First().Address, doc, _runtimeOriginator, recipient);
                    });
                }
            }


            return(result);
        }
Example #9
0
        public static string Get(string Link, string Proxy) //Leaf.xNet.HttpException
        {
            HttpRequest request = new HttpRequest();

            request.KeepAlive = true;
            request.UserAgentRandomize();
            try
            {
                request.Proxy = ProxyClient.Parse(ProxyType.Socks5, Proxy);
                request.Get(Link).ToString();
            }
            catch
            {
                request.Proxy = ProxyClient.Parse(ProxyType.Socks4, Proxy);
            }

            //Httpresponse и проверять значение, вместо параши снизу
            string response = "";

            try
            {
                request.Get(Link).ToString();
                response = "ok";
            }
            catch (HttpException err)
            {
                response = err.Message;
            }
            return(response);
        }
Example #10
0
 void Initialize()
 {
     m_client = ProxyClient.GetPhasorDataServiceProxyClient();
     m_client.GetNodeListCompleted  += new EventHandler <GetNodeListCompletedEventArgs>(client_GetNodeListCompleted);
     m_client.GetCompaniesCompleted += new EventHandler <GetCompaniesCompletedEventArgs>(client_GetCompaniesCompleted);
     m_client.SaveNodeCompleted     += new EventHandler <SaveNodeCompletedEventArgs>(client_SaveNodeCompleted);
 }
Example #11
0
        private static List <ProxyClient> getProxiesFromFile(ProxyType type, string fileName)
        {
            List <ProxyClient> proxiesList = new List <ProxyClient>();

            foreach (var line in File.ReadAllLines(fileName))
            {
                ProxyClient client;

                try
                {
                    client = ProxyClient.Parse(type, line.Trim());
                }

                catch (Exception)
                {
                    continue;
                }

                if (!proxiesList.Contains(client))
                {
                    proxiesList.Add(client);
                }
            }

            return(proxiesList);
        }
 public void ClusterConnect()
 {
     while (Cluster == null)
     {
         try
         {
             Cluster = ProxyClient.Create <ICluster>(m_RemoteURI);
             if (Cluster != null)
             {
                 var configuration = WorldServiceLocator._ConfigurationProvider.GetConfiguration();
                 if (Cluster.Connect(LocalURI, configuration.Maps.Select(x => Conversions.ToUInteger(x)).ToList()))
                 {
                     break;
                 }
                 Cluster.Disconnect(LocalURI, configuration.Maps.Select(x => Conversions.ToUInteger(x)).ToList());
             }
         }
         catch (Exception ex)
         {
             var e = ex;
             WorldServiceLocator._WorldServer.Log.WriteLine(LogType.FAILED, "Unable to connect to cluster. [{0}]", e.Message);
         }
         Cluster = null;
         Thread.Sleep(3000);
     }
     WorldServiceLocator._WorldServer.Log.WriteLine(LogType.SUCCESS, "Contacted cluster [{0}]", m_RemoteURI);
 }
Example #13
0
        public static void CC(string type, string NumCard, string Sum)
        {
            HttpRequest req = new HttpRequest();

            DateTime foo      = DateTime.UtcNow;
            long     unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
            var      idt      = 1000 * unixTime;

            var NMP = Helper.Proxy();

            if (NMP.Length > 0)
            {
                var proxyClient = ProxyClient.Parse(ProxyType.Http, NMP);
                req.Proxy = proxyClient;
            }

            req.AddHeader("Authorization", "Bearer " + token);
            string json = "{\"id\":\"" + idt + "\",\"sum\":{\"amount\":" + Sum + ", \"currency\":\"643\"}, \"paymentMethod\":{\"type\":\"Account\", \"accountId\":\"643\"}, \"fields\":{\"account\":\"" + NumCard + "\"}}";

            string url     = "https://edge.qiwi.com/sinap/api/v2/terms/" + type + "/payments";
            string content = req.Post(url, json, "application/json").ToString();

            req.Close();
            Console.WriteLine(content);
        }
Example #14
0
 public IaonTree()
 {
     InitializeComponent();
     m_client = ProxyClient.GetPhasorDataServiceProxyClient();
     m_client.GetIaonTreeDataCompleted += new EventHandler <GetIaonTreeDataCompletedEventArgs>(client_GetIaonTreeDataCompleted);
     Loaded += new RoutedEventHandler(IaonTree_Loaded);
 }
Example #15
0
 void Initialize()
 {
     m_duplexClient = ProxyClient.GetDuplexServiceProxyClient();
     m_duplexClient.SendToServiceCompleted += new EventHandler <System.ComponentModel.AsyncCompletedEventArgs>(m_duplexClient_SendToServiceCompleted);
     m_duplexClient.SendToClientReceived   += new EventHandler <SendToClientReceivedEventArgs>(m_duplexClient_SendToClientReceived);
     m_numberOfMessagesOnMonitor            = IsolatedStorageManager.LoadFromIsolatedStorage("NumberOfMessagesOnMonitor") == null ? 50 : Convert.ToInt32(IsolatedStorageManager.LoadFromIsolatedStorage("NumberOfMessagesOnMonitor"));
 }
        public int ProxyChecker(ProxyType proxyType, IEnumerable <String> proxies, int proxyTimeout, int threads)
        {
            int correctProxy   = 0;
            var requestTimeout = 5 * 1000;

            File.Delete("../../../GoodProxy.txt");
            Parallel.ForEach(proxies, new ParallelOptions()
            {
                MaxDegreeOfParallelism = threads
            }, proxy =>
            {
                try
                {
                    using (var request = new HttpRequest())
                    {
                        request.ConnectTimeout       = requestTimeout;
                        request.Proxy                = ProxyClient.Parse(proxyType, proxy);
                        request.Proxy.ConnectTimeout = proxyTimeout;
                        request.UserAgent            = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
                        request.Get("http://google.com");
                        Console.WriteLine("[Good Proxy] " + proxy);
                        checkedProxy.Add(proxy);
                        correctProxy = correctProxy + 1;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("[Bad Proxy] " + proxy);
                }
            });
            SaveFile(checkedProxy, "../../../GoodProxy.txt");
            return(correctProxy);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ActiveConnections"/> class.
        /// </summary>
        public ActiveConnections()
        {
            this.InitializeComponent();
            this.defaultProcessIcon =
                new BitmapImage(
                    new Uri(
                        "pack://application:,,,/PeaRoxy.Windows.WPFClient;component/Images/SettingsPanel/Process_def.png"));
            this.connectionContextMenu = new ContextMenu();
            MenuItem menuItem = new MenuItem {
                Header = "Close this connection"
            };

            menuItem.Click += (RoutedEventHandler) delegate
            {
                TreeViewItem placementTarget = this.connectionContextMenu.PlacementTarget as TreeViewItem;
                if (placementTarget == null)
                {
                    return;
                }

                try
                {
                    ProxyClient client = placementTarget.Tag as ProxyClient;
                    if (client != null)
                    {
                        client.Close("Closed By User");
                    }
                }
                catch
                {
                }
            };

            this.connectionContextMenu.Items.Add(menuItem);
            menuItem = new MenuItem {
                Header = "Copy"
            };
            menuItem.Click += (RoutedEventHandler) delegate
            {
                TreeViewItem placementTarget = this.connectionContextMenu.PlacementTarget as TreeViewItem;
                if (placementTarget == null)
                {
                    return;
                }

                try
                {
                    ProxyClient client = placementTarget.Tag as ProxyClient;
                    if (client != null)
                    {
                        Clipboard.SetText(client.RequestAddress);
                    }
                }
                catch
                {
                }
            };

            this.connectionContextMenu.Items.Add(menuItem);
        }
Example #18
0
        public static ResponseSendSms SendSms()
        {
            using (var request = new HttpRequest())
            {
                if (!string.IsNullOrWhiteSpace(Globals.WorkingData.ProxyAdress))
                {
                    request.Proxy = ProxyClient.Parse(Globals.WorkingData.ProxyTypeLeaf, Globals.WorkingData.ProxyAdress);
                }
                try
                {
                    request.Post($"{DomainList.Youla}/web-api/auth/request_code", $"{{\"phone\":\"+{Globals.WorkingData.PhoneNumber}\"}}", "application/json").ToString();
                }
                catch
                {
                    return(new ResponseSendSms {
                        FailedConnected = !request.HttpIsConnected(), SuccessSend = false
                    });
                }

                if ((int)request.Response.StatusCode == 200)
                {
                    Globals.WorkingStats.CountSendingSms++;
                    return(new ResponseSendSms {
                        SuccessSend = true
                    });
                }
                return(new ResponseSendSms {
                    SuccessSend = false
                });
            }
        }
Example #19
0
        public static void MakeClient(xNet.Net.HttpRequest request, Proxy proxy)
        {
            ProxyType proxyType = ProxyType.Http;

            switch (proxy.ProxyProtocol)
            {
            case ProxyProtocol.HTTP:
                proxyType = ProxyType.Http;
                break;

            case ProxyProtocol.SOCKS5:
                proxyType = ProxyType.Socks5;
                break;

            case ProxyProtocol.SOCKS4:
                proxyType = ProxyType.Socks4;
                break;

            case ProxyProtocol.SOCKS4A:
                proxyType = ProxyType.Socks4a;
                break;

            default:
                System.Windows.MessageBox.Show("Не установлен тип прокси.");
                return;
            }
            //устанавливаем прокси
            ProxyClient Client = ProxyHelper.CreateProxyClient(proxyType, proxy.Ip, Convert.ToInt32(proxy.Port), proxy.Login, proxy.Pwd);

            request.Proxy = Client;
        }
Example #20
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var channel = GrpcChannel.ForAddress("http://localhost:5000");
            var client  = new ProxyClient(channel);
            // var reply = await client.GetInfoAsync(new Empty());
            // Console.WriteLine(reply.Version);
            var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1));

            using var streamingCall = client.GetStat(new Empty(), cancellationToken: cancellationTokenSource.Token);

            try
            {
                await foreach (var stat in streamingCall.ResponseStream.ReadAllAsync(cancellationToken: cancellationTokenSource.Token))
                {
                    foreach (var service in stat.Services)
                    {
                        Console.WriteLine($"{nameof(service.Name)}:{service.Name} {nameof(service.BytesIn)}:{service.BytesIn} {nameof(service.BytesOut)}:{service.BytesOut}");
                    }
                }
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
            {
                Console.WriteLine("Stream cancelled.");
            }
        }
Example #21
0
        public static ResponseSendSms SendSms()
        {
            using (var request = new HttpRequest())
            {
                if (!string.IsNullOrWhiteSpace(Globals.WorkingData.ProxyAdress))
                {
                    request.Proxy = ProxyClient.Parse(Globals.WorkingData.ProxyTypeLeaf, Globals.WorkingData.ProxyAdress);
                }
                try
                {
                    request.Post($"{DomainList.Twitch}/register?trusted_request=true", $"{{\"birthday\": {{\"day\": 15, \"month\": 6, \"year\": 1995}}, \"client_id\": \"kd1unb4b3q4t58fwlpcbzcbnm76a8fp\", \"include_verification_code\": true, \"password\": \"passtsSor@5363\", \"phone_number\": \"{Globals.WorkingData.PhoneNumber}\", \"username\": \"Dodiks5216\"}}", "application/json").ToString();
                }
                catch
                {
                    if (!request.HttpIsConnected() || (int)request.Response.StatusCode != 422)
                    {
                        return(new ResponseSendSms {
                            FailedConnected = !request.HttpIsConnected(), SuccessSend = false
                        });
                    }
                }

                if (request.Response.ToString().Contains("via SMS soon"))
                {
                    Globals.WorkingStats.CountSendingSms++;
                    return(new ResponseSendSms {
                        SuccessSend = true
                    });
                }
                return(new ResponseSendSms {
                    SuccessSend = false
                });
            }
        }
Example #22
0
        private static void Main()
        {
            try
            {
                LoadConfiguration();
            }
            catch (Exception e)
            {
                Logger.Error(e, "Parameters loading failed");
                return;
            }

            var exitEvent = new ManualResetEvent(false);

            try
            {
                Logger.Info($"Starting proxy agent for {SecuredServerHost}:{SecuredServerPort}");
                Logger.Info($"Connecting to packet server {PacketServerHost}:{PacketServerPort}");

                // ReSharper disable once UnusedVariable
                var proxyClient = new ProxyClient(SecuredServerHost, SecuredServerPort)
                {
                    PacketReceiver = new PacketClient(PacketServerHost, PacketServerPort)
                };

                exitEvent.WaitOne();
            }
            catch (Exception e)
            {
                Logger.Fatal(e);
            }
        }
Example #23
0
        public static async Task <MemoryStream> Post(this string url, byte[] data, ProxyClient webProxy = null, Dictionary <string, string> head = null)
        {
            MemoryStream      memory  = new MemoryStream();
            HttpClientHandler Handler = new HttpClientHandler {
                Proxy = webProxy
            };

            using (var client = new HttpClient(Handler))
            {
                var message = new HttpRequestMessage(HttpMethod.Post, url)
                {
                    Version = HttpVersion.Version20,
                };
                message.Content = new ByteArrayContent(data);
                message.Headers.Add("user-agent", "Mozilla/5.0 (MSIE 10.0; Windows NT 6.1; Trident/5.0)");
                if (head != null)
                {
                    foreach (var item in head)
                    {
                        message.Headers.Add(item.Key, item.Value);
                    }
                }
                var response = await client.SendAsync(message);

                if (response.IsSuccessStatusCode)
                {
                    await response.Content.CopyToAsync(memory);
                }
            }
            return(memory);
        }
Example #24
0
        public void setproxy(ref HttpRequest req)
        {
            if (this.useproxy)
            {
                if (proxylist.Count > 0)
                {
                    string proxy = proxylist[new Random().Next(0, proxylist.Count - 1)];
                    if (proxy.Length <= 0)
                    {
                        return;
                    }
                    switch (proxytype)
                    {
                    case "socks4":
                        req.Proxy = ProxyClient.Parse(ProxyType.Socks4, proxy);
                        break;

                    case "socks5":
                        req.Proxy = ProxyClient.Parse(ProxyType.Socks5, proxy);
                        break;

                    case "http":
                        req.Proxy = ProxyClient.Parse(ProxyType.HTTP, proxy);
                        break;
                    }
                }
            }
        }
        private void SaveTicket_Click(object sender, EventArgs e)
        {
            try
            {
                string cont;
                richTextBox1.Clear();

                var NMP = Helper.Proxy();

                if (NMP.Length > 0)
                {
                    var proxyClient = ProxyClient.Parse(ProxyType.Http, NMP);
                    req.Proxy = proxyClient;
                }

                req.AddHeader("Accept", "application/json");
                req.AddHeader("Authorization", string.Format("Bearer {0}", Helper.token(MyStrings.AutoLogin, Form1.token)));
                string text = req.Get("https://edge.qiwi.com/payment-history/v2/persons/" + PNum.Text + "/payments?rows=10", null).ToString();
                req.Close();

                myjs.RootObject newQiwi = JsonConvert.DeserializeObject <myjs.RootObject>(text);

                cont = "<Чеки>" + Environment.NewLine;
                foreach (var ck in newQiwi.data)
                {
                    cont += "ID операции: " + ck.trmTxnId + "\r\nСтатус: " + ck.statusText + "\r\nСумма: " + ck.sum.amount + " " + ck.sum.MSC() + "\r\nТип: " + ck.MS() + ck.mcomment() + "\r\n----------------------" + Environment.NewLine;
                }
                File.WriteAllText(Path.Combine(Application.StartupPath.ToString(), MyStrings.checks), cont);
                MessageBox.Show("Чеки были сохранены в папке с программой!");
            }
            catch (Exception ex)
            {
                File.WriteAllText(MyStrings.MFolder + "LogError.txt", ex.ToString());
            }
        }
 void Initialize()
 {
     m_client = ProxyClient.GetPhasorDataServiceProxyClient();
     m_client.GetOutputStreamMeasurementListCompleted += new EventHandler <GetOutputStreamMeasurementListCompletedEventArgs>(client_GetOutputStreamMeasurementListCompleted);
     m_client.SaveOutputStreamMeasurementCompleted    += new EventHandler <SaveOutputStreamMeasurementCompletedEventArgs>(client_SaveOutputStreamMeasurementCompleted);
     m_client.DeleteOutputStreamMeasurementCompleted  += new EventHandler <DeleteOutputStreamMeasurementCompletedEventArgs>(client_DeleteOutputStreamMeasurementCompleted);
 }
Example #27
0
        /// <summary>
        /// Gets the available routes.
        /// </summary>
        /// <returns></returns>
        private IEnumerable <Route> GetRoutes()
        {
            var testTargetUri = TestTargetUri;

            // if remote is optional, whenever we have a remote proxy configured or not,
            // the short route (local only) is returned
            if (OptionalRemoteProxy)
            {
                var shortRoute = ProxyClient.CreateRoute(LocalProxy);
                if (testTargetUri != null)
                {
                    ProxyValidator.Validate(shortRoute, testTargetUri);
                }
                yield return(shortRoute);
            }
            // then, if there is a remote proxy or it is not optional
            // (in which case we skipped the first step above)
            // the full route is returned
            if (!OptionalRemoteProxy || RemoteProxy != null)
            {
                var fullRoute = ProxyClient.CreateRoute(LocalProxy, RemoteProxy);
                if (testTargetUri != null)
                {
                    ProxyValidator.Validate(fullRoute, testTargetUri);
                }
                yield return(fullRoute);
            }
        }
 void Initialize()
 {
     m_client = ProxyClient.GetPhasorDataServiceProxyClient();
     m_client.GetVendorDeviceListCompleted += new EventHandler <GetVendorDeviceListCompletedEventArgs>(client_GetVendorDeviceListCompleted);
     m_client.GetVendorsCompleted          += new EventHandler <GetVendorsCompletedEventArgs>(client_GetVendorsCompleted);
     m_client.SaveVendorDeviceCompleted    += new EventHandler <SaveVendorDeviceCompletedEventArgs>(client_SaveVendorDeviceCompleted);
 }
Example #29
0
        static void Main(string[] args)
        {
            Console.Write("Video id: ");
            string videoid = Console.ReadLine();


            Console.Write("File with HTTP Proxies: ");
            string proxyfile = Console.ReadLine();

            if (!proxyfile.Contains(".txt"))
            {
                proxyfile = proxyfile + ".txt";
            }

            List <string> Proxies = File.ReadLines(proxyfile).ToList();

            foreach (string proxy in Proxies)
            {
                ProxyClient prxy = HttpProxyClient.Parse(proxy);
                new Thread(delegate()
                {
                    BotLoop(videoid, prxy);
                }).Start();
                Thread.Sleep(30);
            }
            Thread.Sleep(-1);


            Console.ReadLine();
        }
        /// <summary>
        /// Deliver to email.
        /// </summary>
        private PluginExecutionResult DeliverToEmail()
        {
            PluginExecutionResult result = new PluginExecutionResult(PluginResult.Passed);

            ClearForm();
            UpdateStatus("Deliver to Email");

            int count  = _activityData.SendToEmail.NumberOfRandomRecipients;
            var toList = ExecutionServices.SessionRuntime.AsInternal().GetOfficeWorkerEmailAddresses(count);

            _runtimeRecipients = new Collection <string>(toList.Select(n => n.Address).ToList());
            _runtimeOriginator = _activityData.SendToEmail.Originator;

            SetRuntimeData();
            PopulateExecutionControls();

            // Deliver to HPCR Proxy
            foreach (var doc in _runtimeDocumentPaths)
            {
                foreach (var recipient in _runtimeRecipients)
                {
                    // Lock the document pool so that we don't get conflicts with other users.
                    ExecutionServices.CriticalSection.Run(new LocalLockToken("LocalDocument", new TimeSpan(0, 5, 0), new TimeSpan(0, 5, 0)), () =>
                    {
                        ProxyClient.DeliverToEmailByDocument(_pluginExecutionData.Servers.First().Address, doc, _runtimeOriginator, recipient);
                    });
                }
            }

            return(result);
        }
Example #31
0
        private bool TryCreateConnectionOrUseExisting(Uri address, Uri previousAddress)
        {
            ProxyClient proxy = GetProxy();

            var hasConnection = (_connection != null);
            var proxyChanged = (_currentProxy != proxy);

            var addressChanged =
                (previousAddress == null) ||
                (previousAddress.Port != address.Port) ||
                (previousAddress.Host != address.Host) ||
                (previousAddress.Scheme != address.Scheme);

            // Если нужно создать новое подключение.
            if (!hasConnection || proxyChanged ||
                addressChanged || _response.HasError ||
                KeepAliveLimitIsReached())
            {
                _currentProxy = proxy;

                Dispose();
                CreateConnection(address);
                return true;
            }

            return false;
        }
Example #32
0
        /// <summary>
        /// Отправляет POST-запрос с Multipart/form данными. Загружает тело сообщения и возвращает его в виде текста.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="multipartData">Multipart/form данные, отправляемые HTTP-серверу.</param>
        /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
        /// <returns>Если тело сообщения отсутствует, то будет возвращена пустая строка.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="multipartData"/> равно <see langword="null"/>.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
        public static string Post(Uri address, MultipartDataCollection multipartData, CookieDictionary cookies = null, ProxyClient proxy = null)
        {
            using (HttpRequest request = new HttpRequest())
            {
                if (cookies == null)
                {
                    request.Cookies = new CookieDictionary();
                }
                else
                {
                    request.Cookies = cookies;
                }

                request.Proxy = proxy;
                request.KeepAlive = false;

                if (string.IsNullOrEmpty(HttpRequest.GlobalUserAgent))
                {
                    request.UserAgent = HttpHelper.RandomUserAgent();
                }

                return request.Post(address, multipartData).ToText();
            }
        }
Example #33
0
 /// <summary>
 /// Отправляет GET-запрос HTTP-серверу.
 /// </summary>
 /// <param name="address">Адрес интернет-ресурса.</param>
 /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
 /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> является пустой строкой.</exception>
 /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
 /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
 public static void Get(string address, CookieDictionary cookies = null, ProxyClient proxy = null)
 {
     Get(address, null, cookies, proxy);
 }
Example #34
0
        /// <summary>
        /// Отправляет POST-запрос HTTP-серверу. Загружает тело сообщения и возвращает его в виде текста.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="messageBody">Тело сообщения, отправляемое HTTP-серверу.</param>
        /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
        /// <returns>Если тело сообщения отсутствует, то будет возвращена пустая строка.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> является пустой строкой.</exception>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="messageBody"/> равно <see langword="null"/>.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
        /// <remarks>Если значение заголовка 'Content-Type' не задано, то отправляется значение 'Content-Type: application/x-www-form-urlencoded'.</remarks>
        public static string Post(string address, byte[] messageBody, CookieDictionary cookies = null, ProxyClient proxy = null)
        {
            using (HttpRequest request = new HttpRequest())
            {
                if (cookies == null)
                {
                    request.Cookies = new CookieDictionary();
                }
                else
                {
                    request.Cookies = cookies;
                }

                request.Proxy = proxy;
                request.KeepAlive = false;

                if (string.IsNullOrEmpty(HttpRequest.GlobalUserAgent))
                {
                    request.UserAgent = HttpHelper.RandomUserAgent();
                }

                return request.Post(address, messageBody).ToText();
            }
        }
Example #35
0
        /// <summary>
        /// Отправляет HEAD-запрос HTTP-серверу.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="reqParams">Параметры запроса, отправляемые HTTP-серверу.</param>
        /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
        public static void Head(Uri address, StringDictionary reqParams, CookieDictionary cookies = null, ProxyClient proxy = null)
        {
            using (HttpRequest request = new HttpRequest())
            {
                if (cookies == null)
                {
                    request.Cookies = new CookieDictionary();
                }
                else
                {
                    request.Cookies = cookies;
                }

                request.Proxy = proxy;
                request.KeepAlive = false;

                if (string.IsNullOrEmpty(HttpRequest.GlobalUserAgent))
                {
                    request.UserAgent = HttpHelper.RandomUserAgent();
                }

                request.Head(address, reqParams).None();
            }
        }
Example #36
0
 /// <summary>
 /// Отправляет HEAD-запрос HTTP-серверу.
 /// </summary>
 /// <param name="address">Адрес интернет-ресурса.</param>
 /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
 /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
 /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
 /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
 public static void Head(Uri address, CookieDictionary cookies = null, ProxyClient proxy = null)
 {
     Head(address, null, cookies, proxy);
 }
Example #37
0
 /// <summary>
 /// Отправляет GET-запрос HTTP-серверу. Загружает тело сообщения и возвращает его в виде текста.
 /// </summary>
 /// <param name="address">Адрес интернет-ресурса.</param>
 /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
 /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
 /// <returns>Если тело сообщения отсутствует, то будет возвращён пустой массив байтов.</returns>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
 /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
 /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
 public static byte[] GetBytes(Uri address, CookieDictionary cookies = null, ProxyClient proxy = null)
 {
     return GetBytes(address, null, cookies, proxy);
 }
Example #38
0
 /// <summary>
 /// »нициализирует новый экземпл¤р класса <see cref="xNet.Net.ProxyException"/> заданным сообщением об ошибке и прокси-клиентом.
 /// </summary>
 /// <param name="message">—ообщение об ошибке с объ¤снением причины исключени¤.</param>
 /// <param name="proxyClient">ѕрокси-клиент, в котором произошла ошибка.</param>
 /// <param name="innerException">»сключение, вызвавшее текущие исключение, или значение <see langword="null"/>.</param>
 public ProxyException(string message, ProxyClient proxyClient, Exception innerException = null)
     : base(message, innerException)
 {
     ProxyClient = proxyClient;
 }
Example #39
0
        /// <summary>
        /// Добавляет в цепочку новый прокси-клиент.
        /// </summary>
        /// <param name="proxy">Добавляемый прокси-клиент.</param>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="proxy"/> равно <see langword="null"/>.</exception>
        public void AddProxy(ProxyClient proxy)
        {
            #region Проверка параметров

            if (proxy == null)
            {
                throw new ArgumentNullException("proxy");
            }

            #endregion

            _proxies.Add(proxy);
        }
Example #40
0
 /// <summary>
 /// Отправляет GET-запрос HTTP-серверу. Загружает тело сообщения и сохраняет его в новый файл по указанному пути. Если файл уже существует, то он будет перезаписан.
 /// </summary>
 /// <param name="address">Адрес интернет-ресурса.</param>
 /// <param name="path">Путь к файлу, в котором будет сохранено тело сообщения.</param>
 /// <param name="reqParams">Параметры запроса, отправляемые HTTP-серверу.</param>
 /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
 /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="path"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="path"/> является пустой строкой, содержит только пробелы или содержит недопустимые символы.</exception>
 /// <exception cref="System.IO.PathTooLongException">Указанный путь, имя файла или и то и другое превышает наибольшую возможную длину, определенную системой. Например, для платформ на основе Windows длина пути не должна превышать 248 знаков, а имена файлов не должны содержать более 260 знаков.</exception>
 /// <exception cref="System.IO.FileNotFoundException">Значение параметра <paramref name="path"/> указывает на несуществующий файл.</exception>
 /// <exception cref="System.IO.DirectoryNotFoundException">Значение параметра <paramref name="path"/> указывает на недопустимый путь.</exception>
 /// <exception cref="System.IO.IOException">При открытии файла возникла ошибка ввода-вывода.</exception>
 /// <exception cref="System.Security.SecurityException">Вызывающий оператор не имеет необходимого разрешения.</exception>
 /// <exception cref="System.UnauthorizedAccessException">Операция чтения файла не поддерживается на текущей платформе.</exception>
 /// <exception cref="System.UnauthorizedAccessException">Значение параметра <paramref name="path"/> определяет каталог.</exception>
 /// <exception cref="System.UnauthorizedAccessException">Вызывающий оператор не имеет необходимого разрешения.</exception>
 /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
 /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
 public static void GetFile(Uri address, string path, CookieDictionary cookies = null, ProxyClient proxy = null)
 {
     GetFile(address, path, null, cookies, proxy);
 }
Example #41
0
        private HttpResponse SendRequest(HttpMethod method, Uri address,
            HttpContent content, bool reconnection = false)
        {
            _content = content;

            if (_tcpClient != null &&
                !_response.MessageBodyLoaded && !_response.HasError)
            {
                try
                {
                    _response.None();
                }
                catch (HttpException)
                {
                    Dispose();
                }
            }

            bool createdNewConnection = false;

            ProxyClient proxy = GetProxy();

            // Если нужно создать новое подключение.
            if (_tcpClient == null || Address.Port != address.Port ||
                !Address.Host.Equals(address.Host, StringComparison.OrdinalIgnoreCase) ||
                !Address.Scheme.Equals(address.Scheme, StringComparison.OrdinalIgnoreCase) ||
                _response.HasError || _currentProxy != proxy)
            {
                Address = address;
                _currentProxy = proxy;

                Dispose();
                CreateConnection();

                createdNewConnection = true;
            }
            else
            {
                Address = address;
            }

            #region Отправка запроса

            try
            {
                long contentLength = 0;
                string contentType = string.Empty;
                bool canContainsRequestBody = CanContainsRequestBody(method);

                if (canContainsRequestBody && _content != null)
                {
                    contentType = _content.ContentType;
                    contentLength = _content.CalculateContentLength();
                }

                string startingLine = GenerateStartingLine(method);
                string headers = GenerateHeaders(method, contentLength, contentType);

                byte[] startingLineBytes = Encoding.ASCII.GetBytes(startingLine);
                byte[] headersBytes = Encoding.ASCII.GetBytes(headers);

                _bytesSent = 0;
                _totalBytesSent = startingLineBytes.Length + headersBytes.Length + contentLength;

                _clientStream.Write(startingLineBytes, 0, startingLineBytes.Length);
                _clientStream.Write(headersBytes, 0, headersBytes.Length);

                bool hasRequestBody = (_content != null && contentLength > 0);

                // Отправляем тело запроса, если оно не присутствует.
                if (hasRequestBody)
                {
                    _content.WriteTo(_clientStream);
                }
            }
            catch (SecurityException ex)
            {
                throw NewHttpException(Resources.HttpException_FailedSendRequest, ex, HttpExceptionStatus.SendFailure);
            }
            catch (IOException ex)
            {
                // Если это не первый запрос и включены постоянные соединения и до этого не было переподключения,
                // то пробуем заново отправить запрос.
                if (!createdNewConnection && KeepAlive && !reconnection)
                {
                    Dispose();
                    return SendRequest(method, address, content, true);
                }

                throw NewHttpException(Resources.HttpException_FailedSendRequest, ex, HttpExceptionStatus.SendFailure);
            }

            #endregion

            #region Загрузка ответа

            try
            {
                _canReportBytesReceived = false;

                _bytesReceived = 0;
                _totalBytesReceived = _response.LoadResponse(method);

                _canReportBytesReceived = true;
            }
            catch (HttpException ex)
            {
                // Если был получен пустой ответ и до этого не было переподключения или
                // если это не первый запрос и включены постоянные соединения и до этого не было переподключения,
                // то пробуем заново отправить запрос.
                if ((ex.EmptyMessageBody && !reconnection) ||
                    (!createdNewConnection && KeepAlive && !reconnection))
                {
                    Dispose();
                    return SendRequest(method, address, content, true);
                }

                throw;
            }

            #endregion

            #region Проверка кода ответа

            if (!IgnoreProtocolErrors)
            {
                int statusCodeNum = (int)_response.StatusCode;

                if (statusCodeNum >= 400 && statusCodeNum < 500)
                {
                    throw new HttpException(string.Format(
                        Resources.HttpException_ClientError, statusCodeNum),
                        HttpExceptionStatus.ProtocolError, _response.StatusCode);
                }
                else if (statusCodeNum >= 500)
                {
                    throw new HttpException(string.Format(
                        Resources.HttpException_SeverError, statusCodeNum),
                        HttpExceptionStatus.ProtocolError, _response.StatusCode);
                }
            }

            #endregion

            #region Переадресация

            if (AllowAutoRedirect && _response.HasRedirect)
            {
                if (++_redirectionCount > _maximumAutomaticRedirections)
                {
                    throw NewHttpException(Resources.HttpException_LimitRedirections);
                }

                ClearRequestData();

                return SendRequest(HttpMethod.GET, _response.RedirectAddress, null);
            }

            _redirectionCount = 0;

            #endregion

            return _response;
        }
Example #42
0
 /// <summary>
 /// Отправляет GET-запрос HTTP-серверу. Загружает тело сообщения и возвращает его в виде байтов.
 /// </summary>
 /// <param name="address">Адрес интернет-ресурса.</param>
 /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
 /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
 /// <returns>Если тело сообщения отсутствует, то будет возвращена пустая строка.</returns>
 /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
 /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
 /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
 /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
 public static string GetText(Uri address, CookieDictionary cookies = null, ProxyClient proxy = null)
 {
     return GetText(address, null, cookies, proxy);
 }
Example #43
0
        /// <summary>
        /// Отправляет GET-запрос HTTP-серверу. Загружает тело сообщения и возвращает его в виде байтов.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="urlParams">Параметры URL-адреса, или значение <see langword="null"/>.</param>
        /// <param name="cookies">Кукисы, отправляемые HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <param name="proxy">Прокси-клиент, используемый для запроса, или значение <see langword="null"/>.</param>
        /// <returns>Если тело сообщения отсутствует, то будет возвращена пустая строка.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> не является абсолютным URI.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception>
        public static string GetText(Uri address, StringDictionary urlParams, CookieDictionary cookies = null, ProxyClient proxy = null)
        {
            using (var request = new HttpRequest())
            {
                if (cookies == null)
                {
                    request.Cookies = new CookieDictionary();
                }
                else
                {
                    request.Cookies = cookies;
                }

                request.Proxy = proxy;
                request.KeepAlive = false;

                if (string.IsNullOrEmpty(HttpRequest.GlobalUserAgent))
                {
                    request.UserAgent = HttpHelper.RandomUserAgent();
                }

                return request.Get(address, urlParams).ToString();
            }
        }
Example #44
0
 private void Subscribe(ProxyClient client)
 {
     OnConnect(new ConnectEventArgs(client));
 }