Пример #1
0
        public MSBuildConfiguration(MSBuildProject project, NAnt.MSBuild.BuildEngine.Project msproj, Configuration projectConfig)
            : base(project)
        {
            _name = projectConfig.Name;
            _platform = projectConfig.Platform;

            //explicit set. EvaluatedProperties will use those.
            //Its caller responsibility to set it back to original values, if needed
            msproj.GlobalProperties.SetProperty("Configuration", _name);

            if (!String.IsNullOrEmpty(_platform)) {
                msproj.GlobalProperties.SetProperty("Platform", _platform.Replace(" ", string.Empty));
            }

            _relativeOutputDir = msproj.GetEvaluatedProperty("OutputPath");
            if (!_relativeOutputDir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) {
                _relativeOutputDir = _relativeOutputDir + Path.DirectorySeparatorChar;
            }
            _outputDir = new DirectoryInfo(FileUtils.CombinePaths(
                project.ProjectDirectory.FullName,
                _relativeOutputDir));

            _objdir = new DirectoryInfo(msproj.GetEvaluatedProperty("IntermediateOutputPath"));

            _outputType = GetType(msproj.GetEvaluatedProperty("OutputType"));
            _asmname = msproj.GetEvaluatedProperty("AssemblyName");
        }
Пример #2
0
        public MSBuildProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir)
            : base(xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir)
        {
            string cfgname = solutionTask.Configuration;
            string platform = solutionTask.Platform;

            _msbuild = MSBuildEngine.CreateMSEngine(solutionTask);
            _msproj = new Microsoft.Build.BuildEngine.Project(_msbuild);
            _msproj.FullFileName = projectPath;
            _msproj.LoadXml(xmlDefinition.OuterXml);
            _msproj.GlobalProperties.SetProperty("Configuration", cfgname);
            SetPlatform (platform);
            if (outputDir != null) _msproj.GlobalProperties.SetProperty("OutputPath", outputDir.FullName);

            //evaluating
            _guid = _msproj.GetEvaluatedProperty("ProjectGuid");
            _projectDirectory = new DirectoryInfo(_msproj.GetEvaluatedProperty("ProjectDir"));
            _projectPath = _msproj.GetEvaluatedProperty("ProjectPath");

            ProjectEntry projectEntry = solution.ProjectEntries [_guid];
            if (projectEntry != null && projectEntry.BuildConfigurations != null) {
                foreach (ConfigurationMapEntry ce in projectEntry.BuildConfigurations) {
                    Configuration projectConfig = ce.Value;
                    ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig);
                }
            } else {
                Configuration projectConfig = new Configuration (cfgname, platform);
                ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig);
            }

            //references
            _references = new ArrayList();
            Microsoft.Build.BuildEngine.BuildItemGroup refs = _msproj.GetEvaluatedItemsByName("Reference");
            foreach (Microsoft.Build.BuildEngine.BuildItem r in refs) {
                string rpath = r.FinalItemSpec;
                string priv = r.GetMetadata("Private");
                string hintpath = r.GetMetadata("HintPath");

                ReferenceBase reference = new MSBuildAssemblyReference(
                    xmlDefinition, ReferencesResolver, this, gacCache,
                    rpath, priv, hintpath);
                _references.Add(reference);
            }
            refs = _msproj.GetEvaluatedItemsByName("ProjectReference");
            foreach (Microsoft.Build.BuildEngine.BuildItem r in refs) {
                string pguid = r.GetMetadata("Project");
                string pname = r.GetMetadata("Name");
                string rpath = r.FinalItemSpec;
                string priv = r.GetMetadata("Private");
                ReferenceBase reference = new MSBuildProjectReference(
                    ReferencesResolver, this, solution, tfc, gacCache, outputDir,
                    pguid, pname, rpath, priv);
                _references.Add(reference);
            }
        }
Пример #3
0
        public MSBuildConfiguration(MSBuildProject project, Microsoft.Build.BuildEngine.Project msproj, Configuration projectConfig)
            : base(project)
        {
            _name = projectConfig.Name;

            msproj.GlobalProperties.SetProperty("Configuration", _name);
            project.SetPlatform (projectConfig.Platform);
            _platform = msproj.GetEvaluatedProperty("Platform");

            _relativeOutputDir = msproj.GetEvaluatedProperty("OutputPath");
            if (!_relativeOutputDir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) {
                _relativeOutputDir = _relativeOutputDir + Path.DirectorySeparatorChar;
            }
            _outputDir = new DirectoryInfo(FileUtils.CombinePaths(
                project.ProjectDirectory.FullName,
                _relativeOutputDir));

            _objdir = new DirectoryInfo(msproj.GetEvaluatedProperty("IntermediateOutputPath"));

            _outputType = GetType(msproj.GetEvaluatedProperty("OutputType"));
            _asmname = msproj.GetEvaluatedProperty("AssemblyName");
        }
Пример #4
0
 /// <summary>
 /// Gets a value indicating whether the reference is managed for the
 /// specified configuration.
 /// </summary>
 /// <param name="config">The build configuration of the reference.</param>
 /// <returns>
 /// <see langword="true" />.
 /// </returns>
 public override bool IsManaged(Configuration config)
 {
     return true;
 }
Пример #5
0
 /// <summary>
 /// Gets the timestamp of the reference.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// The timestamp of the reference.
 /// </returns>
 public abstract DateTime GetTimestamp(Configuration solutionConfiguration);
Пример #6
0
 /// <summary>
 /// Gets the complete set of output files of the reference for the 
 /// specified configuration.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <param name="outputFiles">The set of output files to be updated.</param>
 /// <remarks>
 /// The key of the case-insensitive <see cref="Hashtable" /> is the 
 /// full path of the output file and the value is the path relative to
 /// the output directory.
 /// </remarks>
 public abstract void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles);
Пример #7
0
 public void Add(Configuration key, Configuration value) {
     _innerHash.Add (key, value);
 }
Пример #8
0
 public void Remove(Configuration configuration) {
     _innerHash.Remove(configuration);
 }
Пример #9
0
 public Configuration this[Configuration key] {
     get { return (Configuration) _innerHash[key]; }
     set { _innerHash[key] = value; }
 }
Пример #10
0
        /// <summary>
        /// Gets the complete set of output files for the project configuration
        /// matching the specified solution configuration.
        /// </summary>
        /// <param name="solutionConfiguration">The solution configuration that is built.</param>
        /// <param name="outputFiles">The set of output files to be updated.</param>
        /// <remarks>
        ///   <para>
        ///   The key of the case-insensitive <see cref="Hashtable" /> is the 
        ///   full path of the output file and the value is the path relative to
        ///   the output directory.
        ///   </para>
        ///   <para>
        ///   If the project is not configured to be built for the specified
        ///   solution configuration, then no output files are added.
        ///   </para>
        /// </remarks>
        public override void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles)
        {
            base.GetOutputFiles (solutionConfiguration, outputFiles);

            // obtain project configuration (corresponding with solution configuration)
            ConfigurationSettings projectConfig = (ConfigurationSettings)
                BuildConfigurations[solutionConfiguration];
            if (projectConfig == null) {
                // the project is not configured to be built for the specified
                // solution configuration
                return;
            }

            // add type library
            if (projectConfig.RegisterForComInterop) {
                string typeLib = GetTypeLibraryPath(projectConfig);
                if (!outputFiles.ContainsKey(typeLib)) {
                    outputFiles.Add(typeLib, Path.GetFileName(typeLib));
                }
            }

            // add satellite assemblies
            Hashtable resourceSets = GetLocalizedResources();
            foreach (LocalizedResourceSet localizedResourceSet in resourceSets.Values) {
                FileInfo satelliteAssembly = localizedResourceSet.GetSatelliteAssemblyPath(
                    projectConfig, ProjectSettings);
                // skip files that do not exist, or are already in hashtable
                if (satelliteAssembly.Exists && !outputFiles.ContainsKey(satelliteAssembly.FullName)) {
                    string relativePath = localizedResourceSet.GetRelativePath(
                        ProjectSettings);
                    outputFiles.Add(satelliteAssembly.FullName, relativePath);
                }
            }
        }
Пример #11
0
        private void WriteNeutralResourceOptions(StreamWriter sw, Configuration solutionConfiguration)
        {
            // no further processing required if there are no neutral resource
            // files
            if (_neutralResources.Count == 0) {
                return;
            }

            foreach (Resource resource in _neutralResources) {
                Log(Level.Verbose, " - {0}", resource.InputFile);

                if (resource.IsResX) {
                    // determine filename of compiled file
                    FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration);
                    // determine manifest resource name
                    string manifestResourceName = resource.GetManifestResourceName(
                        solutionConfiguration);
                    // write option to response file
                    sw.WriteLine(string.Format(CultureInfo.InvariantCulture,
                        "/res:\"{0}\",\"{1}\"", compiledResxFile.FullName,
                        manifestResourceName));
                } else {
                    // compile resource
                    FileInfo compiledResourceFile = resource.Compile(
                        solutionConfiguration);
                    // write option to response file
                    sw.WriteLine(string.Format(CultureInfo.InvariantCulture,
                        "/res:\"{0}\",\"{1}\"", compiledResourceFile.FullName,
                        resource.GetManifestResourceName(solutionConfiguration)));
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Unregister a type library for the specified assembly, and the types
        /// in that assembly.
        /// </summary>
        /// <param name="config">The project configuration that is built.</param>
        /// <param name="solutionConfiguration">The solution configuration that is built.</param>
        /// <remarks>
        /// The <c>regasm</c> tool is used to unregister the type library, and
        /// remove the COM registration for types in the specified assembly.
        /// </remarks>
        private void UnregisterForComInterop(ConfigurationSettings config, Configuration solutionConfiguration)
        {
            // if COM interop registration is not enabled or the previous project
            // output does not exist, then there's nothing to do
            if (!config.RegisterForComInterop || !File.Exists(config.OutputPath)) {
                return;
            }

            Log(Level.Verbose, "Unregistering project output for COM Interop...");

            // create and initialize regasm task
            RegAsmTask regasm = CreateRegAsmTask();
            // add assembly references
            foreach (ReferenceBase reference in References) {
                StringCollection assemblyReferences = reference.GetAssemblyReferences(
                    solutionConfiguration);
                foreach (string assemblyFile in assemblyReferences) {
                    regasm.References.Includes.Add(assemblyFile);
                }
            }
            // unregister types
            regasm.Unregister = true;
            // assembly to unregister
            regasm.AssemblyFile = new FileInfo(config.OutputPath);
            // determine path for type library
            string typeLibPath = GetTypeLibraryPath(config);
            // if the type library exists, unregister it
            if (File.Exists(typeLibPath)) {
                regasm.TypeLib = new FileInfo(typeLibPath);
            }

            // increment indentation level
            regasm.Project.Indent();
            try {
                regasm.Execute();
            } finally {
                // restore indentation level
                regasm.Project.Unindent();
            }
        }
Пример #13
0
        /// <summary>
        /// Generates a type library for the specified assembly, registers it.
        /// </summary>
        /// <param name="config">The project configuration that is built.</param>
        /// <param name="solutionConfiguration">The solution configuration that is built.</param>
        /// <param name="typelibPath">The path of the type library to generate.</param>
        /// <remarks>
        /// The <c>regasm</c> tool is used to generate the type library.
        /// </remarks>
        private void RegisterForComInterop(ConfigurationSettings config, Configuration solutionConfiguration, string typelibPath)
        {
            Log(Level.Verbose, "Registering project output for COM Interop...");

            // create and initialize regasm task
            RegAsmTask regasm = CreateRegAsmTask();
            // add assembly references
            foreach (ReferenceBase reference in References) {
                StringCollection assemblyReferences = reference.GetAssemblyReferences(
                    solutionConfiguration);
                foreach (string assemblyFile in assemblyReferences) {
                    regasm.References.Includes.Add(assemblyFile);
                }
            }
            // assembly to register for COM interop
            regasm.AssemblyFile = new FileInfo(config.BuildPath);
            // type library to create
            regasm.TypeLib = new FileInfo(typelibPath);

            // increment indentation level
            regasm.Project.Indent();
            try {
                // execute task
                regasm.Execute();
            } finally {
                // restore indentation level
                regasm.Project.Unindent();
            }
        }
Пример #14
0
        private void CompileResXFiles(Configuration solutionConfiguration)
        {
            Log(Level.Verbose, "Compiling resources:");

            Hashtable resxResources = new Hashtable();

            // neutral resources
            foreach (Resource resource in _neutralResources) {
                if (!resource.IsResX) {
                    continue;
                }

                Log(Level.Verbose, " - {0}", resource.InputFile);

                // determine filename of output file
                FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration);
                // add to list of resx files to compile
                resxResources.Add(resource, compiledResxFile);
            }

            // localized resources
            foreach (Resource resource in _localizedResources) {
                if (!resource.IsResX) {
                    continue;
                }

                Log(Level.Verbose, " - {0}", resource.InputFile);

                // determine filename of output file
                FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration);
                // add to list of resx files to compile
                resxResources.Add(resource, compiledResxFile);
            }

            // no further processing required if there are no resx files to
            // compile
            if (resxResources.Count == 0) {
                return;
            }

            // create instance of ResGen task
            ResGenTask rt = new ResGenTask();

            // inherit project from solution task
            rt.Project = SolutionTask.Project;

            // inherit namespace manager from solution task
            rt.NamespaceManager = SolutionTask.NamespaceManager;

            // parent is solution task
            rt.Parent = SolutionTask;

            // inherit verbose setting from solution task
            rt.Verbose = SolutionTask.Verbose;

            // make sure framework specific information is set
            rt.InitializeTaskConfiguration();

            // set parent of child elements
            rt.Assemblies.Parent = rt;

            // inherit project from solution task from parent task
            rt.Assemblies.Project = rt.Project;

            // inherit namespace manager from parent task
            rt.Assemblies.NamespaceManager = rt.NamespaceManager;

            // set base directory for filesets
            rt.Assemblies.BaseDirectory = ProjectDirectory;

            // set resx files to compile
            foreach (DictionaryEntry entry in resxResources) {
                Resource resource = (Resource) entry.Key;
                FileInfo outputFile = (FileInfo) entry.Value;

                QualifiedResource qualifiedResource = new QualifiedResource(
                    resource.InputFile, outputFile);

                rt.QualifiedResources.Add(qualifiedResource);
            }

            // inherit assembly references from project
            foreach (ReferenceBase reference in References) {
                StringCollection assemblyReferences = reference.GetAssemblyReferences(
                    solutionConfiguration);
                foreach (string assemblyFile in assemblyReferences) {
                    rt.Assemblies.Includes.Add(assemblyFile);
                }
            }

            // increment indentation level
            rt.Project.Indent();
            try {
                // execute task
                rt.Execute();
            } finally {
                // restore indentation level
                rt.Project.Unindent();
            }
        }
Пример #15
0
 /// <summary>
 /// Gets a value indicating whether the reference is managed for the
 /// specified configuration.
 /// </summary>
 /// <param name="config">The build configuration of the reference.</param>
 /// <returns>
 /// <see langword="true" /> if the reference is managed for the
 /// specified configuration; otherwise, <see langword="false" />.
 /// </returns>
 public override bool IsManaged(Configuration config)
 {
     return Project.IsManaged(config);
 }
Пример #16
0
        protected override BuildResult Build(Configuration solutionConfiguration)
        {
            // prepare the project for build
            Prepare(solutionConfiguration);

            // obtain project configuration (corresponding with solution configuration)
            VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration];

            // perform pre-build actions
            if (!PreBuild(projectConfig)) {
                return BuildResult.Failed;
            }

            string nmakeCommand = projectConfig.GetToolSetting(VcConfigurationBase.NMakeTool, "BuildCommandLine");
            if (!String.IsNullOrEmpty(nmakeCommand)) {
                RunNMake(nmakeCommand);
                return BuildResult.Success;
            }

            VcConfigurationBase stdafxConfig = null;

            // build idl files before everything else
            foreach (VcConfigurationBase idlConfig in projectConfig.IdlConfigs.Keys) {
                BuildIDLFiles((ArrayList) projectConfig.IdlConfigs[idlConfig],
                    projectConfig, idlConfig);
            }

            // If VC project uses precompiled headers then the precompiled header
            // output (.pch file) must be generated before compiling any other
            // source files.
            foreach (VcConfigurationBase vcConfig in projectConfig.SourceConfigs.Keys) {
                if (vcConfig.UsePrecompiledHeader == UsePrecompiledHeader.Create) {
                    BuildCPPFiles((ArrayList) projectConfig.SourceConfigs[vcConfig],
                        solutionConfiguration, vcConfig);
                    stdafxConfig = vcConfig;
                }
            }

            foreach (VcConfigurationBase vcConfig in projectConfig.SourceConfigs.Keys) {
                if (vcConfig != stdafxConfig) {
                    BuildCPPFiles((ArrayList) projectConfig.SourceConfigs[vcConfig],
                        solutionConfiguration, vcConfig);
                }
            }

            // build resource files
            foreach (VcConfigurationBase rcConfig in projectConfig.RcConfigs.Keys) {
                BuildResourceFiles((ArrayList) projectConfig.RcConfigs[rcConfig],
                    projectConfig, rcConfig);
            }

            switch (projectConfig.Type) {
                case VcProjectConfiguration.ConfigurationType.StaticLibrary:
                    RunLibrarian(projectConfig);
                    break;
                case VcProjectConfiguration.ConfigurationType.Application:
                case VcProjectConfiguration.ConfigurationType.DynamicLibrary:
                    // perform pre-link actions
                    if (!PreLink(projectConfig)) {
                        return BuildResult.Failed;
                    }
                    RunLinker(solutionConfiguration);
                    break;
            }

            Log(Level.Verbose, "Copying references:");

            foreach (ReferenceBase reference in _references) {
                if (reference.CopyLocal) {
                    Log(Level.Verbose, " - " + reference.Name);

                    Hashtable outputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable();
                    reference.GetOutputFiles(solutionConfiguration, outputFiles);

                    foreach (DictionaryEntry de in outputFiles) {
                        // determine file to copy
                        FileInfo srcFile = new FileInfo((string) de.Key);
                        // determine destination file
                        FileInfo destFile = new FileInfo(FileUtils.CombinePaths(
                            projectConfig.OutputDir.FullName, (string) de.Value));
                        // perform actual copy
                        CopyFile(srcFile, destFile, SolutionTask);
                    }
                }
            }

            // run custom build steps
            if (!RunCustomBuildStep(solutionConfiguration, projectConfig)) {
                return BuildResult.Failed;
            }

            // perform post-build actions
            if (!PostBuild(projectConfig)) {
                return BuildResult.Failed;
            }

            return BuildResult.Success;
        }
Пример #17
0
        private void BuildCPPFiles(ArrayList fileNames, Configuration solutionConfiguration, VcConfigurationBase fileConfig)
        {
            // obtain project configuration (corresponding with solution configuration)
            VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration];

            string intermediateDir = FileUtils.CombinePaths(ProjectDirectory.FullName,
                projectConfig.IntermediateDir);

            // create instance of Cl task
            ClTask clTask = new ClTask();

            // inherit project from solution task
            clTask.Project = SolutionTask.Project;

            // inherit namespace manager from solution task
            clTask.NamespaceManager = SolutionTask.NamespaceManager;

            // parent is solution task
            clTask.Parent = SolutionTask;

            // inherit verbose setting from solution task
            clTask.Verbose = SolutionTask.Verbose;

            // make sure framework specific information is set
            clTask.InitializeTaskConfiguration();

            // set parent of child elements
            clTask.IncludeDirs.Parent = clTask;
            clTask.Sources.Parent = clTask;
            clTask.MetaDataIncludeDirs.Parent = clTask;
            clTask.ForcedUsingFiles.Parent = clTask;

            // inherit project from solution task for child elements
            clTask.IncludeDirs.Project = clTask.Project;
            clTask.Sources.Project = clTask.Project;
            clTask.MetaDataIncludeDirs.Project = clTask.Project;
            clTask.ForcedUsingFiles.Project = clTask.Project;

            // set namespace manager of child elements
            clTask.IncludeDirs.NamespaceManager = clTask.NamespaceManager;
            clTask.Sources.NamespaceManager = clTask.NamespaceManager;
            clTask.MetaDataIncludeDirs.NamespaceManager = clTask.NamespaceManager;
            clTask.ForcedUsingFiles.NamespaceManager = clTask.NamespaceManager;

            // set base directories
            clTask.IncludeDirs.BaseDirectory = ProjectDirectory;
            clTask.Sources.BaseDirectory = ProjectDirectory;
            clTask.MetaDataIncludeDirs.BaseDirectory = ProjectDirectory;
            clTask.ForcedUsingFiles.BaseDirectory = ProjectDirectory;

            // set task properties
            clTask.OutputDir = new DirectoryInfo(intermediateDir);

            // TODO: add support for disabling specific warnings !!!

            // check if precompiled headers are used
            if (fileConfig.UsePrecompiledHeader != UsePrecompiledHeader.No && fileConfig.UsePrecompiledHeader != UsePrecompiledHeader.Unspecified) {
                // get location of precompiled header file
                string pchFile = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool,
                    "PrecompiledHeaderFile", "$(IntDir)/$(TargetName).pch");

                // we must set an absolute path for the PCH location file,
                // otherwise <cl> assumes a location relative to the output
                // directory - not the project directory.
                if (!String.IsNullOrEmpty(pchFile)) {
                    clTask.PchFile = FileUtils.CombinePaths(ProjectDirectory.FullName, pchFile);
                }

                // check if a header file is specified for the precompiled header
                // file, use "StdAfx.h" as default value
                string headerThrough = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool,
                    "PrecompiledHeaderThrough", "StdAfx.h");
                if (!String.IsNullOrEmpty(headerThrough)) {
                    clTask.PchThroughFile = headerThrough;
                }

                switch (fileConfig.UsePrecompiledHeader) {
                    case UsePrecompiledHeader.Use:
                        clTask.PchMode = ClTask.PrecompiledHeaderMode.Use;
                        break;
                    case UsePrecompiledHeader.AutoCreate:
                        clTask.PchMode = ClTask.PrecompiledHeaderMode.AutoCreate;
                        break;
                    case UsePrecompiledHeader.Create:
                        clTask.PchMode = ClTask.PrecompiledHeaderMode.Create;
                        break;
                }
            }

            clTask.CharacterSet = projectConfig.CharacterSet;

            // ensure output directory exists
            if (!clTask.OutputDir.Exists) {
                clTask.OutputDir.Create();
                clTask.OutputDir.Refresh();
            }

            string includeDirs = MergeToolSetting(projectConfig, fileConfig,
                VcConfigurationBase.CLCompilerTool, "AdditionalIncludeDirectories");
            if (!String.IsNullOrEmpty(includeDirs)) {
                foreach (string includeDir in includeDirs.Split(',', ';')) {
                    if (includeDir.Length == 0) {
                        continue;
                    }
                    clTask.IncludeDirs.DirectoryNames.Add(FileUtils.CombinePaths(
                        ProjectDirectory.FullName, CleanPath(includeDir)));
                }
            }

            string metadataDirs = MergeToolSetting(projectConfig, fileConfig,
                VcConfigurationBase.CLCompilerTool, "AdditionalUsingDirectories");
            if (!String.IsNullOrEmpty(metadataDirs)) {
                foreach (string metadataDir in metadataDirs.Split(';')) {
                    if (metadataDir.Length == 0) {
                        continue;
                    }
                    clTask.MetaDataIncludeDirs.DirectoryNames.Add(
                        CleanPath(fileConfig.ExpandMacros(metadataDir)));
                }
            }

            string forcedUsingFiles = MergeToolSetting(projectConfig, fileConfig,
                VcConfigurationBase.CLCompilerTool, "ForcedUsingFiles");
            if (!String.IsNullOrEmpty(forcedUsingFiles)) {
                foreach (string forcedUsingFile in forcedUsingFiles.Split(';')) {
                    if (forcedUsingFile.Length == 0) {
                        continue;
                    }
                    clTask.ForcedUsingFiles.Includes.Add(
                        CleanPath(fileConfig.ExpandMacros(forcedUsingFile)));
                }
            }

            // add project and assembly references
            foreach (ReferenceBase reference in References) {
                if (!reference.IsManaged(solutionConfiguration)) {
                    continue;
                }

                StringCollection assemblyReferences = reference.GetAssemblyReferences(
                    solutionConfiguration);
                foreach (string assemblyFile in assemblyReferences) {
                    clTask.ForcedUsingFiles.Includes.Add(assemblyFile);
                }
            }

            // Since the name of the pdb file is based on the VS version, we need to see
            // which version we are targeting to make sure the right pdb file is used.
            string pdbTargetFileName;

            switch (ProductVersion) {
                case ProductVersion.Rosario:
                    pdbTargetFileName = "$(IntDir)/vc100.pdb";
                    break;
                case ProductVersion.Orcas:
                    pdbTargetFileName = "$(IntDir)/vc90.pdb";
                    break;
                case ProductVersion.Whidbey:
                    pdbTargetFileName = "$(IntDir)/vc80.pdb";
                    break;
                default:
                    pdbTargetFileName = "$(IntDir)/vc70.pdb";
                    break;
            }

            // set name of program database file
            //
            // we must set an absolute path for the program database file,
            // otherwise <cl> assumes a location relative to the output
            // directory - not the project directory.
            string pdbFile = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool,
                "ProgramDataBaseFileName", pdbTargetFileName);
            if (!String.IsNullOrEmpty(pdbFile)) {
                clTask.ProgramDatabaseFile = FileUtils.CombinePaths(ProjectDirectory.FullName,
                    pdbFile);
            }

            // set path of object file or directory (can be null)
            clTask.ObjectFile = GetObjectFile(fileConfig);

            string asmOutput = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AssemblerOutput");
            string asmListingLocation = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AssemblerListingLocation");
            if (!String.IsNullOrEmpty(asmOutput) && asmOutput != "0" && !String.IsNullOrEmpty(asmListingLocation)) {
                // parameter for AssemblerOutput itself will be handled by the map
                clTask.Arguments.Add(new Argument("/Fa\"" + asmListingLocation + "\""));
            }

            foreach (string fileName in fileNames) {
                clTask.Sources.FileNames.Add(FileUtils.CombinePaths(
                    ProjectDirectory.FullName, fileName));
            }

            string preprocessorDefs = MergeToolSetting(projectConfig, fileConfig,
                VcConfigurationBase.CLCompilerTool, "PreprocessorDefinitions");
            if (!String.IsNullOrEmpty(preprocessorDefs)) {
                foreach (string def in preprocessorDefs.Split(';', ',')) {
                    if (def.Length != 0) {
                        Option op = new Option();
                        op.OptionName = def;
                        clTask.Defines.Add(op);
                    }
                }
            }

            string undefinePreprocessorDefs = MergeToolSetting(projectConfig, fileConfig,
                VcConfigurationBase.CLCompilerTool, "UndefinePreprocessorDefinitions");
            if (!String.IsNullOrEmpty(undefinePreprocessorDefs)) {
                foreach (string def in undefinePreprocessorDefs.Split(';', ',')) {
                    Option op = new Option();
                    op.OptionName = def;
                    clTask.Undefines.Add(op);
                }
            }

            string addOptions = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AdditionalOptions");
            if (!String.IsNullOrEmpty(addOptions)) {
                using (StringReader reader = new StringReader(addOptions)) {
                    string addOptionsLine = reader.ReadLine();
                    while (addOptionsLine != null) {
                        foreach (string addOption in addOptionsLine.Split(' '))  {
                            clTask.Arguments.Add(new Argument(addOption));
                        }
                        addOptionsLine = reader.ReadLine();
                    }
                }
            }

            //exception handling stuff
            string exceptionHandling = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "ExceptionHandling");
            if (exceptionHandling == null) {
                if (ProductVersion >= ProductVersion.Whidbey) {
                    exceptionHandling = "2";
                } else {
                    exceptionHandling = "false";
                }
            } else {
                exceptionHandling = exceptionHandling.ToLower();
            }
            switch(exceptionHandling) {
                case "0":
                case "false":
                    break;
                case "1":
                case "true":
                    clTask.Arguments.Add(new Argument("/EHsc"));
                    break;
                case "2":
                    clTask.Arguments.Add(new Argument("/EHa"));
                    break;
            }

            string browseInformation = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "BrowseInformation");
            if (!String.IsNullOrEmpty(browseInformation) && browseInformation != "0") {
                // determine file name of browse information file
                string browseInformationFile = fileConfig.GetToolSetting(
                    VcConfigurationBase.CLCompilerTool, "BrowseInformationFile",
                    "$(IntDir)/");
                if (!String.IsNullOrEmpty(browseInformationFile)) {
                    switch (browseInformation) {
                        case "1": // Include All Browse Information
                            clTask.Arguments.Add(new Argument("/FR\""
                                + browseInformationFile + "\""));
                            break;
                        case "2": // No Local Symbols
                            clTask.Arguments.Add(new Argument("/Fr\""
                                + browseInformationFile + "\""));
                            break;
                    }
                } else {
                    switch (browseInformation) {
                        case "1": // Include All Browse Information
                            clTask.Arguments.Add(new Argument("/FR"));
                            break;
                        case "2": // No Local Symbols
                            clTask.Arguments.Add(new Argument("/Fr"));
                            break;
                    }
                }
            }

            if (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary) {
                clTask.Arguments.Add(new Argument("/D"));
                clTask.Arguments.Add(new Argument("_WINDLL"));
            }

            if (projectConfig.WholeProgramOptimization) {
                clTask.Arguments.Add(new Argument("/GL"));
            }

            // used to ignore some arguments
            VcArgumentMap.ArgGroup vcArgIgnoreGroup = VcArgumentMap.ArgGroup.Unassigned;

            // if optimzation level is Minimum Size (1) or Maximum size (2), we
            // need to ignore all the arguments of the group "OptiIgnoreGroup"
            string optimization = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "Optimization");
            if (!String.IsNullOrEmpty(optimization)) {
                int optimizationLevel = int.Parse(optimization);
                if (optimizationLevel == 1 || optimizationLevel == 2) {
                    vcArgIgnoreGroup |= VcArgumentMap.ArgGroup.OptiIgnoreGroup;
                }
            }

            Hashtable compilerArgs = fileConfig.GetToolArguments(VcConfigurationBase.CLCompilerTool,
                _clArgMap, vcArgIgnoreGroup);
            foreach (string arg in compilerArgs.Values) {
                Argument compilerArg = new Argument();
                compilerArg.Line = arg;
                clTask.Arguments.Add(compilerArg);
            }

            // check for shared MFC
            if (projectConfig.UseOfMFC == UseOfMFC.Shared) {
                clTask.Arguments.Add(new Argument("/D"));
                clTask.Arguments.Add(new Argument("_AFXDLL"));
            }

            // check for shared ATL
            switch (projectConfig.UseOfATL) {
                case UseOfATL.Shared:
                    clTask.Arguments.Add(new Argument("/D"));
                    clTask.Arguments.Add(new Argument("_ATL_DLL"));
                    break;
                case UseOfATL.Static:
                    clTask.Arguments.Add(new Argument("/D"));
                    clTask.Arguments.Add(new Argument("_ATL_STATIC_REGISTRY"));
                    break;
            }

            // enable/disable Managed Extensions for C++
            clTask.ManagedExtensions = projectConfig.ManagedExtensions;

            // execute the task
            ExecuteInProjectDirectory(clTask);
        }
Пример #18
0
        /// <summary>
        /// Builds the specified solution configuration.
        /// </summary>
        /// <param name="solutionConfiguration">The solution configuration.</param>
        /// <returns></returns>
        protected override BuildResult Build(Configuration solutionConfiguration)
        {
            bool bSuccess = true;
            bool outputUpdated;
            string tempFile = null;

            GacCache.RecreateDomain();

            try {
                // obtain project configuration (corresponding with solution configuration)
                ConfigurationSettings cs = (ConfigurationSettings) BuildConfigurations[solutionConfiguration];

                // perform prebuild actions (for VS.NET 2003 and higher)
                if (!PreBuild(cs)) {
                    // no longer bother trying to build the project and do not
                    // execute any post-build events
                    return BuildResult.Failed;
                }

                // unregister types exposed to COM, and unregister type
                // library (if it exists)
                UnregisterForComInterop(cs, solutionConfiguration);

                // ensure temp directory exists
                if (!Directory.Exists(TemporaryFiles.BasePath)) {
                    Directory.CreateDirectory(TemporaryFiles.BasePath);
                }

                // compile neutral and localized resx files
                CompileResXFiles(solutionConfiguration);

                // check if project output needs to be rebuilt
                if (CheckUpToDate(solutionConfiguration)) {
                    Log(Level.Verbose, "Project is up-to-date.");

                    // project output is up-to-date
                    outputUpdated = false;
                } else {
                    // prepare the project for build
                    Prepare(solutionConfiguration);

                    // check if project does not contain any sources
                    if (_sourceFiles.Count == 0) {
                        // create temp file
                        tempFile = Path.GetTempFileName();

                        // add temp file to collection of sources to compile
                        // as command line compilers require a least one source
                        // file to be specified, but VS.NET supports empty
                        // projects
                        _sourceFiles[tempFile] = null;
                    }

                    string tempResponseFile = FileUtils.CombinePaths(TemporaryFiles.BasePath,
                        CommandFile);

                    using (StreamWriter sw = File.CreateText(tempResponseFile)) {
                        // write compiler options
                        WriteCompilerOptions(sw, solutionConfiguration);
                    }

                    Log(Level.Verbose, "Starting compiler...");

                    if (SolutionTask.Verbose) {
                        using (StreamReader sr = new StreamReader(tempResponseFile)) {
                            Log(Level.Verbose, "Commands:");

                            // increment indentation level
                            SolutionTask.Project.Indent();
                            try {
                                while (true) {
                                    // read line
                                    string line = sr.ReadLine();
                                    if (line == null) {
                                        break;
                                    }
                                    // display line
                                    Log(Level.Verbose, "    "  + line);
                                }
                            } finally {
                                // restore indentation level
                                SolutionTask.Project.Unindent();
                            }
                        }
                    }

                    ProcessStartInfo psi = GetProcessStartInfo(cs, tempResponseFile);
                    psi.UseShellExecute = false;
                    psi.RedirectStandardOutput = true;

                    // start compiler
                    Process p = Process.Start(psi);

                    while (true) {
                        // read line
                        string line = p.StandardOutput.ReadLine();
                        if (line == null) {
                            break;
                        }
                        // display line
                        Log(Level.Info, line);
                    }

                    p.WaitForExit();

                    int exitCode = p.ExitCode;
                    Log(Level.Verbose, "{0}! (exit code = {1})", (exitCode == 0) ? "Success" : "Failure", exitCode);

                    if (exitCode > 0) {
                        bSuccess = false;
                    }

                    // project output has been updated
                    outputUpdated = true;
                }

                #region Process culture-specific resource files

                Log(Level.Verbose, "Building satellite assemblies...");

                Hashtable resourceSets = GetLocalizedResources();
                foreach (LocalizedResourceSet localizedResourceSet in resourceSets.Values) {
                    AssemblyLinkerTask al = new AssemblyLinkerTask();
                    al.Project = SolutionTask.Project;
                    al.NamespaceManager = SolutionTask.NamespaceManager;
                    al.Parent = SolutionTask;
                    al.BaseDirectory = cs.OutputDir;
                    al.InitializeTaskConfiguration();

                    DirectoryInfo satelliteBuildDir = localizedResourceSet.
                        GetBuildDirectory(cs);

                    // ensure satellite build directory exists
                    if (!satelliteBuildDir.Exists) {
                        satelliteBuildDir.Create();
                    }

                    al.OutputFile = localizedResourceSet.GetSatelliteAssemblyPath(
                        cs, ProjectSettings);
                    al.OutputTarget = "lib";
                    al.Culture = localizedResourceSet.Culture.Name;
                    al.TemplateFile = new FileInfo(cs.BuildPath);
                    foreach (Resource resource in localizedResourceSet.Resources) {
                        FileInfo compiledResourceFile = null;

                        if (resource.IsResX) {
                            // localized resx files have already been compiled
                            compiledResourceFile = resource.GetCompiledResourceFile(
                                solutionConfiguration);
                        } else {
                            // compile resource
                            compiledResourceFile = resource.Compile(solutionConfiguration);
                        }

                        // add resources to embed
                        EmbeddedResource embeddedResource = new EmbeddedResource(
                            compiledResourceFile.FullName, resource.GetManifestResourceName(solutionConfiguration));
                        al.EmbeddedResources.Add(embeddedResource);
                    }

                    // increment indentation level
                    SolutionTask.Project.Indent();
                    try {
                        Log(Level.Verbose, " - {0}", al.Culture);
                        // run assembly linker
                        al.Execute();
                    } finally {
                        // restore indentation level
                        SolutionTask.Project.Unindent();
                    }
                }

                #endregion Process culture-specific resource files

                #region Register project output for COM Interop

                // check if we need to build type library
                if (cs.RegisterForComInterop) {
                    // create type library in output dir, and register it using
                    // that path to match VS.NET
                    string typeLibPath = GetTypeLibraryPath(cs);
                    RegisterForComInterop(cs, solutionConfiguration, typeLibPath);

                    // copy generated type library to object directory to match
                    // VS.NET
                    string objTypeLibPath = Path.ChangeExtension(cs.BuildPath, ".tlb");
                    CopyFile(new FileInfo(typeLibPath), new FileInfo (objTypeLibPath),
                        SolutionTask);
                }

                #endregion Register project output for COM Interop

                #region Deploy project and configuration level output files

                // copy primary project output (and related files)
                Hashtable outputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable();
                GetOutputFiles(solutionConfiguration, outputFiles);

                foreach (DictionaryEntry de in outputFiles) {
                    string srcPath = (string) de.Key;
                    string relativePath = (string) de.Value;

                    if (IsWebProject) {
                        WebDavClient wdc = new WebDavClient(new Uri(_webProjectBaseUrl));
                        wdc.UploadFile(srcPath, FileUtils.CombinePaths(cs.RelativeOutputDir,
                            relativePath).Replace(@"\", "/"));
                    } else {
                        // determine destination file
                        FileInfo destFile = new FileInfo(FileUtils.CombinePaths(cs.OutputDir.FullName,
                            relativePath));
                        // copy file using <copy> task
                        CopyFile(new FileInfo(srcPath), destFile, SolutionTask);
                    }
                }

                #endregion Deploy project and configuration level output files

                if (ProjectSettings.RunPostBuildEvent != null) {
                    if (!PostBuild(cs, !outputUpdated || bSuccess, outputUpdated)) {
                        bSuccess = false;
                    }
                }

                if (!bSuccess) {
                    Log(Level.Error, "Build failed.");
                    return BuildResult.Failed;
                }

                return outputUpdated ? BuildResult.SuccessOutputUpdated : BuildResult.Success;
            } finally {
                // check if temporary file was created to support empty projects
                if (tempFile != null) {
                    // ensure temp file is deleted
                    File.Delete(tempFile);
                }
            }
        }
Пример #19
0
 internal ConfigurationMapEntry(Configuration key, Configuration value) {
     _key = key;
     _value = value;
 }
Пример #20
0
        /// <summary>
        /// Prepares the project for being built.
        /// </summary>
        /// <param name="solutionConfiguration">The solution configuration that is built.</param>
        /// <remarks>
        /// Ensures the configuration-level object directory exists and ensures 
        /// that none of the output files are marked read-only.
        /// </remarks>
        protected override void Prepare(Configuration solutionConfiguration)
        {
            // obtain project configuration (corresponding with solution configuration)
            ConfigurationBase config = BuildConfigurations[solutionConfiguration];

            // ensure configuration-level object directory exists
            if (!config.ObjectDir.Exists) {
                config.ObjectDir.Create();
                config.ObjectDir.Refresh();
            }

            // ensure that none of the output files in the configuration-level
            // object directory are marked read-only
            base.Prepare(solutionConfiguration);
        }
Пример #21
0
 public bool Contains(Configuration key) {
     return _innerHash.Contains(key);
 }
Пример #22
0
        /// <summary>
        /// Writes the compiler options.
        /// </summary>
        /// <param name="sw">The sw.</param>
        /// <param name="solutionConfiguration">The solution configuration.</param>
        protected virtual void WriteCompilerOptions(StreamWriter sw, Configuration solutionConfiguration)
        {
            // obtain project configuration (corresponding with solution configuration)
            ConfigurationSettings config = (ConfigurationSettings) BuildConfigurations[solutionConfiguration];

            // write project level options (eg. /target)
            foreach (string setting in ProjectSettings.Settings) {
                sw.WriteLine(setting);
            }

            // write configuration-level compiler options
            foreach (string setting in config.Settings) {
                sw.WriteLine(setting);
            }

            // write assembly references to response file
            foreach (string assemblyReference in GetAssemblyReferences(solutionConfiguration)) {
                sw.WriteLine("/r:\"{0}\"", assemblyReference);
            }

            if (ProjectSettings.ApplicationIcon != null) {
                sw.WriteLine(@"/win32icon:""{0}""",
                    ProjectSettings.ApplicationIcon.FullName);
            }

            if (_neutralResources.Count > 0) {
                WriteNeutralResourceOptions(sw, solutionConfiguration);
            }

            // before writing files to response file, allow project specific
            // options to be written (eg. VB specific options)
            WriteProjectOptions(sw);

            // add the files to compile
            foreach (string file in _sourceFiles.Keys) {
                sw.WriteLine(@"""" + file + @"""");
            }
        }
Пример #23
0
 /// <summary>
 /// Gets the complete set of assemblies that need to be referenced when
 /// a project references this component.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// The complete set of assemblies that need to be referenced when a 
 /// project references this component.
 /// </returns>
 public abstract StringCollection GetAssemblyReferences(Configuration solutionConfiguration);
Пример #24
0
        private bool CheckUpToDate(Configuration solutionConfiguration)
        {
            DateTime dtOutputTimeStamp;

            // obtain project configuration (corresponding with solution configuration)
            ConfigurationSettings cs = (ConfigurationSettings) BuildConfigurations[solutionConfiguration];

            // check if project build output exists
            if (File.Exists(cs.BuildPath)) {
                dtOutputTimeStamp = File.GetLastWriteTime(cs.BuildPath);
            } else {
                return false;
            }

            // check if project file was updated after the output file was
            // built
            string fileName = FileSet.FindMoreRecentLastWriteTime(ProjectPath,
                dtOutputTimeStamp);
            if (fileName != null) {
                Log(Level.Debug, "Project file \"0\" has been updated, recompiling.",
                    fileName);
                return false;
            }

            // check all of the input files
            foreach (string file in _sourceFiles.Keys) {
                if (dtOutputTimeStamp < File.GetLastWriteTime(file)) {
                    return false;
                }
            }

            // check all culture-neutral resources
            foreach (Resource resource in _neutralResources) {
                // check if input file was updated since last compile
                if (dtOutputTimeStamp < resource.InputFile.LastWriteTime) {
                    return false;
                }

                // check if compiled resource file exists
                FileInfo compiledResourceFile = resource.GetCompiledResourceFile(solutionConfiguration);
                if (!compiledResourceFile.Exists) {
                    return false;
                }

                // check if compiled resource file is up-to-date
                if (dtOutputTimeStamp < compiledResourceFile.LastWriteTime) {
                    return false;
                }
            }

            // check all of the input references
            foreach (ReferenceBase reference in _references) {
                if (dtOutputTimeStamp < reference.GetTimestamp(solutionConfiguration)) {
                    return false;
                }
            }

            // check extra output files
            foreach (DictionaryEntry de in cs.ExtraOutputFiles) {
                string extraOutputFile = (string) de.Key;

                // check if extra output file exists
                if (!File.Exists(extraOutputFile)) {
                    return false;
                }
            }

            return true;
        }
Пример #25
0
 /// <summary>
 /// Gets the output path of the reference, without taking the "copy local"
 /// setting into consideration.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// The full output path of the reference.
 /// </returns>
 public abstract string GetPrimaryOutputFile(Configuration solutionConfiguration);
Пример #26
0
        private bool RunCustomBuildStep(Configuration solutionConfiguration, VcProjectConfiguration projectConfig)
        {
            // check if a custom build step is configured
            string commandLine = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool,
                "CommandLine");
            if (String.IsNullOrEmpty(commandLine)) {
                return true;
            }

            DateTime oldestOutputFile = DateTime.MinValue;

            string outputs = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool,
                "Outputs");
            if (!String.IsNullOrEmpty(outputs)) {
                foreach (string output in outputs.Split(';')) {
                    if (output.Length == 0) {
                        continue;
                    }

                    string outputFile = Path.Combine (ProjectDirectory.FullName,
                        output);
                    if (File.Exists(outputFile)) {
                        DateTime lastWriteTime = File.GetLastWriteTime(outputFile);
                        if (lastWriteTime < oldestOutputFile || oldestOutputFile == DateTime.MinValue) {
                            oldestOutputFile = lastWriteTime;
                        }
                    }
                }
            }

            bool runCustomBuildStep = false;

            // when at least one of the output files of the custom build step
            // does not exist or is older than the project output file, then
            // the custom build step must be executed
            string projectOutputFile = GetOutputPath(solutionConfiguration);
            if (projectOutputFile != null && File.Exists (projectOutputFile)) {
                DateTime lastWriteTime = File.GetLastWriteTime(projectOutputFile);
                if (lastWriteTime > oldestOutputFile) {
                    runCustomBuildStep = true;
                }
            }

            // if one of the additional dependencies was updated after the oldest
            // output file of the custom build step, then the custom build step
            // must also be executed
            if (!runCustomBuildStep) {
                string additionalDependencies = projectConfig.GetToolSetting(
                    VcConfigurationBase.CustomBuildTool, "AdditionalDependencies");
                if (!String.IsNullOrEmpty(additionalDependencies)) {
                    foreach (string dependency in additionalDependencies.Split(';')) {
                        if (dependency.Length == 0) {
                            continue;
                        }

                        string dependencyFile = Path.Combine (ProjectDirectory.FullName,
                            dependency);
                        if (File.Exists (dependencyFile)) {
                            DateTime lastWriteTime  = File.GetLastWriteTime(dependencyFile);
                            if (lastWriteTime > oldestOutputFile) {
                                runCustomBuildStep = true;
                                break;
                            }
                        }
                    }
                }
            }

            if (!runCustomBuildStep) {
                return true;
            }

            string description = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool,
                "Description", "Performing Custom Build Step");
            Log(Level.Info, description);
            return ExecuteBuildEvent("Custom-Build", commandLine, projectConfig);
        }
Пример #27
0
 /// <summary>
 /// Gets a value indicating whether the reference is managed for the
 /// specified configuration.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// <see langword="true" /> if the reference is managed for the
 /// specified configuration; otherwise, <see langword="false" />.
 /// </returns>
 public abstract bool IsManaged(Configuration solutionConfiguration);
Пример #28
0
        private void RunLinker(Configuration solutionConfiguration)
        {
            const string noinherit = "$(noinherit)";

            // obtain project configuration (corresponding with solution configuration)
            VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration];

            // check if linking needs to be performed
            if (projectConfig.ObjFiles.Count == 0) {
                Log(Level.Debug, "No files to link.");
                return;
            }

            // create instance of Link task
            LinkTask linkTask = new LinkTask();

            // inherit project from solution task
            linkTask.Project = SolutionTask.Project;

            // inherit namespace manager from solution task
            linkTask.NamespaceManager = SolutionTask.NamespaceManager;

            // parent is solution task
            linkTask.Parent = SolutionTask;

            // inherit verbose setting from solution task
            linkTask.Verbose = SolutionTask.Verbose;

            // make sure framework specific information is set
            linkTask.InitializeTaskConfiguration();

            // set parent of child elements
            linkTask.Sources.Parent = linkTask;
            linkTask.LibDirs.Parent = linkTask;
            linkTask.Modules.Parent = linkTask;
            linkTask.EmbeddedResources.Project = linkTask.Project;

            // inherit project from solution task for child elements
            linkTask.Sources.Project = linkTask.Project;
            linkTask.LibDirs.Project = linkTask.Project;
            linkTask.Modules.Project = linkTask.Project;
            linkTask.EmbeddedResources.Project = linkTask.Project;

            // inherit namespace manager from parent
            linkTask.Sources.NamespaceManager = linkTask.NamespaceManager;
            linkTask.LibDirs.NamespaceManager = linkTask.NamespaceManager;
            linkTask.Modules.NamespaceManager = linkTask.NamespaceManager;
            linkTask.EmbeddedResources.NamespaceManager = linkTask.NamespaceManager;

            // set base directory of filesets
            linkTask.Sources.BaseDirectory = ProjectDirectory;
            linkTask.LibDirs.BaseDirectory = ProjectDirectory;
            linkTask.Modules.BaseDirectory = ProjectDirectory;
            linkTask.EmbeddedResources.BaseDirectory = ProjectDirectory;

            string addDeps = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalDependencies");
            if (!String.IsNullOrEmpty(addDeps)) {
                // only include default libraries if noinherit is not set
                if (addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit) == -1) {
                    foreach (string defaultLib in _defaultLibraries) {
                        linkTask.Sources.FileNames.Add(defaultLib);
                    }
                } else {
                    addDeps = addDeps.Remove(addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit), noinherit.Length);
                }
                foreach (string addDep in addDeps.Split(' ')) {
                    if (Path.GetExtension(addDep) == ".obj") {
                        // skip obj files are these are handled in
                        // VcProjectConfiguration
                        continue;
                    }
                    linkTask.Sources.FileNames.Add(addDep);
                }
            } else {
                // always include default libraries if no additional dependencies
                // are specified
                foreach (string defaultLib in _defaultLibraries) {
                    linkTask.Sources.FileNames.Add(defaultLib);
                }
            }

            string delayLoadedDlls = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "DelayLoadDLLs");
            if (!String.IsNullOrEmpty(delayLoadedDlls)) {
                foreach (string dll in delayLoadedDlls.Split(';')) {
                    linkTask.DelayLoadedDlls.FileNames.Add(dll);
                }
            }

            foreach (string objFile in projectConfig.ObjFiles) {
                linkTask.Sources.FileNames.Add(objFile);
            }

            // add output generated by referenced projects and explicit project
            // dependencies
            ProjectBaseCollection projectDependencies = GetVcProjectDependencies();
            foreach (VcProject vcProject in projectDependencies) {
                VcProjectConfiguration vcProjectConfig = vcProject.BuildConfigurations[
                    solutionConfiguration] as VcProjectConfiguration;

                switch (vcProjectConfig.Type) {
                    case VcProjectConfiguration.ConfigurationType.Application:
                    case VcProjectConfiguration.ConfigurationType.DynamicLibrary:
                        FileInfo dependencyImportLibrary = vcProjectConfig.LinkerConfiguration.ImportLibrary;
                        if (dependencyImportLibrary != null) {
                            linkTask.Sources.FileNames.Add(
                                dependencyImportLibrary.FullName);
                        }
                        break;
                    case VcProjectConfiguration.ConfigurationType.StaticLibrary:
                        linkTask.Sources.FileNames.Add(vcProjectConfig.OutputPath);
                        break;
                }
            }

            linkTask.OutputFile = new FileInfo(projectConfig.OutputPath);

            // ensure directory exists
            if (!linkTask.OutputFile.Directory.Exists) {
                linkTask.OutputFile.Directory.Create();
                linkTask.OutputFile.Directory.Refresh();
            }

            // generation of debug information
            linkTask.Debug = bool.Parse(projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "GenerateDebugInformation", "FALSE"));

            string pdbFile = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "ProgramDatabaseFile");
            // use default value if pdb was not explicitly disabled (by setting it to empty string)
            if (pdbFile == null && linkTask.Debug) {
                pdbFile = projectConfig.ExpandMacros("$(OutDir)/$(ProjectName).pdb");
            }
            if (!String.IsNullOrEmpty(pdbFile)) {
                if (OutputDir != null) {
                    pdbFile = FileUtils.CombinePaths(OutputDir.FullName, Path.GetFileName(pdbFile));
                } else {
                    pdbFile = FileUtils.CombinePaths(ProjectDirectory.FullName, pdbFile);
                }
                linkTask.ProgramDatabaseFile = new FileInfo(pdbFile);

                // ensure directory exists
                if (!linkTask.ProgramDatabaseFile.Directory.Exists) {
                    linkTask.ProgramDatabaseFile.Directory.Create();
                    linkTask.ProgramDatabaseFile.Directory.Refresh();
                }
            }

            // generation of import library
            FileInfo importLibrary = projectConfig.LinkerConfiguration.ImportLibrary;
            if (importLibrary != null) {
                Argument importLibraryArg = new Argument();
                importLibraryArg.Line = "/IMPLIB:" + LinkTask.QuoteArgumentValue(
                    importLibrary.FullName);
                linkTask.Arguments.Add(importLibraryArg);

                // ensure directory exists
                if (!importLibrary.Directory.Exists) {
                    importLibrary.Directory.Create();
                    importLibrary.Directory.Refresh();
                }
            }

            // Ignore Specific Libraries
            string ignoreDefaultLibraries = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool,
                "IgnoreDefaultLibraryNames");
            if (!String.IsNullOrEmpty(ignoreDefaultLibraries)) {
                foreach (string ignoreLibrary in ignoreDefaultLibraries.Split(';')) {
                    linkTask.IgnoreLibraries.Add(new Library(ignoreLibrary));
                }
            }

            // Forced Symbol References
            string symbolReferences = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool,
                "ForceSymbolReferences");
            if (!String.IsNullOrEmpty(symbolReferences)) {
                foreach (string symbol in symbolReferences.Split(';')) {
                    linkTask.Symbols.Add(new Symbol(symbol));
                }
            }

            // generation of map file during linking
            bool generateMapFile = bool.Parse(projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "GenerateMapFile", "FALSE"));
            if (generateMapFile) {
                Argument mapArg = new Argument();

                string mapFileName = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "MapFileName");
                if (!String.IsNullOrEmpty(mapFileName)) {
                    mapArg.Line = "/MAP:" + LinkTask.QuoteArgumentValue(mapFileName);;
                } else {
                    mapArg.Line = "/MAP";
                }

                linkTask.Arguments.Add(mapArg);
            }

            // total heap allocation size
            string heapReserveSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "HeapReserveSize");
            if (!String.IsNullOrEmpty(heapReserveSize)) {
                Argument heapArg = new Argument();

                string heapCommitSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "HeapCommitSize");
                if (!String.IsNullOrEmpty(heapCommitSize)) {
                    heapArg.Line = string.Format(CultureInfo.InvariantCulture,
                        "/HEAP:{0},{1}", heapReserveSize, heapCommitSize);
                } else {
                    heapArg.Line = "/HEAP:" + heapReserveSize;
                }

                linkTask.Arguments.Add(heapArg);
            }

            // total stack allocation size
            string stackReserveSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "StackReserveSize");
            if (!String.IsNullOrEmpty(stackReserveSize)) {
                Argument stackArg = new Argument();

                string stackCommitSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "StackCommitSize");
                if (!String.IsNullOrEmpty(stackCommitSize)) {
                    stackArg.Line = string.Format(CultureInfo.InvariantCulture,
                        "/STACK:{0},{1}", stackReserveSize, stackCommitSize);
                } else {
                    stackArg.Line = "/STACK:" + stackReserveSize;
                }

                linkTask.Arguments.Add(stackArg);
            }

            if (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary) {
                linkTask.Arguments.Add(new Argument("/DLL"));
            }

            string addLibDirs = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalLibraryDirectories");
            if (!String.IsNullOrEmpty(addLibDirs)) {
                foreach (string addLibDir in addLibDirs.Split(',', ';')) {
                    if (addLibDir.Length == 0) {
                        continue;
                    }
                    linkTask.LibDirs.DirectoryNames.Add(addLibDir);
                }
            }

            // links to modules
            string modules = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AddModuleNamesToAssembly");
            if (!String.IsNullOrEmpty(modules)) {
                foreach (string module in modules.Split(';')) {
                    linkTask.Modules.FileNames.Add(module);
                }
            }

            // embedded resources
            string embeddedResources = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "EmbedManagedResourceFile");
            if (!String.IsNullOrEmpty(embeddedResources)) {
                foreach (string embeddedResource in embeddedResources.Split(';')) {
                    linkTask.EmbeddedResources.FileNames.Add(embeddedResource);
                }
            }

            Hashtable linkerArgs = projectConfig.GetToolArguments(VcConfigurationBase.LinkerTool, _linkerArgMap);
            foreach (string arg in linkerArgs.Values) {
                Argument linkArg = new Argument();
                linkArg.Line = (string) arg;
                linkTask.Arguments.Add(linkArg);
            }

            string addOptions = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalOptions");
            if (!String.IsNullOrEmpty(addOptions)) {
                using (StringReader reader = new StringReader(addOptions)) {
                    string addOptionsLine = reader.ReadLine();
                    while (addOptionsLine != null) {
                        foreach (string addOption in addOptionsLine.Split(' ')) {
                            linkTask.Arguments.Add(new Argument(addOption));
                        }
                        addOptionsLine = reader.ReadLine();
                    }
                }
            }

            if (projectConfig.WholeProgramOptimization) {
                linkTask.Arguments.Add(new Argument("/LTCG"));
            }

            // execute the task
            ExecuteInProjectDirectory(linkTask);
        }
Пример #29
0
 /// <summary>
 /// Gets a value indicating whether the reference is managed for the
 /// specified configuration.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// <see langword="true" />.
 /// </returns>
 public override bool IsManaged(Configuration solutionConfiguration)
 {
     return true;
 }
Пример #30
0
 /// <summary>
 /// Gets a value indicating whether building the project for the specified
 /// build configuration results in managed output.
 /// </summary>
 /// <param name="solutionConfiguration">The solution configuration that is built.</param>
 /// <returns>
 /// <see langword="true" /> if the project output for the specified build
 /// configuration is either a Dynamic Library (dll) or an Application
 /// (exe), and Managed Extensions are enabled; otherwise, 
 /// <see langword="false" />.
 /// </returns>
 public override bool IsManaged(Configuration solutionConfiguration)
 {
     VcProjectConfiguration projectConfig = (VcProjectConfiguration)
         BuildConfigurations[solutionConfiguration];
     return (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary ||
         projectConfig.Type == VcProjectConfiguration.ConfigurationType.Application) &&
         projectConfig.ManagedExtensions;
 }