Esempio n. 1
0
        /// <summary>
        /// Extracts the package to the specified <see cref="DirectoryMap"/>
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="args"></param>
        public void ExtractTo(DirectoryMap directory, TurtleExtractArgs args)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            else if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            ExtractFiles(args, delegate(ExtractorEventArgs e)
            {
                PackFile file        = e.PackFile;
                DirectoryMapFile dmf = directory.GetFile(file.RelativePath);

                if ((dmf == null) || !dmf.Unmodified() || !QQnCryptoHelpers.HashComparer.Equals(dmf.FileHash, file.FileHash))
                {
                    using (Stream s = directory.CreateFile(file.RelativePath, file.FileHash, file.FileSize))
                    {
                        QQnPath.CopyStream(e.Stream, s);
                    }
                }
                else
                {
                    directory.UnscheduleDelete(file.RelativePath);                     // Make sure it stays
                }
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Extracts the package to the specified directory
        /// </summary>
        /// <param name="directory">The directory.</param>
        /// <param name="args">The args.</param>
        public void ExtractTo(string directory, TurtleExtractArgs args)
        {
            if (string.IsNullOrEmpty(directory))
            {
                throw new ArgumentNullException("directory");
            }
            else if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (args.UseDirectoryMap)
            {
                using (DirectoryMap dm = DirectoryMap.Get(directory))
                {
                    ExtractTo(dm, args);
                }
                return;
            }

            ExtractFiles(args, delegate(ExtractorEventArgs e)
            {
                using (Stream s = File.Create(QQnPath.Combine(directory, e.PackFile.RelativePath)))
                {
                    QQnPath.CopyStream(e.Stream, s);
                }
            });
        }
Esempio n. 3
0
        /// <summary>
        /// Gets log file with the specified name
        /// </summary>
        /// <param name="name">The name of the project or the name of the logfile</param>
        /// <returns></returns>
        public TBLogFile Get(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            name = QQnPath.EnsureExtension(name, ".tbLog");

            if (ContainsKey(name))
            {
                return(this[name]);
            }

            if (!string.IsNullOrEmpty(_logPath))
            {
                name = QQnPath.Combine(_logPath, name);
            }

            TBLogFile logFile = TBLogFile.Load(name);

            Add(name, logFile);

            return(logFile);
        }
Esempio n. 4
0
        public void CreateZipAndTpz()
        {
            using (ZipFile zf = ZipFile.Create(QQnPath.Combine(TmpPath, "TestZip.zip")))
            {
                AddSomeFiles(zf);
            }

            AssuredStreamCreateArgs assuredArgs = new AssuredStreamCreateArgs();

            assuredArgs.StrongNameKey = StrongNameKey.LoadFrom(SnkFile);
            assuredArgs.FileType      = "TPZ-Test";

            MultipleStreamCreateArgs mutlArgs = new MultipleStreamCreateArgs();

            mutlArgs.VerificationMode = VerificationMode.Full;

            using (FileStream fileStream = File.Create(QQnPath.Combine(TmpPath, "TestTpz.zip")))
                using (AssuredStream assuredStream = new AssuredStream(fileStream, assuredArgs))
                    using (MultipleStreamWriter msw = new MultipleStreamWriter(assuredStream, mutlArgs))
                    {
                        using (Stream s = msw.CreateStream())
                        {
                            s.WriteByte(255);
                        }

                        using (Stream s = msw.CreateStream())
                            using (ZipFile zf = ZipFile.Create(s))
                            {
                                AddSomeFiles(zf);
                            }
                    }
        }
Esempio n. 5
0
        public void EnsureRelativePath()
        {
            Assert.That(QQnPath.EnsureRelativePath("c:\\tools", "c:/tools/t.txt"), Is.EqualTo("t.txt"));
            Assert.That(QQnPath.EnsureRelativePath("c:\\tools", "c:/t.txt"), Is.EqualTo("..\\t.txt"));

            Assert.That(QQnPath.EnsureRelativePath("c:\\tools", "t.txt"), Is.EqualTo("t.txt"));
            Assert.That(QQnPath.EnsureRelativePath("c:\\tools", "\\banaan\\t.txt"), Is.EqualTo("..\\banaan\\t.txt"));

            string currentDisk = Path.GetPathRoot(Environment.CurrentDirectory);
            string otherDisk;

            if (string.Equals(currentDisk, "z:\\", StringComparison.OrdinalIgnoreCase))
            {
                otherDisk = "z:\\";
            }
            else
            {
                otherDisk = "c:\\";
            }

            Assert.That(Path.Combine(otherDisk + "tools", "\\t.txt"), Is.EqualTo("\\t.txt"), "Path.Combine works like .Net 2.0");
            Assert.That(Path.GetFullPath(Path.Combine(otherDisk + "tools", "\\t.txt")), Is.EqualTo(currentDisk + "t.txt"), "Path.Combine works like .Net 2.0");
            Assert.That(QQnPath.Combine(otherDisk + "tools", "\\t.txt"), Is.EqualTo(otherDisk + "t.txt"), "QQnPath combines always relative");


            Assert.That(QQnPath.NormalizePath("c:\\", false), Is.EqualTo("c:\\"));
        }
Esempio n. 6
0
        /// <summary>
        /// Gets the framework path which best matches the specified version
        /// </summary>
        /// <param name="frameworkVersion">The framework version.</param>
        /// <returns></returns>
        public static DirectoryInfo GetFrameworkDirectory(Version frameworkVersion)
        {
            if (frameworkVersion == null)
            {
                throw new ArgumentNullException("frameworkVersion");
            }

            string runtimeDir   = QQnPath.NormalizePath(RuntimeEnvironment.GetRuntimeDirectory());
            string frameworkDir = Path.GetDirectoryName(runtimeDir);

            DirectoryInfo dir = new DirectoryInfo(frameworkDir);

            if (!dir.Exists)
            {
                return(null);
            }

            if (frameworkVersion.Major == 4 && frameworkVersion.Minor == 5)
            {
                frameworkVersion = new Version(4, 0);
            }

            DirectoryInfo[] dirs = dir.GetDirectories("v*.*", SearchOption.TopDirectoryOnly);

            int start = 2;

            if (frameworkVersion.Build >= 0)
            {
                start = 4;
            }
            else if (frameworkVersion.Revision >= 0)
            {
                start = 3;
            }

            for (int i = start; i >= 2; i--)
            {
                string name = "v" + frameworkVersion.ToString(i);

                foreach (DirectoryInfo d in dirs)
                {
                    if (string.Equals(d.Name, name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(d);
                    }
                }

                name += ".";

                foreach (DirectoryInfo d in dirs)
                {
                    if (d.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(d);
                    }
                }
            }

            return(null);
        }
Esempio n. 7
0
        public void GetToolsDirectory_40_ReturnsDirectory()
        {
            DirectoryInfo dir = BuildTools.GetBuildToolsDirectory(new Version("4.0"));

            Assert.That(dir.Name, Is.EqualTo("v4.0.30319"));
            Assert.That(File.Exists(QQnPath.Combine(dir.FullName, "msbuild.exe")), "MSBuild exists");
        }
Esempio n. 8
0
        private void OnExternalProjectFinished(object sender, ExternalProjectFinishedEventArgs e)
        {
            if (_solution == null)
            {
                return;                 // Shortcut
            }
            ExternalProject ep;

            if (_solution.ExternalProjects.TryGetValue(e.ProjectFile, out ep))
            {
                ep.ProjectFinished(_solution);
                return;
            }

            // VC Uses temporary project files; look for the real file
            string dir  = Path.GetDirectoryName(e.ProjectFile);
            string file = Path.GetFileNameWithoutExtension(e.ProjectFile);
            string ext  = Path.GetExtension(e.ProjectFile);

            string ext2 = Path.GetExtension(file);

            if (!string.IsNullOrEmpty(ext2) && ext2.StartsWith(".tmp_", StringComparison.OrdinalIgnoreCase))
            {
                // PROJECT.tmp_Win32_Release.VCPROJ -> PROJECT.VCPROJ
                string realProject = QQnPath.Combine(dir, Path.GetFileNameWithoutExtension(file) + ext);

                // Try in memory first, as this is always faster than on disk
                if (_solution.ExternalProjects.TryGetValue(realProject, out ep) && File.Exists(realProject))
                {
                    ep.ProjectFinished(_solution);
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Tries to get the generated metadata item.
        /// </summary>
        /// <param name="metaDataName">Name of the meta data.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        bool TryTransformMetaData(string metaDataName, out string value)
        {
            int n;

            switch (metaDataName)
            {
            case "FullPath":
                value = FullPath;
                return(true);

            case "RootDir":
                value = Path.GetPathRoot(QQnPath.Combine(_project.ProjectPath, Include));
                return(true);

            case "Filename":
                value = Filename;
                return(true);

            case "Extension":
                value = Extension;
                return(true);

            case "RelativeDir":
                n     = Include.LastIndexOfAny(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
                value = (n >= 0) ? Include.Substring(0, n + 1) : "";
                return(true);

            case "Directory":
                value = QQnPath.Combine(_project.ProjectPath, Include);
                n     = value.LastIndexOfAny(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
                value = (n >= 0) ? Include.Substring(0, n + 1) : "";
                value = value.Substring(Path.GetPathRoot(value).Length);
                return(true);

            case "RecursiveDir":
                value = "";
                return(true);

            case "Identity":
                value = Include;
                return(true);

            case "ModifiedTime":
                value = new DirectoryInfo(QQnPath.Combine(_project.ProjectPath, Include)).LastWriteTime.ToString("u");
                return(true);

            case "CreatedTime":
                value = new DirectoryInfo(QQnPath.Combine(_project.ProjectPath, Include)).CreationTime.ToString("u");
                return(true);

            case "AccessedTime":
                value = new DirectoryInfo(QQnPath.Combine(_project.ProjectPath, Include)).LastAccessTime.ToString("u");
                return(true);

            default:
                value = null;
                return(false);
            }
        }
Esempio n. 10
0
        public void BuildExternal()
        {
            ProcessStartInfo psi = new ProcessStartInfo(MSBuild, string.Format("/nologo \"{0}\" /v:q /p:Configuration={1} \"/logger:MSBuildLogger,{2};OutputDir={3};Indent=true\"", Solution, OtherConfiguration, Logger, LoggerPath));

            psi.UseShellExecute        = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;
            psi.CreateNoWindow         = true;

            using (Process p = Process.Start(psi))
            {
                p.WaitForExit();
                string output = p.StandardOutput.ReadToEnd();
                string err    = p.StandardError.ReadToEnd();

                Assert.That(err, Is.EqualTo(""), "MSBuild gave no error");
                //Assert.That(output, Is.EqualTo(""), "MSBuild gave no output");
                Assert.That(p.ExitCode, Is.EqualTo(0), "MSBuild ran successfully");
            }

            Assert.That(File.Exists(QQnPath.Combine(LoggerPath, "QQn.TurtleMSBuild.tbLog")), Is.True, "Logfile created");

            XPathDocument doc = new XPathDocument(QQnPath.Combine(LoggerPath, "QQn.TurtleMSBuild.tbLog"));

            XPathNavigator      nav   = doc.CreateNavigator();
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);

            nsMgr.AddNamespace("tb", "http://schemas.qqn.nl/2007/TurtleBuild/BuildResult");
            Assert.That(nav.SelectSingleNode("/tb:TurtleBuildData/tb:Configuration", nsMgr).GetAttribute("outputPath", ""), Is.Not.EqualTo(""), "outputPath is set");
            //doc.CreateNavigator().SelectSingleNode("

            TBLogFile file = TBLogFile.Load(QQnPath.Combine(LoggerPath, "QQn.TurtleMSBuild.tbLog"));

            Assert.That(file, Is.Not.Null);
            Assert.That(file.Configurations.Count, Is.GreaterThanOrEqualTo(1), "Configurations available");

            Assert.That(file.Configurations[0].ProjectOutput.Items.Count, Is.GreaterThan(1));

            Assert.That(file.Configurations[0].ProjectOutput.Items[0].Container, Is.SameAs(file.Configurations[0].ProjectOutput), "Container is set");

            Assert.That(file.Configurations[0].Target.DebugSrc, Is.Not.Null);


            using (StringWriter sw = new StringWriter())
            {
                using (XmlWriter xw = new XmlTextWriter(sw))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("TurtleBuild", "q:q");
                    QQn.TurtleUtils.Tokens.Tokenizer.TryWriteXml(new XmlTextWriter(sw), file);

                    xw.WriteEndDocument();
                }

                string text = sw.ToString();
                Assert.That(text.Length, Is.GreaterThan(100));
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Normalizes the directory.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        protected static string NormalizeDirectory(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            return(QQnPath.NormalizeUnixPath(value, true));
        }
Esempio n. 12
0
        public void CopyResources()
        {
            Uri    uri     = new Uri(typeof(AssemblyUtils).Assembly.CodeBase);
            string file    = uri.LocalPath;
            string tmpFile = QQnPath.Combine(Path.GetTempPath(), Path.GetFileName(file));

            File.Copy(file, tmpFile, true);
            Assert.That(AssemblyUtils.RefreshVersionInfoFromAttributes(tmpFile, Path.GetFullPath("..\\..\\..\\..\\Libraries\\QQn.TurtleBuildUtils\\QQn.TurtleBuildUtils.snk"), null));
        }
Esempio n. 13
0
        public void CalculatePackage(bool useProjectReferences)
        {
            string logFile = QQnPath.Combine(LoggerPath, "QQn.TurtleMSBuild.tbLog");

            if (!File.Exists(logFile))
            {
                BuildInternal();
            }

            TBLogCache logCollection = new TBLogCache(LoggerPath);

            logCollection.LoadAll();

            PackageArgs args = new PackageArgs();

            args.LogCache  = logCollection;
            args.BuildRoot = Path.GetDirectoryName(Solution);
            args.UseProjectDependencies = useProjectReferences;

            args.ProjectsToPackage.AddRange(logCollection.KeysAsFullPaths);

            PackageList newPackages;

            Assert.That(Packager.TryCreatePackages(args, out newPackages), "Created packages");

            Assert.That(newPackages.Count, Is.EqualTo(args.ProjectsToPackage.Count), "All projects packaged");

            if (Directory.Exists("f:\\extractor"))
            {
                Directory.Delete("f:\\extractor", true);
            }

            if (Directory.Exists("f:\\extractor2"))
            {
                Directory.Delete("f:\\extractor2", true);
            }

            if (!Directory.Exists("f:\\extractor"))
            {
                Directory.CreateDirectory("f:\\extractor");
            }
            if (!Directory.Exists("f:\\extractor2"))
            {
                Directory.CreateDirectory("f:\\extractor2");
            }

            foreach (TPack p in newPackages)
            {
                p.ExtractTo("f:\\extractor");
            }

            foreach (TPack p in newPackages)
            {
                p.ExtractTo("f:\\extractor2", true);
            }
        }
Esempio n. 14
0
        public BuildOrigin(TBLogFile logFile)
        {
            if (logFile == null)
            {
                throw new ArgumentNullException("logFile");
            }

            _log         = logFile;
            _projectFile = QQnPath.Combine(logFile.ProjectPath, logFile.Project.File);
        }
Esempio n. 15
0
        /// <summary>
        /// Tries to create packages from the specified logfiles; walking dependencies if needed.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <param name="newPackages">The new packages.</param>
        /// <returns></returns>
        public static bool TryCreatePackages(PackageArgs args, out PackageList newPackages)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            PackageState state = new PackageState(args);

            state.LoadExternalOrigins();
            state.CreateBuildOrigins();
            state.AddRequirements();

            state.CalculateDependencies();

            newPackages = new PackageList();

            List <TBLogFile> filesToRun = new List <TBLogFile>(state.Logs);

            while (filesToRun.Count > 0)
            {
                int n = 0;
                for (int i = 0; i < filesToRun.Count; i++)
                {
                    TBLogFile file = filesToRun[i];
                    if (state.CanPackage(file))
                    {
                        filesToRun.RemoveAt(i--);

                        string   target     = QQnPath.Combine(args.OutputDir, file.Project.Name + ".tpZip");
                        FileInfo targetInfo = new FileInfo(target);

                        TPack pack;
                        if (targetInfo.Exists && targetInfo.LastWriteTime > file.GetLastWriteTime())
                        {
                            pack = TPack.OpenFrom(target, VerificationMode.None);
                            state.SetOriginPack(file, pack.Pack);
                        }
                        else
                        {
                            pack = TPack.Create(target, state.CreateDefinition(file));
                        }
                        newPackages.Add(target, pack);
                        n++;
                    }
                }

                if (n == 0)
                {
                    break; // Can't package anything
                }
            }

            return(true);
        }
Esempio n. 16
0
        /// <summary>
        /// Adds the file.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="include">The include.</param>
        /// <param name="baseDirectory">The base directory.</param>
        /// <returns></returns>
        public TagItem AddFile(string name, string include, string baseDirectory)
        {
            baseDirectory = Path.GetFullPath(baseDirectory);
            include       = QQnPath.EnsureRelativePath(baseDirectory, include);

            TagItem item = new TagItem(name, include);

            item.Keys.Add("FileOrigin", baseDirectory);

            Add(item);

            return(item);
        }
Esempio n. 17
0
        public void VerifyTrueName()
        {
            foreach (Environment.SpecialFolder sv in Enum.GetValues(typeof(Environment.SpecialFolder)))
            {
                string path = Environment.GetFolderPath(sv);

                if (string.IsNullOrEmpty(path))
                {
                    continue;
                }

                Assert.That(QQnPath.GetTruePath(path.ToUpperInvariant()), Is.Not.Null);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Updates the version info in the file header from the attributes defined on the assembly.
        /// </summary>
        /// <param name="assemblyFile">The assembly.</param>
        /// <param name="keyFile">The key file.</param>
        /// <param name="keyContainer">The key container.</param>
        /// <returns></returns>
        public static bool RefreshVersionInfoFromAttributes(string assemblyFile, string keyFile, string keyContainer)
        {
            if (string.IsNullOrEmpty(assemblyFile))
            {
                throw new ArgumentNullException("assemblyFile");
            }

            if (!File.Exists(assemblyFile))
            {
                throw new FileNotFoundException("File to update not found", assemblyFile);
            }
            else if (!string.IsNullOrEmpty(keyFile) && !File.Exists(keyFile))
            {
                throw new FileNotFoundException("Keyfile not found", keyFile);
            }

            string tmpDir = QQnPath.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(tmpDir);
            try
            {
                string tmpName = QQnPath.Combine(tmpDir, Path.GetFileNameWithoutExtension(assemblyFile) + ".dll");

                Assembly       myAssembly = typeof(AssemblyUtils).Assembly;
                AppDomainSetup setup      = new AppDomainSetup();
                setup.ApplicationName               = "TB-AttributeRefresher";
                setup.ApplicationBase               = Path.GetDirectoryName(new Uri(myAssembly.CodeBase).LocalPath);
                setup.AppDomainInitializer          = new AppDomainInitializer(OnRefreshVersionInfo);
                setup.AppDomainInitializerArguments = new string[] { assemblyFile, tmpDir, tmpName };

                AppDomain dom = AppDomain.CreateDomain("AttributeRefresher", myAssembly.Evidence, setup);
                AppDomain.Unload(dom);                 // Remove locks

                if (!File.Exists(tmpName))
                {
                    return(false);
                }

                return(CopyFileVersionInfo(tmpName, assemblyFile, keyFile, keyContainer));
            }
            finally
            {
                if (Directory.Exists(tmpDir))
                {
                    Directory.Delete(tmpDir, true);
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Ensures the specified key is relative
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        protected virtual string EnsureRelative(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key");
            }

            if (string.IsNullOrEmpty(BaseDirectory))
            {
                return(Path.GetFullPath(key));
            }
            else
            {
                return(QQnPath.EnsureRelativePath(BaseDirectory, key));
            }
        }
Esempio n. 20
0
        public virtual void PostParseBuildResult()
        {
            if (string.IsNullOrEmpty(TargetPath) || string.IsNullOrEmpty(ProjectPath))
            {
                return;
            }

            if ((DebugSrc == null) || (DebugId == null))
            {
                string targetFile = GetFullPath(TargetPath);

                if (QQnPath.IsAssemblyFile(targetFile) && File.Exists(targetFile))
                {
                    DebugReference reference = AssemblyUtils.GetDebugReference(targetFile);

                    if (reference != null)
                    {
                        string   pdbSrc    = EnsureRelativePath(QQnPath.Combine(ProjectPath, Path.GetDirectoryName(TargetPath), reference.PdbFile));
                        FileInfo pdbTarget = new FileInfo(Path.GetFullPath(QQnPath.Combine(ProjectPath, Path.GetDirectoryName(TargetPath), Path.GetFileName(pdbSrc))));

                        if (pdbTarget.Exists)
                        {
                            FileInfo pdbFrom = new FileInfo(GetFullPath(pdbSrc));

                            if (!pdbFrom.Exists || ((pdbFrom.Length == pdbTarget.Length) && (pdbFrom.LastWriteTime == pdbTarget.LastWriteTime)))
                            {
                                pdbSrc = EnsureRelativePath(pdbTarget.FullName);
                            }
                        }

                        DebugSrc = pdbSrc;
                        DebugId  = reference.DebugId;
                    }
                    else
                    {
                        string pdbFile = Path.ChangeExtension(targetFile, ".pdb");

                        if (ProjectOutput.ContainsKey(pdbFile) && File.Exists(pdbFile))
                        {
                            pdbFile = EnsureRelativePath(pdbFile);

                            DebugSrc = pdbFile;
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        public void WriteTBLog()
        {
            if (TargetName == null)
            {
                return;
            }

            string outDir = OutputPath;

            outDir = Parameters.OutputPath ?? GetFullPath(OutputPath);

            if (!Directory.Exists(outDir))
            {
                Directory.CreateDirectory(outDir);
            }

            string atPath = QQnPath.Combine(outDir, ProjectName + ".tbLog");

            if (File.Exists(atPath))
            {
                try
                {
                    using (FileStream fs = File.OpenRead(atPath))
                    {
                        _previousLog = new XPathDocument(fs);
                    }
                }
                catch
                {
                    _previousLog = null;
                }
            }

            using (StreamWriter sw = new StreamWriter(atPath, false, Encoding.UTF8))
            {
                XmlWriterSettings xs = new XmlWriterSettings();

                xs.Indent = Parameters.Indent;

                using (XmlWriter xw = XmlWriter.Create(sw, xs))
                {
                    WriteTBLog(xw, xs.Indent);
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Calculates the target.
        /// </summary>
        /// <param name="pi">The pi.</param>
        /// <returns></returns>
        protected string CalculateTarget(ITaskItem pi)
        {
            string target = pi.GetMetadata("TargetPath");

            if (!string.IsNullOrEmpty(target))
            {
                return(QQnPath.Combine(OutputPath, target));
            }

            string destinationSubDirectory = pi.GetMetadata("DestinationSubDirectory");
            string filename = Path.GetFileName(pi.ItemSpec);

            if (!string.IsNullOrEmpty(destinationSubDirectory))
            {
                return(QQnPath.Combine(OutputPath, destinationSubDirectory, filename));
            }
            else
            {
                return(QQnPath.Combine(OutputPath, filename));
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Creates the specified package
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="definition">The definition.</param>
        /// <returns></returns>
        public static TPack Create(string fileName, Pack definition)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            else if (definition == null)
            {
                throw new ArgumentNullException("definition");
            }

            AssuredStreamCreateArgs args = new AssuredStreamCreateArgs();

            if (definition.StrongNameKey != null)
            {
                args.StrongNameKey = definition.StrongNameKey;
            }

            SortedFileList added = new SortedFileList();

            added.BaseDirectory = "c:\\" + Guid.NewGuid();
            foreach (PackContainer container in definition.Containers)
            {
                foreach (PackFile file in container.Files)
                {
                    if (!QQnPath.IsRelativeSubPath(file.StreamName) || added.Contains(file.StreamName))
                    {
                        string name = Path.GetFileNameWithoutExtension(file.StreamName);
                        string ext  = Path.GetExtension(file.StreamName);

                        string attempt = "_/" + name + ext;
                        int    n       = 0;
                        do
                        {
                            if (!added.Contains(attempt))
                            {
                                file.StreamName = attempt;
                                break;
                            }

                            attempt = string.Format("_/{0}.{1}.{2}", name, n++, ext);
                        }while (true);
                    }

                    if (file.StreamName.Contains("\\"))
                    {
                        file.StreamName = file.StreamName.Replace('\\', '/');
                    }
                }
            }

            args.FileType = PackageFileType;

            MultipleStreamCreateArgs msca = new MultipleStreamCreateArgs();

            msca.MaximumNumberOfStreams = 4;
            msca.VerificationMode       = VerificationMode.None;

            using (FileStream fs = File.Create(fileName, 32768))
                using (AssuredStream assurance = new AssuredStream(fs, args))
                    using (MultipleStreamWriter msw = new MultipleStreamWriter(assurance, msca))
                    {
                        MultipleStreamArgs msa = new MultipleStreamArgs();
                        msa.StreamType = 0x10;
                        msa.Assured    = true;
                        msa.GZipped    = true;
                        using (XmlWriter xw = new XmlTextWriter(msw.CreateStream(msa), Encoding.UTF8))
                        {
                            xw.WriteStartDocument();
                            xw.WriteStartElement("TurtlePackage", "http://schemas.qqn.nl/2007/TurtlePackage");
                            Tokenizer.TryWriteXml(xw, definition);
                            xw.WriteEndDocument();
                        }

                        msa            = new MultipleStreamArgs();
                        msa.StreamType = 0x11;

                        using (XmlWriter xw = new XmlTextWriter(msw.CreateStream(msa), Encoding.UTF8))
                        {
                            // TODO: Write tblog file
                        }


                        // Last stream: We add a zip file
                        msa            = new MultipleStreamArgs();
                        msa.StreamType = ZipFileId;  // Defined
                        msa.Assured    = false;      // Use the whole file assurance for the zip
                        msa.GZipped    = false;      // Don't compress again

                        using (Stream ms = msw.CreateStream(msa))
                            using (ZipFile zipFile = ZipFile.Create(ms))
                            {
                                zipFile.BeginUpdate();
                                zipFile.UseZip64 = UseZip64.Dynamic;

                                SetName setName = new SetName();

                                zipFile.NameTransform = setName;

                                foreach (PackContainer container in definition.Containers)
                                {
                                    foreach (PackFile file in container.Files)
                                    {
                                        setName.NextName = file.StreamName;

                                        Debug.Assert(File.Exists(file.FullName));

                                        zipFile.Add(file.FullName);
                                    }
                                }

                                zipFile.CommitUpdate();
                            }
                    }

            return(TPack.OpenFrom(fileName, VerificationMode.None));
        }
Esempio n. 24
0
        public void MakePackage()
        {
            string logFile = QQnPath.Combine(LoggerPath, "QQn.TurtleMSBuild.tbLog");

            if (!File.Exists(logFile))
            {
                BuildInternal();
            }

            TBLogFile log = TBLogFile.Load(logFile);

            Assert.That(!string.IsNullOrEmpty(log.Project.Name));

            DebugReference reference = null;

            foreach (TBLogItem item in log.Configurations[0].ProjectOutput.Items)
            {
                if (!item.IsShared && !item.IsCopy)
                {
                    switch (Path.GetExtension(item.Src).ToUpperInvariant())
                    {
                    case ".PDB":
                    case ".DLL":
                        if (reference == null)
                        {
                            reference = AssemblyUtils.GetDebugReference(item.FullSrc);

                            Assert.That(reference, Is.Not.Null);
                            Assert.That(reference.PdbFile, Is.Not.Null);
                        }
                        else
                        {
                            DebugReference dr = AssemblyUtils.GetDebugReference(item.FullSrc);

                            Assert.That(dr, Is.Not.Null);
                            // Path does not have to equal; the pdb information contains the sourcepath (obj directory for c# code)
                            Assert.That(Path.GetFileName(dr.PdbFile), Is.EqualTo(Path.GetFileName(reference.PdbFile)));
                            Assert.That(dr.DebugId, Is.EqualTo(reference.DebugId));
                        }
                        break;
                    }
                }
            }

            Pack pack = null;

            Assert.That(PackUtils.TryCreatePack(log, out pack));

            string path = QQnPath.Combine(PackagePath, "QQn.TurtleMSBuild.tpZip");
            TPack  tp   = TPack.Create(path, pack);

            using (TPack pkg = TPack.OpenFrom(path, VerificationMode.Full))
                using (DirectoryMap dm = DirectoryMap.Get(ExtractPath))
                {
                    Assert.That(pkg, Is.Not.Null);

                    pkg.ExtractTo(dm);
                }

            using (TPack pkg = TPack.OpenFrom(path, VerificationMode.Full))
            {
                Assert.That(pkg, Is.Not.Null);

                pkg.ExtractTo(ExtractPath);
            }
        }
Esempio n. 25
0
        private static string GenerateAttributeAssembly(Assembly assembly, string outputDirectory)
        {
            AssemblyName srcName = new AssemblyName(assembly.FullName);

            if (srcName == null || string.IsNullOrEmpty(srcName.Name))
            {
                return(null);
            }

            try
            {
                // Prepare dynamic assembly for resources
                AssemblyName asmName = new AssemblyName(srcName.FullName);
                asmName.Name = "Tmp." + srcName.Name;

                // Only create an on-disk assembly. We never have to execute anything
                AssemblyBuilder newAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.ReflectionOnly, outputDirectory);

                string tmpFile = srcName.Name + ".dll";
                newAssembly.DefineDynamicModule(asmName.Name, tmpFile);

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(OnReflectionOnlyAssemblyResolve);

                try
                {
                    Assembly mscorlib = Assembly.ReflectionOnlyLoad(typeof(int).Assembly.FullName);
                    Assembly system   = Assembly.ReflectionOnlyLoad(typeof(Uri).Assembly.FullName);
                    bool     hasInformationalVersion = false;
                    bool     hasVersion = false;

                    foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(assembly))
                    {
                        if ((attr.NamedArguments.Count > 0) || (attr.Constructor == null))
                        {
                            // We don't use named arguments at this time; not needed for the version resources
                            continue;
                        }

                        Type type = attr.Constructor.ReflectedType;

                        if (type.Assembly != mscorlib && type.Assembly != system)
                        {
                            continue;
                        }

                        if (type.Assembly == mscorlib)
                        {
                            switch (type.Name)
                            {
                            case "System.Reflection.AssemblyInformationalVersionAttribute":
                                hasInformationalVersion = true;
                                break;

                            case "System.Reflection.AssemblyVersionAttribute":
                                hasVersion = true;
                                break;
                            }
                        }

                        List <object> values = new List <object>();
                        foreach (CustomAttributeTypedArgument arg in attr.ConstructorArguments)
                        {
                            values.Add(arg.Value);
                        }

                        CustomAttributeBuilder cb = new CustomAttributeBuilder(attr.Constructor, values.ToArray());

                        newAssembly.SetCustomAttribute(cb);
                    }

                    if (!hasVersion)
                    {
                        newAssembly.SetCustomAttribute(
                            new CustomAttributeBuilder(typeof(AssemblyVersionAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                       new object[] { srcName.Version.ToString() }));
                    }
                    if (!hasInformationalVersion)
                    {
                        newAssembly.SetCustomAttribute(
                            new CustomAttributeBuilder(typeof(AssemblyInformationalVersionAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                       new object[] { srcName.Version.ToString() }));
                    }

                    newAssembly.SetCustomAttribute(
                        new CustomAttributeBuilder(typeof(AssemblyCultureAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                   new object[] { "" }));
                }
                finally
                {
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= new ResolveEventHandler(OnReflectionOnlyAssemblyResolve);
                }

                newAssembly.DefineVersionInfoResource();
                newAssembly.Save(tmpFile);

                return(QQnPath.Combine(outputDirectory, tmpFile));
            }
            catch (FileLoadException)
            {
                return(null);
            }
            catch (IOException)
            {
                return(null);
            }
        }
Esempio n. 26
0
 /// <summary>
 /// Makes a relative path from the path
 /// </summary>
 /// <param name="include">The include.</param>
 /// <returns></returns>
 public string EnsureRelativePath(string include)
 {
     return(QQnPath.EnsureRelativePath(ProjectPath, include));
 }
Esempio n. 27
0
 public string GetFullPath(string include)
 {
     return(Path.GetFullPath(QQnPath.Combine(ProjectPath, include)));
 }
Esempio n. 28
0
        public override void ApplyProjectDependencies(PackageState state)
        {
            if (!state.DontUseProjectDependencies)             // Allow disabling for testing
            {
                // Add an initial set of dependencies directly from the project files
                foreach (TBLogConfiguration config in LogFile.Configurations)
                {
                    foreach (TBLogItem project in config.References.Projects)
                    {
                        string src = QQnPath.NormalizePath(project.FullSrc);

                        foreach (Origin o in state.Origins)
                        {
                            BuildOrigin bo = o as BuildOrigin;
                            if (bo == null)
                            {
                                continue;
                            }

                            if (QQnPath.Equals(bo.ProjectFile, src) && !Dependencies.ContainsKey(o))
                            {
                                EnsureDependency(o, DependencyType.LinkedTo);
                            }
                        }
                    }
                }
            }

            foreach (TBLogItem item in LogFile.AllProjectOutput)
            {
                FileData fd = state.Files[item.FullSrc];

                if (!string.IsNullOrEmpty(fd.CopiedFrom))
                {
                    FileData src;

                    if (state.Files.TryGetValue(fd.CopiedFrom, out src))
                    {
                        if (src.Origin != this)
                        {
                            EnsureDependency(src.Origin, item.IsCopy ? DependencyType.Required : DependencyType.LinkedTo);
                        }
                    }
                }
            }

            foreach (TBLogItem item in LogFile.AllContents)
            {
                FileData fd = state.Files[item.FullSrc];

                if (!string.IsNullOrEmpty(fd.CopiedFrom))
                {
                    FileData src;

                    if (state.Files.TryGetValue(fd.CopiedFrom, out src))
                    {
                        if (src.Origin != this)
                        {
                            EnsureDependency(src.Origin, DependencyType.Required);
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        public Pack CreateDefinition(TBLogFile file)
        {
            BuildOrigin myOrigin = null;

            foreach (BuildOrigin bo in BuildOrigins)
            {
                if (bo.LogFile == file)
                {
                    myOrigin = bo;
                    break;
                }
            }

            Pack p = new Pack();

            TBLogConfiguration config = file.Configurations[0];
            TBLogTarget        target = config.Target;
            TBLogAssembly      asm    = config.Assembly;

            if (!string.IsNullOrEmpty(target.KeySrc))
            {
                p.StrongNameKey = StrongNameKey.LoadFrom(QQnPath.Combine(file.ProjectPath, target.KeySrc));
            }
            else if (!string.IsNullOrEmpty(target.KeyContainer))
            {
                p.StrongNameKey = StrongNameKey.LoadFromContainer(target.KeyContainer, false);
            }

            if (asm != null && !string.IsNullOrEmpty(asm.AssemblyName))
            {
                AssemblyName name = new AssemblyName(asm.AssemblyName);
                p.Version = name.Version;
            }

            PackContainer po = p.Containers.AddItem("#ProjectOutput");

            po.ContainerDir = config.OutputPath;
            po.BaseDir      = QQnPath.Combine(file.ProjectPath);
            foreach (TBLogItem item in file.AllProjectOutput)
            {
                if (item.IsShared)
                {
                    continue;
                }

                PackFile pf = po.Files.AddItem(QQnPath.EnsureRelativePath(po.BaseDir, item.FullSrc));
                pf.StreamName = item.Src;
            }

            PackContainer ct = p.Containers.AddItem("#Content");

            ct.ContainerDir = "";
            po.BaseDir      = file.ProjectPath;

            foreach (TBLogItem item in file.AllContents)
            {
                if (item.IsShared)
                {
                    continue;
                }

                PackFile pf = po.Files.AddItem(QQnPath.EnsureRelativePath(po.BaseDir, item.FullSrc));
            }

            myOrigin.Pack = p;

            return(p);
        }
Esempio n. 30
0
 /// <summary>
 /// Ensures the specified key is relative
 /// </summary>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 protected override string EnsureRelative(string key)
 {
     return(QQnPath.EnsureExtension(base.EnsureRelative(key), ".tbLog"));
 }