public DownloadTaskList(DownloadHelper downloadHelper) { InitializeComponent(); m_DownloadHelper = downloadHelper; m_DownloadTaskItemMap = new Dictionary<ListViewItem, Guid>(); m_DownloadHelper.Start(); }
public FileContentResult DownloadFeedback(bool nonSpamOnly = false) { var feedback = dataRepository.GetAll <Feedback>(); if (nonSpamOnly) { feedback = feedback.Where(f => f.FeedbackStatus == FeedbackStatus.NotSpam); } return(DownloadHelper.CreateCsvDownload(feedback, "Feedback.csv")); }
private static void Main(string[] args) { for (int i = 0; i < 100; i++) { var downloadUrl = $@"https://example.com/mag-{i}.pdf"; var savePath = $@"D:\DownloadFile\FileName{i}.pdf"; DownloadHelper downloadHelper = new DownloadHelper(downloadUrl, savePath); downloadHelper.StartDownload(); } Console.ReadLine(); }
private async Task <Tuple <TaskResultStatus, bool> > DownloadFiles(IEnumerable <DownloadFile> downloadList) { var retryFileList = new List <DownloadFile>(); var retryCount = 0; var needRetry = false; if (TotalRetry != 0) { DownloadFileCompletedEvent += (sender, args) => { if (args.Success) { return; } retryFileList.Add(args.File); needRetry = true; } } ; return(await Task.Run(async() => { if (retryCount == 0) { await DownloadHelper.AdvancedDownloadListFile(downloadList, DownloadThread, null) .ConfigureAwait(false); } if (!needRetry) { return new Tuple <TaskResultStatus, bool>(TaskResultStatus.Success, false); } while (retryFileList.Any() && retryCount <= TotalRetry) { foreach (var rF in retryFileList) { rF.RetryCount++; } var tempList = retryFileList; await DownloadHelper.AdvancedDownloadListFile(tempList, DownloadThread, null).ConfigureAwait(false); retryCount++; } var flag = retryFileList.Any(rF => rF.FileType.Equals("Library", StringComparison.Ordinal)); var resultType = retryFileList.Any() ? TaskResultStatus.PartialSuccess : TaskResultStatus.Success; return new Tuple <TaskResultStatus, bool>(resultType, flag); }).ConfigureAwait(false)); }
private void MessageList_OpenFile(object sender, EventArgs e) { FileListItem fileItem = (FileListItem)sender; if (fileItem.File.Data == null) { EventHandler <FileDownloadedEventArgs> eventDelegate = null; eventDelegate = (s, args) => { if (fileItem.File.Downloaded) { if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool"); } if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name)) { DownloadHelper.DownloadFile(fileItem.File, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool"); while (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name)) { } } Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name); _parent.DownloadClient.FileDownloaded -= eventDelegate; } }; _parent.DownloadClient.FileDownloaded += eventDelegate; _parent.DownloadClient.DownloadQueue.Add(fileItem.File); } else { if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool"); } if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name)) { DownloadHelper.DownloadFile(fileItem.File, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool"); while (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name)) { } } Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/CRMTool/" + fileItem.File.Name); } }
public async Task CalculateFairValue() { // var tenYearsBondYield = await DownloadHelper.GetQuote(new string[] { "^TNX" }, QuoteProperty.LastTradePriceOnly, QuoteProperty.ChangeInPercent); // var currentPrice = DownloadHelper.GetQuote(new string[] { ticker }, QuoteProperty.LastTradePriceOnly, QuoteProperty.ChangeInPercent); double inflation = await DownloadHelper.GetCpiData(); //todo: get from yahoo quote double fixincomeReturnRate = 0.0796; //todo: get from yahoo quote var setting = new YahooCompanyStatisticsSetting("CSCO"); var dl = new YahooCompanyStatisticsDownloader(setting); //var bag = new ConcurrentBag<CompanyStatisticsData>(); var results = await dl.BatchDownloadObjectsTaskAsync(setting.GetUrls(tickers)).ConfigureAwait(false); //Parallel.ForEach(tickers, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, // id => // { // var resp = dl.BatchDownloadObjectsTaskAsync(id); // if (resp.Result.Connection.State == ConnectionState.Success) // { // var item = resp.Result.Result.Item; // bag.Add(item); // } // }); results.OrderBy(result => { return(result.Item.TradingInfo.TwoHundredDayMovingAverage); }); //TODO: Add property FairValue and Market Price in CompanyStatisticsData foreach (var result in results) { var ti = result.Item.TradingInfo; var vm = result.Item.ValuationMeasures; var highlight = result.Item.FinancialHighlights; var eps = result.Item.FinancialHighlights.DilutedEPS; // var growthRate1 = vm.TrailingPE / vm.ForwardPE; var growthRate = highlight.QuarterlyRevenueGrowthPercent;//.QuaterlyEarningsGrowthPercent /100.0; //var outStandingShare = vm.MarketCapitalisationInMillion / highlight.RevenuePerShare. var fairValue = FairValueEngine.DiscountedCurrentValue(eps, 3, growthRate / 100.0, inflation / 10000.0, fixincomeReturnRate); if (eps <= 0 && fairValue <= 0) { fairValue = FairValueEngine.FutureValue(highlight.RevenuePerShare, growthRate / 100.0, 1) * 1.5; } Debug.WriteLine("{0} FairValue : {1} forward P/E : {2} EV/Rev : {3} Margin: {4} ShortPercentage : {5} EPS: {6} GrowthRate: {7}", result.Item.ID.PadRight(5), fairValue.ToString("C").PadLeft(9), vm.ForwardPE.ToString().PadLeft(8), vm.EnterpriseValueToRevenue.ToString().PadLeft(8), (highlight.ProfitMarginPercent / 100.0).ToString("P").PadLeft(9), (ti.ShortPercentOfFloat / 100.0).ToString("P").PadLeft(8), eps.ToString("C").PadLeft(8), (growthRate / 100.0).ToString("P").PadLeft(8)); } }
void searchWorker_DoWork(object sender, DoWorkEventArgs e) { try { DownloadSearchCriteria crit = e.Argument as DownloadSearchCriteria; List <TorrentLinkVM> links = DownloadHelper.SearchTorrents(crit); e.Result = links; } catch (Exception ex) { } }
private void Button1_Click(object sender, EventArgs e) { string url = txt_url.Text; download = new DownloadHelper(); HelperDownload h = this.UpdateProgress; //DownloadComplete d = this.DisplayMessage; IntenetSlow slow = this.PrintMessage; string[] urls = { "https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1280_10MG.mp4", "https://file-examples.com/wp-content/uploads/2017/10/file_example_ODP_1MB.odp", "https://file-examples.com/wp-content/uploads/2017/02/zip_10MB.zip", "https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4" }; try { List <Task> threads = new List <Task>(); Task t; try { //foreach (string url1 in urls) //{ // download = new DownloadHelper(); // t = download.DownloadHelperDownloadAsync(url1, slow); //} t = download.DownloadHelperDownloadAsync(url, slow); } catch (UserDefinedException ex) { slow(ex.Message); } download.FileWatcher(h, slow); //downloader.DownloadHelperDownloadAsync(url, h, d, slow); //Task.WaitAll(threads.ToArray()); } catch (ArgumentNullException ex) { slow(ex.ToString()); } catch (WebException ex) { slow(ex.ToString()); } catch (Exception ex) { slow(ex.ToString()); } }
static public int get_downloadRootUrl(IntPtr l) { try { DownloadHelper self = (DownloadHelper)checkSelf(l); pushValue(l, true); pushValue(l, self.downloadRootUrl); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int UseBackupDownloadUrls(IntPtr l) { try { DownloadHelper self = (DownloadHelper)checkSelf(l); self.UseBackupDownloadUrls(); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
public FileContentResult DownloadAllSicCodes() { List <SicCode> allSicCodes = dataRepository.GetAll <SicCode>().ToList(); var records = allSicCodes.Select(GetSicCodeDetails) .ToList(); string fileDownloadName = $"Gpg-SicCodes-{VirtualDateTime.Now:yyyy-MM-dd HH:mm}.csv"; FileContentResult fileContentResult = DownloadHelper.CreateCsvDownload(records, fileDownloadName); return(fileContentResult); }
protected override decimal InternalGetFiatPrice(ITradeParser parser, ECoin coin, DateTime date) { if (coin == ECoin.USD) { return(FiatProviderHelper.UsdPerCoin(Coin, date)); } if (_coinCache.Count == 0) { // Fill cache var coins = DownloadHelper.Download <CoinInfo[]>("https://api.coinpaprika.com/v1/coins", false); foreach (var c in coins.Where(u => u.Rank > 0).OrderBy(u => u.Rank)) { if (!_coinCache.ContainsKey(c.Symbol)) { _coinCache[c.Symbol] = c.Id; } } var exchages = DownloadHelper.Download <ExchageInfo[]>("https://api.coinpaprika.com/v1/exchanges", false); foreach (var exchage in exchages.OrderBy(u => u.Active)) { if (!_exchangeCache.ContainsKey(exchage.Name)) { _exchangeCache[exchage.Name] = exchage.Id; } } } var preparedDate = date.AddSeconds(-date.Second); preparedDate = preparedDate.AddMinutes(-5); var ticks = DownloadHelper.Download <TickInfo[]>( $"https://api.coinpaprika.com/v1/tickers/{GetCoinId(coin)}/historical?start={PrepareDate(preparedDate)}&limit=10"e=usd&interval=5m"); var usdPrice = 0M; foreach (var tick in ticks.OrderBy(u => u.Date)) { if (tick.Date > date) { break; } usdPrice = tick.Price; } return(UsdToPrice(usdPrice, date)); }
public IActionResult AccountEdite(AccountModel acc) { Downloader.IDownloader downloader = DownloadHelper.GetDownloader(acc.Hoster); if (downloader.IsFree) { acc.IsPremium = true; } _context.Accounts.Update(acc); _context.SaveChanges(); return(RedirectToAction("Accounts")); }
void SetImageViewFromRakuten(RakutenAPI rakutenAPI) { rakutenAPI.Query.hits = 5; rakutenAPI.CallBackString += (string json) => { try { var parse = DynamicJson.Parse(json); // 検索結果商品数 int count = (int)parse.count; int cnt = 0; for (int i = 0; i < count; i++) { var item = parse.Items[i].Item; string isbn = (string)item.isbn; string jan = (string)item.jan; string title = (string)item.title; string largeImageUrl = (string)item.largeImageUrl; string itemCaption = (string)item.itemCaption; // 先頭から3文字を取得 // ex) "001004008006/001017005004" → "001" → "Book" int genreId = int.Parse(((string)item.booksGenreId).Substring(0, 3)); string genreName = RakutenAPI.GetGenreName(genreId); var downloadHelper = new DownloadHelper(); downloadHelper.CallBackBytes += (byte[] bytes) => { string imgFilePath = MyData.GetImgFilePath(genreName, isbn, jan); string datFilePath = MyData.GetDatFilePath(genreName, isbn, jan); var obj = new { isbn = isbn, jan = jan, title = title, itemCaption = itemCaption, genreName = genreName }; SDCardHelper.save(datFilePath, DynamicJson.Serialize(obj)); SDCardHelper.save(imgFilePath, bytes); Bitmap bitmap = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); UIHelper.showImageToast(title, bitmap, itemCaption); }; downloadHelper.BytesFromUrl(largeImageUrl); } } catch (Exception ee) { UIHelper.DelayedToast("データの解析失敗…", 10); } }; rakutenAPI.start(); UIHelper.DelayedToast("情報取得開始", 10); }
public void ExportToExcel(HttpContext context) { ReturnsApplyQuery returnsApplyQuery = new ReturnsApplyQuery(); returnsApplyQuery.ReturnIds = context.Request["Ids"].ToNullString(); returnsApplyQuery.SupplierId = 0; returnsApplyQuery.OrderId = Globals.UrlDecode(context.Request["OrderId"]); returnsApplyQuery.HandleStatus = base.GetIntParam(context, "HandleStatus", true); returnsApplyQuery.SortBy = "ApplyForTime"; returnsApplyQuery.SortOrder = SortAction.Desc; IList <ReturnInfo> returnApplysNoPage = OrderHelper.GetReturnApplysNoPage(returnsApplyQuery); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("<table border='1'>"); stringBuilder.Append("<thead><tr>"); stringBuilder.Append("<th>编号</th>"); stringBuilder.Append("<th>会员名</th>"); stringBuilder.Append("<th>订单编号</th>"); stringBuilder.Append("<th>申请时间</th>"); stringBuilder.Append("<th>匹配门店</th>"); stringBuilder.Append("<th>处理状态</th>"); stringBuilder.Append("<th>退款/退货原因</th>"); stringBuilder.Append("<th>退款商品</th>"); stringBuilder.Append("<th>退款金额</th>"); stringBuilder.Append("<th>处理时间</th>"); stringBuilder.Append("<th>退款途径</th>"); stringBuilder.Append("</tr></thead>"); StringBuilder stringBuilder2 = new StringBuilder(); foreach (ReturnInfo item in returnApplysNoPage) { stringBuilder2.Append("<tr>"); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.ReturnId, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.UserName, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.OrderId, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.ApplyForTime, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD((item.StoreId.HasValue && item.StoreId.Value > 0) ? DepotHelper.GetStoreNameByStoreId(item.StoreId.Value) : "平台店", true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(EnumDescription.GetEnumDescription((Enum)(object)item.HandleStatus, 0), true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.ReturnReason, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.ShopName + "(" + item.Quantity + ")", true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.RefundAmount, false)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(this.GetHandleTime(item), false)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(EnumDescription.GetEnumDescription((Enum)(object)item.RefundType, 0), true)); stringBuilder2.Append("</tr>"); } stringBuilder.AppendFormat("<tbody>{0}</tbody></table>", stringBuilder2.ToString()); StringWriter stringWriter = new StringWriter(); stringWriter.Write(stringBuilder); DownloadHelper.DownloadFile(context.Response, stringWriter.GetStringBuilder(), "ReturnApplys" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"); stringWriter.Close(); context.Response.End(); }
public IActionResult DownloadReturnDetailsCsv(long id) { Organisation organisation = dataRepository.Get <Organisation>(id); var returns = organisation.Returns.OrderByDescending(r => r.AccountingDate).ThenByDescending(r => r.StatusDate); var records = returns.Select( ret => new { OrganisationId = ret.Organisation.OrganisationId, OrganisationName = ret.Organisation.OrganisationName, ReturnId = ret.ReturnId, SnapshotDate = ret.AccountingDate, DeadlineDate = ReportingYearsHelper.GetDeadlineForAccountingDate(ret.AccountingDate), ModifiedDate = ret.Modified, Status = ret.Status, Modifications = ret.Modifications, Late = ret.IsLateSubmission, LateReason = ret.LateReason, Employees = ret.OrganisationSize.GetAttribute <DisplayAttribute>().Name, HourlyPayGapMean = ret.DiffMeanHourlyPayPercent, HourlyPayGapMedian = ret.DiffMedianHourlyPercent, BonusPayPercentMale = ret.MaleMedianBonusPayPercent, BonusPayPercentFemale = ret.FemaleMedianBonusPayPercent, BonusPayGapMean = ret.DiffMeanBonusPercent, BonusPayGapMedian = ret.DiffMedianBonusPercent, UpperQuarterPercentMale = ret.MaleUpperQuartilePayBand, UpperQuarterPercentFemale = ret.FemaleUpperQuartilePayBand, UpperMiddleQuarterPercentMale = ret.MaleUpperPayBand, UpperMiddleQuarterPercentFemale = ret.FemaleUpperPayBand, LowerMiddleQuarterPercentMale = ret.MaleMiddlePayBand, LowerMiddleQuarterPercentFemale = ret.FemaleMiddlePayBand, LowerQuarterPercentMale = ret.MaleLowerPayBand, LowerQuarterPercentFemale = ret.FemaleLowerPayBand, LinkToCompanyWebsite = ret.CompanyLinkToGPGInfo, SeniorResponsibleOfficer = ret.ResponsiblePerson }); string sanitisedOrganisationName = SanitiseOrganisationNameForFilename(organisation.OrganisationName); string fileDownloadName = $"ReturnsForOrganisation-{sanitisedOrganisationName}--{VirtualDateTime.Now:yyyy-MM-dd HH:mm}.csv"; FileContentResult fileContentResult = DownloadHelper.CreateCsvDownload(records, fileDownloadName); return(fileContentResult); }
public void ExportToExcel(HttpContext context) { MemberQuery dataQuery = this.GetDataQuery(context); IList <Hidistro.Entities.Members.ReferralInfo> referralExportData = MemberHelper.GetReferralExportData(dataQuery); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("<table border='1'>"); stringBuilder.Append("<thead><tr>"); stringBuilder.Append("<th>分销员</th>"); stringBuilder.Append("<th>真实姓名</th>"); stringBuilder.Append("<th>电话号码</th>"); stringBuilder.Append("<th>邮箱</th>"); stringBuilder.Append("<th>店铺名称</th>"); stringBuilder.Append("<th>分销员等级</th>"); stringBuilder.Append("<th>直接下级数</th>"); stringBuilder.Append("<th>直接下级成交额</th>"); stringBuilder.Append("<th>累计获得佣金</th>"); stringBuilder.Append("<th>成为分销员时间</th>"); stringBuilder.Append("</tr></thead>"); StringBuilder stringBuilder2 = new StringBuilder(); DateTime dateTime; foreach (Hidistro.Entities.Members.ReferralInfo item in referralExportData) { ReferralExtInfo referralExtInfo = MemberProcessor.GetReferralExtInfo(item.RequetReason); stringBuilder2.Append("<tr>"); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.UserName, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(string.IsNullOrEmpty(referralExtInfo.RealName) ? item.RealName : referralExtInfo.RealName, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(string.IsNullOrEmpty(referralExtInfo.CellPhone) ? item.CellPhone : referralExtInfo.CellPhone, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(string.IsNullOrEmpty(referralExtInfo.Email) ? item.Email : referralExtInfo.Email, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.ShopName, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.GradeName, true)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.SubNumber, false)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.LowerSaleTotal.F2ToString("f2"), false)); stringBuilder2.Append(ExcelHelper.GetXLSFieldsTD(item.UserAllSplittin.F2ToString("f2"), false)); StringBuilder stringBuilder3 = stringBuilder2; dateTime = item.AuditDate.Value; stringBuilder3.Append(ExcelHelper.GetXLSFieldsTD(dateTime.ToString("yyyy-MM-dd HH:mm:ss"), false)); stringBuilder2.Append("</tr>"); } stringBuilder.AppendFormat("<tbody>{0}</tbody></table>", stringBuilder2.ToString()); StringWriter stringWriter = new StringWriter(); stringWriter.Write(stringBuilder); HttpResponse response = context.Response; StringBuilder stringBuilder4 = stringWriter.GetStringBuilder(); dateTime = DateTime.Now; DownloadHelper.DownloadFile(response, stringBuilder4, "ReferralList_" + dateTime.ToString("yyyyMMddhhmmss") + ".xls"); stringWriter.Close(); context.Response.End(); }
public async Task LoadOrUpdate() { Task updateTask = null; lock (_lock) { if (_updateTask == null) { updateTask = _updateTask = Task.Run(async () => { try { try { //this resource contains species stats that we need await DownloadHelper.DownloadFile( @"https://raw.githubusercontent.com/cadon/ARKStatsExtractor/master/ARKBreedingStats/json/values.json", _speciesstatsFileName, true, TimeSpan.FromDays(1) ); } catch { /*ignore exceptions */ } //even if download failed try with local file if it exists if (File.Exists(_speciesstatsFileName)) { using (var reader = new StreamReader(_speciesstatsFileName)) { var json = await reader.ReadToEndAsync(); var data = JsonConvert.DeserializeObject<ArkSpeciesStatsData>(json); if (data != null) Data = data; } } } catch (Exception ex) { Logging.LogException($"Error when attempting to read {_speciesstatsFileName}", ex, typeof(ArkSpeciesStats), LogLevel.ERROR, ExceptionLevel.Ignored); } finally { lock(_lock) { _updateTask = null; } } }); } else updateTask = _updateTask; } await updateTask; }
public async Task Execute() { byte[] imagebytes = await DownloadHelper.DownloadFileAsync(this.DownloadTask.AbsoluteUrl, Manager.CookieContainer); if (imagebytes != null) { this.AddDownload(imagebytes); } else { this.Manager.AddRetry(this.DownloadTask); } }
/// <summary> /// 执行下载 /// </summary> public async void StartDownloadHandler() { _progressBar.Progress = 0; Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>(); progressReporter.ProgressChanged += (s, args) => _progressBar.Progress = (int)(100 * args.PercentComplete); string tarPath = Android.OS.Environment.ExternalStorageDirectory + "/JYandroidpda.apk"; Task <int> downloadTask = DownloadHelper.CreateDownloadTask(tarPath, url_down, progressReporter); int bytesDownloaded = await downloadTask; System.Diagnostics.Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded); }
async void StartDownloadHandler(object sender, EventArgs e) { ProgressBar.Progress = 0f; Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>(); progressReporter.ProgressChanged += (s, args) => ProgressBar.Progress = args.PercentComplete; Task <int> downloadTask = DownloadHelper.CreateDownloadTask(DownloadHelper.ImageToDownload, progressReporter); int bytesDownloaded = await downloadTask; Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded); }
private void Download_Click(object sender, RoutedEventArgs e) { _savePath = System.IO.Path.Combine(@"C:\Temporary\Other", DownloadHelper.GetFileNameFromUrl(Url)); this._downloader = new Downloader(Url, _savePath, 4, 1024 * 1024 * 10); this._downloader.Completed += Downloader_Completed; this._downloader.ProgressChanged += Downloader_ProgressChanged; this._downloader.Paused += Downloader_Paused; this._downloader.Cancelled += Downloader_Cancelled; this._downloader.Failed += Downloader_Failed; this._downloader.Start(); this._startTime = DateTime.Now; }
static public int constructor(IntPtr l) { try { DownloadHelper o; o = new DownloadHelper(); pushValue(l, true); pushValue(l, o); return(2); } catch (Exception e) { return(error(l, e)); } }
private static bool LoadLinks() { if (!File.Exists(linksFile)) { DownloadHelper.DownloadFile("PokemonGo.RocketAPI.Console/Resources", Program.path, linksFileName); } if (File.Exists(linksFile)) { links = JsonConvert.DeserializeObject <Components.HRefLink[]>(File.ReadAllText(linksFile)); return(true); } return(false); }
/// <summary> /// 析构函数 /// </summary> void OnDestroy() { //if (NetManager != null) { // NetManager.Unload(); //} //if (LuaManager != null) //{ // LuaManager.Destroy(); //} base.OnDestroy(); DownloadHelper.CloseAll(); Debug.Log("~GameManager was destroyed"); }
public async void DownloadInstaller() { const string Url = @"http://www.mapwindow.org/dokuwiki-2011-05-25a.tgz"; var filename = Path.GetTempFileName(); Debug.WriteLine(filename); await DownloadHelper.DownloadBinaryAsync(Url, filename); var fileInfo = new FileInfo(filename); Debug.WriteLine("File size: " + fileInfo.Length); Assert.IsTrue(fileInfo.Length > 0); Debug.WriteLine("Saved as " + filename); }
static void Main(string[] args) { var file = new File() { Title = "File 1" }; var downloadHelper = new DownloadHelper(); // Publisher var unpackService = new UnpackService(); // Receiver var notificationOfDownload = new NotificationOfDownload(); // Receiver downloadHelper.FileDownloaded += unpackService.OnFileDownloaded; downloadHelper.FileDownloaded += notificationOfDownload.OnFileDownloaded; downloadHelper.Download(file); }
private async void btn_Ok_Click(object sender, RoutedEventArgs e) { if (gv_Play.SelectedItems.Count == 0) { return; } var info = gv_Play.SelectedItem as episodesModel; int i = 1; foreach (episodesModel item in gv_Play.SelectedItems) { if (item.IsDowned == Visibility.Collapsed) { var vitem = new PlayerModel() { Aid = _banId, Mid = item.danmaku.ToString(), Mode = PlayMode.Video, No = item.index, VideoTitle = item.index_title, Title = (this.DataContext as BangumiInfoModel).title }; DownloadModel m = new DownloadModel(); m.folderinfo = new FolderListModel() { id = _banId, desc = txt_desc.Text, title = txt_Name.Text, isbangumi = true, thumb = (this.DataContext as BangumiInfoModel).cover }; m.videoinfo = new VideoListModel() { id = _banId, mid = vitem.Mid, part = Convert.ToInt32(vitem.No), partTitle = vitem.No + " " + vitem.VideoTitle, videoUrl = await ApiHelper.GetVideoUrl(vitem, cb_Qu.SelectedIndex + 1), title = txt_Name.Text }; DownloadHelper.StartDownload(m); } i++; } messShow.Show("任务已加入下载", 3000); gv_Play.SelectionMode = ListViewSelectionMode.None; gv_Play.IsItemClickEnabled = true; Down_ComBar.Visibility = Visibility.Collapsed; com_bar.Visibility = Visibility.Visible; }
/// <summary> /// 开始下载 /// </summary> private async void Btn_ok_Click(object sender, RoutedEventArgs e) { int i = 0; flyout_download.Hide(); foreach (Pages item in ReadyList.SelectedItems) { try { cid = item.Cid; VideoURL url = await ContentServ.GetVedioURL(cid, quality, format); string name = StringDeal.RemoveSpecial(title.Text); string part = StringDeal.RemoveSpecial(item.Part); StorageFolder folder = await DownloadHelper.GetMyFolderAsync(); StorageFolder f1 = await folder.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists); List <DownloadOperation> list = new List <DownloadOperation>(); for (int j = 0; j < url.Ps.Count; j++) { list.Add(await DownloadHelper.Download(url.Ps[j].Url, $"{part}_{j}.{format.ToString()}", f1)); } // 如果await,那么执行完第一个StartAsync()后即退出循环.GetCurrentDownloadsAsync()方法同样会遇到此问题.(Download页) IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> start; for (int k = 0; k < list.Count; k++) { start = list[k].StartAsync(); } i++; await DownloadHelper.AddVideoInfo(part, cid, details.Sid); await popup.Show(i.ToString() + "个视频已加入下载队列"); if (SettingHelper.ContainsKey("_downdanmu")) { if ((bool)SettingHelper.GetValue("_downdanmu") == false) { continue; } } await DownloadHelper.DownloadDanmakuAsync(cid, part, f1); } catch (Exception err) { await popup.Show(err.Message); } } SwitchCommandBar(false); }
public async Task Execute() { var download = await DownloadHelper.DownloadUrlAsync(this.DownloadTask.AbsoluteUrl, Manager.CookieContainer); if (download != null) { AddDownload(download); } else { this.Manager.AddRetry(this.DownloadTask); } // this.Manager.SiteDb.Routes.EnsureExists(this.DownloadTask.RelativeUrl, ConstObjectType.Style); }
IEnumerator OnDownloadlevelIndexFile() { LogModule.DebugLog("ger version form " + m_resServerUrl + "/" + ResLevelIndexFileName); WWW wwwResLevelFile = null; yield return(StartCoroutine(DownloadHelper.GetCDNWWW(m_resServerUrl + "/" + ResLevelIndexFileName, value => wwwResLevelFile = value))); if (!string.IsNullOrEmpty(wwwResLevelFile.error)) { LogModule.ErrorLog(wwwResLevelFile.error); UpdateFinish(UpdateResult.GetVersionFail); yield break; } m_remoteResLevelIndex = wwwResLevelFile.text; // check level string[] strLevels = m_remoteResLevelIndex.Split(','); if (strLevels.Length > 0) { int curLevel = 0; LogModule.DebugLog("level index string:" + m_remoteResLevelIndex); for (int i = 0; i < strLevels.Length; i++) { if (int.TryParse(strLevels[i], out curLevel)) { LogModule.DebugLog("level index:" + curLevel.ToString()); if (m_localResLevel < curLevel && m_playerNeedResLevel >= curLevel) { // need update LogModule.DebugLog("remote verion level is big than local, begin update"); m_curUpdateStep = UpdateStep.GetFileList; // 下载文件列表 m_versionFileDownloader = DownloadHelper.StartDownload(this, m_resServerUrl + "/" + ResFileListName, true, CacheVersionPath + "/" + ResFileListName, OnDownloadRemoteResFileList); yield break; } } else { LogModule.ErrorLog("parse level index file error " + strLevels[i]); } } } UpdateFinish(UpdateResult.Success); }
public void Test() { string imagesPath = Path.Combine(Environment.CurrentDirectory, "images"); if (!Directory.Exists(imagesPath)) { Directory.CreateDirectory(imagesPath); } DownloadHelper downloadHelper = new DownloadHelper(new InMemoryDownloadSettings(200, 5, 1024, 5, 5), new LocalFileDownloadStreamManager(new TempFileAllocator(new DefaultFileNameCorrector()))); downloadHelper.AddNewDownloadTask( new Uri("http://dc455.4shared.com/img/OctFRjPl/s3/13470492140/marika-fruscio-01.jpg"), Path.Combine(imagesPath, "marika-fruscio-01.jpg")); downloadHelper.OnDownloadFinished( x => { x.DownloadTask.State.ToString(); }); downloadHelper.Start(); downloadHelper.Shutdown(true); }
void SetImageViewFromRakuten(RakutenAPI rakutenAPI) { rakutenAPI.Query.hits = 5; rakutenAPI.CallBackString += (string json) => { try { var parse = DynamicJson.Parse(json); // �������ʏ��i�� int count = (int)parse.count; int cnt = 0; for (int i = 0; i < count; i++) { var item = parse.Items[i].Item; string isbn = (string)item.isbn; string jan = (string)item.jan; string title = (string)item.title; string largeImageUrl = (string)item.largeImageUrl; string itemCaption = (string)item.itemCaption; // �擪����3������擾 // ex) "001004008006/001017005004" �� "001" �� "Book" int genreId = int.Parse(((string)item.booksGenreId).Substring(0, 3)); string genreName = RakutenAPI.GetGenreName(genreId); var downloadHelper = new DownloadHelper(); downloadHelper.CallBackBytes += (byte[] bytes) => { string imgFilePath = MyData.GetImgFilePath(genreName, isbn, jan); string datFilePath = MyData.GetDatFilePath(genreName, isbn, jan); var obj = new { isbn = isbn, jan = jan, title = title, itemCaption = itemCaption, genreName = genreName }; SDCardHelper.save(datFilePath, DynamicJson.Serialize(obj)); SDCardHelper.save(imgFilePath, bytes); Bitmap bitmap = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); UIHelper.showImageToast(title, bitmap, itemCaption); }; downloadHelper.BytesFromUrl(largeImageUrl); } } catch (Exception ee) { UIHelper.DelayedToast("�f�[�^�̉�͎��s�c", 10); } }; rakutenAPI.start(); UIHelper.DelayedToast("���擾�J�n", 10); }