private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { UpdateControlState(() => { DownloadVersionText.Text = $"正在安装{_currentInstallVersionName}版本的更新包"; }); string fileName; string contentDisposition = _webClient.ResponseHeaders["Content-Disposition"] ?? string.Empty; if (string.IsNullOrEmpty(contentDisposition)) { fileName = Path.GetFileName(_webClient.ResponseUri.LocalPath); } else { fileName = _tryToFindFileName(contentDisposition, "filename="); if (string.IsNullOrEmpty(fileName)) { fileName = _tryToFindFileName(contentDisposition, "filename*=UTF-8''"); } } var tempPath = Path.Combine(Path.GetTempPath(), fileName); try { if (File.Exists(tempPath)) { File.Delete(tempPath); } File.Move(_tempFile, tempPath); } catch (Exception ex) { UpdateControlState(() => { DownloadVersionText.Text = $"安装{_currentInstallVersionName}版本的更新包失败," + ex.Message; }); _webClient = null; return; } var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); ZipStorer zip = ZipStorer.Open(tempPath, FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); for (var index = 0; index < dir.Count; index++) { ZipStorer.ZipFileEntry entry = dir[index]; zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip)); int progress = (index + 1) * 100 / dir.Count;; UpdateControlState(() => { DownloadProgressBar.Value = progress; }); UpdateControlState(() => { DownloadProgressText.Text = progress + "%"; }); } zip.Close(); UpdateControlState(() => { DownloadVersionText.Text = $"版本{_currentInstallVersionName}安装成功"; }); UpdateControlState(() => { DownloadProgressText.Text = string.Empty; }); UpdateControlState(() => { CurrentVersion.Content = _currentInstallVersionName; }); }
static void Main(string[] args) { FlagParser.Parse(args); var exeFile = FlagParser.StringFlag("exeFile", string.Empty, true); var exePath = FlagParser.StringFlag("exePath", string.Empty, true); var zipFile = FlagParser.StringFlag("zipFile", string.Empty, true); if (string.IsNullOrWhiteSpace(exeFile) || string.IsNullOrWhiteSpace(exePath) || string.IsNullOrWhiteSpace(zipFile)) { Console.WriteLine("Invalid Parameters"); return; } // make sure exe file to update is not running foreach (var proc in Process.GetProcesses()) { try { if (proc.MainModule.FileName.Equals(exeFile, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("-- Waiting for exit " + exeFile + " --"); proc.WaitForExit(); Console.WriteLine("-- Application closed " + exeFile + " --"); } } catch (Exception e) { Debug.WriteLine(e.Message); Debug.WriteLine(e.StackTrace); } } Console.WriteLine("-- Waiting for process to close --"); Thread.Sleep(5000); Console.WriteLine("-- Extrating Files --"); // open zip file using var zip = ZipStorer.Open(zipFile, FileAccess.Read); var dir = zip.Files.Values; foreach (var item in dir) { try { if (item.FilenameInZip.ToLower().Contains("zipextractor", StringComparison.OrdinalIgnoreCase)) { continue; } var extractFile = Path.Combine(exePath, item.FilenameInZip); if (File.Exists(extractFile)) { Console.WriteLine("-- Deleting File " + extractFile); File.Delete(extractFile); } Console.WriteLine("-- Extracting File " + extractFile); zip.ExtractFile(item, extractFile); Console.WriteLine("-- Done Extracting File " + extractFile); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); continue; } } zip.Close(); // done extract, run exe file again var psi = new ProcessStartInfo(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.X64) { psi.FileName = exeFile; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.X86) { psi.FileName = exeFile; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.Arm) { psi.FileName = exeFile; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && RuntimeInformation.OSArchitecture == Architecture.X64) { psi.FileName = "/usr/bin/dotnet"; psi.Arguments = exeFile.Replace(".exe", ".dll"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && RuntimeInformation.OSArchitecture == Architecture.Arm) { psi.FileName = "/usr/bin/dotnet"; psi.Arguments = exeFile.Replace(".exe", ".dll"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && RuntimeInformation.OSArchitecture == Architecture.X64) { psi.FileName = "/usr/bin/dotnet"; psi.Arguments = exeFile.Replace(".exe", ".dll"); } Console.WriteLine("-- Running Application --"); Console.WriteLine("Filename : " + psi.FileName); Console.WriteLine("Args : " + psi.Arguments); Process.Start(psi).WaitForExit(); File.Delete(zipFile); Console.WriteLine("-- Update Done --"); return; }
private string DetectPackageType(string file) { using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None)) { try { using (var zip = ZipStorer.Open(stream, FileAccess.Read, false)) { zip.ReadCentralDir(); return(PackageManager.ARCHIVE_FORMAT_NUGET_ZIP); } } catch (ExecEnvironment.SelfInvokeExitException) { throw; } catch { stream.Seek(0, SeekOrigin.Begin); try { using (var gzip = new GZipStream(stream, CompressionMode.Decompress, true)) { using (var reader = new StreamReader(gzip)) { reader.ReadToEnd(); } } return(PackageManager.ARCHIVE_FORMAT_TAR_GZIP); } catch (ExecEnvironment.SelfInvokeExitException) { throw; } catch { stream.Seek(0, SeekOrigin.Begin); try { using (var memory = new MemoryStream()) { LZMA.LzmaHelper.Decompress(stream, memory); } return(PackageManager.ARCHIVE_FORMAT_TAR_LZMA); } catch (ExecEnvironment.SelfInvokeExitException) { throw; } catch { throw new InvalidOperationException("Package format not recognised for " + file); } } } } }
static int Main(string[] args) { string restartTarget = null; string configFileName = ConfigFileNameDefault; // Set path string defaultPath = Path.GetFullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); Directory.SetCurrentDirectory(defaultPath); // Parse command-line arguments List <string> argsList = new List <string>(); foreach (string arg in args) { Console.WriteLine(arg); if (arg.StartsWith("--path=", StringComparison.OrdinalIgnoreCase)) { Directory.SetCurrentDirectory(arg.Substring(arg.IndexOf('=') + 1).TrimQuotes()); argsList.Add(arg); } else if (arg.StartsWith("--config=", StringComparison.OrdinalIgnoreCase)) { configFileName = arg.Substring(arg.IndexOf('=') + 1).TrimQuotes(); argsList.Add(arg); } else if (arg.StartsWith("--restart=", StringComparison.OrdinalIgnoreCase)) { restartTarget = arg.Substring(arg.IndexOf('=') + 1).TrimQuotes(); } else if (arg != "&") { argsList.Add(arg); } } // Parse update settings string runBefore = null, runAfter = null; bool doBackup = true; try { if (File.Exists(configFileName)) { XDocument doc = XDocument.Load(configFileName); if (doc.Root != null) { XElement elRunBefore = doc.Root.Element("RunBeforeUpdate"); if (elRunBefore != null) { runBefore = elRunBefore.Value; } XElement elRunAfter = doc.Root.Element("RunAfterUpdate"); if (elRunAfter != null) { runAfter = elRunAfter.Value; } XElement elDoBackup = doc.Root.Element("BackupBeforeUpdate"); if (elDoBackup != null && !String.IsNullOrEmpty(elDoBackup.Value)) { if (!Boolean.TryParse(elDoBackup.Value, out doBackup)) { doBackup = true; } } } } } catch (Exception ex) { Console.Error.WriteLine("Error reading fCraft config: {0}", ex); } // Backup data files (if requested) if (doBackup) { DoBackup(); } // Run pre-update script (if any) if (!String.IsNullOrEmpty(runBefore)) { Console.WriteLine("Executing pre-update script..."); try { Process preUpdateProcess = Process.Start(runBefore, ""); if (preUpdateProcess != null) { preUpdateProcess.WaitForExit(); } } catch (Exception ex) { Console.Error.WriteLine("Failed to run pre-update process, aborting update application: {0}", ex); return((int)ReturnCodes.FailedToRunPreUpdateCommand); } } // Apply the update using (MemoryStream ms = new MemoryStream(Resources.Payload)) { using (ZipStorer zs = ZipStorer.Open(ms, FileAccess.Read)) { var allFiles = zs.ReadCentralDir().Select(entry => entry.FilenameInZip).Union(LegacyFiles); // ensure that fcraft files are writable bool allPassed; do { allPassed = true; foreach (var fileName in allFiles) { try { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) { continue; } using (fi.OpenWrite()) { } } catch (Exception ex) { if (ex is IOException) { Console.WriteLine("Waiting for fCraft-related applications to close..."); } else { Console.Error.WriteLine("ERROR: could not write to {0}: {1} - {2}", fileName, ex.GetType().Name, ex.Message); Console.WriteLine(); } allPassed = false; Thread.Sleep(1000); break; } } } while (!allPassed); // delete legacy files foreach (var legacyFile in LegacyFiles) { try { File.Delete(legacyFile); } catch (Exception ex) { Console.Error.WriteLine(" ERROR: {0} {1}", ex.GetType().Name, ex.Message); } } // extract files foreach (var entry in zs.ReadCentralDir()) { Console.WriteLine("Extracting {0}", entry.FilenameInZip); try { using (FileStream fs = File.Create(entry.FilenameInZip)) { zs.ExtractFile(entry, fs); } } catch (Exception ex) { Console.Error.WriteLine(" ERROR: {0} {1}", ex.GetType().Name, ex.Message); } } } } // Run post-update script if (!String.IsNullOrEmpty(runAfter)) { Console.WriteLine("Executing post-update script..."); try { Process postUpdateProcess = Process.Start(runAfter, ""); if (postUpdateProcess != null) { postUpdateProcess.WaitForExit(); } } catch (Exception ex) { Console.Error.WriteLine("Failed to run post-update process, aborting restart: {0}", ex); return((int)ReturnCodes.FailedToRunPostUpdateCommand); } } Console.WriteLine("fCraft update complete."); // Restart fCraft (if requested) if (restartTarget != null) { if (restartTarget == "fCraftConsole.exe") { restartTarget = "ServerCLI.exe"; } else if (restartTarget == "fCraftUI.exe") { restartTarget = "ServerGUI.exe"; } if (!File.Exists(restartTarget)) { Console.Error.WriteLine("Restart target not found, quitting: {0}", restartTarget); return((int)ReturnCodes.RestartTargetNotFound); } string argString = String.Join(" ", argsList.ToArray()); Console.WriteLine("Starting: {0} {1}", restartTarget, argString); switch (Environment.OSVersion.Platform) { case PlatformID.MacOSX: case PlatformID.Unix: Process.Start("mono", "\"" + restartTarget + "\" " + argString + " &"); break; default: Process.Start(restartTarget, argString); break; } } return((int)ReturnCodes.Ok); }
/// <summary> /// Deploy a given list of files (can reduce the list if there are duplicated items so it returns it) /// </summary> public List <FileToDeploy> DeployFiles(List <FileToDeploy> deployToDo, Action <float> updateDeploymentPercentage = null) { int[] totalFile = { 0 }; int[] nbFilesDone = { 0 }; // make sure to transfer a given file only once at the same place (happens with .cls file since a source // can have several .r files generated if it is used in another classes) deployToDo = deployToDo .GroupBy(deploy => deploy.To) .Select(group => group.FirstOrDefault(move => Path.GetFileNameWithoutExtension(move.From ?? "").Equals(Path.GetFileNameWithoutExtension(move.Origin))) ?? group.First()) .ToList(); totalFile[0] = deployToDo.Count; // check that every target dir exist (for copy/move deployments) deployToDo .Where(deploy => deploy.DeployType == DeployType.Copy || deploy.DeployType == DeployType.Move) .GroupBy(deploy => Path.GetDirectoryName(deploy.To)) .Select(group => group.First()) .ToNonNullList() .ForEach(deploy => Utils.CreateDirectory(Path.GetDirectoryName(deploy.To))); #region for archives (zip/pl) // for archives, compute the path to the archive file (+ make sure the directory of the archive exists) deployToDo.Where(deploy => deploy.DeployType <= DeployType.Archive).ToNonNullList().ForEach(deploy => { var ext = deploy.DeployType == DeployType.Prolib ? ".pl" : ".zip"; var pos = deploy.To.LastIndexOf(ext, StringComparison.CurrentCultureIgnoreCase); if (pos >= 0) { var posEnd = pos + ext.Length; deploy.ArchivePath = deploy.To.Substring(0, posEnd); deploy.RelativePathInArchive = deploy.To.Substring(posEnd + 1); // ensure that the folder to the .archive file exists Utils.CreateDirectory(Path.GetDirectoryName(deploy.ArchivePath)); // for .zip, open the zip stream for later usage if (deploy.DeployType > DeployType.Prolib) { if (!_openedZip.ContainsKey(deploy.ArchivePath)) { try { if (!File.Exists(deploy.ArchivePath)) { _openedZip.Add(deploy.ArchivePath, ZipStorer.Create(deploy.ArchivePath, "Created with 3P @ " + DateTime.Now + "\r\n" + Config.UrlWebSite)); } else { _openedZip.Add(deploy.ArchivePath, ZipStorer.Open(deploy.ArchivePath, FileAccess.Write)); _filesToRemoveFromZip.Add(deploy.ArchivePath, new HashSet <string>()); } } catch (Exception e) { ErrorHandler.ShowErrors(e, "Couldn't create/open the .zip file"); } } // we didn't create the zip? then we need to remove this file if it exists if (_filesToRemoveFromZip.ContainsKey(deploy.ArchivePath)) { _filesToRemoveFromZip[deploy.ArchivePath].Add(deploy.RelativePathInArchive.Replace('\\', '/')); } } } }); #endregion #region for .pl deployments, we treat them before anything else // for PL, we need to MOVE each file into a temporary folder with the internal structure of the .pl file, // then move it back where it was for further deploys... var plDeployments = deployToDo .Where(deploy => deploy.DeployType == DeployType.Prolib) .ToNonNullList(); if (plDeployments.Count > 0) { // then we create a unique temporary folder for each .pl var dicPlToTempFolder = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase); foreach (var pathPl in plDeployments.Where(deploy => !string.IsNullOrEmpty(deploy.ArchivePath)).Select(deploy => deploy.ArchivePath).Distinct()) { // create a unique temp folder for this .pl if (!dicPlToTempFolder.ContainsKey(pathPl)) { var plDirPath = Path.GetDirectoryName(pathPl); if (plDirPath != null) { var uniqueTempFolder = Path.Combine(plDirPath, Path.GetFileName(pathPl) + "~" + Path.GetRandomFileName()); dicPlToTempFolder.Add(pathPl, uniqueTempFolder); Utils.CreateDirectory(uniqueTempFolder, FileAttributes.Hidden); } } } var prolibMessage = new StringBuilder(); // for each .pl that needs to be created... foreach (var pl in dicPlToTempFolder) { var pl1 = pl; var onePlDeployments = plDeployments .Where(deploy => !string.IsNullOrEmpty(deploy.ArchivePath) && deploy.ArchivePath.Equals(pl1.Key)) .ToNonNullList(); if (onePlDeployments.Count == 0) { continue; } // we set the temporary folder on which each file will be copied.. // Tuple : <(base) temp directory, relative path in pl, path to .pl> var dicTempFolderToPl = new Dictionary <string, Tuple <string, string, string> >(StringComparer.CurrentCultureIgnoreCase); foreach (var fileToDeploy in onePlDeployments) { if (string.IsNullOrEmpty(fileToDeploy.ArchivePath)) { continue; } if (dicPlToTempFolder.ContainsKey(fileToDeploy.ArchivePath)) { fileToDeploy.ToTemp = Path.Combine( dicPlToTempFolder[fileToDeploy.ArchivePath], fileToDeploy.To.Replace(fileToDeploy.ArchivePath, "").TrimStart('\\') ); // If not already done, remember that the *.r code in this temp folder must be integrated to this .pl file var tempSubFolder = Path.GetDirectoryName(fileToDeploy.ToTemp); if (!string.IsNullOrEmpty(tempSubFolder) && !dicTempFolderToPl.ContainsKey(tempSubFolder)) { dicTempFolderToPl.Add( tempSubFolder, new Tuple <string, string, string>( dicPlToTempFolder[fileToDeploy.ArchivePath], // path of the temp dir Path.GetDirectoryName(fileToDeploy.To.Replace(fileToDeploy.ArchivePath, "").TrimStart('\\')), // relative path in .pl fileToDeploy.ArchivePath) // path to the .pl file ); // also, create the folder Utils.CreateDirectory(tempSubFolder); } } } var prolibExe = new ProcessIo(ProEnv.ProlibPath); // for each subfolder in the .pl foreach (var plSubFolder in dicTempFolderToPl) { var onePlSubFolderDeployments = onePlDeployments .Where(deploy => plSubFolder.Key.Equals(Path.GetDirectoryName(deploy.ToTemp))) .ToNonNullList(); if (onePlSubFolderDeployments.Count == 0) { continue; } Parallel.ForEach(onePlSubFolderDeployments, deploy => { if (File.Exists(deploy.From)) { deploy.IsOk = !string.IsNullOrEmpty(deploy.ToTemp) && Utils.MoveFile(deploy.From, deploy.ToTemp); } if (deploy.IsOk) { nbFilesDone[0]++; } if (updateDeploymentPercentage != null) { updateDeploymentPercentage((float)nbFilesDone[0] / totalFile[0] * 100); } }); // now we just need to add the content of temp folders into the .pl prolibExe.StartInfo.WorkingDirectory = plSubFolder.Value.Item1; // base temp dir prolibExe.Arguments = plSubFolder.Value.Item3.ProQuoter() + " -create -nowarn -add " + Path.Combine(plSubFolder.Value.Item2, "*").ProQuoter(); if (!prolibExe.TryDoWait(true)) { prolibMessage.Append(prolibExe.ErrorOutput); } Parallel.ForEach(onePlSubFolderDeployments, deploy => { deploy.IsOk = deploy.IsOk && Utils.MoveFile(deploy.ToTemp, deploy.From); }); } // compress .pl prolibExe.StartInfo.WorkingDirectory = Path.GetDirectoryName(pl.Key) ?? ""; prolibExe.Arguments = pl.Key.ProQuoter() + " -compress -nowarn"; if (!prolibExe.TryDoWait(true)) { prolibMessage.Append(prolibExe.ErrorOutput); } // delete temp folders Utils.DeleteDirectory(pl.Value, true); } if (prolibMessage.Length > 0) { UserCommunication.Notify("Errors occured when trying to create/add files to the .pl file :<br>" + prolibMessage, MessageImg.MsgError, "Prolib output", "Errors"); } } #endregion #region for zip // remove the files that are already in the zip file or they will appear twice when we add them foreach (var kpv in _filesToRemoveFromZip) { ZipStorer zip = _openedZip[kpv.Key]; var filesToDelete = zip.ReadCentralDir().Where(zipFileEntry => kpv.Value.Contains(zipFileEntry.FilenameInZip)).ToList(); _openedZip.Remove(kpv.Key); ZipStorer.RemoveEntries(ref zip, filesToDelete); _openedZip.Add(kpv.Key, zip); } #endregion // do a deployment action for each file (parallel for MOVE and COPY) Parallel.ForEach(deployToDo.Where(deploy => deploy.DeployType >= DeployType.Copy), file => { if (DeploySingleFile(file)) { nbFilesDone[0]++; } if (updateDeploymentPercentage != null) { updateDeploymentPercentage((float)nbFilesDone[0] / totalFile[0] * 100); } }); // don't use parallel for the other types foreach (var file in deployToDo.Where(deploy => deploy.DeployType < DeployType.Copy)) { if (DeploySingleFile(file)) { nbFilesDone[0]++; } if (updateDeploymentPercentage != null) { updateDeploymentPercentage((float)nbFilesDone[0] / totalFile[0] * 100); } } #region for zip, dispose of zipStorers // also, need to dispose of the object/stream here foreach (var zipStorer in _openedZip) { zipStorer.Value.Close(); } _openedZip.Clear(); #endregion return(deployToDo); }
public void OpenRead_Test() { using (ZipStorer zip = ZipStorer.Open(sampleFile, FileAccess.Read)) { } }
private void Execute() { try { _fs.Close(); try { FileManagement fm1 = new FileManagement(); fm1.createFolder(0, username, null, null); FileManagement fm2 = new FileManagement(); fm2.createFolder(1, username, getGame, null); FileManagement fm3 = new FileManagement(); fm3.createFolder(2, username, getGame, getMatchID); } catch (Exception) { // we assume that the server is down. Environment.Exit(0); } FileStream fs = new FileStream(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileMode.Open, FileAccess.ReadWrite, FileShare.None); writeProcesses(); FileManagement fm = new FileManagement(); fs.Close(); ZipStorer zip; zip = ZipStorer.Open(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileAccess.Write); zip.AddFile(ZipStorer.Compression.Store, Core.AppPath + "ac_log_" + getTimeProcesses + "_matchid" + getMatchID + ".txt", "ac_log_" + getTimeProcesses + "_matchid" + getMatchID + ".txt", "Anticheat process log during game for match ID " + getMatchID.ToString() + "and at " + DateTime.Now.ToString()); zip.Close(); File.Delete(Core.AppPath + "ac_log_" + getTimeProcesses + "_matchid" + getMatchID + ".txt"); FileStream fs2 = new FileStream(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileMode.Open, FileAccess.ReadWrite, FileShare.None); int getTime2 = TextHandling.GetUnixTimestamp(); using (ScreenshotDump screen = new ScreenshotDump()) { try { AeroControl ac = new AeroControl(); ac.ControlAero(false); screen.SaveToFile(Core.AppPath + "acscreens\\" + "screen_" + getTime2 + "_matchid" + getMatchID + ".jpeg"); fs2.Close(); zip = ZipStorer.Open(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileAccess.Write); zip.AddFile(ZipStorer.Compression.Store, Core.AppPath + "acscreens\\" + "screen_" + getTime2 + "_matchid" + getMatchID + ".jpeg", "screen_" + getTime2 + "_matchid" + getMatchID + ".jpeg", "Screenshot during game for match ID " + getMatchID.ToString() + "and at " + DateTime.Now.ToString()); zip.Close(); File.Delete(Core.AppPath + "acscreens\\" + "screen_" + getTime2 + "_matchid" + getMatchID + ".jpeg"); } catch (Exception) { File.WriteAllText(Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt", "Failed to grab screenshot! at " + DateTime.Now.TimeOfDay); fm.postFile(username, getGame, getMatchID, Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt"); File.Delete(Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt"); ReportForm ef = new ReportForm(); ef.label2.Text = "Screenshot capture failed!"; ef.Show(); } } FileStream fs3 = new FileStream(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileMode.Open, FileAccess.ReadWrite, FileShare.None); using (ScreenshotBitBltDump screenbitblthandle = new ScreenshotBitBltDump()) { try { string grabProc; grabProc = File.ReadAllText(Core.AppPath + "chosengameexec.txt"); grabProc = grabProc.Substring(0, grabProc.Length - 4); Process[] getHandle = Process.GetProcessesByName(grabProc); foreach (Process p in getHandle) { IntPtr windowHandle = p.MainWindowHandle; AeroControl ac = new AeroControl(); ac.ControlAero(false); screenbitblthandle.CaptureWindowToFile(windowHandle, Core.AppPath + "acscreens\\" + "screen_bitblt_handle_" + getTime2 + "_matchid" + getMatchID + ".jpeg", ImageFormat.Jpeg); fs3.Close(); zip = ZipStorer.Open(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileAccess.Write); zip.AddFile(ZipStorer.Compression.Store, Core.AppPath + "acscreens\\" + "screen_bitblt_handle_" + getTime2 + "_matchid" + getMatchID + ".jpeg", "screen_bitblt_handle_" + getTime2 + "_matchid" + getMatchID + ".jpeg", "Screenshot aggro mode during game for match ID " + getMatchID.ToString() + "and at " + DateTime.Now.ToString()); zip.Close(); File.Delete(Core.AppPath + "acscreens\\" + "screen_bitblt_handle_" + getTime2 + "_matchid" + getMatchID + ".jpeg"); } } catch (Exception) { File.WriteAllText(Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt", "Failed to grab screenshot! at " + DateTime.Now.TimeOfDay); fm.postFile(username, getGame, getMatchID, Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt"); File.Delete(Core.AppPath + "acscreens\\captureerror_" + getTime2 + "_matchid" + getMatchID + ".txt"); ReportForm ef = new ReportForm(); ef.label2.Text = "Screenshot capture failed!"; ef.Show(); } } FileStream fs4 = new FileStream(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileMode.Open, FileAccess.ReadWrite, FileShare.None); if (ProcessManagement.ProcessIsRunning("taskmgr.exe")) { int tskmgrtimestamp = TextHandling.GetUnixTimestamp(); GameReport taskmgrReport = new GameReport(); taskmgrReport.WriteLine("Taskmgr opened while anticheat running for user " + username + " at " + DateTime.Now.TimeOfDay + " timestamp: " + tskmgrtimestamp + " on match: " + getMatchID); File.WriteAllText(Core.AppPath + "acscreens\\taskmgr.txt", taskmgrReport.toFile()); fm.postFile(username, getGame, getMatchID, Core.AppPath + "acscreens\\taskmgr.txt"); File.Delete(Core.AppPath + "acscreens\\taskmgr.txt"); TaskManagerIsRunning(); } fs4.Close(); } catch (Exception ex) { ReportForm ef = new ReportForm(); ef.label2.Text = ex.ToString(); ef.Show(); } }
private void FormMain_Shown(object sender, EventArgs e) { _logBuilder.AppendLine(DateTime.Now.ToString("F")); _logBuilder.AppendLine(); _logBuilder.AppendLine("ZipExtractor started with following command line arguments."); string[] args = Environment.GetCommandLineArgs(); for (var index = 0; index < args.Length; index++) { var arg = args[index]; _logBuilder.AppendLine($"[{index}] {arg}"); } _logBuilder.AppendLine(); if (args.Length >= 4) { string executablePath = args[3]; // Extract all the files. _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += (o, eventArgs) => { foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executablePath))) { try { if (process.MainModule != null && process.MainModule.FileName.Equals(executablePath)) { _logBuilder.AppendLine("Waiting for application process to exit..."); _backgroundWorker.ReportProgress(0, "Waiting for application to exit..."); process.WaitForExit(); } } catch (Exception exception) { Debug.WriteLine(exception.Message); } } _logBuilder.AppendLine("BackgroundWorker started successfully."); var path = args[2]; // Ensures that the last character on the extraction path // is the directory separator char. // Without this, a malicious zip file could try to traverse outside of the expected // extraction path. if (!path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { path += Path.DirectorySeparatorChar; } #if NET45 var archive = ZipFile.OpenRead(args[1]); var entries = archive.Entries; #else // Open an existing zip file for reading. var zip = ZipStorer.Open(args[1], FileAccess.Read); // Read the central directory collection. var entries = zip.ReadCentralDir(); #endif _logBuilder.AppendLine($"Found total of {entries.Count} files and folders inside the zip file."); try { int progress = 0; for (var index = 0; index < entries.Count; index++) { if (_backgroundWorker.CancellationPending) { eventArgs.Cancel = true; break; } var entry = entries[index]; #if NET45 string currentFile = string.Format(Resources.CurrentFileExtracting, entry.FullName); #else string currentFile = string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip); #endif _backgroundWorker.ReportProgress(progress, currentFile); int retries = 0; bool notCopied = true; while (notCopied) { string filePath = String.Empty; try { #if NET45 filePath = Path.Combine(path, entry.FullName); if (!entry.IsDirectory()) { var parentDirectory = Path.GetDirectoryName(filePath); if (!Directory.Exists(parentDirectory)) { Directory.CreateDirectory(parentDirectory); } entry.ExtractToFile(filePath, true); } #else filePath = Path.Combine(path, entry.FilenameInZip); zip.ExtractFile(entry, filePath); #endif notCopied = false; } catch (IOException exception) { const int errorSharingViolation = 0x20; const int errorLockViolation = 0x21; var errorCode = Marshal.GetHRForException(exception) & 0x0000FFFF; if (errorCode == errorSharingViolation || errorCode == errorLockViolation) { retries++; if (retries > MaxRetries) { throw; } List <Process> lockingProcesses = null; if (Environment.OSVersion.Version.Major >= 6 && retries >= 2) { try { lockingProcesses = FileUtil.WhoIsLocking(filePath); } catch (Exception) { // ignored } } if (lockingProcesses == null) { Thread.Sleep(5000); } else { foreach (var lockingProcess in lockingProcesses) { var dialogResult = MessageBox.Show( string.Format(Resources.FileStillInUseMessage, lockingProcess.ProcessName, filePath), Resources.FileStillInUseCaption, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (dialogResult == DialogResult.Cancel) { throw; } } } } else { throw; } } } progress = (index + 1) * 100 / entries.Count; _backgroundWorker.ReportProgress(progress, currentFile); _logBuilder.AppendLine($"{currentFile} [{progress}%]"); } } finally { #if NET45 archive.Dispose(); #else zip.Close(); #endif } }; _backgroundWorker.ProgressChanged += (o, eventArgs) => { progressBar.Value = eventArgs.ProgressPercentage; textBoxInformation.Text = eventArgs.UserState.ToString(); textBoxInformation.SelectionStart = textBoxInformation.Text.Length; textBoxInformation.SelectionLength = 0; }; _backgroundWorker.RunWorkerCompleted += (o, eventArgs) => { try { if (eventArgs.Error != null) { throw eventArgs.Error; } if (!eventArgs.Cancelled) { textBoxInformation.Text = @"Finished"; try { ProcessStartInfo processStartInfo = new ProcessStartInfo(executablePath); if (args.Length > 4) { processStartInfo.Arguments = args[4]; } Process.Start(processStartInfo); _logBuilder.AppendLine("Successfully launched the updated application."); } catch (Win32Exception exception) { if (exception.NativeErrorCode != 1223) { throw; } } } } catch (Exception exception) { _logBuilder.AppendLine(); _logBuilder.AppendLine(exception.ToString()); MessageBox.Show(exception.Message, exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { _logBuilder.AppendLine(); Application.Exit(); } }; _backgroundWorker.RunWorkerAsync(); } }
private void FormMain_Shown(object sender, EventArgs e) { _logBuilder.AppendLine(DateTime.Now.ToString("F")); _logBuilder.AppendLine(); _logBuilder.AppendLine("ZipExtractor started with following command line arguments."); var args = Environment.GetCommandLineArgs(); for (var index = 0; index < args.Length; index++) { var arg = args[index]; _logBuilder.AppendLine($"[{index}] {arg}"); } _logBuilder.AppendLine(); if (args.Length >= 3) { // Extract all the files. _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += (o, eventArgs) => { foreach (var process in Process.GetProcesses()) { try { if (process.MainModule.FileName.Equals(args[2])) { _logBuilder.AppendLine("Waiting for application process to Exit..."); _backgroundWorker.ReportProgress(0, "Waiting for application to Exit..."); process.Kill(); process.WaitForExit(); } } catch (Exception exception) { Debug.WriteLine(exception.Message); } } Thread.Sleep(2000); _logBuilder.AppendLine("BackgroundWorker started successfully."); var path = Path.GetDirectoryName(args[2]); // Open an existing zip file for reading. var zip = ZipStorer.Open(args[1], FileAccess.Read); // Read the central directory collection. var dir = zip.ReadCentralDir(); _logBuilder.AppendLine($"Found total of {dir.Count} files and folders inside the zip file."); for (var index = 0; index < dir.Count; index++) { if (_backgroundWorker.CancellationPending) { eventArgs.Cancel = true; zip.Close(); return; } var entry = dir[index]; var attemptCount = 1; var tryAgain = true; while (tryAgain) { try { _logBuilder.AppendLine($"Extracting File {entry.FilenameInZip}, attempt {attemptCount}"); zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip)); tryAgain = false; } catch { if (attemptCount > 10) { throw; } attemptCount++; tryAgain = true; Thread.Sleep(2000); } } var currentFile = string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip); var progress = (index + 1) * 100 / dir.Count; _backgroundWorker.ReportProgress(progress, currentFile); _logBuilder.AppendLine($"{currentFile} [{progress}%]"); } zip.Close(); }; _backgroundWorker.ProgressChanged += (o, eventArgs) => { progressBar.Value = eventArgs.ProgressPercentage; labelInformation.Text = eventArgs.UserState.ToString(); }; _backgroundWorker.RunWorkerCompleted += (o, eventArgs) => { try { if (eventArgs.Error != null) { throw eventArgs.Error; } if (!eventArgs.Cancelled) { labelInformation.Text = @"Finished"; try { var processStartInfo = new ProcessStartInfo(args[2]); if (args.Length > 3) { processStartInfo.Arguments = args[3]; } Process.Start(processStartInfo); _logBuilder.AppendLine("Successfully launched the updated application."); } catch (Win32Exception exception) { if (exception.NativeErrorCode != 1223) { throw; } } } } catch (Exception exception) { _logBuilder.AppendLine(); _logBuilder.AppendLine(exception.ToString()); MessageBox.Show(exception.Message, exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { _logBuilder.AppendLine(); Application.Exit(); } }; _backgroundWorker.RunWorkerAsync(); } }
public void ExecuteCode(string[] code, bool close_window) { foreach (string line in code) { if (progress) { this.updwindow.Invoke(updwindow.newtick); } List <string> commands = TokenizeLine(line); if (commands[0] == "--") { continue; } bool canfail = false; if (commands[0] == "CANFAIL") { canfail = true; commands.RemoveAt(0); } if (commands[0] == "IFLOONIX") { commands.RemoveAt(0); if (!Updater.IsLoonix()) { continue; } } if (commands[0] == "IFWIN") { commands.RemoveAt(0); if (Updater.IsLoonix()) { continue; } } try { if (commands[0] == "EXECUTE") { this.UpdateStatus("Zaganjam command file " + commands[1]); this.ExecuteCode(commands[1], false, false); if ((progress) && (this.updwindow.update_error != "")) { throw new Exception(this.updwindow.update_error); } } if (commands[0] == "VERIFY") { this.UpdateStatus("Verifying file " + commands[1]); if (this.GetSHAHashFromFile(commands[1]) != commands[2]) { throw new Exception("Datoteka " + commands[1] + " zgleda da je bila nepričakovano spremenjena!"); } } if (commands[0] == "EXTRACT") { this.UpdateStatus("Extractam file '" + commands[2] + "' iz '" + commands[1] + "' v '" + commands[3] + "'"); ZipStorer zip = ZipStorer.Open(commands[1], FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); bool success = false; foreach (ZipStorer.ZipFileEntry entry in dir) { if (entry.FilenameInZip == commands[2]) { zip.ExtractFile(entry, commands[3]); success = true; break; } } if (!success) { throw new Exception("Datoteka " + commands[1] + "/" + commands[2] + " ne obstaja!"); } zip.Close(); } if (commands[0] == "ADD") { bool shamatch = false; if (File.Exists(commands[1])) { string shasum = this.GetSHAHashFromFile(commands[1]); if (shasum == commands[2]) { shamatch = true; } } if (shamatch) { this.UpdateStatus("Ze imam fajl: " + commands[1] + ", skip..."); continue; } DownloadFile(commands[1], commands[1]); } if (commands[0] == "SET") { this.SetVar(commands[1], commands[2]); } if (commands[0] == "CLEARMIRRORS") { this.UpdateStatus("Spucal vse mirrorje"); this.mirrorlist.Clear(); this.mirrors.Clear(); } if (commands[0] == "MIRROR") { this.mirrors.Add(commands[1], commands[2]); this.mirrorlist.Add(commands[1]); this.UpdateStatus("Dodajam nov mirror: " + commands[2] + ", ID: " + this.FindMirrorIndex(commands[1]).ToString()); } if (commands[0] == "MKDIR") { this.UpdateStatus("Ustvarjam mapo " + commands[1]); Directory.CreateDirectory(commands[1]); } if (commands[0] == "DEL") { this.UpdateStatus("Brisem " + commands[1]); if (Directory.Exists(commands[1])) { Directory.Delete(commands[1], true); } else { File.Delete(commands[1]); } } if (commands[0] == "COMMIT") { this.UpdateStatus("Koncujem update..."); File.WriteAllText("cversion", this.GetVar("VERSION")); this.UpdateStatus("Done"); } if (commands[0] == "OVERRIDE") { try { this.UpdateStatus("Dodajam override za " + commands[1] + "..."); overrides.Add(commands[1], commands[2]); } catch { }; } if (commands[0] == "SETCFG") { Form1.config.SetValue(commands[1], commands[2]); Form1.config.FlushConfig(); } if (commands[0] == "RENAME") { File.Move(commands[1], commands[2]); } if (commands[0] == "RESTART") { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = commands[1]; startInfo.UseShellExecute = true; process.StartInfo = startInfo; process.Start(); Environment.Exit(0); } } catch (Exception e) { if (progress) { this.UpdateStatus("ERROR: " + e.Message); } if (!canfail) { System.Threading.Thread.Sleep(1000); if (progress) { this.progress = false; this.updwindow.Invoke(updwindow.weredone); } this.updwindow.update_error = e.Message; return; } } } if ((progress) && (close_window)) { System.Threading.Thread.Sleep(1000); this.updwindow.update_success = true; this.updwindow.Invoke(updwindow.weredone); } }
private void mainForm_Shown(object sender, EventArgs e) { //morhpeus font for prettier labels. not mandatory //MorpheusFont morpheusFont = new MorpheusFont(); //morpheusFont.Load(); //playButtonLabel.Font = new Font(morpheusFont.fontFamily(), 12, FontStyle.Regular); settingsFile.Read(); if (settingsFile.startUpSound() == true) { WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer(); player.URL = @Directory.GetCurrentDirectory() + "\\sound\\startup.mp3"; player.controls.play(); } //change control properties on runtime //upArrowPicture.Parent = newsTextLabel; //upArrowPicture.Location = new Point(436, -2); //downArrowPicture.Parent = newsTextLabel; //downArrowPicture.Location = new Point(436, 73); trayIcon.BalloonTipTitle = "TrueWoW Launcher"; trayIcon.BalloonTipText = "Launcher minimized to tray. Right click icon for menu."; if (settingsFile.minimizeToTray() == true) { trayIcon.Visible = true; } else { trayIcon.Visible = false; } #region BLP-TEST //try //{ // if (this.blpLoader != null) // { // this.blpLoader.close(); // this.blpLoader = null; // } // FileStream file = new FileStream("example.blp", FileMode.Open); // this.blpLoader = new SereniaBLPLib.BlpFile(file); // // loading bitmap level 0 // loadedBLP = this.blpLoader.getBitmap(0); // Rectangle imgDimensions = new Rectangle(); // imgDimensions.Location = new Point(50, 15); // imgDimensions.Width = 155; // imgDimensions.Height = 32; // playButtonBitmap = loadedBLP.Clone(imgDimensions, loadedBLP.PixelFormat); // playButton.Image = playButtonBitmap; // if (this.blpLoader != null) // { // this.blpLoader.close(); // this.blpLoader = null; // } // file.Close(); // file = new FileStream("Glues-BigButton-Glow.blp", FileMode.Open); // this.blpLoader = new SereniaBLPLib.BlpFile(file); // loadedBLP = this.blpLoader.getBitmap(0); // imgDimensions = new Rectangle(); // imgDimensions.Location = new Point(43, 7); // imgDimensions.Width = 170; // imgDimensions.Height = 50; // playButtonBitmap = loadedBLP.Clone(imgDimensions, loadedBLP.PixelFormat); // playButtonHoover.Image = playButtonBitmap; //} //catch (FileNotFoundException fe) //{ // MessageBox.Show("The 'example.blp' was not found!"); //} #endregion //read data inside zip ZipStorer newsZIP = ZipStorer.Open(@Directory.GetCurrentDirectory() + "\\news\\news.zip", FileAccess.Read); // Read all directory contents List <ZipStorer.ZipFileEntry> dir = newsZIP.ReadCentralDir(); // Extract all files in target directory string path; bool result; foreach (ZipStorer.ZipFileEntry entry in dir) { path = Path.Combine(@Directory.GetCurrentDirectory() + "\\news\\", Path.GetFileName(entry.FilenameInZip)); result = newsZIP.ExtractFile(entry, path); } newsZIP.Close(); this.Refresh(); readedNews.Read(); for (int i = 0; i < readedNews.newsCount(); i++) { Label tmpControl = new Label(); if (i == 0) { tmpControl.BackColor = System.Drawing.Color.Aqua; } else { tmpControl.BackColor = System.Drawing.Color.Gray; } tmpControl.Cursor = System.Windows.Forms.Cursors.Hand; tmpControl.Name = "newsSelector" + i.ToString(); //tmpControl. = "newsSelector" + i.ToString(); tmpControl.Size = new System.Drawing.Size(10, 10); tmpControl.Click += new System.EventHandler(this.newsSelectorSelected_Click); this.Controls.Add(tmpControl); tmpControl.Parent = this.newsPicture; tmpControl.Location = new System.Drawing.Point((3 + (i * 16)), 3); newsSelector.Add(tmpControl); } newsPicture.ImageLocation = @Directory.GetCurrentDirectory() + "\\news\\" + readedNews.newsImg(0); newsTittleLabel.Text = readedNews.newsTittle(0); newsTextLabel.Text = readedNews.newsText(0); newsSelectorHistory = 0; newsLoopWorker.RunWorkerAsync(); }
private void FormMain_Shown(object sender, EventArgs e) { //foreach (var process in Process.GetProcesses()) //{ // try // { // if (process.MainModule.FileName.Equals(mianExeFile)) // { // labelInformation.Text = @"Waiting for application to Exit..."; // process.WaitForExit(); // } // } // catch (Exception exception) // { // Debug.WriteLine(exception.Message); // } //} // Extract all the files. _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += (o, eventArgs) => { var path = Path.GetDirectoryName(mianExeFile); // Open an existing zip file for reading. ZipStorer zip = ZipStorer.Open(zipFile, FileAccess.Read); // Read the central directory collection. List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); for (var index = 0; index < dir.Count; index++) { if (_backgroundWorker.CancellationPending) { eventArgs.Cancel = true; zip.Close(); return; } ZipStorer.ZipFileEntry entry = dir[index]; zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip)); _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format(MyAutoUpdater.Properties.Resources.CurrentFileExtracting, entry.FilenameInZip)); } zip.Close(); }; _backgroundWorker.ProgressChanged += (o, eventArgs) => { progressBar.Value = eventArgs.ProgressPercentage; labelInformation.Text = eventArgs.UserState.ToString(); }; _backgroundWorker.RunWorkerCompleted += (o, eventArgs) => { if (!eventArgs.Cancelled) { labelInformation.Text = @"Finished"; //try //{ // ProcessStartInfo processStartInfo = new ProcessStartInfo(args[2]); // if (args.Length > 3) // { // processStartInfo.Arguments = args[3]; // } // Process.Start(processStartInfo); //} //catch (Win32Exception exception) //{ // if (exception.NativeErrorCode != 1223) // throw; //} Close(); } }; _backgroundWorker.RunWorkerAsync(); }
private void FormMain_Shown(object sender, EventArgs e) { string[] args = Environment.GetCommandLineArgs(); File.AppendAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{DateTime.Now:yyyy-MM-dd}.log"), $"cmd line args\n{string.Join("\n", args)}"); if (args.Length >= 3) { var zipFileName = args[1]; var progToStart = args[2]; var argsToStart = args.Length > 3 ? args[3] : string.Empty; foreach (var process in Process.GetProcesses()) { try { if (process.MainModule.FileName.Equals(progToStart)) { labelInformation.Text = @"Waiting for application to Exit..."; process.WaitForExit(); } } catch (Exception exception) { Debug.WriteLine(exception.Message); } } // Extract all the files. _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += (o, eventArgs) => { var path = Path.GetDirectoryName(progToStart); // Open an existing zip file for reading. ZipStorer zip = ZipStorer.Open(zipFileName, FileAccess.Read); // Read the central directory collection. List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); for (var index = 0; index < dir.Count; index++) { if (_backgroundWorker.CancellationPending) { eventArgs.Cancel = true; zip.Close(); return; } ZipStorer.ZipFileEntry entry = dir[index]; zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip)); _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip)); } zip.Close(); }; _backgroundWorker.ProgressChanged += (o, eventArgs) => { progressBar.Value = eventArgs.ProgressPercentage; labelInformation.Text = eventArgs.UserState.ToString(); }; _backgroundWorker.RunWorkerCompleted += (o, eventArgs) => { if (!eventArgs.Cancelled) { labelInformation.Text = @"Finished"; try { ProcessStartInfo processStartInfo = new ProcessStartInfo(progToStart); if (!string.IsNullOrEmpty(progToStart)) { processStartInfo.Arguments = argsToStart; } Process.Start(processStartInfo); } catch (Win32Exception exception) { if (exception.NativeErrorCode != 1223) { throw; } } Application.Exit(); } }; _backgroundWorker.RunWorkerAsync(); } }
private void download(short dl) { if (dl == 0) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://sergi4ua.com/equine/versions/Diablo-1.00.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } else if (dl == 1) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://sergi4ua.com/equine/versions/Diablo-1.07.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } if (dl == 2) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://sergi4ua.com/equine/versions/Diablo-1.08.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } if (dl == 3) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://www.sergi4ua.com/equine/versions/Diablo-1.02.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } if (dl == 4) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://www.sergi4ua.com/equine/versions/Diablo-1.03.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } if (dl == 5) { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; wc.DownloadFile("https://www.sergi4ua.com/equine/versions/Diablo-1.04.zip", Application.StartupPath + "\\dv100.zip"); } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\dv100.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\dv100.zip"); } noErr = true; }
public IPackageMetadata ResolveSource(string workingDirectory, PackageRequestRef request) { var path = request.Uri.Substring("local-nuget-v3://".Length); string packageName; string packageType; string sourceCodeUrl; string version; string binaryFormat; string binaryUri; string commitHashForSourceResolve; // Figure out the package type by looking at the tags inside // the package's .nuspec file. using (var storer = ZipStorer.Open(path, FileAccess.Read)) { var entries = storer.ReadCentralDir(); var nuspecEntries = entries.Where( x => x.FilenameInZip.EndsWith(".nuspec") && !x.FilenameInZip.Contains("/") && !x.FilenameInZip.Contains("\\")).ToList(); if (nuspecEntries.Count != 0) { using (var stream = new MemoryStream()) { storer.ExtractFile(nuspecEntries[0], stream); stream.Seek(0, SeekOrigin.Begin); var document = new XmlDocument(); document.Load(stream); packageName = document.SelectSingleNode("//id")?.InnerText; version = document.SelectSingleNode("//version")?.InnerText; var tags = document.SelectSingleNode("//tags")?.InnerText?.Split(new[] { ' ' }) ?? new string[0]; packageType = PackageManager.PACKAGE_TYPE_LIBRARY; commitHashForSourceResolve = null; sourceCodeUrl = null; foreach (var tag in tags) { if (!string.IsNullOrWhiteSpace(tag)) { if (tag == "type=global-tool") { packageType = PackageManager.PACKAGE_TYPE_GLOBAL_TOOL; } else if (tag == "type=template") { packageType = PackageManager.PACKAGE_TYPE_TEMPLATE; } if (tag.StartsWith("commit=")) { commitHashForSourceResolve = tag.Substring("commit=".Length); } if (tag.StartsWith("git=")) { sourceCodeUrl = tag.Substring("git=".Length); } } } binaryUri = path; binaryFormat = PackageManager.ARCHIVE_FORMAT_NUGET_ZIP; } } else { throw new InvalidOperationException("NuGet package is missing nuspec file!"); } } return(new NuGet3PackageMetadata( null, packageName, packageType, sourceCodeUrl, request.Platform, version, binaryFormat, binaryUri, commitHashForSourceResolve, (workingDirectoryAlt, metadata, folder, name, upgrade, source) => { if (source == true) { _sourcePackageResolve.Resolve(workingDirectoryAlt, metadata, folder, name, upgrade); } else { _binaryPackageResolve.Resolve(workingDirectoryAlt, metadata, folder, name, upgrade); } })); }
public PakFile(string name, string handle) { Handle = handle; Name = name; Storer = ZipStorer.Open(handle, FileAccess.Read); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { using (WebClient wc = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; if (_109b == false) { wc.DownloadFile("http://sergi4ua.com/equine/versions/d1forceupdate.zip", Application.StartupPath + "\\d1forceupdate.zip"); } else { wc.DownloadFile("http://sergi4ua.com/equine/versions/Diablo-1.09b.zip", Application.StartupPath + "\\d1forceupdate.zip"); } } ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\d1forceupdate.zip", System.IO.FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { zip.ExtractFile(entry, Application.StartupPath + "\\" + entry.FilenameInZip); } zip.Close(); File.Delete(Application.StartupPath + "\\d1forceupdate.zip"); if (Directory.Exists(Application.StartupPath + "\\EquineData")) { if (!Directory.Exists(Application.StartupPath + "\\EquineData\\GameBackup")) { Directory.CreateDirectory(Application.StartupPath + "\\EquineData\\GameBackup"); } if (File.Exists(Application.StartupPath + "\\Storm.dll") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\Storm.dll")) { File.Copy(Application.StartupPath + "\\Storm.dll", Application.StartupPath + "\\EquineData\\GameBackup\\Storm.dll"); } if (File.Exists(Application.StartupPath + "\\SMACKW32.DLL") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\SMACKW32.DLL")) { File.Copy(Application.StartupPath + "\\SMACKW32.DLL", Application.StartupPath + "\\EquineData\\GameBackup\\SMACKW32.DLL"); } if (File.Exists(Application.StartupPath + "\\diabloui.dll") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\diabloui.dll")) { File.Copy(Application.StartupPath + "\\diabloui.dll", Application.StartupPath + "\\EquineData\\GameBackup\\diabloui.dll"); } if (File.Exists(Application.StartupPath + "\\Diablo.exe") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\Diablo.exe")) { File.Copy(Application.StartupPath + "\\Diablo.exe", Application.StartupPath + "\\EquineData\\GameBackup\\Diablo.exe"); } if (File.Exists(Application.StartupPath + "\\standard.snp") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\standard.snp")) { File.Copy(Application.StartupPath + "\\standard.snp", Application.StartupPath + "\\EquineData\\GameBackup\\standard.snp"); } if (File.Exists(Application.StartupPath + "\\battle.snp") && !File.Exists(Application.StartupPath + "\\EquineData\\GameBackup\\battle.snp")) { File.Copy(Application.StartupPath + "\\battle.snp", Application.StartupPath + "\\EquineData\\GameBackup\\battle.snp"); } } MessageBox.Show("Operation completed successfully!", "EQUINE", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Force update failed.\nWindows reported the error:\n" + ex.Message, "EQUINE", MessageBoxButtons.OK, MessageBoxIcon.Stop); } }
private void FormMain_Shown(object sender, EventArgs e) { string[] args = Environment.GetCommandLineArgs(); if (args.Length.Equals(3)) { foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(args[2]))) { process.WaitForExit(); } // Extract all the files. _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += (o, eventArgs) => { var path = Path.GetDirectoryName(args[2]); // Open an existing zip file for reading. ZipStorer zip = ZipStorer.Open(args[1], FileAccess.Read); // Read the central directory collection. List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); for (var index = 0; index < dir.Count; index++) { if (_backgroundWorker.CancellationPending) { eventArgs.Cancel = true; zip.Close(); return; } ZipStorer.ZipFileEntry entry = dir[index]; zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip)); _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip)); } zip.Close(); }; _backgroundWorker.ProgressChanged += (o, eventArgs) => { progressBar.Value = eventArgs.ProgressPercentage; labelInformation.Text = eventArgs.UserState.ToString(); }; _backgroundWorker.RunWorkerCompleted += (o, eventArgs) => { if (!eventArgs.Cancelled) { labelInformation.Text = @"Finished"; try { Process.Start(args[2]); } catch (Win32Exception exception) { if (exception.NativeErrorCode != 1223) { throw; } } Application.Exit(); } }; _backgroundWorker.RunWorkerAsync(); } }
private int PushToNuGetRepository(Execution execution, bool pushGitVersion, string platform, string commitHash) { if (pushGitVersion) { // We have to patch the package file in memory to include the Git hash // as part of the version. This is required so that Protobuild // can resolve source-equivalent binary packages. RedirectableConsole.WriteLine("Patching package file to include Git version information..."); using (var patchedPackage = new MemoryStream()) { using (var patchedPackageWriter = ZipStorer.Create(patchedPackage, string.Empty, true)) { using (var packageReader = ZipStorer.Open(execution.PackagePushFile, FileAccess.Read)) { var entries = packageReader.ReadCentralDir(); var progressRenderer = new PackagePatchProgressRenderer(entries.Count); var i = 0; foreach (var entry in packageReader.ReadCentralDir()) { if (entry.FilenameInZip.EndsWith(".nuspec") && !entry.FilenameInZip.Contains("/")) { // This is the NuGet specification file in the root of the package // that we need to patch. using (var fileStream = new MemoryStream()) { packageReader.ExtractFile(entry, fileStream); fileStream.Seek(0, SeekOrigin.Begin); string nuspecContent; using ( var reader = new StreamReader(fileStream, Encoding.UTF8, true, 4096, true)) { nuspecContent = reader.ReadToEnd(); var regex = new Regex("version\\>[^\\<]+\\<\\/version"); nuspecContent = regex.Replace(nuspecContent, "version>" + NuGetVersionHelper.CreateNuGetPackageVersion(commitHash, platform) + "</version"); using (var patchedFileStream = new MemoryStream()) { using ( var writer = new StreamWriter(patchedFileStream, Encoding.UTF8, 4096, true)) { writer.Write(nuspecContent); writer.Flush(); patchedFileStream.Seek(0, SeekOrigin.Begin); patchedPackageWriter.AddStream( entry.Method, entry.FilenameInZip, patchedFileStream, entry.ModifyTime, entry.Comment, true); } } } } } else { using (var fileStream = new MemoryStream()) { packageReader.ExtractFile(entry, fileStream); fileStream.Seek(0, SeekOrigin.Begin); patchedPackageWriter.AddStream( entry.Method, entry.FilenameInZip, fileStream, entry.ModifyTime, entry.Comment, true); } } i++; progressRenderer.SetProgress(i); } progressRenderer.FinalizeRendering(); } } patchedPackage.Seek(0, SeekOrigin.Begin); // Push the patched package to the NuGet repository. RedirectableConsole.WriteLine("Uploading package with Git version..."); return(this.PushNuGetBinary(execution.PackagePushUrl, execution.PackagePushApiKey, patchedPackage, execution.PackagePushIgnoreOnExisting)); } } else { RedirectableConsole.WriteLine("Uploading package with semantic version..."); using ( var stream = new FileStream(execution.PackagePushFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // Note about the true argument here: We always ignore a conflict for the semantic version, as // the build server may be pushing on every commit. In this scenario, developers will leave // the semantic version as-is until they're ready to release a new semantic version. return(this.PushNuGetBinary(execution.PackagePushUrl, execution.PackagePushApiKey, memoryStream, true)); } } } }
private void unzipEPubAndParseOpf() { if (RequestCancellation) { return; } /*string directoryName = Path.GetTempPath(); * if (!directoryName.EndsWith("" + Path.DirectorySeparatorChar)) * { * directoryName += Path.DirectorySeparatorChar; * }*/ string unzipDirectory = Path.Combine( Path.GetDirectoryName(m_Book_FilePath), //m_outDirectory, //FileDataProvider.EliminateForbiddenFileNameCharacters(m_Book_FilePath) //m_Book_FilePath.Replace('.', '_') m_Book_FilePath + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); #if ENABLE_SHARPZIP ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(m_Book_FilePath)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { if (RequestCancellation) { return; } string zipEntryName = Path.GetFileName(zipEntry.Name); if (!String.IsNullOrEmpty(zipEntryName)) // || zipEntryName.IndexOf(".ini") >= 0 { // string unzippedFilePath = Path.Combine(unzipDirectory, zipEntryName); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + zipEntry.Name; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } FileStream fileStream = File.Create(unzippedFilePath); //byte[] data = new byte[2 * 1024]; // 2 KB buffer //int bytesRead = 0; try { const uint BUFFER_SIZE = 1024 * 2; // 2 KB MAX BUFFER StreamUtils.Copy(zipInputStream, 0, fileStream, BUFFER_SIZE); //while ((bytesRead = zipInputStream.Read(data, 0, data.Length)) > 0) //{ // fileStream.Write(data, 0, bytesRead); //} } finally { fileStream.Close(); } } } zipInputStream.Close(); #else //ENABLE_SHARPZIP ZipStorer zip = ZipStorer.Open(File.OpenRead(m_Book_FilePath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { if (RequestCancellation) { return; } reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } //zip.Close(); zip.Dispose(); #endif //ENABLE_SHARPZIP string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); #if NET40 IEnumerable <FileInfo> opfFiles = dirInfo.EnumerateFiles("*.opf", SearchOption.AllDirectories); #else FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); #endif // string[] fileNames = Directory.GetFiles(unzipDirectory, "*.opf", //#if NET40 // SearchOption.AllDirectories //#endif // ); foreach (FileInfo fileInfo in opfFiles) { if (RequestCancellation) { return; } m_Book_FilePath = Path.Combine(unzipDirectory, fileInfo.FullName); m_OPF_ContainerRelativePath = null; openAndParseOPF(m_Book_FilePath); break; } } else { parseContainerXML(containerPath); } // string opfPath = ""; // string parentDir = Path.GetDirectoryName(opfPath); // while (!string.IsNullOrEmpty(parentDir)) // { // DirectoryInfo dirInfo = new DirectoryInfo(parentDir); // DirectoryInfo[] metaInfDirs = dirInfo.GetDirectories(@"META-INF", SearchOption.TopDirectoryOnly); // if (RequestCancellation) return; // foreach (DirectoryInfo dirInfo in metaInfDirs) // { // string containerPath = Path.Combine(parentDir, dirInfo.FullName + Path.DirectorySeparatorChar + @"container.xml"); // if (!File.Exists(containerPath)) // { //#if DEBUG // Debugger.Break(); //#endif // } // else // { // if (!parseContainerXML(containerPath)) // { // openAndParseOPF(opfPath); // } // } // break; // } // DirectoryInfo parentDirInfo = dirInfo.Parent; // if (parentDirInfo != null) // { // parentDir = parentDirInfo.FullName; // } // else // { // parentDir = null; // } // } // // final fallback // openAndParseOPF(opfPath); }
async Task InstallApp(string installRoot) { PreInstallTB.Visibility = Visibility.Visible; PreInstallTB.Text = "Идет установка ПО..."; InstallButton.IsEnabled = false; CancelButton.IsEnabled = false; ((Storyboard)InstallButtons.Resources["InstallButtonsDisappearStoryboard"]).Begin(); ((Storyboard)ComponentsLV.Resources["ComponentsLVDisappearStoryboard"]).Begin(); if (!Directory.Exists(CommonVariables.TMPDirPath)) { Directory.CreateDirectory(CommonVariables.TMPDirPath); } foreach (var currentComponent in InstallComponents) { if (currentComponent.Selected) { PreInstallTB.Text = $"Установка \"{currentComponent.DisplayName}\"..."; await Task.Run(() => { currentComponent.InstallLocation = currentComponent.InstallLocation .Replace("INSTALL_ROOT", installRoot); currentComponent.ExecutablePath = currentComponent.ExecutablePath .Replace("INSTALL_LOCATION", currentComponent.InstallLocation); currentComponent.DisplayIcon = currentComponent.DisplayIcon .Replace("INSTALL_LOCATION", currentComponent.InstallLocation); currentComponent.UninstallString = currentComponent.UninstallString .Replace("INSTALL_LOCATION", currentComponent.InstallLocation); var tmpFilename = Path.Combine(CommonVariables.TMPDirPath, currentComponent.ID); File.WriteAllBytes(tmpFilename, (byte[])ResourceSet.GetObject(currentComponent.ID.Replace('.', '_'))); if (!Directory.Exists(currentComponent.InstallLocation)) { Directory.CreateDirectory(currentComponent.InstallLocation); } var zip = ZipStorer.Open(tmpFilename, FileAccess.Read); foreach (var current in zip.ReadCentralDir()) { if (!current.FilenameInZip.EndsWith("\\") && !current.FilenameInZip.EndsWith("/")) { zip.ExtractFile(current, Path.Combine(currentComponent.InstallLocation, current.FilenameInZip)); } } zip.Close(); var componentMarkupResourceName = $"{currentComponent.ID.Replace('.', '_')}_APM"; File.WriteAllBytes(Path.Combine(Directory.GetParent(currentComponent.UninstallString).FullName, componentMarkupResourceName), (byte[])((DictionaryEntry)ResourceSet.OfType <object>().FirstOrDefault(c => ((DictionaryEntry)c).Key.ToString() == componentMarkupResourceName)).Value); File.Copy(MyFileName, currentComponent.UninstallString, true); RegistryManager.CreateApplicationEntry(currentComponent); LNKManager.CreateLinks(currentComponent, Path.Combine(CommonVariables.DesktopPath, $"{currentComponent.DisplayName}.lnk")); }); } } PreInstallTB.Text = "Удаление временных файлов..."; await Task.Run(() => { while (true) { try { Directory.Delete(CommonVariables.TMPDirPath, true); break; } catch (IOException) { Thread.Sleep(100); } } }); PreInstallTB.Text = "Установка успешно завершена!"; await Task.Run(() => Thread.Sleep(2000)); }