public Stream OpenStream() { if (_stream == null) { _stream = _zipArchiveEntry?.Open(); } else if (!_stream.CanRead) { _stream.Close(); _stream = _zipArchiveEntry?.Open(); } return(_stream); }
static FeedEntryInfo GetFeedEntryInfo(string vsixPath, string destination) { string fileName = Path.GetFileName(vsixPath); string destinationPath = Path.Combine(destination, fileName ?? throw new ArgumentNullException(nameof(vsixPath))); using (ZipArchive zipArchive = ZipFile.Open(destinationPath, ZipArchiveMode.Read)) { ZipArchiveEntry entry = zipArchive.GetEntry(ExtensionVsixManifest); XDocument doc; using (Stream stream = entry?.Open()) { doc = XDocument.Load(stream); } XElement metadataElement = GetElement(doc.Root, "Metadata"); XElement identityElement = GetElement(metadataElement, "Identity"); return(new FeedEntryInfo() { Id = GetAttributeValue(identityElement, "Id"), Author = GetAttributeValue(identityElement, "Publisher"), Title = GetElement(metadataElement, "DisplayName").Value, Description = GetElement(metadataElement, "Description").Value, Version = GetAttributeValue(identityElement, "Version") }); } }
private Stream GetPerfScriptStream(string path, out ZipArchive archive) { archive = null; if (path.EndsWith(".zip")) { archive = ZipFile.OpenRead(path); ZipArchiveEntry foundEntry = null; foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWithOneOf(PerfDumpSuffixes)) { foundEntry = entry; break; } } return(foundEntry?.Open()); } else { if (path.EndsWithOneOf(PerfDumpSuffixes)) { return(new FileStream(path, FileMode.Open)); } } throw new FileNotFoundException("Invalid perf script file or no perf script file found in the specified archive."); }
private byte[] Uncompress(byte[] data) { using (var outputStream = new MemoryStream()) using (var inputStream = new MemoryStream(data)) { ZipArchive archive = new ZipArchive(inputStream); ZipArchiveEntry entry = archive.Entries.FirstOrDefault(x => x.Name.Equals(PeFileName)); entry?.Open().CopyTo(outputStream); return(outputStream.ToArray()); } }
private Stream GetPerfScriptStream(string path, out ZipArchive archive) { archive = null; if (path.EndsWith(".trace.zip")) { archive = ZipFile.OpenRead(path); ZipArchiveEntry foundEntry = null; foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".data.txt")) { foundEntry = entry; break; } } return(foundEntry?.Open()); } else { return(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)); } }
private static async Task <string> GetEntryContentsAsync(ZipArchiveEntry entry) { using var fileReader = new StreamReader(entry.Open()); return(await fileReader.ReadToEndAsync().ConfigureAwait(false)); }
private void Createbtn_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(PkgName.Text)) { MessageBox.Show("Error", "A package name must be declared!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(PkgVersion.Text)) { MessageBox.Show("Error", "A package version must be declared!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(Auths.Text)) { MessageBox.Show("Error", "An author must be declared!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(ResourceFolderBox.Text)) { MessageBox.Show("Error", "Resource folder must be declared!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DirectoryInfo Resource; try { Resource = new DirectoryInfo(ResourceFolderBox.Text); } catch { MessageBox.Show("Error", "Invalid resource path!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!Resource.Exists) { MessageBox.Show("Error", "Resource folder does not exist!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } SaveFileDialog sfDialog = new SaveFileDialog { Filter = "Package File | *.pkg", DefaultExt = "pkg" }; if (sfDialog.ShowDialog() == DialogResult.OK) { FileInfo SaveLocation = new FileInfo(sfDialog.FileName); if (SaveLocation.Exists) { SaveLocation.Delete(); } using (ZipArchive zip = new ZipArchive(SaveLocation.Create(), ZipArchiveMode.Update, false)) { Uri uri; if (checkBox1.Checked) { try { uri = new Uri(UrlBox.Text); } catch { MessageBox.Show("Invalid URL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { uri = null; foreach (FileInfo file in Resource.GetFiles("*", SearchOption.AllDirectories)) { ZipArchiveEntry entry = zip.CreateEntry(file.FullName.Replace(Resource.FullName, $"Resource{Path.DirectorySeparatorChar}{PathBox.Text}")); using (Stream f = file.OpenRead()) using (Stream d = entry.Open()) f.CopyTo(d); } } Package package = new Package(PkgName.Text, Auths.Text, DateTime.Now, PkgVersion.Text, Resource.EnumerateFiles("*", SearchOption.AllDirectories).Select(f => f.FullName.Replace(Resource.FullName + "\\", "")).ToArray(), uri); using (StreamWriter writer = new StreamWriter(zip.CreateEntry("Package.json").Open())) { writer.Write(JsonConvert.SerializeObject(package)); } } } }
private static CreateFileEntryResult CreateFileEntry( ZipArchive zip, string templateFilename, PlayerMedalInfo playerMedalInfo, Tenant tenant, PostModel postModel) { var top3ValidResults = playerMedalInfo.PlayerTopThreeResults .Where(x => x.Item2) .GroupBy(x => new { x.Item1.BitsMatchId, x.Item1.Turn, x.Item1.Date }) .OrderBy(x => x.Key.Turn) .ThenBy(x => x.Key.Date) .ToArray(); if (top3ValidResults.Length < 3) { return(CreateFileEntryResult.NotAchievedThreeResults); } if (playerMedalInfo.PlayerPersonalNumber == 0) { return(CreateFileEntryResult.MissingPersonalNumber); } ZipArchiveEntry entry = zip.CreateEntry($"{playerMedalInfo.PlayerName}.pdf", CompressionLevel.Fastest); using Stream entryStream = entry.Open(); using PdfDocument document = PdfReader.Open(templateFilename, PdfDocumentOpenMode.Modify); if (document.AcroForm.Elements.ContainsKey("/NeedAppearances")) { document.AcroForm.Elements["/NeedAppearances"] = new PdfBoolean(true); } else { document.AcroForm.Elements.Add("/NeedAppearances", new PdfBoolean(true)); } document.AcroForm.Fields["Text1"].Value = new PdfString(playerMedalInfo.PlayerName); document.AcroForm.Fields["Text2"].Value = new PdfString(playerMedalInfo.PlayerPersonalNumber.ToString()); document.AcroForm.Fields["Text3"].Value = new PdfString(playerMedalInfo.FormattedExistingMedal.Description); //document.AcroForm.Fields["Text4"].Value = new PdfString("Märkets nummer"); document.AcroForm.Fields["Text5"].Value = new PdfString(playerMedalInfo.FormattedNextMedal.Description); var firstResult = top3ValidResults[0]; var secondResult = top3ValidResults[1]; var thirdResult = top3ValidResults[2]; document.AcroForm.Fields["Text6"].Value = new PdfString(firstResult.Key.Date.ToString("yyyy-MM-dd")); document.AcroForm.Fields["Text7"].Value = new PdfString($"Omgång {firstResult.Key.Turn}"); document.AcroForm.Fields["Text8"].Value = new PdfString(firstResult.Count().ToString()); document.AcroForm.Fields["Text9"].Value = new PdfString(firstResult.Sum(x => x.Item1.Pins).ToString()); document.AcroForm.Fields["1"].Value = new PdfString(secondResult.Key.Date.ToString("yyyy-MM-dd")); document.AcroForm.Fields["2"].Value = new PdfString($"Omgång {secondResult.Key.Turn}"); document.AcroForm.Fields["3"].Value = new PdfString(secondResult.Count().ToString()); document.AcroForm.Fields["4"].Value = new PdfString(secondResult.Sum(x => x.Item1.Pins).ToString()); document.AcroForm.Fields["5"].Value = new PdfString(thirdResult.Key.Date.ToString("yyyy-MM-dd")); document.AcroForm.Fields["6"].Value = new PdfString($"Omgång {thirdResult.Key.Turn}"); document.AcroForm.Fields["7"].Value = new PdfString(thirdResult.Count().ToString()); document.AcroForm.Fields["8"].Value = new PdfString(thirdResult.Sum(x => x.Item1.Pins).ToString()); //document.AcroForm.Fields["9"].Value = new PdfString("Datum fjärde matchen"); //document.AcroForm.Fields["10"].Value = new PdfString("Tävling eller omgång fjärde matchen"); //document.AcroForm.Fields["11"].Value = new PdfString("Antal serier fjärde matchen"); //document.AcroForm.Fields["12"].Value = new PdfString("Poäng fjärde matchen"); document.AcroForm.Fields["Text10"].Value = new PdfString(postModel.Location); document.AcroForm.Fields["Text11"].Value = new PdfString(DateTime.Now.Date.ToString("yyyy-MM-dd")); document.AcroForm.Fields["Text12"].Value = new PdfString(tenant.TeamFullName); //document.AcroForm.Fields["Text14"].Value = new PdfString("OrtBestyrkes"); //document.AcroForm.Fields["Text15"].Value = new PdfString("DatumBestyrkes"); //document.AcroForm.Fields["Text16"].Value = new PdfString("Distriktförbund"); document.Save(entryStream); return(CreateFileEntryResult.CreatedDocument); }
private string Archive(string[] exoFiles) { Console.WriteLine("[{0}] [Info] Start archiving - {1}", GetType().Name, exoFiles.Length); StringBuilder messageBuilder = new StringBuilder(); // Exo parser List <Exo> exos = new List <Exo>(); foreach (string exoFile in exoFiles) { Exo exo = new Exo(exoFile, Encoding.Default); exos.Add(exo); } // Create hash set for file paths HashSet <string> filePathsSet = new HashSet <string>(); HashSet <string> fontNamesSet = new HashSet <string>(); foreach (Exo exo in exos) { foreach (Exo.Exedit.Item item in exo.MainExedit.Items) { foreach (Exo.Exedit.Item.SubItem subItem in item.SubItems) { // Find files if (subItem.Name == "Image file" || subItem.Name == "Video file" || subItem.Name == "Audio file") { if (subItem.Params.ContainsKey("file")) { string filePath = subItem.Params["file"]; if (filePathsSet.Add(filePath)) { Console.WriteLine("[{0}] [Info] File found in the project: {1}", GetType().Name, filePath); } } } // Find fonts if (subItem.Name == "Text") { if (subItem.Params.ContainsKey("file")) { string font = subItem.Params["font"]; if (fontNamesSet.Add(font)) { Console.WriteLine("[{0}] [Info] Font found in the project: {1}", GetType().Name, font); } } } } } } // Create list for FileInfos & calc total size long totalLength = 0; List <FileInfo> fileInfosList = new List <FileInfo>(); foreach (string filePath in filePathsSet) { FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { fileInfosList.Add(fileInfo); totalLength += fileInfo.Length; Console.WriteLine("[{0}] [Info] Confirm file exists: {1}", GetType().Name, fileInfo.FullName); } else { messageBuilder.AppendFormat("未找到文件: {0}\n", fileInfo.FullName); Console.WriteLine("[{0}] [Warn] File not found: {1}", GetType().Name, fileInfo.FullName); } } List <FileInfo> fontFileInfosList = new List <FileInfo>(); foreach (string fontName in fontNamesSet) { if (FontMap.ContainsKey(fontName)) { FileInfo fileInfo = new FileInfo(FontMap[fontName]); if (fileInfo.Exists) { fontFileInfosList.Add(fileInfo); totalLength += fileInfo.Length; Console.WriteLine("[{0}] [Info] Confirm font exists: {1} - {2}", GetType().Name, fontName, fileInfo.FullName); } else { messageBuilder.AppendFormat("未找到字体文件: {0} - {1}\n", fontName, fileInfo.FullName); Console.WriteLine("[{0}] [Warn] Font file not found: {1} - {2}", GetType().Name, fontName, fileInfo.FullName); } } else { messageBuilder.AppendFormat("未找到字体: {0}\n", fontName); Console.WriteLine("[{0}] [Info] Font not found: {1}", GetType().Name, fontName); } } // Collect files and create archive Dictionary <string, string> archivedFileMap = new Dictionary <string, string>(); string archivePath; if (exoFiles.Length == 1) { archivePath = Path.Combine(Path.GetDirectoryName(exoFiles[0]), string.Format("{0}.auz", Path.GetFileNameWithoutExtension(exoFiles[0]))); } else { archivePath = Path.Combine(Path.GetDirectoryName(exoFiles[0]), string.Format("{0}.auz", Path.GetDirectoryName(exoFiles[0]).Split('\\').Last())); } using (FileStream archiveStream = new FileStream(archivePath, FileMode.Create)) { using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Create)) { // Archive files long currentLength = 0; byte[] buffer = new byte[1024 * 1024]; foreach (FileInfo file in fileInfosList) { string archivedPath = GetArchivedPath(file.FullName); if (archivedFileMap.ContainsValue(archivedPath)) { string fullFileNameWithoutExtension = Path.Combine(Path.GetDirectoryName(archivedPath), Path.GetFileNameWithoutExtension(archivedPath)); string extension = Path.GetExtension(archivedPath); long i = 0; do { i++; archivedPath = string.Format("{0} (1){2}", fullFileNameWithoutExtension, i, extension); }while (archivedFileMap.ContainsValue(archivedPath)); } archivedFileMap[file.FullName] = archivedPath; ZipArchiveEntry archiveEntry = archive.CreateEntry(archivedPath, CompressionLevel.Optimal); using (Stream archiveEntryStream = archiveEntry.Open()) { using (FileStream sourceStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { while (sourceStream.Position != sourceStream.Length) { int readLength = sourceStream.Read(buffer, 0, buffer.Length); archiveEntryStream.Write(buffer, 0, readLength); currentLength += readLength; double progress = (double)currentLength / totalLength; Console.WriteLine("[{0}] [Info] Writting files {1}/{2} ({3})", GetType().Name, currentLength, totalLength, progress); CurrentProgress = progress; } Console.WriteLine("[{0}] [Info] File archived: {1} - {2}", GetType().Name, file.FullName, archivedPath); } } } foreach (FileInfo file in fontFileInfosList) { string archivedPath = Path.Combine("Fonts", file.Name); ZipArchiveEntry archiveEntry = archive.CreateEntry(archivedPath); using (Stream archiveEntryStream = archiveEntry.Open()) { using (FileStream sourceStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { while (sourceStream.Position != sourceStream.Length) { int readLength = sourceStream.Read(buffer, 0, buffer.Length); archiveEntryStream.Write(buffer, 0, readLength); currentLength += readLength; double progress = (double)currentLength / totalLength; Console.WriteLine("[{0}] [Info] Writting fonts {1}/{2} ({3})", GetType().Name, currentLength, totalLength, progress); CurrentProgress = progress; } Console.WriteLine("[{0}] [Info] Font archived: {1} - {2}", GetType().Name, file.FullName, archivedPath); } } } // Generate Exo HashSet <string> archivedExoSet = new HashSet <string>(); for (int i = 0; i < exoFiles.Length; i++) { string exoFile = exoFiles[i]; string archivedExoPath = Path.GetFileName(exoFile); if (archivedExoSet.Contains(archivedExoPath)) { string fullFileNameWithoutExtension = Path.Combine(Path.GetDirectoryName(archivedExoPath), Path.GetFileNameWithoutExtension(archivedExoPath)); string extension = Path.GetExtension(archivedExoPath); long j = 0; do { j++; archivedExoPath = string.Format("{0} (1){2}", fullFileNameWithoutExtension, j, extension); }while (archivedExoSet.Contains(archivedExoPath)); } archivedExoSet.Add(archivedExoPath); Exo exo = exos[i]; foreach (Exo.Exedit.Item item in exo.MainExedit.Items) { foreach (Exo.Exedit.Item.SubItem subItem in item.SubItems) { // Find files if (subItem.Name == "Image file" || subItem.Name == "Video file" || subItem.Name == "Audio file") { if (subItem.Params.ContainsKey("file")) { string filePath = subItem.Params["file"]; if (archivedFileMap.ContainsKey(filePath)) { string archivedPath = archivedFileMap[filePath]; subItem.Params["file"] = string.Format(".\\{0}", archivedPath); } } } } } ZipArchiveEntry exoArchiveEntry = archive.CreateEntry(archivedExoPath); using (Stream archiveEntryStream = exoArchiveEntry.Open()) { using (StreamWriter streamWriter = new StreamWriter(archiveEntryStream, Encoding.Default)) { streamWriter.Write(exo.ToString()); Console.WriteLine("[{0}] [Info] Exo archived: {1} - {2}", GetType().Name, exoFile, archivedExoPath); } } } } } messageBuilder.AppendFormat("共处理{0}个Exo存档,已归档{1}/{2}个素材,{3}/{4}个字体。\n{5}", exoFiles.Length, fileInfosList.Count, filePathsSet.Count, fontNamesSet.Count, fontFileInfosList.Count, archivePath); Console.WriteLine("[{0}] [Info] Archiving finished - {1}", GetType().Name, exoFiles.Length); return(messageBuilder.ToString()); }
private void ParseAuditFvdlWithXmlReader(ZipArchiveEntry zipArchiveEntry, string systemName) { try { XmlReaderSettings xmlReaderSettings = GenerateXmlReaderSettings(); using (XmlReader xmlReader = XmlReader.Create(zipArchiveEntry.Open(), xmlReaderSettings)) { while (xmlReader.Read()) { if (xmlReader.IsStartElement()) { switch (xmlReader.Name) { case "CreatedTS": { lastObserved = DateTime.Parse(xmlReader.GetAttribute("date")).ToLongDateString(); break; } case "BuildID": { CreateAddAssetCommand(xmlReader, systemName); break; } case "Vulnerability": { ParseFvdlVulnerablityNode(xmlReader); break; } case "Description": { ParseFvdlDescriptionNode(xmlReader); break; } case "EngineVersion": { CreateUpdateSourceCommand(xmlReader); break; } default: { break; } } } } } foreach (FprVulnerability fprVulnerability in fprVulnerabilityList) { using (SQLiteCommand sqliteCommand = FindingsDatabaseActions.sqliteConnection.CreateCommand()) { AddVulnerabilityAndUniqueFinding(fprVulnerability); } } } catch (Exception exception) { log.Error("Unable to read \"audit.fvdl\"."); throw exception; } }
public static void WriteAllBytes(this ZipArchiveEntry entry, byte[] content) { using var stream = entry.Open(); stream.Write(content, 0, content.Length); }
public FileInfo GenerateZip(FileInfo fileForName, CancellationToken token) { string outputPath = Util.ReplaceUtil.Replace(m_Parameters.OutputPath, fileForName); if (m_Files.Count == 0) { return(null); } string path0 = Path.GetFullPath(m_Files[0].FullName); string[] path0Pieces = path0.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); int numSharedPieces = path0Pieces.Length - 1; foreach (FileInfo file in m_Files) { token.ThrowIfCancellationRequested(); string path = Path.GetFullPath(file.FullName); string[] pathPieces = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); numSharedPieces = Math.Min(numSharedPieces, pathPieces.Length); for (int i = numSharedPieces - 1; i >= 0; i--) { if (!String.Equals(path0Pieces[i], pathPieces[i], StringComparison.OrdinalIgnoreCase)) { numSharedPieces = i; } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < numSharedPieces; i++) { if (i > 0) { sb.Append(Path.DirectorySeparatorChar); } sb.Append(path0Pieces[i]); } string sharedPath = sb.ToString(); int sharedPathLength = sharedPath.Length; if (!File.Exists(outputPath) || m_Parameters.Overwrite) { using (FileStream stream = File.Create(outputPath)) { using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create)) { foreach (FileInfo file in m_Files) { token.ThrowIfCancellationRequested(); string path = Path.GetFullPath(file.FullName); string pathInZip = path.Substring(sharedPathLength).TrimStart(Path.DirectorySeparatorChar) .TrimStart(Path.AltDirectorySeparatorChar); if (m_Parameters.AddContainingFolder) { string containingFolderName = Path.GetFileNameWithoutExtension(outputPath); pathInZip = Path.Combine(containingFolderName, pathInZip); } ZipArchiveEntry entry = archive.CreateEntry(pathInZip); entry.LastWriteTime = file.LastWriteTime; using (Stream outputStream = entry.Open()) { using (Stream inputStream = File.OpenRead(path)) { inputStream.CopyTo(outputStream); } } } } } return(new FileInfo(outputPath)); } else { return(null); } }
private void WriteEntry(IDomainEvent @event, ZipArchiveEntry entry) { using var stream = entry.Open(); this.SerializeToStream(stream, this.Transform(@event)); }
private void ZipPackage(PassGeneratorRequest request) { using (MemoryStream zipToOpen = new MemoryStream()) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, true)) { ZipArchiveEntry imageEntry = null; if (request.Images.ContainsKey(PassbookImage.Icon)) { imageEntry = archive.CreateEntry(@"icon.png"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.Icon]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.IconRetina)) { imageEntry = archive.CreateEntry(@"*****@*****.**"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.IconRetina]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.Logo)) { imageEntry = archive.CreateEntry(@"logo.png"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.Logo]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.LogoRetina)) { imageEntry = archive.CreateEntry(@"*****@*****.**"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.LogoRetina]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.Background)) { imageEntry = archive.CreateEntry(@"background.png"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.Background]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.BackgroundRetina)) { imageEntry = archive.CreateEntry(@"*****@*****.**"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.BackgroundRetina]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.Strip)) { imageEntry = archive.CreateEntry(@"strip.png"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.Strip]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.StripRetina)) { imageEntry = archive.CreateEntry(@"*****@*****.**"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.StripRetina]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.Thumbnail)) { imageEntry = archive.CreateEntry(@"thumbnail.png"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.Thumbnail]); writer.Flush(); } } if (request.Images.ContainsKey(PassbookImage.ThumbnailRetina)) { imageEntry = archive.CreateEntry(@"*****@*****.**"); using (BinaryWriter writer = new BinaryWriter(imageEntry.Open())) { writer.Write(request.Images[PassbookImage.ThumbnailRetina]); writer.Flush(); } } ZipArchiveEntry PassJSONEntry = archive.CreateEntry(@"pass.json"); using (BinaryWriter writer = new BinaryWriter(PassJSONEntry.Open())) { writer.Write(passFile); writer.Flush(); } ZipArchiveEntry ManifestJSONEntry = archive.CreateEntry(@"manifest.json"); using (BinaryWriter writer = new BinaryWriter(ManifestJSONEntry.Open())) { writer.Write(manifestFile); writer.Flush(); } ZipArchiveEntry SignatureEntry = archive.CreateEntry(@"signature"); using (BinaryWriter writer = new BinaryWriter(SignatureEntry.Open())) { writer.Write(signatureFile); writer.Flush(); } } pkPassFile = zipToOpen.ToArray(); zipToOpen.Flush(); } }
public static void IsZipSameAsDir(Stream archiveFile, String directory, ZipArchiveMode mode, Boolean dontRequireExplicit, Boolean dontCheckTimes) { int count = 0; using (ZipArchive archive = new ZipArchive(archiveFile, mode)) { List <FileData> files = FileData.InPath(directory); Assert.All <FileData>(files, (file) => { count++; String entryName = file.FullName; if (file.IsFolder) { entryName += Path.DirectorySeparatorChar; } ZipArchiveEntry entry = archive.GetEntry(entryName); if (entry == null) { entryName = FlipSlashes(entryName); entry = archive.GetEntry(entryName); } if (file.IsFile) { Assert.NotNull(entry); Int64 givenLength = entry.Length; var buffer = new byte[entry.Length]; using (Stream entrystream = entry.Open()) { entrystream.Read(buffer, 0, buffer.Length); String crc = CRC.CalculateCRC(buffer); Assert.Equal(file.Length, givenLength); Assert.Equal(file.CRC, crc); } if (!dontCheckTimes) { const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution); DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution); Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks); } Assert.Equal(file.Name, entry.Name); Assert.Equal(entryName, entry.FullName); Assert.Equal(entryName, entry.ToString()); Assert.Equal(archive, entry.Archive); } else if (file.IsFolder) { if (entry == null) //entry not found { string entryNameOtherSlash = FlipSlashes(entryName); bool isEmtpy = !files.Any( f => f.IsFile && (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) || f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase))); if (!dontRequireExplicit || isEmtpy) { Assert.Contains("emptydir", entryName); } if ((dontRequireExplicit && !isEmtpy) || entryName.Contains("emptydir")) { count--; //discount this entry } } else { using (Stream es = entry.Open()) { try { Assert.Equal(0, es.Length); } catch (NotSupportedException) { try { Assert.Equal(-1, es.ReadByte()); } catch (Exception) { Console.WriteLine("Didn't return EOF"); throw; } } } } } }); Assert.Equal(count, archive.Entries.Count); } }
private static T DeserializedZipEntry <T>(ZipArchiveEntry ZipArchiveEntry) { using (Stream stream = ZipArchiveEntry.Open()) return((T) new XmlSerializer(typeof(T)).Deserialize(XmlReader.Create(stream))); }
/// <param name="useSpansForWriting">Tests the Span overloads of Write</param> /// <param name="writeInChunks">Writes in chunks of 5 to test Write with a nonzero offset</param> public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode, bool useSpansForWriting = false, bool writeInChunks = false) { var files = FileData.InPath(directory); using (ZipArchive archive = new ZipArchive(archiveStream, mode, true)) { foreach (var i in files) { if (i.IsFolder) { string entryName = i.FullName; ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/"); e.LastWriteTime = i.LastModifiedDate; } } foreach (var i in files) { if (i.IsFile) { string entryName = i.FullName; var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName)); if (installStream != null) { ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/')); e.LastWriteTime = i.LastModifiedDate; using (Stream entryStream = e.Open()) { int bytesRead; var buffer = new byte[1024]; if (useSpansForWriting) { while ((bytesRead = installStream.Read(new Span <byte>(buffer))) != 0) { entryStream.Write(new ReadOnlySpan <byte>(buffer, 0, bytesRead)); } } else if (writeInChunks) { while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0) { for (int k = 0; k < bytesRead; k += 5) { entryStream.Write(buffer, k, Math.Min(5, bytesRead - k)); } } } else { while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0) { entryStream.Write(buffer, 0, bytesRead); } } } } } } } }
public async Task <IActionResult> DownloadUnico(string[] check, string[] pdf, string[] nativo, string cosa, string filePath, string nomeProgetto, string daDove) { if (string.IsNullOrEmpty(cosa)) { MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: richiesta malformata", controller: "ReportController", metodo: "DownloadUnico"); return(Error()); } if (cosa.Equals("unico")) { if (check == null || check.Count() == 0) { MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: richiesta malformata", controller: "ReportController", metodo: "DownloadUnico"); return(Redirect(Url.Action(daDove, "Report").Replace("%2F", "/"))); } MyLogger.Log(messaggio: $"Richiesta POST: iniziata generazione PDF unico", controller: "ReportController", metodo: "DownloadUnico"); // converto tutti i report in pdf (se già non lo sono) e li accorpo, poi restituisco l'oggetto risultante var collezionePercorsi = await _context.PercorsiReport.ToListAsync(); string[] percorsiPdf = new string[check.Length]; for (int i = 0; i < check.Length; i++) { var percorso = collezionePercorsi.SingleOrDefault(x => x.ID == int.Parse(check[i])); string extension = Path.GetExtension(percorso.Percorso).ToLower(); if (extension.Equals(".txt") || extension.Equals(".html")) { percorsiPdf[i] = Globals.ConvertiReportTXT(Path.Combine(Globals.CARTELLAREPORT, percorso.Percorso)); } else if (extension.Equals(".xml")) { percorsiPdf[i] = Globals.ConvertiReportXML(Path.Combine(Globals.CARTELLAREPORT, percorso.Percorso)); } else if (extension.Equals(".pdf")) { percorsiPdf[i] = Path.Combine(Globals.CARTELLAREPORT, percorso.Percorso); } MyLogger.Log(messaggio: $"\t{percorsiPdf[i]} generato", controller: "ReportController", metodo: "DownloadUnico"); } List <string> listaPercorsi = percorsiPdf.ToList(); string percorsoPdfUnico = Path.Combine(Globals.CARTELLAREPORT, nomeProgetto, nomeProgetto + ".pdf"); if (Globals.MergePDF(percorsoPdfUnico, listaPercorsi)) { var fileName = Path.GetFileName(percorsoPdfUnico); IFileProvider provider = new PhysicalFileProvider(Path.GetDirectoryName(percorsoPdfUnico)); IFileInfo fileInfo = provider.GetFileInfo(fileName); var readStream = fileInfo.CreateReadStream(); string mimetype = "application/pdf"; MyLogger.Log(messaggio: $"\tPDF unico generato correttamente", controller: "ReportController", metodo: "DownloadUnico"); return(File(readStream, mimetype, fileName)); } } else if (cosa.Equals("zip")) { //https://stackoverflow.com/questions/43281554/create-zip-in-net-core-from-urls-without-downloading-on-server if (nativo.Count() == 0 && pdf.Count() == 0) { MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: richiesta malformata", controller: "ReportController", metodo: "DownloadUnico"); return(Redirect(Url.Action(daDove, "Report").Replace("%2F", "/"))); } MyLogger.Log(messaggio: $"Richiesta POST: iniziata generazione ZIP", controller: "ReportController", metodo: "DownloadUnico"); // prendo i report selezionati, li zippo e restituisco l'oggetto risultante string[] percorsiPdf = new string[pdf.Length]; var collezionePercorsi = await _context.PercorsiReport.ToListAsync(); List <string> listaPercorsi = new List <string>(); foreach (string str in nativo) { listaPercorsi.Add(Path.Combine(Globals.CartellaWEBMVA, "wwwroot", str)); } for (int i = 0; i < pdf.Length; i++) { var percorso = collezionePercorsi.SingleOrDefault(x => "Report/" + x.Percorso == pdf[i]); string extension = Path.GetExtension(percorso.Percorso).ToLower(); if (extension.Equals(".txt") || extension.Equals(".html")) { percorsiPdf[i] = Globals.ConvertiReportTXT(Path.Combine(Globals.CartellaWEBMVA, "wwwroot", "Report", percorso.Percorso)); } else if (extension.Equals(".xml")) { percorsiPdf[i] = Globals.ConvertiReportXML(Path.Combine(Globals.CartellaWEBMVA, "wwwroot", "Report", percorso.Percorso)); } else if (extension.Equals(".pdf")) { percorsiPdf[i] = Path.Combine(Globals.CartellaWEBMVA, "wwwroot", "Report", percorso.Percorso); } } listaPercorsi.AddRange(percorsiPdf.ToList()); var path = Path.Combine(Globals.CartellaWEBMVA, "wwwroot", "Report", nomeProgetto, "Report.zip"); using (var fs = new FileStream(path, FileMode.Create)) { using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Create)) { foreach (string item in listaPercorsi) { IFileProvider provider = new PhysicalFileProvider(Path.GetDirectoryName(item)); IFileInfo fileInfo = provider.GetFileInfo(Path.GetFileName(item)); var readStream = fileInfo.CreateReadStream(); ZipArchiveEntry entry = zip.CreateEntry(Path.GetFileName(item)); using (Stream entryStream = entry.Open()) { readStream.CopyTo(entryStream); } MyLogger.Log(messaggio: $"\tFile {item} aggiunto allo ZIP", controller: "ReportController", metodo: "DownloadUnico"); } IFileProvider provider2 = new PhysicalFileProvider(Path.GetDirectoryName(path)); IFileInfo fileInfo2 = provider2.GetFileInfo(Path.GetFileName(path)); MyLogger.Log(messaggio: $"\tFile ZIP generato con successo", controller: "ReportController", metodo: "DownloadUnico"); return(File(fileInfo2.CreateReadStream(), "application/zip", "Report.zip")); } } } else if (cosa.Equals("singolo")) { // download del singolo report Download(filePath); } return(Error()); }
public int ImportWatchFromFile(HttpPostedFileBase excel, HttpPostedFileBase zip, string username) { int totalImported = 0; using (ExcelPackage package = new ExcelPackage(excel.InputStream)) using (ZipArchive archive = new ZipArchive(zip.InputStream, ZipArchiveMode.Read)) { ExcelWorksheet workSheet = package.Workbook.Worksheets[1]; int startRow = workSheet.Dimension.Start.Row; int endRow = workSheet.Dimension.End.Row; int startCol = workSheet.Dimension.Start.Column; int endCol = workSheet.Dimension.End.Column; string watchCodeColumn, watchDescriptionColumn, quantityColumn, priceColumn, movementIdColumn, modelIdColumn, waterResistantColumn, bandMaterialColumn, caseRadiusColumn, caseMaterialColumn, discountColumn, ledLightColumn, guaranteeColumn, alarmColumn; using (var headers = workSheet.Cells[startRow, startRow, startCol, endCol]) { watchCodeColumn = headers.First(h => h.Value.Equals("WatchCode")).Address[0].ToString(); watchDescriptionColumn = headers.First(h => h.Value.Equals("WatchDescription")).Address[0].ToString(); priceColumn = headers.First(h => h.Value.Equals("Price")).Address[0].ToString(); quantityColumn = headers.First(h => h.Value.Equals("Quantity")).Address[0].ToString(); movementIdColumn = headers.First(h => h.Value.Equals("MovementID")).Address[0].ToString(); modelIdColumn = headers.First(h => h.Value.Equals("ModelID")).Address[0].ToString(); waterResistantColumn = headers.First(h => h.Value.Equals("WaterResistant")).Address[0].ToString(); bandMaterialColumn = headers.First(h => h.Value.Equals("BandMaterial")).Address[0].ToString(); caseRadiusColumn = headers.First(h => h.Value.Equals("CaseRadius")).Address[0].ToString(); caseMaterialColumn = headers.First(h => h.Value.Equals("CaseMaterial")).Address[0].ToString(); discountColumn = headers.First(h => h.Value.Equals("Discount")).Address[0].ToString(); ledLightColumn = headers.First(h => h.Value.Equals("LEDLight")).Address[0].ToString(); guaranteeColumn = headers.First(h => h.Value.Equals("Guarantee")).Address[0].ToString(); alarmColumn = headers.First(h => h.Value.Equals("Alarm")).Address[0].ToString(); } for (int row = startRow + 1; row <= endRow; row++) { try { string watchCode = workSheet.Cells[watchCodeColumn + row].Value.ToString().ToUpper().Trim(); if (Regex.Match(watchCode, "^[A-Za-z0-9-]{1,}$").Success&& !IsDuplicatedWatchCode(watchCode)) { //validate code pattern ////Duplicate code found. Skip add. Otherwise will continue to check ZipArchiveEntry entry = archive.Entries.FirstOrDefault(e => e.Name.Contains(watchCode)); //No Thumbnail match watchcode. Skip add. Otherwise will continue if (entry != null) { Watch watch = new Watch { WatchCode = watchCode, WatchDescription = workSheet.Cells[watchDescriptionColumn + row].Value == null ? null : workSheet.Cells[watchDescriptionColumn + row].Value.ToString().Trim(), BandMaterial = workSheet.Cells[bandMaterialColumn + row].Value == null ? null : workSheet.Cells[bandMaterialColumn + row].Value.ToString().Trim(), CaseMaterial = workSheet.Cells[caseMaterialColumn + row].Value == null ? null : workSheet.Cells[caseMaterialColumn + row].Value.ToString().Trim(), Quantity = Int32.Parse(workSheet.Cells[quantityColumn + row].Value.ToString().Trim()), Price = Double.Parse(workSheet.Cells[priceColumn + row].Value.ToString().Trim()), MovementID = Int32.Parse(workSheet.Cells[movementIdColumn + row].Value.ToString().Trim()), ModelID = Int32.Parse(workSheet.Cells[modelIdColumn + row].Value.ToString().Trim()), CaseRadius = Double.Parse(workSheet.Cells[caseRadiusColumn + row].Value.ToString().Trim()), Discount = Int32.Parse(workSheet.Cells[discountColumn + row].Value.ToString().Trim()), Guarantee = Int32.Parse(workSheet.Cells[guaranteeColumn + row].Value.ToString().Trim()), WaterResistant = workSheet.Cells[waterResistantColumn + row].Value.ToString().Trim().Equals("true", StringComparison.OrdinalIgnoreCase), LEDLight = workSheet.Cells[ledLightColumn + row].Value.ToString().Trim().Equals("true", StringComparison.OrdinalIgnoreCase), Alarm = workSheet.Cells[alarmColumn + row].Value.ToString().Trim().Equals("true", StringComparison.OrdinalIgnoreCase), }; if (watch.Quantity >= 0 && watch.Price >= 0 && watch.CaseRadius.GetValueOrDefault() >= 0 && watch.Discount >= 0 && watch.Guarantee >= 0) { string path = HostingEnvironment.MapPath("~/Content/img/ProductThumbnail/") + watchCode + DateTime.Now.ToBinary(); ImageProcessHelper.ResizedImage(entry.Open(), 360, 500, ResizeMode.Pad, ref path); watch.Thumbnail = path; watch.PublishedTime = DateTime.Now; watch.PublishedBy = username; watch.Status = true; db.Watches.Add(watch); db.SaveChanges(); totalImported++; } } } } catch (Exception) { } } } return(totalImported); }
private static async Task WriteEntryContentsAsync(ZipArchiveEntry entry, string newContents) { using var fileWriter = new StreamWriter(entry.Open()); await fileWriter.WriteAsync(newContents).ConfigureAwait(false); }
public void Read(byte[] buffer, int offset, int length) { m_entry.Open().Read(buffer, offset, length); }
public async Task ProcessCSETAssessmentImport(byte[] zipFileFromDatabase, int currentUserId) { using (CSET_Context context = new CSET_Context()) { //* read from db and set as memory stream here. using (Stream fs = new MemoryStream(zipFileFromDatabase)) { ZipArchive zip = new ZipArchive(fs); StreamReader r = new StreamReader(zip.GetEntry("model.json").Open()); string jsonObject = r.ReadToEnd(); // Apply any data updates to older versions ImportUpgradeManager upgrader = new ImportUpgradeManager(); jsonObject = upgrader.Upgrade(jsonObject); try { UploadAssessmentModel model = (UploadAssessmentModel)JsonConvert.DeserializeObject(jsonObject, new UploadAssessmentModel().GetType()); foreach (var doc in model.CustomStandardDocs) { var genFile = context.GEN_FILE.FirstOrDefault(s => s.File_Name == doc); if (genFile == null) { StreamReader docReader = new StreamReader(zip.GetEntry(doc + ".json").Open()); var docModel = JsonConvert.DeserializeObject <ExternalDocument>(docReader.ReadToEnd()); genFile = docModel.ToGenFile(); var extension = Path.GetExtension(genFile.File_Name).Substring(1); genFile.File_Type_ = context.FILE_TYPE.Where(s => s.File_Type1 == extension).FirstOrDefault(); try { context.FILE_REF_KEYS.Add(new FILE_REF_KEYS { Doc_Num = genFile.Doc_Num }); await context.SaveChangesAsync(); } catch (Exception e) { throw e; } context.GEN_FILE.Add(genFile); context.SaveChanges(); } } foreach (var standard in model.CustomStandards) { var sets = context.SETS.Where(s => s.Set_Name.Contains(standard)).ToList(); SETS set = null; StreamReader setReader = new StreamReader(zip.GetEntry(standard + ".json").Open()); var setJson = setReader.ReadToEnd(); var setModel = JsonConvert.DeserializeObject <ExternalStandard>(setJson); var originalSetName = setModel.ShortName; foreach (var testSet in sets) { setModel.ShortName = testSet.Short_Name; var testSetJson = JsonConvert.SerializeObject(testSet.ToExternalStandard(), Newtonsoft.Json.Formatting.Indented); if (testSetJson == setJson) { set = testSet; break; } else { setModel.ShortName = originalSetName; } } if (set == null) { int incr = 1; while (sets.Any(s => s.Short_Name == setModel.ShortName)) { setModel.ShortName = originalSetName + " " + incr; incr++; } var setResult = await setModel.ToSet(); if (setResult.IsSuccess) { context.SETS.Add(setResult.Result); foreach (var question in setResult.Result.NEW_REQUIREMENT.SelectMany(s => s.NEW_QUESTIONs()).Where(s => s.Question_Id != 0).ToList()) { context.Entry(question).State = EntityState.Unchanged; } try { await context.SaveChangesAsync(); } catch (Exception e) { throw (e); } //Set the GUID at time of export so we are sure it's right!!! model.jANSWER = model.jANSWER.Where(s => s.Is_Requirement).GroupJoin(setResult.Result.NEW_REQUIREMENT, s => s.Custom_Question_Guid, req => new Guid(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(originalSetName + "|||" + req.Requirement_Title + "|||" + req.Requirement_Text))).ToString(), (erea, s) => { var req = s.FirstOrDefault(); if (req != null) { erea.Question_Or_Requirement_Id = req.Requirement_Id; } return(erea); }).Concat(model.jANSWER.Where(s => !s.Is_Requirement).GroupJoin(setResult.Result.NEW_QUESTION, s => s.Custom_Question_Guid, req => new Guid(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(req.Simple_Question))).ToString(), (erer, s) => { var req = s.FirstOrDefault(); if (req != null) { erer.Question_Or_Requirement_Id = req.Question_Id; } return(erer); })).ToList(); } } foreach (var availableStandard in model.jAVAILABLE_STANDARDS.Where(s => s.Set_Name == Regex.Replace(originalSetName, @"\W", "_") && s.Selected)) { availableStandard.Set_Name = Regex.Replace(setModel.ShortName, @"\W", "_"); } } string email = context.USERS.Where(x => x.UserId == currentUserId).First().PrimaryEmail; Importer import = new Importer(); int newAssessmentId = import.RunImportManualPortion(model, currentUserId, email, context); import.RunImportAutomatic(newAssessmentId, jsonObject); // Save the diagram var assessment = context.ASSESSMENTS.Where(x => x.Assessment_Id == newAssessmentId).FirstOrDefault(); if (!string.IsNullOrEmpty(assessment.Diagram_Markup)) { var diagramManager = new DiagramManager(context); var diagReq = new DiagramRequest() { DiagramXml = assessment.Diagram_Markup, AnalyzeDiagram = false, revision = false }; var xDocDiagram = new XmlDocument(); xDocDiagram.LoadXml(assessment.Diagram_Markup); diagramManager.SaveDiagram(newAssessmentId, xDocDiagram, diagReq); } // Clean up any imported standards that are unselected or deprecated var unselectedStandards = context.AVAILABLE_STANDARDS.Where(x => x.Assessment_Id == newAssessmentId && !x.Selected).ToList(); context.AVAILABLE_STANDARDS.RemoveRange(unselectedStandards); var deprecatedStandards = from av in context.AVAILABLE_STANDARDS join set in context.SETS on av.Set_Name equals set.Set_Name where set.Is_Deprecated select av; context.AVAILABLE_STANDARDS.RemoveRange(deprecatedStandards.ToList()); context.SaveChanges(); //NOTE THAT THIS ENTRY WILL ONLY COME FROM A OLD .cset file //IMPORT ZipArchiveEntry importLegacyDiagram = zip.GetEntry("Diagram.csetd"); if (importLegacyDiagram != null) { StreamReader ldr = new StreamReader(importLegacyDiagram.Open()); string oldXml = ldr.ReadToEnd(); DiagramManager dm = new DiagramManager(context); dm.ImportOldCSETDFile(oldXml, newAssessmentId); } } catch (Exception e) { throw e; } } } }
public bool ProcessPackage(Stream fileStream) { MemoryStream memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); ZipArchive archive = new ZipArchive(memoryStream); ZipArchiveEntry file = archive.Entries.FirstOrDefault(entry => entry.FullName.EndsWith(".nuspec")); if (file == null) { throw new InvalidOperationException("No nuspec in nupkg"); } string nuspecContent = new StreamReader(file.Open()).ReadToEnd(); XmlSerializer ser = new XmlSerializer(typeof(package)); using (StringReader sr = new StringReader(nuspecContent)) { package nuspec = (package)ser.Deserialize(new NamespaceIgnorantXmlTextReader(sr)); if (nuspec == null || nuspec.metadata == null) { throw new InvalidOperationException("Invalid nuspec"); } packageMetadata metadata = nuspec.metadata; if (string.IsNullOrWhiteSpace(metadata.id)) { throw new InvalidOperationException("Invalid nuspec (missing id)"); } if (string.IsNullOrWhiteSpace(metadata.version)) { throw new InvalidOperationException("Invalid nuspec (missing version)"); } string title = metadata.id; string version = metadata.version; Regex rgxId = new Regex(@"^[A-Za-z0-9\.\~\+_\-]+$"); if (!rgxId.IsMatch(title)) { throw new InvalidOperationException("Invalid id specified in nuspec"); } Regex rgxVersion = new Regex(@"^[0-9\.\-]+$"); if (!rgxVersion.IsMatch(version)) { throw new InvalidOperationException("Invalid version specified in nuspec"); } long size = memoryStream.Length; memoryStream.Position = 0; string checksum = FileStore.SaveFile(memoryStream, title + "." + version); Package package = new Package(nuspec, checksum, size); memoryStream.Close(); archive.Dispose(); fileStream.Close(); return(Create(package).Result); } }
public void DownLoadFile(string filePath) { try { var version = FileVersionInfo.GetVersionInfo(filePath)?.FileVersion; var versionSplit = version.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (versionSplit.Length > 3) { var masterVersion = versionSplit[0]; var subVersion1 = versionSplit[1]; var subVersion2 = versionSplit[2]; var subVersion3 = versionSplit[3]; var threeVersionNumber = $"{masterVersion}.{subVersion1}.{subVersion2}"; using (HttpClient httpClient = new HttpClient()) { // XHR version address. var versionContent = httpClient.GetAsync($"{DriverDownloadURL}?delimiter=/&prefix=").Result.Content.ReadAsStreamAsync().Result; XmlDocument doc = new XmlDocument(); doc.Load(versionContent); var version_Nodes = doc.DocumentElement.ChildNodes.Cast <XmlNode>() .Where(x => x.Name == "CommonPrefixes" && x.ChildNodes[0].InnerText != "icons/" && x.ChildNodes[0].InnerText.Remove(x.ChildNodes[0].InnerText.LastIndexOf(".")) == threeVersionNumber) // Remove unuse elements .Select(n => n.InnerText.Remove(n.InnerText.Length - 1, 1)) .OrderBy(o => o.Substring(o.LastIndexOf("."))) .ToList(); string userfulVersion = string.Empty; for (int i = 0; i < version_Nodes.Count; i++) { int subVersionCompare = Convert.ToInt32(version_Nodes[i].Substring(version_Nodes[i].LastIndexOf(".") + 1)); if (i == 0) { // 0 ~ anyversion if (Convert.ToInt32(subVersion3) < subVersionCompare) { userfulVersion = version_Nodes[i]; break; } } else { int subVersionCompareLast = Convert.ToInt32(version_Nodes[i - 1].Substring(version_Nodes[i - 1].LastIndexOf(".") + 1)); if (i == version_Nodes.Count - 1) { userfulVersion = version_Nodes[i]; break; } // anyversion1 ~ anyversion2 if (Convert.ToInt32(subVersion3) > subVersionCompareLast && Convert.ToInt32(subVersion3) < subVersionCompare) { userfulVersion = version_Nodes[i]; break; } } } using (var chromeDriver_Stream = httpClient.GetAsync($"{DriverDownloadURL}{userfulVersion}/{DriverDownloadFile}").Result.Content.ReadAsStreamAsync().Result) { chromeDriver_Stream.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[1024 * 5]; using (ZipArchive archive = new ZipArchive(chromeDriver_Stream, ZipArchiveMode.Read)) { ZipArchiveEntry entry = archive.GetEntry("chromedriver.exe"); using (var entry_Stream = entry.Open()) { if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}\\Driver")) { Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}\\Driver"); } var output = new FileStream($"{AppDomain.CurrentDomain.BaseDirectory}\\Driver\\chromedriver.exe", FileMode.CreateNew, FileAccess.Write); int stream_Available; while (true) { stream_Available = entry_Stream.Read(buffer, 0, buffer.Length); if (stream_Available == 0) { break; } output.Write(buffer, 0, stream_Available); Array.Clear(buffer, 0, buffer.Length); } output.Close(); output.Dispose(); } } } } } GC.Collect(); } catch (Exception e) { throw new Exception(e.Message); } }
public Entity GetSourceSolutionInfo(string solutionFileName) { using (ZipArchive archive = ZipFile.Open(solutionFileName, ZipArchiveMode.Read)) { ZipArchiveEntry solutionEntry = archive.GetEntry("solution.xml"); if (solutionEntry != null) { try { MemoryStream readerStream = new MemoryStream(); var xmlStream = solutionEntry.Open(); xmlStream.CopyTo(readerStream); readerStream.Position = 0; XmlDocument solutionXml = new XmlDocument(); solutionXml.Load(readerStream); //xmlDoc.FirstChild.FirstChild.ChildNodes string solutionName = null, solutionVersion = null; var solutionManifest = solutionXml.GetElementsByTagName("SolutionManifest"); if (solutionManifest != null && solutionManifest.Count > 0) { var solutionManifestNode = solutionManifest.Item(0); if (solutionManifestNode == null) { return(null); } for (int index = 0; index <= solutionManifestNode.ChildNodes.Count; index++) { var curNode = solutionManifestNode.ChildNodes[index]; if (curNode != null) { if (curNode.Name.ToLower().Equals("uniquename")) { solutionName = curNode.InnerText; } else if (curNode.Name.ToLower().Equals("version")) { solutionVersion = curNode.InnerText; } } } if (solutionName != null) { var solutionInfo = new Entity("solution") { ["uniquename"] = solutionName, ["version"] = solutionVersion }; return(solutionInfo); } } } catch //(Exception ex) { //don't throw - if it return null means the solution file is invalid!!! } } } return(null); }
public static string ReadString(this ZipArchiveEntry entry) { using var entryStream = entry.Open(); using StreamReader reader = new(entryStream); return(reader.ReadToEnd()); }
void ReadNuspec(ZipArchiveEntry entry) { using (var stream = entry.Open()) { var xdoc = XDocument.Load(stream); var ns = xdoc.Root.Name.Namespace; var meta = xdoc.Root.Elements().FirstOrDefault(x => x.Name.LocalName == "metadata"); if (meta == null) { throw new Exception("Failed to find metadata in " + xdoc); } string GetS(string name, string def = "") { try { return(meta.Element(ns + name).Value.Trim()); } catch { return(def); } } string GetUrl(string name) { var u = GetS(name); if (!u.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { return(""); } if (u.ToLowerInvariant().Contains("_url_here_or_delete")) { return(""); } return(u); } NuspecXml = xdoc.ToString(SaveOptions.OmitDuplicateNamespaces); Id = GetS("id", IndexId); Authors = GetS("authors"); Owners = GetS("owners"); ProjectUrl = GetUrl("projectUrl"); LicenseUrl = GetUrl("licenseUrl"); if (LicenseUrl == ProjectUrl) { LicenseUrl = ""; } IconUrl = GetUrl("iconUrl"); Description = GetS("description"); var repo = meta.Element(ns + "repository"); if (repo != null) { RepositoryType = repo.Attribute("type")?.Value ?? ""; RepositoryUrl = repo.Attribute("url")?.Value ?? ""; RepositoryCommit = repo.Attribute("commit")?.Value ?? ""; } var deps = meta.Element(ns + "dependencies"); if (deps != null) { // System.Console.WriteLine(deps); foreach (var de in deps.Elements()) { if (de.Name.LocalName == "group") { var tfa = de.Attribute("targetFramework"); if (tfa != null) { var tfName = tfa.Value; var tf = FindExactTargetFramework(TargetFrameworkNameToMoniker(tfName)); if (tf != null) { foreach (var ge in de.Elements(ns + "dependency")) { var dep = new PackageDependency(ge); tf.AddDependency(dep); } } } } else if (de.Name.LocalName == "dependency") { var dep = new PackageDependency(de); foreach (var tf in TargetFrameworks) { tf.AddDependency(dep); } } } } } }
private string ReleaseArchive(string archiveFile) { Console.WriteLine("[{0}] [Info] Start releasing archive - {1}", GetType().Name, archiveFile); bool isTileRelease = MessageBox.Show("是否按文件夹释放素材", "释放素材", MessageBoxButton.YesNo) == MessageBoxResult.No; StringBuilder messageBuilder = new StringBuilder(); uint fileCount = 0; uint exoCount = 0; string exoDirectory = Path.Combine(Path.GetDirectoryName(archiveFile), Path.GetFileNameWithoutExtension(archiveFile)); using (FileStream archiveStream = new FileStream(archiveFile, FileMode.Open)) { using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Read)) { // Calc total length long totalLength = 0; foreach (ZipArchiveEntry archiveEntry in archive.Entries) { if (archiveEntry.FullName.EndsWith(".exo")) { continue; } totalLength += archiveEntry.Length; } // Release files long currentLength = 0; byte[] buffer = new byte[1024 * 1024]; foreach (ZipArchiveEntry archiveEntry in archive.Entries) { if (archiveEntry.FullName.EndsWith(".exo")) { continue; } string releaseDirectory; string releaseFullFileName; if (!archiveEntry.FullName.StartsWith("Fonts\\") && isTileRelease) { releaseDirectory = Path.Combine(Path.GetDirectoryName(archiveFile), Path.GetFileNameWithoutExtension(archiveFile)); releaseFullFileName = Path.Combine(releaseDirectory, archiveEntry.FullName.Replace('\\', '_')); } else { releaseDirectory = Path.Combine(Path.GetDirectoryName(archiveFile), Path.GetFileNameWithoutExtension(archiveFile), Path.GetDirectoryName(archiveEntry.FullName)); releaseFullFileName = Path.Combine(releaseDirectory, archiveEntry.Name); } Directory.CreateDirectory(releaseDirectory); using (Stream archiveEntryStream = archiveEntry.Open()) { using (FileStream releaseStream = new FileStream(releaseFullFileName, FileMode.Create)) { int position = 0; while (position != archiveEntry.Length) { int readLength = archiveEntryStream.Read(buffer, 0, buffer.Length); releaseStream.Write(buffer, 0, readLength); position += readLength; currentLength += readLength; double progress = (double)currentLength / totalLength; Console.WriteLine("[{0}] [Info] Releasing files {1}/{2} ({3})", GetType().Name, currentLength, totalLength, progress); CurrentProgress = progress; } } } fileCount++; } // Generate Exo foreach (ZipArchiveEntry archiveEntry in archive.Entries) { if (!archiveEntry.FullName.EndsWith(".exo")) { continue; } ZipArchiveEntry exoArchiveEntry = archiveEntry; using (Stream exoStream = exoArchiveEntry.Open()) { Exo exo = new Exo(exoStream, Encoding.Default); foreach (Exo.Exedit.Item item in exo.MainExedit.Items) { foreach (Exo.Exedit.Item.SubItem subItem in item.SubItems) { if (subItem.Name == "Image file" || subItem.Name == "Video file" || subItem.Name == "Audio file") { if (subItem.Params.ContainsKey("file")) { string archivedPath = subItem.Params["file"]; if (archivedPath.StartsWith(".\\")) { if (isTileRelease) { subItem.Params["file"] = Path.Combine(Path.GetDirectoryName(archiveFile), Path.GetFileNameWithoutExtension(archiveFile), archivedPath.Substring(".\\".Length).Replace('\\', '_')); } else { subItem.Params["file"] = Path.Combine(Path.GetDirectoryName(archiveFile), Path.GetFileNameWithoutExtension(archiveFile), archivedPath.Substring(".\\".Length)); } } } } } } if (!Directory.Exists(exoDirectory)) { Directory.CreateDirectory(exoDirectory); } string exoFullFileName = Path.Combine(exoDirectory, exoArchiveEntry.Name); using (StreamWriter streamWriter = new StreamWriter(exoFullFileName, false, Encoding.Default)) { streamWriter.Write(exo.ToString()); } } Console.WriteLine("[{0}] [Info] Exo generated - {1}", GetType().Name, exoArchiveEntry.Name); exoCount++; } } } messageBuilder.AppendFormat("共释放{0}个素材,生成{1}个Exo存档\n{2}", fileCount, exoCount, exoDirectory); Console.WriteLine("[{0}] [Info] Archive releasing finished - {1}", GetType().Name, archiveFile); return(messageBuilder.ToString()); }
/// <summary> /// Get the specified entry of the UCC file and return it as a bitmap /// </summary> /// <param name="entryName">Name of the entry</param> /// <returns>Bitmap instance of the specified entry</returns> public SKBitmap GetBitmapFromFileEntry(string entryName) { int width; int height; int posX = 0; int posY = 0; ZipArchiveEntry entry = ZIPFile.GetEntry(entryName); MemoryStream memoryStream = new MemoryStream(); entry?.Open().CopyTo(memoryStream); memoryStream.Position = 0; if (memoryStream.Length > 65536) { width = 256; height = 256; } else if (memoryStream.Length > 32768) { width = 128; height = 64; } else if (entryName == "icon") { width = 64; height = 84; } else { width = 128; height = 128; } SKBitmap bitmap = new SKBitmap(width, height); using (BinaryReader reader = new BinaryReader(memoryStream)) { while (reader.BaseStream.Position < reader.BaseStream.Length) { int loopCount = 3; if (entryName == "icon") { loopCount = 4; } byte[] hexColor = new byte[4]; for (byte i = 0; i < loopCount; i++) { hexColor[i] = reader.ReadByte(); } SKColor color = new SKColor(hexColor[2], hexColor[1], hexColor[0], entryName == "icon" ? hexColor[3] : (byte)255); bitmap.SetPixel(posX, posY, color); posX++; if (posX != width) { continue; } posY++; posX = 0; } } return(bitmap); }
public static void PerformNightlyBuild(ConfigFile config) { string packagePath = Path.Combine(config.PackageDir, config.PackageName); FileVersionInfo versionCore = null; FileVersionInfo versionEditor = null; FileVersionInfo versionLauncher = null; // Build the target Solution if (!config.NoBuild) { Console.WriteLine("================================ Build Solution ==============================="); { bool buildSuccess = BuildVisualStudioSolution(config.SolutionPath, "Release"); if (!buildSuccess) { throw new ApplicationException("The project doesn't compile properly. Cannot proceed in this state."); } versionCore = FileVersionInfo.GetVersionInfo(Path.Combine(config.BuildResultDir, "Duality.dll")); versionEditor = FileVersionInfo.GetVersionInfo(Path.Combine(config.BuildResultDir, "DualityEditor.exe")); versionLauncher = FileVersionInfo.GetVersionInfo(Path.Combine(config.BuildResultDir, "DualityLauncher.exe")); Console.WriteLine("Build Successful"); Console.WriteLine(" Core Version: {0}", versionCore.FileVersion); Console.WriteLine(" Editor Version: {0}", versionEditor.FileVersion); Console.WriteLine(" Launcher Version: {0}", versionLauncher.FileVersion); } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); } // Perform unit testing if (!config.NoTests) { Console.WriteLine("================================= Unit Testing ================================"); foreach (string nunitProjectFile in Directory.EnumerateFiles(config.UnitTestProjectDir, "*.nunit", SearchOption.TopDirectoryOnly)) { Console.Write("Testing '{0}'... ", Path.GetFileName(nunitProjectFile)); // Don't use /timeout, as it will execute tests from a different thread, // which will break a lot of graphics-related Duality stuff! string resultFile = "UnitTestResult.xml"; ExecuteCommand( string.Format("{0} {1} /result={2}", Path.Combine(config.NUnitBinDir, "nunit3-console.exe"), nunitProjectFile, resultFile), verbose: true); if (File.Exists(resultFile)) { XmlDocument resultDoc = new XmlDocument(); resultDoc.Load(resultFile); XmlElement testRunElement = resultDoc["test-run"]; XmlAttribute failedAttribute = testRunElement.Attributes["failed"]; int failedCount = int.Parse(failedAttribute.Value); if (failedCount > 0) { ExecuteBackgroundCommand(resultFile); ExecuteBackgroundCommand( string.Format("{0} {1}", Path.Combine(config.NUnitBinDir, "nunit.exe"), nunitProjectFile)); throw new ApplicationException(string.Format("At least one unit test has failed. See {0} for more information.", resultFile)); } else { Console.WriteLine("success!"); File.Delete(resultFile); } } else { throw new ApplicationException("Something appears to have failed during unit testing, because no result file was found."); } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); } // Build the documentation bool includeDocs = !string.IsNullOrWhiteSpace(config.DocBuildResultDir) && !string.IsNullOrWhiteSpace(config.DocBuildResultFile); if (!config.NoDocs) { Console.WriteLine("================================== Build Docs ================================="); { bool buildSuccess = BuildVisualStudioSolution(config.DocSolutionPath, "Release"); if (!buildSuccess) { throw new ApplicationException("Documentation Build Failure"); } Console.WriteLine("Documentation Build Successful"); if (includeDocs) { File.Copy( Path.Combine(config.DocBuildResultDir, config.DocBuildResultFile), Path.Combine(config.BuildResultDir, config.DocBuildResultFile), true); Console.WriteLine("Documentation copied to build directory"); } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); } else if (includeDocs && File.Exists(Path.Combine(config.DocBuildResultDir, config.DocBuildResultFile))) { Console.WriteLine("============================== Copy existing Docs ============================="); { File.Copy( Path.Combine(config.DocBuildResultDir, config.DocBuildResultFile), Path.Combine(config.BuildResultDir, config.DocBuildResultFile), true); } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); } // Copy the results to the target directory Console.WriteLine("================================ Copy to Target ==============================="); { Console.WriteLine("Creating target directory '{0}'", config.IntermediateTargetDir); if (Directory.Exists(config.IntermediateTargetDir)) { Directory.Delete(config.IntermediateTargetDir, true); } CopyDirectory(config.BuildResultDir, config.IntermediateTargetDir, true, path => { string fileName = Path.GetFileName(path); foreach (string blackListEntry in config.FileCopyBlackList) { if (Regex.IsMatch(fileName, WildcardToRegex(blackListEntry), RegexOptions.IgnoreCase)) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("Ignore {0}", path); Console.ForegroundColor = ConsoleColor.Gray; return(false); } } Console.WriteLine("Copy {0}", path); return(true); }); if (!string.IsNullOrEmpty(config.AdditionalFileDir) && Directory.Exists(config.AdditionalFileDir)) { CopyDirectory(config.AdditionalFileDir, config.IntermediateTargetDir, true); } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); // Create the ZIP package Console.WriteLine("============================== Create ZIP Package ============================="); { Console.WriteLine("Package Path: {0}", packagePath); if (!Directory.Exists(config.PackageDir)) { Directory.CreateDirectory(config.PackageDir); } string[] files = Directory.GetFiles(config.IntermediateTargetDir, "*", SearchOption.AllDirectories); using (FileStream packageStream = File.Open(packagePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(packageStream, ZipArchiveMode.Create, true)) { foreach (string filePath in files) { ZipArchiveEntry fileEntry = archive.CreateEntry(filePath); using (Stream entryStream = fileEntry.Open()) using (BinaryWriter entryWriter = new BinaryWriter(entryStream)) { byte[] fileData = File.ReadAllBytes(filePath); entryWriter.Write(fileData); } } } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); // Cleanup Console.WriteLine("=================================== Cleanup ==================================="); { Console.WriteLine("Deleting target directory '{0}'", config.IntermediateTargetDir); if (Directory.Exists(config.IntermediateTargetDir)) { Directory.Delete(config.IntermediateTargetDir, true); } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); // Build all NuGet Packages Console.WriteLine("============================= Build NuGet Packages ============================"); { bool nugetFound = File.Exists(config.NuGetPath); bool nugetSpecsFound = Directory.Exists(config.NuGetPackageSpecsDir); if (nugetFound && nugetSpecsFound) { if (!Directory.Exists(config.NuGetPackageTargetDir)) { Directory.CreateDirectory(config.NuGetPackageTargetDir); } Console.WriteLine("Deleting old package files in '{0}'...", config.NuGetPackageTargetDir); foreach (string file in Directory.EnumerateFiles(config.NuGetPackageTargetDir, "*.nupkg", SearchOption.TopDirectoryOnly)) { File.Delete(file); } Console.WriteLine("Determining package data from '{0}'...", config.NuGetPackageSpecsDir); Dictionary <string, Version> packageVersions = new Dictionary <string, Version>(); foreach (string file in Directory.EnumerateFiles(config.NuGetPackageSpecsDir, "*.nuspec", SearchOption.AllDirectories)) { Console.Write(" {0}: ", Path.GetFileName(file)); string fileAbs = Path.GetFullPath(file); XDocument doc = XDocument.Load(fileAbs); XElement elemId = doc.Descendants("id").FirstOrDefault(); XElement elemVersion = doc.Descendants("version").FirstOrDefault(); string id = elemId.Value.Trim(); Version version = Version.Parse(elemVersion.Value.Trim()); packageVersions[id] = version; Console.WriteLine("{0}", version); } Console.WriteLine(); Console.WriteLine("Creating packages from '{0}'...", config.NuGetPackageSpecsDir); foreach (string file in Directory.EnumerateFiles(config.NuGetPackageSpecsDir, "*.nuspec", SearchOption.AllDirectories)) { Console.Write(" {0}... ", Path.GetFileName(file)); string fileAbs = Path.GetFullPath(file); XDocument doc = XDocument.Load(fileAbs); bool skip = false; foreach (XElement elemDependency in doc.Descendants("dependency")) { string id = elemDependency.Attribute("id").Value.Trim(); Version version = Version.Parse(elemDependency.Attribute("version").Value.Trim()); Version developedAgainstVersion; if (packageVersions.TryGetValue(id, out developedAgainstVersion)) { if (version != developedAgainstVersion) { skip = true; break; } } } if (skip) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("dependency mismatch (skip)"); Console.ResetColor(); continue; } XElement elemId = doc.Descendants("id").FirstOrDefault(); XElement elemVersion = doc.Descendants("version").FirstOrDefault(); string targetFileName = string.Format("{0}.{1}.nupkg", elemId.Value.Trim(), elemVersion.Value.Trim()); string packResult = ExecuteCommand(Path.GetFullPath(config.NuGetPath) + " pack " + fileAbs, config.NuGetPackageTargetDir, false); if (!File.Exists(Path.Combine(config.NuGetPackageTargetDir, targetFileName))) { string errorMessage = string.Format( "Failed to create NuGet Package {0}:" + Environment.NewLine + "{1}", Path.GetFileName(file), packResult); // If in non-interactive mode, continue to build packages even if one of them failed. if (config.NonInteractive) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("failed"); Console.WriteLine(errorMessage); Console.ForegroundColor = ConsoleColor.Gray; } // Otherwise, stop with an exception. else { throw new ApplicationException(errorMessage); } } else { Console.WriteLine("done"); } } } else if (!nugetFound) { throw new ApplicationException(string.Format("Can't find NuGet command line tool '{0}'.", config.NuGetPath)); } else if (!nugetSpecsFound) { throw new ApplicationException(string.Format("Can't find NuGet package specs directory '{0}'.", config.NuGetPackageSpecsDir)); } } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); // Copy ZIP Package if (!string.IsNullOrWhiteSpace(config.CopyPackageTo)) { Console.WriteLine("=============================== Copy ZIP Package =============================="); { Console.WriteLine("Copying package to '{0}'", config.CopyPackageTo); if (!Directory.Exists(config.CopyPackageTo)) { Directory.CreateDirectory(config.CopyPackageTo); } File.Copy(packagePath, Path.Combine(config.CopyPackageTo, config.PackageName), true); } Console.WriteLine("==============================================================================="); Console.WriteLine(); Console.WriteLine(); } Console.WriteLine("Finished Build."); if (!config.NonInteractive) { Console.ReadLine(); } }