public ClickOnceWebProxy(ProxySettings settings) { webProxy = new WebProxy(settings.Server) { Credentials = new NetworkCredential(settings.Username, settings.Password), BypassProxyOnLocal = false }; }
public ServerWorker(ProxySettings settings, string remoteHost, ClientWorker clientWorker, SocketWrapper clientSocket) : base(settings) { this.remoteHost = remoteHost; this.clientWorker = clientWorker; this.clientSocket = clientSocket; this.inspectorFactory = settings.InspectorFactory; }
public void QueryProjects() { var proxySettings = new ProxySettings(new Uri(ProxyPath), ProxyUsername, ProxyPassword); var proxiedInstance = new V1Instance(V1Path, V1Username, V1Password, false, proxySettings); var instance = new V1Instance(V1Path, V1Username, V1Password, false); var projects = instance.Get.Projects(null); var projectsOverProxy = proxiedInstance.Get.Projects(null); Assert.AreEqual(projects.Count, projectsOverProxy.Count); }
public Script(string namespaceToGen, string className) { this.compileUnit = new CodeCompileUnit(); this.codeNamespace = new CodeNamespace(namespaceToGen); this.compileUnit.Namespaces.Add(this.codeNamespace); this.codeClass = new CodeTypeDeclaration(className); this.codeNamespace.Types.Add(this.codeClass); this.proxySetting = ProxySettings.RequiredHeaders; this.mainMethod = new CodeEntryPointMethod(); this.mainMethod.Name = "Main"; this.mainMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; this.codeClass.Members.Add(this.mainMethod); this.dumpMethodRef = this.BuildDumper(); }
public HostConnector(string host, bool secure, Action<Socket> connectionMadeCallback, Action errorCallback, ProxySettings settings) { this.connectionMadeCallback = connectionMadeCallback; this.errorCallback = errorCallback; Uri uri = new Uri((secure ? "https://" : "http://") + host); this.host = uri.Host; this.port = uri.Port; this.hostIsIP = uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6; if (settings != null && settings.InspectorFactory != null) { this.connectionInspector = settings.InspectorFactory.CreateServerConnectionInspector(this.host, this.port, secure); } }
public WebSocketClient(IMessageInterpreter interpreter, string url, ProxySettings proxySettings) { _interpreter = interpreter; _webSocket = new WebSocket(url); _webSocket.OnMessage += WebSocketOnMessage; _webSocket.OnClose += (sender, args) => OnClose?.Invoke(sender, args); _webSocket.Log.Level = GetLoggingLevel(); _webSocket.EmitOnPing = true; if (proxySettings != null) { _webSocket.SetProxy(proxySettings.Url, proxySettings.Username, proxySettings.Password); } }
public HttpMessage(ProxySettings settings) { this.settings = settings; this.Request = new HttpRequestInfo(); this.Response = new HttpResponseInfo(); this.requestHeaderBuffer = new HeaderSearchBuffer(HeaderSearchBufferType.Request); this.responseHeaderBuffer = new HeaderSearchBuffer(HeaderSearchBufferType.Response); if (settings.InspectorFactory != null) { this.messageInspector = settings.InspectorFactory.CreateHttpMessageInspector(this); } }
public LiteClient(string HostIp, ushort HostPort, ProxySettings proxy = null, Action<LiteClient> BeforeConnect = null) : base(HostIp, HostPort, typeof(ClientChannel), new object[0], EncryptionType.None, CompressionType.None, true, proxy) { this.aClient = new AClient(); if (BeforeConnect != null) BeforeConnect(this); aClient.Connection = this; //aClient.Connection.MultiThreadProcessing = true; aClient.ShareClass(typeof(Lite_Static_Cursor)); aClient.ShareClass(typeof(Lite_Socket), true); aClient.ShareClass(typeof(Lite_Graphics), true); aClient.ShareClass(typeof(Lite_Process), true); aClient.ShareClass(typeof(Lite_FileStream), true); aClient.Lock("InitConnect"); //just wait till server side completed his part }
public void UpdateData() { var settings = new ProxySettings( true, HTTP.Text, GetInt(HTTPPort.Text), FTP.Text, GetInt(FTPPort.Text), Socks.Text, GetInt(SocksPort.Text), SSL.Text, GetInt(SSLPort.Text) ); actProfile.BrowserSettings.Proxy = settings; actProfile.BrowserSettings.HomePage = HomePage.Text; foreach (string name in lbBrowsers.Items) { var set = actProfile.BrowserNames.First(x => x.Name == name); set.Used = lbBrowsers.GetItemChecked(lbBrowsers.Items.IndexOf(name)); } }
public ProxyBuilderHelper(ProxySettings proxySettings) { ProxySettings = proxySettings; }
/// <summary> /// Constructor /// </summary> public Setting() { Title = Properties_Resources.EditTitle; ResizeMode = ResizeMode.NoResize; Height = 370; Width = 660; Icon = UIHelpers.GetImageSource("app", "ico"); ElementHost.EnableModelessKeyboardInterop(this); WindowStartupLocation = WindowStartupLocation.CenterScreen; Closing += delegate (object sender, CancelEventArgs args) { Controller.HideWindow(); args.Cancel = true; }; LoadSetting(); Controller.ShowWindowEvent += delegate { Dispatcher.BeginInvoke((Action)delegate { RefreshSetting(); Show(); Activate(); BringIntoView(); }); }; Controller.HideWindowEvent += delegate { Dispatcher.BeginInvoke((Action)delegate { Hide(); }); }; FinishButton.Click += delegate { ProxySettings proxy = new ProxySettings(); if (ProxyNone.IsChecked.GetValueOrDefault()) { proxy.Selection = ProxySelection.NOPROXY; } else if (ProxySystem.IsChecked.GetValueOrDefault()) { proxy.Selection = ProxySelection.SYSTEM; } else { proxy.Selection = ProxySelection.CUSTOM; } proxy.LoginRequired = LoginCheck.IsChecked.GetValueOrDefault(); string server = Controller.GetServer(AddressText.Text); if (server != null) { proxy.Server = new Uri(server); } else { proxy.Server = ConfigManager.CurrentConfig.Proxy.Server; } proxy.Username = UserText.Text; proxy.ObfuscatedPassword = Crypto.Obfuscate(PasswordText.Password); ConfigManager.CurrentConfig.Proxy = proxy; ConfigManager.CurrentConfig.Notifications = NotificationsCheck.IsChecked.GetValueOrDefault(); ConfigManager.CurrentConfig.Save(); Controller.HideWindow(); }; CancelButton.Click += delegate { Controller.HideWindow(); }; }
public WorkerBase(ProxySettings settings) { this.Settings = settings; }
/// <inheritdoc/> public new async Task <IChromiumBrowserContext> LaunchPersistentContextAsync( string userDataDir, bool?headless = null, string[] args = null, bool?devtools = null, string executablePath = null, string downloadsPath = null, bool?ignoreHTTPSErrors = null, int?timeout = null, bool?dumpIO = null, int?slowMo = null, bool?ignoreDefaultArgs = null, string[] ignoredDefaultArgs = null, Dictionary <string, string> env = null, Dictionary <string, object> firefoxUserPrefs = null, ProxySettings proxy = null, string userAgent = null, bool?bypassCSP = null, bool?javaScriptEnabled = null, string timezoneId = null, Geolocation geolocation = null, ContextPermission[] permissions = null, bool?isMobile = null, bool?offline = null, decimal?deviceScaleFactor = null, Credentials httpCredentials = null, bool?hasTouch = null, bool?acceptDownloads = null, ColorScheme?colorScheme = null, string locale = null, Dictionary <string, string> extraHttpHeaders = null, bool?chromiumSandbox = null, bool?handleSIGINT = null, bool?handleSIGTERM = null, bool?handleSIGHUP = null, RecordHarOptions recordHar = null, RecordVideoOptions recordVideo = null) => await LaunchPersistentContextAsync( userDataDir, headless, args, devtools, executablePath, downloadsPath, ignoreHTTPSErrors, timeout, dumpIO, slowMo, ignoreDefaultArgs, ignoredDefaultArgs, env, firefoxUserPrefs, proxy, userAgent, bypassCSP, javaScriptEnabled, timezoneId, geolocation, permissions, isMobile, offline, deviceScaleFactor, httpCredentials, hasTouch, acceptDownloads, colorScheme, locale, extraHttpHeaders, chromiumSandbox, handleSIGINT, handleSIGTERM, handleSIGHUP, recordHar, recordVideo).ConfigureAwait(false) as IChromiumBrowserContext;
public InspectorFactory(ProxySettings settings) { this.settings = settings; }
/// <summary> /// Initializes a new instance of the <see cref="ProxySettingsAdapter"/> class. /// </summary> /// <param name="settings">The settings.</param> public ProxySettingsAdapter( ProxySettings settings ) : this( (BG_JOB_PROXY_USAGE) settings.Usage, settings.ProxyList.Aggregate( ( current, next ) => current + " " + next ), settings.ProxyBypassList.Aggregate( ( current, next ) => current + " " + next ) ) { }
/// <summary> /// Send a POST request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to POST to.</param> /// <param name="data">The data to POST.</param> public string Post(string url, string data) { ProxySettings settings = new ProxySettings() { UseProxy = false }; return Post(url, data, settings); }
static void Main(string[] args) { //args = new string[] { // "--create", // "5000", // "+79062532468", // "3DVobv7Pf5TVWdy7fykuSdWscy3kTS4MvV" //}; //args = new string[] { "--gettypebtcaddress" }; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; NetexSettings settings = new NetexSettings(); settings.CreateIfNotExists(); settings.LoadSettings(); string USER_TOKEN = Guid.NewGuid().ToString(); DB db = new DB(); StorageModelDB storageDB = new StorageModelDB() { db = db }.MigrateUp(); StorageModelREG storageREG = new StorageModelREG(); EmailStorageModelDB emailStorageModel = new EmailStorageModelDB() { storageDB = storageDB }; EmailStack emailStack = new EmailStack() { allowEmails = settings.allowEmails, emailStorageModel = emailStorageModel }; EmailSender emailSender = new EmailSender() { settings = settings.email }; //proxy list create const string FILE_CREATE_PROXY = "ProxyListForCreate.json"; ProxyStorageModelMixed createProxyStorageModel = new ProxyStorageModelMixed(settings.registerKeyPrefix, settings.dbKeyPrefix, FILE_CREATE_PROXY) { storageDB = storageDB, storageREG = storageREG }; ProxySettings createProxySettings = new ProxySettings(FILE_CREATE_PROXY) { createProxyStorageModel = createProxyStorageModel }.LoadSettings(); ProxyStack createProxyStack = new ProxyStack() { settings = settings, emailSender = emailSender, proxySettings = createProxySettings, proxyStorageModel = createProxyStorageModel }; //proxy list rate const string FILE_RATE_PROXY = "ProxyListForRate.json"; ProxySettings rateProxySettings = new ProxySettings(FILE_RATE_PROXY).LoadSettings(); ProxyStorageModelMixed rateProxyStorageModel = new ProxyStorageModelMixed(settings.registerKeyPrefix, settings.dbKeyPrefix, FILE_RATE_PROXY) { storageDB = storageDB, storageREG = storageREG }; ProxyStack rateProxyStack = new ProxyStack() { settings = settings, emailSender = emailSender, proxySettings = rateProxySettings, proxyStorageModel = rateProxyStorageModel }; //proxy list type addr const string FILE_TYPEADDR_PROXY = "ProxyListForGetTypeAddr.json"; ProxySettings typeaddrProxySettings = new ProxySettings(FILE_TYPEADDR_PROXY).LoadSettings(); ProxyStorageModelMixed typeaddrProxyStorageModel = new ProxyStorageModelMixed(settings.registerKeyPrefix, settings.dbKeyPrefix, FILE_TYPEADDR_PROXY) { storageDB = storageDB, storageREG = storageREG }; ProxyStack typeaddrProxyStack = new ProxyStack() { settings = settings, emailSender = emailSender, proxySettings = typeaddrProxySettings, proxyStorageModel = typeaddrProxyStorageModel }; try { if (args.Length == 0) { Console.WriteLine(CheckCapcha(createProxyStack, settings)); Console.WriteLine("\n==========================================\n"); Console.WriteLine("Check proxy " + FILE_TYPEADDR_PROXY + ":"); CheckAllProxy(typeaddrProxyStack, typeaddrProxySettings, settings); Console.WriteLine("\n==========================================\n"); Console.WriteLine("Check proxy " + FILE_CREATE_PROXY + ":"); CheckAllProxy(createProxyStack, createProxySettings, settings); Console.ReadKey(); return; } //первым делом установи доступную валюту switch (args[ACTION_ID]) { case "--rate": Console.WriteLine(Rate(rateProxyStack.First(), settings)); break; case "--create": double amount = -1; try { amount = double.Parse(args[1].Replace(',', '.')); } catch (Exception) { amount = double.Parse(args[1].Replace('.', ',')); } string phone = PhoneHelper.PhoneReplacer(args[2]); string btcAddr = args[3]; List <string> usedProxyList = new List <string>(); int cntTry = settings.maxTryReCreate; do { try { NetexRequestPaymentResponseType response = Create(USER_TOKEN, emailStack, createProxyStack, settings, amount, phone, btcAddr, ref usedProxyList); response.used_proxy_list = usedProxyList.ToArray(); Console.WriteLine(response.toJson()); if (WRITE_DEBUG) { Console.ReadKey(); } return; } catch (Exception) { } } while (--cntTry > 0); break; case "--gettypebtcaddress": if (typeaddrProxyStack.proxySettings.items.Count() == 0) { Console.WriteLine( new GetTypeBtcAddressResponse() { btc_addresstype = "", target_currency_id = 106 }.toJson() ); if (WRITE_DEBUG) { Console.ReadKey(); } return; } Console.WriteLine(GetTypeBtcAddress(typeaddrProxyStack.First(), settings)); if (WRITE_DEBUG) { Console.ReadKey(); } break; case "--getallowcurrenciesids": Console.WriteLine(GetAllowCurrenciesIds(typeaddrProxyStack.First(), settings)); if (WRITE_DEBUG) { Console.ReadKey(); } break; case "--checkallproxy": CheckAllProxy(createProxyStack, createProxySettings, settings); if (WRITE_DEBUG) { Console.ReadKey(); } break; default: if (args[ACTION_ID].Substring(args[ACTION_ID].Length - 4).Trim().ToLower() == ".txt") { AddNexProxy(args[ACTION_ID], createProxySettings); } break; } } catch (Exception ex) { if (TEST) { Console.WriteLine(ex.Message); } } }
public VoxelBuildActivity(Logger logger, Run3DOptions options, ProxySettings proxySettings, CancellationToken finishToken) : base(logger, options, proxySettings, finishToken) { this.options = options; }
public DevUpdateChecker(ProxySettings proxySettings) { _proxySettings = proxySettings; _currentVersion = Assembly.GetEntryAssembly().GetName().Version; }
public bool Open(gView.MapServer.IServiceRequestContext context) { if (_class == null) { _class = new AGSClass(this); } #region Parameters string server = ConfigTextStream.ExtractValue(ConnectionString, "server"); string service = ConfigTextStream.ExtractValue(ConnectionString, "service"); string user = ConfigTextStream.ExtractValue(ConnectionString, "user"); string pwd = ConfigTextStream.ExtractValue(ConnectionString, "pwd"); if ((user == "#" || user == "$") && context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null) { string roles = String.Empty; if (user == "#" && context.ServiceRequest.Identity.UserRoles != null) { foreach (string role in context.ServiceRequest.Identity.UserRoles) { if (String.IsNullOrEmpty(role)) { continue; } roles += "|" + role; } } user = context.ServiceRequest.Identity.UserName + roles; pwd = context.ServiceRequest.Identity.HashedPassword; } #endregion try { _proxy = ProxySettings.Proxy(server); _themes.Clear(); _parentIds.Clear(); _mapServer = new gView.Interoperability.AGS.Proxy.MapServer(service); _mapServer.Proxy = gView.Framework.Web.ProxySettings.Proxy(service); MapServerInfo msi = _mapServer.GetServerInfo(_mapServer.GetDefaultMapName()); _mapDescription = msi.DefaultMapDescription; MapLayerInfo[] mapLayerInfos = msi.MapLayerInfos; foreach (MapLayerInfo layerInfo in mapLayerInfos) { if (layerInfo.Extent is EnvelopeN) { EnvelopeN env = (EnvelopeN)layerInfo.Extent; if (_envelope == null) { _envelope = new gView.Framework.Geometry.Envelope(env.XMin, env.YMin, env.XMax, env.YMax); } else { _envelope.Union(new gView.Framework.Geometry.Envelope(env.XMin, env.YMin, env.XMax, env.YMax)); } } CalcParentLayerIds(mapLayerInfos, layerInfo.LayerID); IClass themeClass = null; IWebServiceTheme theme = null; LayerDescription ld = LayerDescriptionById(layerInfo.LayerID); if (ld == null) { continue; } if (layerInfo.LayerType == "Feature Layer") { #region Geometry Type (Point, Line, Polygon) geometryType geomType = geometryType.Unknown; if (layerInfo.Fields != null) { foreach (Proxy.Field fieldInfo in layerInfo.Fields.FieldArray) { if (fieldInfo.Type == esriFieldType.esriFieldTypeGeometry && fieldInfo.GeometryDef != null) { switch (fieldInfo.GeometryDef.GeometryType) { case esriGeometryType.esriGeometryMultipoint: case esriGeometryType.esriGeometryPoint: geomType = geometryType.Point; break; case esriGeometryType.esriGeometryPolyline: geomType = geometryType.Polyline; break; case esriGeometryType.esriGeometryPolygon: geomType = geometryType.Polygon; break; case esriGeometryType.esriGeometryMultiPatch: break; } } } } #endregion themeClass = new AGSThemeFeatureClass(this, layerInfo, geomType); theme = LayerFactory.Create(themeClass, _class as IWebServiceClass) as IWebServiceTheme; if (theme == null) { continue; } } else if (layerInfo.LayerType == "Raster Layer" || layerInfo.LayerType == "Raster Catalog Layer") { themeClass = new AGSThemeRasterClass(this, layerInfo); theme = LayerFactory.Create(themeClass, _class as IWebServiceClass) as IWebServiceTheme; if (theme == null) { continue; } } else { MapLayerInfo parentLayer = MapLayerInfoById(mapLayerInfos, layerInfo.ParentLayerID); if (parentLayer != null && parentLayer.LayerType == "Annotation Layer") { themeClass = new AGSThemeFeatureClass(this, layerInfo, geometryType.Polygon); theme = LayerFactory.Create(themeClass, _class as IWebServiceClass) as IWebServiceTheme; if (theme == null) { continue; } } } if (theme != null) { theme.MinimumScale = layerInfo.MaxScale; theme.MaximumScale = layerInfo.MinScale; theme.Visible = ld.Visible; _themes.Add(theme); } } _state = DatasetState.opened; return(true); } catch (Exception ex) { _state = DatasetState.unknown; _errMsg = ex.Message; return(false); } }
public UpdateChecker(ProxySettings ProxySettings) { _proxySettings = ProxySettings; _currentVersion = ServiceProvider.AppVersion; }
/// <summary> /// Constructor. /// </summary> /// <param name="settings"></param> public ProxyAuthenticationWindow(ProxySettings settings) : this() { m_proxySetting = settings; UpdateFields(); }
public YouTubeUploader(IYouTubeApiKeys apiKeys, ProxySettings proxySettings) { _apiKeys = apiKeys; _proxySettings = proxySettings; }
/// <summary> /// Send a GET request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to GET.</param> public string Get(string url, ProxySettings settings) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); // Use a proxy if (settings.UseProxy) { IWebProxy proxy = request.Proxy; WebProxy myProxy = new WebProxy(); Uri newUri = new Uri(settings.ProxyAddress); myProxy.Address = newUri; myProxy.Credentials = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword); request.Proxy = myProxy; } request.Method = "GET"; request.CookieContainer = cookies; WebResponse response = request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8); string result = sr.ReadToEnd(); sr.Close(); response.Close(); return result; }
/// <summary> /// Send a POST request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to POST to.</param> /// <param name="postVars">The list of variables to POST to the server.</param> public string Post(string url, PostPackageBuilder postVars, ProxySettings settings) { return Post(url, postVars.PostDataString, settings); }
public ProxyParser() { this.path = HostingEnvironment.MapPath("~/App_Data/") + ProxySettings.GetPath(); }
public SlackClient(ProxySettings proxySettings) { _proxySettings = proxySettings; }
/// <inheritdoc/> public new async Task <IChromiumBrowserContext> LaunchPersistentContextAsync( string userDataDir, ViewportSize viewport, bool?headless, string[] args, bool?devtools, string executablePath, string downloadsPath, bool?ignoreHTTPSErrors, int?timeout, bool?dumpIO, int?slowMo, bool?ignoreDefaultArgs, string[] ignoredDefaultArgs, Dictionary <string, string> env, Dictionary <string, object> firefoxUserPrefs, ProxySettings proxy, string userAgent, bool?bypassCSP, bool?javaScriptEnabled, string timezoneId, Geolocation geolocation, ContextPermission[] permissions, bool?isMobile, bool?offline, decimal?deviceScaleFactor, Credentials httpCredentials, bool?hasTouch, bool?acceptDownloads, ColorScheme?colorScheme, string locale, Dictionary <string, string> extraHttpHeaders, bool?chromiumSandbox, bool?handleSIGINT, bool?handleSIGTERM, bool?handleSIGHUP) => await LaunchPersistentContextAsync( userDataDir, viewport, headless, args, devtools, executablePath, downloadsPath, ignoreHTTPSErrors, timeout, dumpIO, slowMo, ignoreDefaultArgs, ignoredDefaultArgs, env, firefoxUserPrefs, proxy, userAgent, bypassCSP, javaScriptEnabled, timezoneId, geolocation, permissions, isMobile, offline, deviceScaleFactor, httpCredentials, hasTouch, acceptDownloads, colorScheme, locale, extraHttpHeaders, chromiumSandbox, handleSIGINT, handleSIGTERM, handleSIGHUP).ConfigureAwait(false) as IChromiumBrowserContext;
public void SetProxySettings(ProxySettings settings) { config["network.proxy.http"] = new ConfigFileValue {Value = settings.HTTP, Comma = true}; config["network.proxy.http_port"] = new ConfigFileValue { Value = settings.HTTPPort.ToString(CultureInfo.InvariantCulture) }; config["network.proxy.ftp"] = new ConfigFileValue { Value = settings.FTP, Comma = true }; config["network.proxy.ftp_port"] = new ConfigFileValue { Value =settings.FTPPort.ToString(CultureInfo.InvariantCulture) }; config["network.proxy.socks"] = new ConfigFileValue { Value =settings.Socks, Comma = true }; config["network.proxy.socks_port"] = new ConfigFileValue { Value =settings.SocksPort.ToString(CultureInfo.InvariantCulture) }; config["network.proxy.ssl"] = new ConfigFileValue { Value =settings.SSL, Comma = true }; config["network.proxy.ssl_port"] = new ConfigFileValue { Value = settings.SSLPort.ToString(CultureInfo.InvariantCulture) }; config["network.proxy.type"] = new ConfigFileValue { Value = settings.Enabled ? "1" : "0" }; }
void DownloadServerIcon(string websiteUrl, FileInfo iconFile) { Trace.Call(websiteUrl, iconFile); var webClient = new WebClient(); // ignore proxy settings of remote engines WebProxy proxy = null; if (Frontend.IsLocalEngine) { proxy = ProxySettings.GetWebProxy(websiteUrl); if (proxy == null) { // HACK: WebClient will always use the system proxy if set to // null so explicitely override this by setting an empty proxy proxy = new WebProxy(); } webClient.Proxy = proxy; } var content = webClient.DownloadString(websiteUrl); var links = new List <Dictionary <string, string> >(); foreach (Match linkMatch in Regex.Matches(content, @"<link[\s]+([^>]*?)/?>")) { var attributes = new Dictionary <string, string>(); foreach (Match attrMatch in Regex.Matches(linkMatch.Value, @"([\w]+)[\s]*=[\s]*[""']([^""']*)[""'][\s]*")) { var key = attrMatch.Groups[1].Value; var value = attrMatch.Groups[2].Value; attributes.Add(key, value); } links.Add(attributes); } string faviconRel = null; foreach (var link in links) { var iconLink = false; foreach (var attribute in link) { if (attribute.Key != "rel" || !attribute.Value.Split(' ').Contains("icon")) { continue; } iconLink = true; break; } if (!iconLink) { continue; } foreach (var attribute in link) { if (attribute.Key != "href") { continue; } // yay, we have found the favicon in all this junk faviconRel = attribute.Value; break; } } string faviconUrl = null; if (String.IsNullOrEmpty(faviconRel)) { faviconRel = "/favicon.ico"; } faviconUrl = new Uri(new Uri(websiteUrl), faviconRel).ToString(); #if LOG4NET f_Logger.DebugFormat("DownloadServerIcon(): favicon URL: {0}", faviconUrl); #endif var iconRequest = WebRequest.Create(faviconUrl); // ignore proxy settings of remote engines if (Frontend.IsLocalEngine) { iconRequest.Proxy = proxy; } if (iconRequest is HttpWebRequest) { var iconHttpRequest = (HttpWebRequest)iconRequest; if (iconFile.Exists) { iconHttpRequest.IfModifiedSince = iconFile.LastWriteTime; } } WebResponse iconResponse; try { iconResponse = iconRequest.GetResponse(); } catch (WebException ex) { if (ex.Response is HttpWebResponse) { var iconHttpResponse = (HttpWebResponse)ex.Response; if (iconHttpResponse.StatusCode == HttpStatusCode.NotModified) { // icon hasn't changed, nothing to do return; } } throw; } // save new or modified icon file using (var iconStream = iconFile.OpenWrite()) using (var httpStream = iconResponse.GetResponseStream()) { byte[] buffer = new byte[4096]; int read; while ((read = httpStream.Read(buffer, 0, buffer.Length)) > 0) { iconStream.Write(buffer, 0, read); } } }
public ProxySettings GetProxySettings() { return(ProxySettings.smethod_0(this.ProxyString)); }
public WebRequestHandler(ProxySettings proxySettings) { _proxySettings = proxySettings; }
public LoggingMessageInspector(ProxySettings settings) { this.settings = settings; }
public ClientWorker(Socket workerSocket, ProxySettings settings) : base(settings) { this.workerSocket = new SocketWrapper(workerSocket, settings); }
public SocketWrapper(Socket socket, ProxySettings settings) { this.socket = socket; this.settings = settings; }
public BrowserSettings() { HomePage = ""; Proxy = new ProxySettings(); }
private async Task <IWebSocketClient> GetWebSocket(HandshakeResponse handshakeResponse, ProxySettings proxySettings) { var webSocketClient = _connectionFactory.CreateWebSocketClient(handshakeResponse.WebSocketUrl, proxySettings); await webSocketClient.Connect(); return(webSocketClient); }
public SessionManager(ProxySettings proxySettings) { sessionsDir = new DirectoryInfo(PathTo.SessionsFolder); this.proxySettings = proxySettings; }
/// <summary> /// Send a GET request to a web page asynchronously. The result will be returned in OnHttpResponse. /// </summary> /// <param name="url">The address to GET.</param> public bool Get(string url, ProxySettings settings) { if (!busy) { busy = true; request = new HttpAsyncInfo(); request.url = url; request.settings = settings; background.RunWorkerAsync(RequestOption.Get); return true; } else { return false; } }
public async void Run(DateTime dateBgn, DateTime dateEnd) { string err = ""; try { Log("Установливаем соединение:"); Log("Имя пользователя: " + this._Username); Log("Хост: " + this._Hostname); Log("Порт: " + this._Port); ProxySettings proxySettings = ProxySettings.GetSystemDefaultProxy(); var authInfo = new Lers.Networking.BasicAuthenticationInfo(this._Username, Lers.Networking.SecureStringHelper.ConvertToSecureString(this._Password)); theSplash.Show(); await this.theServer.ConnectAsync(this._Hostname, this._Port, proxySettings, authInfo, connectCancellation.Token); this.Log("Ищем точку учёта."); var measurePoint = this.theServer.MeasurePoints.GetByNumber(727); this.Log(measurePoint.FullTitle); this.Log("Запрашиваем суточные данные за указанный интервал"); var consumptionData = measurePoint.Data.GetConsumption(dateBgn, dateEnd, Lers.Data.DeviceDataType.Day); this.Log("Выводим на экран массовый расход"); foreach (var consumptionRecord in consumptionData) { double?valueT = consumptionRecord.GetValue(Lers.Data.DataParameter.T_in.ToString()); string stringValueT = valueT.HasValue ? valueT.Value.ToString() : "<нет данных>"; double?valueP = consumptionRecord.GetValue(Lers.Data.DataParameter.P_in.ToString()); string stringValueP = valueP.HasValue ? valueP.Value.ToString() : "<нет данных>"; if (theListView != null) { ListViewItem Item = new ListViewItem(consumptionRecord.DateTime.ToLongDateString()); Item.SubItems.Add(stringValueT); Item.SubItems.Add(stringValueP); theListView.Items.Add(Item); } } Log("Разрываем соединение с сервером"); this.theServer.Disconnect(1000, true); } catch (AuthorizationFailedException ex) { err = ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } } catch (ServerConnectionException ex) { err = "Ошибка подключения" + Environment.NewLine + ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } } catch (TimeoutException ex) { err = "Превышено время ожидания!" + Environment.NewLine + ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } err += Environment.NewLine + Environment.NewLine + "Убедитесь, что сервер ЛЭРС УЧЕТ запущен, работает правильно и имеет соединение с базой данных."; } catch (RequestDisconnectException ex) { err = "Разрыв соединения!" + Environment.NewLine + ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } err += Environment.NewLine + Environment.NewLine + "Проверьте параметры подключения, настройки прокси и брэндмауэра."; } catch (OperationCanceledException ex) { err = "Операция отменена!" + Environment.NewLine + ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } } catch (VersionMismatchException ex) { err = "Версии клиента и сервера отличаются!" + Environment.NewLine + ex.Message + Environment.NewLine; err += "Версия клиента: " + ex.ClientVersion.BuildNumber.ToString() + Environment.NewLine; err += "Версия сервера: " + ex.ServerVersion.BuildNumber.ToString() + Environment.NewLine; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } } catch (Exception ex) { err = "Неизвестная ошибка!" + Environment.NewLine + ex.Message; if (ex.InnerException != null) { err += Environment.NewLine + ex.InnerException.Message; } } finally { this.connectCancellation.CancelAfter(1000); this.connectCancellation.Dispose(); this.theSplash.Hide(); if (err.Length > 0) { MessageBox.Show(err, "Ошибка подключения!"); this.Log(err); } } }
public BrowserSettings(BrowserSettings other) { HomePage = other.HomePage; Proxy = new ProxySettings(other.Proxy); }
public NativeTcpTransport(string host, int port, string staticHost, int staticPort, MTProtoTransportType mtProtoType, short protocolDCId, byte[] protocolSecret, TLProxyConfigBase proxyConfig) : base(host, port, staticHost, staticPort, mtProtoType, proxyConfig) { // System.Diagnostics.Debug.WriteLine( // " [NativeTcpTransport] .ctor begin host={0} port={1} static_host={2} static_port={3} type={4} protocol_dcid={5} protocol_secret={6} proxy={7}", // host, port, staticHost, staticPort, mtProtoType, protocolDCId, protocolSecret, proxyConfig); ActualHost = host; ActualPort = port; var ipv4 = true; ProxySettings proxySettings = null; if (proxyConfig != null && proxyConfig.IsEnabled.Value && !proxyConfig.IsEmpty) { var socks5Proxy = proxyConfig.GetProxy() as TLSocks5Proxy; if (socks5Proxy != null) { try { ipv4 = new HostName(socks5Proxy.Server.ToString()).Type == HostNameType.Ipv4; } catch (Exception ex) { } proxySettings = new ProxySettings { Type = ProxyType.Socks5, Host = socks5Proxy.Server.ToString(), Port = socks5Proxy.Port.Value, Username = socks5Proxy.Username.ToString(), Password = socks5Proxy.Password.ToString(), IPv4 = ipv4 }; ActualHost = staticHost; ActualPort = staticPort; protocolSecret = null; protocolDCId = protocolDCId; } var mtProtoProxy = proxyConfig.GetProxy() as TLMTProtoProxy; if (mtProtoProxy != null) { try { ipv4 = new HostName(mtProtoProxy.Server.ToString()).Type == HostNameType.Ipv4; } catch (Exception ex) { } proxySettings = new ProxySettings { Type = ProxyType.MTProto, Host = mtProtoProxy.Server.ToString(), Port = mtProtoProxy.Port.Value, Secret = TLUtils.ParseSecret(mtProtoProxy.Secret), IPv4 = ipv4 }; ActualHost = staticHost; ActualPort = staticPort; } } try { ipv4 = new HostName(ActualHost).Type == HostNameType.Ipv4; } catch (Exception ex) { } var connectionSettings = new ConnectionSettings { Host = ActualHost, Port = ActualPort, IPv4 = ipv4, ProtocolDCId = protocolDCId, ProtocolSecret = protocolSecret }; _proxySettings = proxySettings; // var proxyString = proxySettings == null // ? "null" // : string.Format("[host={0} port={1} ipv4={2} type={3} secret={4} username={5} password={6}]", // proxySettings.Host, // proxySettings.Port, // proxySettings.IPv4, // proxySettings.Type, // proxySettings.Secret, // proxySettings.Username, // proxySettings.Password); // System.Diagnostics.Debug.WriteLine( // " [NativeTcpTransport] .ctor end host={0} port={1} ipv4={2} protocol_dcid={3} protocol_secret={4} proxy={5}", // connectionSettings.Host, connectionSettings.Port, connectionSettings.IPv4, connectionSettings.ProtocolDCId, connectionSettings.ProtocolSecret, proxyString); _wrapper = new ConnectionSocketWrapper(connectionSettings, proxySettings); _wrapper.Closed += Wrapper_OnClosed; _wrapper.PacketReceived += Wrapper_OnPacketReceived; }
/// <summary> /// Send a GET request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to GET.</param> public string Get(string url) { ProxySettings settings = new ProxySettings() { UseProxy = false }; return Get(url, settings); }
public HttpProxyClient(ProxySettings settings) : base(settings) { }
/// <summary> /// Send a POST request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to POST to.</param> /// <param name="postVars">The list of variables to POST to the server.</param> public string Post(string url, PostPackageBuilder postVars) { ProxySettings settings = new ProxySettings() { UseProxy = false }; return Post(url, postVars.PostDataString, settings); }
void _networkChangeDetector_ProxyChanged(string name, NetworkInfo networkInfo, ProxySettings proxySettings, string reason) { try { log.DebugFormat("ProxyChanged event: {0}, network {1}, proxy {2}, reason", name, networkInfo, proxySettings, reason); lastUpdateTime = DateTime.Now; _activeConfiguration = _configurationsList.First((c) => c.Name == name); this.interfaceName = networkInfo != null ? networkInfo.IfName : "N/A"; this.addresses = networkInfo != null?String.Join(", ", networkInfo.IP) : ""; this.reason = reason; _currentNetworks = _networkChangeDetector.CurrentNetworks; _currentNetwork = networkInfo != null?_currentNetworks.FirstOrDefault((n) => networkInfo.IfName == n.IfName) : null; _currentProxySettings = proxySettings; RaisePropertyChanged("LastUpdateTime"); RaisePropertyChanged("ActiveConfiguration"); RaisePropertyChanged("InterfaceName"); RaisePropertyChanged("Addresses"); RaisePropertyChanged("Reason"); RaisePropertyChanged("CurrentNetworks"); RaisePropertyChanged("CurrentNetwork"); RaisePropertyChanged("CurrentProxySettings"); log.Debug("Sending ChangeMessage"); ChangeMessage msg = new ChangeMessage() { ConfName = name, Network = networkInfo, ProxySettings = proxySettings, Reason = reason }; Messenger.Default.Send <ChangeMessage>(msg); } catch (Exception ex) { log.Error("Failure", ex); } }
/// <summary> /// Send a POST request to a web page. Returns the contents of the page. /// </summary> /// <param name="url">The address to POST to.</param> /// <param name="data">The data to POST.</param> public string Post(string url, string data, ProxySettings settings) { try { byte[] buffer = Encoding.ASCII.GetBytes(data); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); // Use a proxy if (settings.UseProxy) { IWebProxy proxy = request.Proxy; WebProxy myProxy = new WebProxy(); Uri newUri = new Uri(settings.ProxyAddress); myProxy.Address = newUri; myProxy.Credentials = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword); request.Proxy = myProxy; } // Send request request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = buffer.Length; request.CookieContainer = cookies; Stream postData = request.GetRequestStream(); postData.Write(buffer, 0, buffer.Length); postData.Close(); // Get and return response request.CookieContainer = cookies; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream Answer = response.GetResponseStream(); StreamReader answer = new StreamReader(Answer); return answer.ReadToEnd(); } catch (Exception ex) { return "ERROR: " + ex.Message; } }
private void SendToSlack(AsyncLogEventInfo info) { var message = RenderLogEvent(Layout, info.LogEvent); SlackMessageBuilder slack; if (UseProxy) { var proxy = new ProxySettings { Host = ProxyHost, Port = ProxyPort, User = ProxyUser, Password = ProxyPassword }; slack = SlackMessageBuilder.Build(WebHookUrl, proxy) .OnError(e => info.Continuation(e)) .WithMessage(message); } else { slack = SlackMessageBuilder .Build(WebHookUrl) .OnError(e => info.Continuation(e)) .WithMessage(message); } if (ShouldIncludeProperties(info.LogEvent) || ContextProperties.Count > 0) { var color = GetSlackColorFromLogLevel(info.LogEvent.Level); Attachment attachment = new Attachment(info.LogEvent.Message) { Color = color }; var allProperties = GetAllProperties(info.LogEvent); foreach (var property in allProperties) { if (string.IsNullOrEmpty(property.Key)) { continue; } var propertyValue = property.Value?.ToString(); if (string.IsNullOrEmpty(propertyValue)) { continue; } attachment.Fields.Add(new Field(property.Key) { Value = propertyValue, Short = true }); } if (attachment.Fields.Count > 0) { slack.AddAttachment(attachment); } } var exception = info.LogEvent.Exception; if (!Compact && exception != null) { var color = GetSlackColorFromLogLevel(info.LogEvent.Level); var exceptionAttachment = new Attachment(exception.Message) { Color = color }; exceptionAttachment.Fields.Add(new Field("StackTrace") { Title = $"Type: {exception.GetType()}", Value = exception.StackTrace ?? "N/A" }); slack.AddAttachment(exceptionAttachment); } slack.Send(); }
public void SetUp() { this.settings = new ProxySettings(); }
public static IEnumerable <ProxySettings> Get_WMIRegProxy(Args_Get_WMIRegProxy args = null) { if (args == null) { args = new Args_Get_WMIRegProxy(); } var ProxySettings = new List <ProxySettings>(); foreach (var Computer in args.ComputerName) { try { var RegProvider = WmiWrapper.GetClass($@"\\{Computer}\ROOT\DEFAULT", "StdRegProv", args.Credential); var Key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings"; // HKEY_CURRENT_USER var HKCU = 2147483649; var outParams = WmiWrapper.CallMethod(RegProvider, "GetStringValue", new Dictionary <string, object> { { "hDefKey", HKCU }, { "sSubKeyName", Key }, { "sValueName", "ProxyServer" } }) as System.Management.ManagementBaseObject; var ProxyServer = outParams["sValue"] as string; outParams = WmiWrapper.CallMethod(RegProvider, "GetStringValue", new Dictionary <string, object> { { "hDefKey", HKCU }, { "sSubKeyName", Key }, { "sValueName", "AutoConfigURL" } }) as System.Management.ManagementBaseObject; var AutoConfigURL = outParams["sValue"] as string; var Wpad = ""; if (AutoConfigURL != null && AutoConfigURL != "") { try { Wpad = (new System.Net.WebClient()).DownloadString(AutoConfigURL); } catch { Logger.Write_Warning($@"[Get-WMIRegProxy] Error connecting to AutoConfigURL : {AutoConfigURL}"); } } if (ProxyServer != null || AutoConfigURL != null) { var Out = new ProxySettings { ComputerName = Computer, ProxyServer = ProxyServer, AutoConfigURL = AutoConfigURL, Wpad = Wpad }; ProxySettings.Add(Out); } else { Logger.Write_Warning($@"[Get-WMIRegProxy] No proxy settings found for {Computer}"); } } catch (Exception e) { Logger.Write_Warning($@"[Get-WMIRegProxy] Error enumerating proxy settings for {Computer} : {e}"); } } return(ProxySettings); }
public ProxySettings ProxySettings() { var settings = new ProxySettings(GetConfigInt("network.proxy.type") == 1, GetConfig("network.proxy.http"), GetConfigInt("network.proxy.http_port"), GetConfig("network.proxy.ftp"), GetConfigInt("network.proxy.ftp_port"), GetConfig("network.proxy.ssl"), GetConfigInt("network.proxy.ssl_port"), GetConfig("network.proxy.socks"), GetConfigInt("network.proxy.socks_port") ); return settings; }
private void btnProxySettingsClick(object sender, EventArgs e) { var frm = new ProxySettings(); frm.ShowDialog(this); }
public ProxySettingsLoadedEvent(ProxySettings proxySettings) { ProxySettings = proxySettings; }
public SessionActivity(Logger logger, SessionsOptions options, ProxySettings proxySettings) { this.logger = logger; this.options = options; sessionManager = new SessionManager(proxySettings); }
public CommonModelFactory(AdminAreaSettings adminAreaSettings, AppSettings appSettings, CatalogSettings catalogSettings, CurrencySettings currencySettings, IActionContextAccessor actionContextAccessor, IAuthenticationPluginManager authenticationPluginManager, IBaseAdminModelFactory baseAdminModelFactory, ICurrencyService currencyService, ICustomerService customerService, IEventPublisher eventPublisher, INopDataProvider dataProvider, IDateTimeHelper dateTimeHelper, INopFileProvider fileProvider, IExchangeRatePluginManager exchangeRatePluginManager, IHttpContextAccessor httpContextAccessor, ILanguageService languageService, ILocalizationService localizationService, IMaintenanceService maintenanceService, IMeasureService measureService, IMultiFactorAuthenticationPluginManager multiFactorAuthenticationPluginManager, IOrderService orderService, IPaymentPluginManager paymentPluginManager, IPickupPluginManager pickupPluginManager, IPluginService pluginService, IProductService productService, IReturnRequestService returnRequestService, ISearchTermService searchTermService, IServiceCollection serviceCollection, IShippingPluginManager shippingPluginManager, IStaticCacheManager staticCacheManager, IStoreContext storeContext, IStoreService storeService, ITaxPluginManager taxPluginManager, IUrlHelperFactory urlHelperFactory, IUrlRecordService urlRecordService, IWebHelper webHelper, IWidgetPluginManager widgetPluginManager, IWorkContext workContext, MeasureSettings measureSettings, NopHttpClient nopHttpClient, ProxySettings proxySettings) { _adminAreaSettings = adminAreaSettings; _appSettings = appSettings; _catalogSettings = catalogSettings; _currencySettings = currencySettings; _actionContextAccessor = actionContextAccessor; _authenticationPluginManager = authenticationPluginManager; _baseAdminModelFactory = baseAdminModelFactory; _currencyService = currencyService; _customerService = customerService; _eventPublisher = eventPublisher; _dataProvider = dataProvider; _dateTimeHelper = dateTimeHelper; _exchangeRatePluginManager = exchangeRatePluginManager; _httpContextAccessor = httpContextAccessor; _languageService = languageService; _localizationService = localizationService; _maintenanceService = maintenanceService; _measureService = measureService; _multiFactorAuthenticationPluginManager = multiFactorAuthenticationPluginManager; _fileProvider = fileProvider; _orderService = orderService; _paymentPluginManager = paymentPluginManager; _pickupPluginManager = pickupPluginManager; _pluginService = pluginService; _productService = productService; _returnRequestService = returnRequestService; _searchTermService = searchTermService; _serviceCollection = serviceCollection; _shippingPluginManager = shippingPluginManager; _staticCacheManager = staticCacheManager; _storeContext = storeContext; _storeService = storeService; _taxPluginManager = taxPluginManager; _urlHelperFactory = urlHelperFactory; _urlRecordService = urlRecordService; _webHelper = webHelper; _widgetPluginManager = widgetPluginManager; _workContext = workContext; _measureSettings = measureSettings; _nopHttpClient = nopHttpClient; _proxySettings = proxySettings; }
async private Task LoadAsync() { _lastLoad = DateTime.Now; _isInitialized = true; try { string geoJsonString = String.Empty; if (_target.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || _target.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { using (var clientHandler = new HttpClientHandler()) { var proxy = ProxySettings.Proxy(_target); if (proxy != null) { clientHandler.UseProxy = true; clientHandler.Proxy = proxy; } using (var httpClient = new HttpClient(clientHandler)) { if (_webAuthorization != null) { await _webAuthorization.AddAuthorizationHeaders(httpClient); } var httpResponseMessage = await httpClient.GetAsync(_target); geoJsonString = await httpResponseMessage.Content.ReadAsStringAsync(); } } } else { geoJsonString = System.IO.File.ReadAllText(_target); } var geoJson = JsonConvert.DeserializeObject <GeoJsonFeatures>(geoJsonString); List <IFeature> features = new List <IFeature>(); foreach (var geoJsonFeature in geoJson.Features) { var feature = new Feature(); feature.Shape = geoJsonFeature.ToGeometry(); IDictionary <string, object> properties = null; if (feature.Shape != null) { if (_envelope == null) { _envelope = new Envelope(feature.Shape.Envelope); } else { _envelope.Union(feature.Shape.Envelope); } } try { geoJsonFeature.PropertiesToDict(); properties = (IDictionary <string, object>)geoJsonFeature.Properties; } catch { } if (properties != null) { foreach (var key in properties.Keys) { feature.Fields.Add(new FieldValue(key, properties[key])); } } features.Add(feature); } _features = features; } catch (Exception ex) { this.LastException = ex; } }