public static void Pack(this ArchiveInfo o, string sourceDirectory, IList <string> sourceFileNames, IList <string> fileNames, CompressionLevel compLevel, EventHandler <ArchiveProgressEventArgs> progressHandler, IPackStreamContext ipackstreamcontext) { if (sourceFileNames == null) { throw new ArgumentNullException("sourceFileNames"); } checked { if (fileNames == null) { string[] array = new string[sourceFileNames.Count]; for (int i = 0; i < sourceFileNames.Count; i++) { array[i] = Path.GetFileName(sourceFileNames[i]); } fileNames = array; } else if (fileNames.Count != sourceFileNames.Count) { throw new ArgumentOutOfRangeException("fileNames"); } using (CompressionEngine compressionEngine = new CabEngine()) { compressionEngine.Progress += progressHandler; IDictionary <string, string> files = CreateStringDictionary(fileNames, sourceFileNames); ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(o.FullName, sourceDirectory, files); archiveFileStreamContext.EnableOffsetOpen = true; compressionEngine.CompressionLevel = compLevel; compressionEngine.Pack(archiveFileStreamContext, fileNames); } } }
public static byte[] Pack(byte[] unpackedBytes, string unpackedFileName) { MemoryStream unpackedStream = new MemoryStream(unpackedBytes); BasicPackStreamContext streamContext = new BasicPackStreamContext(unpackedStream); List <string> fileNames = new List <string>(); fileNames.Add(unpackedFileName); using (CabEngine engine = new CabEngine()) { engine.Pack(streamContext, fileNames); } Stream packedStream = streamContext.ArchiveStream; if (packedStream != null) { packedStream.Position = 0; byte[] packedBytes = new byte[packedStream.Length]; packedStream.Read(packedBytes, 0, packedBytes.Length); return(packedBytes); } else { string message = String.Format("Error: File '{0}' failed to be repacked"); Console.WriteLine(message); Program.Exit(); throw new Exception(message); } }
public static byte[] Unpack(byte[] fileBytes, string unpackedFileName) { MemoryStream packedStream = new MemoryStream(fileBytes); BasicUnpackStreamContext streamContext = new BasicUnpackStreamContext(packedStream); Predicate <string> isFileMatch = delegate(string match) { return(String.Compare(match, unpackedFileName, true) == 0); }; using (CabEngine engine = new CabEngine()) { engine.Unpack(streamContext, isFileMatch); } Stream unpackedStream = streamContext.FileStream; if (unpackedStream != null) { unpackedStream.Position = 0; byte[] unpackedBytes = new byte[unpackedStream.Length]; unpackedStream.Read(unpackedBytes, 0, unpackedBytes.Length); return(unpackedBytes); } else { string message = String.Format("Error: File does not contain the expected file ('{1}')", unpackedFileName); Console.WriteLine(message); Program.Exit(); return(new byte[0]); } }
/// <inheritdoc/> public override void Extract(IBuilder builder, Stream stream, string?subDir = null) { EnsureFile(stream, msiPath => { try { using var engine = new CabEngine(); using var package = new MsiPackage(msiPath); package.ForEachCabinet(cabStream => { Handler.CancellationToken.ThrowIfCancellationRequested(); EnsureSeekable(cabStream, seekableStream => { // ReSharper disable once AccessToDisposedClosure engine.Unpack( new CabExtractorContext(builder, seekableStream, x => NormalizePath(package.Files[x], subDir), Handler.CancellationToken), fileFilter: package.Files.ContainsKey); }); }); } #region Error handling catch (Exception ex) when(ex is InstallerException or CabException) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion });
public static byte[] Unpack(byte[] fileBytes, string unpackedFileName) { var packedStream = new MemoryStream(fileBytes); var streamContext = new BasicUnpackStreamContext(packedStream); Predicate <string> isFileMatch = match => String.Compare(match, unpackedFileName, StringComparison.OrdinalIgnoreCase) == 0; using (var engine = new CabEngine()) { engine.Unpack(streamContext, isFileMatch); } var unpackedStream = streamContext.FileStream; if (unpackedStream != null) { unpackedStream.Position = 0; var unpackedBytes = new byte[unpackedStream.Length]; unpackedStream.Read(unpackedBytes, 0, unpackedBytes.Length); return(unpackedBytes); } var message = string.Format("Error: File does not contain the expected file ('{1}')", unpackedFileName); Console.WriteLine(message); Program.Exit(); return(new byte[0]); }
private bool ProcessCatalog() { string tempFile = Path.Combine(Path.GetTempPath(), "HPClientDriverPackCatalog.cab"); using (FileStream innerCab = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { CabEngine engine = new CabEngine(); foreach (ArchiveFileInfo archiveFileInfo in engine.GetFileInfo(innerCab)) { using (Stream stream = engine.Unpack(innerCab, archiveFileInfo.Name)) { XElement catalog = XElement.Load(stream); comboBoxOS.Items.Clear(); List <XElement> nodeList = catalog.Element("HPClientDriverPackCatalog").Element("OSList").Elements("OS").ToList(); foreach (XElement node in nodeList) { string os = node.Element("Name").Value; comboBoxOS.Items.Add(os); comboBoxOS.SelectedIndex = 0; } } } } return(true); }
private void ExtractCab(Stream stream) { using var tempFile = new TemporaryFile("0install"); // Extract embedded CAB from MSI using (var tempStream = File.Create(tempFile)) stream.CopyToEx(tempStream, cancellationToken: CancellationToken); // Extract individual files from CAB using (CabStream = File.OpenRead(tempFile)) CabEngine.Unpack(this, _ => true); }
public static Stream Unpack(Stream compressedStream) { CabEngine cabEngine = new CabEngine(); InMemoryUnpackContext unpackContext = new InMemoryUnpackContext(compressedStream); cabEngine.Unpack(unpackContext, suffix => true); Stream s = unpackContext.UncompressedStream; s.Seek(0, SeekOrigin.Begin); return(s); }
/// <inheritdoc/> protected override void ExtractArchive() { try { CabEngine.Unpack(this, _ => true); } #region Error handling catch (CabException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion }
/// <summary> /// Prepares to extract a MS Cabinet archive contained in a stream. /// </summary> /// <param name="stream">The stream containing the archive data to be extracted. Will be disposed when the extractor is disposed.</param> /// <param name="targetPath">The path to the directory to extract into.</param> /// <exception cref="IOException">The archive is damaged.</exception> internal CabExtractor(Stream stream, string targetPath) : base(targetPath) { CabStream = stream ?? throw new ArgumentNullException(nameof(stream)); try { UnitsTotal = CabEngine.GetFileInfo(this, _ => true).Sum(x => x.Length); } #region Error handling catch (CabException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion }
/// <inheritdoc/> public override void Extract(IBuilder builder, Stream stream, string?subDir = null) { using var engine = new CabEngine(); EnsureSeekable(stream, seekableStream => { try { engine.Unpack( new CabExtractorContext(builder, seekableStream, path => NormalizePath(path, subDir), Handler.CancellationToken), fileFilter: path => NormalizePath(path, subDir) != null); } #region Error handling catch (CabException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion }); }
/// <inheritdoc/> protected override void Execute() { State = TaskState.Data; try { if (!Directory.Exists(EffectiveTargetDir)) { Directory.CreateDirectory(EffectiveTargetDir); } CabEngine.Unpack(this, _ => true); } #region Error handling catch (CabException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion State = TaskState.Complete; }
/// <summary> /// Prepares to extract a MS Cabinet archive contained in a stream. /// </summary> /// <param name="stream">The stream containing the archive data to be extracted. Will be disposed when the extractor is disposed.</param> /// <param name="target">The path to the directory to extract into.</param> /// <exception cref="IOException">The archive is damaged.</exception> internal CabExtractor([NotNull] Stream stream, [NotNull] string target) : base(target) { #region Sanity checks if (stream == null) { throw new ArgumentNullException("stream"); } #endregion CabStream = stream; try { UnitsTotal = CabEngine.GetFileInfo(this, _ => true).Sum(x => x.Length); } #region Error handling catch (CabException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion }
private void ProcessCatalog() { dataGridViewDriverPackages.Rows.Clear(); bool known = false; string prefix = string.IsNullOrEmpty(registry.ReadString("HPFolderPrefix")) ? "HP" : registry.ReadString("HPFolderPrefix"); string tempFile = Path.Combine(Path.GetTempPath(), "HPClientDriverPackCatalog.cab"); using (FileStream innerCab = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { CabEngine engine = new CabEngine(); foreach (ArchiveFileInfo archiveFileInfo in engine.GetFileInfo(innerCab)) { using (Stream stream = engine.Unpack(innerCab, archiveFileInfo.Name)) { catalog = XElement.Load(stream); IEnumerable <XElement> nodeList = catalog.Element("HPClientDriverPackCatalog").Element("ProductOSDriverPackList").Elements("ProductOSDriverPack").Where( x => x.Element("OSName").Value == UserData["OS"].ToString() ); foreach (XElement node in nodeList) { HPDriverPackage package = new HPDriverPackage(node) { SoftPaq = catalog.Element("HPClientDriverPackCatalog").Element("SoftPaqList").Elements("SoftPaq").Where( x => x.Element("Id").Value == node.Element("SoftPaqId").Value ).FirstOrDefault(), Vendor = prefix }; package.ProcessSoftPaq(); package.GenerateModelFolderName(os, structure); DataGridViewRow dataGridViewRow = new DataGridViewRow(); dataGridViewRow.CreateCells(dataGridViewDriverPackages); dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[1].Value = package.Model; dataGridViewRow.Cells[2].Value = package.VersionShort; dataGridViewRow.Cells[3].Value = package.Size.ToString(); dataGridViewRow.Tag = package; dataGridViewDriverPackages.Rows.Add(dataGridViewRow); } } } } // TODO: will implement when I have an HP device to test with //string query = "SELECT DISTINCT Model FROM SMS_G_System_COMPUTER_SYSTEM WHERE Manufacturer = 'HP' OR Manufacturer = 'Hewlett-Packard'"; //List<IResultObject> models = Utility.SearchWMIToList(ConnectionManager, query); //foreach (IResultObject model in models) //{ // string testModel = model["Model"].StringValue; // testModel = Regex.Replace(testModel, "HP", "", RegexOptions.IgnoreCase); // testModel = Regex.Replace(testModel, "COMPAQ", "", RegexOptions.IgnoreCase); // testModel = Regex.Replace(testModel, "SFF", "Small Form Factor"); // testModel = Regex.Replace(testModel, "USDT", "Desktop"); // testModel = Regex.Replace(testModel, " TWR", " Tower"); // testModel = testModel.TrimEnd("PC").Trim(); // DataGridViewRow row = dataGridViewDriverPackages.Rows // .Cast<DataGridViewRow>() // .Where(r => r.Cells[1].Value.ToString().Equals(testModel, StringComparison.CurrentCultureIgnoreCase)) // .FirstOrDefault(); // if (row != null) // { // row.Cells[0].Value = true; // row.Cells[4].Value = "Model detected"; // known = true; // } //} foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows) { HPDriverPackage package = (HPDriverPackage)dataGridViewRow.Tag; string path = Path.Combine(sourceFolderPath, package.FolderName); if (Directory.Exists(path)) { string[] fileList = Directory.GetFiles(path, "*.version"); if (File.Exists(Path.Combine(path, package.VersionFile))) { dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[4].Value = "Downloaded"; } else if (fileList.Length > 0) { dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[4].Value = "New version"; } } } dataGridViewDriverPackages.Sort(known ? columnStatus : columnPack, known ? ListSortDirection.Descending : ListSortDirection.Ascending); Initialized = true; }
private void ProcessCatalog() { dataGridViewDriverPackages.Rows.Clear(); bool known = false; string prefix = string.IsNullOrEmpty(registry.ReadString("DellFolderPrefix")) ? "Dell" : registry.ReadString("DellFolderPrefix"); string tempFile = Path.Combine(Path.GetTempPath(), "DriverPackCatalog.cab"); using (FileStream innerCab = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { CabEngine engine = new CabEngine(); foreach (ArchiveFileInfo archiveFileInfo in engine.GetFileInfo(innerCab)) { using (Stream stream = engine.Unpack(innerCab, archiveFileInfo.Name)) { catalog = XElement.Load(stream); XNamespace ns = catalog.GetDefaultNamespace(); // Get download base location from DriverPackCatalog.xml UserData["baseLocation"] = catalog.Attribute("baseLocation").Value; IEnumerable <XElement> nodeList = catalog.Elements(ns + "DriverPackage").Where( x => x.Element(ns + "SupportedOperatingSystems").Elements(ns + "OperatingSystem").Any( y => y.Attribute("osCode").Value == UserData["OS"].ToString().Replace(" ", string.Empty) && y.Attribute("osArch").Value == UserData["Architecture"].ToString() ) ); foreach (XElement node in nodeList) { DellDriverPackage package = new DellDriverPackage(node) { Vendor = prefix }; package.GenerateModelFolderName(os, structure); DataGridViewRow dataGridViewRow = new DataGridViewRow(); dataGridViewRow.CreateCells(dataGridViewDriverPackages); dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[1].Value = package.Model; dataGridViewRow.Cells[2].Value = package.Version; dataGridViewRow.Cells[3].Value = package.Size.ToString(); dataGridViewRow.Tag = package; dataGridViewDriverPackages.Rows.Add(dataGridViewRow); } } } } string query = "SELECT DISTINCT Model FROM SMS_G_System_COMPUTER_SYSTEM WHERE Manufacturer = 'Dell Inc.'"; List <IResultObject> models = Utility.SearchWMIToList(ConnectionManager, query); foreach (IResultObject model in models) { DataGridViewRow row = dataGridViewDriverPackages.Rows .Cast <DataGridViewRow>() .Where(r => r.Cells[1].Value.ToString().Equals(model["Model"].StringValue, StringComparison.CurrentCultureIgnoreCase)) .FirstOrDefault(); if (row != null) { row.Cells[0].Value = true; row.Cells[4].Value = "Model detected"; known = true; } } foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows) { DellDriverPackage package = (DellDriverPackage)dataGridViewRow.Tag; string path = Path.Combine(sourceFolderPath, package.FolderName); if (Directory.Exists(path)) { string[] fileList = Directory.GetFiles(path, "*.version"); if (File.Exists(Path.Combine(path, package.VersionFile))) { dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[4].Value = "Downloaded"; } else if (fileList.Length > 0) { dataGridViewRow.Cells[0].Value = false; dataGridViewRow.Cells[4].Value = "New version"; } } } dataGridViewDriverPackages.Sort(known ? columnStatus : columnPack, known ? ListSortDirection.Descending : ListSortDirection.Ascending); Initialized = true; }
/// <summary> /// Expects the directory to contain an infopath manifest.xsf & template.xml files. The contents are then persisted & /// indexed by DocTypeName & DocTypeRev (aka solutionVersion) for OpenStream & OpenText operations. As of this writing, /// this application must have write access to the parent folder of the given directory for cab compression operations. /// </summary> /// <param name="importFolderPath"></param> /// <param name="workingFolderPath">default is parent of importFolderPath</param> public static List <ImporterLightDoc> ImportContentFolder(string sourceFolderPath, string workingFolderPath = null) { List <ImporterLightDoc> List_ImporterLightDoc = new List <ImporterLightDoc>(); DirectoryInfo _DirectoryInfo = new DirectoryInfo(sourceFolderPath); if (workingFolderPath == null) { workingFolderPath = RequestPaths.GetPhysicalApplicationPath("import"); } //// ensure the import folder actually exists //Task.Factory.StartNew(() =>{ new DirectoryInfo(workingFolderPath) .mkdir() .Attributes = FileAttributes.NotContentIndexed | FileAttributes.Hidden; //}); string DocMD5, DocTypeVer; string DocTypeName = ScanContentFolder(_DirectoryInfo, out DocTypeVer, out DocMD5); if (!ServiceController.LuceneController.List(new List <string> { "DOCREV" }, null, null, DocMD5).Any()) { try { IList <string> relativeFilePathsInDirectoryTree = GetRelativeFilePathsInDirectoryTree(_DirectoryInfo.FullName, true); IDictionary <string, string> files = CreateStringDictionary(relativeFilePathsInDirectoryTree, relativeFilePathsInDirectoryTree); //the folder's contents compressed string cabFilePath = string.Format(@"{0}\{1}_{2}.cab", workingFolderPath, DocTypeName, FileSystem.CleanFileName(DocTypeVer)); Dictionary <string, string> DocIdKeys = new Dictionary <string, string> { { "TargetDocTypeName", DocTypeName }, { "TargetDocTypeVer", DocTypeVer } }; //TODO:Unit Test this! Generating in memory cab files has not been tested at all!!! using (CompressionEngine _CompressionEngine = new CabEngine { CompressionLevel = CompressionLevel.Max }) using (ArchiveMemoryStreamContext _ArchiveMemoryStreamContext = new ArchiveMemoryStreamContext(cabFilePath, sourceFolderPath, files) { EnableOffsetOpen = true }) using (MemoryStream _TargetDocTypeFilesMemoryStream = new MemoryStream()) { _CompressionEngine.Pack(_ArchiveMemoryStreamContext, files.Keys); string fileName = Path.GetFileName(cabFilePath); uint fileNameLength = (uint)fileName.Length + 1; byte[] fileNameBytes = Encoding.Unicode.GetBytes(fileName); using (MemoryStream CabFileMemoryStream = _ArchiveMemoryStreamContext.DictionaryStringMemoryStream.Values.First()) { CabFileMemoryStream.Position = 0; using (BinaryReader _BinaryReader = new BinaryReader(CabFileMemoryStream)) using (BinaryWriter _BinaryWriter = new BinaryWriter(_TargetDocTypeFilesMemoryStream)) { // Write the InfoPath attachment signature. _BinaryWriter.Write(new byte[] { 0xC7, 0x49, 0x46, 0x41 }); // Write the default header information. _BinaryWriter.Write((uint)0x14); // size _BinaryWriter.Write((uint)0x01); // version _BinaryWriter.Write((uint)0x00); // reserved // Write the file size. _BinaryWriter.Write((uint)_BinaryReader.BaseStream.Length); // Write the size of the file name. _BinaryWriter.Write(fileNameLength); // Write the file name (Unicode encoded). _BinaryWriter.Write(fileNameBytes); // Write the file name terminator. This is two nulls in Unicode. _BinaryWriter.Write(new byte[] { 0, 0 }); // Iterate through the file reading data and writing it to the outbuffer. byte[] data = new byte[64 * 1024]; int bytesRead = 1; while (bytesRead > 0) { bytesRead = _BinaryReader.Read(data, 0, data.Length); _BinaryWriter.Write(data, 0, bytesRead); } } // these contents will be stored in yet another document as an attached cab file IDocRev_Gen2 DocRevBaseDoc = (IDocRev_Gen2)DocInterpreter.Instance.Create("DOCREV"); DocRevBaseDoc.DocChecksum = int.MinValue; DocRevBaseDoc.DocIdKeys = DocIdKeys; DocRevBaseDoc.DocStatus = true; DocRevBaseDoc.DocTitle = String.Format("{0} {1}", DocTypeName, DocTypeVer); DocRevBaseDoc.DocTypeName = "DOCREV"; DocRevBaseDoc.TargetDocTypeFiles = _TargetDocTypeFilesMemoryStream.ToArray(); DocRevBaseDoc.TargetDocTypeName = DocTypeName; DocRevBaseDoc.TargetDocTypeVer = DocTypeVer; /* * BANDAID: DOCREV * (search for this though out the code for more on DOCREV snafus in general), * earlier implementations of DOCREV did not have a TargetDocMD5 property, the IDocRev must be compatible with all versions of this object */ foreach (PropertyInfo p in DocRevBaseDoc.GetType().GetProperties().Where(p => p.Name == "TargetDocMD5")) { p.SetValue(DocRevBaseDoc, DocMD5, null); } List_ImporterLightDoc.Add( new ImporterLightDoc { LightDoc = ServiceController.Instance.Import(DocRevBaseDoc.GetDocData()) }); } } } catch (ThreadAbortException) { } }