/// <summary> /// Synchronize the <see cref="AppList"/> with the sync server and (un)apply <see cref="AccessPoint"/>s accordingly. /// </summary> /// <param name="resetMode">Controls how synchronization data is reset.</param> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="InvalidDataException">A problem occurred while deserializing the XML data or the specified crypto key was wrong.</exception> /// <exception cref="KeyNotFoundException">An <see cref="AccessPoint"/> reference to a <see cref="Capability"/> is invalid.</exception> /// <exception cref="ConflictException">One or more new <see cref="AccessPoint"/> would cause a conflict with the existing <see cref="AccessPoint"/>s in <see cref="AppList"/>.</exception> /// <exception cref="WebException">A problem occurred while communicating with the sync server or while downloading additional data (such as icons).</exception> /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception> public void Sync(SyncResetMode resetMode = SyncResetMode.None) { using var webClient = new WebClientTimeout { Credentials = new NetworkCredential(Config.SyncServerUsername, Config.SyncServerPassword), CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) }; var uri = new Uri(_syncServer, new Uri(MachineWide ? "app-list-machine" : "app-list", UriKind.Relative)); ExceptionUtils.Retry<SyncRaceException>(delegate { Handler.CancellationToken.ThrowIfCancellationRequested(); // ReSharper disable AccessToDisposedClosure var data = DownloadAppList(webClient, uri, resetMode); HandleDownloadedAppList(data, resetMode); UploadAppList(webClient, uri, resetMode); // ReSharper restore AccessToDisposedClosure }, maxRetries: 3); // Save reference point for future syncs AppList.SaveXml(AppListPath + AppListLastSyncSuffix); Handler.CancellationToken.ThrowIfCancellationRequested(); }
/// <summary> /// Performs a feed search query using the <see cref="Config.FeedMirror"/>. /// </summary> /// <param name="config">The current configuration determining which mirror server to query.</param> /// <param name="keywords">The keywords to search for.</param> public static SearchQuery Perform([NotNull] Config config, [CanBeNull] string keywords) { #region Sanity checks if (config == null) { throw new ArgumentNullException("config"); } #endregion if (string.IsNullOrEmpty(keywords)) { return(new SearchQuery()); } var url = new Uri( config.FeedMirror.EnsureTrailingSlash(), new Uri("search/?q=" + Uri.EscapeUriString(keywords), UriKind.Relative)); Log.Info("Performing search query: " + url.ToStringRfc()); using (var webClient = new WebClientTimeout()) { var result = XmlStorage.FromXmlString <SearchQuery>(webClient.DownloadString(url)); result.Keywords = keywords; return(result); } }
/// <summary> /// Adds a feed to the list of custom feeds. /// </summary> private void AddCustomFeed(string input) { FeedUri feedUri; try { feedUri = new FeedUri(input); } catch (UriFormatException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } if (_interfaceUri.IsFile) { if (!File.Exists(_interfaceUri.LocalPath)) { Msg.Inform(this, string.Format(Resources.FileOrDirNotFound, _interfaceUri.LocalPath), MsgSeverity.Warn); return; } } else { Feed feed = null; try { using var handler = new DialogTaskHandler(this); handler.RunTask(new SimpleTask(Resources.CheckingFeed, delegate { using var webClient = new WebClientTimeout(); feed = XmlStorage.FromXmlString <Feed>(webClient.DownloadString(feedUri)); })); }
/// <summary> /// Query Google Async. /// </summary> /// <param name="request"></param> /// <param name="timeout"></param> /// <param name="token"></param> /// <returns>Task[TResponse]</returns> protected internal static Task <TResponse> QueryGoogleApiAsync(TRequest request, TimeSpan timeout, CancellationToken token = default(CancellationToken)) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var uri = request.GetUri(); var webClient = new WebClientTimeout(timeout); var taskCompletionSource = new TaskCompletionSource <TResponse>(); if (request is IJsonRequest) { webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var jsonString = JsonConvert.SerializeObject(request, jsonSerializerSettings); webClient.UploadStringTaskAsync(uri, WebRequestMethods.Http.Post, jsonString) .ContinueWith(x => GenericEngine <TRequest, TResponse> .JsonRequestAsync(x, taskCompletionSource), TaskContinuationOptions.ExecuteSynchronously); return(taskCompletionSource.Task); } if (request is IQueryStringRequest) { webClient.DownloadDataTaskAsync(uri, timeout, token) .ContinueWith(x => GenericEngine <TRequest, TResponse> .QuerystringRequestAsync(x, taskCompletionSource), TaskContinuationOptions.ExecuteSynchronously); return(taskCompletionSource.Task); } throw new InvalidOperationException("Invalid Request. Request class missing Request interface implementation."); }
private void CheckCryptoKey() { var appListUri = new Uri(_config.SyncServer, new Uri("app-list", UriKind.Relative)); using var webClient = new WebClientTimeout { Credentials = new NetworkCredential(_config.SyncServerUsername, _config.SyncServerPassword), CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) }; try { AppList.LoadXmlZip(new MemoryStream(webClient.DownloadData(appListUri)), _config.SyncCryptoKey); } #region Error handling catch (WebException ex) when(ex.Status == WebExceptionStatus.ProtocolError && (ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Unauthorized) { // Wrap exception to add context information throw new WebException(Resources.SyncCredentialsInvalid, ex, ex.Status, ex.Response); } catch (ZipException ex) { // Wrap exception to add context information if (ex.Message == "Invalid password for AES") { throw new InvalidDataException(Resources.SyncCryptoKeyInvalid); } else { throw new InvalidDataException(Resources.SyncServerDataDamaged, ex); } } #endregion }
private void Initialize() { _stopwatch = new Stopwatch(); _webClient = new WebClientTimeout(3000); _webClient.DownloadProgressChanged += HandleDownloadProgressChanged; _webClient.DownloadStringCompleted += HandleDownloadStringCompleted; _webClient.DownloadFileCompleted += HandleDownloadFileCompleted; }
public void LoadFromUrl() { using (WebClientTimeout client = new WebClientTimeout(5000)) { byte[] imageBuffer = client.DownloadData(this.Image); this.BannerPixbuf = new Gdk.Pixbuf(imageBuffer); //imageBuffer); } }
public Starbook(IPAddress ipAddress) { this.IPAddress = ipAddress; this.J2000 = true; this.web = new WebClientTimeout() { Timeout = 5000 }; }
//--------------------// #region Sync /// <summary> /// Synchronize the <see cref="AppList"/> with the sync server and (un)apply <see cref="AccessPoint"/>s accordingly. /// </summary> /// <param name="resetMode">Controls how synchronization data is reset.</param> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="InvalidDataException">A problem occurred while deserializing the XML data or the specified crypto key was wrong.</exception> /// <exception cref="WebException">A problem occured while communicating with the sync server or while downloading additional data (such as icons).</exception> /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception> public void Sync(SyncResetMode resetMode = SyncResetMode.None) { if (!_server.IsValid) { throw new InvalidDataException(Resources.PleaseConfigSync); } var appListUri = new Uri(_server.Uri, new Uri(MachineWide ? "app-list-machine" : "app-list", UriKind.Relative)); using (var webClient = new WebClientTimeout { Credentials = _server.Credentials, CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) }) { ExceptionUtils.Retry <WebRaceConditionException>(delegate { Handler.CancellationToken.ThrowIfCancellationRequested(); byte[] appListData; try { appListData = DownloadAppList(appListUri, webClient, resetMode); } #region Error handling catch (WebException ex) when(ex.Status == WebExceptionStatus.ProtocolError && (ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Unauthorized) { Handler.CancellationToken.ThrowIfCancellationRequested(); throw new WebException(Resources.SyncCredentialsInvalid, ex, ex.Status, ex.Response); } #endregion HandleDownloadedAppList(resetMode, appListData); try { UploadAppList(appListUri, webClient, resetMode); } #region Error handling catch (WebException ex) when(ex.Status == WebExceptionStatus.ProtocolError && (ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.PreconditionFailed) { Handler.CancellationToken.ThrowIfCancellationRequested(); throw new WebRaceConditionException(ex); } #endregion }, maxRetries: 3); } // Save reference point for future syncs AppList.SaveXml(AppListPath + AppListLastSyncSuffix); Handler.CancellationToken.ThrowIfCancellationRequested(); }
private byte[] DownloadAppList([NotNull] Uri appListUri, [NotNull] WebClientTimeout webClient, SyncResetMode resetMode) { if (resetMode == SyncResetMode.Server) { return(new byte[0]); } byte[] data = null; Handler.RunTask(new SimpleTask(Resources.SyncDownloading, () => { data = webClient.DownloadData(appListUri); })); return(data); }
private static TResponse QuerystringRequest(TRequest request, TimeSpan timeout) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var uri = request.GetUri(); var webClient = new WebClientTimeout(timeout); var downloadData = webClient.DownloadData(uri); return(GenericEngine <TRequest, TResponse> .Deserialize(downloadData)); }
private Catalog DownloadCatalog([NotNull] FeedUri source) { if (source.IsFile) { return(XmlStorage.LoadXml <Catalog>(source.LocalPath)); } Log.Info("Downloading catalog: " + source.ToStringRfc()); byte[] data; using (var webClient = new WebClientTimeout()) data = webClient.DownloadData(source); _trustManager.CheckTrust(data, source); return(XmlStorage.LoadXml <Catalog>(new MemoryStream(data))); }
private static void CheckOriginXB1() { try { var wc = new WebClientTimeout { Proxy = null, Timeout = 10000 }; var str = wc.DownloadString("http://origin.xb1.warframe.com/index.txt.lzma"); FlatFile.WriteStatus("originxb1", true); } catch (Exception ex) { FlatFile.WriteStatus("originxb1", false); Log.ErrorFormat("Origin XB1 check failed: {0}", ex.Message); } }
public SyncDeviceManagerService(ISyncDeviceSpecifications deviceSpecifications, ISyncDiscoveryService discoveryService) { Console.WriteLine("SyncDeviceManagerService - Starting..."); OnStatusUpdated += (status) => {}; OnDeviceUpdated += (device) => {}; OnDevicesUpdated += (devices) => {}; OnDeviceAdded += (device) => {}; OnDeviceRemoved += (device) => {}; _devices = new List<SyncDevice>(); _deviceSpecifications = deviceSpecifications; _discoveryService = discoveryService; _discoveryService.OnDeviceFound += HandleOnDeviceFound; _discoveryService.OnDiscoveryProgress += HandleOnDiscoveryProgress; _webClient = new WebClientTimeout(3000); _webClientRemote = new WebClientTimeout(3000); }
private static void CheckForums() { try { var wc = new WebClientTimeout { Proxy = null, Timeout = 10000 }; var str = wc.DownloadString("https://forums.warframe.com"); if (!str.Contains("div")) { throw new Exception("No div detected in str"); } FlatFile.WriteStatus("forums", true); } catch (Exception ex) { FlatFile.WriteStatus("forums", false); Log.ErrorFormat("Forums check failed: {0}", ex.Message); } }
private static TResponse JsonRequest(TRequest request, TimeSpan timeout) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var webClient = new WebClientTimeout(timeout); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var uri = request.GetUri(); var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var jsonString = JsonConvert.SerializeObject(request, jsonSerializerSettings); var uploadString = webClient.UploadString(uri, WebRequestMethods.Http.Post, jsonString); return(GenericEngine <TRequest, TResponse> .Deserialize(uploadString)); }
private static void CheckCryptoKey(SyncServer server, string key) { var appListUri = new Uri(server.Uri, new Uri("app-list", UriKind.Relative)); using (var webClient = new WebClientTimeout { Credentials = server.Credentials, CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) }) { try { AppList.LoadXmlZip(new MemoryStream(webClient.DownloadData(appListUri)), key); } #region Error handling catch (WebException ex) { // Wrap exception to add context information if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { throw new WebException(Resources.SyncCredentialsInvalid, ex); } } throw; } catch (ZipException ex) { // Wrap exception to add context information if (ex.Message == "Invalid password") { throw new InvalidDataException(Resources.SyncCryptoKeyInvalid); } throw new InvalidDataException(Resources.SyncServerDataDamaged, ex); } #endregion } }
/// <summary> /// Upload the encrypted AppList back to the server (unless the client was reset) /// </summary> private void UploadAppList([NotNull] Uri appListUri, [NotNull] WebClientTimeout webClient, SyncResetMode resetMode) { if (resetMode == SyncResetMode.Client) { return; } var memoryStream = new MemoryStream(); AppList.SaveXmlZip(memoryStream, _cryptoKey); // Prevent "lost updates" (race conditions) with HTTP ETags if (resetMode == SyncResetMode.None && (appListUri.Scheme == "http" || appListUri.Scheme == "https")) { if (!string.IsNullOrEmpty(webClient.ResponseHeaders[HttpResponseHeader.ETag])) { webClient.Headers[HttpRequestHeader.IfMatch] = webClient.ResponseHeaders[HttpResponseHeader.ETag]; } } Handler.RunTask(new SimpleTask(Resources.SyncUploading, () => webClient.UploadData(appListUri, "PUT", memoryStream.ToArray()))); }
public async Task <HDriveData> CollectData(string ipAddress, string mac) { int protocolVersion = 0; int fwVersion = 0; int serialNumber = 0; int bootloderVersion = 0; int appId = 0; string guiVersion = "N/A"; DebugConsoleText += System.Environment.NewLine + DateTime.Now.TimeOfDay + " reading Web-Gui version of:" + ipAddress; DebugConsoleText += System.Environment.NewLine + DateTime.Now.TimeOfDay + " Reading objects from motor:" + ipAddress; try { using (var client = new WebClientTimeout()) { string downloadString = client.DownloadString("http://" + ipAddress); guiVersion = GetBetween(downloadString, "Web-Gui version", "</p>"); } using (var client = new WebClientTimeout()) { int subindex = 22; int index = 4; string downloadString = client.DownloadString("http://" + ipAddress + "/getData.cgi?obj=" + (subindex << 8 | index)); int.TryParse(downloadString, out protocolVersion); } using (var client = new WebClientTimeout()) { int subindex = 0; int index = 3; string downloadString = client.DownloadString("http://" + ipAddress + "/getData.cgi?obj=" + (subindex << 8 | index)); int.TryParse(downloadString, out fwVersion); } using (var client = new WebClientTimeout()) { int subindex = 13; int index = 3; string downloadString = client.DownloadString("http://" + ipAddress + "/getData.cgi?obj=" + (subindex << 8 | index)); int.TryParse(downloadString, out serialNumber); } using (var client = new WebClientTimeout()) { int subindex = 15; int index = 3; string downloadString = client.DownloadString("http://" + ipAddress + "/getData.cgi?obj=" + (subindex << 8 | index)); int.TryParse(downloadString, out appId); } using (var client = new WebClientTimeout()) { int subindex = 16; int index = 3; string downloadString = client.DownloadString("http://" + ipAddress + "/getData.cgi?obj=" + (subindex << 8 | index)); int.TryParse(downloadString, out bootloderVersion); } if (guiVersion.Length > 10) { guiVersion = "N/A"; } } catch (Exception e) { Console.WriteLine(e); } return(new HDriveData(ipAddress, mac, protocolVersion, fwVersion, serialNumber, bootloderVersion, appId, guiVersion)); }
//--------------------// #region Sync /// <summary> /// Synchronize the <see cref="AppList"/> with the sync server and (un)apply <see cref="AccessPoint"/>s accordingly. /// </summary> /// <param name="resetMode">Controls how synchronization data is reset.</param> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="InvalidDataException">A problem occurred while deserializing the XML data or if the specified crypto key was wrong.</exception> /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception> /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception> public void Sync(SyncResetMode resetMode) { var appListUri = new Uri(_server.Uri, new Uri(MachineWide ? "app-list-machine" : "app-list", UriKind.Relative)); using (var webClient = new WebClientTimeout { Credentials = _server.Credentials, CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) }) { ExceptionUtils.Retry <TimeoutException>(delegate { Handler.CancellationToken.ThrowIfCancellationRequested(); byte[] appListData; try { appListData = DownloadAppList(appListUri, webClient, resetMode); } #region Error handling catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.ProtocolError: var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { throw new WebException(Resources.SyncCredentialsInvalid, ex); } else { throw; } case WebExceptionStatus.Timeout: throw new TimeoutException(ex.Message, ex); default: if (ex.InnerException != null && ex.InnerException.InnerException is FileNotFoundException) { appListData = new byte[0]; } else { throw; } break; } } #endregion HandleDownloadedAppList(resetMode, appListData); try { UploadAppList(appListUri, webClient, resetMode); } #region Error handling catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.PreconditionFailed) { Handler.CancellationToken.ThrowIfCancellationRequested(); throw new TimeoutException("Race condition encountered while syncing."); } } else { throw; } } #endregion }, maxRetries: 3); } // Save reference point for future syncs AppList.SaveXml(AppListPath + AppListLastSyncSuffix); Handler.CancellationToken.ThrowIfCancellationRequested(); }
/// <summary> /// Adds a feed to the list of custom feeds. /// </summary> private void AddCustomFeed(string input) { FeedUri feedUri; try { feedUri = new FeedUri(input); } catch (UriFormatException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } if (_interfaceUri.IsFile) { if (!File.Exists(_interfaceUri.LocalPath)) { Msg.Inform(this, string.Format(Resources.FileOrDirNotFound, _interfaceUri.LocalPath), MsgSeverity.Warn); return; } } else { Feed feed = null; try { using (var handler = new DialogTaskHandler(this)) { handler.RunTask(new SimpleTask(Resources.CheckingFeed, delegate { using (var webClient = new WebClientTimeout()) feed = XmlStorage.FromXmlString <Feed>(webClient.DownloadString(feedUri)); })); } } #region Error handling catch (OperationCanceledException) { return; } catch (IOException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } catch (InvalidDataException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } catch (WebException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } catch (UnauthorizedAccessException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } #endregion // Ensure a matching <feed-for> is present for online feeds if (feed.FeedFor.All(entry => entry.Target != _interfaceUri)) { if (!Msg.YesNo(this, Resources.IgnoreMissingFeedFor, MsgSeverity.Warn)) { return; } } } var reference = new FeedReference { Source = feedUri }; if (_interfacePreferences.Feeds.Contains(reference)) { return; } _interfacePreferences.Feeds.Add(reference); listBoxFeeds.Items.Add(reference); }
public HttpService() { _webClient = new WebClientTimeout(); }