public static string JudgeDownloadResult(DownloadResult res) { switch (res) { case DownloadResult.OK: //return "Download OK"; case DownloadResult.ExistedLocalFile: //return "Detect existed local package cache. Jump downloading"; case DownloadResult.LocalFileOperationError: //return "Couldn't operate local package cache"; case DownloadResult.NetworkError: //return "Network error"; case DownloadResult.VerificationError: //return "Un-matched verification code"; case DownloadResult.Timeout: //return "Network timeout"; case DownloadResult.NoPackage: //return "No matched package"; case DownloadResult.RemoteServerError: //return "Remote server return a error"; case DownloadResult.OutdatedVersion: //return "Outdated bpm version"; case DownloadResult.UnexceptError: //return "Unknow error"; return(I18N.Core($"Download_{res.ToString()}")); default: return(I18N.Core("Download_UnexceptError")); } }
async Task DownloadSyncObjectInstance(StreamInstance streamInstance, CancellationToken token) { DownloadResult downloadResult; Task <DownloadResult> task; lock (m_Tasks) { m_Tasks.TryGetValue(streamInstance.instance.ObjectId, out task); } if (task != null && !task.IsCompleted) { var result = await task; downloadResult = new DownloadResult { exception = result.exception, instanceData = new StreamInstanceData(streamInstance, result.instanceData.syncObject), downloadedDependencies = result.downloadedDependencies }; } else { lock (m_Tasks) { task = DownloadSyncInstanceDependencies(streamInstance, token); m_Tasks[streamInstance.instance.ObjectId] = task; } downloadResult = await task; } m_DownloadedInstances.Enqueue(downloadResult); }
public async Task FunctionsUpdateFile_UpdateDownloads_AddAllReturns() { //ARRANGE var log = new Mock <ILogger>(); var year = SectorTypes.Private.GetAccountingStartDate(2017).Year; IEnumerable <Return> returns = await _functions.SharedBusinessLogic.DataRepository .ToListAsync <Return>( r => r.AccountingDate.Year == year && r.Status == ReturnStatuses.Submitted && r.Organisation.Status == OrganisationStatuses.Active); //ACT await _functions.UpdateDownloadFilesAsync(log.Object, "*****@*****.**", true); //ASSERT //Check each return is in the download file var downloadFilePath = _functions.SharedBusinessLogic.FileRepository.GetFullPath( Path.Combine(ConfigHelpers.SharedOptions.DownloadsLocation, $"GPGData_{year}-{year + 1}.csv")); //Check the file exists Assert.That(await _functions.SharedBusinessLogic.FileRepository.GetFileExistsAsync(downloadFilePath), $"File '{downloadFilePath}' should exist"); //Get the actual results var actualResults = await _functions.SharedBusinessLogic.FileRepository.ReadCSVAsync <DownloadResult>(downloadFilePath); //Generate the expected results var expectedResults = returns.Select(r => DownloadResult.Create(r)).OrderBy(d => d.EmployerName).ToList(); //Check the results expectedResults.Compare(actualResults); }
public Task RequestLongProcessTaskAsync(string id) { var guid = Guid.NewGuid(); var timer = new Timer(async o => { var userIdentifyer = o as TaskId; var result = new DownloadResult { Id = id, Url = "http://pudim.com.br" }; if (!downloads.ContainsKey(userIdentifyer.Id)) { downloads[userIdentifyer.Id] = new List <DownloadResult>(); } downloads[userIdentifyer.Id].Add(result); await userIdentifyer.User.SendAsync("LongProcessFinished", result); timers[guid].Dispose(); timers.Remove(guid); }, new TaskId { Id = Context.UserIdentifier, User = Clients.User(Context.UserIdentifier) }, 5000, Timeout.Infinite); timers[guid] = timer; return(Task.CompletedTask); }
// Token: 0x0600223F RID: 8767 RVA: 0x0007EA34 File Offset: 0x0007CC34 private void GetListItemChangesSinceToken(IClientContext context, OwaIdentity identity, string listName, string location, out string changeToken, out bool hasChanges, DataProviderCallLogEvent logEvent) { changeToken = null; hasChanges = false; DownloadResult downloadResult = OneDriveProUtilities.SendRestRequest("POST", string.Format("{0}/_vti_bin/client.svc/web/lists/getByTitle('{1}')/GetListItemChangesSinceToken", context.Url, listName), identity, this.GetRequestStream(location, this.ChangeToken), logEvent, "GetListItemChangesSinceToken"); if (!downloadResult.IsSucceeded) { OneDriveProItemsPagingMetadata.TraceError(OneDriveProItemsPagingMetadata.LogMetadata.GetListItemChangesSinceToken, downloadResult.Exception); hasChanges = true; return; } using (XmlReader xmlReader = XmlReader.Create(downloadResult.ResponseStream)) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { if (xmlReader.LocalName == "Changes") { changeToken = xmlReader.GetAttribute("LastChangeToken"); } else if (xmlReader.LocalName == "row" && xmlReader.NamespaceURI == "#RowsetSchema") { hasChanges = true; break; } } } } }
/// <summary> /// Called when prices downloaded. /// </summary> /// <param name="result">The result.</param> private void OnPricesDownloaded(DownloadResult <SerializableECItemPrices> result) { if (CheckQueryStatus(result)) { return; } if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"Remaining ids: {String.Join(", ", s_queryMonitorList)}", printMethod: false); } Loaded = true; CachedUntil = DateTime.UtcNow.AddDays(1); // Reset query pending flag s_queryPending = false; EveMonClient.Trace("done"); EveMonClient.OnPricesDownloaded(null, String.Empty); // Save the file in cache SaveAsync(Filename, Util.SerializeToXmlDocument(Export())).ConfigureAwait(false); }
private void LogDownloadResult(DownloadResult result) { switch (result.Code) { case DownloadResult.ResultCode.Success: Log($"SUCCESS: {result.FileName}", LogType.Success); break; case DownloadResult.ResultCode.WebException: Log($"Interrupted: {result.FileName} | {result.FileUrl}", LogType.Error); break; case DownloadResult.ResultCode.RequestFailed: Log($"Request failed: {result.FileName} | {result.FileUrl}", LogType.Error); break; case DownloadResult.ResultCode.NotComplete: Log($"Not fully loaded: {result.FileName} | {result.FileUrl}", LogType.Error); break; default: Log("WTF?", LogType.None); break; } }
/// <summary> /// Tracks the event. /// </summary> /// <param name="type">The type.</param> /// <param name="category">The category.</param> /// <param name="action">The action.</param> private static void TrackEvent(Type type, string category, string action) { InitEvent(type, category, action); if (NetworkMonitor.IsNetworkAvailable) { DownloadResult <Image> result = HttpWebClientService.DownloadImage(new Uri(NetworkConstants.GoogleAnalyticsUrl), HttpMethod.Post, postdata: BuildQueryString()); if (!EveMonClient.IsDebugBuild) { return; } EveMonClient.Trace($"({category} - {action})"); if (result.Error != null) { EveMonClient.Trace($"{result.Error.Message}"); } return; } // Reschedule later otherwise Dispatcher.Schedule(TimeSpan.FromMinutes(1), () => TrackEvent(type, category, action)); if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"in {TimeSpan.FromMinutes(1)}"); } }
public static DownloadResult saveFileContent(Stream stream, String filename, String path) { DownloadResult result = new DownloadResult(); string targetFile = path + @"\" + filename; try { using (var responseStream = stream) { using (var fs = new FileStream(targetFile, FileMode.Append)) { long beforeLength = fs.Length; responseStream.CopyTo(fs); if (fs.Length == beforeLength) { result.state = 1; } } } } catch (Exception e) { Console.WriteLine("Exception caught: {0}", e); result.state = 2; } return(result); }
public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context) { List <Task <DownloadResult> > tasks = _urls.Select(DownloadUrl).ToList(); Task.WhenAll(tasks).Wait(); return(tasks.Where(x => !x.IsFaulted).Select(t => { string key = t.Result.Uri.ToString(); IDocument doc; if (_cacheResponse && context.ExecutionCache.TryGetValue(key, out doc)) { return doc; } DownloadResult result = t.Result; string uri = result.Uri.ToString(); doc = context.GetDocument(uri, result.Stream, new MetadataItems { { Keys.SourceUri, uri }, { Keys.SourceHeaders, result.Headers } }); if (_cacheResponse) { context.ExecutionCache.Set(key, doc); } return doc; })); }
/// <summary> /// Processes the queried eve flags. /// </summary> /// <param name="result">The result.</param> private static void OnDownloaded(DownloadResult <SerializableEveFlags> result) { if (result.Error != null) { // Reset query pending flag s_queryPending = false; EveMonClient.Trace(result.Error.Message); // Fallback EnsureInitialized(); return; } // Import the list Import(result.Result); // Reset query pending flag s_queryPending = false; // Notify the subscribers EveMonClient.OnEveFlagsUpdated(); // Save the file in cache LocalXmlCache.SaveAsync(Filename, Util.SerializeToXmlDocument(result.Result)). ConfigureAwait(false); }
public static bool Install(DownloadResult downloaded) { try { switch (downloaded.Enclosure.InstallerType) { case InstallerType.Archive: case InstallerType.ServiceArchive: { var tmpdir = CreateTempPath("PeerCastStation.Updater"); ZipFile.ExtractToDirectory(downloaded.FilePath, tmpdir); var appdir = Path.GetDirectoryName(GetProcessEntryFile()); StartUpdate(tmpdir, appdir, PeerCastApplication.Current?.Args ?? new string[0]); } PeerCastApplication.Current.Stop(); break; case InstallerType.Installer: Process.Start(downloaded.FilePath); PeerCastApplication.Current.Stop(); break; case InstallerType.ServiceInstaller: Process.Start(downloaded.FilePath, "/quiet"); break; case InstallerType.Unknown: throw new ApplicationException(); } return(true); } catch (Exception) { return(false); } }
/// <summary> /// Processes the queried notification text parser. /// </summary> /// <param name="result">The result.</param> private static void OnDownloaded(DownloadResult <string> result) { if (result.Error != null) { // Reset query pending flag s_queryPending = false; EveMonClient.Trace(result.Error.Message); return; } string[] referenceAssemblies = { typeof(Enumerable).Assembly.Location, typeof(YamlNode).Assembly.Location, }; // Revert to internal parser if the compilation fails for any reason s_parser = CodeCompiler.GenerateAssembly <EveNotificationTextParser>( referenceAssemblies, result.Result) ?? new InternalEveNotificationTextParser(); // Reset query pending flag // after we compiled the parser s_queryPending = false; s_cachedUntil = DateTime.UtcNow.AddHours(12); // Notify the subscribers NotificationTextParserUpdated?.ThreadSafeInvoke(null, EventArgs.Empty); }
private async Task DownloadSequentiallyAsync(Stopwatch sw, string[] urls) { int i = 0; Progress1.Value = 0; foreach (string url in urls) { string status = ""; try { _cancellation.Token.ThrowIfCancellationRequested(); TextBox1.Text += $"{url}..."; DownloadResult dlRes = await DownloadUrlAsync(url); status = $"{Math.Round(dlRes.Html.Length / 1024.0)}KB"; } catch (OperationCanceledException) { status = "CANCELED"; } catch (Exception) { status = "error"; } TextBox1.Text += $" {status} {sw.ElapsedMilliseconds}ms\n"; i++; Progress1.Value = i * 100 / urls.Length; } }
public async void CancelDownloadTask() { await LoginUtil.Instance.ValidateUserLogin("*****@*****.**", "1234", "AU"); DownloadResult downloadResult = new DownloadResult(); int bookId = 35; try { //for (int i = 0; i < 3; i++) //{ CancellationTokenSource source = new CancellationTokenSource(); source.CancelAfter(2000); //download this book downloadResult = await PublicationUtil.Instance.DownloadPublicationByBookId(bookId, source.Token, new DownloadProgressEventHandler((bytes, downloadSize) => { Debug.Write(bytes); })); Assert.IsTrue(downloadResult.DownloadStatus == DownLoadEnum.Canceled); //} } catch (Exception) { throw; } }
public static bool Install(DownloadResult downloaded) { try { switch (downloaded.Enclosure.InstallerType) { case InstallerType.Archive: case InstallerType.ServiceArchive: PeerCastApplication.Current.Stop(3); break; case InstallerType.Installer: System.Diagnostics.Process.Start(downloaded.FilePath); PeerCastApplication.Current.Stop(); break; case InstallerType.ServiceInstaller: System.Diagnostics.Process.Start(downloaded.FilePath, "/quiet"); break; case InstallerType.Unknown: throw new ApplicationException(); } return(true); } catch (Exception) { return(false); } }
/// <summary> /// Synchronously download an XML and deserializes it into the specified type. /// </summary> /// <typeparam name="T">The inner type to deserialize</typeparam> /// <param name="url">The url to query</param> /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param> /// <param name="postData">The post data.</param> /// <param name="transform">The XSL transform to apply, may be null.</param> internal static CCPAPIResult <T> DownloadAPIResult <T>(Uri url, bool acceptEncoded = false, string postData = null, XslCompiledTransform transform = null) { CCPAPIResult <T> result; try { DownloadResult <IXPathNavigable> apiResult = HttpWebClientService.DownloadXmlAsync(url, HttpMethod.Post, acceptEncoded, postData).Result; // Was there an HTTP error ? result = apiResult.Error != null ? new CCPAPIResult <T>(apiResult.Error) : DeserializeAPIResultCore <T>(apiResult.Result, transform); } catch (Exception e) { ExceptionHandler.LogException(e, true); result = new CCPAPIResult <T>(Enumerations.CCPAPI.CCPAPIErrors.Http, e.Message); EveMonClient.Trace( $"Method: DownloadAPIResult, url: {url.AbsoluteUri}, postdata: {postData}, type: {typeof(T).Name}", false); } // Returns return(result); }
private async Task <long?> DownloadUsingHttpDownloaderAsync(OperationContext context, ContentHash contentHash, string path) { var downloader = new ManagedParallelBlobDownloader( _parallelSegmentDownloadConfig, new AppTraceSourceContextAdapter(context, Tracer.Name, SourceLevels.All), VssClientHttpRequestSettings.Default.SessionId, _httpClient); var uri = await GetUriAsync(context, contentHash); if (uri == null) { return(null); } DownloadResult result = await downloader.DownloadAsync(path, uri.ToString(), knownSize : null, cancellationToken : context.Token); if (result.HttpStatusCode == HttpStatusCode.NotFound) { return(null); } else if (result.HttpStatusCode != HttpStatusCode.OK) { throw new ResultPropagationException(new ErrorResult($"Error in DownloadAsync({uri}) => [{path}]: HttpStatusCode={result.HttpStatusCode}. ErrorCode={result.ErrorCode}")); } return(result.BytesDownloaded); }
public static ToastNotification DownloadToast(string filename, DownloadResult result) { ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); switch (result) { case DownloadResult.Success: toastTextElements[0].AppendChild(toastXml.CreateTextNode("下载完成!")); toastTextElements[1].AppendChild(toastXml.CreateTextNode("文件:" + filename + "下载完成")); break; case DownloadResult.Failure: toastTextElements[0].AppendChild(toastXml.CreateTextNode("下载失败!")); toastTextElements[1].AppendChild(toastXml.CreateTextNode("文件:" + filename + "下载失败")); break; default: break; } var doc = new Windows.Data.Xml.Dom.XmlDocument(); ToastNotification toast = new ToastNotification(toastXml); return(toast); }
private DownloadResult Download(DownloadResult downloadResult) { try { // Logic to download file int i = 0; while (i < 10) { Thread.Sleep(10000); i++; string log = string.Format("Content Manager: Task - {4} - (Time {0}; ID: {1}) is downloading this File: '{2}' from URL: '{3}' ", DateTime.Now.ToString(), downloadResult.ContentItem.ID, downloadResult.ContentItem.FileName, downloadResult.ContentItem.URL, i.ToString()); CustomLogger.CustomLogger.WriteNormalLog(log); } downloadResult.Result = true; } catch (Exception ex) { #region Error LogEntry l = new LogEntry(); l.Message = string.Format("Error: {0}", ex.Message); l.Title = "MyApp Error"; l.Categories.Add(Category.General); l.Priority = Priority.Highest; l.ExtendedProperties.Add("Method", "DownloadError Download()"); if (ex.InnerException != null) { l.ExtendedProperties.Add("InnerException", ex.InnerException.Message); } CustomLogger.CustomLogger.WriteErrorLog(l); #endregion downloadResult.Error = ex; } return(downloadResult); }
/// <summary> /// Asynchronously download an XML and deserializes it into the specified type. /// </summary> /// <typeparam name="T">The inner type to deserialize</typeparam> /// <param name="url">The url to query</param> /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param> /// <param name="postData">The post data.</param> /// <param name="transform">The XSL transform to apply, may be null.</param> internal static async Task <CCPAPIResult <T> > DownloadAPIResultAsync <T>(Uri url, bool acceptEncoded = false, string postData = null, XslCompiledTransform transform = null) { DownloadResult <IXPathNavigable> asyncResult = await HttpWebClientService.DownloadXmlAsync(url, HttpMethod.Post, acceptEncoded, postData); CCPAPIResult <T> result; try { // Was there an HTTP error ? result = asyncResult.Error != null ? new CCPAPIResult <T>(asyncResult.Error) : DeserializeAPIResultCore <T>(asyncResult.Result, transform); // We got the result return(result); } catch (Exception e) { result = new CCPAPIResult <T>(HttpWebClientServiceException.Exception(url, e)); ExceptionHandler.LogException(e, false); EveMonClient.Trace( $"Method: DownloadAPIResultAsync, url: {url.AbsoluteUri}, postdata: {postData}, type: {typeof(T).Name}", false); } return(result); }
/// <summary> /// Processes the queried notification text parser. /// </summary> /// <param name="result">The result.</param> private static void OnDownloaded(DownloadResult<String> result) { if (result.Error != null) { // Reset query pending flag s_queryPending = false; EveMonClient.Trace(result.Error.Message); return; } string[] referenceAssemblies = { typeof(Enumerable).Assembly.Location, typeof(YamlNode).Assembly.Location, }; // Revert to internal parser if the compilation fails for any reason s_parser = CodeCompiler.GenerateAssembly<EveNotificationTextParser>(referenceAssemblies, result.Result) ?? new InternalEveNotificationTextParser(); // Reset query pending flag // after we compiled the parser s_queryPending = false; s_cachedUntil = DateTime.UtcNow.AddHours(12); EveMonClient.Trace(); // Notify the subscribers NotificationTextParserUpdated?.ThreadSafeInvoke(null, EventArgs.Empty); }
// Token: 0x0600020F RID: 527 RVA: 0x000081AC File Offset: 0x000063AC internal static DownloadResult SendRestRequest(string requestMethod, string requestUri, OwaIdentity identity, Stream requestStream, DataProviderCallLogEvent logEvent, string spCallName) { DownloadResult result; using (HttpClient httpClient = new HttpClient()) { HttpSessionConfig httpSessionConfig = new HttpSessionConfig { Method = requestMethod, Credentials = OauthUtils.GetOauthCredential(identity.GetOWAMiniRecipient()), UserAgent = OneDriveProUtilities.UserAgentString, RequestStream = requestStream, ContentType = "application/json;odata=verbose", PreAuthenticate = true }; httpSessionConfig.Headers = OneDriveProUtilities.GetOAuthRequestHeaders(); if (logEvent != null) { logEvent.TrackSPCallBegin(); } ICancelableAsyncResult cancelableAsyncResult = httpClient.BeginDownload(new Uri(requestUri), httpSessionConfig, null, null); cancelableAsyncResult.AsyncWaitHandle.WaitOne(); DownloadResult downloadResult = httpClient.EndDownload(cancelableAsyncResult); if (logEvent != null) { string correlationId = (downloadResult.ResponseHeaders == null) ? null : downloadResult.ResponseHeaders["SPRequestGuid"]; logEvent.TrackSPCallEnd(spCallName, correlationId); } result = downloadResult; } return(result); }
// Собственно сама качалка public DownloadResult DownloadFile(Preferences preferences, RemoteFile record) { string fileFullPath = $"{preferences.targetFolder}{record.name}"; string fileFullUrl = $"{FAYLOOBMENNIK_URL}{record.href }"; var result = new DownloadResult { FileName = fileFullPath, FileUrl = fileFullUrl }; string remoteFileUrl = ParseFileDirectLink(fileFullUrl, preferences); if (remoteFileUrl == null) { result.Code = DownloadResult.ResultCode.RequestFailed; return(result); } try { using (WebClient wc = new WebClient()) { wc.DownloadFile(new Uri(remoteFileUrl), fileFullPath); } result.Code = DownloadResult.ResultCode.Success; } catch (WebException) { result.Code = DownloadResult.ResultCode.WebException; } return(result); }
public static DownloadResult DownloadObject(DownloadRecord record, String targetFolder, long start = 0, long end = 199) { GetObjectRequest getObjectRequest = new GetObjectRequest() { BucketName = BosConfig.BucketName, Key = record.CloudFile.Key }; // 获取 范围内的数据 getObjectRequest.SetRange(start, end); // 获取Object,返回结果为BosObject对象 try { BosObject bosObject = GetBosClient().GetObject(getObjectRequest); Stream stream = bosObject.ObjectContent; return(FileUtil.saveFileContent(stream, record.FileName, targetFolder)); } catch (BceServiceException BceServiceException) { if (BceServiceException.Message.IndexOf("The requested range cannot be satisfied") != -1) { DownloadResult result2 = new DownloadResult(); result2.state = 1; return(result2); } Console.WriteLine("exception:" + BceServiceException); } DownloadResult result = new DownloadResult(); result.state = 2; return(result); }
public async Task <DownloadResult> Download(int id) { var result = new DownloadResult(); var file = FileRepository.GetById(id); if (file == null) { result.Result = Result.Failed; result.Message = "Không tìm thấy file"; return(result); } var path = string.IsNullOrEmpty(file.Path) ? Path.Combine(WebHostEnvironment.WebRootPath, "upload", file.HashName) : Path.Combine(WebHostEnvironment.WebRootPath, "upload", file.Path, file.HashName); if (!File.Exists(path)) { await Delete(file.Id); result.Result = Result.Failed; result.Message = "Không tìm thấy file"; return(result); } var memory = new MemoryStream(); using (var stream = new FileStream(path, FileMode.Open)) { await stream.CopyToAsync(memory); result.File = memory; result.Name = file.Name; } return(result); }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <returns>json:{"status"}</returns> private void EditorGetString(object obj) { DownloadResult result = obj as DownloadResult; try { string content = ""; HttpWebRequest request = WebRequest.Create(result.Url) as HttpWebRequest; request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; int statusCode = (int)response.StatusCode; if (response.StatusCode == HttpStatusCode.OK) { XLog.Log(TAG, "请求成功"); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8")); content = streamReader.ReadToEnd(); streamReader.Close(); response.Close(); } result.StatusCode = statusCode; result.Content = content; Results.Add(result); } catch (Exception exception) { XLog.LogError(TAG, exception.Message); result.StatusCode = -1; Results.Add(result); } }
private void ReportDownloadResult(DownloadResult downloadResult) { switch (downloadResult) { case DownloadResult.NetConnectError: // do nothing break; case DownloadResult.UndefineError: case DownloadResult.LocalHardDiskNoSpace: case DownloadResult.LocalIncorrectPathOrFileName: ChangeDownloadingStatus(DownloadStatus.DownloadFailed); break; case DownloadResult.FileNotExist: ChangeDownloadingStatus(DownloadStatus.DownloadFailed_FileNotExist); break; case DownloadResult.DownloadPause: ChangeDownloadingStatus(DownloadStatus.DownloadPause); break; case DownloadResult.DownloadFinished: ChangeDownloadingStatus(DownloadStatus.DownloadSuccess); break; } }
/// <summary> /// Queries the ids. /// </summary> /// <returns></returns> private async Task QueryIDs() { var idsToQuery = new List <int>(); var url = new Uri($"{NetworkConstants.EVECentralBaseUrl}{NetworkConstants.EVECentralAPIItemPrices}"); while (s_queue.Count > 0) { idsToQuery.Clear(); for (int i = 0; i < s_queryStep; i++) { idsToQuery.Add(s_queue.Dequeue()); if (s_queue.Count == 0) { break; } } s_queryCounter++; DownloadResult <SerializableECItemPrices> result = await Util.DownloadXmlAsync <SerializableECItemPrices>(url, postData : GetPostData(idsToQuery), acceptEncoded : true); OnPricesDownloaded(result); } }
private void OnFinishedCallback(DownloadResult code) { if (FinishedCallback != null) { FinishedCallback(code); } }
T Deserialize <T>(DownloadResult res) where T : FlysasLib.RootBaseClass { var o = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(res.Content); o.json = res.Content; o.httpSuccess = res.Success; return(o); }
/// <summary> /// Called when prices downloaded. /// </summary> /// <param name="result">The result.</param> private void OnPricesDownloaded(DownloadResult<SerializableECItemPrices> result) { if (CheckQueryStatus(result)) return; if (EveMonClient.IsDebugBuild) EveMonClient.Trace($"Remaining ids: {String.Join(", ", s_queryMonitorList)}", printMethod: false); Loaded = true; CachedUntil = DateTime.UtcNow.AddDays(1); // Reset query pending flag s_queryPending = false; EveMonClient.Trace("done"); EveMonClient.OnPricesDownloaded(null, String.Empty); // Save the file in cache SaveAsync(Filename, Util.SerializeToXmlDocument(Export())).ConfigureAwait(false); }
/// <exception cref="ObjectDisposedException"></exception> public async Task<DownloadResult<byte[]>> DownloadFileAsync(Uri requestUri) { if (_disposed) throw new ObjectDisposedException(GetType().FullName); var response = await DownloadAsync(requestUri, _fileRequestDelay, acceptMediaType: "*/*"); if (response == null || !response.IsSuccessStatusCode) { var request = _proxy.GenerateRequestMessage(HttpMethod.Get, requestUri, acceptMediaType: "*/*"); return new DownloadResult<byte[]>(request, response); } var memoryStream = new MemoryStream(); await response.Content.CopyToAsync(memoryStream); var downloadResult = new DownloadResult<byte[]>(memoryStream.ToArray()); return downloadResult; }
/// <exception cref="ObjectDisposedException"></exception> public async Task<DownloadResult<string>> DownloadAsStringAsync(Uri requestUri, string acceptMediaType = "*/*") { if (_disposed) throw new ObjectDisposedException(GetType().FullName); var response = await DownloadAsync(requestUri, _requestDelay, acceptMediaType); if (response == null || !response.IsSuccessStatusCode) { var request = _proxy.GenerateRequestMessage(HttpMethod.Get, requestUri, acceptMediaType); return new DownloadResult<string>(request, response); } var responseString = await _proxy.GetResponseContentStringAsync(response); var downloadResult = new DownloadResult<string>(responseString); return downloadResult; }
/// <summary> /// Occurs when we downloaded a loadout from the provider. /// </summary> /// <param name="result">The result.</param> private static void OnLoadoutDownloaded(DownloadResult<String> result) { s_queryPending = false; EveMonClient.OnLoadoutDownloaded(result.Result, result.Error?.Message); }
public static ToastNotification DownloadToast(string filename,DownloadResult result) { ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); switch (result) { case DownloadResult.Success: toastTextElements[0].AppendChild(toastXml.CreateTextNode("下载完成!")); toastTextElements[1].AppendChild(toastXml.CreateTextNode("文件:" + filename + "下载完成")); break; case DownloadResult.Failure: toastTextElements[0].AppendChild(toastXml.CreateTextNode("下载失败!")); toastTextElements[1].AppendChild(toastXml.CreateTextNode("文件:" + filename + "下载失败")); break; default: break; } var doc = new Windows.Data.Xml.Dom.XmlDocument(); ToastNotification toast = new ToastNotification(toastXml); return toast; }
private void OnDownloadFinished(DownloadResult code) { downloader_ = null; Debug.Log("Download completed. result:" + code); }
/// <summary> /// Called when patch file check completed. /// </summary> /// <param name="result">The result.</param> private static void OnCheckCompleted(DownloadResult<SerializablePatch> result) { // If update manager has been disabled since the last // update was triggered quit out here if (!s_enabled) { s_checkScheduled = false; return; } // Was there an error ? if (result.Error != null) { // Logs the error and reschedule EveMonClient.Trace($"UpdateManager - {result.Error.Message}", printMethod: false); ScheduleCheck(TimeSpan.FromMinutes(1)); return; } try { // No error, let's try to deserialize ScanUpdateFeed(result.Result); } catch (InvalidOperationException exc) { // An error occurred during the deserialization ExceptionHandler.LogException(exc, true); } finally { EveMonClient.Trace(); // Reschedule ScheduleCheck(s_frequency); } }
private void updaterWorker_fileDownloaded(DownloadResult r) { toolStripProgressBar1.Value = 0; toolStripProgressBar1.Visible = false; toolStripStatusLabel1.Text = ""; // switch (r) { case DownloadResult.Success: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate); displayStatus("Revision " + '"' + updaterWorker.latestRevision + '"' + "has been downloaded"); beginInstall(); break; case DownloadResult.Canceled: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Paused); displayStatus("Download canceled"); changeNextAction("Download"); break; case DownloadResult.InvalidURL: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error); if (MessageBox.Show("The updater URLs are invalid. Would you like to correct it now?", "Chromium Updater", MessageBoxButtons.YesNo) == DialogResult.Yes) new SettingsForm().Show(); changeNextAction("Check"); break; case DownloadResult.NoInternet: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error); displayStatus("You are not connected to the Internet", 0); changeNextAction("Check"); break; case DownloadResult.FileInUse: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error); MessageBox.Show("The file that we are downloading to is in use."); changeNextAction("Check"); break; } }
private void OnFinishedCallback (DownloadResult code) { if (FinishedCallback != null) FinishedCallback(code); }
/// <summary> /// Called when data downloaded. /// </summary> /// <param name="result">The result.</param> private static void OnPricesDownloaded(DownloadResult<SerializableEMDItemPrices> result) { // Reset query pending flag s_queryPending = false; if (result == null || result.Error != null || result.Result.Result == null || !result.Result.Result.ItemPrices.Any()) { Loaded = true; CachedUntil = DateTime.UtcNow.AddHours(1); if (result?.Result == null) EveMonClient.Trace("no result"); else if (result.Error != null) EveMonClient.Trace(result.Error.Message); else if (result.Result.Result == null || !result.Result.Result.ItemPrices.Any()) EveMonClient.Trace("empty result"); else EveMonClient.Trace("failed"); EveMonClient.OnPricesDownloaded(null, String.Empty); return; } Import(result.Result.Result.ItemPrices); Loaded = true; CachedUntil = DateTime.UtcNow.AddDays(1); // Reset query pending flag s_queryPending = false; EveMonClient.Trace("done"); EveMonClient.OnPricesDownloaded(null, String.Empty); // Save the file in cache SaveAsync(Filename, Util.SerializeToXmlDocument(result.Result)).ConfigureAwait(false); }
/// <summary> /// Processes the queried eve flags. /// </summary> /// <param name="result">The result.</param> private static void OnDownloaded(DownloadResult<SerializableEveFlags> result) { if (result.Error != null) { // Reset query pending flag s_queryPending = false; EveMonClient.Trace(result.Error.Message); // Fallback EnsureInitialized(); return; } // Import the list Import(result.Result); // Reset query pending flag s_queryPending = false; // Notify the subscribers EveMonClient.OnEveFlagsUpdated(); // Save the file in cache LocalXmlCache.SaveAsync(Filename, Util.SerializeToXmlDocument(result.Result)).ConfigureAwait(false); }
/// <summary> /// Checks the query status. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> private bool CheckQueryStatus(DownloadResult<SerializableECItemPrices> result) { s_queryCounter--; if (result == null || result.Error != null) { if (result?.Error != null) { EveMonClient.Trace(result.Error.Message); // Abort further attempts if (result.Error.Status == HttpWebClientServiceExceptionStatus.Timeout || result.Error.Status == HttpWebClientServiceExceptionStatus.ServerError) { s_queue.Clear(); // Set a retry Loaded = true; CachedUntil = DateTime.UtcNow.AddHours(1); // Reset query pending flag s_queryPending = false; EveMonClient.OnPricesDownloaded(null, String.Empty); // We return 'true' to avoid saving a file return true; } // If it's a 'Bad Request' just return // We'll check those items later on a lower query step if (result.Error.Status == HttpWebClientServiceExceptionStatus.Exception && result.Error.Message.Contains("400 (Bad Request)") && s_queue.Count != 0) { return true; } // If we are done set the proper flags if (!s_queryMonitorList.Any() || s_queryStep <= 1) { Loaded = true; EveMonClient.Trace("ECItemPricer.Import - done", printMethod: false); return false; } } } // When the query succeeds import the data and remove the ids from the monitoring list if (result?.Result != null) { foreach (SerializableECItemPriceListItem item in result.Result.ItemPrices) { s_queryMonitorList.Remove(item.ID); } Import(result.Result.ItemPrices); } // If all items where queried we are done if (s_queryCounter == 0 && s_queue.Count == 0 && s_queryStep <= 1) return false; // If there are still items in queue just continue if (s_queryCounter != 0 || !s_queryMonitorList.Any() || s_queue.Count != 0) return true; // if there are ids still to query repeat the query on a lower query step s_queryStep = s_queryStep / 2; s_queue = new Queue<int>(s_queryMonitorList); Task.WhenAll(QueryIDs()); return true; }
private void OnDownloadFinished(DownloadResult code) { downloader_ = null; }
/// <summary> /// Callback used when images are downloaded. /// </summary> /// <param name="result">The result.</param> private static Image GotImage(DownloadResult<Image> result) { if (result.Error == null) return result.Result; if (result.Error.Status == HttpWebClientServiceExceptionStatus.Timeout) EveMonClient.Trace(result.Error.Message); else ExceptionHandler.LogException(result.Error, true); return null; }