void StartDownload() { try { if (Media != null) { switch (Media.MediaType) { case InstaMediaType.Image: { var url = Media.Images?[0].Uri; DownloadHelper.Download(url, url, false); } break; case InstaMediaType.Video: { var url = Media.Videos?[0].Uri; DownloadHelper.Download(url, Media.Images?[0].Uri, true); } break; } } else if (User != null) { DownloadHelper.Download(User.HdProfilePicUrlInfo.Uri, User.ProfilePicture, false, User.UserName); } } catch { } }
/// <summary> /// Download correct version of FFmpeg depending on your OS /// </summary> public static async Task DownloadZip() { var bits = Environment.Is64BitOperatingSystem ? 64 : 32; if (bits == 32) { throw new Exception("No FFmpeg download link for 32 bit systems."); } // Set DownloadUri depending on OS if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { DownloadUri = new Uri($"https://ul.sbond.co/ffmpeg/ffmpeg-latest-win-amd64.zip"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { DownloadUri = new Uri($"https://ul.sbond.co/ffmpeg/ffmpeg-latest-macos-amd64.zip"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { DownloadUri = new Uri($"https://ul.sbond.co/ffmpeg/ffmpeg-release-linux-amd64.zip"); } ZipPath = Path.Combine(Path.GetTempPath(), "ffmpeg.zip"); // Update programStatus on ProgressChanged DownloadHelper.ProgressChanged += (progress => { ProgramStatus.DoingSomething(true, "Fetching Recording Utilities", progress); }); await DownloadHelper.Download(DownloadUri, ZipPath); }
private static void CheckVCRedist(PhpVersion phpVersion) { if (!phpVersion.VisualCRedist.Installed) { Console.Write("Visual C++ Redistributable {0} not installed. Install now? (Y/n): ", phpVersion.VisualCRedist.Name); var input = Console.ReadLine(); if (input == "" || input.Equals("y", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Downloading..."); var downloader = new DownloadHelper(phpVersion.VisualCRedist.DownloadURL, "vc.exe"); downloader.DownloadProgressChanged += (a, b) => { Console.SetCursorPosition(0, 0); Console.Write("{0:0}%\t{1:0} s ", b.DownloadPercentage, b.TimeRemaining.TotalSeconds); }; Console.Clear(); downloader.Download(); Console.Clear(); Console.WriteLine("Download complete!"); Thread.Sleep(500); InstallVCRedist(phpVersion.VisualCRedist); File.Delete("vc.exe"); } } }
private async void download_Click(object sender, RoutedEventArgs e) { int i = 0; StorageFolder folder = await Methods.GetMyFolderAsync(); foreach (PostPic item in list.SelectedItems) { try { string name = "konachan_" + item.Id; DownloadOperation download = await DownloadHelper.Download(item.File_url, name + ".png", folder); //如果await,那么执行完第一个StartAsync()后即退出循环.GetCurrentDownloadsAsync()方法同样会遇到此问题.(Download页) IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> start = download.StartAsync(); i++; } catch (Exception err) { await new ContentDialog { Content = "错误:" + err.Message, IsSecondaryButtonEnabled = false, PrimaryButtonText = "确定" }.ShowAsync(); } } if (i > 0) { list.SelectionMode = ListViewSelectionMode.None; await popup.Show(i.ToString() + "个图片已加入下载队列"); } }
void StartDownload() { try { switch (InboxItem.VisualMedia.Media.MediaType) { case InstaMediaType.Image: { var url = (SettingsHelper.Settings.DownloadQuality == DownloadQuality.HighestQuality ? InboxItem.VisualMedia.Media.Images?[0] : InboxItem.VisualMedia.Media.Images.LastOrDefault()).Uri; DownloadHelper.Download(url, InboxItem.VisualMedia.Media.Images.LastOrDefault().Uri, false); } break; case InstaMediaType.Video: { var url = (SettingsHelper.Settings.DownloadQuality == DownloadQuality.HighestQuality ? InboxItem.VisualMedia.Media.Videos?[0] : InboxItem.VisualMedia.Media.Videos.LastOrDefault()).Uri; DownloadHelper.Download(url, InboxItem.VisualMedia.Media.Images?.LastOrDefault().Uri, true); } break; } } catch { } }
public async Task SendToIdAsync(string videoId) { try { string requestUrl = Path.Combine(url, videoId); var htmlDoc = await web.LoadFromWebAsync(requestUrl); var node = htmlDoc.DocumentNode.SelectSingleNode("//a"); string downloadUrl = node.Attributes["href"].Value; string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string downloadFolderPath = Path.Combine(desktopPath, "Downloaded Musics"); Directory.CreateDirectory(downloadFolderPath); string musicName = await GetMusicNameAsync(videoId) + ".mp3"; string downloadPath = Path.Combine(downloadFolderPath, musicName); DownloadHelper.Download(downloadUrl, downloadPath); } catch (Exception) { } }
void StartDownload() { try { if (Media != null) { switch (Media.MediaType) { case InstaMediaType.Image: { var url = (SettingsHelper.Settings.DownloadQuality == DownloadQuality.HighestQuality ? Media.Images?[0] : Media.Images.LastOrDefault()).Uri; DownloadHelper.Download(url, Media.Images?.LastOrDefault().Uri, false); } break; case InstaMediaType.Video: { var url = (SettingsHelper.Settings.DownloadQuality == DownloadQuality.HighestQuality ? Media.Videos?[0] : Media.Videos.LastOrDefault()).Uri; DownloadHelper.Download(url, Media.Images?.LastOrDefault().Uri, true); } break; } } else if (User != null) { DownloadHelper.Download(User.HdProfilePicUrlInfo.Uri, User.ProfilePicture, false, User.UserName); } } catch { } }
void StartDownload() { try { var url = User.HdProfilePicUrlInfo.Uri; DownloadHelper.Download(url, url, false, User.UserName, null, false, false, true); } catch { } }
public void Download() { DownloadHelper downloadHelper = new DownloadHelper(); String url = "http://b354.photo.store.qq.com/psb?/V13pHVVf2GwiZg/WNGARehOFNIa*ho9Rcypvrxce71LilpaVwQtIT4SdTE!/b/dGIBAAAAAAAA&bo=gAJxBAAAAAAFB9M!&rf=viewer_4"; String savePath = "E:\\study\\QQ控件相册图片批量下载"; String fileType = "jpg"; downloadHelper.Download(url, savePath, fileType); }
private String DownloadWebPI() { String downloadLocation = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.GetExtension(Resources.WebPIDownloadLoc)); using (DownloadHelper downloadWebPI = new DownloadHelper()) { downloadWebPI.Download(new Uri(Resources.WebPIDownloadLoc), downloadLocation); } return(downloadLocation); }
//public delegate double PerformCalculation(double x, double y); //public static double Addition(double a, double b) //{ // Console.WriteLine("a+b is : " + (a+b)); // return a + b; //} //public static double Division(double a, double b) //{ // Console.WriteLine("a/b is : " + (a / b)); // return a / b; //} //public static double Subtraction(double a, double b) //{ // Console.WriteLine("a-b is : " + (a - b)); // return a - b; //} //public delegate string GetTextDelegate(string name); //public delegate double GetResultDelegate(double a, double b); static void Main(string[] args) { // Creating an anonymous method or inline delegate //GetTextDelegate getTextDelegate = delegate (string name) //{ // return "Hello, " + name; //}; //Lambda expression //GetTextDelegate getHelloText = (string name) => { return "Hello, " + name; }; //Statement lambda //GetTextDelegate getGoodbyeText = (string name) => //{ // Console.WriteLine("I'm inside of a statement lambda"); // return "Goodbye, " + name; //}; //GetTextDelegate getWelcomeText = name => "Welcome, " + name; //GetResultDelegate getSum = (a, b) => a + b; //GetResultDelegate getProductDelegate = (a, b) => a * b; //DisplayNum(getSum); //DisplayNum1(getProductDelegate); //Console.WriteLine(getWelcomeText("Sophie")); //Display(getTextDelegate); //PerformCalculation getSum = Addition; ////getSum(5.0, 5.0); //PerformCalculation getQuotient = Division; ////getQuotient(5.0, 5.0); //PerformCalculation multiCalc = getSum + getQuotient; //multiCalc += Subtraction; //multiCalc -= getSum; //multiCalc(3.2, 3.2); var file = new File() { Title = "File 1" }; var downloadHelper = new DownloadHelper(); //publisher var unpackService = new UnpackService(); //reciever var notificationService = new NotificationService(); downloadHelper.FileDownloaded += unpackService.OnFileDownloaded; downloadHelper.FileDownloaded += notificationService.OnFileDownloaded; downloadHelper.Download(file); }
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)); }
/// <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); }
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); }
//[Command("Add", RunMode = RunMode.Async)] //[Summary("add only a song to play list ")] public async Task Add(string parameter) { try { if (parameter != null && _textChannel != null) { using (_textChannel.EnterTypingState()) { //Test for valid URL bool result = Uri.TryCreate(parameter, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == "http" || uriResult.Scheme == "https"); //Answer if (result) { try { Tuple <string, string> info = await DownloadHelper.GetInfo(parameter); await SendMessage($"{Context.User.Mention} requested \"{info.Item1}\" ({info.Item2})! Downloading now..."); //Download string file = await DownloadHelper.Download(parameter); var vidInfo = new Tuple <string, string, string, string>(file, info.Item1, info.Item2, Context.User.Mention); _queue.Enqueue(vidInfo); Pause = false; } catch (Exception ex) { await SendMessage( $"Sorry {Context.User.Mention}, unfortunately I can't play that Song!"); } } else { await _textChannel.SendMessageAsync( $"Sorry {Context.User.Mention}, but that was not a valid URL!"); } } } } catch (Exception ex) { CommonTools.ErrorReporting(ex); } }
private async void OnDownloadButtonClicked(object sender, RoutedEventArgs e) { try { string name = "konachan_" + Pic.Id; StorageFolder folder = await Methods.GetMyFolderAsync(); DownloadOperation download = await DownloadHelper.Download(Pic.File_url, name + Pic.File_url.Substring(Pic.File_url.Length - 4), folder); //如果await,那么执行完第一个StartAsync()后即退出循环.GetCurrentDownloadsAsync()方法同样会遇到此问题.(Download页) IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> start = download.StartAsync(); await popup.Show("图片已加入下载队列"); } catch (Exception err) { await popup.Show("错误:" + err.Message); } }
static void Main(string[] args) { var file = new File() { Title = "File1" }; var downloadHelper = new DownloadHelper(); var unpackService = new UnpackService(); var notifLed = new Notification(); downloadHelper.FileDownloaded += unpackService.OnFileDownloaded; downloadHelper.FileDownloaded += notifLed.onDownloadedNotif; // event+= downloadHelper.Download(file); }
/// <summary> ///选中分p后点确定开始下载视频 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OK_Tapped(object sender, TappedRoutedEventArgs e) { var items = PartList.SelectedItems; int i = 0; foreach (PartInfo item in items) { if (item.SourceType == "已下载") { continue; } await DownloadHelper.Download(info, item.PartNumber); i++; } if (i < 1) { Link.ShowToast("未选择任何项"); return; } Link.ShowToast("尝试下载" + i + "个视频"); Cancel_Tapped(Cancel, new TappedRoutedEventArgs()); }
void StartDownload() { try { switch (InboxItem.VisualMedia.Media.MediaType) { case InstaMediaType.Image: { var url = InboxItem.VisualMedia.Media.Images?[0].Uri; DownloadHelper.Download(url, url, false); } break; case InstaMediaType.Video: { var url = InboxItem.VisualMedia.Media.Videos?[0].Uri; DownloadHelper.Download(url, InboxItem.VisualMedia.Media.Images?[0].Uri, true); } break; } } catch { } }
/// <summary> /// Get fiat price for one coin in specific date /// </summary> /// <param name="parser">Parser</param> /// <param name="coin">Coin</param> /// <param name="date">Date</param> /// <returns>Price</returns> protected override decimal InternalGetFiatPrice(ITradeParser parser, ECoin coin, DateTime date) { if (coin == ECoin.USD) { return(FiatProviderHelper.UsdPerCoin(Coin, date)); } var ret = DownloadHelper.Download <JObject> ( $"http://api.coinlayer.com/{date.ToString("yyyy-MM-dd")}?access_key={ApiKey}&symbols={GetCoin(coin)}&target={GetCoin(Coin)}&expand=1" ); if (!ret.TryGetValue("success", out var sucess) || !sucess.Value <bool>() || !ret.TryGetValue("rates", out var rates)) { throw new ArgumentException(); } var val = ((JProperty)rates.First).Value.ToObject <Entry>(); return(val.Rate); }
private string Download() { if (RetryCount == 0) { RetryCount = 3; //Try 3 times before giving up if not specified. } String tempLocation = String.Empty; int tryCount = 0; while (tryCount < RetryCount) { try { tempLocation = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.GetExtension(Url.ToString())); using (DownloadHelper helper = new DownloadHelper()) { helper.Download(new Uri(Url), tempLocation); } break; } catch (Exception ex) { tryCount++; if (tryCount < RetryCount == false) { throw ex; } else { String errorMessage = String.Format(CultureInfo.InvariantCulture, "Retry count - {0}. Error downloading the file - {1}", tryCount, ex.Message); Console.WriteLine(errorMessage); } } } return(tempLocation); }
public override bool BeforeOnStart() { var onStartSuccessful = true; System.Net.ServicePointManager.DefaultConnectionLimit = 12; #region create plugins if (!this.ActivePlugins.Any(p => p.GetType() == typeof(Plugins.HybrisPlugin))) { this.AddPlugin <Plugins.HybrisPlugin>(null); } else { Trace.TraceAndLogWarning(TRACESOURCE, "Before on Start called with a running HybrisPlugin. Sending stop..."); try { this.ActivePlugins.First(p => p.GetType() == typeof(Plugins.HybrisPlugin)).SendStop(); Trace.TraceAndLogInformation(TRACESOURCE, "Successfully stopped HybrisPlugin in BeforeOnStart."); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "Error stopping HybrisPlugin in BeforeOnStart. Error: " + ex.ToString()); } } try { bool startSolr = false; if (!bool.TryParse(RoleEnvironment.GetConfigurationSettingValue("HybrisOnAzure.StartSolrPlugin"), out startSolr)) { Trace.TraceAndLogError(TRACESOURCE, "ERROR: Could not parse 'HybrisOnAzure.StartSolrPlugin' configuration."); } if (startSolr && !this.ActivePlugins.Any(p => p.GetType() == typeof(Plugins.SolrPlugin))) { this.AddPlugin <Plugins.SolrPlugin>(null); } else if (this.ActivePlugins.Any(p => p.GetType() == typeof(Plugins.SolrPlugin))) { Trace.TraceAndLogWarning(TRACESOURCE, "Before on Start called with a running SolrPlugin. Sending stop..."); try { this.ActivePlugins.First(p => p.GetType() == typeof(Plugins.SolrPlugin)).SendStop(); Trace.TraceAndLogInformation(TRACESOURCE, "Successfully stopped SolrPlugin in BeforeOnStart."); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "Error stopping SolrPlugin in BeforeOnStart. Error: " + ex.ToString()); } if (!startSolr) { Trace.TraceAndLogInformation(TRACESOURCE, "Removing SolrPlugin."); this.RemovePlugin(this.ActivePlugins.First(p => p.GetType() == typeof(Plugins.SolrPlugin))); } } } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "Error creating SolrPlugin in BeforeOnStart. Error: " + ex.ToString()); } #endregion #region CLEANUP try { var rootDirectory = RoleEnvironment.GetConfigurationSettingValue("HybrisOnAzure.BaseDirectory"); Trace.TraceInformation(TRACESOURCE + " OnStart - cleanup old files from '{0}'.", rootDirectory); if (System.IO.Directory.Exists(rootDirectory)) { Trace.TraceInformation(TRACESOURCE + " OnStart - '{0}' exists > delete.", rootDirectory); System.IO.Directory.Delete(rootDirectory, true); if (System.IO.Directory.Exists(rootDirectory)) { Trace.TraceError(TRACESOURCE + " OnStart -'{0}' successfully deleted but still exists!.", rootDirectory); } else { Trace.TraceInformation(TRACESOURCE + " OnStart - '{0}' successfully deleted.", rootDirectory); } } else { Trace.TraceInformation(TRACESOURCE + " OnStart - '{0}' does not exist.", rootDirectory); } } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "OnStart - error at Cleanup old files: " + ex.ToString()); } #endregion #region Download stuff from storage // download files from storage to this computer try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting DownloadHelper."); DownloadHelper.Download(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing DownloadHelper. Message: " + ex.Message); onStartSuccessful = false; } #endregion #region PatchFiles // patch files try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting PatchFiles."); PatchFileHelper.PatchAllFilesFromConfig(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing PatchFileHelper. Message: " + ex.Message, ex); onStartSuccessful = false; } #endregion #region Run Commandlets // execute setup via configurable commandlets. try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting SetupHelper."); new StartupScriptHelper().ExecuteScripts(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing SetupHelper. Message: " + ex.Message, ex); onStartSuccessful = false; } #endregion #region handle role environment changes RoleEnvironment.Changed += RoleEnvironment_Changed; #endregion #region hadle additional changes AdditionalConfigurationManager.Instance.AdditionalConfigurationChanged += AdditionalConfiguration_Changed; try { AdditionalConfigurationManager.Instance.ProcessConfiguration(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "Error processing initial AdditionalConfiguration:" + ex.ToString()); } #endregion return(onStartSuccessful); }
/// <summary> /// Is executed before the "OnStart" method is called. /// Here all configuration takes place. /// </summary> /// <returns></returns> public override bool BeforeOnStart() { var onStartSuccessful = true; System.Net.ServicePointManager.DefaultConnectionLimit = 64; #region create plugins this.AddPlugin <ArrPlugin>(null); #endregion #region Download stuff from storage // download files from storage to this computer try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting DownloadHelper."); DownloadHelper.Download(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing DownloadHelper. Message: " + ex.Message); onStartSuccessful = false; } #endregion #region PatchFiles // patch files try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting PatchFiles."); PatchFileHelper.PatchAllFilesFromConfig(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing PatchFileHelper. Message: " + ex.Message, ex); onStartSuccessful = false; } #endregion #region Run Commandlets // execute setup via configurable commandlets. try { Trace.TraceInformation(TRACESOURCE + ": BeforeOnStart: Starting SetupHelper."); new StartupScriptHelper().ExecuteScripts(); } catch (Exception ex) { Trace.TraceAndLogError(TRACESOURCE, "BeforeOnStart: ERROR while executing SetupHelper. Message: " + ex.Message, ex); onStartSuccessful = false; } #endregion #region Configure ARR Trace.TraceInformation("WebServer - OnStart: Configuring ARR HealthMonitoring."); onStartSuccessful = (!IISHelper.ConfigureHealthMonitoring()) ? false : onStartSuccessful; Trace.TraceInformation("WebServer - OnStart: Configure WebFarm"); onStartSuccessful = (!IISHelper.ConfigureWebFarm()) ? false : onStartSuccessful; #endregion #region handle role environment changes RoleEnvironment.Changed += RoleEnvironment_Changed; #endregion return(onStartSuccessful); }
private async void btn_ok_Click(object sender, RoutedEventArgs e) { int i = 0; foreach (Pages item in ReadyList.SelectedItems) { try { cid = item.Cid; VideoURL url = await ContentServ.GetVedioURL(cid, 2, VideoFormat.mp4); string name = StringDeal.RemoveSpecial(title.Text); string part = StringDeal.RemoveSpecial(item.Part); StorageFolder folder = await KnownFolders.VideosLibrary.CreateFolderAsync("哔哩哔哩", CreationCollisionOption.OpenIfExists); StorageFolder f1 = await folder.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists); var download = await DownloadHelper.Download(url.Url, part + ".mp4", f1); if (SettingHelper.ContainsKey("_downdanmu")) { if ((bool)SettingHelper.GetValue("_downdanmu") == true) { string xml = await BaseService.SentGetAsync("http://comment.bilibili.com/" + cid + ".xml"); StorageFile file = await f1.CreateFileAsync(part + ".xml"); using (Stream file0 = await file.OpenStreamForWriteAsync()) { using (StreamWriter writer = new StreamWriter(file0)) { writer.Write(xml); } } } } else { string xml = await BaseService.SentGetAsync("http://comment.bilibili.com/" + cid + ".xml"); StorageFile file = await f1.CreateFileAsync(name + ".xml"); using (Stream file0 = await file.OpenStreamForWriteAsync()) { using (StreamWriter writer = new StreamWriter(file0)) { writer.Write(xml); } } } //如果await,那么执行完第一个StartAsync()后即退出循环.GetCurrentDownloadsAsync()方法同样会遇到此问题.(Download页) IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> start = download.StartAsync(); i++; messagepop.Show(i.ToString() + "个视频已加入下载队列"); } catch (Exception err) { messagepop.Show(err.Message); } } }
private void BtnDownload_Click(object sender, RoutedEventArgs e) { DataGridTemplateColumn column = this.grdList.Columns[0] as DataGridTemplateColumn; //获取指定的行与列相交位置的单元格 FrameworkElement element = column.GetCellContent(this.grdList.Items[this.grdList.SelectedIndex]); var bar = column.CellTemplate.FindName("progressCtl", element) as ProgressBar; var btnShow = column.CellTemplate.FindName("btnShow", element) as Button; var btnDownload = sender as Button; Border b = btnDownload.Template.FindName("ContentContainer", btnDownload) as Border; Button btnCancel = column.CellTemplate.FindName("btnCancel", element) as Button; string filePath = btnShow.Tag != null?btnShow.Tag.ToString() : string.Empty; if (string.IsNullOrEmpty(filePath)) { var m_Dialog = new System.Windows.Forms.FolderBrowserDialog(); System.Windows.Forms.DialogResult result = m_Dialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.Cancel) { return; } filePath = m_Dialog.SelectedPath.Trim(); } var index = this.grdList.SelectedIndex; var rowData = AppList[index]; (sender as Button).IsEnabled = false; string downFoldar = filePath; btnShow.Tag = filePath; if (!Directory.Exists(downFoldar)) { Directory.CreateDirectory(downFoldar); } Thread td = new Thread(() => { DownloadHelper downLoadHelper = null; try { this.Dispatcher.BeginInvoke(new Action(() => { btnCancel.Visibility = Visibility.Visible; btnDownload.Visibility = Visibility.Hidden; })); string serverFileUrl = rowData.DownUrl; downLoadHelper = new DownloadHelper(serverFileUrl, downFoldar); downLoadHelper.GetTotalSize(); this.Dispatcher.BeginInvoke(new Action(() => { bar.Maximum = downLoadHelper.TotalSize; })); string downLoadStep = ConfigHelper.GetAppSettingValue("DownloadStep"); downLoadHelper.Step = !string.IsNullOrEmpty(downLoadStep) ? Convert.ToInt32(downLoadStep) : 102400; while (!downLoadHelper.IsFinished && !DicIsStop[index]) { downLoadHelper.Download(); this.Dispatcher.BeginInvoke(new Action(() => { bar.Visibility = Visibility.Visible; bar.Value = downLoadHelper.CurrentSize; })); } if (downLoadHelper.IsFinished) { string localFileName = downLoadHelper.FilePath; string localMd5 = CommonHelper.GetMD5HashFromFile(localFileName); if (localMd5 == rowData.MD5) { this.Dispatcher.BeginInvoke(new Action(() => { this.Dispatcher.BeginInvoke(new Action(() => { btnDownload.Visibility = Visibility.Hidden; btnShow.Visibility = Visibility.Visible; btnCancel.Visibility = Visibility.Hidden; })); })); } else { File.Delete(localFileName); this.Dispatcher.BeginInvoke(new Action(() => { MessageBoxEx.Show(this, string.Format(Message.DownFail, rowData.AppName), Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error); btnDownload.Visibility = Visibility.Visible; b.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(PRO_ReceiptsInvMgr.Resources.Common.IcoDownRestart)) }; btnDownload.IsEnabled = true; btnShow.Visibility = Visibility.Hidden; btnCancel.Visibility = Visibility.Hidden; bar.Visibility = Visibility.Hidden; })); } } } catch (Exception ex) { if (!(ex is System.Threading.ThreadAbortException)) { string errMsg = PRO_ReceiptsInvMgr.Resources.Message.NetworkError; this.Dispatcher.BeginInvoke(new Action(() => { MessageBoxEx.Show(this, errMsg, Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error); btnCancel.Visibility = Visibility.Hidden; bar.Visibility = Visibility.Hidden; btnDownload.Visibility = Visibility.Visible; btnDownload.IsEnabled = true; })); Logging.Log4NetHelper.Error(typeof(AppDownload), string.Format(PRO_ReceiptsInvMgr.Resources.Message.DownAppFail, rowData.AppName) + ex.Message + System.Environment.NewLine + ex.StackTrace); } } finally { if (DicMap.Keys.Contains(index)) { DicMap.Remove(index); } if (downLoadHelper != null) { downLoadHelper.Dispose(); } } }); td.IsBackground = true; td.Start(); DicMap.Add(index, td); if (!DicIsStop.ContainsKey(index)) { DicIsStop.Add(index, false); } else { DicIsStop[index] = false; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/SetHost", async context => { var host = context.Request.Query["host"].ToString(); if (string.IsNullOrWhiteSpace(host)) { await context.Response.WriteAsync("SetHost Error! Parameter host is null!"); } host = host.Replace("https://", "").Replace("http://", "").Replace(" ", "").Trim().Trim('/'); context.Response.Cookies.Append("host", host); await context.Response.WriteAsync($"SetHost {host}!"); }); endpoints.MapGet("/AddHost", async context => { var host = context.Request.Query["host"].ToString(); if (string.IsNullOrWhiteSpace(host)) { await context.Response.WriteAsync("AddHost Error! Parameter host is null!"); } var name = context.Request.Query["name"].ToString(); if (string.IsNullOrWhiteSpace(name)) { await context.Response.WriteAsync("AddHost Error! Parameter name is null!"); } host = host.Replace("https://", "").Replace("http://", "").Replace(" ", "").Trim().Trim('/'); name = name.Replace("https://", "").Replace("http://", "").Replace(" ", "").Trim().Trim('/'); context.Response.Cookies.Append("host-" + name, host); await context.Response.WriteAsync($"AddHost {name}: {host}"); }); endpoints.MapGet("/ClearHost", async context => { var cookies = context.Request.Cookies; foreach (var item in cookies) { context.Response.Cookies.Delete(item.Key); } await context.Response.WriteAsync("ClearHost OK!"); }); endpoints.MapGet("{*url}", async context => { if (DownloadHelper.HasCookie(context)) { await DownloadHelper.Download(context); return; } await context.Response.WriteAsync("Error!"); }); endpoints.MapPost("{*url}", async context => { if (DownloadHelper.HasCookie(context)) { await DownloadHelper.Post(context); return; } await context.Response.WriteAsync("Error!"); }); }); }
/// <summary> /// 下载 /// </summary> /// <param name="url"></param> /// <param name="name"></param> /// <param name="type"></param> public void Download(string url, string name, string type) { var path = HttpContext.Current.Server.MapPath(url); DownloadHelper.Download(path, name, type); }
/// <summary> /// 升级服务器下载最新版本软件 /// </summary> /// <param name="LBBM">类别编码, 1:开票软件2:客户端软件</param> /// <param name="filePath">客户端更新包路径</param> /// <returns></returns> public bool DownloadSoftware(int LBBM, ref string filePath) { bool isNewVersion = false; string serverClientVersion; bool isForce = false; try { if (!CheckClientUpdate(LBBM, out serverClientVersion, out isForce)) { string updateDirectory = string.Empty; string RelativeFilePath = string.Empty; if (!string.IsNullOrEmpty(serverClientVersion)) { RelativeFilePath = "UpdatePackage" + @"\" + LbblmType.Client.ToString() + @"\" + serverClientVersion; //存放更新包路径 updateDirectory = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativeFilePath); } if (!Directory.Exists(updateDirectory)) { Directory.CreateDirectory(updateDirectory); } string strRequest = "{\"LBBM\":\"" + LBBM + "\",\"VERSION\":\"" + serverClientVersion + "\"}"; bool result = true; string errorMsg = string.Empty; string ret = WSInterface.GetResponse(strRequest, InterfaceType.DownLoad, ref result, out errorMsg); if (!result) { return(false); } string localFileName = string.Empty; string serverFileUrl = string.Empty; string serverMd5 = string.Empty; if (!string.IsNullOrEmpty(ret)) { dynamic downLoadResponse = new JsonSerializer().Deserialize <dynamic>(new JsonTextReader(new StringReader(ret))); serverFileUrl = downLoadResponse.FILEURL.ToString(); serverMd5 = downLoadResponse.MD5; localFileName = updateDirectory + "\\" + System.IO.Path.GetFileName(serverFileUrl); RelativeFilePath += "\\" + System.IO.Path.GetFileName(serverFileUrl); } bool isFinish = false; DownloadHelper downLoadHelper = new DownloadHelper(serverFileUrl, updateDirectory); downLoadHelper.GetTotalSize(); if (!File.Exists(localFileName) || (File.Exists(localFileName) && new FileInfo(localFileName).Length < downLoadHelper.TotalSize)) { Logging.Log4NetHelper.Info(typeof(MainWindowService), string.Format(((LbblmType)LBBM).GetDescription() + Message.DownStart, serverClientVersion)); string downLoadStep = ConfigHelper.GetAppSettingValue("DownloadStep"); downLoadHelper.Step = !string.IsNullOrEmpty(downLoadStep) ? Convert.ToInt32(downLoadStep) : 102400; while (!downLoadHelper.IsFinished) { downLoadHelper.Download(); } isFinish = downLoadHelper.IsFinished; if (isFinish) { Logging.Log4NetHelper.Info(typeof(MainWindowService), string.Format(((LbblmType)LBBM).GetDescription() + Message.UpdateSoftSuccessed, serverClientVersion, downLoadHelper.FilePath)); } } else { if (File.Exists(localFileName) && new FileInfo(localFileName).Length == downLoadHelper.TotalSize) { isFinish = true; } downLoadHelper.OperateFile.Close(); downLoadHelper.OperateFile.Dispose(); } if (isFinish) { string localMd5 = CommonHelper.GetMD5HashFromFile(localFileName); if (localMd5 == serverMd5) { var entity = SoftwareVersionService.GetFirstEntity(x => x.LBBM == LBBM && x.Version == serverClientVersion); if (entity != null) { entity.Version = serverClientVersion; entity.OPERATEDATE = DateTime.Now; entity.DowloadPath = RelativeFilePath; entity.IsDownComplete = true; entity.IsForceUpdate = isForce; SoftwareVersionService.UpdateEntities(entity); } else { entity = new SoftwareVersion(); entity.LBBM = LBBM; entity.Name = ((LbblmType)LBBM).ToString(); entity.Version = serverClientVersion; entity.OPERATEDATE = DateTime.Now; entity.DowloadPath = RelativeFilePath; entity.IsDownComplete = true; entity.IsForceUpdate = isForce; SoftwareVersionService.AddEntities(entity); } filePath = localFileName; isNewVersion = true; } else { Logging.Log4NetHelper.Info(typeof(MainWindowService), PRO_ReceiptsInvMgr.Resources.Message.DownloadMd5Fail); File.Delete(localFileName); isNewVersion = false; } } } } catch (Exception ex) { Logging.Log4NetHelper.Error(typeof(MainWindowService), (LBBM == LbblmType.Client.GetHashCode() ? Message.ClientUpdateError : Message.FwkpUpdateFailed) + ex.Message + System.Environment.NewLine + ex.StackTrace); isNewVersion = false; } return(isNewVersion); }
public void DownloadManual() { ManualResponse manualResponse; string strRequest = new JavaScriptSerializer().Serialize(new { SCVERSION = "" }); bool result = false; string errorMsg = string.Empty; var fileName = AppDomain.CurrentDomain.BaseDirectory + @"\Init.ini"; var myIni = new MyIniFile(fileName); var manualVersion = myIni.IniReadValue("InitializeInfo", "ManualVersion"); if (string.IsNullOrEmpty(manualVersion)) { manualVersion = "1.0.1"; myIni.IniWriteValue("InitializeInfo", "ManualVersion", manualVersion); } var response = WSInterface.GetResponse(strRequest, InterfaceType.ManualDownload, ref result, out errorMsg); if (result) { try { manualResponse = new JsonSerializer().Deserialize <ManualResponse>(new JsonTextReader(new StringReader(response))); if (manualResponse == null) { return; } if (!string.IsNullOrEmpty(manualResponse.SCWJURL)) { if (GetClientVersionToDouble(manualVersion) >= GetClientVersionToDouble(manualResponse.SCVERSION)) { return; } bool isFinish = false; DownloadHelper downLoadHelper = new DownloadHelper(manualResponse.SCWJURL, AppDomain.CurrentDomain.BaseDirectory); downLoadHelper.GetTotalSize(); string localFileName = AppDomain.CurrentDomain.BaseDirectory + downLoadHelper.FileName; if (!File.Exists(localFileName) || (File.Exists(localFileName) && new FileInfo(localFileName).Length < downLoadHelper.TotalSize)) { string downLoadStep = ConfigHelper.GetAppSettingValue("DownloadStep"); downLoadHelper.Step = !string.IsNullOrEmpty(downLoadStep) ? Convert.ToInt32(downLoadStep) : 102400; while (!downLoadHelper.IsFinished) { downLoadHelper.Download(); } isFinish = downLoadHelper.IsFinished; if (isFinish) { Logging.Log4NetHelper.Info(typeof(MainWindowService), string.Format(Resources.Message.ManualDownloadSuccess, manualResponse.SCVERSION)); } } else { downLoadHelper.OperateFile.Close(); downLoadHelper.OperateFile.Dispose(); } string localMd5 = CommonHelper.GetMD5HashFromFile(localFileName); if (localMd5 != manualResponse.MD5) { File.Delete(localFileName); } else { string oldChmPath = AppDomain.CurrentDomain.BaseDirectory + PRO_ReceiptsInvMgr.Resources.Common.ManualFilename; string newChmPath = AppDomain.CurrentDomain.BaseDirectory + downLoadHelper.FileName; if (File.Exists(newChmPath)) { if (File.Exists(oldChmPath)) { File.Delete(oldChmPath); } FileInfo fileInfo = new FileInfo(newChmPath); fileInfo.MoveTo(oldChmPath); } myIni.IniWriteValue("InitializeInfo", "ManualVersion", manualResponse.SCVERSION); } } } catch (Exception ex) { Logging.Log4NetHelper.Error(typeof(MainWindowService), string.Format(Message.ManualDownloadFail, ex.Message + System.Environment.NewLine + ex.StackTrace)); } } }
private async void LVMenuItemClick(object sender, ItemClickEventArgs e) { try { if (e.ClickedItem != null && e.ClickedItem is StoryMenu menu && menu != null) { switch (menu.Command) { case StoryMenuCommand.Delete: { var type = InstagramApiSharp.Enums.InstaSharingType.Photo; if (StoryItem.MediaType == InstaMediaType.Video) { type = InstagramApiSharp.Enums.InstaSharingType.Video; } var delete = await Helper.InstaApi.StoryProcessor .DeleteStoryAsync(StoryItem.Id, type); if (delete.Succeeded) { try { //View.FeedList[View.FeedListIndex].Items.Clear(); //FeedList[FeedListIndex].Items.AddRange(storiesAfter.FirstOrDefault().Items); var yek = View.FeedList[View.FeedListIndex].Items.SingleOrDefault(ss => ss.Id.ToLower() == StoryItem.Id.ToLower()); if (yek != null) { View.SkipNext(); View.FeedList[View.FeedListIndex].Items.Remove(yek); } if (Views.Main.MainView.Current?.MainVM?.Stories?.Count > 0) { try { foreach (var item in Views.Main.MainView.Current.MainVM.Stories.ToList()) { //var single = storiesAfter.SingleOrDefault(ss => ss.User.Pk.ToString() == item.User.Pk.ToString()); if (item.User.Pk == Helper.CurrentUser.Pk) { var single = item.Items.SingleOrDefault(ss => ss.Id.ToLower() == StoryItem.Id.ToLower()); item.Items.Remove(single); if (item.Items.Count == 0) { Views.Main.MainView.Current.MainVM.Stories.Remove(item); } break; } } } catch { } } } catch { } } Hide(); } break; case StoryMenuCommand.Download: try { var item = StoryItem; if (item.MediaType == InstaMediaType.Image) { var url = item.Images.FirstOrDefault().Uri; DownloadHelper.Download(url, item.Images.LastOrDefault().Uri, false, item.User.UserName, null, true, true); } else { var url = item.Videos.FirstOrDefault().Uri; DownloadHelper.Download(url, item.Images.LastOrDefault().Uri, true, item.User.UserName, null, true, true); } } catch { } break; case StoryMenuCommand.Report: var report = await Helper.InstaApi.MediaProcessor.ReportMediaAsync(StoryItem.Id); Hide(); if (report.Succeeded) { Helper.ShowNotify("Reported"); } break; case StoryMenuCommand.Settings: var abc = await new Windows.UI.Popups.MessageDialog("NOT available at the moment...").ShowAsync(); break; case StoryMenuCommand.ShareLink: try { var url = ExtensionHelper.GetUrl(ReelFeed.User.UserName.ToLower(), StoryItem.Pk); url.CopyText(); Helper.ShowNotify("Url copied ;-)"); } catch { } Hide(); break; case StoryMenuCommand.Cancel: Hide(); break; } } } catch { Hide(); } }