private async Task CopyPackageFileToPath(string installPath, IPackageFile packageFile)
 {
     using (var fileStream = File.Create(Path.Combine(installPath, Path.GetFileName(packageFile.Path))))
     {
         await packageFile.GetStream().CopyToAsync(fileStream);
     }
 }
Ejemplo n.º 2
0
 internal static string Process(IPackageFile file, IPropertyProvider propertyProvider)
 {
     using (var stream = file.GetStream())
     {
         return Process(stream, propertyProvider, throwIfNotFound: false);
     }
 }
 private static PackageIssue CreatePackageIssue(IPackageFile file)
 {
     return new PackageIssue(
         AnalysisResources.MisplacedInitScriptTitle,
         String.Format(CultureInfo.CurrentCulture, AnalysisResources.MisplacedInitScriptDescription, file.Path),
         AnalysisResources.MisplacedInitScriptSolution);
 }
 public PowerShellConsole(IPackage package, IProcess process, IFileSystem fileSystem, IPackageFile packageFile)
 {
     this.fileSystem = fileSystem;
     this.package = package;
     this.process = process;
     this.packageFile = packageFile;
 }
Ejemplo n.º 5
0
 private static PackageIssue CreateIssue(IPackageFile file)
 {
     return new PackageIssue(
         AnalysisResources.WinRTObsoleteTitle,
         String.Format(CultureInfo.CurrentCulture, AnalysisResources.WinRTObsoleteDescription, file.Path),
         AnalysisResources.WinRTObsoleteSolution);
 }
Ejemplo n.º 6
0
        public void ConvertWithTwoFilesInDifferentFolders()
        {
            // Arrange
            var files = new IPackageFile[] {
                CreatePackageFile(@"content\one.txt"),
                CreatePackageFile(@"lib\two.dll")
            };

            // Act
            var root = PathToTreeConverter.Convert(files);

            // Assert
            Assert.NotNull(root);
            AssertItem(root, "", 2);

            var contentNode = root.Children.ElementAt(0);
            AssertItem(contentNode, "content", 1);

            var libNode = root.Children.ElementAt(1);
            AssertItem(libNode, "lib", 1);

            var firstChild = contentNode.Children.ElementAt(0);
            AssertItem(firstChild, "one.txt", 0);

            var secondChild = libNode.Children.ElementAt(0);
            AssertItem(secondChild, "two.dll", 0);
        }
        private static string CheckFile(string url, IPackageFile file)
        {
            var binary = new BinaryStoreManager();
            var symbol = new SymbolStoreManager();

            var name = Path.ChangeExtension(Path.GetFileName(file.Path), "pdb");
            var compressedName = name.Substring(0, name.Length - 1) + '_';

            string hash;

            using (var stream = file.GetStream())
                hash = binary.ReadPdbHash(stream);

            byte[] buffer;

            try
            {
                using (var client = new WebClient())
                    buffer = client.DownloadData(string.Format("{0}/{1}/{2}/{3}", url, name, hash, compressedName));
            }
            catch (WebException exception)
            {
                return ((HttpWebResponse)exception.Response).StatusCode.ToString();
            }

            //using (var stream = new MemoryStream(buffer))
            //    if (symbol.ReadHash(stream) != hash)
            //        return "MISMATCHED";

            return "FOUND";
        }
Ejemplo n.º 8
0
 public void TransformFile(IPackageFile file, string targetPath, IProjectSystem projectSystem)
 {
     if (!projectSystem.FileExists(targetPath)) {
         using (Stream stream = Process(file, projectSystem).AsStream()) {
             projectSystem.AddFile(targetPath, stream);
         }
     }
 }
Ejemplo n.º 9
0
 private static XElement GetXml(IPackageFile file, IProjectSystem projectSystem)
 {
     using (Stream stream = file.GetStream())
     {
         var content = Preprocessor.Process(file, projectSystem);
         return XElement.Parse(content);
     }
 }
Ejemplo n.º 10
0
        private PackageFile(IPackageFile file, string name, PackageFolder parent, PackageViewModel viewModel)
            : base(name, parent, viewModel)
        {
            if (file == null) {
                throw new ArgumentNullException("file");
            }

            _file = file;
        }
        public ZipPackageAssemblyReference(IPackageFile file)
            : base(file)
        {
            Debug.Assert(Path.StartsWith("lib", StringComparison.OrdinalIgnoreCase), "path doesn't start with lib");

            // Get rid of the lib folder            
            string path = Path.Substring(3).Trim(System.IO.Path.DirectorySeparatorChar);

            _targetFramework = VersionUtility.ParseFrameworkFolderName(path);
        }
Ejemplo n.º 12
0
 private static string ResolvePath(IPackageFile packageFile)
 {
     var physicalPackageFile = packageFile as PhysicalPackageFile;
     // For PhysicalPackageFiles, we want to filter by SourcePaths, the path on disk. The Path value maps to the TargetPath
     if (physicalPackageFile == null)
     {
         return packageFile.Path;
     }
     return physicalPackageFile.SourcePath;
 }
 private static bool VerifySigned(IPackageFile packageFile)
 {
     bool result;
     using (Stream stream = packageFile.GetStream())
     {
         System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
         string text = streamReader.ReadToEnd();
         result = (text.IndexOf("# SIG # Begin signature block", StringComparison.OrdinalIgnoreCase) > -1 && text.IndexOf("# SIG # End signature block", StringComparison.OrdinalIgnoreCase) > -1);
     }
     return result;
 }
        public IAddInfo Build(IPackageFile directoryInfo, IEnumerable<IPackageEntry> includeFiles)
        {
            var addInfo = new AddInfo();

            var items = directoryInfo.Entries.ToArray();

            addInfo.Binaries = includeFiles
                .Select(b => BuildBinaryInfo(addInfo, items, b))
                .ToArray();

            return addInfo;
        }
Ejemplo n.º 15
0
        public void TransformFile(IPackageFile file, string targetPath, IProjectSystem projectSystem)
        {
            // Get the xml fragment
            XElement xmlFragment = GetXml(file, projectSystem);

            XDocument transformDocument = XmlUtility.GetOrCreateDocument(xmlFragment.Name, projectSystem, targetPath);

            // Do a merge
            transformDocument.Root.MergeWith(xmlFragment, _nodeActions);

            projectSystem.AddFile(targetPath, transformDocument.Save);
        }
Ejemplo n.º 16
0
        public IAddInfo Build(IPackageFile directoryInfo)
        {
            var addInfo = new AddInfo();

            var items = directoryInfo.Entries.ToArray();

            addInfo.Binaries = items
                .Where(f => f.FullPath.EndsWith("exe", StringComparison.InvariantCultureIgnoreCase) || f.FullPath.EndsWith("dll", StringComparison.InvariantCultureIgnoreCase))
                .Select(b => BuildBinaryInfo(addInfo, items, b))
                .ToArray();

            return addInfo;
        }
Ejemplo n.º 17
0
        private static void PerformXdtTransform(IPackageFile file, string targetPath, IProjectSystem projectSystem)
        {
            if (projectSystem.FileExists(targetPath))
            {
                string content = Preprocessor.Process(file, projectSystem);

                try
                {
                    using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null))
                    {
                        using (var document = new XmlTransformableDocument())
                        {
                            document.PreserveWhitespace = true;

                            // make sure we close the input stream immediately so that we can override 
                            // the file below when we save to it.
                            using (var inputStream = projectSystem.OpenFile(targetPath))
                            {
                                document.Load(inputStream);
                            }

                            bool succeeded = transformation.Apply(document);
                            if (succeeded)
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    // save the result into a memoryStream first so that if there is any
                                    // exception during document.Save(), the original file won't be truncated.
                                    document.Save(memoryStream);
                                    memoryStream.Seek(0, SeekOrigin.Begin);
                                    using (var fileStream = projectSystem.CreateFile(targetPath))
                                    {
                                        memoryStream.CopyTo(fileStream);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new InvalidDataException(
                        String.Format(
                            CultureInfo.CurrentCulture, 
                            NuGetResources.XdtError + " " + exception.Message,
                            targetPath, 
                            projectSystem.ProjectName), 
                        exception);
                }
            }
        }
        public IAddInfo Build(IPackageFile directoryInfo)
        {
            var addInfo = new AddInfo();

            var items = directoryInfo.Entries.ToArray();
            var binaryExtensions = new[] { ".dll", ".exe", ".winmd" };

            addInfo.Binaries = items
                .Where(f => binaryExtensions.Any(e => f.FullPath.EndsWith(e, StringComparison.InvariantCultureIgnoreCase)))
                .Select(b => BuildBinaryInfo(addInfo, items, b))
                .ToArray();

            return addInfo;
        }
Ejemplo n.º 19
0
        private static byte[] GetConfigurationFileAsBytes(IPackageFile agentConfigurationFile)
        {
            var agentConfigurationFileStream = agentConfigurationFile.GetStream();

            byte[] configBytes;

            using (var memoryStream = new MemoryStream())
            {
                agentConfigurationFileStream.CopyTo(memoryStream);
                configBytes = memoryStream.ToArray();
                memoryStream.Close();
            }
            return configBytes;
        }
Ejemplo n.º 20
0
        public void ConvertWithOneFile()
        {
            // Arrange
            var files = new IPackageFile[] {
                CreatePackageFile(@"one.txt")
            };

            // Act
            var root = PathToTreeConverter.Convert(files);

            // Assert
            Assert.NotNull(root);
            AssertItem(root, "", 1);
            AssertItem(root.Children.ElementAt(0), "one.txt", 0);
        }
Ejemplo n.º 21
0
        public void RevertFile(IPackageFile file, string targetPath, IEnumerable<IPackageFile> matchingFiles, IProjectSystem projectSystem)
        {
            // Get the xml snippet
            XElement xmlFragment = GetXml(file, projectSystem);

            XDocument document = XmlUtility.GetOrCreateDocument(xmlFragment.Name, projectSystem, targetPath);

            // Merge the other xml elements into one element within this xml hierarchy (matching the config file path)
            var mergedFragments = matchingFiles.Select(f => GetXml(f, projectSystem))
                                               .Aggregate(new XElement(xmlFragment.Name), (left, right) => left.MergeWith(right, _nodeActions));

            // Take the difference of the xml and remove it from the main xml file
            document.Root.Except(xmlFragment.Except(mergedFragments));

            // Save the new content to the file system
            projectSystem.AddFile(targetPath, document.Save);
        }
Ejemplo n.º 22
0
        private PackageFile(IPackageFile file, string name, PackageFolder parent, PackageViewModel viewModel)
            : base(name, parent, viewModel)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            _file = file;

            var physicalFile = file as PhysicalPackageFile;
            if (physicalFile != null)
            {
                WatchPhysicalFile(physicalFile);
            }
            ReplaceCommand = new RelayCommand(Replace, () => !viewModel.IsInEditFileMode);
        }
        public void Execute(IPackageFile file, IPackage package, ILogger logger)
        {
            if (file == null)
            {
                throw ExceptionFactory.CreateArgumentNullException("file");
            }

            if (logger == null)
            {
                throw ExceptionFactory.CreateArgumentNullException("logger");
            }

            var installationPath = Path.Combine(
                this.manager.FileSystem.Root, this.manager.PathResolver.GetPackageDirectory(package));
            IShellConsole console = new PowerShellConsole(package, this.process, this.fileSystem, file);
            var processExitInfo = console.Start(installationPath, this.configurationPath);

            Func<string, bool> predicate = message => !string.IsNullOrWhiteSpace(message);
            foreach (var message in processExitInfo.OutputMessage.Split('\n').Where(predicate))
            {
                logger.Log(MessageLevel.Info, message.Trim());
            }

            foreach (var message in processExitInfo.ErrorMessage.Split('\n').Where(predicate))
            {
                logger.Log(MessageLevel.Error, message.Trim());
            }

            if (processExitInfo.ExitCode > 0)
            {
                throw ExceptionFactory.CreateInvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.PowershellErrorMessage,
                        file.Path,
                        processExitInfo.ErrorMessage));
            }
        }
Ejemplo n.º 24
0
        private bool ExecuteCore(
            string fullScriptPath,
            string installPath,
            IPackage package,
            Project project,
            FrameworkName targetFramework,
            ILogger logger,
            IPackageFile scriptFile)
        {
            if (File.Exists(fullScriptPath))
            {
                if (project != null && scriptFile != null)
                {
                    // targetFramework can be null for unknown project types
                    string shortFramework = targetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(targetFramework);

                    logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(),
                        project.Name, shortFramework);

                    logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo_PowershellScripts,
                        Path.GetDirectoryName(scriptFile.Path), VersionUtility.GetTargetFrameworkLogString(scriptFile.TargetFramework));
                }

                string toolsPath = Path.GetDirectoryName(fullScriptPath);
                string logMessage = String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullScriptPath);

                // logging to both the Output window and progress window.
                logger.Log(MessageLevel.Info, logMessage);

                IConsole console = OutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: true);
                Host.Execute(console,
                    "$__pc_args=@(); $input|%{$__pc_args+=$_}; & " + PathHelper.EscapePSPath(fullScriptPath) + " $__pc_args[0] $__pc_args[1] $__pc_args[2] $__pc_args[3]; Remove-Variable __pc_args -Scope 0",
                    new object[] { installPath, toolsPath, package, project });

                return true;
            }
            return false;
        }
Ejemplo n.º 25
0
        public static bool FindCompatibleToolFiles(
            this IPackage package,
            string scriptName,
            FrameworkName targetFramework,
            out IPackageFile toolFile)
        {
            if (scriptName.Equals("init.ps1", StringComparison.OrdinalIgnoreCase))
            {
                IPackageFile initFile = package.GetToolFiles()
                                               .FirstOrDefault(a => a.Path.Equals("tools\\init.ps1", StringComparison.OrdinalIgnoreCase));
                if (initFile != null)
                {
                    toolFile = initFile;
                    return true;
                }

                toolFile = null;
                return false;
            }

            // this is the case for either install.ps1 or uninstall.ps1
            // search for the correct script according to target framework of the project
            IEnumerable<IPackageFile> toolFiles;
            if (VersionUtility.TryGetCompatibleItems(targetFramework, package.GetToolFiles(), out toolFiles))
            {
                IPackageFile foundToolFile = toolFiles.FirstOrDefault(p => p.EffectivePath.Equals(scriptName, StringComparison.OrdinalIgnoreCase));
                if (foundToolFile != null && !foundToolFile.IsEmptyFolder())
                {
                    toolFile = foundToolFile;
                    return true;
                }
            }

            toolFile = null;
            return false;
        }
        private static XElement GetXml(IPackageFile file, IProjectSystem projectSystem)
        {
            var content = Preprocessor.Process(file, projectSystem);

            return(XElement.Parse(content, LoadOptions.PreserveWhitespace));
        }
Ejemplo n.º 27
0
 public ZipPackageAssemblyReference(IPackageFile file)
     : base(file)
 {
     Debug.Assert(Path.StartsWith("lib", StringComparison.OrdinalIgnoreCase), "path doesn't start with lib");
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Creates a new Isntance based on an existing Package
 /// </summary>
 /// <param name="package">The Package that should receive the Clone</param>
 public ObjectCloner(IPackageFile package)
 {
     this.package = package;
     setup        = new CloneSettings();
 }
Ejemplo n.º 29
0
        private void Main()
        {
            ArrayList al = new ArrayList();

            #region Prompt for mesh name or browse for package and extract names
            GetMeshName  gmn = new GetMeshName();
            DialogResult dr  = gmn.ShowDialog();
            if (dr.Equals(DialogResult.OK))
            {
                if (gmn.MeshName.Length > 0)
                {
                    al.Add(gmn.MeshName);
                }
                else
                {
                    MessageBox.Show(L.Get("noMeshName"), L.Get("pjSME"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else if (dr.Equals(DialogResult.Retry)) // nasty...
            {
                #region Get body mesh package file name and open the package
                String bodyMeshPackage = getFilename();
                if (bodyMeshPackage == null)
                {
                    return;
                }

                IPackageFile p = SimPe.Packages.File.LoadFromFile(bodyMeshPackage);
                if (p == null)
                {
                    return;
                }
                #endregion

                #region Find the Property Set or XML Mesh Overlay
                IPackedFileDescriptor[] pfa = p.FindFiles(SimPe.Data.MetaData.GZPS);
                IPackedFileDescriptor[] pfb = p.FindFiles(0x0C1FE246); // XMOL?
                if ((pfa == null || pfa.Length == 0) && (pfb == null || pfb.Length == 0))
                {
                    MessageBox.Show(L.Get("noGZPSXMOL"),
                                    L.Get("pjSME"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                #endregion

                #region Get the mesh name(s)
                bool prompted = false;
                SimPe.PackedFiles.Wrapper.Cpf cpf = new SimPe.PackedFiles.Wrapper.Cpf();
                for (int i = 0; i < pfa.Length + pfb.Length; i++)
                {
                    if (i < pfa.Length)
                    {
                        cpf.ProcessData(pfa[i], p);
                    }
                    else
                    {
                        cpf.ProcessData(pfb[i - pfa.Length], p);
                    }

                    for (int j = 0; j < cpf.Items.Length; j++)
                    {
                        if (cpf.Items[j].Name.ToLower().Equals("name"))
                        {
                            al.Add(cpf.Items[j].StringValue);
                        }
                        if (al.Count > 1 && !prompted)
                        {
                            if (MessageBox.Show(L.Get("multipleMeshes"),
                                                L.Get("pjSME"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                != DialogResult.Yes)
                            {
                                return;
                            }
                            prompted = true;
                        }
                    }
                }
                if (al.Count == 0)
                {
                    MessageBox.Show(L.Get("noMeshPkg"),
                                    L.Get("pjSME"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                #endregion
            }
            else
            {
                return;
            }

            #endregion

            #region For each mesh, find the GMDC, GMND, SHPE and CRES and add them to the current package

            foreach (String m in al)
            {
                String[] ma   = m.Split('_');
                String   mesh = ma[ma[0].Equals("CASIE") ? 1 : 0];
                if (mesh.ToLower().StartsWith("ym"))
                {
                    mesh = "am" + mesh.Substring(2);
                }
                if (mesh.ToLower().StartsWith("yf"))
                {
                    mesh = "af" + mesh.Substring(2);
                }

                bool success = true;
                SimPe.RemoteControl.ApplicationForm.Cursor = Cursors.WaitCursor;
                success = success && findAndAdd(mesh, SimPe.Data.MetaData.GMDC, "Sims03.package");
                success = success && findAndAdd(mesh, SimPe.Data.MetaData.GMND, "Sims04.package");
                success = success && findAndAdd(mesh, SimPe.Data.MetaData.SHPE, "Sims05.package");
                success = success && findAndAdd(mesh, SimPe.Data.MetaData.CRES, "Sims06.package");
                SimPe.RemoteControl.ApplicationForm.Cursor = Cursors.Default;
                if (!success)
                {
                    MessageBox.Show(L.Get("notAllPartsFound") + m,
                                    L.Get("pjSME"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            #endregion
        }
Ejemplo n.º 30
0
 public static string?OriginalPath(this IPackageFile packageFile)
 {
     return((packageFile as PackageFileBase)?.OriginalPath);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Creates the List for the specific Package
 /// </summary>
 /// <param name="folder">The Base Package</param>
 /// <param name="names">null or a valid SimNames Provider</param>
 /// <param name="famnames">nullr or a valid SimFamilyNames Provider</param>
 public SimDescriptions(IPackageFile package, ISimNames names, ISimFamilyNames famnames) : base(package)
 {
     this.names    = names;
     this.famnames = famnames;
 }
Ejemplo n.º 32
0
        private void Read(Stream input)
        {
            UInt32 magic = input.ReadValueU32();

            if (magic != 0x51890ACE && magic != 0xCE0A8951)
            {
                throw new FormatException("not a volition package");
            }

            this.LittleEndian = (magic == 0x51890ACE) ? true : false;
            this.Version      = input.ReadValueU32(this.LittleEndian);

            if (this.Version != 3 &&
                this.Version != 4 &&
                this.Version != 6)
            {
                throw new FormatException("unsupported volition package version");
            }

            input.Seek(-8, SeekOrigin.Current);

            IPackageFile packageFile = null;

            if (this.Version == 3)
            {
                packageFile = new Packages.PackageFile3();
            }
            else if (this.Version == 4)
            {
                packageFile = new Packages.PackageFile4();
            }
            else if (this.Version == 6)
            {
                packageFile = new Packages.PackageFile6();
            }
            else
            {
                throw new NotSupportedException();
            }

            packageFile.Deserialize(input, this.LittleEndian);

            this.Entries.Clear();
            this.OriginalEntries.Clear();

            if (packageFile.IsSolid == false)
            {
                foreach (Packages.PackageEntry packageEntry in packageFile.Entries)
                {
                    StreamEntry entry = new StreamEntry();
                    entry.Offset          = packageEntry.Offset;
                    entry.Size            = packageEntry.UncompressedSize;
                    entry.CompressedSize  = packageEntry.CompressedSize;
                    entry.CompressionType = packageEntry.CompressionType;

                    if (this.Entries.ContainsKey(packageEntry.Name) == false)
                    {
                        this.Entries.Add(packageEntry.Name, entry);
                    }
                    else
                    {
                        // Saints Row 1 seems to have bugged duplicate entries that point to
                        // different offsets with the same data.
                        this.Entries.Add(packageEntry.Name + "_DUPLICATE_" + packageEntry.Offset.ToString("X8"), entry);
                    }
                }
            }
            else
            {
                this.IsSolid = true;

                byte[] solid = new byte[packageFile.SolidUncompressedSize];

                input.Seek(packageFile.SolidOffset, SeekOrigin.Begin);

                // Decompress solid data
                var zlib = new InflaterInputStream(input);
                if (zlib.Read(solid, 0, solid.Length) != solid.Length)
                {
                    throw new InvalidOperationException("zlib error");
                }

                foreach (Packages.PackageEntry packageEntry in packageFile.Entries)
                {
                    var entry = new MemoryEntry();
                    entry.Data = new byte[packageEntry.UncompressedSize];
                    Array.Copy(solid, (int)packageEntry.Offset, entry.Data, 0, entry.Data.Length);
                    entry.Size = entry.Data.Length;
                    this.Entries.Add(packageEntry.Name, entry);
                }
            }
        }
Ejemplo n.º 33
0
 private static bool IsTransformFile(IPackageFile file)
 {
     return(Path.GetExtension(file.Path).Equals(TransformFileExtension, StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 34
0
 private static PackageIssue CreatePackageIssue(IPackageFile file)
 {
     object[] args = new object[] { file.Path };
     return(new PackageIssue(AnalysisResources.MisplacedInitScriptTitle, string.Format(CultureInfo.CurrentCulture, AnalysisResources.MisplacedInitScriptDescription, args), AnalysisResources.MisplacedInitScriptSolution));
 }
Ejemplo n.º 35
0
        public void Commit(Packages.PackageCompressionType compressionType)
        {
            Stream clean;
            string tempFileName = Path.GetTempFileName();

            tempFileName = Path.GetTempFileName();
            clean        = File.Open(tempFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

            IPackageFile packageFile = null;

            if (this.Version == 3)
            {
                packageFile = new Packages.PackageFile3();
            }
            else if (this.Version == 4)
            {
                packageFile = new Packages.PackageFile4();
            }
            else if (this.Version == 6)
            {
                packageFile = new Packages.PackageFile6();
            }
            else
            {
                throw new NotSupportedException();
            }

            foreach (KeyValuePair <string, Entry> kvp in this.Entries)
            {
                var packageEntry = new Packages.PackageEntry();
                packageEntry.Name             = kvp.Key;
                packageEntry.CompressedSize   = -1;
                packageEntry.UncompressedSize = kvp.Value.Size;
                packageEntry.Offset           = 0;
                packageFile.Entries.Add(packageEntry);
            }

            int headerSize = packageFile.EstimateHeaderSize();

            clean.Seek(headerSize, SeekOrigin.Begin);

            int uncompressedDataSize = 0;
            int compressedDataSize   = 0;

            if (compressionType == Packages.PackageCompressionType.None)
            {
                long offset = 0;
                foreach (Packages.PackageEntry packageEntry in packageFile.Entries)
                {
                    packageEntry.Offset = offset;

                    this.ExportEntry(packageEntry.Name, clean);

                    int align = packageEntry.UncompressedSize.Align(2048) - packageEntry.UncompressedSize;
                    if (align > 0)
                    {
                        byte[] block = new byte[align];
                        clean.Write(block, 0, (int)align);
                    }

                    offset += packageEntry.UncompressedSize + align;
                    uncompressedDataSize += packageEntry.UncompressedSize + align;
                }
            }
            else if (compressionType == Packages.PackageCompressionType.Zlib)
            {
                long offset = 0;
                foreach (Packages.PackageEntry packageEntry in packageFile.Entries)
                {
                    packageEntry.Offset = offset;

                    byte[] uncompressedData = this.GetEntry(packageEntry.Name);
                    using (var temp = new MemoryStream())
                    {
                        var zlib = new DeflaterOutputStream(temp);
                        zlib.Write(uncompressedData, 0, uncompressedData.Length);
                        zlib.Finish();

                        temp.Position = 0;
                        clean.WriteFromStream(temp, temp.Length);
                        packageEntry.CompressedSize = (int)temp.Length;

                        int align = packageEntry.CompressedSize.Align(2048) - packageEntry.CompressedSize;
                        if (align > 0)
                        {
                            byte[] block = new byte[align];
                            clean.Write(block, 0, (int)align);
                        }

                        offset += packageEntry.CompressedSize + align;
                        uncompressedDataSize += packageEntry.UncompressedSize;
                        compressedDataSize   += packageEntry.CompressedSize + align;
                    }
                }
            }
            else if (compressionType == Packages.PackageCompressionType.SolidZlib)
            {
                using (var compressed = new MemoryStream())
                {
                    var zlib = new DeflaterOutputStream(compressed, new Deflater(Deflater.DEFAULT_COMPRESSION));

                    long offset = 0;
                    foreach (Packages.PackageEntry packageEntry in packageFile.Entries)
                    {
                        packageEntry.Offset = offset;

                        this.ExportEntry(packageEntry.Name, zlib);

                        int align = packageEntry.UncompressedSize.Align(2048) - packageEntry.UncompressedSize;
                        if (align > 0)
                        {
                            byte[] block = new byte[align];
                            zlib.Write(block, 0, (int)align);
                        }

                        offset += packageEntry.UncompressedSize + align;
                        uncompressedDataSize += packageEntry.UncompressedSize + align;
                    }

                    zlib.Close();

                    compressed.Seek(0, SeekOrigin.Begin);
                    clean.WriteFromStream(compressed, compressed.Length);

                    compressedDataSize = (int)compressed.Length;
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            packageFile.PackageSize          = (int)clean.Length;
            packageFile.UncompressedDataSize = uncompressedDataSize;
            packageFile.CompressedDataSize   = compressedDataSize;

            clean.Seek(0, SeekOrigin.Begin);
            packageFile.Serialize(clean, this.LittleEndian, compressionType);

            // copy clean to real stream
            {
                this.Stream.Seek(0, SeekOrigin.Begin);
                clean.Seek(0, SeekOrigin.Begin);
                this.Stream.WriteFromStream(clean, clean.Length);
            }

            this.Stream.SetLength(clean.Length);
            clean.Close();

            if (tempFileName != null)
            {
                File.Delete(tempFileName);
            }

            this.Entries.Clear();
            this.OriginalEntries.Clear();

            foreach (Packages.PackageEntry entry in packageFile.Entries)
            {
                this.Entries.Add(entry.Name, new StreamEntry()
                {
                    Offset          = entry.Offset,
                    Size            = entry.UncompressedSize,
                    CompressedSize  = entry.CompressedSize,
                    CompressionType = entry.CompressionType,
                });
            }
        }
Ejemplo n.º 36
0
        private void AddFiles(PackageBuilder builder, string itemType, string targetFolder)
        {
            // Skip files that are added by dependency packages
            var references = PackageReferenceFile.CreateFromProject(_project.FullPath).GetPackageReferences();
            IPackageRepository repository  = GetPackagesRepository();
            string             projectName = Path.GetFileNameWithoutExtension(_project.FullPath);

            var contentFilesInDependencies = new List <IPackageFile>();

            if (references.Any() && repository != null)
            {
                contentFilesInDependencies = references.Select(reference => repository.FindPackage(reference.Id, reference.Version))
                                             .Where(a => a != null)
                                             .SelectMany(a => a.GetContentFiles())
                                             .ToList();
            }

            // Get the content files from the project
            foreach (var item in _project.GetItems(itemType))
            {
                string fullPath = item.GetMetadataValue("FullPath");
                if (_excludeFiles.Contains(Path.GetFileName(fullPath)))
                {
                    continue;
                }

                string targetFilePath = GetTargetPath(item);

                if (!File.Exists(fullPath))
                {
                    Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_FileDoesNotExist"), targetFilePath);
                    continue;
                }

                // Skip target file paths containing msbuild variables since we do not offer a way to install files with variable paths.
                // These are show up in shared files found in universal apps.
                if (targetFilePath.IndexOf("$(MSBuild", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_UnresolvedFilePath"), targetFilePath);
                    continue;
                }

                // if IncludeReferencedProjects is true and we are adding source files,
                // add projectName as part of the target to avoid file conflicts.
                string targetPath = IncludeReferencedProjects && itemType == SourcesItemType?
                                    Path.Combine(targetFolder, projectName, targetFilePath) :
                                        Path.Combine(targetFolder, targetFilePath);

                // Check that file is added by dependency
                IPackageFile targetFile = contentFilesInDependencies.Find(a => a.Path.Equals(targetPath, StringComparison.OrdinalIgnoreCase));
                if (targetFile != null)
                {
                    // Compare contents as well
                    var isEqual = ContentEquals(targetFile, fullPath);
                    if (isEqual)
                    {
                        Logger.Log(MessageLevel.Info, LocalizedResourceManager.GetString("PackageCommandFileFromDependencyIsNotChanged"), targetFilePath);
                        continue;
                    }

                    Logger.Log(MessageLevel.Info, LocalizedResourceManager.GetString("PackageCommandFileFromDependencyIsChanged"), targetFilePath);
                }

                var packageFile = new PhysicalPackageFile
                {
                    SourcePath = fullPath,
                    TargetPath = targetPath
                };
                AddFileToBuilder(builder, packageFile);
            }
        }
Ejemplo n.º 37
0
 public static bool IsEmptyFolder(this IPackageFile packageFile)
 {
     return(packageFile != null &&
            Constants.PackageEmptyFileName.Equals(Path.GetFileName(packageFile.Path), StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 38
0
 public ReverseTransformFormFile(IPackageFile file, IEnumerable <IPackageFile> transforms)
 {
     Path            = file.Path + ".transform";
     _streamFactory  = new Lazy <Func <Stream> >(() => ReverseTransform(file, transforms), isThreadSafe: false);
     TargetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Path, out _effectivePath);
 }
Ejemplo n.º 39
0
 internal static bool ContentEquals(IPackageFile targetFile, string fullPath)
 {
     bool isEqual;
     using (var dependencyFileStream = targetFile.GetStream())
     using (var fileContentsStream = File.OpenRead(fullPath))
     {
         isEqual = dependencyFileStream.ContentEquals(fileContentsStream);
     }
     return isEqual;
 }
Ejemplo n.º 40
0
 public bool IsEnabled(IPackedFileDescriptor pfd, IPackageFile package)
 {
     return(true);
 }
Ejemplo n.º 41
0
            private static Func<Stream> ReverseTransform(IPackageFile file, IEnumerable<IPackageFile> transforms)
            {
                // Get the original
                XElement element = GetElement(file);

                // Remove all the transforms
                foreach (var transformFile in transforms)
                {
                    element.Except(GetElement(transformFile));
                }

                // Create the stream with the transformed content
                var ms = new MemoryStream();
                element.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                byte[] buffer = ms.ToArray();
                return () => new MemoryStream(buffer);
            }
Ejemplo n.º 42
0
 /// <summary>
 /// Creates the List for the specific Folder
 /// </summary>
 /// <param name="folder">The Folder with the Character Files</param>
 public SimCommonPackage(IPackageFile package)
 {
     BasePackage = package;
 }
Ejemplo n.º 43
0
        public void RemoveFile(IPackageFile file)
        {
            PackageFile realFile = file as PackageFile;

            m_files.Remove(realFile);
        }
Ejemplo n.º 44
0
 private static XElement GetXml(IPackageFile file, IProjectSystem projectSystem) =>
 XElement.Parse(Preprocessor.Process(file, projectSystem), LoadOptions.PreserveWhitespace);
Ejemplo n.º 45
0
 public abstract IPackage       Push(IPackageFile file);
Ejemplo n.º 46
0
 protected static T ReadFile <T>(IPackageFile file)
 {
     using (var stream = file.GetStream())
         using (var reader = new StreamReader(stream))
             return(JsonConvert.DeserializeObject <T>(reader.ReadToEnd()));
 }
Ejemplo n.º 47
0
 public override IPackage     Push(IPackageFile file)
 {
     return(null);
 }
Ejemplo n.º 48
0
 public PackageFile(IPackageFile file, string name, PackageFolder parent)
     : this(file, name, parent, parent.PackageViewModel)
 {
 }
Ejemplo n.º 49
0
 public void Before()
 {
     base.BeforeEach();
     nunit  = new Nupkg(PathToContent("packages/NUnit.2.5.7.10213.nupkg"));
     fluent = new Nupkg(PathToContent("packages/FluentNHibernate.1.1.0.694.nupkg"));
 }
Ejemplo n.º 50
0
 public ZipPackageFile(IPackageFile file)
 {
     Path           = file.Path;
     _streamFactory = file.GetStream().ToStreamFactory();
 }
Ejemplo n.º 51
0
 protected override void UpdateFile(string exePath, IPackageFile file)
 {
     UpdatedFiles[exePath] = file.Path;
 }
Ejemplo n.º 52
0
 public void TransformFile(IPackageFile file, string targetPath, IProjectSystem projectSystem)
 {
     PerformXdtTransform(file, targetPath, projectSystem);
 }
Ejemplo n.º 53
0
 /// <summary>
 /// Constructor, Initializes the Object with Data from the File
 /// </summary>
 /// <param name="type">ize of the Package Index</param>
 /// <param name="pfd"></param>
 /// <param name="package"></param>
 public CompressedFileList(IPackedFileDescriptor pfd, IPackageFile package) : base()
 {
     iformat = package.Header.IndexType;
     items   = new ClstItem[0];
     this.ProcessData(pfd, package);
 }
Ejemplo n.º 54
0
 public void RevertFile(IPackageFile file, string targetPath, IEnumerable <IPackageFile> matchingFiles, IProjectSystem projectSystem)
 {
     PerformXdtTransform(file, targetPath, projectSystem);
 }
Ejemplo n.º 55
0
 private static bool IsTransformFile(IPackageFile file)
 {
     return Path.GetExtension(file.Path).Equals(TransformFileExtension, StringComparison.OrdinalIgnoreCase);
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Initializes a new instance of <see cref="PackageFile"/> located in <paramref name="path"/>.
 /// </summary>
 /// <param name="file">Nuget package file</param>
 public PackageFile(IPackageFile file)
 {
     packageFile = file;
 }
Ejemplo n.º 57
0
 public ReverseTransformFormFile(IPackageFile file, IEnumerable<IPackageFile> transforms)
 {
     Path = file.Path + ".transform";
     _streamFactory = new Lazy<Func<Stream>>(() => ReverseTransform(file, transforms), isThreadSafe: false);
     TargetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Path, out _effectivePath);
 }
Ejemplo n.º 58
0
 public ZipPackageFile(IPackageFile file)
     : this(file.Path, file.GetStream().ToStreamFactory())
 {
 }
Ejemplo n.º 59
0
 private static XElement GetElement(IPackageFile file)
 {
     using (Stream stream = file.GetStream())
     {
         return XElement.Load(stream);
     }
 }
Ejemplo n.º 60
0
        private JProperty WritePackageFile(IPackageFile item)
        {
            var json = new JObject();

            return(new JProperty(PathUtility.GetPathWithForwardSlashes(item.Path), new JObject()));
        }