protected void OnButton1Clicked(object sender, EventArgs e) { if (!String.IsNullOrEmpty (entry1.Text)) { // Our test youtube link string link = entry1.Text; IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls (link); if (vid == true) { VideoInfo video = videoInfos .First (info => info.VideoType == VideoType.Mp4 && info.Resolution == 720); WebClient wc = new WebClient (); wc.DownloadProgressChanged += wc_DownloadProgressChanged; wc.DownloadFileAsync (new Uri (video.DownloadUrl), Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + @"/" + video.Title + video.VideoExtension); label1.Text = dlspeed; } else { VideoInfo video = videoInfos .Where(info => info.CanExtractAudio) .OrderByDescending(info => info.AudioBitrate) .First(); entry1.Text = video.DownloadUrl; /*WebClient wc = new WebClient (); wc.DownloadProgressChanged += wc_DownloadProgressChanged; wc.DownloadFileAsync (new Uri (video.DownloadUrl), Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + @"/" + video.Title + video.AudioExtension); */} } }
static void Main() { while (true) { try { Console.Write("Enter URL Path to download image : "); string path = Console.ReadLine(); Console.Write("Enter Filename : "); string filename = Console.ReadLine(); WebClient wc = new WebClient(); string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); fullpath = desktop + filename; wc.DownloadFileAsync(new Uri(path), filename); wc.DownloadFileCompleted += wc_DownloadFileCompleted; wc.DownloadProgressChanged += wc_DownloadProgressChanged; string answer = Console.ReadLine(); if (answer == "y") { Process.Start(fullpath); } Console.WriteLine("Bye"); break; } catch (Exception ex) { Console.WriteLine("There was something not allwright with {0}", ex); } } }
void Start() { string[] arguments = Environment.GetCommandLineArgs(); ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; downloadLink = new Uri (arguments[2].ToString ().Substring (1, arguments[2].Length-1)); applicationLocation += arguments[1].ToString().Substring (1, arguments[1].Length -1) + "/UnityMusicPlayer"; Directory.Delete(applicationLocation + ".app", true); guitext.text = "Downloading Update"; using (WebClient client = new WebClient()) try { client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted); client.DownloadProgressChanged += (start, end) => { progresstText.text = end.ProgressPercentage.ToString() + "%" ; }; client.DownloadFileAsync (downloadLink, applicationLocation + ".zip", 0); } catch (Exception error) { guitext.text = error.ToString (); } }
public static void DownloadFile_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, "", null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync(new Uri("http://localhost"), null); }); }
static void Main(string[] args) { int timeout = 0; if ((args.Length % 2) != 1 || args.Length == 1 || !int.TryParse(args[0], out timeout)) { Console.WriteLine("Usage: download.exe <timeout_in_seconds> [<url> <output_file>]+"); Environment.Exit(1); } int n = 1; int completed = 0; ManualResetEvent waitHandle = new ManualResetEvent(false); try { while (n < args.Length) { WebClient client = new WebClient(); int k = n; client.DownloadFileCompleted += new AsyncCompletedEventHandler(delegate (object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { OnError(args[k], args[k + 1], e.Error); } Console.WriteLine("Finished download from " + args[k] + " to " + args[k + 1]); if (++completed == ((args.Length - 1) / 2)) { waitHandle.Set(); } }); Console.WriteLine("Starting download from " + args[n] + " to " + args[n + 1]); client.DownloadFileAsync(new Uri(args[n]), args[n + 1]); n += 2; } } catch (Exception e) { OnError(args[n], args[n + 1], e); } if (!waitHandle.WaitOne(new TimeSpan(0, 0, timeout))) { Console.WriteLine("Download timed out."); Environment.Exit(1); } }
void Download() { using (WebClient client = new WebClient()) try { client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted); client.DownloadProgressChanged += (start, end) => { currentDownloadPercentage = end.ProgressPercentage.ToString() + "%"; }; client.DownloadFileAsync (url, path + Path.DirectorySeparatorChar + file.name + "." + file.format); } catch (Exception error) { UnityEngine.Debug.Log (error); } }
internal static void StartDelayedCache(string url) { if (EnsureEnoughSpace()) { Task.Delay(DelayAmount).ContinueWith(t => { if (!IsCaching(url)) { using (WebClient client = new WebClient()) { client.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFileComplete); string filename = Path.GetFileName(url); client.DownloadFileAsync(new Uri(url), Path.Combine(TempFolder, filename), filename); } } }); } }
private void button_download_Click(object sender, EventArgs e) { button_download.Enabled = false; if (!_install) { if (File.Exists(@"update.zip")) { File.Delete(@"update.zip"); } WebClient client = new WebClient(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(UpdateProgressBar); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(_update.Link), @"update.zip"); } else { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = @"updater.exe"; Process.Start(startInfo); Application.Exit(); } }
public static void Main(string[] args) { var urls = Console.In.ReadToEnd().Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); var dir = args[0]; var taskList = new List<Task<bool>>(urls.Length); foreach (var u in urls) { var wc = new WebClient(); var uri = new Uri(u); var fileName = Path.Combine(dir, Path.GetFileName(u)); TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); wc.DownloadFileCompleted += (sender, e) => { if (e.Error != null) { Console.WriteLine("failed: {0}, {1}", uri, e.Error.Message); tcs.TrySetResult(false); } else { Console.WriteLine("downloaded: {0} => {1}", uri, fileName); tcs.TrySetResult(true); } }; wc.DownloadFileAsync(uri, fileName); taskList.Add(tcs.Task); } Task.WaitAll(taskList.ToArray()); }
private void DownloadNext(ThemeConfig theme) { this.Invoke(new Action(() => UpdatePercentage(0))); stopwatch.Start(); wc.DownloadFileAsync(themeUris[themeUriIndex], imagesZipDest, theme); }
public void download_file_async(string url, string path, WebClient webClient, MainWindow tmp) { if (global_iter != 0) { global_iter = 0; webClient_global.DownloadFileAsync(new Uri(url_global), path_global); } else { var marge = new Thickness(form1.uc.gridDownloadScreen.Width * 0.02, 0, 0, 0); label_glob.Content = "...\\" + name_global; label_glob.HorizontalContentAlignment = 0; //progressBar_glob.Width = tmp.gridDownloadScreen.Width * 0.95; progressBar_glob.Height = 10; progressBar_glob.HorizontalAlignment = 0; progressBar_glob.Margin = marge; url_global = url; webClient_global = webClient; webClient_global.DownloadProgressChanged += new DownloadProgressChangedEventHandler(web_client_download_progress); webClient_global.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(web_client_download_completed); webClient_global.DownloadFileAsync(new Uri(url), path, cts); pgBar_grid_glob.RowDefinitions.Add(new RowDefinition()); var column1 = new ColumnDefinition(); column1.Width = new GridLength(90, GridUnitType.Star); pgBar_grid_glob.ColumnDefinitions.Add(column1); var column2 = new ColumnDefinition(); column2.Width = new GridLength(10, GridUnitType.Star); pgBar_grid_glob.ColumnDefinitions.Add(column2); progressBar_glob.Width = ((column1.Width.Value * 0.01) * (form1.uc.gridDownloadScreen.ActualWidth)) * 0.95; progressBar_glob.Height = 5; progressBar_glob.SetValue(Grid.RowProperty, 0); progressBar_glob.SetValue(Grid.ColumnProperty, 0); pgBar_grid_glob.Children.Add(progressBar_glob); //pgBar_pause_glob.Content = "⏸"; pgBar_pause_glob.Style = (Style)form1.uc.FindResource("MaterialDesignFloatingActionMiniButton"); pgBar_pause_glob.ToolTip = "Stop Download"; PackIcon pauseIcon = new PackIcon(); pauseIcon.Kind = PackIconKind.Pause; pauseIcon.Width = 18; pauseIcon.Height = 18; pgBar_pause_glob.Content = pauseIcon; pgBar_pause_glob.Width = 25; pgBar_pause_glob.Height = 25; pgBar_pause_glob.Padding = new Thickness(0, 0, 0, 0); pgBar_pause_glob.VerticalContentAlignment = VerticalAlignment.Center; pgBar_pause_glob.HorizontalContentAlignment = HorizontalAlignment.Center; pgBar_pause_glob.Click += cancel; pgBar_pause_glob.SetValue(Grid.RowProperty, 0); pgBar_pause_glob.SetValue(Grid.ColumnProperty, 1); pgBar_grid_glob.Children.Add(pgBar_pause_glob); form1.uc.gridDownloadScreen.RowDefinitions.Add(new RowDefinition()); label_glob.SetValue(Grid.RowProperty, form1.uc.gridDownloadScreen.RowDefinitions.Count - 1); form1.uc.gridDownloadScreen.Children.Add(label_glob); form1.uc.gridDownloadScreen.RowDefinitions.Add(new RowDefinition()); //progressBar_glob.SetValue(Grid.RowProperty, form1.uc.gridDownloadScreen.RowDefinitions.Count - 1); pgBar_grid_glob.SetValue(Grid.RowProperty, form1.uc.gridDownloadScreen.RowDefinitions.Count - 1); form1.uc.gridDownloadScreen.Children.Add(pgBar_grid_glob); } }
public void UpdateDatabase()//读取github release的json,进行正则解析,根据版本号判断是否有更新并进行更新实装 { if (!ToolFunctions.CheckNetworkStatus()) { return; } string jsonUrl = "https://api.github.com/repos/sjn4048/Chalaoshi_CrawlAndAnalysis/releases/latest"; HttpWebRequest request = WebRequest.Create(jsonUrl) as HttpWebRequest; request.UserAgent = "Mozilla/4.0"; request.Method = "GET"; request.AllowReadStreamBuffering = false; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream jsonStream = response.GetResponseStream(); byte[] jsonBuf = new byte[1024]; string jsonString = string.Empty; int count = jsonStream.Read(jsonBuf, 0, jsonBuf.Length); while (count > 0) //通过循环收集json内容 { jsonString += Encoding.Default.GetString(jsonBuf, 0, count); count = jsonStream.Read(jsonBuf, 0, jsonBuf.Length); } //分析是否有更新 string databaseRegexString = @"""name"":"".*([0-9]{8})"""; //正则表达式 Regex versionRegex = new Regex(databaseRegexString); Match match = Regex.Match(jsonString, databaseRegexString); int LatestDatabaseVersion; if (!match.Success) //匹配失败 { return; } else { LatestDatabaseVersion = int.Parse(match.Groups[1].Value); } if (Config.DatabaseVersion == LatestDatabaseVersion) //无更新时 { return; } //有更新时 if (MessageBox.Show(caption: "数据库有更新", text: "检测到服务器上有数据库更新,是否立即更新?", buttons: MessageBoxButtons.OKCancel, icon: MessageBoxIcon.Information) == DialogResult.Cancel) { return; //选择不更新 } //选择更新 string downloadRegexString = @"""browser_download_url"":""(.*?)"""; //正则表达式 Regex downloadRegex = new Regex(downloadRegexString); match = Regex.Match(jsonString, downloadRegexString); if (!match.Success) //匹配失败 { return; } //下载文件 string url = match.Groups[1].Value; string path = "downloading_tmp.csv"; WebClient webClient = new WebClient(); try { webClient.DownloadFileAsync(new Uri(url), path); } catch { MessageBox.Show(caption: "下载失败", text: "由于服务器架设在Github.com上,国内网络访问较不稳定,导致下载失败。请尝试稍后再试或科学上网解决。", icon: MessageBoxIcon.Error, buttons: MessageBoxButtons.OK); } MessageBox.Show(caption: "开始下载", text: "已开始更新,结束后将提示。", icon: MessageBoxIcon.Information, buttons: MessageBoxButtons.OK); webClient.DownloadFileCompleted += (s, arg) => { Config.DatabaseVersion = LatestDatabaseVersion; Config.SetConfig(Config.MaxResultPerPage, Config.HideUnrated, Config.Order); new GetData().GetTeacherDataFromCsv(new FileStream("downloading_tmp.csv", FileMode.Open, FileAccess.Read)); MessageBox.Show(caption: "更新完成", text: "恭喜您,数据库已更新成功", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.None); }; //别忘了重新加载数据库、更新数据库版本 }
private void LoadConnection(object sender, DoWorkEventArgs e) { if (_clientChangelogDownloader.IsBusy) { return; } bool blnChummerVersionGotten = true; string strError = LanguageManager.GetString("String_Error", GlobalOptions.Language).Trim(); _strExceptionString = string.Empty; LatestVersion = strError; string strUpdateLocation = _blnPreferNightly ? "https://api.github.com/repos/chummer5a/chummer5a/releases" : "https://api.github.com/repos/chummer5a/chummer5a/releases/latest"; HttpWebRequest request = null; try { WebRequest objTemp = WebRequest.Create(strUpdateLocation); request = objTemp as HttpWebRequest; } catch (System.Security.SecurityException) { blnChummerVersionGotten = false; } if (request == null) { blnChummerVersionGotten = false; } if (blnChummerVersionGotten) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; request.Accept = "application/json"; request.Timeout = 5000; // Get the response. HttpWebResponse response = null; try { response = request.GetResponse() as HttpWebResponse; } catch (WebException ex) { blnChummerVersionGotten = false; string strException = ex.ToString(); int intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (intNewLineLocation == -1) { intNewLineLocation = strException.IndexOf('\n'); } if (intNewLineLocation != -1) { strException = strException.Substring(0, intNewLineLocation); } _strExceptionString = strException; } if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; response?.Close(); return; } // Get the stream containing content returned by the server. Stream dataStream = response?.GetResponseStream(); if (dataStream == null) { blnChummerVersionGotten = false; } if (blnChummerVersionGotten) { if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; dataStream.Close(); response.Close(); return; } // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream, Encoding.UTF8, true); // Read the content. if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; reader.Close(); response.Close(); return; } string responseFromServer = reader.ReadToEnd(); if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; reader.Close(); response.Close(); return; } string[] stringSeparators = { "," }; if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; reader.Close(); response.Close(); return; } string[] result = responseFromServer.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); bool blnFoundTag = false; bool blnFoundArchive = false; foreach (string line in result) { if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; reader.Close(); response.Close(); return; } if (!blnFoundTag && line.Contains("tag_name")) { _strLatestVersion = line.Split(':')[1]; LatestVersion = _strLatestVersion.Split('}')[0].FastEscape('\"').Trim(); blnFoundTag = true; if (blnFoundArchive) { break; } } if (!blnFoundArchive && line.Contains("browser_download_url")) { _strDownloadFile = line.Split(':')[2]; _strDownloadFile = _strDownloadFile.Substring(2); _strDownloadFile = _strDownloadFile.Split('}')[0].FastEscape('\"'); _strDownloadFile = "https://" + _strDownloadFile; blnFoundArchive = true; if (blnFoundTag) { break; } } } if (!blnFoundArchive || !blnFoundTag) { blnChummerVersionGotten = false; } // Cleanup the streams and the response. reader.Close(); } dataStream?.Close(); response?.Close(); } if (!blnChummerVersionGotten || LatestVersion == strError) { MessageBox.Show( string.IsNullOrEmpty(_strExceptionString) ? LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language) : string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), _strExceptionString), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } else { if (File.Exists(_strTempUpdatePath)) { if (File.Exists(_strTempUpdatePath + ".old")) { File.Delete(_strTempUpdatePath + ".old"); } File.Move(_strTempUpdatePath, _strTempUpdatePath + ".old"); } string strURL = "https://raw.githubusercontent.com/chummer5a/chummer5a/" + LatestVersion + "/Chummer/changelog.txt"; try { Uri uriConnectionAddress = new Uri(strURL); if (File.Exists(_strTempUpdatePath + ".tmp")) { File.Delete(_strTempUpdatePath + ".tmp"); } _clientChangelogDownloader.DownloadFileAsync(uriConnectionAddress, _strTempUpdatePath + ".tmp"); while (_clientChangelogDownloader.IsBusy) { if (_workerConnectionLoader.CancellationPending) { _clientChangelogDownloader.CancelAsync(); e.Cancel = true; return; } } File.Move(_strTempUpdatePath + ".tmp", _strTempUpdatePath); } catch (WebException ex) { string strException = ex.ToString(); int intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (intNewLineLocation == -1) { intNewLineLocation = strException.IndexOf('\n'); } if (intNewLineLocation != -1) { strException = strException.Substring(0, intNewLineLocation); } _strExceptionString = strException; MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } catch (UriFormatException ex) { string strException = ex.ToString(); int intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (intNewLineLocation == -1) { intNewLineLocation = strException.IndexOf('\n'); } if (intNewLineLocation != -1) { strException = strException.Substring(0, intNewLineLocation); } _strExceptionString = strException; MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } } }
public static void DownloadToolGithub(string localToolFolderName, string tool, List <Release> releases, string executable, Action <string> currentTaskUpdateCallback = null, Action <bool> setPercentVisibilityCallback = null, Action <int> setPercentTaskDone = null, Action <string> resultingExecutableStringCallback = null, Action <Exception, string, string> errorExtractingCallback = null) { Release latestRelease = null; ReleaseAsset asset = null; Uri downloadLink = null; currentTaskUpdateCallback?.Invoke(M3L.GetString(M3L.string_interp_downloadingX, tool)); setPercentVisibilityCallback?.Invoke(true); setPercentTaskDone?.Invoke(0); foreach (var release in releases) { //Get asset info asset = release.Assets.FirstOrDefault(); if (Path.GetFileName(executable) == @"MassEffectModder.exe") { //Requires specific asset asset = release.Assets.FirstOrDefault(x => x.Name == @"MassEffectModder-v" + release.TagName + @".7z"); if (asset == null) { Log.Warning( $@"No applicable assets in release tag {release.TagName} for MassEffectModder, skipping"); continue; } latestRelease = release; downloadLink = new Uri(asset.BrowserDownloadUrl); break; } if (Path.GetFileName(executable) == @"MassEffectModderNoGui.exe") { //Requires specific asset asset = release.Assets.FirstOrDefault(x => x.Name == @"MassEffectModderNoGui-v" + release.TagName + @".7z"); if (asset == null) { Log.Warning( $@"No applicable assets in release tag {release.TagName} for MassEffectModderNoGui, skipping"); continue; } latestRelease = release; downloadLink = new Uri(asset.BrowserDownloadUrl); break; } if (asset != null) { latestRelease = release; Log.Information($@"Using release {latestRelease.Name}"); downloadLink = new Uri(asset.BrowserDownloadUrl); break; } } if (latestRelease == null || downloadLink == null) { return; } Analytics.TrackEvent(@"Downloading new external tool", new Dictionary <string, string>() { { @"Tool name", Path.GetFileName(executable) }, { @"Version", latestRelease.TagName } }); currentTaskUpdateCallback?.Invoke($@"{M3L.GetString(M3L.string_interp_downloadingX, tool)} {latestRelease.TagName}"); WebClient downloadClient = new WebClient(); downloadClient.Headers[@"Accept"] = @"application/vnd.github.v3+json"; downloadClient.Headers[@"user-agent"] = @"ME3TweaksModManager"; string temppath = Utilities.GetTempPath(); downloadClient.DownloadProgressChanged += (s, e) => { setPercentTaskDone?.Invoke(e.ProgressPercentage); }; var extension = Path.GetExtension(asset.BrowserDownloadUrl); string downloadPath = Path.Combine(temppath, tool.Replace(@" ", "") + extension); downloadClient.DownloadFileCompleted += (a, b) => { extractTool(tool, executable, extension, downloadPath, currentTaskUpdateCallback, setPercentVisibilityCallback, setPercentTaskDone, resultingExecutableStringCallback, errorExtractingCallback); }; Log.Information(@"Downloading file: " + downloadLink); downloadClient.DownloadFileAsync(downloadLink, downloadPath); }
protected void rptrModule_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "DownLoad") { string url = e.CommandArgument.ToString(); WebClient client = new WebClient(); try { string fileName = Path.GetFileName(url); hdnFileName.Value = fileName; string path = HttpContext.Current.Server.MapPath("~/"); string temPath = SageFrame.Common.RegisterModule.Common.TemporaryFolder; string destPath = Path.Combine(path, temPath); if (!Directory.Exists(destPath)) Directory.CreateDirectory(destPath); client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileAsync(new Uri(url), Server.MapPath(string.Format("~/Install/Temp/{0}", fileName))); } catch (Exception) { client.Dispose(); throw; } } }
private void StartFileDownload(string address) { _cancelDownload = false; _httpDownloadThread?.Abort(); _httpDownloadThread = new Thread((ThreadStart) delegate { try { using (var wc = new WebClient()) { var manifestJson = wc.DownloadString(address + "/manifest.json"); var obj = JsonConvert.DeserializeObject <FileManifest>(manifestJson); wc.DownloadProgressChanged += (sender, args) => { _threadsafeSubtitle = "Downloading " + args.ProgressPercentage; }; foreach (var resource in obj.exportedFiles) { if (!Directory.Exists(FileTransferId._DOWNLOADFOLDER_ + resource.Key)) { Directory.CreateDirectory(FileTransferId._DOWNLOADFOLDER_ + resource.Key); } for (var index = resource.Value.Count - 1; index >= 0; index--) { var file = resource.Value[index]; if (file.type == FileType.Script) { continue; } var target = Path.Combine(FileTransferId._DOWNLOADFOLDER_, resource.Key, file.path); if (File.Exists(target)) { var newHash = DownloadManager.HashFile(target); if (newHash == file.hash) { continue; } } wc.DownloadFileAsync( new Uri($"{address}/{resource.Key}/{file.path}"), target); while (wc.IsBusy) { Thread.Yield(); if (!_cancelDownload) { continue; } wc.CancelAsync(); return; } } } } } catch (Exception ex) { LogManager.LogException(ex, "HTTP FILE DOWNLOAD"); } }); }
/// <summary> /// 从网页版微博中获取微博信息 /// </summary> /// <param name="fansList">保存爬得的粉丝数组</param> public void GetInfoFromHtml(List <Fan> fansList) { Lexer lexer = new Lexer(currentHtmlContent); Parser parser = new Parser(lexer); //获取包含每条微博的div标记列表 NodeList fansNodeList = parser.Parse(fanFilter); for (int i = 0; i < fansNodeList.Size(); i++) { Fan fan = new Fan(); //获取包含一个粉丝的<li>标记 Bullet fanBullet = (Bullet)fansNodeList[i]; #region 获取该粉丝头像 NodeList fanPortraitNodeList = fanBullet.Children.ExtractAllNodesThatMatch(portraitFilter, true); if (fanPortraitNodeList.Size() == 1) { Div fanPortraitDiv = (Div)fanPortraitNodeList[0]; NodeList imgNodeList = fanPortraitDiv.Children.ExtractAllNodesThatMatch(new NodeClassFilter(typeof(ImageTag)), true); if (imgNodeList.Size() == 1) { ImageTag imgNode = (ImageTag)imgNodeList[0]; if (imgNode.Attributes.ContainsKey("SRC") && imgNode.Attributes.ContainsKey("ALT")) { string imgUrl = imgNode.GetAttribute("SRC"); string imgName = imgNode.GetAttribute("ALT"); fan.Name = imgName; WebClient wc = new WebClient();//使用WebClient是因为下载用户头像不用登录cookie wc.DownloadFileAsync(new Uri(imgUrl), @"portrait\" + imgName + ".jpg"); wc.DownloadFileCompleted += wc_DownloadFileCompleted; } else { Console.WriteLine("第" + i + "个粉丝中,<img>标记缺少必要的属性!"); } } else { Console.WriteLine("第" + i + "个粉丝中,获取img标记出错!"); } } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝头像的标准出错!"); } #endregion #region 获取该粉丝的关注数/粉丝数/微博数 NodeList fanConnectNodeList = fanBullet.Children.ExtractAllNodesThatMatch(fanConnectFilter, true); if (fanConnectNodeList.Size() == 1) { NodeList ATagList = fanConnectNodeList[0].Children.ExtractAllNodesThatMatch(new NodeClassFilter(typeof(ATag)), true); if (ATagList.Size() == 3) { for (int j = 0; j < 3; j++) { ATag aTag = (ATag)ATagList[j]; switch (j) { case 0: if (aTag.Attributes.ContainsKey("HREF") && aTag.GetAttribute("HREF").Contains("follow")) { fan.FollowCount = Int32.Parse(aTag.StringText); } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝的关注数出错!"); } break; case 1: if (aTag.Attributes.ContainsKey("HREF") && aTag.GetAttribute("HREF").Contains("fans")) { fan.FansCount = Int32.Parse(aTag.StringText); } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝的粉丝数出错!"); } break; default: fan.FeedsCount = Int32.Parse(aTag.StringText); break; } } } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝关注数/粉丝数/微博数的数量出错!"); } } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝关注数/粉丝数/微博数的标准出错!"); } #endregion #region 获取该粉丝的简介信息 NodeList fanInfoNodeList = fanBullet.Children.ExtractAllNodesThatMatch(fanInfoFilter, true); if (fanInfoNodeList.Size() == 1) { //Console.WriteLine(fanInfoNodeList[0].Parent.ToHtml()); Div fanInfoDiv = (Div)fanInfoNodeList[0]; string intro = fanInfoDiv.StringText; if (intro.Substring(0, 2).Equals("简介")) { fan.Introduction = intro.Substring(3, intro.Length - 3).Replace("\n", " ").Replace("\t", " "); } } else { if (fanInfoNodeList.Size() == 0) { fan.Introduction = ""; } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝简介的标准出错!"); } } #endregion #region 获取该粉丝的UserID、地点和性别信息;校验该粉丝的用户名信息 NodeList fanLocationNodeList = fanBullet.Children.ExtractAllNodesThatMatch(fanNameFilter, true); if (fanLocationNodeList.Size() == 1) { //获取粉丝的UserID信息;校验该粉丝的用户名信息 NodeList aTagNodeList = fanLocationNodeList[0].Children.ExtractAllNodesThatMatch(new NodeClassFilter(typeof(ATag)), true); if (aTagNodeList.Size() >= 1) { ATag nameNode = (ATag)aTagNodeList[0]; if (nameNode.Attributes.ContainsKey("USERCARD") && nameNode.Attributes.ContainsKey("HREF")) { //获取粉丝的UserID信息 string uidStr = nameNode.GetAttribute("USERCARD"); if (uidStr.Substring(0, 3).Equals("id=")) { fan.UserID = uidStr.Substring(3, uidStr.Length - 3); } //获取粉丝的微博链接 string linkUrl = nameNode.GetAttribute("HREF"); fan.LinkURL = "http://www.weibo.com" + linkUrl; } else { Console.WriteLine("第" + i + "个粉丝中,包含用户id和链接的<a>标记中缺少必要的属性!"); } //校验该粉丝的用户名信息 if (!nameNode.StringText.Equals(fan.Name)) { Console.WriteLine("第" + i + "个粉丝中,用户名与用户头像文字描述不一致!"); } } //获取粉丝的性别和地点信息 NodeList locationNodeList = fanLocationNodeList[0].Children.ExtractAllNodesThatMatch(new HasAttributeFilter("class", "addr"), true); if (locationNodeList.Size() == 1) { string locationStr = ""; for (int j = 0; j < locationNodeList[0].Children.Size(); j++) { INode node = locationNodeList[0].Children[j]; if (node.GetType().Equals(typeof(TextNode))) { TextNode tNode = (TextNode)node; locationStr += tNode.ToPlainTextString(); } if (node.GetType().Equals(typeof(TagNode))) { TagNode tNode = (TagNode)node; if (tNode.Attributes.ContainsKey("CLASS")) { if (tNode.GetAttribute("CLASS").Contains("female"))//必须先female,因为female中也含有male,如果male在前,则所有用户均符合该条件了= = { fan.Gender = "female"; } else { if (tNode.GetAttribute("CLASS").Contains("male")) { fan.Gender = "male"; } else { fan.Gender = "unknown"; Console.WriteLine("第" + i + "个粉丝性别不明!"); } } } } } fan.Location = locationStr.Trim(); } else { Console.WriteLine("第" + i + "个粉丝中,获取粉丝地点的标准出错!"); } } else { Console.WriteLine("第" + i + "个粉丝中,获取该粉丝的UserID、地点和性别信息的标准出错!"); } #endregion #region 获取该粉丝关注用户的方式 NodeList followMethodNodeList = fanBullet.Children.ExtractAllNodesThatMatch(followMethodFilter, true); if (followMethodNodeList.Size() == 1) { NodeList methodNodeList = followMethodNodeList[0].Children.ExtractAllNodesThatMatch(new NodeClassFilter(typeof(ATag))); if (methodNodeList.Size() == 1) { ATag methodNode = (ATag)methodNodeList[0]; fan.FollowMethod = methodNode.StringText.Trim(); } else { Console.WriteLine("第" + i + "个粉丝中,获取该粉丝关注用户的方式的数量出错!"); } } else { Console.WriteLine("第" + i + "个粉丝中,获取该粉丝关注用户的方式的标准出错!"); } #endregion fansList.Add(fan); } }
private void BGThread_DoWork(object sender, DoWorkEventArgs e) { // Make sure ifme temp folder is clean if (Directory.Exists(Globals.AppInfo.TempFolder)) { foreach (var item in Directory.GetFiles(Globals.AppInfo.TempFolder)) { File.Delete(item); } } // Move here, let another thread do his job Addons.Installed.Get(); Language.Installed.Get(); // Delete old old stuff if (File.Exists(Path.Combine(Globals.AppInfo.CurrentFolder, "za.dll"))) { File.Delete(Path.Combine(Globals.AppInfo.CurrentFolder, "za.dll")); } // Get IFME version try { InvokeStatus("Checking version", Globals.AppInfo.NameTitle); Globals.AppInfo.VersionNew = client.DownloadString("http://ifme.sourceforge.net/update/version.txt"); string[] GetVersion = Globals.AppInfo.VersionNew.Split('.'); int[] GetVersionInt = new int[4]; for (int x = 0; x < 4; x++) { GetVersionInt[x] = int.Parse(GetVersion[x]); } string[] NowVersion = Globals.AppInfo.Version.Split('.'); int[] NowVersionInt = new int[4]; for (int i = 0; i < 4; i++) { NowVersionInt[i] = int.Parse(NowVersion[i]); } for (int i = 0; i < 4; i++) { if (NowVersionInt[i] == GetVersionInt[i]) { Globals.AppInfo.VersionEqual = true; Globals.AppInfo.VersionMsg = String.Format("{0} is Up-to-date!", Globals.AppInfo.NameShort); continue; } else if (NowVersionInt[i] < GetVersionInt[i]) { Globals.AppInfo.VersionEqual = false; Globals.AppInfo.VersionMsg = String.Format("Version {0}.{1}.{2}.{3} is available! click About button to perform updates!", GetVersion); break; } else { Globals.AppInfo.VersionEqual = false; Globals.AppInfo.VersionMsg = String.Format("This version intend for private testing, public version are {0}.{1}.{2}.{3}", GetVersion); break; } } } catch (WebException ex) { InvokeStatus("Error", ex.Message); System.Threading.Thread.Sleep(wait); return; } // IFME have new version, dont proceed check addons verions if (!Globals.AppInfo.VersionEqual) { return; } // If use disable update, dont proceed if (!Properties.Settings.Default.UpdateAlways) { return; } // Get addons version and update for (int i = 1; i < Addons.Installed.Data.GetLength(0); i++) { // Stop when reach end of addons if (Addons.Installed.Data[i, 0] == null) { break; } // Get version try { InvokeStatus("Loading", Addons.Installed.Data[i, 2]); string GetVersion = client.DownloadString(Addons.Installed.Data[i, 8]); if (GetVersion == Addons.Installed.Data[i, 4] || GetVersion == null) { continue; } } catch { continue; } // Apply update try { InvokeStatus("Downloading updates", Addons.Installed.Data[i, 2]); client.DownloadFileAsync(new Uri(Addons.Installed.Data[i, 9]), Path.Combine(Addons.Folder, "addons.ifz")); finish = false; while (finish == false) { // block and do noting... } InvokeStatus("Updating", Addons.Installed.Data[i, 2]); System.IO.Directory.Delete(Addons.Installed.Data[i, 0], true); Addons.Extract(Path.Combine(Addons.Folder, "addons.ifz"), Addons.Folder); // Tell startup there are got addon update Addons.Installed.IsUpdated = true; } catch (WebException ex) { InvokeStatus("Error", ex.Message); System.Threading.Thread.Sleep(wait); if (ex.Status == WebExceptionStatus.ProtocolError) { if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound) { continue; } } if (ex.Status == WebExceptionStatus.ConnectFailure) { break; } } } // Re-run, get latest addons if (Addons.Installed.IsUpdated) { InvokeStatus("Initialising Addons!", "Please Wait..."); Addons.Installed.Get(); } }
//开始、继续、从新下载 public void CheckDownLoadList() { LoggerHelper.Debug("核对下载列表"); if (tasks.Count == 0) { return; } var finishedCount = 0;//已经完成的数目 foreach (var task in tasks) { LoggerHelper.Debug("核对任务:" + task.FileName); if (task.bFineshed && !task.bDownloadAgain) { LoggerHelper.Debug("已经完成不用从下:" + task.FileName); finishedCount++; } else { //判断下载文件的文件夹是否存在 var dirName = Path.GetDirectoryName(task.FileName); if (dirName != null && !Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); LoggerHelper.Debug("下载目录不存在,创建目录:" + dirName); } //重新下载的,或者新的下载 if (!BreakPoint) { LoggerHelper.Debug("新的下载或从新下载:" + task.FileName); _webClient.DownloadFileAsync(new Uri(task.Url), task.FileName, task.Url); } else { LoggerHelper.Debug("断点下载:" + task.FileName); //Action action = () => DownloadFileBreakPoint(task.Url, task.FileName); //var t = new Thread(action); var download = new ThreadDownloadBreakPoint(this, task); var t = new Thread(download.Download); t.Start(); LoggerHelper.Debug("开始断点下载:" + task.FileName); } break; } } //Action actionFinish = () => //{ //如果全部完成,修改原来等于判断,不然最后一个或者只有一个下载任务时不会执行自己的finish if (finishedCount > tasks.Count - 1) { LoggerHelper.Debug("下载的数据包数量已经达到要求的,删除所有任务和全部任务完成的回调"); tasks.Clear(); tasks = null; if (AllDownloadFinished != null) { AllDownloadFinished(); AllDownloadFinished = null; } } //}; //actionFinish.Invoke(); }
/// <summary> /// Function to control the first launch install. /// </summary> public async void FirstInstall() { VersionCheck.GetLatestGameVersionName(); await VersionCheck.UpdateLatestVersions(); //Get the current root path and prepare the installation var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchUrls = VersionCheck.GamePatchUrls; var patchVersion = VersionCheck.GetLatestGameVersionName(); //Create an empty var containing the progress report from the patcher var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); Task task = new RXPatcher().ApplyPatchFromWeb(patchUrls, targetDir, applicationDir, progress, cancellationTokenSource.Token); //Create the update window int index = await new UpdateServerSelector().SelectHostIndex(patchUrls); var window = new ApplyUpdateWindow(task, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Install, new Uri(patchUrls[index]).Host); //window.Owner = this; //Show the dialog and wait for completion window.ShowDialog(); if (task.IsCompleted == true) { VersionCheck.UpdateGameVersion(); //Create the UE3 redist dialog if (UERedistDialog.DialogResult.Value == true) { //Determine which server has best ping String[] PatchUrls = VersionCheck.GamePatchUrls; RXPatchLib.UpdateServerSelector Selector = new RXPatchLib.UpdateServerSelector(); //Need to solve a import issue regarding duplicate classes Task <int> SelectorTask = Selector.SelectHostIndex(VersionCheck.GamePatchUrls); //NEed to suppress the ui from showing here await SelectorTask; Uri Redistserver = new Uri(PatchUrls[SelectorTask.Result]); //Create new URL based on the patch url (Without the patch part) String RedistUrl = "http://" + Redistserver.Host + "/redists/UE3Redist.exe"; string SystemUrl = GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"; //Create canceltokens to stop the downloaderthread if neccesary CancellationTokenSource downloaderTokenSource = new CancellationTokenSource(); CancellationToken downloaderToken = downloaderTokenSource.Token; //Task for downloading the redist from patch server Task RedistDownloader = new Task(() => { System.IO.Directory.CreateDirectory(GameInstallation.GetRootPath() + "Launcher\\Redist"); System.Net.WebClient RedistRequest = new WebClient(); RedistRequest.DownloadFileAsync(new Uri(RedistUrl), SystemUrl); while (RedistRequest.IsBusy && !downloaderToken.IsCancellationRequested) { if (downloaderToken.IsCancellationRequested) { RedistRequest.CancelAsync(); } //Thread.Sleep(1000); } }, downloaderToken); //Redist downloader statuswindow GeneralDownloadWindow RedistWindow = new GeneralDownloadWindow(downloaderTokenSource, "UE3Redist download"); RedistWindow.Show(); //Task to keep the status of the UE3Redist download Task RedistDownloadStatus = new Task(() => { WebRequest req = System.Net.HttpWebRequest.Create(RedistUrl); req.Method = "HEAD"; int ContentLength; using (WebResponse resp = req.GetResponse()) { int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength); } RedistWindow.initProgressBar(ContentLength); while (RedistDownloader.Status == TaskStatus.Running) { RedistWindow.Status = "Downloading UE3Redist"; FileInfo inf = new FileInfo(SystemUrl); RedistWindow.updateProgressBar(inf.Length); //Thread.Sleep(1000); } }); //Start downloading RedistDownloader.Start(); RedistDownloadStatus.Start(); await RedistDownloader; RedistWindow.Close(); //When done, execute the UE3Redist here try { using (Process UE3Redist = Process.Start(GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe")) { UE3Redist.WaitForExit(); if (UE3Redist.ExitCode != 0)//If redist install fails, notify the user { MessageBox.Show("Error while installing the UE3 Redist."); } else//Everything done! save installed flag and restart { Properties.Settings.Default.Installed = true; Properties.Settings.Default.Save(); try { System.IO.File.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"); System.IO.Directory.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\"); } catch (Exception) { MessageBox.Show("Could not cleanup the redist file. This won't hinder the game."); } } } } catch { MessageBox.Show("Error while executing the UE3 Redist."); } finally { //Restart launcher System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } } else { ModernDialog notInstalledDialog = new ModernDialog(); notInstalledDialog.Title = "UE3 Redistributable"; notInstalledDialog.Content = MessageNotInstalled; notInstalledDialog.Buttons = new Button[] { notInstalledDialog.OkButton }; notInstalledDialog.ShowDialog(); //Shutdown launcher Application.Current.Shutdown(); } } else { Application.Current.Shutdown(); } }
// TODO: Delete this. Use UIDownloadMods internal void DownloadMod(UIMouseEvent evt, UIElement listeningElement) { Main.PlaySound(SoundID.MenuTick); try { if (UIModBrowser.PlatformSupportsTls12) // Needed for downloads from Github { ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; // SecurityProtocolType.Tls12 } using (WebClient client = new WebClient()) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return(true); }); Interface.modBrowser.selectedItem = this; Interface.downloadMod.SetDownloading(displayname); Interface.downloadMod.SetCancel(client.CancelAsync); client.DownloadProgressChanged += (s, e) => { Interface.downloadMod.SetProgress(e); }; client.DownloadFileCompleted += (s, e) => { Main.menuMode = Interface.modBrowserID; if (e.Error != null) { if (e.Cancelled) { } else { // TODO yuck HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error); if (httpStatusCode == HttpStatusCode.ServiceUnavailable) { Interface.errorMessage.Show(Language.GetTextValue("tModLoader.MBExceededBandwidth"), 0); } else { Interface.errorMessage.Show(Language.GetTextValue("tModLoader.MBUnknownMBError"), 0); } } } else if (!e.Cancelled) { // Downloaded OK File.Copy(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod", ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod", true); if (!update) { Interface.modBrowser.aNewModDownloaded = true; } else { Interface.modBrowser.aModUpdated = true; } if (ModLoader.autoReloadAndEnableModsLeavingModBrowser) { ModLoader.EnableMod(mod); } RemoveChild(updateButton); } // Clean up: Delete temp File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod"); }; client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod"); //client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod"); } Main.menuMode = Interface.downloadModID; } catch (WebException e) { UIModBrowser.LogModBrowserException(e); } }
public bool DownloadFile(string sURL, string sPath, string sFile) { bool bTimeout = false; wc = new WebClient(); wc.UseDefaultCredentials = true; this.bDownloadCancelled = false; if (sPath.EndsWith("\\") == false) sPath += "\\"; //sPath = sPath.Replace("?", "") sPath = modFiles.ConvertToRealPath(sPath); sFile = modFiles.ConvertToRealPath(sFile); this.sPath = sPath; this.sFile = sFile; this.sURL = sURL; if (Directory.Exists(sPath) == false) { if (AllowAutoCreateFolder == false) { SetStatusMessage(true, "DEFAULTFOLDER_NOT_AVAILABLE", sPath); return false; } else { try { Directory.CreateDirectory(sPath); if (Directory.Exists(sPath) == false) { SetStatusMessage(true, "DEFAULTFOLDER_NOT_CREATEABLE", sPath); return false; } } catch { SetStatusMessage(true, "DEFAULTFOLDER_NOT_CREATEABLE", sPath); return false; } } } if (File.Exists(sPath + sFile) == true) { if (new FileInfo(sPath + sFile).Length > 0) { if (AllowFileOverwrite == true) { try { File.Delete(sPath + sFile); } catch { SetStatusMessage(true, "FILE_NOT_OVERWRITEABLE", sPath + sFile); return false; } } else { SetStatusMessage(true, "FILE_ALREADY_EXISTS", sPath + sFile); return false; } } } try { wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)"); if (!string.IsNullOrEmpty(Referer)) { wc.Headers.Add("Referer", Referer); } bDownloading = true; tmrInit = false; SetStatusMessage(false, "DOWNLOAD_START", sPath + sFile); tmrDownloadSpeed.Start(); tmrTimeout.Start(); wc.DownloadFileAsync(new Uri(sURL), Path.Combine(sPath, sFile)); while ((this.bDownloading == true)) { if (tmrTimeout.ElapsedMilliseconds >= (iTimeoutSec * 1000)) { this.CancelDownload(); bTimeout = true; break; // TODO: might not be correct. Was : Exit While } } wc.Dispose(); tmrTimeout.Reset(); tmrDownloadSpeed.Reset(); if (bTimeout) { SetStatusMessage(true, "DOWNLOAD_TIMEOUT", Path.Combine(sPath, sFile)); if (DeleteFileOnError) File.Delete(Path.Combine(sPath, sFile)); return false; } if (this.bDownloadCancelled == true) { this.bDownloadCancelled = false; SetStatusMessage(false, "DOWNLOAD_CANCELLED", sPath + sFile); if (DeleteFileOnError) File.Delete(Path.Combine(sPath, sFile)); return false; } if (iDownloadPercent != 100) { SetStatusMessage(true, "DOWNLOAD_ERROR", sPath + sFile); if (DeleteFileOnError) File.Delete(Path.Combine(sPath, sFile)); return false; } SetStatusMessage(false, "DOWNLOAD_COMPLETE", sPath + sFile); return true; } catch (Exception ex) { SetStatusMessage(true, "DOWNLOAD_ERROR", ex.Message); try { if (DeleteFileOnError) File.Delete(Path.Combine(sPath, sFile)); } catch (Exception) { } finally { wc.Dispose(); } return false; } }
private void CheckUpdate() { // version info from xml file Version newVersion = null; // and in this variable we will put the url we // would like to open so that the user can // download the new version // it can be a homepage or a direct // link to zip/exe file string url = ""; XmlTextReader reader = null; try { // provide the XmlTextReader with the URL of // our xml document var StrxmlURL = BadouSquidClient.Properties.Resources.xmlURL; // MessageBox.Show(StrxmlURL); reader = new XmlTextReader(StrxmlURL); // simply (and easily) skip the junk at the beginning reader.MoveToContent(); // internal - as the XmlTextReader moves only // forward, we save current xml element name // in elementName variable. When we parse a // text node, we refer to elementName to check // what was the node name string elementName = ""; // we check if the xml starts with a proper // "ourfancyapp" element node if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "BadouAPP")) { while (reader.Read()) { // when we find an element node, // we remember its name if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { // for text nodes... if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { // we check what the name of the node was switch (elementName) { case "version": // thats why we keep the version info // in xxx.xxx.xxx.xxx format // the Version class does the // parsing for us newVersion = new Version(reader.Value); break; case "url": url = reader.Value; break; } } } } } } catch (Exception) { } finally { if (reader != null) { reader.Close(); } } Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; // compare the versions if (curVersion.CompareTo(newVersion) < 0) { string message = "已经存在一个新的版本" + newVersion + ", 是否更新?"; string caption = "更新提示"; DialogResult result; MessageBoxButtons buttons = MessageBoxButtons.YesNo; // MessageBox.Show("new version is available"); result = MessageBox.Show(message, caption, buttons); if (result == System.Windows.Forms.DialogResult.Yes) { string path = System.Environment.CurrentDirectory; // MessageBox.Show("为你下载新版"); string Downloadfilename = "巴豆Squid" + newVersion + ".exe"; var myStringWebResource = BadouSquidClient.Properties.Resources.myStringWebResource; //System.Net.WebClient unreasonably slow //http://stackoverflow.com/questions/4415443/system-net-webclient-unreasonably-slow WebClient webClient = new WebClient(); webClient.Proxy = null; ServicePointManager.DefaultConnectionLimit = 25; webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); // webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); webClient.DownloadFileAsync(new Uri(myStringWebResource), @path + "/" + Downloadfilename); } else { Console.ReadLine(); // MessageBox.Show(path); } } else { notifyIcon1.Visible = true; notifyIcon1.ShowBalloonTip(3000, "版本提示:", "已经是最新版本", ToolTipIcon.Info); } }
private async void Form1_Load(object sender, EventArgs e) { downloadRoot = rootUrl + "resources/"; await GetLocalVersion(); try { await GetServerVersion(); } catch (Exception ex) { Debug.WriteLine("catch " + ex.ToString()); OpenTeacherClient(); return; } //JObject sv = JObject.Parse(serverVersion); Debug.WriteLine("localVersion " + localVersion["version"]); Debug.WriteLine("serverVersion " + serverVersion["version"]); if (serverVersion["update"].ToString() == "0") { Debug.WriteLine("NO UPDATE "); OpenTeacherClient(); return; } fileInfos = (JArray)serverVersion["files"]; Debug.WriteLine(fileInfos.Count); if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } updateTeacher = serverVersion["update_teacher"].ToString() != "0"; if (updateTeacher) { JObject t = new JObject(); t["name"] = teacherFileName; t["path"] = ""; fileInfos.Add(t); } //KillNodeProcess(); updateServer = serverVersion["update_server"].ToString() != "0"; if (updateServer) { KillNodeProcess(); JObject t = new JObject(); t["name"] = serverFileName; t["path"] = ""; fileInfos.Add(t); } updateStudent = serverVersion["update_student"].ToString() != "0"; if (updateStudent) { JObject t = new JObject(); t["name"] = studentFileName; t["path"] = ""; fileInfos.Add(t); } if (fileIndex < fileInfos.Count) { label1.Text = string.Format("下载中({0}/{1})", fileIndex + 1, fileInfos.Count); JToken fileInfo = fileInfos[fileIndex]; webClient = new WebClient(); webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted; webClient.DownloadProgressChanged += Wb_DownloadProgressChanged; CreateDirectory(tempFolderPath + fileInfo["path"]); webClient.DownloadFileAsync(new Uri(downloadRoot + fileInfo["path"] + fileInfo["name"]), tempFolderPath + fileInfo["path"] + fileInfo["name"]); Debug.WriteLine("downloading ... " + downloadRoot + fileInfo["path"] + fileInfo["name"] + " " + tempFolderPath + fileInfo["path"] + fileInfo["name"]); } }
public static void DownloadFileAsync(this Uri uri, string fileName, Action completed) { if (uri == null) return; WebClient client = new WebClient(); client.DownloadFileAsync(uri, fileName); client.DownloadFileCompleted += (sender, e) => { if (completed != null) { completed(); } }; }
public bool LoadRemoteUpdateCollection() { try { this._Form.AddToDetails("Downloading remote update XML file...."); if (File.Exists(Paths.Files + "RemoteUpdate.xml")) { File.Delete(Paths.Files + "RemoteUpdate.xml"); } WebClient Client = new WebClient(); bool _isDownloading = false; Client.DownloadFileCompleted += (s, e) => { this._Form.UpdateProgress(100); this._Form.AddToDetails("Download Complete."); Client.Dispose(); Client = null; _isDownloading = false; }; Client.DownloadProgressChanged += (s, e) => { this._Form.UpdateProgress(e.ProgressPercentage); }; try { Client.DownloadFileAsync(new Uri(Paths.RemoteUpdateXML), Paths.Files + "RemoteUpdate.xml"); _isDownloading = true; } catch (Exception) { throw new Exception("Error"); } //await Task.Run(() => //{ while (_isDownloading) { } // }); XDocument RemoteXML = XDocument.Load(Paths.Files + "RemoteUpdate.xml"); UpdateCollection tUpdateColleciton = new UpdateCollection(); //replaceoriginal = (XmlRoot.Element("localpath").HasAttributes) ? ((XmlRoot.Element("localpath").Attribute("replaceoriginal") != null) ? true : false) : false foreach (object UO in (from XmlRoot in RemoteXML.Element("update").Elements("file") select new UpdateObject { localpath = (string)XmlRoot.Element("localpath"), remotepath = (string)XmlRoot.Element("remotepath"), version = (string)XmlRoot.Element("version"), name = (string)XmlRoot.Element("name") } ) ) { tUpdateColleciton.AddObject((UpdateObject)UO); } _RemoteUpdateCollection = tUpdateColleciton; return(true); } catch (Exception) { this._Form.AddToDetails("There was an issue loading the remote updates, try restarting. You can play the game normally still."); return(false); } }
public static async Task ConcurrentOperations_Throw() { await LoopbackServer.CreateServerAsync((server, url) => { var wc = new WebClient(); Task ignored = wc.DownloadDataTaskAsync(url); // won't complete Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); }); return Task.CompletedTask; }); }
/// <summary> /// Downloads and tags a track. Returns true if the track has been correctly downloaded; false otherwise. /// </summary> /// <param name="albumDirectoryPath">The path where to save the tracks.</param> /// <param name="album">The album of the track to download.</param> /// <param name="track">The track to download.</param> /// <param name="tagTrack">True to tag the track; false otherwise.</param> /// <param name="saveCoverArtInTags">True to save the cover art in the tag tracks; false otherwise.</param> /// <param name="artwork">The cover art.</param> private Boolean DownloadAndTagTrack(String albumDirectoryPath, Album album, Track track, Boolean tagTrack, Boolean saveCoverArtInTags, TagLib.Picture artwork) { Log($"Downloading track \"{track.Title}\" from url: {track.Mp3Url}", LogType.VerboseInfo); // Set location to save the file String trackPath = albumDirectoryPath + "\\" + GetFileName(album, track); if (trackPath.Length > 256) { // Shorten the path (Windows doesn't support a path > 256 characters) trackPath = albumDirectoryPath + "\\" + GetFileName(album, track).Substring(0, 3) + Path.GetExtension(trackPath); } int tries = 0; Boolean trackDownloaded = false; if (File.Exists(trackPath)) { long length = new FileInfo(trackPath).Length; foreach (TrackFile trackFile in filesDownload) { if (track.Mp3Url == trackFile.Url && trackFile.Size > length - (trackFile.Size * userSettings.AllowableFileSizeDifference) && trackFile.Size < length + (trackFile.Size * userSettings.AllowableFileSizeDifference)) { Log($"Track already exists within allowed filesize range: track \"{GetFileName(album, track)}\" from album \"{album.Title}\" - Skipping download!", LogType.IntermediateSuccess); return(false); } } } do { var doneEvent = new AutoResetEvent(false); using (var webClient = new WebClient()) { if (webClient.Proxy != null) { webClient.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { UpdateProgress(track.Mp3Url, e.BytesReceived); }; // Warn & tag when downloaded webClient.DownloadFileCompleted += (s, e) => { WaitForCooldown(tries); tries++; if (!e.Cancelled && e.Error == null) { trackDownloaded = true; if (tagTrack) { // Tag (ID3) the file when downloaded TagLib.File tagFile = TagLib.File.Create(trackPath); tagFile.Tag.Album = album.Title; tagFile.Tag.AlbumArtists = new String[1] { album.Artist }; tagFile.Tag.Performers = new String[1] { album.Artist }; tagFile.Tag.Title = track.Title; tagFile.Tag.Track = (uint)track.Number; tagFile.Tag.Year = (uint)album.ReleaseDate.Year; tagFile.Tag.Lyrics = track.Lyrics; tagFile.Save(); } if (saveCoverArtInTags && artwork != null) { // Save cover in tags when downloaded TagLib.File tagFile = TagLib.File.Create(trackPath); tagFile.Tag.Pictures = new TagLib.IPicture[1] { artwork }; tagFile.Save(); } // Note the file as downloaded TrackFile currentFile = this.filesDownload.Where(f => f.Url == track.Mp3Url).First(); currentFile.Downloaded = true; Log($"Downloaded track \"{GetFileName(album, track)}\" from album \"{album.Title}\"", LogType.IntermediateSuccess); } else if (!e.Cancelled && e.Error != null) { if (tries < userSettings.DownloadMaxTries) { Log($"Unable to download track \"{GetFileName(album, track)}\" from album \"{album.Title}\". Try {tries} of {userSettings.DownloadMaxTries}", LogType.Warning); } else { Log($"Unable to download track \"{GetFileName(album, track)}\" from album \"{album.Title}\". Hit max retries of {userSettings.DownloadMaxTries}", LogType.Error); } } // Else the download has been cancelled (by the user) doneEvent.Set(); }; lock (this.pendingDownloads) { if (this.userCancelled) { // Abort return(false); } // Register current download this.pendingDownloads.Add(webClient); // Start download webClient.DownloadFileAsync(new Uri(track.Mp3Url), trackPath); } // Wait for download to be finished doneEvent.WaitOne(); lock (this.pendingDownloads) { this.pendingDownloads.Remove(webClient); } } } while (!trackDownloaded && tries < userSettings.DownloadMaxTries); return(trackDownloaded); }
public override System.Collections.IEnumerator Execute(UTContext context) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayer || EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayerStreamed) { Debug.LogWarning("You have currently set the build target to 'Web Player'. This may cause interference with actions that access the internet. If you get an error message about cross domain policy from this action, switch the target to 'PC and Mac Standalone' and try again."); } var theNexusUrl = nexusUrl.EvaluateIn (context); if (string.IsNullOrEmpty (theNexusUrl)) { throw new UTFailBuildException ("You need to specify the nexus URL", this); } var theRepoId = repositoryId.EvaluateIn (context); if (string.IsNullOrEmpty (theRepoId)) { throw new UTFailBuildException ("You need to specify the repository id.", this); } var theUserName = userName.EvaluateIn (context); var thePassword = password.EvaluateIn (context); var theGroupId = groupId.EvaluateIn (context); if (string.IsNullOrEmpty (theGroupId)) { throw new UTFailBuildException ("You need to specify the group id.", this); } var theArtifactId = artifactId.EvaluateIn (context); if (string.IsNullOrEmpty (theArtifactId)) { throw new UTFailBuildException ("You need to specify the artifact id.", this); } var theVersion = version.EvaluateIn (context); if (string.IsNullOrEmpty (theVersion)) { throw new UTFailBuildException ("You need to specify the version.", this); } var thePackaging = packaging.EvaluateIn(context); if (string.IsNullOrEmpty (thePackaging)) { throw new UTFailBuildException ("You need to specify the packaging.", this); } var theExtension = extension.EvaluateIn(context); var theClassifier = classifier.EvaluateIn(context); var theOutputFileName = outputFileName.EvaluateIn (context); if (string.IsNullOrEmpty (theOutputFileName)) { throw new UTFailBuildException ("You need to specify the output file name.", this); } if (Directory.Exists (theOutputFileName)) { throw new UTFailBuildException ("The specified output file " + theOutputFileName + " is a directory.", this); } UTFileUtils.EnsureParentFolderExists (theOutputFileName); // TODO: ignore SSL certs if required using (var wc = new WebClient()) { if (!string.IsNullOrEmpty (theUserName)) { wc.Credentials = new NetworkCredential (theUserName, thePassword); } Uri uri = new Uri (theNexusUrl + "/service/local/artifact/maven/content?" + "g=" + Uri.EscapeUriString (theGroupId) + "&a=" + Uri.EscapeUriString (theArtifactId) + "&v=" + Uri.EscapeUriString (theVersion) + "&r=" + Uri.EscapeUriString (theRepoId) + "&p=" + Uri.EscapeUriString(thePackaging) + (!string.IsNullOrEmpty(theClassifier) ? "&c=" + Uri.EscapeUriString(theClassifier) : "") + (!string.IsNullOrEmpty(theExtension) ? "&e=" + Uri.EscapeUriString(theExtension) : "")); downloadFinished = false; error = false; wc.DownloadFileCompleted += delegate( object sender, AsyncCompletedEventArgs e) { downloadFinished = true; error = e.Error != null; if (error) { Debug.LogError ("An error occured while downloading. " + e.Error.Message, this); } }; wc.DownloadFileAsync (uri, theOutputFileName); do { yield return ""; if (context.CancelRequested) { wc.CancelAsync (); } } while(!downloadFinished); if (!error && !context.CancelRequested) { Debug.Log ("Successfully downloaded artifact to " + theOutputFileName + ".", this); } if (context.CancelRequested) { File.Delete(theOutputFileName); } } }
/// <summary> /// Downloads the cover art. /// </summary> /// <param name="album">The album to download.</param> /// <param name="downloadsFolder">The downloads folder.</param> /// <param name="saveCovertArtInFolder">True to save cover art in the downloads folder; false otherwise.</param> /// <param name="convertCoverArtToJpg">True to convert the cover art to jpg; false otherwise.</param> /// <param name="resizeCoverArt">True to resize the covert art; false otherwise.</param> /// <param name="coverArtMaxSize">The maximum width/height of the cover art when resizing.</param> /// <returns></returns> private TagLib.Picture DownloadCoverArt(Album album, String downloadsFolder, Boolean saveCovertArtInFolder, Boolean convertCoverArtToJpg, Boolean resizeCoverArt, int coverArtMaxSize) { // Compute path where to save artwork String artworkPath = (saveCovertArtInFolder ? downloadsFolder : Path.GetTempPath()) + "\\" + album.Title.ToAllowedFileName() + Path.GetExtension(album.ArtworkUrl); if (artworkPath.Length > 256) { // Shorten the path (Windows doesn't support a path > 256 characters) artworkPath = (saveCovertArtInFolder ? downloadsFolder : Path.GetTempPath()) + "\\" + album.Title.ToAllowedFileName().Substring(0, 3) + Path.GetExtension(album.ArtworkUrl); } TagLib.Picture artwork = null; int tries = 0; Boolean artworkDownloaded = false; do { var doneEvent = new AutoResetEvent(false); using (var webClient = new WebClient()) { if (webClient.Proxy != null) { webClient.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { UpdateProgress(album.ArtworkUrl, e.BytesReceived); }; // Warn when downloaded webClient.DownloadFileCompleted += (s, e) => { if (!e.Cancelled && e.Error == null) { artworkDownloaded = true; // Convert/resize artwork if (userSettings.ConvertCoverArtToJpg || userSettings.ResizeCoverArt) { var settings = new ResizeSettings(); if (convertCoverArtToJpg) { settings.Format = "jpg"; settings.Quality = 90; } if (resizeCoverArt) { settings.MaxHeight = userSettings.CoverArtMaxSize; settings.MaxWidth = userSettings.CoverArtMaxSize; } ImageBuilder.Current.Build(artworkPath, artworkPath, settings); } artwork = new TagLib.Picture(artworkPath) { Description = "Picture" }; // Delete the cover art file if it was saved in Temp if (!saveCovertArtInFolder) { try { System.IO.File.Delete(artworkPath); } catch { // Could not delete the file. Nevermind, it's in Temp/ folder... } } // Note the file as downloaded TrackFile currentFile = this.filesDownload.Where(f => f.Url == album.ArtworkUrl).First(); currentFile.Downloaded = true; Log($"Downloaded artwork for album \"{album.Title}\"", LogType.IntermediateSuccess); } else if (!e.Cancelled && e.Error != null) { if (tries < userSettings.DownloadMaxTries) { Log($"Unable to download artwork for album \"{album.Title}\". Try {tries} of {userSettings.DownloadMaxTries}", LogType.Warning); } else { Log($"Unable to download artwork for album \"{album.Title}\". Hit max retries of {userSettings.DownloadMaxTries}", LogType.Error); } } // Else the download has been cancelled (by the user) doneEvent.Set(); }; lock (this.pendingDownloads) { if (this.userCancelled) { // Abort return(null); } // Register current download this.pendingDownloads.Add(webClient); // Start download webClient.DownloadFileAsync(new Uri(album.ArtworkUrl), artworkPath); } // Wait for download to be finished doneEvent.WaitOne(); lock (this.pendingDownloads) { this.pendingDownloads.Remove(webClient); } } } while (!artworkDownloaded && tries < userSettings.DownloadMaxTries); return(artwork); }
public void Testa() { int u = 1; int c = Convert.ToInt32(server.Text) + u; try { //Es wird ein neues Update gestartet if (Convert.ToInt32(your.Text) < Convert.ToInt32(server.Text)) { Verbindung.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); Verbindung.DownloadFileCompleted += delegate { try { //Process oProcess = null; var oProcess = Process.Start("UnRAR.exe", "x -y -ac " + your.Text + ".rar"); //extract.extract() //Patch löschen oProcess.WaitForExit(); File.Delete(your.Text + ".rar"); int ergebnis = Convert.ToInt32(your.Text) + u; your.Text = ergebnis.ToString(); string Client = @"Client.dat"; File.WriteAllText(Client, your.Text); this.Testa(); } catch { } }; // Start downloading the file Verbindung.DownloadFileAsync(new Uri("http://127.0.0.1/patcher/data/" + your.Text + ".rar"), your.Text + ".rar"); } else if (your.Text == server.Text) { string tst = label1.Text; if (Convert.ToUInt32(your.Text) > Convert.ToUInt32(tst)) { Verbindung.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); Verbindung.DownloadFileCompleted += delegate { try { //Process oProcess = null; var oProcess = Process.Start("UnRAR.exe", "x -y -ac " + your.Text + ".rar"); //extract.extract() //Patch löschen oProcess.WaitForExit(); File.Delete(your.Text + ".rar"); int ergebnis = Convert.ToInt32(your.Text) + u; your.Text = ergebnis.ToString(); string Client = @"Client.dat"; File.WriteAllText(Client, your.Text); this.Testa(); } catch { } }; // Start downloading the file Verbindung.DownloadFileAsync(new Uri("http://127.0.0.1/patcher/data/" + server.Text + ".rar"), server.Text + ".rar"); } else { your.Text = server.Text; string Client = @"Client.dat"; File.WriteAllText(Client, your.Text); Startbtn.Enabled = true; } } else if (your.Text == c.ToString()) { your.Text = server.Text; string Client = @"Client.dat"; File.WriteAllText(Client, your.Text); Startbtn.Enabled = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void LoadConnection(object sender, DoWorkEventArgs e) { if (_clientChangelogDownloader.IsBusy) { return; } bool blnChummerVersionGotten = true; { LatestVersion = LanguageManager.GetString("String_No_Update_Found", GlobalOptions.Language); string strUpdateLocation = "https://api.github.com/repos/chummer5a/chummer5a/releases/latest"; if (_blnPreferNightly) { strUpdateLocation = "https://api.github.com/repos/chummer5a/chummer5a/releases"; } HttpWebRequest request = null; try { WebRequest objTemp = WebRequest.Create(strUpdateLocation); request = objTemp as HttpWebRequest; } catch (System.Security.SecurityException) { blnChummerVersionGotten = false; } if (request == null) { blnChummerVersionGotten = false; } if (blnChummerVersionGotten) { request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; request.Accept = "application/json"; request.Timeout = 5000; // Get the response. HttpWebResponse response = null; try { IAsyncResult objResult = request.BeginGetResponse(new AsyncCallback(FinishWebRequest), null); void FinishWebRequest(IAsyncResult result) { response = request.EndGetResponse(result) as HttpWebResponse; } while (!objResult.IsCompleted) { if (_workerConnectionLoader.CancellationPending) { request.EndGetResponse(objResult); e.Cancel = true; response?.Close(); return; } } } catch (WebException) { blnChummerVersionGotten = false; } if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; response?.Close(); return; } // Get the stream containing content returned by the server. Stream dataStream = response?.GetResponseStream(); if (dataStream == null) { blnChummerVersionGotten = false; } if (blnChummerVersionGotten) { if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; dataStream.Close(); response.Close(); return; } // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); string[] stringSeparators = new string[] { "," }; string[] result = responseFromServer.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); bool blnFoundTag = false; bool blnFoundArchive = false; foreach (string line in result) { if (_workerConnectionLoader.CancellationPending) { e.Cancel = true; reader.Close(); dataStream.Close(); response.Close(); return; } if (!blnFoundTag && line.Contains("tag_name")) { _strLatestVersion = line.Split(':')[1]; LatestVersion = _strLatestVersion.Split('}')[0].FastEscape('\"'); blnFoundTag = true; if (blnFoundArchive) { break; } } if (!blnFoundArchive && line.Contains("browser_download_url")) { _strDownloadFile = line.Split(':')[2]; _strDownloadFile = _strDownloadFile.Substring(2); _strDownloadFile = _strDownloadFile.Split('}')[0].FastEscape('\"'); _strDownloadFile = "https://" + _strDownloadFile; blnFoundArchive = true; if (blnFoundTag) { break; } } } if (!blnFoundArchive || !blnFoundTag) { blnChummerVersionGotten = false; } // Cleanup the streams and the response. reader.Close(); } dataStream.Close(); response.Close(); } } if (!blnChummerVersionGotten) { MessageBox.Show(LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language), "Chummer5", MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } else if (LatestVersion != LanguageManager.GetString("String_No_Update_Found", GlobalOptions.Language)) { if (File.Exists(_strTempUpdatePath)) { if (File.Exists(_strTempUpdatePath + ".old")) { File.Delete(_strTempUpdatePath + ".old"); } File.Move(_strTempUpdatePath, _strTempUpdatePath + ".old"); } string strURL = "https://raw.githubusercontent.com/chummer5a/chummer5a/" + LatestVersion + "/Chummer/changelog.txt"; if (Uri.TryCreate(strURL, UriKind.Absolute, out Uri uriConnectionAddress)) { try { if (File.Exists(_strTempUpdatePath + ".tmp")) { File.Delete(_strTempUpdatePath + ".tmp"); } _clientChangelogDownloader.DownloadFileAsync(uriConnectionAddress, _strTempUpdatePath + ".tmp"); while (_clientChangelogDownloader.IsBusy) { if (_workerConnectionLoader.CancellationPending) { _clientChangelogDownloader.CancelAsync(); e.Cancel = true; return; } } File.Move(_strTempUpdatePath + ".tmp", _strTempUpdatePath); } catch (WebException) { MessageBox.Show(LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language), "Chummer5", MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } } else { MessageBox.Show(LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language), "Chummer5", MessageBoxButtons.OK, MessageBoxIcon.Error); _blnIsConnected = false; e.Cancel = true; } } }
public void Start() { Utils.StartAsync(() => { var paths = new List <string>(); var platform = "win32"; var archiveName = "minimal-portable+dedicated.zip"; if (Environment.OSVersion.Platform == PlatformID.Unix) { var response = Utils.ExecuteConsoleCommand("uname", "-m") ?? ""; platform = response.Contains("64") ? "linux64" : "linux32"; archiveName = string.Format("minimal-portable-{0}-static.7z", platform); } // special hack for engine 91.0 //if (platform == "linux64" && Name == "91.0") paths.Add("http://springrts.com/dl/spring_91.0.amd64.zip"); //else if (platform == "linux32" && Name == "91.0") paths.Add("http://springrts.com/dl/spring_91.0_portable_linux_i686.zip"); var engineDownloadPath = GlobalConst.EngineDownloadPath; paths.Add(string.Format("{0}buildbot/syncdebug/develop/{1}/spring_[syncdebug]{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/master/{1}/spring_{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/develop/{1}/spring_{{develop}}{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/release/{1}/spring_{{release}}{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/MTsim/{1}/spring_{{MTsim}}{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/master/{1}/{3}/spring_{1}_{2}", engineDownloadPath, Name, archiveName, platform)); paths.Add(string.Format("{0}buildbot/default/develop/{1}/{3}/spring_{{develop}}{1}_{2}", engineDownloadPath, Name, archiveName, platform)); paths.Add(string.Format("{0}buildbot/default/release/{1}/{3}/spring_{{release}}{1}_{2}", engineDownloadPath, Name, archiveName, platform)); paths.Add(string.Format("{0}buildbot/default/MTsim/{1}/{3}/spring_{{MTsim}}{1}_{2}", engineDownloadPath, Name, archiveName, platform)); paths.Add(string.Format("{0}buildbot/default/LockFreeLua/{1}/spring_{{LockFreeLua}}{1}_{2}", engineDownloadPath, Name, archiveName)); paths.Add(string.Format("{0}buildbot/default/LockFreeLua/{1}/{3}/spring_{{LockFreeLua}}{1}_{2}", engineDownloadPath, Name, archiveName, platform)); for (var i = 9; i >= -1; i--) { var version = Name; // if i==-1 we tested without version number if (i >= 0) { version = string.Format("{0}.{1}", Name, i); } paths.Add(string.Format("{0}spring_{1}.zip", engineDownloadPath, version)); } var source = paths.FirstOrDefault(VerifyFile) ?? paths.FirstOrDefault(VerifyFile); if (source != null) { var extension = source.Substring(source.LastIndexOf('.')); var wc = new WebClient() { Proxy = null }; var name = Assembly.GetEntryAssembly().GetName(); wc.Headers.Add("user-agent", string.Format("{0} {1}", name.Name, name.Version)); var target = Path.GetTempFileName() + extension; wc.DownloadProgressChanged += (s, e) => { Length = (int)(e.TotalBytesToReceive); IndividualProgress = 10 + 0.8 * e.ProgressPercentage; }; wc.DownloadFileCompleted += (s, e) => { if (e.Cancelled) { Trace.TraceInformation("Download {0} cancelled", Name); Finish(false); } else if (e.Error != null) { Trace.TraceWarning("Error downloading {0}: {1}", Name, e.Error); Finish(false); } else { Trace.TraceInformation("Installing {0}", source); var timer = new Timer((o) => { IndividualProgress += (100 - IndividualProgress) / 10; }, null, 1000, 1000); if (extension == ".exe") { var p = new Process(); p.StartInfo = new ProcessStartInfo(target, string.Format("/S /D={0}", springPaths.GetEngineFolderByVersion(Name))); p.Exited += (s2, e2) => { timer.Dispose(); if (p.ExitCode != 0) { Trace.TraceWarning("Install of {0} failed: {1}", Name, p.ExitCode); Finish(false); } else { Trace.TraceInformation("Install of {0} complete", Name); springPaths.SetEnginePath(springPaths.GetEngineFolderByVersion(Name)); Finish(true); // run unitsync after engine download; for more info see comments in Program.cs //new PlasmaShared.UnitSyncLib.UnitSync(springPaths); // put it after Finish() so it doesn't hold up the download bar //^ is commented because conflict/non-consensus. See: https://code.google.com/p/zero-k/source/detail?r=12394 for some issue/discussion } }; p.EnableRaisingEvents = true; p.Start(); } else { var targetDir = springPaths.GetEngineFolderByVersion(Name); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } try { if (extension == ".7z") { var proc = Process.Start("7z", string.Format("x -r -y -o\"{1}\" \"{0}\"", target, targetDir)); if (proc != null) { proc.WaitForExit(); } if (proc == null || proc.ExitCode != 0) { Trace.TraceWarning("7z extraction failed, fallback to SharpCompress"); ExtractArchive(target, targetDir); } } else { ExtractArchive(target, targetDir); } Trace.TraceInformation("Install of {0} complete", Name); springPaths.SetEnginePath(targetDir); Finish(true); // run unitsync after engine download; for more info see comments in Program.cs //new PlasmaShared.UnitSyncLib.UnitSync(springPaths); // put it after Finish() so it doesn't hold up the download bar //^ is commented because conflict/non-consensus. See: https://code.google.com/p/zero-k/source/detail?r=12394 for some issue/discussion } catch (Exception ex) { try { Directory.Delete(targetDir, true); } catch {} Trace.TraceWarning("Install of {0} failed: {1}", Name, ex); Finish(false); } } } }; Trace.TraceInformation("Downloading {0}", source); wc.DownloadFileAsync(new Uri(source), target, this); return; } Trace.TraceInformation("Cannot find {0}", Name); Finish(false); }); }
private void ProcDownload(object o) { var errorMessageStr = new StringBuilder(); string tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName); if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } evtPerDonwload = new ManualResetEvent(false); foreach (DownloadFileInfo file in this.downloadFileList) { total += file.Size; } try { while (!evtDownload.WaitOne(0, false)) { if (this.downloadFileList.Count == 0) { break; } DownloadFileInfo file = this.downloadFileList[0]; //Debug.WriteLine(String.Format("Start Download:{0}", file.FileName)); this.ShowCurrentDownloadFileName(file.FileName); //Download clientDownload = new WebClient(); //Added the function to support proxy // clientDownload.Proxy = System.Net.WebProxy.GetDefaultProxy(); clientDownload.Proxy = WebRequest.GetSystemWebProxy(); clientDownload.Proxy.Credentials = CredentialCache.DefaultCredentials; //clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials;//ftp可能不可用 if (!string.IsNullOrEmpty(config.PassWord) && !string.IsNullOrEmpty(config.UserName)) { clientDownload.Credentials = new NetworkCredential(config.UserName, config.PassWord); } else { clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials; } //End added clientDownload.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { try { this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total)); } catch { //log the error message,you can use the application's log code } }; clientDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { try { DealWithDownloadErrors(); DownloadFileInfo dfile = e.UserState as DownloadFileInfo; nDownloadedTotal += dfile.Size; this.SetProcessBar(0, (int)(nDownloadedTotal * 100 / total)); evtPerDonwload.Set(); } catch (Exception) { //log the error message,you can use the application's log code } }; evtPerDonwload.Reset(); //Download the folder file string tempFolderPath1 = CommonUnitity.GetFolderUrl(file, curBakFolderName); if (!string.IsNullOrEmpty(tempFolderPath1)) { tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName); tempFolderPath += tempFolderPath1; } else { tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName); } if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl), Path.Combine(tempFolderPath, file.FileName), file); //Wait for the download complete evtPerDonwload.WaitOne(); clientDownload.Dispose(); clientDownload = null; #region 可能会进行下载失败,进行多次重新下载 string tempUrlPath = CommonUnitity.GetFolderUrl(file, curBakFolderName); var newPath = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName + tempUrlPath, file.FileName); System.IO.FileInfo f = new FileInfo(newPath); if (file.TryTimes < tryTimes && !file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml")) { //下载出错,进行重试 file.TryTimes += 1; //尝试次数递增 var curItem = config.UpdateFileList.Where(c => c.Version == file.Version).FirstOrDefault(); if (curItem != null) { curItem.TryTimes += 1; //失败的文件不保存,用于下次重启 } if (_log != null) { _log.Info(string.Format("文件{0}:{1}下载失败后进行了第{2}次重试下载\n\r", file.DownloadUrl, file.Version, file.TryTimes)); } } else { //Remove the downloaded files this.downloadFileList.Remove(file); } #endregion } } catch (Exception) { ShowErrorAndRestartApplication(); //throw; } //When the files have not downloaded,return. if (downloadFileList.Count > 0) { return; } //Test network and deal with errors if there have DealWithDownloadErrors(); //Debug.WriteLine("All Downloaded"); foreach (DownloadFileInfo file in this.allFileList) { string tempUrlPath = CommonUnitity.GetFolderUrl(file, curBakFolderName); string oldPath = string.Empty; string newPath = string.Empty; try { if (!string.IsNullOrEmpty(tempUrlPath)) { oldPath = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName); newPath = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName + tempUrlPath, file.FileName); } else { oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName); newPath = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName, file.FileName); } //just deal with the problem which the files EndsWith xml can not download System.IO.FileInfo f = new FileInfo(newPath); //errorMessageStr.AppendFormat("{0},", file.FileFullName); //2015.5.11文件不存在可以进行拷贝xml if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml")) { //<LocalFile path="packages.config" lastver="" size="370" version="e0d3579f-44ba-4e99-b557-de2b37d9f588" /> var errorMsg = string.Format("<LocalFile path=\"{0}\" lastver=\"\" size=\"{1}\" version=\"{2}\" downLoadUrl=\"{3}\"/>", file.FileFullName, file.Size, file.Version, file.DownloadUrl); errorMessageStr.AppendLine(file.DownloadUrl); var curItem = config.UpdateFileList.Where(c => c.Version == file.Version).FirstOrDefault(); if (curItem != null) { config.UpdateFileList.Remove(curItem);//失败的文件不保存,用于下次重启 } continue; // ShowErrorAndRestartApplication(); } //Added for dealing with the config file download errors string newfilepath = string.Empty; if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals(ConstFile.CONFIGFILEKEY)) { if (System.IO.File.Exists(newPath)) { if (newPath.EndsWith("_")) { newfilepath = newPath; newPath = newPath.Substring(0, newPath.Length - 1); oldPath = oldPath.Substring(0, oldPath.Length - 1); } File.Copy(newfilepath, newPath, true); } } //End added if (File.Exists(oldPath))//文件存在 { MoveFolderToOld(oldPath, newPath); } else { //Edit for config_ file if (!string.IsNullOrEmpty(tempUrlPath)) { if (!Directory.Exists(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1))) { Directory.CreateDirectory(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1)); MoveFolderToOld(oldPath, newPath); } else { MoveFolderToOld(oldPath, newPath); } } else { MoveFolderToOld(oldPath, newPath); } } } catch (Exception exp) { //log the error message,you can use the application's log code } } //After dealed with all files, clear the data this.allFileList.Clear(); if (!string.IsNullOrEmpty(errorMessageStr.ToString())) { if (_log != null) { _log.Info(string.Format("更新内容出错,无大小或者下载出错文件如下,可尝试手动更新,并配置IIS为可访问下载{0}", errorMessageStr.ToString())); } //CommonUnitity.RestartApplication(); } else { if (_log != null) { _log.Info(string.Format("本次更新成功个数为:{0}", config.UpdateFileList.Count())); } } if (this.downloadFileList.Count == 0) { Exit(true); } else { Exit(false); } evtDownload.Set(); }
private void CheckDownloadQueue() { if (!downloadingData) { if (downloadQueue.Count != 0) { int i = downloadQueue.Dequeue(); try { if (System.IO.File.Exists(downloadDirectoryPath + artistNameList[i.ToString()] + " - " + songTitleList[i.ToString()] + ".mp3")) { //DialogResult dr = MessageBox.Show("File has already been downloaded. Do you want to download it again?", "File already Downloaded", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); bool dummyResult = true; if (dummyResult) //(dr == DialogResult.OK) { try { Uri url = new Uri(downloadURLList[i.ToString()]); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileAsync(url, downloadDirectoryPath + artistNameList[i.ToString()] + " - " + songTitleList[i.ToString()] + ".mp3"); //label4.Text = "Currently downloading " + songTitleList[i.ToString()] + " by " + artistNameList[i.ToString()] + " from album " + albumTitleList[i.ToString()]; downloadingData = true; //progressBar1.Value = 0; } catch (KeyNotFoundException) { //drexit = DialogResult.Yes; //MessageBox.Show("A butterfly fluttered in South America. I can no longer exits. Please call me again if you feel like", "Butterfly effect", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } } else { CheckDownloadQueue(); } } else { Uri url = new Uri(downloadURLList[i.ToString()]); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileAsync(url, downloadDirectoryPath + artistNameList[i.ToString()] + " - " + songTitleList[i.ToString()] + ".mp3"); //label4.Text = "Currently downloading " + songTitleList[i.ToString()] + " by " + artistNameList[i.ToString()] + " from album " + albumTitleList[i.ToString()]; downloadingData = true; //progressBar1.Value = 0; } } catch (WebException) { //MessageBox.Show("Please check your internet connection.", "Connection Failure", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); downloadQueue.Clear(); } catch (InvalidOperationException) { //MessageBox.Show("File in use by another application.", "File in user", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); CheckDownloadQueue(); } } else { //label4.Text = "No songs in Queue"; //progressBar1.Value = 0; } } }
private void DownloadFile() { SettingManager settings = new SettingManager(); string version = settings.minecraftVersionLoad; if (stuffIndex == 3) { if (!File.Exists(cd + "\\plugins\\TechnicLauncher.exe")) { WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("http://launcher.technicpack.net/launcher4/308/TechnicLauncher.exe"), cd + "\\plugins\\TechnicLauncher.exe"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 4) { if (!File.Exists(cd + "\\plugins\\server_template\\RUN.bat")) { Directory.Delete(cd + "\\plugins\\server_template", true); Directory.CreateDirectory(cd + "\\plugins\\server_template"); Directory.CreateDirectory(cd + "\\temp"); WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("https://dl.dropboxusercontent.com/u/46484032/TMC/ServerTemplate.zip"), cd + "\\temp\\server.zip"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 5) { if (version != "" && !File.Exists(cd + "\\plugins\\server_template\\minecraft_server." + version + ".jar")) { WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("https://s3.amazonaws.com/Minecraft.Download/versions/" + version + "/minecraft_server." + version + ".jar"), cd + "\\plugins\\server_template\\minecraft_server." + version + ".jar"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 6) { if (!Directory.Exists(cd + "\\plugins\\client_template\\bin\\natives")) { Directory.CreateDirectory(cd + "\\temp"); WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("https://dl.dropboxusercontent.com/u/46484032/TMC/ClientTemplate.zip"), cd + "\\temp\\client.zip"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 7) { if (version != "" && !File.Exists(cd + "\\plugins\\client_template\\bin\\minecraft.jar")) { WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("https://s3.amazonaws.com/Minecraft.Download/versions/" + version + "/" + version + ".jar"), cd + "\\plugins\\client_template\\bin\\minecraft.jar"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 8) { if (version != "" && !File.Exists(cd + "\\plugins\\client_template\\bin\\" + version + ".json")) { WebClient client = new WebClient(); client.DownloadFileAsync(new Uri("https://s3.amazonaws.com/Minecraft.Download/versions/" + version + "/" + version + ".json"), cd + "\\plugins\\client_template\\bin\\" + version + ".json"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 9) { if (version != "" && Directory.GetFiles(cd + "\\plugins\\potionidhelper").Length == 0) { ModInfo pih = new ModInfo("potionidhelper.jar"); pih.website = "http://minecraft.curseforge.com/mc-mods/231384-potion-id-helper"; pih.UpdateModValues(); pih.CheckForUpdate(version); while (pih.checkBusy) { } WebClient client = new WebClient(); client.DownloadFileAsync(new Uri(pih.dlSite), cd + "\\plugins\\potionidhelper\\" + pih.newFileName); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } else if (stuffIndex == 10) { if (!coreExists) { foreach (string file in Directory.GetFiles(cd + "\\plugins\\potionidhelper")) { if (file.Contains("brandonscore")) { coreExists = true; break; } } } if (version != "" && !coreExists) { ModInfo bc = new ModInfo("brandonscore.jar"); bc.website = "http://minecraft.curseforge.com/mc-mods/231382-brandons-core"; bc.UpdateModValues(); bc.CheckForUpdate(version); while (bc.checkBusy) { } WebClient client = new WebClient(); client.DownloadFileAsync(new Uri(bc.dlSite), cd + "\\plugins\\potionidhelper\\" + bc.newFileName); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); } else { taskDone = true; } return; } }
/// <summary> /// Download file /// </summary> /// <param name="URL"></param> /// <param name="Title"></param> /// <param name="isVideo"></param> private void DownloadFile(string URL, string Title, bool isVideo, string file_extension) { WebClient DownloadFile = new WebClient(); // Event when download progess changed int notificationID = uniquenotificationID(); Android.Support.V4.App.NotificationCompat.Builder builder_ = publishnotification_("Downloading", Title, notificationID); DownloadFile.DownloadProgressChanged += (sender, e) => DownloadFileProgressChanged(sender, e, builder_); // Event when download completed DownloadFile.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted); // Start download var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads); // Check if directory exists try { if (!System.IO.Directory.Exists(directory.AbsolutePath)) { System.IO.Directory.CreateDirectory(directory.AbsolutePath); } } catch { } string file = string.Empty; if (isVideo) { file = Path.Combine(directory.AbsolutePath, makeFilenameValid(Title).Replace("/", "") .Replace(".", "") .Replace("|", "") .Replace("?", "") .Replace("!", "") + file_extension); } else { if (URL.Contains("youtube")) { file = Path.Combine(directory.AbsolutePath, makeFilenameValid(Title).Replace("/", "") .Replace(".", "") .Replace("|", "") .Replace("?", "") .Replace("!", "") + ".m4a"); } else { file = Path.Combine(directory.AbsolutePath, makeFilenameValid(Title).Replace("/", "") .Replace(".", "") .Replace("|", "") .Replace("?", "") .Replace("!", "") + ".mp3"); } } #if DEBUG Console.WriteLine(file); #endif Log.println(file); DownloadFile.DownloadFileAsync(new Uri(URL), file, file + "|" + Title + "|" + notificationID); #if DEBUG Console.WriteLine("Download started"); #endif Log.println("Download started"); }
public async void HandleMessage( SocketMessage message, SocketCommandContext context, IDiscordClient client) { var messageChannel = context.Channel; if (messageChannel.Name == "vb-safe-images") { if (message.Content.Contains("https://twitter.com/")) { await context.Channel.SendMessageAsync("i can't get images from f*****g twitter links"); } else if (message.Attachments.Count > 0) { var attachment = message.Attachments.First(); using (var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(attachment.Url), @"C:\Users\jacob\Desktop\ml_training\safe\" + attachment.Filename); } } } else if (messageChannel.Name == "vb-lewd-images") { if (message.Content.Contains("https://twitter.com/")) { await context.Channel.SendMessageAsync("i can't get images from f*****g twitter links"); } else if (message.Attachments.Count > 0) { var attachment = message.Attachments.First(); using (var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(attachment.Url), @"C:\Users\jacob\Desktop\ml_training\lewd\" + attachment.Filename); } } } var botMention = message.MentionedUsers.FirstOrDefault(x => x.Id == client.CurrentUser.Id); if (botMention == null) { return; } var content = message.Content; if (content.Contains("can you breathe")) { var audioService = _services.GetRequiredService <AudioService>(); var voiceChannel = ((IGuildUser)context.User).VoiceChannel; if (voiceChannel == null) { await context.Channel.SendMessageAsync("no i can't breathe"); return; } await audioService.PlayFileAsync(@"C:\Users\jacob\Desktop\breathe.mp3", context); } else if (content.Contains("kill yourself")) { await context.Channel.SendMessageAsync("Shutting down."); await client.StopAsync(); } }
private void ProcDownload(object o) { evtPerDonwload = new ManualResetEvent(false); if (downloadFileList != null) { total += downloadFileList.Size; } try { while (!evtDownload.WaitOne(0, false)) { if (downloadFileList == null) { break; } DownloadFileInfo file = downloadFileList; this.ShowCurrentDownloadFileName(file.FileName); //Download clientDownload = new WebClient(); //Added the function to support proxy System.Net.IWebProxy iwpxy = WebRequest.GetSystemWebProxy(); clientDownload.Proxy = iwpxy; //clientDownload.Proxy = WebProxy.GetDefaultProxy(); clientDownload.Proxy.Credentials = CredentialCache.DefaultCredentials; clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials; //End added // Progress changed clientDownload.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { try { this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total)); } catch { //log the error message,you can use the application's log code } }; // Download completed clientDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { try { DownloadFileInfo dfile = e.UserState as DownloadFileInfo; nDownloadedTotal += dfile.Size; this.SetProcessBar(0, (int)(nDownloadedTotal * 100 / total)); evtPerDonwload.Set(); } catch (Exception) { //log the error message,you can use the application's log code } }; evtPerDonwload.Reset(); //Download // Telecharge le fichier dans le repertoire downloads clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl), Path.Combine(file.TargetUrl, file.FileName), file); //Wait for the download complete evtPerDonwload.WaitOne(); clientDownload.Dispose(); clientDownload = null; downloadFileList = null; } } catch (Exception) { ShowErrorAndRestartApplication(); //throw; } //After dealed with all files, clear the data allFileList = null; if (downloadFileList == null) { Exit(true); } else { Exit(false); } evtDownload.Set(); }
void BeginDownloadImage(Uri imgUri) { //get image file WebClient wc = new WebClient(); wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted); string fileName = imgUri.ToString();//imgUriList.ElementAt(downloadingImgListIndex).ToString(); string url = fileName; string title = dict[imgUri]; title = title.Replace('/','_').Replace(':','_').Replace('[','_').Replace(']','_'); fileName = fileName.Replace('/','_').Replace(':','_'); string dirName = @"D:\TDDOWNLOAD\6park_pix\"; string filePath = dirName + title + fileName; if (!File.Exists(filePath)) { wc.DownloadFileAsync(imgUri, filePath); this.LogText=DateTime.Now.ToString()+"---downloading:"+ filePath; System.Diagnostics.Debug.WriteLine(LogText); } else { downloadNextImage(); this.LogText=DateTime.Now.ToString()+"---FILE SKIPED:"+ filePath; System.Diagnostics.Debug.WriteLine(LogText); } }
static void Main() { string url = @"http://greensurrealism.pbworks.com/f/body.jpg"; string[] getFileName = url.Split('/'); string outputFileName = getFileName[getFileName.Length - 1]; int dotIndex = outputFileName.LastIndexOf('.'); bool toDownload = false; string fileName = ""; string fileNameExtension = ""; if (dotIndex != -1) { fileName = outputFileName.Substring(0, dotIndex); fileNameExtension = outputFileName.Substring(dotIndex + 1, outputFileName.Length - dotIndex - 1); toDownload = true; } DrawLine(); if (File.Exists(outputFileName) && toDownload) { Console.WriteLine("There is a file with that name."); Console.WriteLine("1) Overwrite the file"); Console.WriteLine("2) Add postfix to the filename"); Console.WriteLine("3) Cancel download"); DrawLine(); Console.Write("Your choice (1,2 or 3): "); int choice = int.Parse(Console.ReadLine()); int postfix = 1; switch (choice) { case 1: DrawLine(); Console.Write("Are you sure you want to delete {0}? (y/n): ", outputFileName); string deleteAnswear = Console.ReadLine(); if (deleteAnswear == "y") { File.Delete(outputFileName); } if (deleteAnswear == "n") { toDownload = false; } break; case 2: while (File.Exists(fileName + "[" + postfix + "]." + fileNameExtension)) { postfix++; } outputFileName = fileName + "[" + postfix + "]." + fileNameExtension; break; default: toDownload = false; break; } } if (toDownload) { using (WebClient download = new WebClient()) { try { download.DownloadFileAsync(new Uri(url), outputFileName); download.DownloadProgressChanged += progress; while (download.IsBusy) { Thread.Sleep(5); } Thread.Sleep(50); Console.WriteLine(); Console.WriteLine("Downloading completed"); DrawLine(); Console.Write("Open file? (y/n): "); string openFile = Console.ReadLine(); if (openFile == "y") { Process.Start(outputFileName); } } catch (WebException) { Console.WriteLine("Some exception"); } finally { download.Dispose(); } } } }
public static void InstallIronPython() { _filesDownloaded = 0; _downloadingInProgress = true; _downloadButtonText = "0.0 %"; _infoText = "<b>Please wait</b>\n"; if (!Directory.Exists(PythonEnvironment.LibPath)) { Directory.CreateDirectory(PythonEnvironment.LibPath); } try { for (var fileIndex = 0; fileIndex < FilesRequired; fileIndex++) { using (var client = new WebClient()) { var i = fileIndex; // delete existing file if (File.Exists(PythonEnvironment.LibPath + FileNames[i])) { File.Delete(PythonEnvironment.LibPath + FileNames[i]); } // progress handler client.DownloadProgressChanged += (sender, e) => { ReceivedSize[i] = e.BytesReceived; TotalSize[i] = e.TotalBytesToReceive; var progress = Convert.ToSingle(ReceivedSize.Sum()) / Convert.ToSingle(TotalSize.Sum()) * 100f; _downloadButtonText = progress.ToString("0.0") + " %"; }; // completion handler client.DownloadFileCompleted += (sender, e) => { if (e.Error != null) { // set error messages ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: Error downloading file:" + FileNames[i]); ModConsole.AddMessage(LogType.Error, "\t" + e.Error.Message); _infoText = FileNames[i] + " <color=red>✘</color>" + "\n\n<b><color=red>Download failed</color></b>\n" + e.Error.Message; _downloadingInProgress = false; _downloadButtonText = "Retry"; // delete failed file if (File.Exists(PythonEnvironment.LibPath + FileNames[i])) { File.Delete(PythonEnvironment.LibPath + FileNames[i]); } } else { ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: File downloaded: " + FileNames[i]); _infoText += "\n" + FileNames[i] + " <color=green>✓</color>"; _filesDownloaded++; if (_filesDownloaded != FilesRequired) { return; } // finish download and load assemblies _downloadButtonText = "Loading"; if (Script.LoadEngine(true)) { Visible = false; } else { _downloadButtonText = "Retry"; _infoText = "<b><color=red>Download failed</color></b>\nFailed to initialize Python engine."; } _downloadingInProgress = false; } }; // start download client.DownloadFileAsync( new Uri(BaseUri + PythonEnvironment.Version + "/" + FileNames[i]), PythonEnvironment.LibPath + FileNames[i]); } } } catch (Exception e) { Debug.Log("[LenchScripterMod]: Error while downloading:"); Debug.LogException(e); _downloadingInProgress = false; _downloadButtonText = "Retry"; _infoText = "<b><color=red>Download failed</color></b>\n" + e.Message; } }
private void OnButton2Clicked(object sender, System.EventArgs e) { button1.Visible = true; button3.Visible = false; button4.Visible = false; button2.Visible = false; string path = System.IO.Path.GetTempPath(); XmlDocument current = new XmlDocument(); current.Load(Environment.CurrentDirectory + @"\Info.xml"); XmlNodeList update = current.GetElementsByTagName("updatexml"); XmlNodeList pro = current.GetElementsByTagName("ProgramName"); XmlNodeList ver1 = current.GetElementsByTagName("Installedversion"); string inversion = ver1[0].InnerText; string updateurl = update[0].InnerText; string prog = pro[0].InnerText; XmlDocument updater = new XmlDocument(); updater.Load(updateurl); XmlNodeList down = updater.GetElementsByTagName("InstallerURL"); XmlNodeList load = updater.GetElementsByTagName("InstallerNAME"); XmlNodeList ver2 = updater.GetElementsByTagName("LatestVersion"); string newversion = ver2[0].InnerText; string installer = load[0].InnerText; string install = down[0].InnerText + load[0].InnerText; WebClient download = new WebClient(); label2.Text = "Downloading update for " + prog + "."; label3.Text = "Please wait..."; label4.Text = "Downloading Version " + newversion + " installer. "; download.DownloadProgressChanged += new DownloadProgressChangedEventHandler(download_DownloadProgressChanged); download.DownloadFileCompleted += new AsyncCompletedEventHandler(download_DownloadFileCompleted); if (System.IO.File.Exists(path + installer) == false) { download.DownloadFileAsync(new Uri(install), (path + installer)); } else if (System.IO.File.Exists(path + installer) == true) { System.IO.File.Delete(path + installer); download.DownloadFileAsync(new Uri(install), (path + installer)); } }
private void DownloadingPatchWindow_Load(object sender, EventArgs e) { // Keep it fresh in the bedroom if (File.Exists(pathUtils.goldenTicketDownloadsFolder + "\\GenericPatch.zip")) { File.Delete(pathUtils.goldenTicketDownloadsFolder + "\\GenericPatch.zip"); } if (File.Exists(pathUtils.goldenTicketDownloadsFolder + "810Configs.zip")) { File.Delete(pathUtils.goldenTicketDownloadsFolder + "810Configs.zip"); } if (Directory.Exists(pathUtils.goldenTicketTempFolder + "\\Generic-Patch-Files-master")) { Directory.Delete(pathUtils.goldenTicketTempFolder + "\\Generic-Patch-Files-master", true); } if (Directory.Exists(pathUtils.goldenTicketTempFolder + "\\8-10-Configs-master")) { Directory.Delete(pathUtils.goldenTicketTempFolder + "\\8-10-Configs-master", true); } // Done with the febreeze! // Let's get ready to download the patch zip from Github WebClient client = new WebClient(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); bytesLabel.Visible = true; patchingTitleLabel.Text = "Downloading patch..."; // Starts the download patchCheck: if (patchToDownload == 1) { // Download Vista/7 patch client.DownloadFileAsync(new Uri("https://github.com/The-Buzzy-Project/Generic-Patch-Files/archive/master.zip"), pathUtils.goldenTicketDownloadsFolder); // OS generic patch files } else { if (patchToDownload == 2) { // Download Vista/7 patch client.DownloadFileAsync(new Uri("https://github.com/The-Buzzy-Project/Generic-Patch-Files/archive/master.zip"), pathUtils.goldenTicketDownloadsFolder + "\\GenericPatch.zip"); // OS generic patch files // Download 8/8.1/10 graphics configs //client.DownloadFileAsync(new Uri("https://github.com/The-Buzzy-Project/8-10-Configs/archive/master.zip"), pathUtils.goldenTicketDownloadsFolder + "\\810Configs.zip"); // 8/8.1/10 graphics configs } else { MessageBox.Show("Um?"); MachineInfo machineInfo = new MachineInfo(); string winVer = machineInfo.WindowsVersion(); if (winVer.Contains("Windows Vista") || winVer.Contains("Windows 7")) { // Patch for Vista/7 patchToDownload = 1; goto patchCheck; } if (winVer.Contains("Windows 8") || winVer.Contains("Windows 8.1") || winVer.Contains("Windows 10")) { // Patch for 8/8.1/10 patchToDownload = 2; goto patchCheck; } // Just in case there's some freak accident where this doesn't return ANY of our expected Windows versions, let's flip out! if (!winVer.Contains("Windows Vista") & !winVer.Contains("Windows 7") & !winVer.Contains("Windows 8") & !winVer.Contains("Windows 8.1") & !winVer.Contains("Windows 10")) { // Set error code to 3 and stop the launcher errorCode = 3; MainWindow mw = new MainWindow(); mw.LauncherStartup.CancelAsync(); } goto patchCheck; } } }
private void DisplayResults() { if(responseProcessed_) { if(resetScroll_) { scroll_.x = scroll_.y = 0.0f; resetScroll_ = false; } object[] sounds = (object[])response_["sounds"]; GUILayout.Label("Number of results: " + response_["num_results"].ToString()); int soundCounter = 0; foreach(object sound in sounds) { var soundDictionary = (Dictionary<string, object>)sound; GUILayout.BeginHorizontal(); GUILayout.Space(10); if(GUILayout.Button(soundWaveforms_[soundCounter], waveformStyle_)) Application.OpenURL(soundDictionary["url"].ToString()); GUILayout.BeginVertical(); if(GUILayout.Button("\nPLAY\n")) { FreesoundAudioPlayer.Instance.StartStream(soundDictionary["preview-lq-ogg"].ToString()); } GUILayout.Space(6); if(GUILayout.Button("IMPORT")) { importPressed_ = true; //TODO: refactor. Change WebClient to HttpWebRequest to handle timeouts better importClient_ = new WebClient(); importClient_.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); importClient_.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); Uri request = new Uri(soundDictionary["serve"] + "?api_key=" + FreesoundHandler.Instance.ApiKey); //If the user hasn't defined a default folder at Freesound configuration //then create it at /Assets/Freesound/ if(String.IsNullOrEmpty(FreesoundHandler.Instance.FreesoundDownloadsPath)) { System.IO.Directory.CreateDirectory(Application.dataPath + "/Freesound"); FreesoundHandler.Instance.FreesoundDownloadsPath = Application.dataPath + "/Freesound"; FreesoundHandler.Instance.FreesoundDownloads = "/Freesound"; } string lastDownloadedFilePath = FreesoundHandler.Instance.FreesoundDownloadsPath + "/" + soundDictionary["original_filename"].ToString(); try { importClient_.DownloadFileAsync(request, lastDownloadedFilePath); //Cache log data to be used in async loading completion Dictionary<string, object> userDataName = (Dictionary<string, object>)soundDictionary["user"]; lastData_.filename = soundDictionary["original_filename"].ToString(); lastData_.id = soundDictionary["id"].ToString(); lastData_.url = soundDictionary["url"].ToString(); lastData_.user = userDataName["username"].ToString(); lastData_.localPath = lastDownloadedFilePath; } catch(WebException e) { UnityEditor.EditorUtility.DisplayDialog("UnityFreesound Request ERROR!", "Can't process the request." + "\n\nException thrown: " + e.Message, "OK"); } } GUILayout.EndVertical(); GUILayout.BeginVertical(); EditorGUILayout.LabelField("File name", soundDictionary["original_filename"].ToString()); int point = soundDictionary["duration"].ToString().IndexOf("."); if(point != -1) { if(soundDictionary["duration"].ToString().Length > 5) EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString().Substring(0, 5)); else EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString()); } else { EditorGUILayout.LabelField("Duration (secs)", soundDictionary["duration"].ToString()); } Dictionary<string, object> userData = (Dictionary<string, object>)soundDictionary["user"]; EditorGUILayout.LabelField("User", userData["username"].ToString()); object[] tags = (object[])soundDictionary["tags"]; if(tags.Length > 0) EditorGUILayout.Popup("Tags", 0, (string[])tags); else EditorGUILayout.LabelField("Tags", "Sound untagged"); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(10); soundCounter++; } GUILayout.BeginHorizontal(); GUILayout.Space(10); if(response_.ContainsKey("previous")) { if(GUILayout.Button("Previous results")) { string searchQuery = response_["previous"].ToString() + "&api_key=" + FreesoundHandler.Instance.ApiKey; responseProcessed_ = false; www_ = new WWW(searchQuery); } } if(response_.ContainsKey("next")) { if(GUILayout.Button("Next results")) { string searchQuery = response_["next"].ToString() + "&api_key=" + FreesoundHandler.Instance.ApiKey; responseProcessed_ = false; www_ = new WWW(searchQuery); } } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(10); } else { GUILayout.Label("Search for keywords/tags in the field above to browse sounds..."); } }
/// <summary> /// Downloads and installs the driver without user interaction /// </summary> private static void DownloadDriverQuiet(bool minimized) { driverFileName = downloadURL.Split('/').Last(); // retrives file name from url savePath = Path.GetTempPath(); string FULL_PATH_DIRECTORY = savePath + OnlineGPUVersion + @"\"; string FULL_PATH_DRIVER = FULL_PATH_DIRECTORY + driverFileName; savePath = FULL_PATH_DIRECTORY; Directory.CreateDirectory(FULL_PATH_DIRECTORY); if (File.Exists(FULL_PATH_DRIVER) && !DoesDriverFileSizeMatch(FULL_PATH_DRIVER)) { LogManager.Log("Deleting " + FULL_PATH_DRIVER + " because its length doesn't match!", LogManager.Level.INFO); File.Delete(savePath + driverFileName); } if (!File.Exists(FULL_PATH_DRIVER)) { Console.Write("Downloading the driver . . . "); if (showUI || confirmDL) { using (WebClient webClient = new WebClient()) { var notifier = new AutoResetEvent(false); var progress = new Handlers.ProgressBar(); bool error = false; webClient.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { progress.Report((double)e.ProgressPercentage / 100); }; // Only set notifier here! webClient.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled || e.Error != null) { File.Delete(savePath + driverFileName); } else { notifier.Set(); } }; try { webClient.DownloadFileAsync(new Uri(downloadURL), FULL_PATH_DRIVER); notifier.WaitOne(); } catch (Exception ex) { error = true; Console.Write("ERROR!"); Console.WriteLine(); Console.WriteLine(ex.ToString()); Console.WriteLine(); } progress.Dispose(); // dispone the progress bar if (!error) { Console.Write("OK!"); Console.WriteLine(); } } } else { using (DownloaderForm dlForm = new DownloaderForm()) { dlForm.Show(); dlForm.Focus(); dlForm.DownloadFile(new Uri(downloadURL), FULL_PATH_DRIVER); dlForm.Close(); } } } if (SettingManager.ReadSettingBool("Minimal install")) { MakeInstaller(minimized); } try { Console.WriteLine(); Console.Write("Running installer . . . "); if (SettingManager.ReadSettingBool("Minimal install")) { Process.Start(FULL_PATH_DIRECTORY + "setup.exe", "/s /noreboot").WaitForExit(); } else { if (minimized) { Process.Start(FULL_PATH_DRIVER, "/s /noreboot").WaitForExit(); } else { Process.Start(FULL_PATH_DRIVER, "/noeula").WaitForExit(); } } Console.Write("OK!"); } catch { Console.WriteLine("Could not run driver installer!"); } Console.WriteLine(); try { Directory.Delete(FULL_PATH_DIRECTORY, true); Console.WriteLine("Cleaned up: " + FULL_PATH_DIRECTORY); } catch { Console.WriteLine("Could not cleanup: " + FULL_PATH_DIRECTORY); } }
void OnlineMusicBrowserPane( int wid ) { if ( musicViewer.hideGUI == false ) { if ( startupManager.preferences.enableOMB == true ) { GUILayout.Space ( onlineMusicBrowserPosition.width / 8 ); GUILayout.BeginArea ( new Rect ( 20, onlineMusicBrowserPosition.width / 8 + 5, 216, 40 )); GUILayout.BeginHorizontal (); foreach ( Sort sort in availableSorts ) { if ( currentSort == sort ) currentStyle = sort.activeStyle; else currentStyle = sort.normalStyle; if ( GUILayout.Button ( "", currentStyle, GUILayout.Height ( 36 ))) { currentSort = sort; sortBy = sort.method; scrollPosition = new Vector2 ( 0, 0 ); } } GUILayout.EndHorizontal (); GUILayout.EndArea (); GUI.Label ( new Rect ( onlineMusicBrowserPosition.width - 236, onlineMusicBrowserPosition.width / 8 + 5, 216, 40 ), currentSort.name, sortLabelStyle ); GUILayout.Space ( 22 ); switch ( sortBy ) { case 0: GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); scrollPosition = GUILayout.BeginScrollView ( scrollPosition, GUILayout.Width( 600 ), GUILayout.Height ( onlineMusicBrowserPosition.height - 200 )); foreach ( Song song in specificSort ) { if ( songInfoOwner == song ) { guiSkin.button.normal.background = guiHover; guiSkin.button.hover.background = guiActiveHover; } else { guiSkin.button.normal.background = null; guiSkin.button.hover.background = guiHover; } if ( GUILayout.Button ( song.name )) { int firstEquation = ( allRecentlyAddedList.Count - 1 ) - specificSort.IndexOf ( song ); int secondEquation = ( allRecentlyAddedList.Count - 1 ) - firstEquation; scrollPosition.y = secondEquation * 36; if ( showSongInformation == false || songInfoOwner != song ) { if ( songInfoOwner != song ) { showSongInformation = false; songInfoOwner = null; } if ( song.downloadURL.StartsWith ( "|" ) == true ) { url = null; downloadButtonText = song.downloadURL.Substring ( 1 ); currentDownloadPercentage = ""; currentDownloadSize = "Unreleased"; } else if ( song.downloadURL.StartsWith ( "h" ) == true ) { url = new Uri ( song.downloadURL ); downloadButtonText = "Download '" + song.name + "'"; currentDownloadPercentage = ""; currentDownloadSize = "Fetching"; Thread getInfoThread = new Thread ( GetInfoThread ); getInfoThread.Priority = System.Threading.ThreadPriority.AboveNormal; getInfoThread.Start (); } showSongInformation = true; songInfoOwner = song; } else { showSongInformation = false; songInfoOwner = null; } } guiSkin.button.normal.background = null; guiSkin.button.hover.background = guiHover; if ( showSongInformation == true ) { if ( songInfoOwner == song ) { if ( downloading == false ) { GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); if ( GUILayout.Button ( downloadButtonText, buttonStyle ) && url != null ) { if ( startupManager.developmentMode == true ) UnityEngine.Debug.Log ( url ); downloadingSong = song; currentDownloadPercentage = " - Processing Download"; try { using ( client = new WebClient ()) { client.DownloadFileCompleted += new AsyncCompletedEventHandler ( DownloadFileCompleted ); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler( DownloadProgressCallback ); client.DownloadFileAsync ( url, startupManager.tempPath + song.name + "." + song.format ); } } catch ( Exception error ) { UnityEngine.Debug.Log ( error ); } downloading = true; } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } else { GUILayout.Label ( "Downloading '" + downloadingSong.name + "'", labelStyle ); GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); if ( GUILayout.Button ( "Cancel Download", buttonStyle )) { client.CancelAsync (); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } if ( String.IsNullOrEmpty ( song.largeArtworkURL ) == false && downloadArtwork == true ) { GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); if ( GUILayout.Button ( "Download Artwork", buttonStyle )) { StartCoroutine ( "DownloadArtwork", song ); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } if ( downloadingSong == songInfoOwner ) { GUILayout.Label ( "Download size: ~" + currentDownloadSize + currentDownloadPercentage ); } else { GUILayout.Label ( "Download size: ~" + currentDownloadSize ); } activeSongFormat = song.format; if ( activeSongFormat == "unity3d" ) { activeSongFormat = "encrypted"; } GUILayout.Label ( "Name: " + song.name, infoLabelStyle ); GUILayout.Label ( "Album: " + song.album, infoLabelStyle ); GUILayout.Label ( "Artist: " + song.artist, infoLabelStyle ); GUILayout.Label ( "Genre: " + song.genre, infoLabelStyle ); GUILayout.Label ( "Format: " + activeSongFormat, infoLabelStyle ); GUILayout.Label ( "Released: " + song.releaseDate, infoLabelStyle ); if ( song.links != null ) { GUILayout.Label ( "", infoLabelStyle ); GUILayout.Label ( "Support " + song.artist + " by visiting", labelStyle ); GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); for ( int supportI = 0; supportI < song.links.Count (); supportI += 1 ) { if ( song.links.Count () > 1 ) { if ( supportI == song.links.Count () - 1 ) { GUILayout.Label ( ", and" ); } else { if ( supportI != 0 ) { GUILayout.Label ( "," ); } } } if ( GUILayout.Button ( song.links[supportI].name, buttonStyle )) { Process.Start ( song.links[supportI].address ); } } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } GUILayout.Label ( "" ); } } } GUILayout.EndScrollView (); GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); break; case 1: GUILayout.BeginHorizontal (); GUILayout.Space ( 10 ); horizontalScrollPosition = GUILayout.BeginScrollView ( horizontalScrollPosition, GUILayout.Width ( onlineMusicBrowserPosition.width - 20 ), GUILayout.Height( 390 )); GUILayout.BeginHorizontal (); foreach ( Featured featured in featuredList ) { if ( GUILayout.Button ( featured.artwork, artworkStyle )) { songInfoOwner = featured.song; showSongInformation = true; if ( featured.song.downloadURL.StartsWith ( "|" ) == true ) { url = null; downloadButtonText = featured.song.downloadURL.Substring ( 1 ); currentDownloadPercentage = ""; currentDownloadSize = "Unreleased"; } else if ( featured.song.downloadURL.StartsWith ( "h" ) == true ) { url = new Uri ( featured.song.downloadURL ); downloadButtonText = "Download '" + featured.song.name + "'"; currentDownloadPercentage = ""; currentDownloadSize = "Fetching"; Thread getInfoThread = new Thread ( GetInfoThread ); getInfoThread.Priority = System.Threading.ThreadPriority.AboveNormal; getInfoThread.Start (); } int firstEquation = ( allRecentlyAddedList.Count - 1 ) - allRecentlyAddedList.IndexOf ( featured.song ); int secondEquation = ( allRecentlyAddedList.Count - 1 ) - firstEquation; scrollPosition.y = secondEquation * 36; currentSort = availableSorts[1]; specificSort = allRecentlyAddedList; sortBy = 0; } } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); GUILayout.EndScrollView (); GUILayout.EndHorizontal (); break; case 2: specificSort = allRecentlyAddedList; sortBy = 0; break; case 3: specificSort = allSongsList; sortBy = 0; break; case 4: GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); scrollPosition = GUILayout.BeginScrollView ( scrollPosition, GUILayout.Width( 600 ), GUILayout.Height ( onlineMusicBrowserPosition.height - 200 )); foreach ( Album album in albums.Values ) { if ( GUILayout.Button ( album.name )) { specificSort = album.songs; sortBy = 0; } } GUILayout.EndScrollView (); GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); break; case 5: GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); scrollPosition = GUILayout.BeginScrollView ( scrollPosition, GUILayout.Width( 600 ), GUILayout.Height ( onlineMusicBrowserPosition.height - 200 )); foreach ( Artist artist in artists.Values ) { if ( GUILayout.Button ( artist.name )) { specificSort = artist.songs; sortBy = 0; } } GUILayout.EndScrollView (); GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); break; case 6: GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); scrollPosition = GUILayout.BeginScrollView ( scrollPosition, GUILayout.Width( 600 ), GUILayout.Height ( onlineMusicBrowserPosition.height - 200 )); foreach ( Genre genre in genres.Values ) { if ( GUILayout.Button ( genre.name )) { specificSort = genre.songs; sortBy = 0; } } GUILayout.EndScrollView (); GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); break; } } else { GUI.Label ( new Rect ( 10, onlineMusicBrowserPosition.height / 4, onlineMusicBrowserPosition.width - 20, 128 ), "The OnlineMusicBrowser has been disabled!", labelStyle ); if ( GUI.Button ( new Rect ( onlineMusicBrowserPosition.width / 2 - 160, onlineMusicBrowserPosition.height / 2, 320, 64 ), "Enable OnlineMusicBrowser" )) { startupManager.SendMessage ( "RefreshOMB" ); } } } }
/// <summary> /// Downloads the driver and some other stuff /// </summary> private static void DownloadDriver() { DriverDialog.ShowGUI(); if (DriverDialog.selectedBtn == DriverDialog.SelectedBtn.DLEXTRACT) { // download and save (and extract) Console.WriteLine(); bool error = false; driverFileName = downloadURL.Split('/').Last(); // retrives file name from url try { string message = "Where do you want to save the drivers?"; if (SettingManager.ReadSettingBool("Minimal install")) { message += " (you should select a empty folder)"; } FolderSelectDialog folderSelectDialog = new FolderSelectDialog(); folderSelectDialog.Title = message; if (folderSelectDialog.Show()) { savePath = folderSelectDialog.FileName + @"\"; } else { Console.WriteLine("User closed dialog!"); return; } if (File.Exists(savePath + driverFileName) && !DoesDriverFileSizeMatch(savePath + driverFileName)) { LogManager.Log($"Deleting {savePath}{driverFileName} because its length doesn't match!", LogManager.Level.INFO); File.Delete(savePath + driverFileName); } // don't download driver if it already exists Console.Write("Downloading the driver . . . "); if (showUI && !File.Exists(savePath + driverFileName)) { using (WebClient webClient = new WebClient()) { var notifier = new AutoResetEvent(false); var progress = new Handlers.ProgressBar(); webClient.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { progress.Report((double)e.ProgressPercentage / 100); }; // Only set notifier here! webClient.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled || e.Error != null) { File.Delete(savePath + driverFileName); } else { notifier.Set(); } }; webClient.DownloadFileAsync(new Uri(downloadURL), savePath + driverFileName); notifier.WaitOne(); // sync with the above progress.Dispose(); // get rid of the progress bar } } // show the progress bar gui else if (!showUI && !File.Exists(savePath + driverFileName)) { using (DownloaderForm dlForm = new DownloaderForm()) { dlForm.Show(); dlForm.Focus(); dlForm.DownloadFile(new Uri(downloadURL), savePath + driverFileName); dlForm.Close(); } } else { LogManager.Log("Driver is already downloaded", LogManager.Level.INFO); } } catch (Exception ex) { error = true; Console.Write("ERROR!"); Console.WriteLine(); Console.WriteLine(ex.ToString()); Console.WriteLine(); } if (!error) { Console.Write("OK!"); Console.WriteLine(); } if (debug) { Console.WriteLine($"savePath: {savePath}"); } if (SettingManager.ReadSettingBool("Minimal install")) { MakeInstaller(false); } } else if (DriverDialog.selectedBtn == DriverDialog.SelectedBtn.DLINSTALL) { DownloadDriverQuiet(false); } }
private static void Download() { client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((object sender, DownloadProgressChangedEventArgs args) => { Console.WriteLine(args.ProgressPercentage + "% downloaded."); }); client.DownloadFileAsync(new Uri(url), tempZip); }
/// <summary> /// 下载文件 /// </summary> private void OnDownloadFile(List<object> evParams) { string url = evParams[0].ToString(); mCurDownFile = evParams[1].ToString(); using (WebClient client = new WebClient()) { mStopwatch.Start(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); client.DownloadFileAsync(new System.Uri(url), mCurDownFile); } }