Esempio n. 1
0
        public override SignatureVerificationResult VerifySignature(string path, string parent, string virtualPath)
        {
            SignatureVerificationResult svr = base.VerifySignature(path, parent, virtualPath);

            if (VerifyRecursive)
            {
                // MSU is just a CAB file really
                Log.WriteMessage(LogVerbosity.Diagnostic, SignCheckResources.DiagExtractingFileContents, svr.TempPath);
                CabInfo cabInfo = new CabInfo(path);
                cabInfo.Unpack(svr.TempPath);

                foreach (string cabFile in Directory.EnumerateFiles(svr.TempPath))
                {
                    string cabFileFullName = Path.GetFullPath(cabFile);
                    SignatureVerificationResult cabEntryResult = VerifyFile(cabFile, svr.Filename, Path.Combine(svr.VirtualPath, cabFile), cabFileFullName);

                    // Tag the full path into the result detail
                    cabEntryResult.AddDetail(DetailKeys.File, SignCheckResources.DetailFullName, cabFileFullName);

                    svr.NestedResults.Add(cabEntryResult);
                }

                DeleteDirectory(svr.TempPath);
            }

            return(svr);
        }
Esempio n. 2
0
        public static void UnCab(string cabFile, string wspFolderToUse)
        {
            EnsureDirectoryExists(wspFolderToUse);
            CabInfo cabToUnpack = new CabInfo(cabFile);

            cabToUnpack.Unpack(wspFolderToUse);
        }
        private static string ExtractMediaStream(Database db)
        {
            string tempFileName    = Path.GetTempFileName();
            string tempFolder      = FileHelper.GetTempFolder(tempFileName);
            string cabTempFileName = Path.ChangeExtension(tempFileName, ".cab");
            var    cabFileName     = (string)db.ExecuteScalar("SELECT `Cabinet` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 });

            using (View view = db.OpenView("SELECT `Name`, `Data` FROM `_Streams` WHERE `Name` = '{0}'", new object[] { cabFileName.Substring(1) }))
            {
                view.Execute();

                Record record = view.Fetch();

                if (record == null)
                {
                    throw new InstallerException("Stream not found: " + cabFileName);
                }

                using (record)
                    record.GetStream("Data", cabTempFileName);
            }
            var cabinetInfo = new CabInfo(cabTempFileName);

            cabinetInfo.Unpack(tempFolder);
            cabinetInfo.Delete();
            return(tempFolder);
        }
Esempio n. 4
0
        /*public void ExpandFiles(string OutputPath, ProgressCallback progressCallback)
         * {
         *  int buffersize = 0x20000;
         *
         *  int fileCount = Files.Count();
         *
         *  int fileCounter = 0;
         *  foreach (var file in Files)
         *  {
         *      int progressOffset = (int)Math.Round((double)fileCounter / fileCount * 100);
         *      int progressScale = (int)Math.Round((double)1 / fileCount * 100);
         *
         *      var filedirectoryonly = file.Contains("\\") ? string.Join("\\", file.Split('\\').Reverse().Skip(1).Reverse()) : "";
         *      var targetDirectory = Path.Combine(OutputPath, filedirectoryonly);
         *      var targetFile = Path.Combine(OutputPath, file);
         *      if (!Directory.Exists(targetDirectory))
         *          Directory.CreateDirectory(targetDirectory);
         *
         *      using (var inStream = OpenFile(file))
         *      using (var outStream = File.Create(targetFile))
         *      {
         *          byte[] buffer = new byte[buffersize];
         *          for (int i = 0; i < inStream.Length; i += buffersize)
         *          {
         *              int read = inStream.Read(buffer, 0, buffersize);
         *              outStream.Write(buffer, 0, read);
         *              progressCallback.Invoke(progressOffset + (int)Math.Round((double)i / inStream.Length * progressScale), file);
         *          }
         *      }
         *      fileCounter++;
         *  }
         * }*/

        public static void ExpandFiles(string CabinetPath, string OutputPath, ProgressCallback progressCallback)
        {
            CabInfo info = new CabInfo(CabinetPath);

            info.Unpack(OutputPath, (a, b) =>
            {
                progressCallback.Invoke((int)Math.Round((double)b.CurrentArchiveBytesProcessed / b.CurrentArchiveTotalBytes * 100), b.CurrentFileName);
            });
        }
        public string ExtractFromCabFile(string filePath, string destinationFolder)
        {
            CabInfo cab = new CabInfo(filePath);

            cab.Unpack(destinationFolder);
            var filepath = Directory.GetFiles(destinationFolder, "*.xml");

            return(filepath[0]);
        }
Esempio n. 6
0
 public static bool Decompress(string filePath, string extractFolder)
 {
     try
     {
         var cab = new CabInfo(filePath);
         cab.Unpack(extractFolder);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 7
0
        public static string GetKeyedWsp(string wspFile, string company, string servers, DateTime expiry)
        {
            Guid transGuid = new Guid();

            //hax: config me
            string baseDir = @"D:\Hosting\5709750\html\sprockettools\d\";

            string source = baseDir + @"original\" + transGuid.ToString() + @"\";
            string dest   = baseDir + @"modified\";

            //load the cab and unpack it to the temporary directory used for this transaction
            CabInfo cab = new CabInfo(baseDir + wspFile);

            cab.Unpack(source);

            //get xml file
            string      keyXmlFile = source + @"Layouts\SprocketValidator\key.xml";
            XmlDocument xd         = new XmlDocument();

            xd.Load(keyXmlFile);

            //update XML file and write back to disk
            XmlNode n = xd.SelectSingleNode(@"/key");

            n.InnerText = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(company + "|" + servers + "|" + DateTime.Today.AddDays(14).ToShortDateString()));
            using (XmlWriter xw = XmlWriter.Create(keyXmlFile))
            {
                xd.WriteTo(xw);
                xw.Flush();
            }

            //create a list with files and add them to a cab file
            string  newFile = (dest + DateTime.Now.ToString("yyyyMMdd") + "_" + company + "_" + wspFile).Replace(" ", "");
            CabInfo newCab  = new CabInfo(newFile);

            List <string> paths = new List <string>();

            //put files into list to be packed
            foreach (string compFile in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
            {
                paths.Add(compFile.Replace(source, ""));
            }

            newCab.PackFiles(source, paths, paths);

            //delete the transaction directory
            Directory.Delete(source, true);

            return(newFile);
        }
Esempio n. 8
0
        public static bool ExpandCabFile(string cabFile, string destDir)
        {
            if (!Directory.Exists(destDir))
            {
                DirectoryInfo dir = Directory.CreateDirectory(destDir);
            }
            if (!Directory.Exists(destDir))
            {
                return(false);
            }

            CabInfo cab = new CabInfo(cabFile);

            cab.Unpack(destDir);
            return(true);
        }
        public List <byte[]> UnpackFile(byte[] data)
        {
            List <byte[]> list = new List <byte[]>();

            if (data == null)
            {
                list.Add(data);
                return(list);
            }

            if (data.LongLength < 4)
            {
                list.Add(data);
                return(list);
            }
            //MSCF
            if (!(data[0] == 77 && data[1] == 83 && data[2] == 67 && data[3] == 70))
            {
                list.Add(data);
                return(list);
            }

            var fileName = $"{ExtractorPath}{ExtractorFile}";

            File.WriteAllBytes(fileName, data);
            CabInfo cab = new CabInfo(fileName);

            try
            {
                cab.Unpack(ExtractorDataPath);
                DirectoryInfo d     = new DirectoryInfo(ExtractorDataPath);
                var           files = d.GetFiles("*.*");
                foreach (var file in files)
                {
                    list.Add(File.ReadAllBytes($@"{ExtractorDataPath}\{file.Name}"));
                    File.Delete($@"{ExtractorDataPath}\{file.Name}");
                }

                File.Delete(fileName);
            }
            catch (Exception e)
            {
                throw e;
            }

            return(list);
        }
        /// <summary>
        /// Extract a .CAB file to the specified folder.
        /// </summary>
        /// <param name="cabFileToExtract">Full path to the .CAB file to extract.</param>
        /// <param name="destinationFolder">Full path to the folder where extract the .cab file.</param>
        /// <returns>True if the extraction succeeded, false otherwise.</returns>
        private bool ExtractCabToFolder(string cabFileToExtract, string destinationFolder)
        {
            Logger.EnteringMethod(cabFileToExtract + " To " + destinationFolder);
            try
            {
                EventHandler <ArchiveProgressEventArgs> unpackArchiveProgression = new EventHandler <ArchiveProgressEventArgs>(UnpackArchiveProgress);
                CabInfo unpacker = new CabInfo(cabFileToExtract);
                unpacker.Unpack(destinationFolder, unpackArchiveProgression);
                Logger.Write("Successfuly extract CAB file.");
                if (UnpackArchiveFinished != null)
                {
                    UnpackArchiveFinished();
                }
                return(true);
            }
            catch (Exception ex) { Logger.Write("**** " + ex.Message); }

            return(false);
        }
Esempio n. 11
0
        private static void DownloadAndUnpackCab()
        {
            var webClient = new WebClient();

            try
            {
                if (Settings.Proxy != null)
                {
                    webClient.Proxy = Settings.Proxy;
                }
                webClient.DownloadFile("http://update.microsoft.com/redist/wuredist.cab",
                                       Path.Combine(TempDir, CabFileName));
            }
            catch (Exception e)
            {
                Logger.Log("Could not download WUA cab file.", LogLevel.Error);
                Logger.LogException(e);
            }

            var cab = new CabInfo(Path.Combine(TempDir, CabFileName));

            cab.Unpack(TempDir);
        }
Esempio n. 12
0
        /// <summary>Extracts all contents of a cab to a folder</summary>
        /// <param name="Cab"></param>
        /// <param name="Folder"></param>
        public static void CabToFolder(string Cab, string Folder)
        {
            CabInfo C = new CabInfo(Cab);

            C.Unpack(Folder, ProgHandler);
        }
Esempio n. 13
0
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using BtsMsiLib.Utilities;
using Microsoft.Deployment.Compression.Cab;
using Microsoft.Deployment.WindowsInstaller;

namespace BtsMsiLib.Msi
{
    //TODO: User better variable names in general
    public static class MsiDatabaseExtensions
    {
        public static void UpdateSummaryInfo(this Database db)
        {
            // TODO: Correct values needs to be set
            using (SummaryInfo summaryInfo = db.SummaryInfo)
            {
                summaryInfo.Title = "A";
                summaryInfo.Author = "B";
                summaryInfo.Subject = "C";
                summaryInfo.Comments = "D";
                summaryInfo.Keywords = "BizTalk, deployment, application, " + "sdfsdWfsdf";
                summaryInfo.RevisionNumber = Guid.NewGuid().ToString("B").ToUpperInvariant();
                summaryInfo.CreatingApp = typeof(MsiDatabaseExtensions).Assembly.FullName;
                summaryInfo.CreateTime = DateTime.Now;
                summaryInfo.Persist();
            }
        }

        public static void UpdateSummaryInfo(this Database db, BtsMsiLib.Model.BtsApplication btsApp)
        {
            using (SummaryInfo summaryInfo = db.SummaryInfo)
            {
                summaryInfo.Title = btsApp.Name;
                summaryInfo.Author = btsApp.Authors;
                summaryInfo.Subject = btsApp.Subject;
                summaryInfo.Comments = btsApp.Description;
                summaryInfo.Keywords = btsApp.Keywords;
                summaryInfo.RevisionNumber = Guid.NewGuid().ToString("B").ToUpperInvariant();
                summaryInfo.CreatingApp = typeof(MsiDatabaseExtensions).Assembly.FullName;
                summaryInfo.CreateTime = DateTime.Now;
                summaryInfo.Persist();
            }
        }

        public static void UpdateUpgradeTable(this Database db, Guid upgradeCode)
        {
            using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
            {
                view.Execute();
                using (Record record = view.Fetch())
                {
                    record[1] = upgradeCode.ToString("B").ToUpperInvariant();
                    view.Replace(record);
                }

                db.Commit();
            }
        }

        public static void UpdateProperties(this Database db, IDictionary<string, object> properties)
        {
            using (View view = db.OpenView("SELECT * FROM `Property`", new object[0]))
            {
                view.Execute();
                foreach (string index in properties.Keys)
                {
                    using (var record = new Record(2))
                    {
                        record[1] = index;
                        record[2] = properties[index];
                        view.Assign(record);
                    }
                }

                db.Commit();
            }
        }

        public static void UpdateFileContent(this Database db, string folder, string adfFile, int resourceCount)
        {
            using (View view1 = db.OpenView("SELECT * FROM `File` WHERE `FileName` = 'APPLIC~1.ADF|ApplicationDefinition.adf'", new object[0]))
            {
                view1.Execute();
                using (Record record1 = view1.Fetch())
                {
                    string path2_1 = (string)record1[1];
                    Guid guid = Guid.NewGuid();
                    string path2_2 = "_" + guid.ToString("N").ToUpperInvariant();
                    string str1 = "C_" + path2_2;
                    string mediaStream = ExtractMediaStream(db);

                    File.Delete(Path.Combine(mediaStream, path2_1));

                    File.Copy(adfFile, Path.Combine(mediaStream, path2_2));
                    using (View view2 = db.OpenView("SELECT * FROM `Component` WHERE `KeyPath` = '{0}'", new object[]
                      {
                        path2_1
                      }))
                    {
                        view2.Execute();
                        using (Record record2 = view2.Fetch())
                        {
                            record2[1] = str1;
                            record2[2] = guid.ToString("B").ToUpperInvariant();
                            record2[6] = path2_2;
                            record2[3] = "ADFDIR";
                            view2.Replace(record2);
                        }
                    }
                    using (View view2 = db.OpenView("SELECT * FROM `FeatureComponents` WHERE `Component_` = '{0}'", new object[] { "C_" + path2_1 }))
                    {
                        view2.Execute();
                        using (Record record2 = view2.Fetch())
                        {
                            record2[2] = str1;
                            view2.Assign(record2);
                        }
                    }
                    record1[1] = path2_2;
                    record1[2] = str1;
                    record1[4] = FileHelper.FileSize(adfFile);
                    view1.Replace(record1);
                    var num = (int)db.ExecuteScalar("SELECT `LastSequence` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 });

                    for (int index = 0; index < resourceCount; ++index)
                    {
                        string cabFileName = string.Format(CultureInfo.InvariantCulture, "ITEM~{0}.CAB", new object[]{index});
                        string cabFilePath = Path.Combine(folder, cabFileName);
                        record1[1] = "_" + Guid.NewGuid().ToString("N").ToUpperInvariant();
                        record1[3] = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", new object[]
                        {
                            cabFileName,
                            cabFileName
                        });
                        record1[4] = FileHelper.FileSize(cabFilePath);
                        record1[8] = ++num;
                        view1.Assign(record1);
                        File.Copy(cabFilePath, Path.Combine(mediaStream, (string)record1[1]));
                    }

                    UpdateMediaCab(db, mediaStream, num);
                }
            }
        }

        private static string ExtractMediaStream(Database db)
        {
            string tempFileName = Path.GetTempFileName();
            string tempFolder = FileHelper.GetTempFolder(tempFileName);
            string cabTempFileName = Path.ChangeExtension(tempFileName, ".cab");
            var cabFileName = (string)db.ExecuteScalar("SELECT `Cabinet` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 });

            using (View view = db.OpenView("SELECT `Name`, `Data` FROM `_Streams` WHERE `Name` = '{0}'", new object[] { cabFileName.Substring(1) }))
            {
                view.Execute();
                
                Record record = view.Fetch();
                
                if (record == null)
                    throw new InstallerException("Stream not found: " + cabFileName);

                using (record)
                    record.GetStream("Data", cabTempFileName);
            }
            var cabinetInfo = new CabInfo(cabTempFileName);
            cabinetInfo.Unpack(tempFolder);
            cabinetInfo.Delete();
            return tempFolder;
        }

        private static void UpdateMediaCab(Database msiDb, string folderToPack, int lastSequence)
        {
            string tempFileName = Path.GetTempFileName();

            if (File.Exists(tempFileName))
                File.Delete(tempFileName);

            string cabFileName = Path.ChangeExtension(tempFileName, ".cab");

            new CabInfo(cabFileName).Pack(folderToPack);

            Directory.Delete(folderToPack, true);

            var list = new List<string>();
            using (View view = msiDb.OpenView("SELECT `File` FROM `File`", new object[0]))
            {
                view.Execute();
                Record record;
                while ((record = view.Fetch()) != null)
                {
                    using (record)
                        list.Add((string)record[1]);
                }
                list.Sort();
            }

            using (View view = msiDb.OpenView("SELECT `File`, `Sequence` FROM `File`", new object[0]))
            {
                view.Execute();
                for (Record record = view.Fetch(); record != null; record = view.Fetch())
                {
                    using (record)
                    {
                        record[2] = list.IndexOf((string)record[1]) + 1;
                        view.Update(record);
                    }
                }
            }

            string cabinet;
            using (View view = msiDb.OpenView("SELECT `LastSequence`, `Cabinet` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 }))
            {
                view.Execute();
                Record record = view.Fetch();
                if (record == null)
                    throw new InstallerException("Media for DiskID=1 is not found: ");
                using (record)
                {
                    cabinet = (string)record[2];
                    record[1] = lastSequence;
                    view.Update(record);
                }
            }

            using (View view = msiDb.OpenView("SELECT `Name`, `Data` FROM `_Streams` WHERE `Name` = '{0}'", new object[] { cabinet.Substring(1) }))
            {
                view.Execute();
                Record record = view.Fetch();
                using (record)
                {
                    record.SetStream("Data", cabFileName);
                    view.Update(record);
                }
            }
        }

        public static void MakeCustomModifications(this Database db, Guid productCode, string applicationName)
        {
            string productCodeUpper = productCode.ToString("B").ToUpperInvariant();
            string shortProductCode = productCodeUpper.Substring(1, productCodeUpper.Length - 2);

            using (View view = db.OpenView("SELECT * FROM `Directory`", new object[0]))
            {
                view.Execute();
                using (var record = new Record(3))
                {
                    record[1] = "ADFDIR";
                    record[2] = "TARGETDIR";
                    record[3] = shortProductCode;
                    view.Assign(record);
                }
                db.Commit();
            }

            using (View view = db.OpenView("SELECT * FROM `ControlCondition`", new object[0]))
            {
                view.Execute();
                using (var record = new Record(4))
                {
                    record[1] = "FolderForm";
                    record[2] = "DiskCostButton";
                    record[3] = "Hide";
                    record[4] = "1=1";
                    view.Assign(record);
                }
                db.Commit();
            }

            Guid applicationGuid = Hasher.HashApplicationName(applicationName);
            string applicationCompId = "C__" + applicationGuid.ToString("N").ToUpperInvariant();

            string msiCompId;
            using (View view = db.OpenView("SELECT * FROM `File` WHERE `FileName` = 'APPLIC~1.ADF|ApplicationDefinition.adf'", new object[0]))
            {
                view.Execute();
                using (Record record = view.Fetch())
                    msiCompId = record[2].ToString();
                db.Commit();
            }

            CustomModifyRegistry(db, applicationCompId, msiCompId);
            CustomModifyComponent(db, applicationGuid, applicationCompId);
            CustomModifyFeatureComponents(db, applicationCompId, msiCompId);
            CustomModifyCustomAction(db);
            ModifySecureCustomProperties(db);
            AddErrorTableEntry(db);
        }

        private static void CustomModifyRegistry(Database msiDb, string applicationCompId, string msiCompId)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Key` = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\[ProductName]\\[ProductCode]'", new object[0]))
            {
                view.Execute();
                using (Record record = view.Fetch())
                {
                    record[6] = msiCompId;
                    view.Replace(record);
                }
            }

            using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Key` = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\[ProductName]' AND `Name` = '*'", new object[0]))
            {
                view.Execute();
                using (Record record = view.Fetch())
                {
                    record[6] = applicationCompId;
                    view.Replace(record);
                }
            }

            CustomModifyRegistryEntry(msiDb, applicationCompId, "NoModify");
            ModifyReadmeRegistryEntry(msiDb, applicationCompId);
            CustomModifyRegistryEntry(msiDb, applicationCompId, "URLInfoAbout");
            CustomModifyRegistryEntry(msiDb, applicationCompId, "Contact");
            CustomModifyRegistryEntry(msiDb, applicationCompId, "Uninstallstring");
            CustomModifyRegistryEntry(msiDb, applicationCompId, "NoRepair");
            CustomModifyRegistryEntry(msiDb, applicationCompId, "DisplayName");

            msiDb.Commit();
        }

        private static void CustomModifyComponent(Database msiDb, Guid applicationGuid, string applicationCompId)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Component` WHERE `Directory_` = 'TARGETDIR' AND `Attributes` = 4", new object[0]))
            {
                view.Execute();
                using (Record record = view.Fetch())
                {
                    record[1] = applicationCompId;
                    record[2] = applicationGuid.ToString("B").ToUpperInvariant();
                    view.Replace(record);
                }
                while (true)
                {
                    using (Record record = view.Fetch())
                    {
                        if (record != null)
                            view.Delete(record);
                        else
                            break;
                    }
                }
                msiDb.Commit();
            }
        }

        private static void CustomModifyFeatureComponents(Database msiDb, string applicationCompId, string msiCompId)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `FeatureComponents`", new object[0]))
            {
                view.Execute();
                while (true)
                {
                    using (Record record = view.Fetch())
                    {
                        if (record != null)
                            view.Delete(record);
                        else
                            break;
                    }
                }

                const string featureName = "DefaultFeature";
                
                using (var record = new Record(2))
                {
                    record[1] = featureName;
                    record[2] = applicationCompId;
                    view.Assign(record);
                }

                using (var record = new Record(2))
                {
                    record[1] = featureName;
                    record[2] = msiCompId;
                    view.Assign(record);
                }
                msiDb.Commit();
            }
        }

        private static void CustomModifyCustomAction(Database msiDb)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `CustomAction` WHERE `Source` = 'InstallUtil'", new object[0]))
            {
                view.Execute();
                
                while (true)
                {
                    using (Record record = view.Fetch())
                    {
                        if (record != null)
                        {
                            record.SetInteger(2, record.GetInteger(2) | 2048);
                            view.Replace(record);
                        }
                        else
                            break;
                    }
                }

                msiDb.Commit();
            }
        }

        private static void ModifySecureCustomProperties(Database msiDb)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Property` WHERE `Property` = 'SecureCustomProperties'", new object[0]))
            {
                view.Execute();

                using (Record record = view.Fetch())
                {
                    record[2] = "NEWERPRODUCTFOUND;BTSVERSION;BTSPATH;BTSPRODUCTNAME";
                    view.Replace(record);
                }

                msiDb.Commit();
            }
        }

        private static void AddErrorTableEntry(Database msiDb)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Error`", new object[0]))
            {
                view.Execute();
                using (var record = new Record(2))
                {
                    record[1] = 1001;
                    record[2] = "Error [1]: [2]";
                    view.Assign(record);
                }
                msiDb.Commit();
            }
        }

        private static void CustomModifyRegistryEntry(Database msiDb, string compId, string name)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Name` = '{0}'", new object[] { name }))
            {
                view.Execute();

                using (Record record = view.Fetch())
                {
                    record[6] = compId;
                    view.Replace(record);
                }
            }
        }

        private static void ModifyReadmeRegistryEntry(Database msiDb, string compId)
        {
            using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Name` = '{0}'", new object[] { "Readme" }))
            {
                view.Execute();

                using (Record record = view.Fetch())
                {
                    record[6] = compId;
                    record[5] = "file://[TARGETDIR]Readme.htm";
                    view.Replace(record);
                }
            }
        }
    }
}

Esempio n. 14
0
        private void ExtractFiles()
        {
            if (_extractFiles.Any())
            {
                KeyValuePair <DellDriverPackage, string> data = _extractFiles.Dequeue();

                // add model so we can re-use it in functions
                DellDriverPackage package = data.Key;
                currentModel = package.Model;

                // update my best friend the progress bar
                backgroundWorker.ReportProgress(Convert.ToInt32(50 + ((40 / totalPacks * extracted) * 0.5)), string.Format("Processing {0} : extracting to temp folder", currentModel));
                // generate model folder name

                // hp sp extract does not work directly to network share, put in temp folder first and than copy to share
                string tempFolder        = Path.Combine(tempFolderPath, "extract", package.FolderName);
                string destinationFolder = Path.Combine(sourceFolderPath, package.FolderName);

                try
                {
                    var cab = new CabInfo(data.Value);
                    cab.Unpack(tempFolder);

                    // update my best friend the progress bar
                    backgroundWorker.ReportProgress(Convert.ToInt32(50 + ((80 / totalPacks * extracted) * 0.5)), string.Format("Processing {0} : moving to destination folder", currentModel));

                    if (!Directory.Exists(tempFolder))
                    {
                        throw new DirectoryNotFoundException("Temp folder not found " + tempFolder);
                    }

                    // add a version file to the folder so we can check later if there is an update to the download
                    string versionFile = Path.Combine(tempFolderPath, "extract", package.FolderName, package.VersionFile);
                    File.Create(versionFile).Close();

                    // wipe old soruce folder
                    if (registry.ReadBool("WipeSource") && Directory.Exists(destinationFolder))
                    {
                        Directory.Delete(destinationFolder, true);
                    }

                    // remove old version file
                    if (Directory.Exists(destinationFolder))
                    {
                        string[] fileList = Directory.GetFiles(destinationFolder, "*.version");
                        foreach (string file in fileList)
                        {
                            File.Delete(file);
                        }
                    }

                    Utility.Copy(tempFolder, destinationFolder, true);

                    Directory.Delete(tempFolder, true);
                }
                catch (Exception ex)
                {
                    error.Add(package.Model, "Cannot extract driver pack: " + ex.Message);

                    CheckExtractQueueCompleted();

                    return;
                }

                successful.Add(currentModel);

                CheckExtractQueueCompleted();

                return;
            }
            // fix if all download fails, dont get stuck in this loop
            else if (_extractFiles.Count == 0)
            {
                extractQueueFinished = true;

                return;
            }
        }
Esempio n. 15
0
        private void InsertUpdateFileToCab(string filePath)
        {
            EFile file;


            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                FileInfo fileInfo = new FileInfo(filePath);
                file            = new EFile();
                file.FileName   = Path.GetFileName(filePath);
                file.Lenght     = fileInfo.Length;
                file.LastUpDate = DateTime.Now;
                file.Source     = "New File";
                file.FileIcon   = FileIconLoader.GetFileIcon(file.FileName, false);
            }
            string temp = Path.GetTempPath() + "TempCab";

            cab.Unpack(temp);

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(Path.GetTempPath() + "TempCab/_setup.xml");
            XmlNode root = xmldoc.SelectSingleNode("/wap-provisioningdoc/characteristic[@type='FileOperation']/characteristic[@translation='install']");
            //XmlNode root = xmldoc.SelectSingleNode("/wap-provisioningdoc/characteristic[@type='FileOperation']");


            //root.Attributes[""] = "";

            bool isExist = false;

            foreach (EFile f in Files)
            {
                if ((f.FileName.ToLower() == file.FileName.ToLower()) || (f.FileName.ToUpper() == file.FileName.ToUpper()))
                {
                    isExist     = true;
                    file.Source = f.Source;

                    f.Lenght     = file.Lenght;
                    f.LastUpDate = file.LastUpDate;

                    File.Copy(filePath, temp + "\\" + file.Source, true);
                }
            }

            if (!isExist)
            {
                File.Copy(filePath, temp + "\\" + file.FileName, true);

                //XmlNode node = xmldoc.CreateNode(XmlNodeType.Element, "characteristic",null);

                //XmlAttribute attr_type = xmldoc.CreateAttribute("type");
                //attr_type.Value = file.FileName;

                //XmlAttribute attr_translation = xmldoc.CreateAttribute("install");
                //attr_translation.Value = "install";

                //node.Attributes.Append(attr_type);
                //node.Attributes.Append(attr_translation);

                //root.AppendChild(node);

                //xmldoc.Save(Path.GetTempPath() + "TempCab/_setup.xml");

                Files.Add(file);
            }



            cab.Pack(temp, true, Microsoft.Deployment.Compression.CompressionLevel.None, null);

            Directory.Delete(temp, true);

            BindDataGrid();
        }
Esempio n. 16
0
        /// <summary>
        /// Unpack an AAPKG file into a specified directory
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="DestinationDirectory"></param>
        public void UnpackAAPKG(string AAPKGFilePath, string DestinationDirectory)
        {
            log.Debug("AAPKGFilePath: " + AAPKGFilePath);
            log.Debug("DestinationDirectory: " + DestinationDirectory);
            log.Debug("begin");

            string file1Path;
            string outerUnpackPath;

            try
            {
                // Calculate our outer unpack path
                outerUnpackPath = Path.GetTempPath();
                log.Debug("outerUnpackPath: " + outerUnpackPath);

                // Go ahead and setup file1 path using the temp folder
                file1Path = outerUnpackPath + "file1.cab";
                log.Debug("file1Path: " + file1Path);

                log.Debug("Outer extraction");
                try
                {
                    // Remove the outer AAPKG wrapper to reveal the inner file1.cab
                    using (ZipFile zip1 = ZipFile.Read(AAPKGFilePath))
                    {
                        log.Debug("ExtractAll to " + outerUnpackPath);
                        zip1.ExtractAll(outerUnpackPath, ExtractExistingFileAction.OverwriteSilently);
                    }
                }
                catch (Ionic.Zip.ZipException)
                {
                    log.Debug("Exception using ExtractAll");
                    log.Debug("Trying to use CabInfo.UnPack");
                    // If we have an error reading as a zip then try to unpack as a CAB
                    CabInfo ci = new CabInfo(AAPKGFilePath);
                    ci.Unpack(outerUnpackPath);
                }

                log.Debug("inner extraction");
                // Extract the innner file1.cab to the destination directory
                try
                {
                    using (ZipFile zip2 = ZipFile.Read(file1Path))
                    {
                        log.Debug("ExtractAll to " + DestinationDirectory);
                        zip2.ExtractAll(DestinationDirectory, ExtractExistingFileAction.OverwriteSilently);
                    }
                }
                catch (Ionic.Zip.ZipException)
                {
                    log.Debug("Exception using ExtractAll");
                    log.Debug("Trying to use CabInfo.UnPack for " + file1Path);
                    // If we have an error reading as a zip then try to unpack as a CAB
                    CabInfo ci = new CabInfo(file1Path);
                    ci.Unpack(DestinationDirectory);
                }

                log.Debug("Delete path " + file1Path);
                // Delete the file1.cab
                System.IO.File.Delete(file1Path);
            }
            catch
            {
                throw;
            }
        }