private string GetUserPropertyUnderCondition(string propertyName, string condition)
        {
            string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();

            if (Project.UserBuildProject != null)
            {
                if (conditionTrimmed.Length == 0)
                {
                    return(Project.UserBuildProject.GetProperty(propertyName).UnevaluatedValue);
                }

                // New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
                // So do it ourselves.
                ProjectPropertyGroupElement matchingGroup = null;

                foreach (ProjectPropertyGroupElement group in Project.UserBuildProject.Xml.PropertyGroups)
                {
                    if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
                    {
                        matchingGroup = group;
                        break;
                    }
                }

                if (matchingGroup != null)
                {
                    foreach (ProjectPropertyElement property in matchingGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
                    {
                        if (string.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) &&
                            (property.Condition == null || property.Condition.Length == 0))
                        {
                            return(property.Value);
                        }
                    }
                }
            }

            return(null);
        }
Exemple #2
0
        private static bool AddGlobalProperty(Microsoft.Build.Evaluation.Project project, String name, String value)
        {
            ProjectPropertyGroupElement globals = project.Xml.PropertyGroups.FirstOrDefault(p => p.Label.Equals("Globals"));

            if (globals == null)
            {
                globals       = project.Xml.AddPropertyGroup();
                globals.Label = "Globals";
                globals.Parent.RemoveChild(globals);
                project.Xml.InsertBeforeChild(globals, project.Xml.FirstChild);
            }

            ProjectPropertyElement property = globals.Properties.FirstOrDefault(p => p.Name.Equals(name));

            if (property == null)
            {
                property           = globals.AddProperty(name, value);
                property.Condition = String.Format("!Exists('$({0})')", name);
                return(true);
            }
            return(false);
        }
        public void MigratingScriptsReplacesRazorPrecompileWithProperty()
        {
            var scriptMigrationRule = new MigrateScriptsRule();
            ProjectRootElement          mockProj            = ProjectRootElement.Create();
            ProjectPropertyGroupElement commonPropertyGroup = mockProj.AddPropertyGroup();

            var commands = new string[] { "dotnet razor-precompile --configuration %publish:Configuration% --framework %publish:TargetFramework% --output-path %publish:OutputPath% %publish:ProjectPath%" };

            var target = scriptMigrationRule.MigrateScriptSet(
                mockProj,
                commonPropertyGroup,
                commands,
                "postpublish",
                IsMultiTFM);

            target.Tasks.Should().BeEmpty();
            commonPropertyGroup.Properties.Count().Should().Be(1);
            var propertyElement = commonPropertyGroup.Properties.First();

            propertyElement.Name.Should().Be("MvcRazorCompileOnPublish");
            propertyElement.Value.Should().Be("true");
        }
        public static void SetProperty(Microsoft.Build.Evaluation.Project project, string label, string name, string value)
        {
            ProjectPropertyGroupElement group = project.Xml.PropertyGroups.FirstOrDefault(
                g => g.Label.Equals(label, StringComparison.CurrentCultureIgnoreCase));

            if (group == null)
            {
                //
                // Create our property group after the main language targets are imported so we can use the properties
                // defined in this files.
                //
                ProjectImportElement import = project.Xml.Imports.FirstOrDefault(
                    p => (p.Project.IndexOf("Microsoft.Cpp.targets", StringComparison.CurrentCultureIgnoreCase) != -1 ||
                          p.Project.Equals(IceBuilderCSharpProps, StringComparison.CurrentCultureIgnoreCase)));
                if (import != null)
                {
                    group = project.Xml.CreatePropertyGroupElement();
                    project.Xml.InsertAfterChild(group, import);
                }
                else
                {
                    group = project.Xml.CreatePropertyGroupElement();
                }
                group.Label = label;
            }

            ProjectPropertyElement property = group.Properties.FirstOrDefault(
                p => p.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));

            if (property != null)
            {
                property.Value = value;
            }
            else
            {
                group.AddProperty(name, value);
            }
        }
Exemple #5
0
        private string AddScriptExtension(ProjectPropertyGroupElement propertyGroup, string scriptCommandline, string scriptId)
        {
            var scriptArguments = CommandGrammar.Process(
                scriptCommandline,
                (s) => null,
                preserveSurroundingQuotes: false);

            scriptArguments = scriptArguments.Where(argument => !string.IsNullOrEmpty(argument)).ToArray();
            var scriptCommand = scriptArguments.First();
            var propertyName  = $"MigratedScriptExtension_{scriptId}";

            var windowsScriptExtensionProperty = propertyGroup.AddProperty(propertyName,
                                                                           s_windowsScriptExtension);
            var unixScriptExtensionProperty = propertyGroup.AddProperty(propertyName,
                                                                        s_unixScriptExtension);

            windowsScriptExtensionProperty.Condition =
                $" '$(OS)' == 'Windows_NT' and Exists('{scriptCommand}{s_windowsScriptExtension}') ";
            unixScriptExtensionProperty.Condition =
                $" '$(OS)' != 'Windows_NT' and Exists('{scriptCommand}{s_unixScriptExtension}') ";

            return(propertyName);
        }
        private static bool AddGlobalProperty(Microsoft.Build.Evaluation.Project project, string name, string value)
        {
            ProjectPropertyGroupElement globals = project.Xml.PropertyGroups.FirstOrDefault(
                p => p.Label.Equals("Globals", StringComparison.CurrentCultureIgnoreCase));

            if (globals == null)
            {
                globals       = project.Xml.AddPropertyGroup();
                globals.Label = "Globals";
                globals.Parent.RemoveChild(globals);
                project.Xml.InsertBeforeChild(globals, project.Xml.FirstChild);
            }

            ProjectPropertyElement property = globals.Properties.FirstOrDefault(
                p => p.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));

            if (property == null)
            {
                property = globals.AddProperty(name, value);
                return(true);
            }
            return(false);
        }
        private static void AddProperties(string projectName, ProjectRootElement root)
        {
            ProjectPropertyGroupElement group = root.AddPropertyGroup();

            group.AddProperty("Configuration", "Debug");
            group.AddProperty("Platform", "AnyCPU");
            group.AddProperty("ProjectGuid", Guid.NewGuid().ToString());
            group.AddProperty("OutputType", "Library");
            group.AddProperty("AppDesignerFolder", "Properties");
            group.AddProperty("RootNamespace", projectName);
            group.AddProperty("AssemblyName", projectName);
            group.AddProperty("TargetFrameworkVersion", "4.5.2");

            ProjectPropertyGroupElement conditionedGroup = root.AddPropertyGroup();

            conditionedGroup.AddProperty("DebugSymbols", "true");
            conditionedGroup.AddProperty("DebugType", "full");
            conditionedGroup.AddProperty("Optimize", "false");
            conditionedGroup.AddProperty("OutputPath", "bin\\Debug\\");
            conditionedGroup.AddProperty("DefineConstants", "DEBUG;TRACE");
            conditionedGroup.AddProperty("ErrorReport", "prompt");
            conditionedGroup.AddProperty("WarningLevel", "4");
            conditionedGroup.Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ";
        }
Exemple #8
0
        //
        // Set Ice Home and force projects to re evaluate changes in the imported project
        //
        public static void SetIceHome(List <IVsProject> projects, String iceHome, String iceVersion, String iceIntVersion, String iceVersionMM)
        {
            foreach (IVsProject p in projects)
            {
                if (DTEUtil.IsIceBuilderEnabled(p) != IceBuilderProjectType.None)
                {
                    Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(ProjectUtil.GetProjectFullPath(p), DTEUtil.IsCppProject(p), true);
                    ResolvedImport import = project.Imports.FirstOrDefault(i => i.ImportedProject.FullPath.EndsWith("IceBuilder.Common.props"));

                    if (import.ImportedProject != null)
                    {
                        ProjectPropertyGroupElement group = import.ImportedProject.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceHome"));
                        if (group != null)
                        {
                            group.SetProperty(Package.IceHomeValue, iceHome);
                            group.SetProperty(Package.IceVersionValue, iceVersion);
                            group.SetProperty(Package.IceIntVersionValue, iceIntVersion);
                            group.SetProperty(Package.IceVersionMMValue, iceVersionMM);
                            project.ReevaluateIfNecessary();
                        }
                    }
                }
            }
        }
Exemple #9
0
        private void PerformConfigurationPropertyAndItemMappings(
            CommonCompilerOptions compilerOptions,
            CommonCompilerOptions configurationCompilerOptions,
            ProjectPropertyGroupElement propertyGroup,
            ProjectItemGroupElement itemGroup,
            ITransformApplicator transformApplicator,
            string projectDirectory,
            ProjectType projectType,
            ProjectRootElement csproj)
        {
            foreach (var transform in _propertyTransforms)
            {
                var nonConfigurationOutput = transform.Transform(compilerOptions);
                var configurationOutput    = transform.Transform(configurationCompilerOptions);

                if (!PropertiesAreEqual(nonConfigurationOutput, configurationOutput))
                {
                    transformApplicator.Execute(configurationOutput, propertyGroup, mergeExisting: true);
                }
            }

            foreach (var includeContextTransformExecute in _includeContextTransformExecutes)
            {
                var nonConfigurationOutput =
                    includeContextTransformExecute(compilerOptions, projectDirectory, projectType);
                var configurationOutput =
                    includeContextTransformExecute(configurationCompilerOptions, projectDirectory, projectType);

                configurationOutput = RemoveDefaultCompileAndEmbeddedResourceForWebProjects(
                    configurationOutput,
                    projectType,
                    csproj);

                transformApplicator.Execute(configurationOutput, itemGroup, mergeExisting: true);
            }
        }
Exemple #10
0
        private void PerformConfigurationPropertyAndItemMappings(
            CommonCompilerOptions compilerOptions,
            CommonCompilerOptions configurationCompilerOptions,
            ProjectPropertyGroupElement propertyGroup,
            ProjectItemGroupElement itemGroup,
            ITransformApplicator transformApplicator,
            string projectDirectory)
        {
            foreach (var transform in _propertyTransforms)
            {
                var nonConfigurationOutput = transform.Transform(compilerOptions);
                var configurationOutput    = transform.Transform(configurationCompilerOptions);

                if (!PropertiesAreEqual(nonConfigurationOutput, configurationOutput))
                {
                    transformApplicator.Execute(configurationOutput, propertyGroup);
                }
            }

            foreach (var includeContextTransformExecute in _includeContextTransformExecutes)
            {
                var nonConfigurationOutput = includeContextTransformExecute(compilerOptions, projectDirectory);
                var configurationOutput    = includeContextTransformExecute(configurationCompilerOptions, projectDirectory).ToArray();

                if (configurationOutput != null && nonConfigurationOutput != null)
                {
                    // TODO: HACK: this is leaky, see top comments, the throw at least covers the scenario
                    ThrowIfConfigurationHasAdditionalExcludes(configurationOutput, nonConfigurationOutput);
                    RemoveCommonIncludes(configurationOutput, nonConfigurationOutput);
                    configurationOutput = configurationOutput.Where(i => i != null && !string.IsNullOrEmpty(i.Include)).ToArray();
                }

                // Don't merge with existing items when doing a configuration
                transformApplicator.Execute(configurationOutput, itemGroup, mergeExisting: false);
            }
        }
Exemple #11
0
        public static void AddProperty(this ProjectPropertyGroupElement element, string name, string value, string condition)
        {
            ProjectPropertyElement property = element.AddProperty(name, value);

            property.Condition = condition;
        }
Exemple #12
0
        public void MergeAndSave(string csprojFilename, string assemblyName, string targetFrameworkVersion, string additonalDefineConst, string[] references)
        {
            ProjectRootElement root = ProjectRootElement.Create();

            if (portable)
            {
                root.ToolsVersion   = "14.0";
                root.DefaultTargets = "Build";
                var import = root.AddImport(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
                import.Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')";
            }
            else
            {
                root.AddImport(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
            }
            ProjectPropertyGroupElement one1 = CreatePropertyGroup(root,
                                                                   targetFrameworkVersion,
                                                                   " '$(Configuration)' == '' ",
                                                                   " '$(Platform)' == '' ",
                                                                   "Debug", "AnyCPU", true, assemblyName);

            if (portable)
            {
                one1.AddProperty("MinimumVisualStudioVersion", "10.0");
                one1.AddProperty("ProjectTypeGuids", "{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}");
                one1.AddProperty("TargetFrameworkProfile", "Profile111");
            }

            ProjectPropertyGroupElement debugGroup = CreatePropertyGroupChoice(root,
                                                                               " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ",
                                                                               true,
                                                                               @"bin\Debug\", false, true, "full", "DEBUG; TRACE" + additonalDefineConst);
            ProjectPropertyGroupElement releaseGroup = CreatePropertyGroupChoice(root,
                                                                                 " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ",
                                                                                 true,
                                                                                 @"bin\Release\", true, false, "pdbonly", " TRACE" + additonalDefineConst);

            if (references.Length > 0)
            {
                AddItems(root, "Reference", references);
            }
            List <string> allList            = new List <string>();
            string        onlyProjPath       = Path.GetDirectoryName(csprojFilename) + "\\";
            int           onlyProjPathLength = onlyProjPath.Length;
            //TODO: review here
            //special for support .net20
            bool foundFirstExtensionAttributeFile = false;

            foreach (var toMergePro in subProjects)
            {
                var allAbsFiles = toMergePro.GetAllAbsoluteFilenames();
                foreach (var filename in allAbsFiles)
                {
                    string onlyFileName = Path.GetFileName(filename);
                    if (onlyFileName == "ExtensionAttribute.cs")
                    {
                        if (foundFirstExtensionAttributeFile)
                        {
                            continue;
                        }
                        else
                        {
                            foundFirstExtensionAttributeFile = true;
                        }
                    }
                    if (filename.StartsWith(onlyProjPath))
                    {
                        allList.Add(filename.Substring(onlyProjPathLength));
                    }
                    else
                    {
                        allList.Add(filename);
                    }
                }
            }
            // items to compile
            AddItems(root, "Compile", allList.ToArray());
            if (portable)
            {
                root.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets");
            }

            root.Save(csprojFilename);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="propertyGroup"></param>
 /// <returns></returns>
 protected abstract bool ParseProperyGroup(ProjectPropertyGroupElement propertyGroup);
Exemple #14
0
        protected override bool ParseProperyGroup(ProjectPropertyGroupElement propertyGroup)
        {
            if (propertyGroup == null || propertyGroup.Count == 0)
            {
                return(false);
            }
            Debug.Assert(!String.IsNullOrEmpty(this.AssemblyName));

            if (String.IsNullOrEmpty(this.AssemblyName))
            {
                return(false);
            }

            ProjectPropertyElement outputPathProperty        = null;
            ProjectPropertyElement constantsProperty         = null;
            ProjectPropertyElement documentationFileProperty = null;
            // Get the OutputPath property to determine the full path of the
            // the build output...
            ICollection <ProjectPropertyElement> properties = propertyGroup.Properties;

            foreach (ProjectPropertyElement property in properties)
            {
                if (String.Equals(property.Name, "OutputPath",
                                  StringComparison.OrdinalIgnoreCase))
                {
                    outputPathProperty = property;
                }
                else if (String.Equals(property.Name, "DocumentationFile",
                                       StringComparison.OrdinalIgnoreCase))
                {
                    documentationFileProperty = property;
                }
                else if (String.Equals(property.Name, "DefineConstants",
                                       StringComparison.OrdinalIgnoreCase))
                {
                    constantsProperty = property;
                }
            }

            string tempValue = null;

            if (constantsProperty != null)
            {
                tempValue = constantsProperty.Value;
                if (!String.IsNullOrEmpty(tempValue))
                {
                    // Script# only defines constants for C# projects...
                    if (tempValue.IndexOf("SCRIPTSHARP",
                                          StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        this.TargetFrameworkIdentifier = "ScriptSharp";
                    }
                    else if (tempValue.IndexOf("SILVERLIGHT",
                                               StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        this.TargetFrameworkIdentifier = "Silverlight";
                    }
                }
            }

            if (documentationFileProperty != null)
            {
                tempValue = documentationFileProperty.Value;
                if (!String.IsNullOrEmpty(tempValue))
                {
                    tempValue = this.EvaluateMacros(tempValue);

                    if (Path.IsPathRooted(tempValue))
                    {
                        this.CommentFile = Path.GetFullPath(tempValue);
                    }
                    else
                    {
                        this.CommentFile = Path.GetFullPath(Path.Combine(
                                                                this.ProjectDir, tempValue));
                    }
                }
            }

            if (outputPathProperty != null)
            {
                tempValue = outputPathProperty.Value;
                if (!String.IsNullOrEmpty(tempValue))
                {
                    tempValue = this.EvaluateMacros(tempValue);

                    if (Path.IsPathRooted(tempValue))
                    {
                        this.OutputPath = Path.GetFullPath(tempValue);
                    }
                    else
                    {
                        this.OutputPath = Path.GetFullPath(Path.Combine(
                                                               this.ProjectDir, tempValue));
                    }

                    switch (this.OutputType.ToLower())
                    {
                    case "library":
                    case "dynamiclibrary":
                        this.OutputFile = Path.GetFullPath(Path.Combine(
                                                               this.OutputPath, this.AssemblyName + ".dll"));
                        break;

                    case "exe":
                    case "application":
                        this.OutputFile = Path.GetFullPath(Path.Combine(
                                                               this.OutputPath, this.AssemblyName + ".exe"));
                        break;
                    }
                }

                // If the DocumentationFile property is not found for some reason,
                // we try looking for the comment in the same directory...
                if (documentationFileProperty == null ||
                    (String.IsNullOrEmpty(this.CommentFile) || !File.Exists(this.CommentFile)))
                {
                    if (File.Exists(this.OutputFile))
                    {
                        tempValue = Path.ChangeExtension(this.OutputFile, ".xml");
                        if (File.Exists(tempValue))
                        {
                            this.CommentFile = tempValue;
                        }
                    }
                }
            }

            //if (this.IsTarget)
            //{
            //    // It is an referenced project and is normally used as dependency.
            //    // For this, only the assembly file is required...
            //    return (!String.IsNullOrEmpty(this.OutputFile) && File.Exists(this.OutputFile));
            //}
            //else
            //{
            //    // It is an outer project, and must have both assembly and comment
            //    // to be valid...
            //    return ((!String.IsNullOrEmpty(this.OutputFile) && File.Exists(this.OutputFile))
            //        && (!String.IsNullOrEmpty(this.CommentFile) && File.Exists(this.CommentFile)));
            //}

            return(!String.IsNullOrEmpty(this.OutputFile) && File.Exists(this.OutputFile));
        }
        private static bool UpgadeCppConfiguration(Microsoft.Build.Evaluation.Project project, OldConfiguration cfg)
        {
            ProjectPropertyGroupElement propertyGroup = project.Xml.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceBuilder"));

            if (propertyGroup == null)
            {
                propertyGroup       = project.Xml.AddPropertyGroup();
                propertyGroup.Label = "IceBuilder";
            }

            if (!string.IsNullOrEmpty(cfg.OutputDir))
            {
                propertyGroup.AddProperty(PropertyNames.OutputDir, cfg.OutputDir);
            }

            if (!string.IsNullOrEmpty(cfg.HeaderExt))
            {
                propertyGroup.AddProperty(PropertyNames.HeaderExt, cfg.HeaderExt);
            }

            if (!string.IsNullOrEmpty(cfg.SourceExt))
            {
                propertyGroup.AddProperty(PropertyNames.SourceExt, cfg.SourceExt);
            }

            if (!string.IsNullOrEmpty(cfg.AdditionalOptions))
            {
                propertyGroup.AddProperty(PropertyNames.AdditionalOptions, cfg.AdditionalOptions);
            }

            if (!string.IsNullOrEmpty(cfg.IncludeDirectories))
            {
                propertyGroup.AddProperty(PropertyNames.IncludeDirectories,
                                          string.Format("{0};$({1})", cfg.IncludeDirectories, PropertyNames.IncludeDirectories));
            }

            if (cfg.Stream)
            {
                propertyGroup.AddProperty(PropertyNames.Stream, "True");
            }

            if (cfg.Checksum)
            {
                propertyGroup.AddProperty(PropertyNames.Checksum, "True");
            }

            if (cfg.Ice)
            {
                propertyGroup.AddProperty(PropertyNames.AllowIcePrefix, "True");
            }

            if (!string.IsNullOrEmpty(cfg.DLLExport))
            {
                propertyGroup.AddProperty(PropertyNames.DLLExport, cfg.DLLExport);
            }

            foreach (ProjectItemDefinitionGroupElement group in project.Xml.ItemDefinitionGroups)
            {
                //
                // Remove old property sheet from all configurations
                //
                IEnumerable <ProjectImportElement> imports = project.Xml.Imports.Where(
                    p => p.Project.Equals("$(ALLUSERSPROFILE)\\ZeroC\\Ice.props"));
                if (imports != null)
                {
                    foreach (ProjectImportElement import in imports)
                    {
                        import.Parent.RemoveChild(import);
                    }
                }
                //
                // WinRT SDK old property sheet
                //
                imports = project.Xml.Imports.Where(
                    p => p.Project.IndexOf("CommonConfiguration\\Neutral\\Ice.props") != -1);
                if (imports != null)
                {
                    foreach (ProjectImportElement import in imports)
                    {
                        import.Parent.RemoveChild(import);
                    }
                }

                foreach (ProjectItemDefinitionElement i in group.ItemDefinitions)
                {
                    if (i.ItemType.Equals("ClCompile"))
                    {
                        if (!string.IsNullOrEmpty(cfg.OutputDir))
                        {
                            ProjectMetadataElement metaData = i.Metadata.FirstOrDefault(
                                e => e.Name.Equals("AdditionalIncludeDirectories"));

                            if (metaData != null)
                            {
                                List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' }));
                                values.Remove(cfg.OutputDir);
                                metaData.Value = string.Join(";", values);

                                if (values.Count == 0 ||
                                    (values.Count == 1 && values[0].Equals("%(AdditionalIncludeDirectories)")))
                                {
                                    i.RemoveChild(metaData);
                                }
                                else
                                {
                                    if (!values.Contains("%(AdditionalIncludeDirectories)"))
                                    {
                                        values.Add("%(AdditionalIncludeDirectories)");
                                    }
                                    metaData.Value = string.Join(";", values);
                                }
                            }
                        }
                    }
                    else if (i.ItemType.Equals("Link"))
                    {
                        ProjectMetadataElement metaData = i.Metadata.FirstOrDefault(
                            e => e.Name.Equals("AdditionalDependencies"));

                        if (metaData != null)
                        {
                            List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' }));
                            foreach (string name in Package.CppLibNames)
                            {
                                values.Remove(string.Format("{0}.lib", name));
                                values.Remove(string.Format("{0}d.lib", name));
                            }

                            if (values.Count == 0 || (values.Count == 1 && values[0].Equals("%(AdditionalDependencies)")))
                            {
                                i.RemoveChild(metaData);
                            }
                            else
                            {
                                metaData.Value = string.Join(";", values);
                            }
                        }

                        metaData = i.Metadata.FirstOrDefault(e => e.Name.Equals("AdditionalLibraryDirectories"));
                        if (metaData != null)
                        {
                            if (metaData.Value.Equals("%(AdditionalLibraryDirectories)"))
                            {
                                i.RemoveChild(metaData);
                            }
                        }
                    }
                }
            }

            List <ProjectItem> sliceItems =
                project.GetItems("None").Where(item => Path.GetExtension(item.UnevaluatedInclude).Equals(".ice")).ToList();

            //
            // Default output directory has changed
            //
            if (string.IsNullOrEmpty(cfg.OutputDir))
            {
                foreach (string itemType in new string[] { "ClInclude", "ClCompile" })
                {
                    project.GetItems(itemType).Where(
                        item =>
                    {
                        return(sliceItems.FirstOrDefault(
                                   slice =>
                        {
                            return slice.UnevaluatedInclude.Equals(Path.ChangeExtension(item.UnevaluatedInclude, ".ice"));
                        }) != null);
                    })
                    .ToList()
                    .ForEach(item => project.RemoveItem(item));
                }
            }

            sliceItems.ForEach(item =>
            {
                project.RemoveItem(item);
                project.AddItem("IceBuilder", item.UnevaluatedInclude);
            });
            return(true);
        }
Exemple #16
0
        public static void AddDefaultProperty(this ProjectPropertyGroupElement element, string name, string value)
        {
            ProjectPropertyElement property = element.AddProperty(name, value);

            property.Condition = $"'$({name})' == ''";
        }
Exemple #17
0
        internal void Save(bool cleanIntermediateFiles)
        {
            // clear out the nuspec files node.
            _nuSpec.files = null;
            var temporaryFiles = new List <string>();

            var files = _nuSpec.Add("files");

            // default xamlUi
            var xamlText = _defaultUIProperties;

            if (xamlText.Is())
            {
                var targetFilename = @"default-propertiesui.xml";
                var xamlPath       = Path.Combine(Directory, targetFilename);
                xamlPath.TryHardToDelete();
                File.WriteAllText(xamlPath, xamlText);
                temporaryFiles.Add(xamlPath);
                AddFileToNuSpec(xamlPath, @"\build\native\{0}".format(targetFilename));
                GetTargetsProject("native").Xml.AddItemGroup().AddItem("PropertyPageSchema", @"$(MSBuildThisFileDirectory)\{0}".format(targetFilename));
            }

            // generated xaml
            var xaml = GenerateSettingsXaml();

            if (xaml != null)
            {
                var targetFilename = @"{0}-propertiesui-{1}.xml".format(_pkgName, Guid.NewGuid());
                var xamlPath       = Path.Combine(Directory, targetFilename);
                xamlPath.TryHardToDelete();
                Event <Verbose> .Raise("NugetPackage.Save", "Saving xaml file [{0}].", xamlPath);

                xaml.Save(xamlPath);
                temporaryFiles.Add(xamlPath);
                AddFileToNuSpec(xamlPath, @"\build\native\{0}".format(targetFilename));
                GetTargetsProject("native").Xml.AddItemGroup().AddItem("PropertyPageSchema", @"$(MSBuildThisFileDirectory)\{0}".format(targetFilename));
            }

            foreach (var framework in _props.Keys)
            {
                var prj = _props[framework];
                if (prj.Xml.Children.Count > 0)
                {
                    prj.FullPath.TryHardToDelete();
                    if (prj.Save())
                    {
                        temporaryFiles.Add(prj.FullPath);
                        AddFileToNuSpec(prj.FullPath, @"\build\{0}\{1}".format(framework, prj.Filename));
                    }
                }
            }

            foreach (var framework in _targets.Keys)
            {
                var prj = _targets[framework];
                if (prj.Xml.Children.Count > 0)
                {
                    prj.FullPath.TryHardToDelete();
                    if (prj.Save())
                    {
                        temporaryFiles.Add(prj.FullPath);
                        AddFileToNuSpec(prj.FullPath, @"\build\{0}\{1}".format(framework, prj.Filename));
                    }
                }
            }

            // save the /build/configurations.autopkg file
            var configurationsFilename = @"configurations.autopkg";
            var cfgPath = Path.Combine(Directory, configurationsFilename);

            cfgPath.TryHardToDelete();
            SaveConfigurationFile(cfgPath);
            temporaryFiles.Add(cfgPath);
            AddFileToNuSpec(cfgPath, @"\build\{0}".format(configurationsFilename));

            var publisherInfoFilename = @"publisher-info.txt";
            var pifPath = Path.Combine(Directory, publisherInfoFilename);

            pifPath.TryHardToDelete();
            SavePifFile(pifPath);
            temporaryFiles.Add(pifPath);
            AddFileToNuSpec(pifPath, @"\build\{0}".format(publisherInfoFilename));

            Event <Verbose> .Raise("NugetPackage.Save", "Saving nuget spec file to [{0}].", FullPath);

            foreach (var src in _files.Keys)
            {
                AddFileToNuSpec(_files[src], src);
            }

            string tags = _nuSpec.metadata.tags;

            tags = tags.Replace(",", " ");

            if (tags.IndexOf("nativepackage") == -1)
            {
                tags = tags + " nativepackage";
            }

            _nuSpec.metadata.tags = tags;

            switch (PkgRole)
            {
            // do any last minute stuff here.

            case "default":
                // add a dependency to the redist package.
                var redistPkg = _packageScript.GetNugetPackage("redist");
                if (redistPkg != null && !redistPkg._files.Values.IsNullOrEmpty())
                {
                    // add the dependency to the list
                    var node = _nuSpec.metadata.dependencies.Add("dependency");
                    node.Attributes.id      = redistPkg._pkgName;
                    node.Attributes.version = (string)_nuSpec.metadata.version;
                    ;
                    var targets = GetTargetsProject("native");
                    targets.BeforeSave += () => {
                        ProjectPropertyGroupElement ppge = null;
                        foreach (var p in Pivots.Values)
                        {
                            if (!p.IsBuiltIn)
                            {
                                ppge = targets.AddPropertyInitializer("{0}-{1}".format(p.Name, redistPkg.SafeName), "", "$({0}-{1})".format(p.Name, SafeName), ppge);
                            }
                        }
                    };
                }
                break;
            }

            _nuSpec.Save(FullPath);
            temporaryFiles.Add(FullPath);

            if (PkgRole == "default" || !_files.Values.IsNullOrEmpty())
            {
                // don't save the package if it has no files in it.
                NuPack(FullPath);
            }

            if (cleanIntermediateFiles)
            {
                temporaryFiles.ForEach(FilesystemExtensions.TryHardToDelete);
            }
        }
Exemple #18
0
        public void MergeAndSave(string csprojFilename, string assemblyName, string targetFrameworkVersion, string additonalDefineConst, string[] references)
        {
            ProjectRootElement root = ProjectRootElement.Create();

            if (portable)
            {
                root.ToolsVersion   = "14.0";
                root.DefaultTargets = "Build";
                var import = root.AddImport(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
                import.Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')";
            }
            else
            {
                root.AddImport(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
            }
            ProjectPropertyGroupElement one1 = CreatePropertyGroup(root,
                                                                   targetFrameworkVersion,
                                                                   " '$(Configuration)' == '' ",
                                                                   " '$(Platform)' == '' ",
                                                                   "Debug", "AnyCPU", true, assemblyName);

            if (portable)
            {
                one1.AddProperty("MinimumVisualStudioVersion", "10.0");
                one1.AddProperty("ProjectTypeGuids", "{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}");
                one1.AddProperty("TargetFrameworkProfile", "Profile111");
            }


            string defineConstForDebug   = " DEBUG; TRACE";
            string defineConstForRelease = " TRACE";

            if (additonalDefineConst != null)
            {
                //for debug
                Dictionary <string, bool> values = SplitDefineConst(additonalDefineConst);
                if (!values.ContainsKey("DEBUG"))
                {
                    values["DEBUG"] = true;
                }
                defineConstForDebug = Concat(values, ";");

                values.Remove("DEBUG");

                defineConstForRelease = Concat(values, ";");
            }



            ProjectPropertyGroupElement debugGroup = CreatePropertyGroupChoice(root,
                                                                               " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ",
                                                                               true,
                                                                               @"bin\Debug\", false, true, "full", defineConstForDebug);


            ProjectPropertyGroupElement releaseGroup = CreatePropertyGroupChoice(root,
                                                                                 " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ",
                                                                                 true,
                                                                                 @"bin\Release\", true, false, "pdbonly", defineConstForRelease);

            if (references.Length > 0)
            {
                AddItems(root, "Reference", references);
            }
            List <string>             allList        = new List <string>();
            Dictionary <string, bool> uniqueFileList = new Dictionary <string, bool>();
            string onlyProjPath       = Path.GetDirectoryName(csprojFilename) + "\\";
            int    onlyProjPathLength = onlyProjPath.Length;
            //TODO: review here
            //special for support .net20
            bool foundFirstExtensionAttributeFile = false;

            foreach (ToMergeProject toMergePro in subProjects)
            {
                List <string> allAbsFiles = toMergePro.GetAllAbsoluteFilenames();
                foreach (string filename in allAbsFiles)
                {
                    string onlyFileName = Path.GetFileName(filename);

                    if (onlyFileName == "PORTING_NOTMERGE.cs")
                    {
                        //our convention***
                        continue;//skip
                    }
                    else if (onlyFileName == "ExtensionAttribute.cs")
                    {    //this is our convention
                         //... if we have ExtensionAttribute.cs
                         //the
                        if (foundFirstExtensionAttributeFile)
                        {
                            continue;
                        }
                        else
                        {
                            foundFirstExtensionAttributeFile = true;
                        }
                    }

                    string combindedFilename = SolutionMx.CombineRelativePath(filename).ToUpper();
                    if (uniqueFileList.ContainsKey(combindedFilename))
                    {
                        continue;
                    }
                    uniqueFileList[combindedFilename] = true;//
                    if (filename.StartsWith(onlyProjPath))
                    {
                        allList.Add(filename.Substring(onlyProjPathLength));
                    }
                    else
                    {
                        allList.Add(filename);
                    }
                }
            }
            // items to compile
            AddItems(root, "Compile", allList.ToArray());
            if (portable)
            {
                root.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets");
            }

            root.Save(csprojFilename);
        }
Exemple #19
0
        /// <summary>
        /// Sets the value of the property.
        /// </summary>
        /// <param name="value">Property value to set.</param>
        /// <param name="configs">Optional list of configurations to set the property in;
        /// defaults to the project current configuration</param>
        /// <remarks>
        /// Before calling this method, the caller must ensure that the value is valid according to
        /// the <see cref="PropertyValidator"/> class, and that the project file is writable.
        /// In most cases the caller should also ensure that the new value is different from the
        /// existing value, to avoid dirtying the project file unnecessarily.
        /// </remarks>
        public void SetValue(string value, IList <XProjectConfig> configs)
        {
            XHelperMethods.VerifyNonNullArgument(value, "value");
            var oldvalue = this.GetValue(false);

            value = value.Trim();

            MSBuild.Project buildProject = this.project.BuildProject;
            if (this.PerUser)
            {
                if (this.project.UserBuildProject == null)
                {
                    this.project.CreateUserBuildProject();
                }

                buildProject = this.project.UserBuildProject;
            }

            value = this.Escape(value);

            if (this.PerConfig)
            {
                if (configs == null || configs.Count == 0)
                {
                    configs = new XProjectConfig[] { (XProjectConfig)this.project.CurrentConfig };
                }

                foreach (XProjectConfig config in configs)
                {
                    bool set = false;

                    // First see if there's an existing property group that matches our condition
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        // if there is, set it within that group
                        if (string.Equals(propGroup.Condition.Trim(), config.Condition.Trim(), StringComparison.Ordinal))
                        {
                            // a property should only occur once in a group
                            // when there is more than one property with the same name then delete all but the first
                            // we filter on condition, because there could be 2
                            // same named properties with different conditions
                            var children = propGroup.Children.Where((prop) =>
                                                                    prop.ElementName == this.propertyName && string.IsNullOrEmpty(prop.Condition));

                            if (children.Count() > 1)
                            {
                                var first = children.First();
                                foreach (var child in children)
                                {
                                    if (child != first)
                                    {
                                        propGroup.RemoveChild(child);
                                    }
                                }
                            }
                            propGroup.SetProperty(this.propertyName, value);
                            set = true;
                            break;
                        }
                    }

                    // If not, add a new property group for the condition and set the property within it
                    if (!set)
                    {
                        ProjectPropertyGroupElement newPropGroup = buildProject.Xml.AddPropertyGroup();
                        newPropGroup.Condition = config.Condition;
                        newPropGroup.SetProperty(this.propertyName, value);
                        set = true;
                    }

                    buildProject.ReevaluateIfNecessary();
                }
            }
            else
            {
                if (this.EndOfProjectFile)
                {
                    List <ProjectPropertyGroupElement> propertyGroupsToDelete = new List <ProjectPropertyGroupElement>();
                    var groups = new List <ProjectPropertyGroupElement>();
                    // First see if there's an existing property group with our property
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        List <ProjectPropertyElement> propertiesToDelete = new List <ProjectPropertyElement>();
                        if (!string.IsNullOrEmpty(propGroup.Condition))
                        {
                            continue;
                        }
                        groups.Add(propGroup);
                        foreach (ProjectPropertyElement property in propGroup.Properties)
                        {
                            // if there is, remove it so the new value is at the end of the file
                            if (string.IsNullOrEmpty(property.Condition) && string.Equals(property.Name, this.propertyName, StringComparison.OrdinalIgnoreCase))
                            {
                                propertiesToDelete.Add(property);
                            }
                        }

                        foreach (ProjectPropertyElement property in propertiesToDelete)
                        {
                            propGroup.RemoveChild(property);
                        }
                        if (propGroup.Count == 0)
                        {
                            propertyGroupsToDelete.Add(propGroup);
                            groups.Remove(propGroup);
                        }
                    }

                    foreach (ProjectPropertyGroupElement propGroup in propertyGroupsToDelete)
                    {
                        buildProject.Xml.RemoveChild(propGroup);
                    }
                    ProjectPropertyGroupElement newPropGroup;
                    if (groups.Count > 1)
                    {
                        newPropGroup = groups[groups.Count - 1];
                    }
                    else
                    {
                        newPropGroup = buildProject.Xml.CreatePropertyGroupElement();
                        buildProject.Xml.AppendChild(newPropGroup);
                    }

                    newPropGroup.SetProperty(this.propertyName, value);
                }
                else
                {
                    buildProject.SetProperty(this.propertyName, value);
                }
            }

            this.project.SetProjectFileDirty(true);
            this.project.RaiseProjectPropertyChanged(this.propertyName, oldvalue, value);
        }
Exemple #20
0
        protected override void ProcessRecord()
        {
            try
            {
                if (Path != null)
                {
                    WriteObject((Collection == null) ? ProjectRootElement.Create(Path) : ProjectRootElement.Create(Path, Collection), false);
                }
                else if (Xml != null)
                {
                    WriteObject((Collection == null) ? ProjectRootElement.Create(ValidateXmlSourceAttribute.AsXmlReader(Xml)) : ProjectRootElement.Create(ValidateXmlSourceAttribute.AsXmlReader(Xml), Collection), false);
                }
                else
                {
                    ProjectRootElement project = (Collection == null) ? ProjectRootElement.Create() : ProjectRootElement.Create(Collection);
                    project.DefaultTargets = DefaultTargets;
                    project.AddImport("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props").Condition = "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')";
                    ProjectPropertyGroupElement propertyGroup = project.AddPropertyGroup();
                    propertyGroup.Condition = "";
                    propertyGroup.AddProperty("Configuration", Configuration).Condition = " $(Configuration)' == '' ";
                    propertyGroup.AddProperty("Platform", Platform).Condition           = " $(Configuration)' == '' ";
                    propertyGroup.AddProperty("ProjectGuid", ProjectGuid.ToString("B").ToUpper());
                    propertyGroup.AddProperty("OutputType", OutputType);
                    propertyGroup.AddProperty("RootNamespace", RootNamespace);
                    propertyGroup.AddProperty("AssemblyName", (String.IsNullOrWhiteSpace(AssemblyName)) ? RootNamespace : AssemblyName);
                    propertyGroup.AddProperty("TargetFrameworkVersion", ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetFrameworkVersion));
                    project.AddImport("$(MSBuildToolsPath)\\Microsoft.CSharp.targets");
                    WriteObject(project);
                    propertyGroup = project.AddPropertyGroup();
                    if (Configuration == "Debug" || Configuration == "Release")
                    {
                        propertyGroup.Condition = " '$(Configuration)|$(Platform)' == 'Debug|" + Platform + "' ";
                    }
                    else
                    {
                        propertyGroup.Condition = " '$(Configuration)|$(Platform)' == '" + Configuration + "|" + Platform + "' ";
                    }
                    propertyGroup.AddProperty("DebugSymbols", "true");
                    propertyGroup.AddProperty("DebugType", "full");
                    propertyGroup.AddProperty("Optimize", "false");
                    if (Configuration == "Debug" || Configuration == "Release")
                    {
                        propertyGroup.AddProperty("OutputPath", "bin\\" + Platform);
                    }
                    else
                    {
                        propertyGroup.AddProperty("OutputPath", "bin\\Debug");
                    }
                    propertyGroup.AddProperty("DefineConstants", "DEBUG;TRACE");
                    propertyGroup.AddProperty("ErrorReport", "prompt");
                    propertyGroup.AddProperty("WarningLevel", "4");

                    propertyGroup           = project.AddPropertyGroup();
                    propertyGroup.Condition = " '$(Configuration)|$(Platform)' == 'Release|" + Platform + "' ";
                    propertyGroup.AddProperty("DebugType", "pdbonly");
                    propertyGroup.AddProperty("Optimize", "true");
                    propertyGroup.AddProperty("OutputPath", "bin\\Release");
                    propertyGroup.AddProperty("DefineConstants", "TRACE");
                    propertyGroup.AddProperty("ErrorReport", "prompt");
                    propertyGroup.AddProperty("WarningLevel", "4");

                    ProjectItemGroupElement itemGroup = project.AddItemGroup();
                    itemGroup.AddItem("Reference", "System");
                    itemGroup.AddItem("Reference", "System.Core");
                    itemGroup.AddItem("Reference", "Microsoft.CSharp");
                    itemGroup.AddItem("Reference", "System.Xml");
                    Assembly assembly = (typeof(PSObject)).Assembly;
                    itemGroup.AddItem("Reference", assembly.FullName + ", processorArchitecture=MSIL",
                                      new KeyValuePair <string, string>[]
                    {
                        new KeyValuePair <string, string>("SpecificVersion", "false"),
                        new KeyValuePair <string, string>("HintPath", assembly.Location)
                    });
                    assembly = (typeof(Microsoft.PowerShell.Commands.OutStringCommand)).Assembly;
                    itemGroup.AddItem("Reference", assembly.FullName + ", processorArchitecture=MSIL",
                                      new KeyValuePair <string, string>[]
                    {
                        new KeyValuePair <string, string>("SpecificVersion", "false"),
                        new KeyValuePair <string, string>("HintPath", assembly.Location)
                    });
                    assembly = (typeof(Microsoft.PowerShell.Commands.GetItemCommand)).Assembly;
                    itemGroup.AddItem("Reference", assembly.FullName + ", processorArchitecture=MSIL",
                                      new KeyValuePair <string, string>[]
                    {
                        new KeyValuePair <string, string>("SpecificVersion", "false"),
                        new KeyValuePair <string, string>("HintPath", assembly.Location)
                    });
                    WriteObject(project);
                }
            }
            catch (Exception exception)
            {
                WriteError(new ErrorRecord(exception, "New_MSBuildProject", ErrorCategory.OpenError, null));
            }
        }
 /// <summary>
 /// Adds the ImportWindowsDesktopTargets=true property to ensure builds targeting .NET Framework will succeed.
 /// </summary>
 /// <param name="propGroup"></param>
 public static void AddImportWindowsDesktopTargets(ProjectPropertyGroupElement propGroup) => propGroup.AddProperty(DesktopFacts.ImportWindowsDesktopTargetsName, "true");
Exemple #22
0
 /// <summary>
 /// Adds the UseWPF=true property to the top-level project property group.
 /// </summary>
 public static void AddUseWPF(ProjectPropertyGroupElement propGroup) => propGroup.AddProperty(DesktopFacts.UseWPFPropertyName, "true");
Exemple #23
0
 public static bool HasWPFOrWinForms(ProjectPropertyGroupElement propGroup)
 {
     return(propGroup.Properties.Any(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, DesktopFacts.UseWPFPropertyName) == 0) ||
            propGroup.Properties.Any(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, DesktopFacts.UseWinFormsPropertyName) == 0));
 }
Exemple #24
0
        public static TestExclusionMap Create(BuildOptions options)
        {
            TestExclusionMap outputMap = new TestExclusionMap();

            if (options.IssuesPath != null)
            {
                Dictionary <string, List <TestExclusion> > exclusionsByCondition = new Dictionary <string, List <TestExclusion> >();

                foreach (FileInfo issuesProject in options.IssuesPath)
                {
                    string    issuesProjectPath = issuesProject.FullName;
                    XDocument issuesXml         = XDocument.Load(issuesProjectPath);
                    foreach (XElement itemGroupElement in issuesXml.Root.Elements(s_xmlNamespace + "ItemGroup"))
                    {
                        string condition = itemGroupElement.Attribute("Condition")?.Value ?? "";
                        List <TestExclusion> exclusions;
                        if (!exclusionsByCondition.TryGetValue(condition, out exclusions))
                        {
                            exclusions = new List <TestExclusion>();
                            exclusionsByCondition.Add(condition, exclusions);
                        }
                        foreach (XElement excludeListElement in itemGroupElement.Elements(s_xmlNamespace + "ExcludeList"))
                        {
                            string testPath = excludeListElement.Attribute("Include")?.Value ?? "";
                            string issueID  = excludeListElement.Element(s_xmlNamespace + "Issue")?.Value ?? "N/A";
                            exclusions.Add(CreateTestExclusion(testPath, issueID));
                        }
                    }
                }

                Project project = new Project();
                project.SetGlobalProperty("XunitTestBinBase", "*");
                project.SetGlobalProperty("BuildArch", "amd64");
                project.SetGlobalProperty("TargetsWindows", "true");
                project.SetGlobalProperty("AltJitArch", "amd64");
                project.SetGlobalProperty("RunTestViaIlLink", "false");

                ProjectRootElement root = project.Xml;
                root.AddTarget("GetListOfTestCmds");

                ProjectPropertyGroupElement propertyGroup = root.AddPropertyGroup();

                // Generate properties into the project to make it evaluate all conditions found in the targets file
                List <List <TestExclusion> > testExclusionLists = new List <List <TestExclusion> >();
                testExclusionLists.Capacity = exclusionsByCondition.Count;
                foreach (KeyValuePair <string, List <TestExclusion> > kvp in exclusionsByCondition)
                {
                    string propertyName = "Condition_" + testExclusionLists.Count.ToString();
                    bool   emptyKey     = string.IsNullOrEmpty(kvp.Key);
                    propertyGroup.AddProperty(propertyName, emptyKey ? "true" : "false");
                    if (!emptyKey)
                    {
                        propertyGroup.AddProperty(propertyName, "true").Condition = kvp.Key;
                    }
                    testExclusionLists.Add(kvp.Value);
                }

                project.Build();
                for (int exclusionListIndex = 0; exclusionListIndex < testExclusionLists.Count; exclusionListIndex++)
                {
                    string conditionValue = project.GetProperty("Condition_" + exclusionListIndex.ToString()).EvaluatedValue;
                    if (conditionValue.Equals("true", StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (TestExclusion exclusion in testExclusionLists[exclusionListIndex])
                        {
                            outputMap.Add(exclusion);
                        }
                    }
                }
            }

            return(outputMap);
        }
        private static bool UpgradeCSharpConfiguration(EnvDTE.Project dteProject,
                                                       Microsoft.Build.Evaluation.Project project, OldConfiguration cfg)
        {
            ProjectPropertyGroupElement propertyGroup = project.Xml.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceBuilder"));

            if (propertyGroup == null)
            {
                propertyGroup       = project.Xml.AddPropertyGroup();
                propertyGroup.Label = "IceBuilder";
            }

            if (!string.IsNullOrEmpty(cfg.OutputDir))
            {
                propertyGroup.AddProperty(PropertyNames.OutputDir, cfg.OutputDir);
            }

            if (!string.IsNullOrEmpty(cfg.AdditionalOptions))
            {
                propertyGroup.AddProperty(PropertyNames.AdditionalOptions, cfg.AdditionalOptions);
            }

            if (!string.IsNullOrEmpty(cfg.IncludeDirectories))
            {
                propertyGroup.AddProperty(PropertyNames.IncludeDirectories,
                                          string.Format(@"{0};$(IceHome)\slice", cfg.IncludeDirectories));
            }
            else
            {
                propertyGroup.AddProperty(PropertyNames.IncludeDirectories, @"$(IceHome)\slice");
            }

            if (cfg.Stream)
            {
                propertyGroup.AddProperty(PropertyNames.Stream, "True");
            }

            if (cfg.Checksum)
            {
                propertyGroup.AddProperty(PropertyNames.Checksum, "True");
            }

            if (cfg.Ice)
            {
                propertyGroup.AddProperty(PropertyNames.AllowIcePrefix, "True");
            }

            if (cfg.Tie)
            {
                propertyGroup.AddProperty(PropertyNames.Tie, "True");
            }

            foreach (string assembly in Package.AssemblyNames)
            {
                VSLangProj80.Reference3 reference = ProjectUtil.FindAssemblyReference(dteProject, assembly) as VSLangProj80.Reference3;
                if (reference != null)
                {
                    reference.SpecificVersion = false;
                }
            }

            List <ProjectItem> sliceItems =
                project.GetItems("None").Where(item => Path.GetExtension(item.UnevaluatedInclude).Equals(".ice")).ToList();

            //
            // Default output directory has changed
            //
            if (string.IsNullOrEmpty(cfg.OutputDir))
            {
                project.GetItems("Compile").Where(
                    item =>
                {
                    return(sliceItems.FirstOrDefault(
                               slice =>
                    {
                        return slice.UnevaluatedInclude.Equals(Path.ChangeExtension(item.UnevaluatedInclude, ".ice"));
                    }) != null);
                })
                .ToList()
                .ForEach(item => project.RemoveItem(item));
            }

            return(true);
        }
        /// <summary>
        /// Copies an existing configuration name or creates a new one.
        /// </summary>
        /// <param name="name">The name of the new configuration.</param>
        /// <param name="cloneName">the name of the configuration to copy, or a null reference, indicating that AddCfgsOfCfgName should create a new configuration.</param>
        /// <param name="fPrivate">Flag indicating whether or not the new configuration is private. If fPrivate is set to true, the configuration is private. If set to false, the configuration is public. This flag can be ignored.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
        public virtual int AddCfgsOfCfgName(string name, string cloneName, int fPrivate)
        {
            // We need to QE/QS the project file
            if (!this.ProjectMgr.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // Get all configs
            List <ProjectPropertyGroupElement> configGroup = new List <ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
            // platform -> property group
            var configToClone = new Dictionary <string, ProjectPropertyGroupElement>(StringComparer.Ordinal);


            if (cloneName != null)
            {
                // Find the configuration to clone
                foreach (var currentConfig in configGroup)
                {
                    // Only care about conditional property groups
                    if (currentConfig.Condition == null || currentConfig.Condition.Length == 0)
                    {
                        continue;
                    }
                    var configCanonicalName = ConfigCanonicalName.OfCondition(currentConfig.Condition);

                    // Skip if it isn't the group we want
                    if (String.Compare(configCanonicalName.ConfigName, cloneName, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        continue;
                    }

                    if (!configToClone.ContainsKey(configCanonicalName.Platform))
                    {
                        configToClone.Add(configCanonicalName.Platform, currentConfig);
                    }
                }
            }


            var platforms = GetPlatformsFromProject();

            if (platforms.Length == 0)
            {
                platforms = new[] { String.Empty }
            }
            ;

            foreach (var platform in platforms)
            {
                // If we have any property groups to clone, and we do not have sourec for this platform, skip
                if (configToClone.Count > 0 && !configToClone.ContainsKey(platform))
                {
                    continue;
                }
                var newCanonicalName = new ConfigCanonicalName(name, platform);

                ProjectPropertyGroupElement newConfig = null;
                if (configToClone.ContainsKey(platform))
                {
                    // Clone the configuration settings
                    newConfig = this.project.ClonePropertyGroup(configToClone[platform]);
                    //Will be added later with the new values to the path
                    foreach (ProjectPropertyElement property in newConfig.Properties)
                    {
                        if (property.Name.Equals("OutputPath", StringComparison.OrdinalIgnoreCase))
                        {
                            property.Parent.RemoveChild(property);
                        }
                    }
                }
                else
                {
                    // no source to clone from, lets just create a new empty config
                    PopulateEmptyConfig(ref newConfig);
                    if (!String.IsNullOrEmpty(newCanonicalName.MSBuildPlatform))
                    {
                        newConfig.AddProperty(ProjectFileConstants.PlatformTarget, newCanonicalName.PlatformTarget);
                    }
                }


                //add the output path
                this.AddOutputPath(newConfig, name);

                // Set the condition that will define the new configuration
                string newCondition = newCanonicalName.ToMSBuildCondition();
                newConfig.Condition = newCondition;
            }
            NotifyOnCfgNameAdded(name);
            return(VSConstants.S_OK);
        }
        public static ProjectRootElement CreateLibraryProject(string name, string defaultConfig, out ProjectPropertyGroupElement mainGroup)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException($"{nameof(name)} cannot be empty", nameof(name));
            }

            var root = ProjectRootElement.Create();

            root.DefaultTargets = "Build";

            mainGroup = root.AddPropertyGroup();
            mainGroup.AddProperty("Configuration", defaultConfig).Condition = " '$(Configuration)' == '' ";
            mainGroup.AddProperty("Platform", "AnyCPU").Condition           = " '$(Platform)' == '' ";
            mainGroup.AddProperty("ProjectGuid", "{" + Guid.NewGuid().ToString().ToUpper() + "}");
            mainGroup.AddProperty("OutputType", "Library");
            mainGroup.AddProperty("OutputPath", Path.Combine("bin", "$(Configuration)"));
            mainGroup.AddProperty("RootNamespace", IdentifierUtils.SanitizeQualifiedIdentifier(name, allowEmptyIdentifiers: true));
            mainGroup.AddProperty("AssemblyName", name);
            mainGroup.AddProperty("TargetFrameworkVersion", "v4.7");
            mainGroup.AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            var exportDebugGroup = root.AddPropertyGroup();

            exportDebugGroup.Condition = " '$(Configuration)|$(Platform)' == 'ExportDebug|AnyCPU' ";
            exportDebugGroup.AddProperty("DebugSymbols", "true");
            exportDebugGroup.AddProperty("DebugType", "portable");
            exportDebugGroup.AddProperty("Optimize", "false");
            exportDebugGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;DEBUG;");
            exportDebugGroup.AddProperty("ErrorReport", "prompt");
            exportDebugGroup.AddProperty("WarningLevel", "4");
            exportDebugGroup.AddProperty("ConsolePause", "false");

            var exportReleaseGroup = root.AddPropertyGroup();

            exportReleaseGroup.Condition = " '$(Configuration)|$(Platform)' == 'ExportRelease|AnyCPU' ";
            exportReleaseGroup.AddProperty("DebugType", "portable");
            exportReleaseGroup.AddProperty("Optimize", "true");
            exportReleaseGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;");
            exportReleaseGroup.AddProperty("ErrorReport", "prompt");
            exportReleaseGroup.AddProperty("WarningLevel", "4");
            exportReleaseGroup.AddProperty("ConsolePause", "false");

            // References
            var referenceGroup = root.AddItemGroup();

            referenceGroup.AddItem("Reference", "System");

            root.AddImport(Path.Combine("$(MSBuildBinPath)", "Microsoft.CSharp.targets").Replace("/", "\\"));

            return(root);
        }
        /// <summary>
        /// Copies an existing platform name or creates a new one.
        /// </summary>
        /// <param name="platformName">The name of the new platform.</param>
        /// <param name="clonePlatformName">The name of the platform to copy, or a null reference, indicating that AddCfgsOfPlatformName should create a new platform.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public virtual int AddCfgsOfPlatformName(string platformName, string clonePlatformName)
        {
            // We need to QE/QS the project file
            if (!this.ProjectMgr.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // Get all configs
            List <ProjectPropertyGroupElement> configGroup = new List <ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
            // configName -> property group
            var configToClone = new Dictionary <string, ProjectPropertyGroupElement>(StringComparer.Ordinal);


            if (clonePlatformName != null)
            {
                // Find the configuration to clone
                foreach (var currentConfig in configGroup)
                {
                    // Only care about conditional property groups
                    if (currentConfig.Condition == null || currentConfig.Condition.Length == 0)
                    {
                        continue;
                    }
                    var configCanonicalName = ConfigCanonicalName.OfCondition(currentConfig.Condition);

                    // Skip if it isn't the group we want
                    if (!configCanonicalName.MatchesPlatform(clonePlatformName))
                    {
                        continue;
                    }

                    if (!configToClone.ContainsKey(configCanonicalName.ConfigName))
                    {
                        configToClone.Add(configCanonicalName.ConfigName, currentConfig);
                    }
                }
            }


            var configNames = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);

            if (configNames.Length == 0)
            {
                return(VSConstants.E_FAIL);
            }

            foreach (var configName in configNames)
            {
                // If we have any property groups to clone, and we do not have sourec for this config, skip
                if (configToClone.Count > 0 && !configToClone.ContainsKey(configName))
                {
                    continue;
                }
                var newCanonicalName = new ConfigCanonicalName(configName, platformName);

                ProjectPropertyGroupElement newConfig = null;
                if (configToClone.ContainsKey(configName))
                {
                    // Clone the configuration settings
                    newConfig = this.project.ClonePropertyGroup(configToClone[configName]);
                    foreach (ProjectPropertyElement property in newConfig.Properties)
                    {
                        if (property.Name.Equals(ProjectFileConstants.PlatformTarget, StringComparison.OrdinalIgnoreCase))
                        {
                            property.Parent.RemoveChild(property);
                        }
                    }
                }
                else
                {
                    // no source to clone from, lets just create a new empty config
                    PopulateEmptyConfig(ref newConfig);
                    this.AddOutputPath(newConfig, configName);
                }

                newConfig.AddProperty(ProjectFileConstants.PlatformTarget, newCanonicalName.PlatformTarget);

                // Set the condition that will define the new configuration
                string newCondition = newCanonicalName.ToMSBuildCondition();
                newConfig.Condition = newCondition;
            }
            NotifyOnPlatformNameAdded(platformName);
            return(VSConstants.S_OK);
        }
Exemple #29
0
        /// <summary>
        /// Copies an existing configuration name or creates a new one.
        /// </summary>
        /// <param name="name">The name of the new configuration.</param>
        /// <param name="cloneName">the name of the configuration to copy, or a null reference, indicating that AddCfgsOfCfgName should create a new configuration.</param>
        /// <param name="fPrivate">Flag indicating whether or not the new configuration is private. If fPrivate is set to true, the configuration is private. If set to false, the configuration is public. This flag can be ignored.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
        public virtual int AddCfgsOfCfgName(string name, string cloneName, int fPrivate)
        {
            // We need to QE/QS the project file
            if (!this.ProjectMgr.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // First create the condition that represent the configuration we want to clone
            string condition = (cloneName == null ? String.Empty : String.Format(CultureInfo.InvariantCulture, configString, cloneName).Trim());

            // Get all configs
            List <ProjectPropertyGroupElement> configGroup   = new List <ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
            ProjectPropertyGroupElement        configToClone = null;

            if (cloneName != null)
            {
                // Find the configuration to clone
                foreach (ProjectPropertyGroupElement currentConfig in configGroup)
                {
                    // Only care about conditional property groups
                    if (currentConfig.Condition == null || currentConfig.Condition.Length == 0)
                    {
                        continue;
                    }

                    // Skip if it isn't the group we want
                    if (String.Compare(currentConfig.Condition.Trim(), condition, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        continue;
                    }

                    configToClone = currentConfig;
                }
            }

            ProjectPropertyGroupElement newConfig = null;

            if (configToClone != null)
            {
                // Clone the configuration settings
                newConfig = this.project.ClonePropertyGroup(configToClone);
                //Will be added later with the new values to the path

                foreach (ProjectPropertyElement property in newConfig.Properties)
                {
                    if (property.Name.Equals("OutputPath", StringComparison.OrdinalIgnoreCase))
                    {
                        property.Parent.RemoveChild(property);
                    }
                }
            }
            else
            {
                // no source to clone from, lets just create a new empty config
                newConfig = this.project.BuildProject.Xml.AddPropertyGroup();
                // Get the list of property name, condition value from the config provider
                IList <KeyValuePair <KeyValuePair <string, string>, string> > propVals = this.NewConfigProperties;
                foreach (KeyValuePair <KeyValuePair <string, string>, string> data in propVals)
                {
                    KeyValuePair <string, string> propData = data.Key;
                    string value = data.Value;
                    ProjectPropertyElement newProperty = newConfig.AddProperty(propData.Key, value);
                    if (!String.IsNullOrEmpty(propData.Value))
                    {
                        newProperty.Condition = propData.Value;
                    }
                }
            }


            //add the output path
            string outputBasePath = this.ProjectMgr.OutputBaseRelativePath;

            if (outputBasePath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                outputBasePath = Path.GetDirectoryName(outputBasePath);
            }
            newConfig.AddProperty("OutputPath", Path.Combine(outputBasePath, name) + Path.DirectorySeparatorChar.ToString());

            // Set the condition that will define the new configuration
            string newCondition = String.Format(CultureInfo.InvariantCulture, configString, name);

            newConfig.Condition = newCondition;

            NotifyOnCfgNameAdded(name);
            return(VSConstants.S_OK);
        }
Exemple #30
0
        /// <summary>
        /// Sets the value of the property.
        /// </summary>
        /// <param name="value">Property value to set.</param>
        /// <param name="configs">Optional list of configurations to set the property in;
        /// defaults to the project current configuration</param>
        /// <remarks>
        /// Before calling this method, the caller must ensure that the value is valid according to
        /// the <see cref="PropertyValidator"/> class, and that the project file is writable.
        /// In most cases the caller should also ensure that the new value is different from the
        /// existing value, to avoid dirtying the project file unnecessarily.
        /// </remarks>
        public void SetValue(string value, IList <ProjectConfig> configs)
        {
            WixHelperMethods.VerifyNonNullArgument(value, "value");

            value = value.Trim();

            MSBuild.Project buildProject = this.project.BuildProject;
            if (this.PerUser)
            {
                if (this.project.UserBuildProject == null)
                {
                    this.project.CreateUserBuildProject();
                }

                buildProject = this.project.UserBuildProject;
            }

            value = this.Escape(value);

            if (this.PerConfig)
            {
                if (configs == null || configs.Count == 0)
                {
                    configs = new ProjectConfig[] { this.project.CurrentConfig };
                }

                foreach (ProjectConfig config in configs)
                {
                    bool set = false;

                    // First see if there's an existing property group that matches our condition
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        // if there is, set it within that group
                        if (String.Equals(propGroup.Condition, config.Condition, StringComparison.Ordinal))
                        {
                            propGroup.SetProperty(this.propertyName, value);
                            set = true;
                            break;
                        }
                    }

                    // If not, add a new property group for the condition and set the property within it
                    if (!set)
                    {
                        ProjectPropertyGroupElement newPropGroup = buildProject.Xml.AddPropertyGroup();
                        newPropGroup.Condition = config.Condition;
                        newPropGroup.SetProperty(this.propertyName, value);
                        set = true;
                    }

                    buildProject.ReevaluateIfNecessary();
                }
            }
            else
            {
                if (this.EndOfProjectFile)
                {
                    List <ProjectPropertyGroupElement> propertyGroupsToDelete = new List <ProjectPropertyGroupElement>();

                    // First see if there's an existing property group with our property
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        List <ProjectPropertyElement> propertiesToDelete = new List <ProjectPropertyElement>();
                        if (!String.IsNullOrEmpty(propGroup.Condition))
                        {
                            continue;
                        }

                        foreach (ProjectPropertyElement property in propGroup.Properties)
                        {
                            // if there is, remove it so the new value is at the end of the file
                            if (String.IsNullOrEmpty(property.Condition) && String.Equals(property.Name, this.propertyName, StringComparison.OrdinalIgnoreCase))
                            {
                                propertiesToDelete.Add(property);
                            }
                        }

                        foreach (ProjectPropertyElement property in propertiesToDelete)
                        {
                            propGroup.RemoveChild(property);
                        }

                        if (propGroup.Count == 0)
                        {
                            propertyGroupsToDelete.Add(propGroup);
                        }
                    }

                    foreach (ProjectPropertyGroupElement propGroup in propertyGroupsToDelete)
                    {
                        buildProject.Xml.RemoveChild(propGroup);
                    }

                    ProjectPropertyGroupElement newPropGroup = buildProject.Xml.CreatePropertyGroupElement();
                    buildProject.Xml.AppendChild(newPropGroup);
                    newPropGroup.SetProperty(this.propertyName, value);
                }
                else
                {
                    buildProject.SetProperty(this.propertyName, value);
                }
            }

            this.project.InvalidatePropertyCache();
            this.project.SetProjectFileDirty(true);
        }