/// <summary> /// Downloads the update configurations from the server. /// </summary> /// <param name="configFileUri">The url of the configuration file.</param> /// <param name="credentials">The HTTP authentication credentials.</param> /// <param name="proxy">The optional proxy to use.</param> /// <param name="cancellationTokenSource"> /// The optional <see cref="CancellationTokenSource" /> to use for canceling the /// operation. /// </param> /// <param name="timeout">The timeout for the download request. In milliseconds. Default 10000.</param> /// <returns>Returns an <see cref="IEnumerable{UpdateConfiguration}" /> containing the package configurations.</returns> public static async Task <IEnumerable <UpdateConfiguration> > DownloadAsync(Uri configFileUri, NetworkCredential credentials, WebProxy proxy, CancellationTokenSource cancellationTokenSource = null, int timeout = 10000) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; var request = (HttpWebRequest)WebRequestWrapper.Create(configFileUri); request.Timeout = timeout; if (credentials != null) { request.Credentials = credentials; } if (proxy != null) { request.Proxy = proxy; } string source; var response = await request.GetResponseAsync(); using (var sr = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException( "The response stream of the configuration file web request is invalid.")) ) { source = await sr.ReadToEndAsync(); } return(!string.IsNullOrEmpty(source) ? Serializer.Deserialize <IEnumerable <UpdateConfiguration> >(source) : Enumerable.Empty <UpdateConfiguration>()); }
private static async Task <string> WebRequest(string url, IEnumerable <string[]> parameters, bool post = false) { var oauth = new OAuth(); var nonce = OAuth.Nonce(); var timestamp = OAuth.TimeStamp(); var signature = OAuth.Signature(post ? "POST" : "GET", url, nonce, timestamp, oauth.AccessToken, oauth.AccessTokenSecret, parameters); var authorizeHeader = OAuth.AuthorizationHeader(nonce, timestamp, oauth.AccessToken, signature); var parameterStrings = parameters.Select(p => $"{OAuth.UrlEncode(p[0])}={OAuth.UrlEncode(p[1])}").ToList(); if (!post) { url += "?" + string.Join("&", parameterStrings); } var request = WebRequestWrapper.Create(new Uri(url)); request.Headers.Add("Authorization", authorizeHeader); request.Method = post ? "POST" : "GET"; if (post) { Trace.TraceInformation(string.Join("&", parameterStrings)); request.ContentType = "application/x-www-form-urlencoded"; if (parameters != null) { using (var requestStream = request.GetRequestStream()) { WriteStream(requestStream, string.Join("&", parameterStrings)); } } } using (var response = await request.GetResponseAsync()) { using (var stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var result = stream.ReadToEnd(); return(result); } } }
/// <summary> /// Downloads the update configurations from the server. /// </summary> /// <param name="configFileUri">The url of the configuration file.</param> /// <param name="credentials">The HTTP authentication credentials.</param> /// <param name="proxy">The optional proxy to use.</param> /// <param name="cancellationTokenSource"> /// The optional <see cref="CancellationTokenSource" /> to use for canceling the /// operation. /// </param> /// <param name="timeout">The timeout for the download request. In milliseconds. Default 10000.</param> /// <returns>Returns an <see cref="IEnumerable{UpdateConfiguration}" /> containing the package configurations.</returns> public static async Task <IEnumerable <UpdateConfiguration> > DownloadAsync(Uri configFileUri, NetworkCredential credentials, WebProxy proxy, CancellationTokenSource cancellationTokenSource = null, int timeout = 10000) { // Check for SSL and ignore it ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); }; var request = (HttpWebRequest)WebRequestWrapper.Create(configFileUri); request.Timeout = timeout; if (credentials != null) { request.Credentials = credentials; } if (proxy != null) { request.Proxy = proxy; } string source; var response = cancellationTokenSource != null ? await request.GetResponseAsync(cancellationTokenSource.Token) : (HttpWebResponse)await request.GetResponseAsync(); using (var sr = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException( "The response stream of the configuration file web request is invalid.")) ) { source = await sr.ReadToEndAsync(); } return(!string.IsNullOrEmpty(source) ? Serializer.Deserialize <IEnumerable <UpdateConfiguration> >(source) : Enumerable.Empty <UpdateConfiguration>()); }
/// <summary> /// Downloads the available update packages from the server. /// </summary> /// <seealso cref="DownloadPackagesAsync" /> public void DownloadPackages() { OnUpdateDownloadStarted(this, EventArgs.Empty); long received = 0; var total = PackageConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri)) .Where(updatePackageSize => updatePackageSize != null) .Sum(updatePackageSize => updatePackageSize.Value); if (!Directory.Exists(_applicationUpdateDirectory)) { Directory.CreateDirectory(_applicationUpdateDirectory); } foreach (var updateConfiguration in PackageConfigurations) { WebResponse webResponse = null; try { var webRequest = WebRequestWrapper.Create(updateConfiguration.UpdatePackageUri); if (HttpAuthenticationCredentials != null) { webRequest.Credentials = HttpAuthenticationCredentials; } using (webResponse = webRequest.GetResponse()) { var buffer = new byte[1024]; _packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion), Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip")); using (var fileStream = File.Create(Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip"))) { using (var input = webResponse.GetResponseStream()) { if (input == null) { throw new Exception("The response stream couldn't be read."); } var size = input.Read(buffer, 0, buffer.Length); while (size > 0) { fileStream.Write(buffer, 0, size); received += size; OnUpdateDownloadProgressChanged(received, (long)total, (float)(received / total) * 100); size = input.Read(buffer, 0, buffer.Length); } if (_downloadCancellationTokenSource.IsCancellationRequested) { return; } if (!updateConfiguration.UseStatistics || !IncludeCurrentPcIntoStatistics) { continue; } var response = new WebClient { Credentials = HttpAuthenticationCredentials }.DownloadString( $"{updateConfiguration.UpdatePhpFileUri}?versionid={updateConfiguration.VersionId}&os={SystemInformation.OperatingSystemName}"); // Only for calling it if (string.IsNullOrEmpty(response)) { return; } OnStatisticsEntryFailed(new StatisticsException(string.Format( _lp.StatisticsScriptExceptionText, response))); } } } } finally { webResponse?.Close(); } } }
/// <summary> /// Downloads the available update packages from the server. /// </summary> /// <seealso cref="DownloadPackagesAsync" /> public void DownloadPackages() { if (!Directory.Exists(_applicationUpdateDirectory)) { Directory.CreateDirectory(_applicationUpdateDirectory); } foreach (var updateConfiguration in PackageConfigurations) { WebResponse webResponse = null; try { var webRequest = WebRequestWrapper.Create(updateConfiguration.UpdatePackageUri); if (HttpAuthenticationCredentials != null) { webRequest.Credentials = HttpAuthenticationCredentials; } using (webResponse = webRequest.GetResponse()) { var buffer = new byte[1024]; _packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion), Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip")); using (var fileStream = File.Create(Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip"))) { using (var input = webResponse.GetResponseStream()) { if (input == null) { throw new Exception("The response stream couldn't be read."); } var size = input.Read(buffer, 0, buffer.Length); while (size > 0) { fileStream.Write(buffer, 0, size); size = input.Read(buffer, 0, buffer.Length); } if (!updateConfiguration.UseStatistics || !IncludeCurrentPcIntoStatistics) { continue; } var response = new WebClient { Credentials = HttpAuthenticationCredentials }.DownloadString( $"{updateConfiguration.UpdatePhpFileUri}?versionid={updateConfiguration.VersionId}&os={SystemInformation.OperatingSystemName}"); // Only for calling it if (string.IsNullOrEmpty(response)) { return; } } } } } finally { webResponse?.Close(); } } }
public void User(CancellationToken cancelationToken) { Task.Run(() => { while (cancelationToken.IsCancellationRequested == false) { //var delay = Task.Delay(30*1000, cancelationToken); //delay.Wait(cancelationToken); //if (delay.IsCanceled || delay.IsFaulted) break; Trace.TraceInformation("{ Start Twitter User Stream }"); const string url = "https://userstream.twitter.com/1.1/user.json"; var oauth = new OAuth(); var nonce = OAuth.Nonce(); var timestamp = OAuth.TimeStamp(); var signature = OAuth.Signature("GET", url, nonce, timestamp, oauth.AccessToken, oauth.AccessTokenSecret, null); var authorizeHeader = OAuth.AuthorizationHeader(nonce, timestamp, oauth.AccessToken, signature); var request = WebRequestWrapper.Create(new Uri(url)); request.Headers.Add("Authorization", authorizeHeader); try { using (var response = request.GetResponse()) using (var stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { stream.BaseStream.ReadTimeout = 60 * 1000; while (true) { var json = stream.ReadLine(); if (json == null) { Trace.TraceInformation("{ null }"); break; } if (cancelationToken.IsCancellationRequested) { break; } Trace.TraceInformation(string.IsNullOrWhiteSpace(json) ? "{ Blankline }" : json); var serializer = new JavaScriptSerializer(); var reply = serializer.Deserialize <Dictionary <string, object> >(json); if (reply != null && reply.ContainsKey("user")) { Trace.TraceInformation("{ tweet identified }"); var statuses = Status.ParseJson("[" + json + "]"); Application.Current.Dispatcher.InvokeAsync(() => { UpdateTimelines(statuses, TweetClassification.Home); }); //Application.Current.Dispatcher.InvokeAsync // (() => UpdateStatusHomeTimelineCommand.Command.Execute(statuses, Application.Current.MainWindow)); } } } } catch (WebException ex) { Trace.TraceError(ex.ToString()); } catch (ArgumentNullException ex) { Trace.TraceError(ex.ToString()); } catch (ArgumentException ex) { Trace.TraceError(ex.ToString()); } catch (InvalidOperationException ex) { Trace.TraceError(ex.ToString()); } catch (IOException ex) { Trace.TraceError(ex.ToString()); } } Trace.TraceInformation("{ Stream task ends }"); }, cancelationToken); }