public string GetFile() { if (!Directory.Exists(Constans.Constans.PathToSaveFile)) { throw new Exception(Constans.Constans.AppDataFolderDosentExists); } string resultGeoJson = ""; var stream = HttpContext.Current.Request.GetBufferedInputStream(); StreamReader reader = new StreamReader(stream); reader.ReadToEnd(); var postedFile = HttpContext.Current.Request.Files[Constans.Constans.FormObjectName]; var ignore = HttpContext.Current.Request.InputStream; if (postedFile != null) { ClearDataDirectory(Constans.Constans.PathToSaveFile); var pathToZipFile = Path.Combine(Constans.Constans.PathToSaveFile, postedFile.FileName); postedFile.SaveAs(pathToZipFile); string fullPathToShpFile = ZipFileHelper.ExtractZipFile(pathToZipFile); IGeometryServices geometryServices = new NtsGeometryServices(); ShapeFileHelper shapeFileHelper = new ShapeFileHelper(fullPathToShpFile); resultGeoJson = shapeFileHelper.ConvertShapeFileToGeoJson(); ClearDataDirectory(Constans.Constans.PathToSaveFile); } return(resultGeoJson); }
/// <summary> /// Initializes the cdg library /// </summary> /// <param name="playlistItem"></param> private void InitializeCdgLibrary(PlaylistItem playlistItem) { IntPtr applicationHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle; IntPtr parentWindowHandle = new WindowInteropHelper(_videoPlayerWindow).Handle; string mp3FilePath = playlistItem.Song.FilePath; string cdgFilePath = playlistItem.Song.CdgFilePath; if (playlistItem.Song.Extension.Equals("zip")) { _zipFileHelper = new ZipFileHelper(); Song tmpUnzippedSong = _zipFileHelper.ExtractFileTemporarily(mp3FilePath); mp3FilePath = tmpUnzippedSong.FilePath; cdgFilePath = tmpUnzippedSong.CdgFilePath; } _cdgLibDllHandle = CdgLibraryWrapper.CDGPlayerOpenExt(applicationHandle, cdgFilePath, parentWindowHandle, 0); _videoPlayerWindow.VideoPlayer.Source = new Uri(mp3FilePath); _cdgWindowHeight = _videoPlayerWindow.Height; _cdgWindowWidth = _videoPlayerWindow.Width; CdgLibraryWrapper.CDGPlayerHeightSet(_cdgLibDllHandle, (int)_cdgWindowHeight); CdgLibraryWrapper.CDGPlayerWidthSet(_cdgLibDllHandle, (int)_cdgWindowWidth); }
static IContentProvider GetContentProvider(NormalizedPath path, IExecutionContext context) { if (path.IsNull) { throw new ExecutionException("Invalid directory"); } IFile zipFile = ZipFileHelper.CreateZipFile(context, path); return(zipFile.GetContentProvider()); }
public ReadWriteZipFile(string filename, bool create = false) { // SharpZipLib breaks when asked to update archives loaded from outside streams or files // We can work around this by creating a clean in-memory-only file, cutting all outside references if (!create) { new MemoryStream(File.ReadAllBytes(filename)).CopyTo(pkgStream); } pkgStream.Position = 0; pkg = ZipFileHelper.Create(pkgStream); Name = filename; }
private void btnZipAndMailTo_Click(object sender, RoutedEventArgs e) { var paths = DocumentsForMail.Where(x => !String.IsNullOrEmpty(x.Path)).Select(x => x.Path).Distinct().ToList(); if (paths.Count() < 1) { MainWindow.ErrorMessage = ((string)Application.Current.FindResource("OdaberiBarJedanDokumentUzvicnik")); return; } try { List <string> completedPaths = new List <string>(); var azureClient = new AzureDataClient(); foreach (var item in paths) { var file = azureClient.GetFile(item); var localPath = azureClient.DownloadFileToOpen(file, (progress, total) => { }); completedPaths.Add(localPath); } System.Windows.Forms.FolderBrowserDialog folderBrowser = new System.Windows.Forms.FolderBrowserDialog(); var result = folderBrowser.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { var path = ZipFileHelper.MakeArchiveFromFiles(completedPaths, folderBrowser.SelectedPath); if (!String.IsNullOrEmpty(path)) { try { string outlookPath = AppConfigurationHelper.Configuration?.OutlookDefinedPath ?? ""; Process.Start($"{outlookPath}", $"/a \"{path}\" /c ipm.note "); } catch (Exception error) { MainWindow.ErrorMessage = ((string)Application.Current.FindResource("OutlookNijeInstaliranIliNijePovezanUzvicnik")); } } } } catch (Exception ex) { } }
/// <summary> /// Stops the playback /// </summary> public void Stop() { if (IsCdgLibraryInitialized()) { _setCdgPositionTimer.Stop(); CdgLibraryWrapper.CDGPlayerHide(_cdgLibDllHandle); CdgLibraryWrapper.CDGPlayerClose(_cdgLibDllHandle); _cdgLibDllHandle = IntPtr.Zero; _videoPlayerWindow.VideoPlayer.Stop(); if (_zipFileHelper != null) { _zipFileHelper.Dispose(); _zipFileHelper = null; } } }
private static void ZipFiles(string tempDir, DateTime dateToUse, string location_name) { string zipFile = "EMR_" + dateToUse.ToString("MM_dd_yyyy") + ".kjzip"; ArrayList filesToZip = new ArrayList(); foreach (string file in Directory.GetFiles(tempDir)) { FileInfo info = new FileInfo(file); if (info.Extension != ".kjzip") { filesToZip.Add(file); Log log = new Log(ssDataLayer) { FileName = file, Image = false, Action = Actions.Zip, Date_created = DateTime.Now, Machine = Environment.MachineName }; log.Save(); } } ZipFileHelper.CreateZipFile(tempDir + "\\" + zipFile, (string[])filesToZip.ToArray(typeof(string))); string message = filesToZip.Count + " were zipped for " + location_name + " by " + Environment.MachineName; message += "<br /><a href=\"http://SSLog/log.aspx?d=" + DateTime.Now.ToString("yyyy/MM/dd") + "&a=" + (int)Actions.Zip + "&l=" + location_name + "\">Click to see which files were Zipped for " + location_name + " </>"; string ssServer = SiteServers.MachineNameForLocation(ssDataLayer, location_name); if (!string.IsNullOrEmpty(ssServer) && ssServer != "Network") { message += "<br /><a href=\"http://" + ssServer + "/SSLog_root/log.aspx?d=" + DateTime.Now.ToString("yyyy/MM/dd") + "&a=" + (int)Actions.Unzip + "\">Click to see which files were unzipped by the Site Server at this location</>"; } else { message += "<br /><a href=\"http://SSLog/log.aspx?d=" + DateTime.Now.ToString("yyyy/MM/dd") + "&a=" + (int)Actions.Unzip + "&l=" + location_name + "\">Click to see which files were Unzipped for " + location_name + " </>"; } string subject = "Files Zipped for " + location_name + " by " + Environment.MachineName; SendEmail(subject, message, MailPriority.Normal); }
/// <summary> /// Parses the given lists of video files and adds them to the library /// </summary> /// <param name="zipFiles"></param> /// <param name="extension">file extension</param> /// <param name="songsInLibrary">list is filled within this method</param> private static void ParseZipFiles(IEnumerable <string> zipFiles, string extension, ObservableCollection <Song> songsInLibrary) { foreach (string zipFilePath in zipFiles) { using (ZipFileHelper zipFileHelper = new ZipFileHelper()) { Song zipFileSong = new Song { FilePath = zipFilePath, Extension = extension }; Song tmpSong = zipFileHelper.ExtractFileTemporarily(zipFilePath); if (string.IsNullOrEmpty(tmpSong.FilePath) == false && string.IsNullOrEmpty(tmpSong.CdgFilePath) == false) { ParseArtistAndTitle(tmpSong.FilePath, zipFileSong); songsInLibrary.Add(zipFileSong); } } } }
public async Task <byte[]> Images(int?contentId) => await ZipFileHelper.ReadBytesFromResource(_assembly, LocalSourceDataFile, $"images_{contentId}.zip");
public async Task <JsonContentSummaries> JsonContentSummaries() { var text = await ZipFileHelper.ReadStringFromResource(_assembly, LocalSourceDataFile, "summaries.json"); return(JsonConvert.DeserializeObject <JsonContentSummaries>(text)); }
public ReadOnlyZipFile(Stream s, string filename) { Name = filename; pkg = ZipFileHelper.Create(s); }
public async Task <byte[]> Images() => await ZipFileHelper.ReadBytesFromResource(_assembly, LocalSourceDataFile, "images.zip");
/// <summary> /// 安装(异步) /// </summary> /// <returns></returns public async Task <ForgeInstallerResultModel> InstallAsync() { using var archive = ZipFile.OpenRead(this.ForgeInstallerPackagePath); var processOutputs = new List <string>(); var processErrorOutputs = new List <string>(); #region Get version.json OnProgressChanged(0.1, $"Installing Forge Loader - Initializing"); var versionJson = await ZipFileHelper.GetStringFromJsonEntryAsync (archive.Entries.First(x => x.Name.Equals("version.json", StringComparison.OrdinalIgnoreCase))); var versionModel = JsonConvert.DeserializeObject <CoreModel>(versionJson); var versionJsonFile = new FileInfo ($"{PathHelper.GetVersionFolder(this.CoreLocator.Root, versionModel.Id)}{PathHelper.X}{versionModel.Id}.json"); if (!versionJsonFile.Directory.Exists) { versionJsonFile.Directory.Create(); } File.WriteAllText(versionJsonFile.FullName, versionJson); OnProgressChanged(0.15, $"Installing Forge Loader - Initializing"); #endregion #region Get install_profile.json var forgeInstallProfile = await ZipFileHelper.GetObjectFromJsonEntryAsync <ForgeInstallProfileModel> (archive.Entries.First(x => x.Name.Equals("install_profile.json", StringComparison.OrdinalIgnoreCase))); var forgeVersion = forgeInstallProfile.Version.Replace("-forge-", "-"); forgeInstallProfile.Data["BINPATCH"].Client = $"[net.minecraftforge:forge:{forgeVersion}:clientdata@lzma]"; forgeInstallProfile.Data["BINPATCH"].Server = $"[net.minecraftforge:forge:{forgeVersion}:serverdata@lzma]"; OnProgressChanged(0.2, $"Installing Forge Loader - Initialized"); #endregion #region Get Lzma OnProgressChanged(0.3, $"Installing Forge Loader - Extracting Files"); var clientLzma = archive.Entries.FirstOrDefault(e => e.FullName.Equals("data/client.lzma", StringComparison.OrdinalIgnoreCase)); var serverLzma = archive.Entries.FirstOrDefault(e => e.FullName.Equals("data/server.lzma", StringComparison.OrdinalIgnoreCase)); var clientLzmaFile = new FileInfo(GetMavenFilePath(forgeInstallProfile.Data["BINPATCH"].Client)); var serverLzmaFile = new FileInfo(GetMavenFilePath(forgeInstallProfile.Data["BINPATCH"].Server)); await ZipFileHelper.WriteAsync(clientLzma, clientLzmaFile.Directory.FullName, clientLzmaFile.Name); await ZipFileHelper.WriteAsync(serverLzma, serverLzmaFile.Directory.FullName, serverLzmaFile.Name); #endregion #region Extract Forge Jar var forgeJar = archive.Entries.FirstOrDefault (e => e.FullName.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}.jar", StringComparison.OrdinalIgnoreCase)); var forgeUniversalJar = archive.Entries.FirstOrDefault (e => e.FullName.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}-universal.jar", StringComparison.OrdinalIgnoreCase)); if (forgeJar != default) { if (forgeUniversalJar != default) { var fileUniversalJar = new FileInfo($"{PathHelper.GetLibrariesFolder(this.CoreLocator.Root)}{PathHelper.X}{forgeUniversalJar.FullName.Replace("maven/", "").Replace("/", PathHelper.X)}"); if (!fileUniversalJar.Directory.Exists) { fileUniversalJar.Directory.Create(); } await ZipFileHelper.WriteAsync(forgeUniversalJar, fileUniversalJar.Directory.FullName); } var file = new FileInfo($"{PathHelper.GetLibrariesFolder(this.CoreLocator.Root)}{PathHelper.X}{forgeJar.FullName.Replace("maven/", "").Replace("/", PathHelper.X)}"); if (!file.Directory.Exists) { file.Directory.Create(); } await ZipFileHelper.WriteAsync(forgeJar, file.Directory.FullName); } OnProgressChanged(0.4, $"Installing Forge Loader - Extracted"); #endregion #region Parser Processor OnProgressChanged(0.4, $"Installing Forge Loader - Parsering Processor"); var replaceValues = new Dictionary <string, string> { { "{SIDE}", "client" }, { "{MINECRAFT_JAR}", $"{PathHelper.GetVersionFolder(this.CoreLocator.Root,this.McVersionId)}{PathHelper.X}{this.McVersionId}.jar" }, { "{MINECRAFT_VERSION}", this.McVersion }, { "{ROOT}", this.CoreLocator.Root }, { "{INSTALLER}", this.ForgeInstallerPackagePath }, { "{LIBRARY_DIR}", PathHelper.GetLibrariesFolder(this.CoreLocator.Root) }, { "/", PathHelper.X } }; var replaceArgs = forgeInstallProfile.Data.Select(x => ($"{{{x.Key}}}", x.Value.Client)).ToDictionary(k => k.Item1, v => { if (v.Client.Contains("[") && v.Client.Contains("]")) { return(GetMavenFilePath(v.Client)); } return(v.Client); }); for (int i = 0; i < forgeInstallProfile.Processors.Count; i++) { var processModel = forgeInstallProfile.Processors[i]; if (processModel.Sides != null && !processModel.Sides.Any(s => s.Equals("client", StringComparison.OrdinalIgnoreCase))) { forgeInstallProfile.Processors.RemoveAt(i); continue; } } for (int i = 0; i < forgeInstallProfile.Processors.Count; i++) { var processModel = forgeInstallProfile.Processors[i]; processModel.Args = StringHelper.Replace(processModel.Args, replaceValues).ToList(); processModel.Args = StringHelper.Replace(processModel.Args, replaceArgs).ToList(); processModel.Args = processModel.Args.Select(x => { if (x.Contains("[") && x.Contains("]")) { return($"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = x.TrimStart('[').TrimEnd(']') }.GetRelativePath())}"); } return(x); }).ToList(); if (processModel.Outputs != default) { processModel.Outputs = processModel.Outputs.Select (x => (StringHelper.Replace(x.Key, replaceArgs), StringHelper.Replace(x.Value, replaceArgs))).ToDictionary(k => k.Item1, v => v.Item2); } forgeInstallProfile.Processors[i] = processModel; } OnProgressChanged(0.5, $"Installing Forge Loader - Parsered Processor"); #endregion #region Download Libraries OnProgressChanged(0.5, $"Installing Forge Loader - Downloading Libraries"); for (int i = 0; i < versionModel.Libraries.Count; i++) { if (versionModel.Libraries[i].Name == forgeInstallProfile.Path) { versionModel.Libraries.Remove(versionModel.Libraries[i]); } } for (int i = 0; i < forgeInstallProfile.Libraries.Count; i++) { if (forgeInstallProfile.Libraries[i].Name == $"{forgeInstallProfile.Path}:universal") { forgeInstallProfile.Libraries.Remove(forgeInstallProfile.Libraries[i]); } } async Task Download(IEnumerable <HttpDownloadRequest> requests) { var manyBlock = new TransformManyBlock <IEnumerable <HttpDownloadRequest>, HttpDownloadRequest>(x => x); var blockOptions = new ExecutionDataflowBlockOptions { BoundedCapacity = DependencesCompleter.MaxThread, MaxDegreeOfParallelism = DependencesCompleter.MaxThread }; var actionBlock = new ActionBlock <HttpDownloadRequest>(async x => { try { if (!x.Directory.Exists) { x.Directory.Create(); } var res = await HttpHelper.HttpDownloadAsync(x, x.FileName); if (res.HttpStatusCode != HttpStatusCode.OK) { this.ErrorDownload.Add(x); } } catch { throw; } }, blockOptions); var linkOptions = new DataflowLinkOptions { PropagateCompletion = true }; _ = manyBlock.LinkTo(actionBlock, linkOptions); _ = manyBlock.Post(requests); manyBlock.Complete(); await actionBlock.Completion; GC.Collect(); } var downloadList = versionModel.Libraries.Union(forgeInstallProfile.Libraries).Select(x => { var result = x.GetDownloadRequest(this.CoreLocator.Root, true); if (SystemConfiguration.Api.Url != new Mojang().Url) { result.Url = result.Url.Replace("https://maven.minecraftforge.net", $"{SystemConfiguration.Api.Url}/maven"); } return(result); }); await Download(downloadList); //Try Again if (ErrorDownload.Count > 0) { await Download(ErrorDownload.Select(x => { x.Url = x.Url.Replace($"{SystemConfiguration.Api.Url}/maven", "https://maven.minecraftforge.net"); return(x); })); } OnProgressChanged(0.8, $"Installing Forge Loader - Downloaded Libraries"); #endregion #region Run Process OnProgressChanged(0.8, $"Installing Forge Loader - Processing"); foreach (var process in forgeInstallProfile.Processors) { string JarFile = $"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = process.Jar }.GetRelativePath())}"; using var JarFileArchive = ZipFile.OpenRead(JarFile); var libEntry = JarFileArchive.Entries.FirstOrDefault(e => e.FullName.Equals("META-INF/MANIFEST.MF", StringComparison.OrdinalIgnoreCase)); string[] lines = (await ZipFileHelper.GetStringFromJsonEntryAsync(libEntry)).Split("\r\n"); var mainClass = lines.ToList().FirstOrDefault(x => x.Contains("Main-Class: ")).Replace("Main-Class: ", ""); var libs = new List <string>() { process.Jar }.Concat(process.Classpath); var classpath = libs.Select(x => $"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = x }.GetRelativePath())}"); var parameter = new List <string> { "-cp", $"\"{string.Join(ArgumentsBuilder.Separator,classpath)}\"", mainClass }; parameter.AddRange(process.Args); var processContainer = new ProcessContainer(new ProcessStartInfo(JavaPath) { Arguments = string.Join(" ", parameter), WorkingDirectory = this.CoreLocator.Root }); processContainer.Start(); await processContainer.Process.WaitForExitAsync(); processOutputs.AddRange(processContainer.OutputData); processErrorOutputs.AddRange(processContainer.ErrorData); processContainer.Dispose(); } OnProgressChanged(0.9, $"Installing Forge Loader - Processed"); #endregion OnProgressChanged(1.0, $"Installing Forge Loader - Finished"); if (processErrorOutputs.Count > 0) { return new ForgeInstallerResultModel { IsSuccessful = false, Message = $"Failed Install Forge-{forgeVersion}!", ProcessOutput = processOutputs, ProcessErrorOutput = processErrorOutputs } } ; return(new ForgeInstallerResultModel { IsSuccessful = true, Message = $"Successfully Install Forge-{forgeVersion}!", ProcessOutput = processOutputs, ProcessErrorOutput = processErrorOutputs }); }
public static void Main111() { var files = Directory.EnumerateFiles(@"d:\", "*.gz*", SearchOption.TopDirectoryOnly); foreach (var file in files) { var r = false; string path = string.Empty; try { if ( ZipFileHelper .Decompress ( file , @"d:\temp" , (x) => { var s = ".Gz"; int p = x.ToLower().LastIndexOf(s.ToLower()); if (p > 0) { x = x.Remove(p + 1, s.Length); } return(x); } , out path ) ) { r = PathFileHelper .MoveFileTo ( path , @"d:\Temp" , @"d:\Temp2" , true ); } } catch (Exception e) { string log = string .Format ( "Process file: [{1}] caught exception:{0}{2}" , "\r\n" , file , e.ToString() ); Console.Error.WriteLine(log); //EventLogHelper // .WriteEventLogEntry // ( // "" // , 1001 // , log // , 101 // , EventLogEntryType.Error // ); r = false; } if (r) { PathFileHelper .MoveFileTo ( file , @"d:\" , @"d:\Temp3" , true ); Console.WriteLine("ok: {0}", file); } else { PathFileHelper .MoveFileTo ( file , @"d:\Temp" , @"d:\Temp4" , true ); } } Console.ReadLine(); }
public static ScormAnalysisReport TryCreate(FileStream fileStream) { return(new ScormAnalysisReport(ZipFileHelper.GetFileStreamAsZipFile(fileStream))); }
public ZippedImagePyramidDataSource(string worldFilePyramidFileName, Func <int, int, int, string> fileNameRule = null, Func <string, TileInfo> inverseFunction = null) { if (!System.IO.File.Exists(worldFilePyramidFileName)) { throw new NotImplementedException(); } _archive = System.IO.Compression.ZipFile.OpenRead(worldFilePyramidFileName); if (fileNameRule == null) { //_fileNameRule = (z, r, c) => System.IO.Path.Combine(z.ToString(), $"{z}, {r}, {c}.jpg"); _fileNameRule = _defaultFileNameRule; } else { _fileNameRule = fileNameRule; } if (inverseFunction == null) { _inverseFunction = _defaultInverseFunction; } else { _inverseFunction = inverseFunction; } var extentString = ZipFileHelper.ReadAsString(_archive, _extentFileName); if (extentString == null || extentString.Contains("NaN")) { _archive.Dispose(); _archive = System.IO.Compression.ZipFile.Open(worldFilePyramidFileName, System.IO.Compression.ZipArchiveMode.Update); var lastPyramid = _archive.Entries.Max(e => { var folder = e.FullName.Replace($"\\{e.Name}", string.Empty); int zoom = -1; int.TryParse(folder, out zoom); return(zoom); } ); this.Extent = BoundingBox.GetMergedBoundingBox( _archive.Entries.Where(e => e.FullName.StartsWith(lastPyramid.ToString())) .Select(e => _inverseFunction(e.FullName).WebMercatorExtent), true); ZipFileHelper.WriteString(_archive, Newtonsoft.Json.JsonConvert.SerializeObject(Extent), _extentFileName); _archive.Dispose(); _archive = System.IO.Compression.ZipFile.OpenRead(worldFilePyramidFileName); } else { this.Extent = JsonHelper.ParseFromJson <BoundingBox>(extentString); } }
public async Task <byte[]> Images() => await ZipFileHelper.ReadBytesFromFile(_contentsDataFile, "images.zip");
public async Task <JsonContentDetail> JsonContentDetail(int?contentId) { var text = await ZipFileHelper.ReadStringFromFile(new FileInfo(LocalSourceDataFile), $"detail_{contentId}.json"); return(JsonConvert.DeserializeObject <JsonContentDetail>(text)); }
public async Task <byte[]> Images() => await ZipFileHelper.ReadBytesFromFile(new FileInfo(LocalSourceDataFile), "images.zip");
public async Task <JsonContentSummaries> JsonContentSummaries() { var text = await ZipFileHelper.ReadStringFromFile(_contentsDataFile, "summaries.json"); return(JsonConvert.DeserializeObject <JsonContentSummaries>(text)); }
public async Task <byte[]> Images(int?contentId) => await ZipFileHelper.ReadBytesFromFile(_contentsDataFile, $"images_{contentId}.zip");
public async Task <byte[]> Images(int?contentId) => await ZipFileHelper.ReadBytesFromFile(new FileInfo(LocalSourceDataFile), $"images_{contentId}.zip");
void ShowDownloadDialog() { getStatusText = () => "Fetching list of mirrors..."; progressBar.Indeterminate = true; var retryButton = panel.Get <ButtonWidget>("RETRY_BUTTON"); retryButton.IsVisible = () => false; var cancelButton = panel.Get <ButtonWidget>("CANCEL_BUTTON"); var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Action deleteTempFile = () => { Log.Write("install", "Deleting temporary file " + file); File.Delete(file); }; Action <DownloadProgressChangedEventArgs> onDownloadProgress = i => { var dataReceived = 0.0f; var dataTotal = 0.0f; var mag = 0; var dataSuffix = ""; if (i.TotalBytesToReceive < 0) { mag = (int)Math.Log(i.BytesReceived, 1024); dataReceived = i.BytesReceived / (float)(1L << (mag * 10)); dataSuffix = SizeSuffixes[mag]; getStatusText = () => "Downloading from {2} {0:0.00} {1}".F(dataReceived, dataSuffix, downloadHost ?? "unknown host"); progressBar.Indeterminate = true; } else { mag = (int)Math.Log(i.TotalBytesToReceive, 1024); dataTotal = i.TotalBytesToReceive / (float)(1L << (mag * 10)); dataReceived = i.BytesReceived / (float)(1L << (mag * 10)); dataSuffix = SizeSuffixes[mag]; getStatusText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(i.ProgressPercentage, dataReceived, dataTotal, dataSuffix, downloadHost ?? "unknown host"); progressBar.Indeterminate = false; } progressBar.Percentage = i.ProgressPercentage; }; Action <string> onExtractProgress = s => Game.RunAfterTick(() => getStatusText = () => s); Action <string> onError = s => Game.RunAfterTick(() => { Log.Write("install", "Download failed: " + s); progressBar.Indeterminate = false; progressBar.Percentage = 100; getStatusText = () => "Error: " + s; retryButton.IsVisible = () => true; cancelButton.OnClick = Ui.CloseWindow; }); Action <AsyncCompletedEventArgs> onDownloadComplete = i => { if (i.Cancelled) { deleteTempFile(); Game.RunAfterTick(Ui.CloseWindow); return; } if (i.Error != null) { deleteTempFile(); onError(Download.FormatErrorMessage(i.Error)); return; } // Automatically extract getStatusText = () => "Extracting..."; progressBar.Indeterminate = true; var extracted = new List <string>(); try { using (var stream = File.OpenRead(file)) using (var z = ZipFileHelper.Create(stream)) { foreach (var kv in download.Extract) { var entry = z.GetEntry(kv.Value); if (entry == null || !entry.IsFile) { continue; } onExtractProgress("Extracting " + entry.Name); Log.Write("install", "Extracting " + entry.Name); var targetPath = Platform.ResolvePath(kv.Key); Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); extracted.Add(targetPath); using (var zz = z.GetInputStream(entry)) using (var f = File.Create(targetPath)) zz.CopyTo(f); } z.Close(); } Game.RunAfterTick(() => { Ui.CloseWindow(); onSuccess(); }); } catch (Exception e) { Log.Write("install", "Archive extraction failed: " + e.ToString()); foreach (var f in extracted) { Log.Write("install", "Deleting " + f); File.Delete(f); } onError("Archive extraction failed"); } finally { deleteTempFile(); } }; Action <string> downloadUrl = url => { Log.Write("install", "Downloading " + url); downloadHost = new Uri(url).Host; var dl = new Download(url, file, onDownloadProgress, onDownloadComplete); cancelButton.OnClick = dl.CancelAsync; retryButton.OnClick = ShowDownloadDialog; }; if (download.MirrorList != null) { Log.Write("install", "Fetching mirrors from " + download.MirrorList); Action <DownloadDataCompletedEventArgs> onFetchMirrorsComplete = i => { progressBar.Indeterminate = true; if (i.Cancelled) { Game.RunAfterTick(Ui.CloseWindow); return; } if (i.Error != null) { onError(Download.FormatErrorMessage(i.Error)); return; } try { var data = Encoding.UTF8.GetString(i.Result); var mirrorList = data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); downloadUrl(mirrorList.Random(new MersenneTwister())); } catch (Exception e) { Log.Write("install", "Mirror selection failed with error:"); Log.Write("install", e.ToString()); onError("Online mirror is not available. Please install from an original disc."); } }; var updateMirrors = new Download(download.MirrorList, onDownloadProgress, onFetchMirrorsComplete); cancelButton.OnClick = updateMirrors.CancelAsync; retryButton.OnClick = ShowDownloadDialog; } else { downloadUrl(download.URL); } }
public async Task <JsonContentSummaries> JsonContentSummaries() { var text = await ZipFileHelper.ReadStringFromFile(new FileInfo(LocalSourceDataFile), "summaries.json"); return(JsonConvert.DeserializeObject <JsonContentSummaries>(text)); }
private void UnZipFiles() { string zippath = GetPath("IZ"); string extractPath = GetPath("IE"); if (String.IsNullOrEmpty(zippath) || String.IsNullOrEmpty(extractPath)) { return; } string unzipped = zippath + "UnZipped\\"; if (!Directory.Exists(unzipped)) { Directory.CreateDirectory(unzipped); } string moveTo = zippath + "Temp\\"; if (!Directory.Exists(moveTo)) { Directory.CreateDirectory(moveTo); } foreach (string file in Directory.GetFiles(moveTo)) { FileInfo info = new FileInfo(file); if (info.Extension.ToLower() != ".jtzip") { continue; } string dir = info.DirectoryName; string movedFile = file.Replace(dir, unzipped); if (File.Exists(movedFile)) { File.Delete(movedFile); } File.Move(file, movedFile); } foreach (string file in Directory.GetFiles(zippath)) { FileInfo info = new FileInfo(file); if (info.Extension.ToLower() != ".jtzip") { continue; } string dir = info.DirectoryName; string movedFile = file.Replace(dir, moveTo); if (File.Exists(movedFile)) { File.Delete(movedFile); } File.Move(file, movedFile); } foreach (string file in Directory.GetFiles(moveTo)) { ZipFileHelper.ExtractZipFile(file, extractPath); } ArrayList emailList = new ArrayList(); AddItemsToEmail(extractPath, emailList); if (!fromCMD) { return; } string subject = "Images Unzipped by " + Environment.MachineName; string message = "<br />" + emailList.Count + " " + subject; message += "<br /><a href=\"http://SSLog/log.aspx?d=" + DateTime.Now.ToString("yyyy/MM/dd") + "&a=" + (int)Actions.Unzip + "\">Click to see which files were Unzipped</>"; SendEmail(subject, message, MailPriority.Normal); Application.Exit(); }
protected override IEnumerable <IDocument> ExecuteConfig(IDocument input, IExecutionContext context, DirectoryPath value) => context.CloneOrCreateDocument(input, ZipFileHelper.CreateZipFile(context, value).GetContentProvider()).Yield();
/// <summary> /// 安装(异步) /// </summary> /// <returns></returns> public async Task <ForgeInstallerResultModel> InstallAsync() { using var archive = ZipFile.OpenRead(this.ForgeInstallerPackagePath); #region Get install_profile.json OnProgressChanged(0.1, $"Installing Forge Loader - Initializing"); var forgeInstallProfile = await ZipFileHelper.GetObjectFromJsonEntryAsync <LegacyForgeInstallProfileModel> (archive.Entries.First(x => x.Name.Equals("install_profile.json", StringComparison.OrdinalIgnoreCase))); #endregion #region Get version.json var versionJsonFile = new FileInfo ($"{PathHelper.GetVersionFolder(this.CoreLocator.Root, forgeInstallProfile.Install.Target)}{PathHelper.X}{forgeInstallProfile.Install.Target}.json"); if (!versionJsonFile.Directory.Exists) { versionJsonFile.Directory.Create(); } File.WriteAllText(versionJsonFile.FullName, forgeInstallProfile.VersionInfo.ToString()); OnProgressChanged(0.2, $"Installing Forge Loader - Initialized"); #endregion #region Extract Forge Jar OnProgressChanged(0.3, $"Installing Forge Loader - Extracting Files"); var legacyJarEntry = archive.Entries.FirstOrDefault(e => e.Name.Equals(forgeInstallProfile.Install.FilePath, StringComparison.OrdinalIgnoreCase)); var model = JsonConvert.DeserializeObject <CoreModel>(forgeInstallProfile.VersionInfo.ToString()); var lib = model.Libraries.First(x => x.Name.StartsWith("net.minecraftforge:forge", StringComparison.OrdinalIgnoreCase)); var fileLib = new FileInfo(Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), lib.GetRelativePath())); await ZipFileHelper.WriteAsync(legacyJarEntry, fileLib.Directory.FullName, fileLib.Name); OnProgressChanged(0.4, $"Installing Forge Loader - Extracted"); #endregion #region Download Libraries OnProgressChanged(0.5, $"Installing Forge Loader - Downloading Libraries"); async Task Download(IEnumerable <HttpDownloadRequest> requests) { var manyBlock = new TransformManyBlock <IEnumerable <HttpDownloadRequest>, HttpDownloadRequest>(x => x); var blockOptions = new ExecutionDataflowBlockOptions { BoundedCapacity = DependencesCompleter.MaxThread, MaxDegreeOfParallelism = DependencesCompleter.MaxThread }; var actionBlock = new ActionBlock <HttpDownloadRequest>(async x => { try { if (!x.Directory.Exists) { x.Directory.Create(); } var res = await HttpHelper.HttpDownloadAsync(x, x.FileName); if (res.HttpStatusCode != HttpStatusCode.OK) { this.ErrorDownload.Add(x); } } catch { throw; } }, blockOptions); var linkOptions = new DataflowLinkOptions { PropagateCompletion = true }; _ = manyBlock.LinkTo(actionBlock, linkOptions); _ = manyBlock.Post(requests); manyBlock.Complete(); await actionBlock.Completion; GC.Collect(); } var downloadList = model.Libraries.Select(x => x.GetDownloadRequest(this.CoreLocator.Root)).ToList(); downloadList.Remove(downloadList.First(x => x.Url.Equals(lib.GetDownloadRequest(this.CoreLocator.Root).Url))); await Download(downloadList); //Try Again if (ErrorDownload.Count > 0) { await Download(ErrorDownload.Select(x => { x.Url = x.Url.Replace($"{SystemConfiguration.Api.Url}/maven", "https://maven.minecraftforge.net"); return(x); })); } OnProgressChanged(0.8, $"Installing Forge Loader - Downloaded Libraries"); #endregion OnProgressChanged(1.0, $"Installing Forge Loader - Finished"); return(new ForgeInstallerResultModel { IsSuccessful = true, Message = $"Successfully Install {forgeInstallProfile.Install.Target}!" }); }