public static async Task Loader(string link, Label message) { if (!string.IsNullOrWhiteSpace(link)) { string filename = FileManager.GetFileName(link); // Получаем имя файла из ссылки string fullpath = FileManager.CombinePath(GlobalPath.CurrDir, filename); // Соединяем путь и имя файла if (!FileManager.ExistsFile(fullpath)) { try { var url = new Uri(link, UriKind.Absolute); using var client = new WebClient(); if (!client.IsBusy) { // Установка сертификата для успешной загрузки файл(а)ов ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12; client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 OPR/49.0.2725.64"); client.Proxy = null; try { await client?.DownloadFileTaskAsync(url, fullpath); var file = new FileInfo(fullpath); if (file.Length > 0) { message.Location = new Point(505, 371); ControlActive.CheckMessage(message, "Файл загружен успешно!", Color.FromKnownColor(KnownColor.MenuHighlight), 4000); } else { message.Location = new Point(505, 371); ControlActive.CheckMessage(message, "Файл повреждён, имеет 0 байтов!", Color.FromKnownColor(KnownColor.MenuHighlight), 4000); } } catch (WebException) { FileManager.DeleteFile(fullpath); message.Location = new Point(505, 371); ControlActive.CheckMessage(message, "Ошибка загрузки файла!", Color.FromKnownColor(KnownColor.MenuHighlight), 4000); } } } catch (Exception ex) { throw new Exception("WebClient error: ", ex); } } else { message.Location = new Point(505, 371); ControlActive.CheckMessage(message, "Файл уже существует!", Color.FromKnownColor(KnownColor.MenuHighlight), 4000); } } }
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); }); }
public static async Task DownloadFileTaskAsync(this WebClient webClient, string address, string fileName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (cancellationToken.Register(webClient.CancelAsync)) await webClient.DownloadFileTaskAsync(address, fileName); }
public async Task <string> GenerateConfigXml() { var currentDirectory = Directory.GetCurrentDirectory() + @"\Scripts"; if (!System.IO.File.Exists(currentDirectory + @"\Generate-ODTConfigurationXML.ps1")) { currentDirectory = Directory.GetCurrentDirectory() + @"\Project\Scripts"; } var xmlFilePath = Environment.ExpandEnvironmentVariables(@"%temp%\localConfig.xml"); if (System.IO.File.Exists(xmlFilePath)) { System.IO.File.Delete(xmlFilePath); } var scriptPath = currentDirectory + @"\Generate-ODTConfigurationXML.ps1"; var scriptPathTmp = currentDirectory + @"\Tmp-Generate-ODTConfigurationXML.ps1"; if (!System.IO.File.Exists(scriptPathTmp)) { System.IO.File.Copy(scriptPath, scriptPathTmp, true); } var scriptUrl = AppSettings.GenerateScriptUrl; try { await Retry.BlockAsync(5, 1, async() => { using (var webClient = new WebClient()) { await webClient.DownloadFileTaskAsync(new Uri(scriptUrl), scriptPath); } }); } catch (Exception ex) { } var n = 1; await Retry.BlockAsync(2, 1, async() => { var arguments = @"/c Powershell -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle " + @"Hidden -File .\RunGenerateXML.ps1"; if (n == 2) { System.IO.File.Copy(scriptPathTmp, scriptPath, true); } var p = new Process { StartInfo = new ProcessStartInfo() { FileName = "cmd", Arguments = arguments, CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = currentDirectory, RedirectStandardOutput = true, RedirectStandardError = true }, }; p.Start(); p.WaitForExit(); var error = await p.StandardError.ReadToEndAsync(); if (!string.IsNullOrEmpty(error)) { throw (new Exception(error)); } n++; }); await Task.Delay(100); var configXml = ""; if (System.IO.File.Exists(xmlFilePath)) { configXml = System.IO.File.ReadAllText(xmlFilePath); } try { var installOffice = new InstallOffice(); var updateUrl = installOffice.GetBaseCdnUrl(); if (!string.IsNullOrEmpty(updateUrl)) { var pd = new ProPlusDownloader(); var channelName = await pd.GetChannelNameFromUrlAsync(updateUrl, OfficeEdition.Office32Bit); if (!string.IsNullOrEmpty(configXml) && !string.IsNullOrEmpty(channelName)) { configXml = installOffice.SetUpdateChannel(configXml, channelName); } } } catch { } return(configXml); }
private async void startDownloadButton_Click(object sender, EventArgs e) { SavePrefs(); startDownloadButton.Enabled = false; cancelDownload = false; if (!Directory.Exists(downloadDestBox.Text)) { MessageBox.Show("The download destination does not exist!", "Problem!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string tags = searchTagsBox.Text.Trim(); string[] tagsArray = string.IsNullOrEmpty(tags) ? new string[0] : tags.Split(' '); if (tagsArray.Length > 4) { MessageBox.Show("You can only search with a maximum of 4 tags!", "Ops!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } try { using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); StringBuilder linkBuilder = new StringBuilder(); linkBuilder.Append("https://e621.net/post/index.xml?tags=rating%3Ae%20"); if (!animatedCheckBox.Checked) linkBuilder.Append("type%3Apng%20"); else linkBuilder.Append("type%3Agif%20"); tags = tags.Replace(" ", "%20"); linkBuilder.Append(tags).Append($"%20order:random&limit={downloadAmountBar.Value}"); //string json = await GetJson(linkBuilder.ToString()); //JArray array = JArray.Parse(json); Clipboard.SetText(linkBuilder.ToString()); var data = await http.GetStreamAsync(linkBuilder.ToString()); var doc = XDocument.Load(data); int amount = doc.Descendants("posts").Nodes().ToArray().Length; //MessageBox.Show(doc.Descendants("posts").ElementAt(0).Descendants("file_url").FirstOrDefault().Value.ToString()); if (amount > 0) { using (WebClient client = new WebClient()) { downloading = true; client.DownloadProgressChanged += Client_DownloadProgressChanged; cancelDownloadButton.Enabled = true; //await client.DownloadFileTaskAsync(array[0]["file_url"].ToString(), downloadDestBox.Text + "\\" + array[0]["id"].ToString() + "." + array[0]["file_ext"].ToString()); //for (int i = 0; i < amount; i++) //{ // downloadingLabel.Text = "Downloading " + (i + 1).ToString() + "/" + amount.ToString(); // string url = doc.Descendants("posts").ElementAt(i).Descendants("file_url").FirstOrDefault().Value.ToString(); // string downloadDest = downloadDestBox.Text + "\\" + doc.Descendants("posts").ElementAt(i).Descendants("id").FirstOrDefault().Value.ToString() + "." + doc.Descendants("posts").ElementAt(i).Descendants("file_ext").FirstOrDefault().Value.ToString(); // //await client.DownloadFileTaskAsync(array[i]["file_url"].ToString(), downloadDestBox.Text + "\\" + array[i]["id"].ToString() + "." + array[i]["file_ext"].ToString()); // await client.DownloadFileTaskAsync(url, downloadDest); //} //MessageBox.Show(doc.Descendants("posts").ToArray().Length.ToString()); int dlIndex = 0; foreach (XElement element in doc.Descendants("posts").Nodes()) { if (cancelDownload) { client.DownloadProgressChanged -= Client_DownloadProgressChanged; downloading = false; startDownloadButton.Enabled = true; downloadProgressBar.Value = 0; downloadingLabel.Text = NOT_DOWNLOADING_TEXT; return; } //MessageBox.Show(element.Descendants("id").FirstOrDefault().Value.ToString()); downloadingLabel.Text = "Downloading " + (dlIndex + 1).ToString() + "/" + amount.ToString(); string url = element.Descendants("file_url").FirstOrDefault().Value.ToString(); string downloadDest = downloadDestBox.Text + "\\" + element.Descendants("id").FirstOrDefault().Value.ToString() + "." + element.Descendants("file_ext").FirstOrDefault().Value.ToString(); await client.DownloadFileTaskAsync(url, downloadDest); dlIndex++; } client.DownloadProgressChanged -= Client_DownloadProgressChanged; downloadingLabel.Text = NOT_DOWNLOADING_TEXT; MessageBox.Show("Downloads done", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); startDownloadButton.Enabled = true; cancelDownloadButton.Enabled = false; downloading = false; downloadProgressBar.Value = 0; } } else { MessageBox.Show("Couldn't find any results with those search tags.", "Ops!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); startDownloadButton.Enabled = true; downloading = false; return; } } } catch (Exception ex) { MessageBox.Show("Something went wrong.\n\n" + ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); startDownloadButton.Enabled = true; downloading = false; } }
public async Task <bool> Update() { try { using (WebClient webClient = new WebClient()) { string remoteBuild = await GetRemoteBuild(); string html = await webClient.DownloadStringTaskAsync("https://www.minecraft.net/en-us/download/server/bedrock/"); Regex regex = new Regex(@"https:\/\/minecraft\.azureedge\.net\/bin-win\/(bedrock-server-(.*?)\.zip)"); var matches = regex.Matches(html); if (matches.Count <= 0) { return(false); } string downloadUrl = matches[0].Value; //https://minecraft.azureedge.net/bin-win/bedrock-server-1.14.21.0.zip string fileName = matches[0].Groups[1].Value; //bedrock-server-1.14.21.0.zip string version = matches[0].Groups[2].Value; //1.14.21.0 string tempPath = Functions.ServerPath.GetServerFiles(_serverData.ServerID, "__temp"); //Delete old __temp folder if (Directory.Exists(tempPath)) { await Task.Run(() => Directory.Delete(tempPath, true)); } Directory.CreateDirectory(tempPath); //Download zip and extract then delete zip - install to __temp folder string zipPath = Path.Combine(tempPath, fileName); await webClient.DownloadFileTaskAsync(downloadUrl, zipPath); await Task.Run(() => ZipFile.ExtractToDirectory(zipPath, tempPath)); await Task.Run(() => File.Delete(zipPath)); string serverFilesPath = Functions.ServerPath.GetServerFiles(_serverData.ServerID); //Delete old folder and files await Task.Run(() => { Directory.Delete(Path.Combine(serverFilesPath, "behavior_packs"), true); Directory.Delete(Path.Combine(serverFilesPath, "definitions"), true); Directory.Delete(Path.Combine(serverFilesPath, "resource_packs"), true); Directory.Delete(Path.Combine(serverFilesPath, "structures"), true); File.Delete(Path.Combine(serverFilesPath, "bedrock_server.exe")); File.Delete(Path.Combine(serverFilesPath, "bedrock_server.pdb")); File.Delete(Path.Combine(serverFilesPath, "release-notes.txt")); }); //Move folder and files await Task.Run(() => { Directory.Move(Path.Combine(serverFilesPath, "__temp", "behavior_packs"), Path.Combine(serverFilesPath, "behavior_packs")); Directory.Move(Path.Combine(serverFilesPath, "__temp", "definitions"), Path.Combine(serverFilesPath, "definitions")); Directory.Move(Path.Combine(serverFilesPath, "__temp", "resource_packs"), Path.Combine(serverFilesPath, "resource_packs")); Directory.Move(Path.Combine(serverFilesPath, "__temp", "structures"), Path.Combine(serverFilesPath, "structures")); File.Move(Path.Combine(serverFilesPath, "__temp", "bedrock_server.exe"), Path.Combine(serverFilesPath, "bedrock_server.exe")); File.Move(Path.Combine(serverFilesPath, "__temp", "bedrock_server.pdb"), Path.Combine(serverFilesPath, "bedrock_server.pdb")); File.Move(Path.Combine(serverFilesPath, "__temp", "release-notes.txt"), Path.Combine(serverFilesPath, "release-notes.txt")); }); //Delete __temp folder await Task.Run(() => Directory.Delete(tempPath, true)); //Create MCBE-version.txt and write the version File.WriteAllText(Functions.ServerPath.GetServerFiles(_serverData.ServerID, "MCBE-version.txt"), version); } return(true); } catch (System.Exception e) { Error = e.ToString(); return(false); } }
private async void RelhaxWindow_Loaded(object sender, RoutedEventArgs e) { //init timer timer = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Background, Timer_Elapsed, this.Dispatcher) { IsEnabled = false }; //set the open folder and file button //if uploading, the buttons are invalid, don't show then //if downloading, the buttons are valid to show, but not enabled until the download is complete switch (Upload) { case true: OpenFodlerButton.Visibility = Visibility.Hidden; OpenFileButton.Visibility = Visibility.Hidden; break; case false: OpenFodlerButton.Visibility = Visibility.Visible; OpenFileButton.Visibility = Visibility.Visible; OpenFodlerButton.IsEnabled = false; OpenFileButton.IsEnabled = false; break; } //set header if (!Upload) { //download ProgressBody.Text = string.Format("Downloading {0} from FTP folder {1}", Path.GetFileName(ZipFilePathDisk), Settings.WoTModpackOnlineFolderVersion); } else if (PackageToUpdate == null) { //upload to medias ProgressBody.Text = string.Format("Uploading {0} to FTP folder Medias/...", ZipFileName); } else { //upload to bigmods ProgressBody.Text = string.Format("Uploading {0} to FTP folder {1}", Path.GetFileName(ZipFilePathDisk), Settings.WoTModpackOnlineFolderVersion); } //set body initial text ProgressHeader.Text = string.Format("{0} 0 kb of 0 kb", Upload ? "Uploaded" : "Downloaded"); CompleteFTPPath = string.Format("{0}{1}", ZipFilePathOnline, ZipFileName); using (client = new WebClient() { Credentials = Credential }) { switch (Upload) { case true: //before uploading, make sure it doesn't exist first ProgressHeader.Text = "Checking if file exists on server..."; Logging.Editor("Checking if {0} already exists on the server in folder {1}", LogLevel.Info, ZipFileName, Settings.WoTModpackOnlineFolderVersion); string[] listOfFilesOnServer = await Utils.FTPListFilesFoldersAsync(ZipFilePathOnline, Credential); if (listOfFilesOnServer.Contains(ZipFileName) && MessageBox.Show("File already exists, overwrite?", "", MessageBoxButton.YesNo) != MessageBoxResult.Yes) { Logging.Editor("DOES exist and user said don't overwrite, aborting"); ProgressHeader.Text = "Canceled"; return; } client.UploadProgressChanged += Client_UploadProgressChanged; //write handler for if upload or download was canceled client.UploadFileCompleted += Client_DownloadUploadFileCompleted; Logging.Editor("STARTING FTP UPLOAD"); try { await client.UploadFileTaskAsync(CompleteFTPPath, ZipFilePathDisk); } catch (Exception ex) { Logging.Editor("FTP UPLOAD Failed"); Logging.Editor(ex.ToString()); } Logging.Editor("FTP UPLOAD COMPLETE"); if (PackageToUpdate == null) { Logging.Editor("FTP media upload complete"); } else { Logging.Editor("FTP zip package upload complete, changing zipFile entry for package {0} from", LogLevel.Info, PackageToUpdate.PackageName); Logging.Editor("\"{0}\"{1}to{2}", LogLevel.Info, PackageToUpdate.ZipFile, Environment.NewLine, Environment.NewLine); Logging.Editor("\"{0}\"", LogLevel.Info, ZipFileName); PackageToUpdate.ZipFile = ZipFileName; } if (OnEditorUploadDownloadClosed != null) { OnEditorUploadDownloadClosed(this, new EditorUploadDownloadEventArgs() { Package = PackageToUpdate, UploadedFilename = ZipFileName, UploadedFilepathOnline = ZipFilePathOnline }); } CancelButton.IsEnabled = false; break; case false: client.DownloadProgressChanged += Client_DownloadProgressChanged; //write handler for if upload or download was canceled client.DownloadFileCompleted += Client_DownloadUploadFileCompleted; Logging.Editor("STARTING FTP DOWNLOAD"); try { FTPDownloadFilesize = await Utils.FTPGetFilesizeAsync(CompleteFTPPath, Credential); await client.DownloadFileTaskAsync(CompleteFTPPath, ZipFilePathDisk); Logging.Editor("FTP DOWNLOAD COMPLETE ({0})", LogLevel.Info, ZipFileName); } catch (Exception ex) { Logging.Editor("FTP download failed"); Logging.Editor(ex.ToString()); //MessageBox.Show(ex.ToString()); } finally { CancelButton.IsEnabled = false; OpenFileButton.IsEnabled = true; OpenFodlerButton.IsEnabled = true; } break; } } StartTimerForClose(); }
private async Task DoUpdate() { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;//3072 ChangeProgress(999); ChangeText(I18N.GetString("Get latest version...")); var newVersion = await GetVersion(); string proxy = null; if (string.IsNullOrEmpty(newVersion)) { proxy = Microsoft.VisualBasic.Interaction.InputBox(I18N.GetString("We need a proxy to download v2ray core"), "Yo", "http://127.0.0.1:1080"); if (Uri.IsWellFormedUriString(proxy, UriKind.Absolute)) { newVersion = await GetVersion(proxy); } } if (string.IsNullOrEmpty(newVersion)) { System.Diagnostics.Process.Start(V2RAY_URL); GoodBye(DialogResult.Abort); return; } ChangeText(I18N.GetString("Upgrade {0} to {1} ...", V2Ray.Version?.ToString() ?? "0.0.0", newVersion)); WebClient webClient = new WebClient(); if (!string.IsNullOrEmpty(proxy) && Uri.IsWellFormedUriString(proxy, UriKind.Absolute)) { webClient.Proxy = new WebProxy(new Uri(proxy)); } webClient.DownloadProgressChanged += (s, e) => { ChangeProgress(e.ProgressPercentage); //ChangeText(newVersion + I18N.GetString("Downloading...") + $" {e.ProgressPercentage}%"); }; var fileName = Utils.GetTempPath(Guid.NewGuid().ToString("N")); var downloadURL = $"https://github.com/v2ray/v2ray-core/releases/download/v{newVersion}/v2ray-windows-{(Environment.Is64BitOperatingSystem ? "64" : "32")}.zip"; ChangeText(I18N.GetString("Downloading file from {0}, You can download it manually and extract to same folder.", downloadURL)); await webClient.DownloadFileTaskAsync(downloadURL, fileName); ChangeProgress(100); ChangeText(newVersion + I18N.GetString("Extracting...")); try { using (ZipArchive archive = ZipFile.OpenRead(fileName)) { var additional = Path.Combine(Global.AppPath, "Additional"); if (!Directory.Exists(additional)) { Directory.CreateDirectory(additional); } V2RayRunner.KillAll(); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.Length == 0) { continue; } if (entry.FullName.Contains('/')) { continue;//directory, useless } if (entry.FullName == "v2ray.exe" || entry.FullName == "v2ctl.exe") { entry.ExtractToFile(Path.Combine(Global.AppPath, entry.FullName), true); } else { entry.ExtractToFile(Path.Combine(additional, entry.FullName), true); } } } } catch (Exception e) { Logging.LogUsefulException(e); GoodBye(DialogResult.Abort); return; } finally { File.Delete(fileName); } GoodBye(DialogResult.OK); }
internal static async Task <bool> UpdateDB(Label status) { await Task.Delay(100); try { if (status == null) { status = new Label(); } using (WebClient wc = new WebClient()) { int now = 0; int total = dbFiles.Length; wc.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { status.Text = $"DB Update Process - Update DB...{e.ProgressPercentage}% ({now}/{total})"; }; wc.DownloadFileCompleted += async(object sender, AsyncCompletedEventArgs e) => { await Task.Delay(500); status.Text = $"DB Update Process - Finalizing Update DB"; }; for (now = 0; now < dbFiles.Length; ++now) { await wc.DownloadFileTaskAsync(Path.Combine(server, "Data", "DB", dbFiles[now]), Path.Combine(tempPath, dbFiles[now])); } await wc.DownloadFileTaskAsync(Path.Combine(server, "DBVer.txt"), Path.Combine(tempPath, "DBVer.txt")); await Task.Delay(100); } for (int i = 0; i < dbFiles.Length; ++i) { File.Copy(Path.Combine(tempPath, dbFiles[i]), Path.Combine(dbPath, dbFiles[i]), true); await Task.Delay(100); } await Task.Delay(500); string oldVersion = Path.Combine(systemPath, "DBVer.txt"); string newVersion = Path.Combine(tempPath, "DBVer.txt"); File.Copy(newVersion, oldVersion, true); using (StreamReader sr = new StreamReader(new FileStream(oldVersion, FileMode.Open, FileAccess.Read))) int.TryParse(sr.ReadToEnd(), out dbVer); await Task.Delay(500); } catch (Exception ex) { LogError(ex); for (int i = 3; i >= 0; --i) { status.Text = $"Update DB Fail!...Skip after {i}s"; await Task.Delay(1000); } return(false); } return(true); }
async Task <bool> CompareAndDownloadFileList( List <CoreFile> files, string filePath, string[] excludedFiles = null, string[] exludedExtensions = null, string[] excludedFolders = null) { var c = 0; var tmpPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "inuse"); var tmpPathOld = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tmp"); if (!Directory.Exists(tmpPathOld)) { Directory.CreateDirectory(tmpPathOld); } if (!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } ReportProgress("Deleting old files..."); var list = await DeleteFiles(files, filePath, excludedFiles, exludedExtensions, excludedFolders); using (var sw = new StreamWriter(Common.Path() + "deleted-files.txt", true)) { sw.WriteLine("--- " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ---"); await sw.WriteLineAsync(string.Join(Environment.NewLine, list)); } foreach (var file in files) { c++; ReportFunctionProgress((int)((double)c * 100.0 / (double)files.Count)); ReportProgress(String.Format("Checking {0}", file.FileName)); var download = !await FileComparisonHelper.AreVersionsEqual(file.Version, file.LocalPath) || !await FileComparisonHelper.AreMd5Equal(file.Hash, file.LocalPath); if (!download) { continue; } var dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var target = file.LocalPath; var inuse = false; if (File.Exists(filePath + file.FileName)) { try { Console.WriteLine(@"Deleting file {0}", file.FileName); File.Delete(filePath + file.FileName); } catch { inuse = true; RequiresUpdaterRestart = true; target = Path.Combine(tmpPath, file.FileName); if (!Directory.Exists(Path.GetDirectoryName(target))) { Directory.CreateDirectory(Path.GetDirectoryName(target)); } } } BeginFileDownload(); ReportProgress(String.Format("Downloading {0}", file.FileName)); if (!Directory.Exists(Path.GetDirectoryName(target))) { Directory.CreateDirectory(Path.GetDirectoryName(target)); } await _webClient.DownloadFileTaskAsync( new Uri(_keys["hospitalserver"].ToString() + "/" + file.DownloadPath), target); await Task.Delay(200); if (inuse) { try { File.Copy(target, Path.Combine(tmpPathOld, Path.GetFileName(file.FileName))); } catch { } } EndFileDownload(); } return(true); }
private static async Task DownloadFileAsync(DirectoryInfo targetDir, WebClient client, string startDocFileName, Uri address) { await client.DownloadFileTaskAsync(address, Path.Combine(targetDir.FullName, startDocFileName)); }
public async Task <RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch) { var releaseContent = File.ReadAllText(Path.Combine(rootAppDirectory, "packages", "RELEASES"), Encoding.UTF8); var releases = ReleaseEntry.ParseReleaseFile(releaseContent); var latest = releases.OrderByDescending(x => x.Version).First(); // Download the icon and PNG => ICO it. If this doesn't work, who cares var pkgPath = Path.Combine(rootAppDirectory, "packages", latest.Filename); var zp = new ZipPackage(pkgPath); var targetPng = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".png"); var targetIco = Path.Combine(rootAppDirectory, "app.ico"); var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default) .CreateSubKey(uninstallRegSubKey + "\\" + applicationName, RegistryKeyPermissionCheck.ReadWriteSubTree); try { var wc = new WebClient(); await wc.DownloadFileTaskAsync(zp.IconUrl, targetPng); using (var fs = new FileStream(targetIco, FileMode.Create)) { if (zp.IconUrl.AbsolutePath.EndsWith("ico")) { var bytes = File.ReadAllBytes(targetPng); fs.Write(bytes, 0, bytes.Length); } else { using (var bmp = (Bitmap)Image.FromFile(targetPng)) using (var ico = Icon.FromHandle(bmp.GetHicon())) { ico.Save(fs); } } key.SetValue("DisplayIcon", targetIco, RegistryValueKind.String); } } catch (Exception ex) { this.Log().InfoException("Couldn't write uninstall icon, don't care", ex); } finally { File.Delete(targetPng); } var stringsToWrite = new[] { new { Key = "DisplayName", Value = zp.Description ?? zp.Summary }, new { Key = "DisplayVersion", Value = zp.Version.ToString() }, new { Key = "InstallDate", Value = DateTime.Now.ToString("yyyymmdd") }, new { Key = "InstallLocation", Value = rootAppDirectory }, new { Key = "Publisher", Value = zp.Authors.First() }, new { Key = "QuietUninstallString", Value = String.Format("{0} {1}", uninstallCmd, quietSwitch) }, new { Key = "UninstallString", Value = uninstallCmd }, }; var dwordsToWrite = new[] { new { Key = "EstimatedSize", Value = (int)((new FileInfo(pkgPath)).Length / 1024) }, new { Key = "NoModify", Value = 1 }, new { Key = "NoRepair", Value = 1 }, new { Key = "Language", Value = 0x0409 }, }; foreach (var kvp in stringsToWrite) { key.SetValue(kvp.Key, kvp.Value, RegistryValueKind.String); } foreach (var kvp in dwordsToWrite) { key.SetValue(kvp.Key, kvp.Value, RegistryValueKind.DWord); } return(key); }
private async Task DownloadRemotelyAgent(string serverUrl) { var targetFile = Path.Combine(Path.GetTempPath(), $"Remotely-Agent.zip"); if (CommandLineParser.CommandLineArgs.TryGetValue("path", out var result) && FileIO.Exists(result)) { targetFile = result; } else { ProgressMessageChanged.Invoke(this, "Downloading Remotely agent."); using (var client = new WebClient()) { client.DownloadProgressChanged += (sender, args) => { ProgressValueChanged?.Invoke(this, args.ProgressPercentage); }; await client.DownloadFileTaskAsync($"{serverUrl}/Downloads/Remotely-Win10-{Platform}.zip", targetFile); } } ProgressMessageChanged.Invoke(this, "Extracting Remotely files."); ProgressValueChanged?.Invoke(this, 0); var tempDir = Path.Combine(Path.GetTempPath(), "RemotelyUpdate"); if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Directory.CreateDirectory(InstallPath); while (!Directory.Exists(InstallPath)) { await Task.Delay(10); } var wr = WebRequest.CreateHttp($"{serverUrl}/Downloads/Remotely-Win10-{Platform}.zip"); wr.Method = "Head"; using (var response = (HttpWebResponse)await wr.GetResponseAsync()) { FileIO.WriteAllText(Path.Combine(InstallPath, "etag.txt"), response.Headers["ETag"]); } ZipFile.ExtractToDirectory(targetFile, tempDir); var fileSystemEntries = Directory.GetFileSystemEntries(tempDir); for (var i = 0; i < fileSystemEntries.Length; i++) { try { ProgressValueChanged?.Invoke(this, (int)((double)i / (double)fileSystemEntries.Length * 100d)); var entry = fileSystemEntries[i]; if (FileIO.Exists(entry)) { FileIO.Copy(entry, Path.Combine(InstallPath, Path.GetFileName(entry)), true); } else if (Directory.Exists(entry)) { FileSystem.CopyDirectory(entry, Path.Combine(InstallPath, new DirectoryInfo(entry).Name), true); } await Task.Delay(1); } catch (Exception ex) { Logger.Write(ex); } } ProgressValueChanged?.Invoke(this, 0); }
public async Task DownloadActionIcons( string saveDirectory, IEnumerable <ActionModel> actions, ProgressDownloadCallbak callback = null) { // ファイル名に使えない文字を取得しておく var invalidChars = Path.GetInvalidFileNameChars(); var iconBaseDirectory = Path.Combine( saveDirectory, "Action icons"); var iconBaseDirectoryBack = iconBaseDirectory + ".back"; if (Directory.Exists(iconBaseDirectory)) { if (Directory.Exists(iconBaseDirectoryBack)) { Directory.Delete(iconBaseDirectoryBack, true); } Directory.Move(iconBaseDirectory, iconBaseDirectoryBack); } var i = 1; var jobIDs = Jobs.PopularJobIDs .Select(x => new { No = i++, ID = x, Name = Jobs.Find(x)?.NameEN }); using (var wc = new WebClient()) { foreach (var jobID in jobIDs) { var actionsByJob = from x in actions where x.ContainsJob(jobID.ID) group x by x.Name; var dirName = $"{jobID.No:00}_{jobID.Name}"; var dir = Path.Combine(iconBaseDirectory, dirName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var current = 1; foreach (var group in actionsByJob) { var action = group.First(); var fileName = $"{action.ID:0000}_{action.Name}.png"; // ファイル名に使えない文字を除去する fileName = string.Concat(fileName.Where(c => !invalidChars.Contains(c))); var file = Path.Combine(dir, fileName); if (File.Exists(file)) { File.Delete(file); } var uri = BaseAddress.ToString() + "/" + action.Icon; await wc.DownloadFileTaskAsync(uri, file); if (callback != null) { callback.Invoke(new DownloadProgressEventArgs() { Current = current, Max = actionsByJob.Count(), CurrentObject = Path.Combine(dirName, fileName), }); } current++; await Task.Delay(1); } } } if (Directory.Exists(iconBaseDirectoryBack)) { Directory.Delete(iconBaseDirectoryBack, true); } }
internal static async Task <bool> UpdateProgram(Label status = null) { if (status == null) { status = new Label(); } using (WebClient wc = new WebClient()) { status.Text = "App Update Process - Check Server Network"; await CheckServerNetwork(); if (!isServerDown) { try { status.Text = "App Update Process - Download Updater"; wc.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { status.Text = $"App Update Process - Download Updater - {e.ProgressPercentage}%"; }; await wc.DownloadFileTaskAsync(Path.Combine(server, "GFDW Updater.exe"), Path.Combine(currentPath, "Updater.exe")); await Task.Delay(500); status.Text = "App Update Process - Run Updater"; await Task.Delay(500); if (File.Exists("Updater.exe")) { Process.Start("Updater.exe", "Client").WaitForExit(); } } catch (Exception ex) { LogError(ex); for (int i = 3; i >= 0; --i) { status.Text = $"Update Program Fail!...Skip after {i}s"; await Task.Delay(1000); } return(false); } } else { for (int i = 3; i >= 0; --i) { status.Text = $"Server is not working!...Skip after {i}s"; await Task.Delay(1000); } return(false); } } return(true); }
public async Task BuildUpdate(UpdateGenerationStatus status) { var request = status.Request; var api = Api.INSTANCE; try { status.UpdateStatus(UpdateGenerationStatusCode.PREPARING); using (var da = api.DAFactory.Get()) { var baseUpdateKey = "updates/"; var branch = da.Updates.GetBranch(status.Request.branchID); //reserve update id. may cause race condition, but only one person can update anyways. if (request.minorVersion) { ++branch.minor_version_number; } else { ++branch.last_version_number; branch.minor_version_number = 0; } var updateID = branch.last_version_number; var minorChar = (branch.minor_version_number == 0) ? "" : ((char)('a' + (branch.minor_version_number - 1))).ToString(); var versionName = branch.version_format.Replace("#", updateID.ToString()).Replace("@", minorChar); var versionText = versionName; var result = new DbUpdate() { addon_id = branch.addon_id, branch_id = branch.branch_id, date = DateTime.UtcNow, version_name = versionName, deploy_after = Epoch.ToDate(status.Request.scheduledEpoch) }; versionName = versionName.Replace('/', '-'); var client = new WebClient(); //fetch artifacts //http://servo.freeso.org/guestAuth/repository/download/FreeSO_TsoClient/.lastSuccessful/client-<>.zip //http://servo.freeso.org/guestAuth/repository/download/FreeSO_TsoClient/.lastSuccessful/server-<>.zip int updateWorkID = status.TaskID; var updateDir = "updateTemp/" + updateWorkID + "/"; try { Directory.Delete(updateDir, true); } catch (Exception) { } Directory.CreateDirectory(updateDir); Directory.CreateDirectory(updateDir + "client/"); Directory.CreateDirectory(updateDir + "server/"); string clientArti = null; string serverArti = null; if (branch.base_build_url != null) { status.UpdateStatus(UpdateGenerationStatusCode.DOWNLOADING_CLIENT); await client.DownloadFileTaskAsync(new Uri(branch.base_build_url), updateDir + "client.zip"); clientArti = updateDir + "client.zip"; } if (branch.base_server_build_url != null) { status.UpdateStatus(UpdateGenerationStatusCode.DOWNLOADING_SERVER); await client.DownloadFileTaskAsync(new Uri(branch.base_server_build_url), updateDir + "server.zip"); serverArti = updateDir + "server.zip"; } string clientAddon = null; string serverAddon = null; if (branch.addon_id != null) { var addon = da.Updates.GetAddon(branch.addon_id.Value); if (addon.addon_zip_url != null) { status.UpdateStatus(UpdateGenerationStatusCode.DOWNLOADING_CLIENT_ADDON); await client.DownloadFileTaskAsync(new Uri(addon.addon_zip_url), updateDir + "clientAddon.zip"); clientAddon = updateDir + "clientAddon.zip"; } if (addon.server_zip_url != null) { status.UpdateStatus(UpdateGenerationStatusCode.DOWNLOADING_SERVER_ADDON); await client.DownloadFileTaskAsync(new Uri(addon.addon_zip_url), updateDir + "serverAddon.zip"); serverAddon = updateDir + "serverAddon.zip"; } else { serverAddon = clientAddon; } } //last client update. var previousUpdate = (branch.current_dist_id == null) ? null : da.Updates.GetUpdate(branch.current_dist_id.Value); //all files downloaded. build the folders. //extract the artifact and then our artifact over it. if (clientArti != null) { status.UpdateStatus(UpdateGenerationStatusCode.EXTRACTING_CLIENT); var clientZip = ZipFile.Open(clientArti, ZipArchiveMode.Read); clientZip.ExtractToDirectory(updateDir + "client/", true); clientZip.Dispose(); File.Delete(clientArti); if (clientAddon != null) { status.UpdateStatus(UpdateGenerationStatusCode.EXTRACTING_CLIENT_ADDON); var addonZip = ZipFile.Open(clientAddon, ZipArchiveMode.Read); addonZip.ExtractToDirectory(updateDir + "client/", true); addonZip.Dispose(); if (clientAddon != serverAddon) { File.Delete(clientAddon); } } //emit version number await System.IO.File.WriteAllTextAsync(updateDir + "client/version.txt", versionText); if (request.catalog != null) { await System.IO.File.WriteAllTextAsync(updateDir + "client/Content/Objects/catalog_downloads.xml", request.catalog); } string diffZip = null; FSOUpdateManifest manifest = null; status.UpdateStatus(UpdateGenerationStatusCode.BUILDING_DIFF); if (previousUpdate != null || request.disableIncremental) { result.last_update_id = previousUpdate.update_id; //calculate difference, generate an incremental update manifest + zip var prevFile = updateDir + "prev.zip"; await client.DownloadFileTaskAsync(new Uri(previousUpdate.full_zip), updateDir + "prev.zip"); var prevZip = ZipFile.Open(prevFile, ZipArchiveMode.Read); prevZip.ExtractToDirectory(updateDir + "prev/", true); prevZip.Dispose(); File.Delete(updateDir + "prev.zip"); var diffs = DiffGenerator.GetDiffs(Path.GetFullPath(updateDir + "prev/"), Path.GetFullPath(updateDir + "client/")); status.UpdateStatus(UpdateGenerationStatusCode.BUILDING_INCREMENTAL_UPDATE); var toZip = diffs.Where(x => x.DiffType == FileDiffType.Add || x.DiffType == FileDiffType.Modify); if (request.contentOnly) { toZip = toZip.Where(x => x.Path.Replace('\\', '/').TrimStart('/').StartsWith("Content")); } if (!request.includeMonogameDelta) { toZip = toZip.Where(x => !x.Path.Replace('\\', '/').TrimStart('/').StartsWith("Monogame")); } //build diff folder Directory.CreateDirectory(updateDir + "diff/"); foreach (var diff in toZip) { Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(updateDir + "diff/", diff.Path))); System.IO.File.Copy(Path.Combine(updateDir + "client/", diff.Path), Path.Combine(updateDir + "diff/", diff.Path)); } diffZip = updateDir + "diffResult.zip"; ClearFolderPermissions(updateDir + "diff/"); ZipFile.CreateFromDirectory(updateDir + "diff/", diffZip, CompressionLevel.Optimal, false); Directory.Delete(updateDir + "diff/", true); manifest = new FSOUpdateManifest() { Diffs = diffs }; Directory.Delete(updateDir + "prev/", true); } else { if (request.contentOnly) { throw new Exception("Invalid request - you cannot make a content only update with no delta."); } //full update only. generate simple manifest that contains all files (added) manifest = new FSOUpdateManifest() { Diffs = new List <FileDiff>() }; } //pack full client if (!request.contentOnly) { status.UpdateStatus(UpdateGenerationStatusCode.BUILDING_CLIENT); var finalClientZip = updateDir + "clientResult.zip"; ClearFolderPermissions(updateDir + "client/"); ZipFile.CreateFromDirectory(updateDir + "client/", finalClientZip, CompressionLevel.Optimal, false); Directory.Delete(updateDir + "client/", true); status.UpdateStatus(UpdateGenerationStatusCode.PUBLISHING_CLIENT); result.full_zip = await Api.INSTANCE.UpdateUploaderClient.UploadFile($"{baseUpdateKey}client-{versionName}.zip", finalClientZip, versionName); } status.UpdateStatus(UpdateGenerationStatusCode.PUBLISHING_CLIENT); if (diffZip != null) { result.incremental_zip = await Api.INSTANCE.UpdateUploaderClient.UploadFile($"{baseUpdateKey}incremental-{versionName}.zip", diffZip, versionName); } await System.IO.File.WriteAllTextAsync(updateDir + "manifest.json", Newtonsoft.Json.JsonConvert.SerializeObject(manifest)); result.manifest_url = await Api.INSTANCE.UpdateUploaderClient.UploadFile($"{baseUpdateKey}{versionName}.json", updateDir + "manifest.json", versionName); } if (serverArti != null && !request.contentOnly) { status.UpdateStatus(UpdateGenerationStatusCode.EXTRACTING_SERVER); var serverZip = ZipFile.Open(serverArti, ZipArchiveMode.Read); serverZip.ExtractToDirectory(updateDir + "server/", true); serverZip.Dispose(); File.Delete(serverArti); if (serverAddon != null) { status.UpdateStatus(UpdateGenerationStatusCode.EXTRACTING_SERVER_ADDON); var addonZip = ZipFile.Open(serverAddon, ZipArchiveMode.Read); addonZip.ExtractToDirectory(updateDir + "server/", true); addonZip.Dispose(); File.Delete(serverAddon); } //emit version number await System.IO.File.WriteAllTextAsync(updateDir + "server/version.txt", versionText); if (request.catalog != null) { await System.IO.File.WriteAllTextAsync(updateDir + "client/Content/Objects/catalog_downloads.xml", request.catalog); } status.UpdateStatus(UpdateGenerationStatusCode.BUILDING_SERVER); var finalServerZip = updateDir + "serverResult.zip"; ClearFolderPermissions(updateDir + "server/"); ZipFile.CreateFromDirectory(updateDir + "server/", finalServerZip, CompressionLevel.Optimal, false); Directory.Delete(updateDir + "server/", true); status.UpdateStatus(UpdateGenerationStatusCode.PUBLISHING_SERVER); result.server_zip = await Api.INSTANCE.UpdateUploader.UploadFile($"{baseUpdateKey}server-{versionName}.zip", finalServerZip, versionName); } else { result.server_zip = result.incremental_zip; //same as client, as server uses same content. } status.UpdateStatus(UpdateGenerationStatusCode.SCHEDULING_UPDATE); var finalID = da.Updates.AddUpdate(result); da.Updates.UpdateBranchLatest(branch.branch_id, branch.last_version_number, branch.minor_version_number); status.SetResult(result); } } catch (Exception e) { status.SetFailure("Update could not be completed." + e.ToString()); } }
private async void RequestCheckUpdateCallback(AsyncTaskResult result) { SetCompleteFlagAfterExecuteCommand(); AIPViewmodel.ButtonCommandOV.IsAppUpdateButtonRunning = false; if (result.MesResult == MessageAsyncTaskResult.Done) { dynamic dataResponse = JsonConvert.DeserializeObject(result.Result.ToString()); try { switch (dataResponse.compareStatus.ToString()) { case "NotCompatible": case "Equal": App.Current.ShowApplicationMessageBox(dataResponse.message.ToString(), HPSolutionCCDevPackage.netFramework.AnubisMessageBoxType.Default, HPSolutionCCDevPackage.netFramework.AnubisMessageImage.Info, OwnerWindow.MainScreen, "Thông báo!"); break; case "Lower": var x = App.Current.ShowApplicationMessageBox("Hiện đã có phiên bản mới, bạn có muốn cập nhật không?", HPSolutionCCDevPackage.netFramework.AnubisMessageBoxType.YesNo, HPSolutionCCDevPackage.netFramework.AnubisMessageImage.Info, OwnerWindow.MainScreen, "Thông báo!"); if (x == HPSolutionCCDevPackage.netFramework.AnubisMessgaeResult.ResultYes) { PopupScreenWindow.MVVM.Views.PopupScreenWindow popupWindow = new PopupScreenWindow.MVVM.Views.PopupScreenWindow(); popupWindow.Height = 155d; popupWindow.Width = 430d; popupWindow.ResizeMode = System.Windows.ResizeMode.NoResize; DownloadProgressControl downloadControl = new DownloadProgressControl(); downloadControl.YesNoButtonGrid.Visibility = System.Windows.Visibility.Collapsed; downloadControl.CancelButton.Visibility = System.Windows.Visibility.Visible; popupWindow.Content = downloadControl; popupWindow.Show(); var path = System.IO.Path.GetTempPath() + dataResponse.fileName.ToString(); var totalBytesRecieve = double.Parse(dataResponse.totalBytes.ToString()); using (downloadFileClient = new WebClient()) { downloadFileClient.DownloadFileCompleted += (sender, args) => { try { downloadControl.TitleText.Text = "Tải về bản cập nhật thành công, bạn có muốn tiến hành cài đặt?"; downloadControl.YesNoButtonGrid.Visibility = System.Windows.Visibility.Visible; downloadControl.CancelButton.Visibility = System.Windows.Visibility.Collapsed; } catch { } finally { } }; downloadFileClient.DownloadProgressChanged += (sender, args) => { try { var percentage = (Math.Truncate(double.Parse(args.BytesReceived.ToString()) / totalBytesRecieve * 100)); downloadControl.ProgressBar.Value = percentage; downloadControl.PercentText.Text = percentage + "%"; } catch { } }; downloadControl.CancelButton.Command = new CommandModel((paramaters) => { downloadFileClient.CancelAsync(); popupWindow.ForceClose(); }); downloadControl.NoButton.Command = new CommandModel((paramaters) => { popupWindow.ForceClose(); }); downloadControl.YesButton.Command = new CommandModel((paramaters) => { popupWindow.ForceClose(); var psi = new ProcessStartInfo() { FileName = path, Verb = "RunAs" }; Process.Start(psi); App.Current.ClearSessionID(); App.Current.Shutdown(); return; }); await downloadFileClient.DownloadFileTaskAsync(new Uri(dataResponse.linkDownload.ToString()), path); } } break; } } catch (Exception e) { Logger.E(e.Message); App.Current.ShowApplicationMessageBox("Lỗi tải về!", HPSolutionCCDevPackage.netFramework.AnubisMessageBoxType.Default, HPSolutionCCDevPackage.netFramework.AnubisMessageImage.Error, OwnerWindow.MainScreen, "Lỗi!"); } } else { App.Current.ShowApplicationMessageBox("Lỗi cập nhật phiên bản, vui lòng liên hệ CSKH để được tư vấn!", HPSolutionCCDevPackage.netFramework.AnubisMessageBoxType.Default, HPSolutionCCDevPackage.netFramework.AnubisMessageImage.Error, OwnerWindow.MainScreen, "Lỗi!"); } }
private static void Update(List <string> mismatchedFiles) { try { System.Threading.ThreadPool.QueueUserWorkItem(async delegate { foreach (var file in mismatchedFiles) { string downloadFile = (file.Replace("_backup", "")).Replace("\\", "/"); string[] s = file.Split('\\'); string fileName = s[(s.Length - 1)]; if (!Directory.Exists(Properties.Settings.Default.launcherpath)) { Directory.CreateDirectory(Properties.Settings.Default.launcherpath); } if (s.Length == 3) { if (!Directory.Exists(Properties.Settings.Default.launcherpath + "\\" + s[1])) { Directory.CreateDirectory(Properties.Settings.Default.launcherpath + "\\" + s[1]); } } if (s.Length == 4) { if (!Directory.Exists(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2])) { Directory.CreateDirectory(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2]); } } if (s.Length == 5) { if (!Directory.Exists(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2] + "\\" + s[3])) { Directory.CreateDirectory(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2] + "\\" + s[3]); } } if (s.Length == 6) { if (!Directory.Exists(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2] + "\\" + s[3] + "\\" + s[4])) { Directory.CreateDirectory(Properties.Settings.Default.launcherpath + "\\" + s[1] + "\\" + s[2] + "\\" + s[3] + "\\" + s[4]); } } using (WebClient downloadClient = new WebClient()) { downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) { }); await downloadClient.DownloadFileTaskAsync(new Uri("http://download.ets2mp.com/files" + downloadFile), Properties.Settings.Default.launcherpath + file); } } }); } catch (Exception a) { string error = a.ToString(); Loghandling.Logerror(error); } }
public static async void CheckVersion() { Console.WriteLine("Checking for updates"); Version currentAppVersion = getRunningVersion(); var request = new RestRequest("/update"); var cTokeS = new CancellationTokenSource(); var response = await Client.ExecuteGetAsync(request, cTokeS.Token); var data = JObject.Parse(response.Content); string newestAppVersion = (string)data["version"]; Version newestAppVersion_ = Version.Parse(newestAppVersion); string patchNotes = (string)data["patch-notes"]; string installer = (string)data["url"]; bool mandatory = (bool)data["mandatory"]; string md5 = (string)data["md5"]; if (currentAppVersion.CompareTo(newestAppVersion_) < 0) { Console.WriteLine("Version is outdated!"); notificationManager.Show(new NotificationContent { Title = "OS Game-Launcher Update", Message = "A new version of the OS Game-Launcher is available!", Type = NotificationType.Information }, expirationTime: TimeSpan.FromSeconds(15)); showMessage("A newer version of OS Game-Launcher is available. Your currently installed version is " + currentAppVersion.ToString() + " and the newest version is " + newestAppVersion + "!\n\nUpdate " + currentAppVersion.ToString() + " => " + newestAppVersion + "\n\nChange log: " + patchNotes + "\n\nNew version is getting Downloaded..."); Console.WriteLine("Installed version outdated. Downloading new version"); string tempFolderPath = Path.GetTempPath(); string installationPath = Path.Combine(tempFolderPath, "osg-updater-" + newestAppVersion.Replace(".", "-") + ".exe"); DriveInfo installDrive = GetDriverFromPrefix(Path.GetPathRoot(new FileInfo(installationPath).FullName)); var freeDiscSpace = installDrive.AvailableFreeSpace; if (await GetHttpStatusCode(installer) && await GetFileSize(new Uri(installer)) < freeDiscSpace) { WebClient webClient = new WebClient(); await webClient.DownloadFileTaskAsync(installer, installationPath); webClient.Dispose(); Console.WriteLine("Updater successfully downloaded! Comparing MD5"); string downloaded_comp_hash = CalculateMD5(installationPath); if (downloaded_comp_hash == (md5).ToLowerInvariant()) { Process p = new Process(); p.StartInfo.FileName = installationPath; p.StartInfo.Verb = "runas"; p.Start(); } else { Console.WriteLine("MD5 not same! DANGER!! Deleting installer"); await Utils.DeleteAsync(new FileInfo(installationPath)); Console.WriteLine("Update cleaned up!"); showMessage("The update installer is not valid! For more infos visit: " + patchNotes); } } else { Console.WriteLine("Installer not available or not enough Disc space"); showMessage("The update installer is not available or you don't have enough disc space! For more infos visit: " + patchNotes); } Application.Current.Shutdown(0); } else if (currentAppVersion.CompareTo(newestAppVersion_) == 0) { Console.WriteLine("Version is up to date!"); } else { Console.WriteLine("Version is not published yet!"); } }
private async Task HandleCommandAsync(SocketMessage s) { if (!(s is SocketUserMessage msg)) { return; } SocketCommandContext context = new SocketCommandContext(_client, msg); int argPos = 0; if (!context.User.IsBot) { // Commands if (msg.HasCharPrefix(prefix, ref argPos)) { var result = await _commands.ExecuteAsync(context, argPos, _services); if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) { await context.Channel.SendMessageAsync($"Error: {result.ErrorReason}"); } } // InterServer Chat else if (Program.interServerChats.ContainsKey(context.Guild.Id) && Program.interServerChats[context.Guild.Id] == context.Channel.Id) { string fileName = ""; EmbedBuilder embed = new EmbedBuilder(); embed.WithAuthor(msg.Author); embed.WithDescription(msg.Content); foreach (Attachment a in msg.Attachments) { if (a.Url.EndsWith(".png") || a.Url.EndsWith(".jpg")) { embed.WithImageUrl(a.Url); } else { WebClient wc = new WebClient(); Uri uri = new Uri(a.Url); string[] extension = a.Url.Split('.', '/'); fileName = $"{extension[extension.Length - 2]}-(1).{extension[extension.Length - 1]}"; await wc.DownloadFileTaskAsync(uri, fileName); } } EmbedBuilder embedGuild = new EmbedBuilder(); embedGuild.WithAuthor(msg.Author); embedGuild.WithDescription(msg.Content); foreach (Attachment a in msg.Attachments) { if (a.Url.EndsWith(".png") || a.Url.EndsWith(".jpg") || a.Url.EndsWith(".jpeg") || a.Url.EndsWith(".gif")) { embed.WithImageUrl(a.Url); } } if (Program.broadcastServerName.Contains(context.Guild.Id)) { EmbedFooterBuilder footer = new EmbedFooterBuilder(); footer.WithIconUrl(context.Guild.IconUrl); footer.WithText($"{context.Guild.Name } [{context.Guild.Id}]"); embedGuild.WithFooter(footer); } List <Task> sendMessage = new List <Task>(); List <Task> sendFile = new List <Task>(); foreach (ulong serverID in Program.interServerChats.Keys.ToList()) { SocketGuild guild = context.Client.GetGuild(serverID); if (guild != null) { SocketTextChannel chan = guild.GetTextChannel(Program.interServerChats[serverID]); if (serverID != context.Guild.Id && chan != null && PermissionChecker.HasSend(guild, chan)) { bool sendMsg = true; bool wlEnabled = Program.wlEnable.Contains(context.Guild.Id); // Host server-side if (wlEnabled && Program.ischatWhitelist.ContainsKey(context.Guild.Id)) { if (!Program.ischatWhitelist[context.Guild.Id].Contains(serverID)) { sendMsg = false; } } else if (wlEnabled) { sendMsg = false; } else if (Program.ischatBlacklist.ContainsKey(context.Guild.Id)) { if (Program.ischatBlacklist[context.Guild.Id].Contains(serverID)) { sendMsg = false; } } // Receiving server-side if (sendMsg) { wlEnabled = Program.wlEnable.Contains(serverID); if (wlEnabled && Program.ischatWhitelist.ContainsKey(serverID)) { if (!Program.ischatWhitelist[serverID].Contains(context.Guild.Id)) { sendMsg = false; } } else if (wlEnabled) { sendMsg = false; } else if (Program.ischatBlacklist.ContainsKey(serverID)) { if (Program.ischatBlacklist[serverID].Contains(context.Guild.Id)) { sendMsg = false; } } } if (sendMsg) { if (Program.showUserServer.Contains(serverID)) { sendMessage.Add(chan.SendMessageAsync("", false, embedGuild.Build())); if (fileName.Length == 0) { sendFile.Add(chan.SendFileAsync(fileName, "")); } } else { sendMessage.Add(chan.SendMessageAsync("", false, embed.Build())); if (fileName.Length == 0) { sendFile.Add(chan.SendFileAsync(fileName, "")); } } } } } } await Task.WhenAll(sendMessage.ToArray()).ContinueWith(t => Task.WhenAll(sendFile.ToArray()).ContinueWith(r => Task.Run(() => { if (fileName.Length == 0) { System.IO.File.Delete(fileName); } }))); } } }
public static async Task DownloadJava() { if (!Directory.Exists(config.javaLocal + "runtime\\jre")) { Directory.CreateDirectory(config.javaLocal + "runtime\\jre"); } /*Pages.SplashScreen.singleton.firstLabel.Visibility = Visibility.Visible; * Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Visible; * Pages.SplashScreen.singleton.mbToDownload.Visibility = Visibility.Visible; * Pages.SplashScreen.singleton.kbps.Visibility = Visibility.Visible;*/ #if STYLE_1 await Task.Delay(1000); DownloadWindowLayout1.instance.downloadtext.Text = "서버에 맞는 자바를 다운로드 중입니다."; #endif System.Threading.Thread.Sleep(1500); // Windows.Splashscreen.singleton.actualActivity.Text = "Downloading Java"; string url = ""; //i .exe sono zip in verita' if (ComputerInfoDetect.GetComputerArchitecture() == 64) { url = config.jre64URL; } else { url = config.jre32URL; } Uri uri = new Uri(url); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); webClient.Headers.Set("Cookie", "oraclelicense=accept-securebackup-cookie"); sw.Start(); try { await webClient.DownloadFileTaskAsync(new Uri(url), config.javaLocal + "runtime\\java.zip"); } catch (Exception e) { MessageBox.Show("Errore nel download di JAVA. Minecraft potrebbe non avviarsi correttamente" + e.Message); } /*Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Visible; * Pages.SplashScreen.singleton.progressbar.IsIndeterminate = true;*/ #if STYLE_1 DownloadWindowLayout1.instance.downloadtext.Text = "자바 압축 해제중입니다."; #endif try { using (Stream targetStream = new GZipInputStream(File.OpenRead(config.javaLocal + "runtime\\java.zip"))) { using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(targetStream, TarBuffer.DefaultBlockFactor)) { await Task.Factory.StartNew(() => { tarArchive.ExtractContents(config.javaLocal + "runtime\\jre"); }) .ContinueWith((ante) => Thread.Sleep(200));; } } } catch (TargetInvocationException e) { MessageBox.Show(e.ToString()); } if (ComputerInfoDetect.GetComputerArchitecture() == 64) { Properties.Settings.Default["JavaPath"] = config.javaLocal + "runtime\\jre\\" + config.jre64FileName + "\\"; Properties.Settings.Default.Save(); } else { Properties.Settings.Default["JavaPath"] = config.javaLocal + "runtime\\jre\\" + config.jre32FileName + "\\"; Properties.Settings.Default.Save(); } #if STYLE_1 DownloadWindowLayout1.instance.downloadtext.Text = ("자바 설치가 완료되었습니다."); await Task.Delay(1000); #endif /*Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Hidden; * Pages.SplashScreen.singleton.progressbar.IsIndeterminate = false; * * Pages.SplashScreen.singleton.firstLabel.Text = "Java Extraction Completed"; * Pages.SplashScreen.singleton.kbps.Visibility = Visibility.Hidden;*/ }
protected override Task DownloadFileAsync(WebClient wc, string address, string fileName) => wc.DownloadFileTaskAsync(address, fileName);
/// <summary> /// Adds menu options for image editing, embedding and a few other /// image operations conditionally. /// </summary> /// <param name="line"></param> /// <param name="pos"></param> /// <returns></returns> private bool CheckForImageLink(string line, AcePosition pos) { // Check for images ![](imageUrl) var matches = ImageRegex.Matches(line); if (matches.Count > 0) { foreach (Match match in matches) { string val = match.Value; var imageLink = HttpUtility.UrlDecode(match.Groups[1].Value); if (match.Index <= pos.column && match.Index + val.Length > pos.column) { bool isWebLink = imageLink.StartsWith("http"); if (!isWebLink) { var mi = new MenuItem { Header = "Edit in Image Editor" }; mi.Click += (o, args) => { imageLink = mmFileUtils.NormalizeFilenameWithBasePath(imageLink, Path.GetDirectoryName(Model.ActiveDocument.Filename)); mmFileUtils.OpenImageInImageEditor(imageLink); }; ContextMenu.Items.Add(mi); } var mi2 = new MenuItem { Header = "Edit Image Url" }; mi2.Click += (o, args) => { Model.ActiveEditor.AceEditor.SetSelectionRange(pos.row, match.Index, pos.row, match.Index + val.Length); Model.ActiveEditor.EditorSelectionOperation("image", val); }; ContextMenu.Items.Add(mi2); if (isWebLink) { var mi = new MenuItem { Header = "Download and embed as Local Image" }; mi.Click += async(o, args) => { var sd = new SaveFileDialog { Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|" + "All Files (*.*)|*.*", FilterIndex = 1, Title = "Save Image from URL as", CheckFileExists = false, OverwritePrompt = true, CheckPathExists = true, RestoreDirectory = true, ValidateNames = true, FileName = Path.GetFileName(imageLink) }; var doc = Model.ActiveDocument; var editor = Model.ActiveEditor; if (!string.IsNullOrEmpty(doc.LastImageFolder)) { sd.InitialDirectory = doc.LastImageFolder; } else if (!string.IsNullOrEmpty(doc.Filename) && !doc.Filename.Equals("untitled", StringComparison.OrdinalIgnoreCase)) { sd.InitialDirectory = Path.GetDirectoryName(doc.Filename); } else { sd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); } sd.ShowDialog(); if (string.IsNullOrEmpty(sd.FileName)) { return; } try { var wc = new WebClient(); await wc.DownloadFileTaskAsync(new Uri(imageLink), sd.FileName); string filename; if (doc.Filename.Equals("untitled", StringComparison.OrdinalIgnoreCase)) { filename = doc.LastImageFolder; // let doc figure out the path } else { filename = FileUtils.GetRelativePath(sd.FileName, Path.GetDirectoryName(doc.Filename)); } // group hold just the filename var group = match.Groups[1]; editor.SetSelectionRange(pos.row, group.Index, pos.row, group.Index + group.Value.Length); editor.SetSelection(WebUtility.UrlEncode(filename)); } catch (Exception ex) { Model.Window.ShowStatusError($"Image failed to download: {ex.Message}"); } }; ContextMenu.Items.Add(mi); } return(true); } } } return(false); }
private static async void RefreshTesseractDlls(CancellationToken token, bool AvxSupport) { WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback); token.Register(webClient.CancelAsync); for (int i = 0; i < list_of_dlls.Length; i++) { if (token.IsCancellationRequested) { break; } string dll = list_of_dlls[i]; string path = app_data_tesseract_catalog + dll; string md5 = AvxSupport ? list_of_checksums[i] : list_of_checksums_AVX_free[i]; if (!File.Exists(path) || GetMD5hash(path) != md5) { if (File.Exists(path)) { File.Delete(path); } if (token.IsCancellationRequested) { break; } bool success = false; try { if (Directory.Exists("lib") && File.Exists("lib" + dll)) { File.Copy("lib" + dll, app_data_tesseract_catalog + dll); success = true; } } catch (Exception ex) { using (StreamWriter sw = File.AppendText(appPath + @"\debug.log")) { await sw.WriteLineAsync("[" + DateTime.UtcNow + "] " + dll + " couldn't be moved"); await sw.WriteLineAsync("[" + DateTime.UtcNow + "] " + ex.ToString()); } } if (token.IsCancellationRequested) { break; } if (!success) { try { if (dll != @"\Tesseract.dll") { await webClient.DownloadFileTaskAsync(tesseract_hotlink_platform_specific_prefix + dll.Replace("\\", "/"), app_data_tesseract_catalog + dll); } else { await webClient.DownloadFileTaskAsync(tesseract_hotlink_prefix + dll.Replace("\\", "/"), app_data_tesseract_catalog + dll); } } catch (Exception) when(stopDownloadTask.Token.IsCancellationRequested) { } } dialogue.Dispatcher.Invoke(() => { dialogue.FileComplete(); }); } } webClient.Dispose(); dialogue.Dispatcher.Invoke(() => { dialogue.Close(); }); }
public async void Update() { Version version = new Version(context.Version); Version latestVersion = new Version(context.LatestVersion); #if PUBLISH try { int maxStep = 6; if (latestVersion.CompareTo(version) > 0) { var selection = await context.DialogCoordinator.ShowMessageAsync(context, "Caution", $"We've detected you're using an older version of AmongUsCapture!\nYour version: {version}\nLatest version: {latestVersion}", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "Update", NegativeButtonText = "No thanks", DefaultButtonFocus = MessageDialogResult.Affirmative }); if (selection == MessageDialogResult.Negative) { selection = await context.DialogCoordinator.ShowMessageAsync(context, "Warning", $"Having an older version could cause compatibility issues with AutoMuteUs.\nWe can automagically update you to {latestVersion}.", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "Update", NegativeButtonText = "no ty", DefaultButtonFocus = MessageDialogResult.Affirmative }); } if (selection == MessageDialogResult.Affirmative) { var DownloadProgress = await context.DialogCoordinator.ShowProgressAsync(context, $"Step 1/{maxStep} - Downloading", "Percent: 0% (0/0)", isCancelable : false, new MetroDialogSettings { AnimateHide = false }); DownloadProgress.Maximum = 100; using (var client = new WebClient()) { var downloadPath = Path.GetTempFileName(); client.DownloadProgressChanged += (sender, args) => { DownloadProgress.SetProgress(args.ProgressPercentage); DownloadProgress.SetMessage($"Percent: {args.ProgressPercentage}% ({args.BytesReceived.Bytes().Humanize("#.##")}/{args.TotalBytesToReceive.Bytes().Humanize("#.##")})"); }; client.DownloadFileCompleted += async(sender, args) => { if (args.Error is not null) { await DownloadProgress.CloseAsync(); } else { DownloadProgress.SetTitle($"Step 2/{maxStep} - Downloading signature"); using var client2 = new WebClient(); var downloadPathSignedHash = Path.GetTempFileName(); client2.DownloadProgressChanged += (sender, args) => { DownloadProgress.SetProgress(args.ProgressPercentage); DownloadProgress.SetMessage($"Percent: {args.ProgressPercentage}% ({args.BytesReceived.Bytes().Humanize("#.##")}/{args.TotalBytesToReceive.Bytes().Humanize("#.##")})"); }; client2.DownloadFileCompleted += async(sender, args) => { if (args.Error is not null) { await DownloadProgress.CloseAsync(); ShowErrorBox(args.Error.Message); } else { DownloadProgress.SetTitle($"Step 3/{maxStep} - Verifying signature"); DownloadProgress.SetMessage(""); DownloadProgress.SetIndeterminate(); bool SignatureValid = VerifySignature(downloadPathSignedHash); if (!SignatureValid) { await DownloadProgress.CloseAsync(); ShowErrorBox("File signature invalid. If you get this after retrying tell us on discord. It is potentially a security risk."); return; } DownloadProgress.SetTitle($"Step 4/{maxStep} - Verifying hash"); DownloadProgress.SetMessage(""); DownloadProgress.SetIndeterminate(); bool HashValid = VerifyHashFromSig(downloadPath, downloadPathSignedHash); if (!HashValid) { await DownloadProgress.CloseAsync(); ShowErrorBox("Capture hash invalid. If you get this after retrying tell us on discord. It is potentially a security risk."); return; } DownloadProgress.SetTitle($"Step 5/{maxStep} - Extracting"); DownloadProgress.SetMessage("Please wait, we may go unresponsive but don't close the window, we will restart the program after."); DownloadProgress.SetIndeterminate(); if (!Directory.Exists(Path.Join( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\AmongUsCapture\\AmongUsGUI\\Update"))) { Directory.CreateDirectory(Path.Join( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\AmongUsCapture\\AmongUsGUI\\Update")); } using (ZipArchive archive = ZipFile.OpenRead(downloadPath)) { try { var entry = archive.Entries.First(x => x.FullName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)); entry.ExtractToFile(Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\AmongUsCapture\\AmongUsGUI\\Update", "AmongUsCapture.exe"), true); } catch (Exception e) { var errorBox = await context.DialogCoordinator.ShowMessageAsync(context, "ERROR", e.Message, MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "retry", NegativeButtonText = "cancel", DefaultButtonFocus = MessageDialogResult.Affirmative }); if (errorBox == MessageDialogResult.Affirmative) { await Task.Factory.StartNew(Update, TaskCreationOptions.LongRunning); } } } //You can't delete a running application. But you can rename it. string appFolder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); string appName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName); string appExtension = Path.GetExtension(Process.GetCurrentProcess().MainModule.FileName); string archivePath = Path.Combine(appFolder, appName + "_Old" + appExtension); DownloadProgress.SetTitle($"Step 6/{maxStep} - Copying files"); DownloadProgress.SetMessage("Finishing up.."); File.Move(Process.GetCurrentProcess().MainModule.FileName, archivePath); File.Move(Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\AmongUsCapture\\AmongUsGUI\\Update", "AmongUsCapture.exe"), Path.Combine(appFolder, appName + appExtension), true); Application.Current.Invoke(() => { IPCAdapter.getInstance().mutex.ReleaseMutex(); //Release the mutex so the other app does not see us. Process.Start(Path.Combine(appFolder, appName + appExtension)); Environment.Exit(0); }); } }; if (!string.IsNullOrEmpty(context.LatestReleaseAssetSignedHashURL)) { var signatureDownloader = client2.DownloadFileTaskAsync(context.LatestReleaseAssetSignedHashURL, downloadPathSignedHash); } else { ShowErrorBox("Release does not have a signature. Not downloading, please retry later."); } } }; var downloaderClient = client.DownloadFileTaskAsync(context.LatestReleaseAssetURL, downloadPath); } } } } catch (Exception e) { ShowErrorBox(e.Message); } #endif }
public Task DownloadFileAsync(Uri address, out string filename) { filename = SessionTempPath + Utilities.GetRandomString(); return(WebClient.DownloadFileTaskAsync(address, filename)); }
private async void DownloadButton_Click(object sender, RoutedEventArgs e) { #region Save as var save = new Microsoft.Win32.SaveFileDialog { FileName = "ScreenToGif" + (IsInstaller ? " Setup " + Element.XPathSelectElement("tag_name").Value : ""), DefaultExt = IsInstaller ? ".msi" : ".exe", Filter = IsInstaller ? "ScreenToGif setup (.msi)|*.msi" : "ScreenToGif executable (.exe)|*.exe" }; var result = save.ShowDialog(); if (!result.HasValue || !result.Value) { return; } if (save.FileName == Assembly.GetExecutingAssembly().Location) { Dialog.Ok(Title, this.TextResource("Update.Filename.Warning"), this.TextResource("Update.Filename.Warning2"), Dialog.Icons.Warning); return; } #endregion DownloadButton.IsEnabled = false; StatusBand.Info("Downloading..."); DownloadProgressBar.Visibility = Visibility.Visible; var tempFilename = !IsInstaller?save.FileName.Replace(".exe", DateTime.Now.ToString(" hh-mm-ss fff") + ".zip") : save.FileName; #region Download try { using (var webClient = new WebClient()) { webClient.Credentials = CredentialCache.DefaultNetworkCredentials; webClient.Proxy = WebHelper.GetProxy(); await webClient.DownloadFileTaskAsync(new Uri((IsInstaller ? Element.XPathSelectElement("assets").LastNode : Element.XPathSelectElement("assets").FirstNode).XPathSelectElement("browser_download_url").Value), tempFilename); } } catch (Exception ex) { LogWriter.Log(ex, "Download updates"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok("Update", "Error while downloading", ex.Message); return; } #endregion //If cancelled. if (!IsLoaded) { return; } #region Installer if (IsInstaller) { if (!Dialog.Ask(Title, this.TextResource("Update.Install.Header"), this.TextResource("Update.Install.Description"))) { return; } try { Process.Start(tempFilename); } catch (Exception ex) { LogWriter.Log(ex, "Starting the installer"); Dialog.Ok(Title, "Error while starting the installer", ex.Message); return; } Environment.Exit(25); } #endregion #region Unzip try { //Deletes if already exists. if (File.Exists(save.FileName)) { File.Delete(save.FileName); } //Unzips the only file. using (var zipArchive = ZipFile.Open(tempFilename, ZipArchiveMode.Read)) zipArchive.Entries.First(x => x.Name.EndsWith(".exe")).ExtractToFile(save.FileName); } catch (Exception ex) { LogWriter.Log(ex, "Unziping update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok("Update", "Error while unzipping", ex.Message); return; } #endregion #region Delete temporary zip and run try { File.Delete(tempFilename); Process.Start(save.FileName); } catch (Exception ex) { LogWriter.Log(ex, "Finishing update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok(Title, "Error while finishing the update", ex.Message); return; } #endregion GC.Collect(); DialogResult = true; }
public async Task Download(string Url, string Path, string FileName) { Directory.CreateDirectory(Path); await WebClient.DownloadFileTaskAsync(Url, Path + FileName); }
private async Task InitLoadProcess(bool IsRefresh) { await Task.Delay(100); try { refreshMainLayout.Refreshing = true; // 장비 타이틀 바 초기화 try { if (!File.Exists(Path.Combine(ETC.cachePath, "Equip", "Normal", $"{equip.Icon}.gfdcache")) || IsRefresh) { using (WebClient wc = new WebClient()) { await wc.DownloadFileTaskAsync(Path.Combine(ETC.server, "Data", "Images", "Equipments", $"{equip.Icon}.png"), Path.Combine(ETC.cachePath, "Equip", "Normal", $"{equip.Icon}.gfdcache")); } } if (Preferences.Get("DBDetailBackgroundImage", true)) { Drawable drawable = Drawable.CreateFromPath(Path.Combine(ETC.cachePath, "Equip", "Normal", $"{equip.Icon}.gfdcache")); drawable.SetAlpha(40); FindViewById <RelativeLayout>(Resource.Id.EquipDBDetailMainLayout).Background = drawable; } FindViewById <ImageView>(Resource.Id.EquipDBDetailImage).SetImageDrawable(Drawable.CreateFromPath(Path.Combine(ETC.cachePath, "Equip", "Normal", $"{equip.Icon}.gfdcache"))); } catch (Exception ex) { ETC.LogError(ex, this); } FindViewById <TextView>(Resource.Id.EquipDBDetailEquipName).Text = equip.Name; FindViewById <TextView>(Resource.Id.EquipDBDetailEquipType).Text = equip.Type; FindViewById <TextView>(Resource.Id.EquipDBDetailEquipProductTime).Text = ETC.CalcTime(equip.ProductTime); // 장비 기본 정보 초기화 StringBuilder gradeString = new(); if (equip.Grade is 0) { gradeString.Append('★'); gradeString.Append(" EX"); } else { for (int i = 0; i < equip.Grade; ++i) { gradeString.Append('★'); } } FindViewById <TextView>(Resource.Id.EquipDBDetailInfoGrade).Text = gradeString.ToString(); FindViewById <TextView>(Resource.Id.EquipDBDetailInfoCategory).Text = equip.Category; FindViewById <TextView>(Resource.Id.EquipDBDetailInfoType).Text = equip.Type; FindViewById <TextView>(Resource.Id.EquipDBDetailInfoName).Text = equip.Name; FindViewById <TextView>(Resource.Id.EquipDBDetailInfoETC).Text = equip.Note; // 장비 사용여부 정보 초기화 bool IsOnlyUse = false; if (equip.OnlyUse != null) { if (string.IsNullOrWhiteSpace(equip.OnlyUse[0]) == false) { IsOnlyUse = true; } else { IsOnlyUse = false; } } else { IsOnlyUse = false; } switch (IsOnlyUse) { case false: FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoOnlyUseLayout).Visibility = ViewStates.Gone; FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoRecommendLayout).Visibility = ViewStates.Visible; FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoUseLayout).Visibility = ViewStates.Visible; string[] TotalAvailable = equip.DollType; List <string> RecommendType = new List <string>(); List <string> UseType = new List <string>(); foreach (string s in TotalAvailable) { string[] temp = s.Split(','); if (temp[1] == "F") { RecommendType.Add(temp[0]); } else if (temp[1] == "U") { UseType.Add(temp[0]); } } RecommendType.TrimExcess(); UseType.TrimExcess(); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for (int i = 0; i < RecommendType.Count; ++i) { sb1.Append(RecommendType[i]); if (i < (RecommendType.Count - 1)) { sb1.Append(" | "); } } for (int i = 0; i < UseType.Count; ++i) { sb2.Append(UseType[i]); if (i < (UseType.Count - 1)) { sb2.Append(" | "); } } FindViewById <TextView>(Resource.Id.EquipDBDetailAvailableInfoRecommend).Text = sb1.ToString(); FindViewById <TextView>(Resource.Id.EquipDBDetailAvailableInfoUse).Text = sb2.ToString(); break; case true: FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoRecommendLayout).Visibility = ViewStates.Gone; FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoUseLayout).Visibility = ViewStates.Gone; FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAvailableInfoOnlyUseLayout).Visibility = ViewStates.Visible; StringBuilder sb = new StringBuilder(); for (int i = 0; i < equip.OnlyUse.Length; ++i) { sb.Append(equip.OnlyUse[i]); if (i < (equip.OnlyUse.Length - 1)) { sb.Append(" | "); } } FindViewById <TextView>(Resource.Id.EquipDBDetailAvailableInfoOnlyUse).Text = sb.ToString(); break; } // 장비 능력치 초기화 string[] Abilities = equip.Abilities; string[] AbilityInitMags = equip.InitMags; string[] AbilityMaxMags = equip.MaxMags; abilityTableSubLayout.RemoveAllViews(); for (int i = 0; i < equip.Abilities.Length; ++i) { LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Horizontal, LayoutParameters = FindViewById <LinearLayout>(Resource.Id.EquipDBDetailAbilityTopLayout).LayoutParameters }; TextView ability = new TextView(this); TextView initmag = new TextView(this); TextView maxmag = new TextView(this); ability.LayoutParameters = FindViewById <TextView>(Resource.Id.EquipDBDetailAbilityTopText1).LayoutParameters; initmag.LayoutParameters = FindViewById <TextView>(Resource.Id.EquipDBDetailAbilityTopText2).LayoutParameters; maxmag.LayoutParameters = FindViewById <TextView>(Resource.Id.EquipDBDetailAbilityTopText3).LayoutParameters; ability.Text = equip.Abilities[i]; ability.SetTextColor(Android.Graphics.Color.LimeGreen); ability.Gravity = GravityFlags.Center; initmag.Text = equip.InitMags[i]; initmag.Gravity = GravityFlags.Center; maxmag.Text = equip.CanUpgrade ? equip.MaxMags[i] : "X"; maxmag.Gravity = GravityFlags.Center; layout.AddView(ability); layout.AddView(initmag); layout.AddView(maxmag); abilityTableSubLayout.AddView(layout); } if (ETC.useLightTheme) { SetCardTheme(); } ShowCardViewVisibility(); } catch (WebException ex) { ETC.LogError(ex, this); ETC.ShowSnackbar(snackbarLayout, Resource.String.RetryLoad_CauseNetwork, Snackbar.LengthShort, Android.Graphics.Color.DarkMagenta); _ = InitLoadProcess(false); return; } catch (Exception ex) { ETC.LogError(ex, this); ETC.ShowSnackbar(snackbarLayout, Resource.String.DBDetail_LoadDetailFail, Snackbar.LengthShort, Android.Graphics.Color.DarkRed); } finally { refreshMainLayout.Refreshing = 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; }); }
public async void Update(string distrib, string path) { if (distrib == string.Empty || (distrib != "linux" && distrib != "windows")) { Console.WriteLine("ERROR: Please choose \"linux\" or \"windows\" as first parameter"); activeCommand = false; return; } if (path == string.Empty) { Console.WriteLine("ERROR: No path specified"); activeCommand = false; return; } if (distrib == "linux") { distrib = "build_proot_linux"; } else if (distrib == "windows") { distrib = "build_server_windows"; } path = path.TrimEnd('/').TrimEnd('\\'); Console.WriteLine("INFO: FxServer update running"); using (WebClient client = new WebClient()) { // Reading html string htmlFile = await client.DownloadStringTaskAsync($"https://runtime.fivem.net/artifacts/fivem/{distrib}/master/"); MatchCollection matches = new Regex("href=\"([0-9]*-.*)\">.*([0-9]{2}-[\\w]*-[0-9]{4} [0-9]{2}:[0-9]{2})").Matches(htmlFile); Dictionary <DateTime, string> versions = new Dictionary <DateTime, string>(); foreach (Match match in matches) { if (match.Groups.Count > 2) { versions.Add(DateTime.ParseExact(match.Groups[2].Value, "dd-MMM-yyyy HH:mm", CultureInfo.InvariantCulture), match.Groups[1].Value); } } string onlineVersion = versions.Last().Value.TrimEnd('/'); // Creating directory & .version file Directory.CreateDirectory(path); Console.WriteLine($"INFO: Online version {onlineVersion} detected"); if (File.Exists($"{path}/version")) { string localVersion = File.ReadAllText($"{path}/version"); Console.WriteLine($"INFO: Local version {localVersion} detected"); if (localVersion == onlineVersion) { Console.WriteLine("ERROR: You already have the latest version"); activeCommand = false; return; } else { Directory.CreateDirectory($"{path}/{localVersion}"); string[] files = Directory.GetFiles(path); foreach (string file in files) { string fileName = file.Split('\\').Last(); File.Move($"{path}/{fileName}", $"{path}/{localVersion}/{fileName}"); } Directory.Move($"{path}/citizen", $"{path}/{localVersion}/citizen"); } } else { if (Directory.GetDirectories(path).Count() != 0 || Directory.GetFiles(path).Count() != 0) { path.CopyServerFiles("versionless"); } } File.Create($"{path}/version").Close(); File.WriteAllText($"{path}/version", onlineVersion); // Downloading file Console.WriteLine("INFO: Downloading file"); client.DownloadProgressChanged += OnDownloadProgressChanged; await client.DownloadFileTaskAsync($"https://runtime.fivem.net/artifacts/fivem/build_server_windows/master/{onlineVersion}/server.zip", $"{path}/server.zip"); } // TODO: create a backup with a versionning system ZipFile.ExtractToDirectory($"{path}/server.zip", path); File.Delete($"{path}/server.zip"); Console.WriteLine("INFO: Update finished"); activeCommand = false; }
internal async Task UpdateDataAsync(Player playerData, string imageSavePath) { if (!_dataUpdated) { return; } _dataUpdated = false; try { if (string.IsNullOrWhiteSpace(imageSavePath)) { imageSavePath = Path.GetTempPath(); } if (!Directory.Exists(imageSavePath)) { Directory.CreateDirectory(imageSavePath); } this.PlayerData = playerData; this.LastUpdated = playerData.FileUpdated; this.TribeName = playerData.Tribe?.Name; this.CharacterName = playerData.CharacterName; this.HasBan = playerData.CommunityBanned || playerData.VACBanned; if (PlayerInfo.avatarImages.TryGetValue(this.SteamId, out BitmapImage avatarImage)) { _logger?.Debug($"Avatar image for {this.SteamId} found."); } else { var localImageFile = Path.Combine(imageSavePath, $"{this.SteamId}{Config.Default.PlayerImageFileExtension}"); // check for a valid URL. if (!String.IsNullOrWhiteSpace(playerData.AvatarUrl)) { try { using (var client = new WebClient()) { await client.DownloadFileTaskAsync(playerData.AvatarUrl, localImageFile); } _logger.Debug($"{nameof(UpdateDataAsync)} - downloaded avatar image for {this.SteamId} from {playerData.AvatarUrl}."); } catch (Exception ex) { _logger.Debug($"{nameof(UpdateDataAsync)} - failed to download avatar image for {this.SteamId} from {playerData.AvatarUrl}. {ex.Message}\r\n{ex.StackTrace}"); } } if (File.Exists(localImageFile)) { avatarImage = new BitmapImage(new Uri(localImageFile, UriKind.Absolute)); PlayerInfo.avatarImages[this.SteamId] = avatarImage; _logger.Debug($"Avatar image for {this.SteamId} found and added."); } else { _logger.Debug($"Avatar image for {this.SteamId} not found."); } } this.AvatarImage = avatarImage; } finally { _dataUpdated = true; } }