public static void CheckMissingValues(ProxyDetails proxyDetails)
        {
            if (proxyDetails.Enabled)
            {
                if (String.IsNullOrEmpty(proxyDetails.Host))
                {
                    throw new ArgumentException("Host is not defined");
                }
                if (proxyDetails.Host.ToLower().StartsWith("http"))
                {
                    throw new ArgumentException("Enter host name without http://. ");
                }


                int port = 0;
                try
                {
                    port = Int32.Parse(proxyDetails.Port);
                }
                catch (Exception)
                {
                    throw new ArgumentException("Port must be a number ranging from 0 to 65535");
                }
                if (port < 1 && port > 65535)
                {
                    throw new ArgumentException("Port must be a number ranging from 0 to 65535");
                }
            }
        }
示例#2
0
 public override void SetProxy(ProxyDetails ProxyInfo)
 {
     if (Sock != null)
     {
         try
         {
             isec = false;
             Sock.Close();
         }
         catch
         {
         }
     }
 }
示例#3
0
            public WebSocketProxy(ProxyDetails proxy)
            {
                if (proxy.Type != ProxyType.HTTP)
                {
                    throw new ProxyException(string.Format("Unknown proxy type {0}.", proxy.Type.ToString()));
                }

                uri = new Uri($"http://{proxy.Host}:{proxy.Port}");

                if (string.IsNullOrWhiteSpace(proxy.UserName) && string.IsNullOrEmpty(proxy.Password))
                {
                    return;
                }

                Credentials = new NetworkCredential(proxy.UserName, proxy.Password);
            }
示例#4
0
 public override void SetProxy(ProxyDetails ProxyInfo)
 {
     throw new NotImplementedException();
 }
示例#5
0
        private void btnGetUrls_Click(object sender, RoutedEventArgs e)
        {
            txtUrls.Clear();
            btnGetUrls.IsEnabled = false;

            int       nrResults       = 0;
            string    url             = txtSearchEngineUrl.Text.Trim();
            bool      useProxy        = (chkUseProxy.IsChecked != null) ? chkUseProxy.IsChecked.Value : false;
            ProxyType proxyType       = ProxyType.None;
            string    proxyFullAdress = string.Empty;

            if (cmbProxyType.SelectedValue != null)
            {
                Enum.TryParse <ProxyType>(cmbProxyType.SelectedValue.ToString(), out proxyType);
            }
            if (!string.IsNullOrEmpty(txtProxyFullAddress.Text))
            {
                proxyFullAdress = txtProxyFullAddress.Text;
            }
            if (!string.IsNullOrEmpty(txtNrResults.Text))
            {
                int.TryParse(txtNrResults.Text, out nrResults);
            }


            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            var th = new Thread(() =>
            {
                string error           = string.Empty;
                string output          = string.Empty;
                ProxyDetails pd        = null;
                IList <string> results = new List <string>();

                useProxy = false;//hardcode this for now so no errors are shown
                if (useProxy)
                {
                    pd = new ProxyDetails()
                    {
                        FullProxyAddress = proxyFullAdress,
                        ProxyType        = proxyType
                    }
                }
                ;

                try
                {
                    results = HtmlHelpers.GoogleSearch(url, nrResults, pd, ref error);
                }
                catch (Exception ex)
                {
                    error = ex.Message;
                }


                if (results.Count > 0)
                {
                    foreach (var result in results)
                    {
                        if (_stopCurActionObtainUrlsTab == true)
                        {
                            break;
                        }
                        gridObtainUrls.Dispatcher.Invoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(
                                delegate()
                        {
                            txtUrls.Text += result + Environment.NewLine;
                        }));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(error))
                    {
                        output = "Error: " + error;
                    }
                    else
                    {
                        output = "Google returned 0 results";
                    }

                    gridObtainUrls.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                            delegate()
                    {
                        txtUrls.Text += output + Environment.NewLine;
                    }));
                }

                _stopCurActionObtainUrlsTab = false;

                gridObtainUrls.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                {
                    btnGetUrls.IsEnabled = true;
                }
                        ));
            });

            th.Start();
        }
示例#6
0
        private async void CheckProxyAsync(Proxy proxy)
        {
            using (TaskItem task = TaskManager.Create(Properties.Resources.CheckingProxyIfItWorks))
            {
                DisposeInitializationTaskIfRequired();

                await Task.Run(async() =>
                {
                    if (CancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    task.UpdateDetails(string.Format(Resources.ProxyCheckingIfAliveFormat, proxy));
                    BanwidthInfo bandwidth = null;

                    if (await Alive(proxy, task, () => bandwidth = new BanwidthInfo()
                    {
                        BeginTime = DateTime.Now
                    }, lenght =>
                    {
                        task.UpdateDetails(string.Format(Resources.ProxyGotFirstResponseFormat, proxy.AddressPort), Tasks.TaskStatus.Progress);
                        bandwidth.FirstTime = DateTime.Now;
                        bandwidth.FirstCount = lenght * 2;
                    }, lenght =>
                    {
                        bandwidth.EndTime = DateTime.Now;
                        bandwidth.EndCount = lenght * 2;
                    }, CancellationTokenSource))
                    {
                        if (CancellationTokenSource.IsCancellationRequested)
                        {
                            return;
                        }

                        task.UpdateDetails(string.Format(Resources.ProxyDeterminingProxyType, proxy.AddressPort), Tasks.TaskStatus.GoodProgress);

                        ProxyDetails proxyDetails = new ProxyDetails(await GetProxyDetails(proxy, task, CancellationTokenSource), UpdateProxyDetails);

                        task.UpdateDetails(string.Format(Resources.ProxyDeterminingLocationFormat, proxy.AddressPort), Tasks.TaskStatus.GoodProgress);

                        IPAddress proxyAddress = proxyDetails.Details.OutgoingIPAddress ?? proxy.Address;

                        CountryInfo countryInfo = await GeoIP.GetLocation(proxyAddress.ToString());

                        ProxyInfo proxyInfo = new ProxyInfo(proxy)
                        {
                            CountryInfo = countryInfo,
                            Details     = proxyDetails
                        };

                        if (bandwidth != null)
                        {
                            HttpDownloaderContainer.BandwidthManager.UpdateBandwidthData(proxyInfo, bandwidth);
                        }

                        proxyInfo.RatingData = await RatingManager.GetRatingDataAsync(proxyInfo);

                        ProxySearchFeedback.OnAliveProxy(proxyInfo);
                    }
                });
            }
        }
示例#7
0
        public RestBase()
        {
            Get["/"] = _ =>
            {
                String view = GetView("console.html");
                return(view);
            };

            Get["/status"] = _ =>
            {
                Dictionary <string, object> map = new Dictionary <string, object>();
                map["pluginStatus"]       = PluginManager.GetInstance().Status.ToString();
                map["pluginVersion"]      = Helpers.GetPluginVersion();
                map["tfsVersion"]         = RunModeManager.GetInstance().TfsVersion.ToString();
                map["generalEventsQueue"] = PluginManager.GetInstance().GeneralEventsQueue.Count;
                map["scmEventsQueue"]     = PluginManager.GetInstance().ScmEventsQueue.Count;
                map["testResultsQueue"]   = PluginManager.GetInstance().TestResultsQueue.Count;

                map["isLocal"] = AllowConfigurationModifyAccess(Request);

                return(map);
            };

            Post["/build-event/"] = _ =>
            {
                RunModeManager runModeManager = RunModeManager.GetInstance();
                if (runModeManager.RunMode == PluginRunMode.ConsoleApp)
                {
                    HandleBuildEvent();
                }

                return("Received");
            };

            Get["/logs/{logType}/{logId}"] = parameters =>
            {
                return(HandleGetLogRequest(parameters.logType, parameters.logId));
            };

            Get["/logs"] = parameters =>
            {
                String view = GetView("logs.html");
                return(view);
                //return HandleGetLogListRequest();
            };

            Get["/logs/download/all"] = _ =>
            {
                string zipPath  = CreateZipFileFromLogFiles();
                string fileName = Path.GetFileName(zipPath);
                DeleteTempZipFileWithDelay(zipPath);

                var file     = new FileStream(zipPath, FileMode.Open);
                var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
                return(response.AsAttachment(fileName));
            };

            Post["/config", AllowConfigurationModifyAccess] = _ =>
            {
                var configStr = Context.Request.Body.AsString();
                Log.Debug($"Received new configuration");//dont log received log configuration as it contains plain passwords
                var config = JsonHelper.DeserializeObject <ConnectionDetails>(configStr);
                try
                {
                    ConnectionCreator.CheckMissingValues(config);
                    ConfigurationManager.ResetSensitiveInfo(config);
                    ConfigurationManager.WriteConfig(config);
                }
                catch (Exception e)
                {
                    string msg = "Failed to save configuration" + e.Message;
                    Log.Error(msg, e);
                    return(new TextResponse(msg).WithStatusCode(HttpStatusCode.BadRequest));
                }

                return("Configuration changed");
            };

            Post["/config/test", AllowConfigurationModifyAccess] = _ =>
            {
                try
                {
                    var configStr = Context.Request.Body.AsString();
                    var config    = JsonHelper.DeserializeObject <ConnectionDetails>(configStr);

                    ConnectionCreator.CheckMissingValues(config);
                    ConfigurationManager.ResetSensitiveInfo(config);
                    ConnectionCreator.CheckProxySettings(config.TfsLocation);
                    ConnectionCreator.CheckProxySettings(config.ALMOctaneUrl);
                    ConnectionCreator.CreateTfsConnection(config);
                    ConnectionCreator.CreateOctaneConnection(config);
                }
                catch (Exception e)
                {
                    return(new TextResponse(e.Message).WithStatusCode(HttpStatusCode.BadRequest));
                }

                return("");
            };

            Get["/config"] = _ =>
            {
                if (AllowConfigurationModifyAccess(Request))
                {
                    String            view = GetView("config.html");
                    ConnectionDetails conf = null;
                    try
                    {
                        conf = ConfigurationManager.Read(false).GetInstanceWithoutSensitiveInfo();
                    }
                    catch (FileNotFoundException)
                    {
                        conf             = new ConnectionDetails();
                        conf.TfsLocation = ConnectionCreator.GetTfsLocationFromHostName();
                    }

                    string confJson = JsonHelper.SerializeObject(conf);
                    view = view.Replace("//{defaultConf}", "var defaultConf =" + confJson);

                    return(view);
                }
                else
                {
                    string prefix = "Configuration is read-only. To modify configuration, access http://localhost:4567/config on the TFS machine.";
                    string config = JsonHelper.SerializeObject(ConfigurationManager.Read(false).GetInstanceWithoutSensitiveInfo(), true);

                    return(new TextResponse(prefix + Environment.NewLine + config));
                }
            };

            Get["/proxy"] = _ =>
            {
                if (AllowConfigurationModifyAccess(Request))
                {
                    String       view = GetView("proxy.html");
                    ProxyDetails conf = null;
                    try
                    {
                        conf = ProxyManager.Read(false).GetInstanceWithoutSensitiveInfo();
                    }
                    catch (FileNotFoundException)
                    {
                        conf = new ProxyDetails();
                    }

                    string confJson = JsonHelper.SerializeObject(conf);
                    view = view.Replace("//{defaultConf}", "var defaultConf =" + confJson);

                    return(view);
                }
                else
                {
                    string prefix = "Proxy is read-only. To modify proxy, access http://localhost:4567/proxy on the TFS machine.";
                    string config = JsonHelper.SerializeObject(ProxyManager.Read(false).GetInstanceWithoutSensitiveInfo(), true);

                    return(new TextResponse(prefix + Environment.NewLine + config));
                }
            };

            Post["/proxy", AllowConfigurationModifyAccess] = _ =>
            {
                var configStr = Context.Request.Body.AsString();
                Log.Debug($"Received new proxy settings");//dont log received log configuration as it contains plain passwords
                try
                {
                    var proxyDetails = JsonHelper.DeserializeObject <ProxyDetails>(configStr);
                    ConnectionCreator.CheckMissingValues(proxyDetails);
                    ProxyManager.ResetSensitiveInfo(proxyDetails);
                    ProxyManager.WriteConfig(proxyDetails);
                }
                catch (Exception e)
                {
                    string msg = "Failed to save proxy settings: " + e.Message;
                    Log.Error(msg, e);
                    return(new TextResponse(msg).WithStatusCode(HttpStatusCode.BadRequest));
                }

                return("Configuration changed");
            };

            Get["/resources/{resourceName}"] = parameters =>
            {
                var    assembly     = Assembly.GetExecutingAssembly();
                var    resourceName = $"{PATH_TO_RESOURCE}.RestServer.Views.Resources.{parameters.resourceName}";
                Stream stream       = assembly.GetManifestResourceStream(resourceName);
                if (stream == null)
                {
                    return(new TextResponse("Resource not found").WithStatusCode(HttpStatusCode.NotFound));
                }

                var response = new StreamResponse(() => stream, MimeTypes.GetMimeType(resourceName));
                return(response);
            };

            Post["/start", AllowConfigurationModifyAccess] = _ =>
            {
                if (PluginManager.GetInstance().Status == PluginManager.StatusEnum.Connected)
                {
                    return("ALM Octane plugin is already running");
                }

                Log.Debug("Plugin start requested");

                PluginManager.GetInstance().StartPlugin();
                return("Starting ALM Octane plugin");
            };

            Post["/stop", AllowConfigurationModifyAccess] = _ =>
            {
                Log.Debug("Plugin stop requested");
                PluginManager.GetInstance().StopPlugin();
                return("Stopping ALM Octane plugin");
            };

            Post["/queues/clear", AllowConfigurationModifyAccess] = _ =>
            {
                Dictionary <string, object> queueStatus = new Dictionary <string, object>();
                queueStatus["GeneralEventsQueue"] = PluginManager.GetInstance().GeneralEventsQueue.Count;
                queueStatus["ScmEventsQueue"]     = PluginManager.GetInstance().ScmEventsQueue.Count;
                queueStatus["TaskResultQueue"]    = PluginManager.GetInstance().TestResultsQueue.Count;

                string json = JsonHelper.SerializeObject(queueStatus, true);
                Log.Debug($"Clear event queues requested : {json}");

                PluginManager.GetInstance().GeneralEventsQueue.Clear();
                PluginManager.GetInstance().ScmEventsQueue.Clear();
                PluginManager.GetInstance().TestResultsQueue.Clear();
                return($"Cleared {json}");
            };
        }
示例#8
0
 public IProxyClient CreateProxyClient(ILog logger, ProxyDetails proxyDetails)
 {
     return(CreateProxyClient(logger, proxyDetails.Type, proxyDetails.Host, proxyDetails.Port, proxyDetails.UserName, proxyDetails.Password));
 }
示例#9
0
 public override void SetProxy(ProxyDetails ProxyInfo)
 {
 }
示例#10
0
 public IProxyClient CreateProxyClient(ILog logger, ProxyDetails proxyDetails)
 {
     return CreateProxyClient(logger, proxyDetails.Type, proxyDetails.Host, proxyDetails.Port, proxyDetails.UserName, proxyDetails.Password);
 }