Пример #1
0
        public void WriteProjectInfo_AnalysisFileList_FilesTypes_SpecifiedPlusDefaults()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            ProjectDescriptor  descriptor  = BuildUtilities.CreateValidProjectDescriptor(rootInputFolder, "fileTypes.proj.txt");
            ProjectRootElement projectRoot = CreateInitializedProject(descriptor, new WellKnownProjectProperties(), rootOutputFolder);

            // Files we don't expect to be included by default
            string fooType1 = AddFileToProject(projectRoot, "fooType", sonarQubeExclude: null);
            string xxxType1 = AddFileToProject(projectRoot, "xxxType", sonarQubeExclude: null);

            AddFileToProject(projectRoot, "barType", sonarQubeExclude: null);

            // Files we'd normally expect to be included by default
            string managed1 = AddFileToProject(projectRoot, TargetProperties.ItemType_Compile, sonarQubeExclude: null);
            string content1 = AddFileToProject(projectRoot, TargetProperties.ItemType_Content, sonarQubeExclude: null);

            // Update the "item types" property to add some extra item type
            // NB this has to be done *after* the integration targets have been imported
            ProjectPropertyGroupElement group = projectRoot.CreatePropertyGroupElement();

            projectRoot.AppendChild(group);
            group.AddProperty("SQAnalysisFileItemTypes", "fooType;$(SQAnalysisFileItemTypes);xxxType");
            projectRoot.Save();

            // Act
            ProjectInfo projectInfo = ExecuteWriteProjectInfo(projectRoot, rootOutputFolder);

            // Assert
            AssertResultFileExists(projectInfo, AnalysisType.FilesToAnalyze, fooType1, xxxType1, content1, managed1);
        }
Пример #2
0
        /// <summary>
        /// Generates choose/when statements to parse values from configuration string
        /// </summary>
        /// <param name="propertyName">name of property to parse</param>
        /// <param name="project">project to update</param>
        private void ParseProperties(string propertyName, ProjectRootElement project, bool includeAdditionalProperites, Func <PropertyInfo, bool> configurationSelector, string parsedValuePrefix = null)
        {
            var parseConfigurationPropertyGroup = project.LastChild as ProjectPropertyGroupElement;

            if (parseConfigurationPropertyGroup == null || !string.IsNullOrEmpty(project.LastChild.Condition))
            {
                parseConfigurationPropertyGroup = project.CreatePropertyGroupElement();
                project.AppendChild(parseConfigurationPropertyGroup);
            }

            // delimit property for parsing, this gaurntees that every property value is surrounded in delimiters
            var parsePropertyName       = $"_parse_{propertyName}";
            var parseConfigurationValue = $"{ConfigurationFactory.PropertySeperator}$({propertyName}){ConfigurationFactory.PropertySeperator}";

            parseConfigurationPropertyGroup.AddProperty(parsePropertyName, parseConfigurationValue);

            // foreach property, pull it out of Configuration and set derived values.
            foreach (var property in ConfigurationFactory.GetProperties().Where(configurationSelector))
            {
                var choosePropertiesElement = project.CreateChooseElement();
                project.AppendChild(choosePropertiesElement);

                foreach (var value in ConfigurationFactory.GetValues(property))
                {
                    var propertiesCondition   = CreateContainsCondition(parsePropertyName, ConfigurationFactory.PropertySeperator + value.Value + ConfigurationFactory.PropertySeperator);
                    var whenPropertiesElement = project.CreateWhenElement(propertiesCondition);
                    choosePropertiesElement.AppendChild(whenPropertiesElement);

                    AddProperties(whenPropertiesElement, value, includeAdditionalProperites, parsedValuePrefix);
                }

                var otherwisePropertiesElement = project.CreateOtherwiseElement();
                choosePropertiesElement.AppendChild(otherwisePropertiesElement);

                if (property.DefaultValue != null)
                {
                    AddProperties(otherwisePropertiesElement, property.DefaultValue, includeAdditionalProperites, parsedValuePrefix);
                }
                else
                {
                    var otherwiseErrorPropertyGroup = project.CreatePropertyGroupElement();
                    otherwisePropertiesElement.AppendChild(otherwiseErrorPropertyGroup);

                    otherwiseErrorPropertyGroup.AddProperty(ErrorMessageProperty, $"$({ErrorMessageProperty})Could not find a value for {property.Name} from {propertyName} '$({propertyName})'.");
                }
            }
        }
        public override bool Execute()
        {
            ProjectRootElement project = ProjectRootElement.Create();
            var propertyGroup          = project.CreatePropertyGroupElement();

            project.AppendChild(propertyGroup);
            propertyGroup.AddProperty("AzureDevOpsCollectionUri", AzureDevOpsCollectionUri ?? "undefined");
            propertyGroup.AddProperty("AzureDevOpsProject", AzureDevOpsProject ?? "undefined");
            propertyGroup.AddProperty("AzureDevOpsBuildId", AzureDevOpsBuildId.ToString());
            var itemGroup = project.CreateItemGroupElement();

            project.AppendChild(itemGroup);
            if (ItemsToSign != null)
            {
                foreach (var itemToSign in ItemsToSign)
                {
                    var filename = itemToSign.ItemSpec.Replace('\\', '/');
                    {
                        var metadata = itemToSign.CloneCustomMetadata() as Dictionary <string, string>;
                        itemGroup.AddItem("ItemsToSign", Path.GetFileName(itemToSign.ItemSpec), metadata);
                    }
                }
            }
            if (StrongNameSignInfo != null)
            {
                foreach (var signInfo in StrongNameSignInfo)
                {
                    itemGroup.AddItem("StrongNameSignInfo", Path.GetFileName(signInfo.ItemSpec), signInfo.CloneCustomMetadata() as Dictionary <string, string>);
                }
            }
            if (FileSignInfo != null)
            {
                foreach (var signInfo in FileSignInfo)
                {
                    itemGroup.AddItem("FileSignInfo", signInfo.ItemSpec, signInfo.CloneCustomMetadata() as Dictionary <string, string>);
                }
            }
            if (FileExtensionSignInfo != null)
            {
                foreach (var signInfo in FileExtensionSignInfo)
                {
                    itemGroup.AddItem("FileExtensionSignInfo", signInfo.ItemSpec, signInfo.CloneCustomMetadata() as Dictionary <string, string>);
                }
            }
            project.Save(ManifestPath);
            return(true);
        }
Пример #4
0
        /// <summary>
        /// Replaces all configuration propertygroups with empty property groups corresponding to the expected configurations.
        /// Doesn't attempt to preserve any content since it can all be regenerated.
        /// Does attempt to preserve the ordering in the project file.
        /// </summary>
        /// <param name="project">Project</param>
        /// <param name="oldPropertyGroups">PropertyGroups to remove</param>
        /// <param name="newConfigurations"></param>
        private static void ReplaceConfigurationPropertyGroups(ProjectRootElement project, IEnumerable <ProjectPropertyGroupElement> oldPropertyGroups, IEnumerable <string> newConfigurations)
        {
            ProjectElement insertAfter = null, insertBefore = null;

            foreach (var oldPropertyGroup in oldPropertyGroups)
            {
                insertBefore = oldPropertyGroup.NextSibling;
                project.RemoveChild(oldPropertyGroup);
            }

            if (insertBefore == null)
            {
                // find first itemgroup after imports
                var insertAt = project.Imports.FirstOrDefault()?.NextSibling;

                while (insertAt != null)
                {
                    if (insertAt is ProjectItemGroupElement)
                    {
                        insertBefore = insertAt;
                        break;
                    }

                    insertAt = insertAt.NextSibling;
                }
            }

            if (insertBefore == null)
            {
                // find last propertygroup after imports, defaulting to after imports
                insertAfter = project.Imports.FirstOrDefault();

                while (insertAfter?.NextSibling != null && insertAfter.NextSibling is ProjectPropertyGroupElement)
                {
                    insertAfter = insertAfter.NextSibling;
                }
            }


            foreach (var newConfiguration in newConfigurations)
            {
                var newPropertyGroup = project.CreatePropertyGroupElement();
                newPropertyGroup.Condition = $"'$(Configuration)|$(Platform)' == '{newConfiguration}'";
                if (insertBefore != null)
                {
                    project.InsertBeforeChild(newPropertyGroup, insertBefore);
                }
                else if (insertAfter != null)
                {
                    project.InsertAfterChild(newPropertyGroup, insertAfter);
                }
                else
                {
                    project.AppendChild(newPropertyGroup);
                }
                insertBefore = null;
                insertAfter  = newPropertyGroup;
            }
        }
Пример #5
0
        private bool EnsureProjectGuid(ProjectRootElement project)
        {
            ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
            string guid = string.Empty;

            if (projectGuid != null)
            {
                guid = projectGuid.Value;
                string projectName;
                if (_guidMap.TryGetValue(guid, out projectName))
                {
                    Log.LogMessage($"The ProjectGuid='{guid}' is duplicated across projects '{projectName}' and '{project.FullPath}', so creating a new one for project '{project.FullPath}'");
                    guid = Guid.NewGuid().ToString("B").ToUpper();
                    _guidMap.Add(guid, project.FullPath);
                    projectGuid.Value = guid;
                    return(true);
                }
                else
                {
                    _guidMap.Add(guid, project.FullPath);
                }
            }

            if (projectGuid == null)
            {
                guid = Guid.NewGuid().ToString("B").ToUpper();

                var propertyGroup = project.Imports.FirstOrDefault()?.NextSibling as ProjectPropertyGroupElement;

                if (propertyGroup == null || !string.IsNullOrEmpty(propertyGroup.Condition))
                {
                    propertyGroup = project.CreatePropertyGroupElement();
                    ProjectElement insertAfter = project.Imports.FirstOrDefault();

                    if (insertAfter == null)
                    {
                        insertAfter = project.Children.FirstOrDefault();
                    }

                    if (insertAfter != null)
                    {
                        project.InsertAfterChild(propertyGroup, insertAfter);
                    }
                    else
                    {
                        project.AppendChild(propertyGroup);
                    }
                }

                propertyGroup.AddProperty("ProjectGuid", guid);
                return(true);
            }

            return(false);
        }
        public MSBuildItemDefinitionGroup(MSBuildBasedProject project, string condition)
        {
            ProjectRootElement root = project.MSBuildProjectFile;

            group = root.ItemDefinitionGroups.SingleOrDefault(item => item.Condition == condition);
            if (group == null)
            {
                group           = root.CreateItemDefinitionGroupElement();
                group.Condition = condition;
                root.AppendChild(group);
            }
        }
        public void ShouldHaveFilePathLocationEvenIfNotLoadedNorSavedYet()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            project.FullPath = "c:\\x";
            ProjectTargetElement target = project.CreateTargetElement("t");

            target.Outputs = "o";
            project.AppendChild(target);

            Assert.Equal(project.FullPath, target.Location.File);
            Assert.Equal(project.FullPath, target.OutputsLocation.File);
        }
        void AddPropertyWithCondition(ProjectRootElement projectRoot, string name, string value, string condition)
        {
            ProjectPropertyGroupElement groupProperty = projectRoot.CreatePropertyGroupElement();

            groupProperty.Condition = condition;
            projectRoot.AppendChild(groupProperty);

            ProjectPropertyElement property = projectRoot.CreatePropertyElement(name);

            groupProperty.AppendChild(property);
            property.Value     = value;
            property.Condition = condition;
        }
        public void XmlLocationsAreCached()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            project.FullPath = "c:\\x";
            ProjectTargetElement target = project.CreateTargetElement("t");

            target.Outputs = "o";
            project.AppendChild(target);

            ElementLocation e1 = target.Location;
            ElementLocation e2 = target.OutputsLocation;

            Assert.Equal(true, Object.ReferenceEquals(e1, target.Location));
            Assert.Equal(true, Object.ReferenceEquals(e2, target.OutputsLocation));
        }
        public void XmlLocationReflectsRename()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            project.FullPath = "c:\\x";
            ProjectTargetElement target = project.CreateTargetElement("t");

            target.Outputs = "o";
            project.AppendChild(target);

            Assert.Equal(project.FullPath, target.Location.File);
            Assert.Equal(project.FullPath, target.OutputsLocation.File);

            project.FullPath = "c:\\y";

            Assert.Equal(project.FullPath, target.Location.File);
            Assert.Equal(project.FullPath, target.OutputsLocation.File);
        }
        /// <summary>
        /// Creates a ProjectTargetElement representing this instance.  Attaches it to the specified root element.
        /// </summary>
        /// <param name="rootElement">The root element to which the new element will belong.</param>
        /// <returns>The new element.</returns>
        internal ProjectTargetElement ToProjectTargetElement(ProjectRootElement rootElement)
        {
            ProjectTargetElement target = rootElement.CreateTargetElement(Name);

            rootElement.AppendChild(target);

            target.Condition        = Condition;
            target.DependsOnTargets = DependsOnTargets;
            target.Inputs           = Inputs;
            target.Outputs          = Outputs;
            target.Returns          = Returns;

            foreach (ProjectTaskInstance taskInstance in Tasks)
            {
                ProjectTaskElement taskElement = target.AddTask(taskInstance.Name);
                taskElement.Condition           = taskInstance.Condition;
                taskElement.ContinueOnError     = taskInstance.ContinueOnError;
                taskElement.MSBuildArchitecture = taskInstance.MSBuildArchitecture;
                taskElement.MSBuildRuntime      = taskInstance.MSBuildRuntime;

                foreach (KeyValuePair <string, string> taskParameterEntry in taskInstance.Parameters)
                {
                    taskElement.SetParameter(taskParameterEntry.Key, taskParameterEntry.Value);
                }

                foreach (ProjectTaskInstanceChild outputInstance in taskInstance.Outputs)
                {
                    if (outputInstance is ProjectTaskOutputItemInstance)
                    {
                        ProjectTaskOutputItemInstance outputItemInstance = outputInstance as ProjectTaskOutputItemInstance;
                        taskElement.AddOutputItem(outputItemInstance.TaskParameter, outputItemInstance.ItemType, outputItemInstance.Condition);
                    }
                    else if (outputInstance is ProjectTaskOutputPropertyInstance)
                    {
                        ProjectTaskOutputPropertyInstance outputPropertyInstance = outputInstance as ProjectTaskOutputPropertyInstance;
                        taskElement.AddOutputItem(outputPropertyInstance.TaskParameter, outputPropertyInstance.PropertyName, outputPropertyInstance.Condition);
                    }
                }
            }

            return(target);
        }
Пример #12
0
        internal static void AddWebProjectExtensions(ProjectRootElement project)
        {
            // Adding this section prevents IIS Express required error message
            var projExt = project.CreateProjectExtensionsElement();

            project.AppendChild(projExt);

            projExt["VisualStudio"] = @"
    <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"">
    <WebProjectProperties>
        <AutoAssignPort>True</AutoAssignPort>
        <UseCustomServer>True</UseCustomServer>
        <CustomServerUrl>http://localhost</CustomServerUrl>
        <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
    </WebProjectProperties>
    </FlavorProperties>
    <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"" User="""">
    <WebProjectProperties>
        <StartPageUrl>
        </StartPageUrl>
        <StartAction>CurrentPage</StartAction>
        <AspNetDebugging>True</AspNetDebugging>
        <SilverlightDebugging>False</SilverlightDebugging>
        <NativeDebugging>False</NativeDebugging>
        <SQLDebugging>False</SQLDebugging>
        <ExternalProgram>
        </ExternalProgram>
        <StartExternalURL>
        </StartExternalURL>
        <StartCmdLineArguments>
        </StartCmdLineArguments>
        <StartWorkingDirectory>
        </StartWorkingDirectory>
        <EnableENC>False</EnableENC>
        <AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
    </WebProjectProperties>
    </FlavorProperties>
";
        }
Пример #13
0
        private void CreateRuntimeIdentifier(ProjectRootElement project)
        {
            var rid = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.GetRuntimeIdentifier();

            string[] ridParts = rid.Split('-');

            if (ridParts.Length < 1)
            {
                throw new System.InvalidOperationException($"Unknown rid format {rid}.");
            }

            string osNameAndVersion = ridParts[0];

            var propertyGroup = project.CreatePropertyGroupElement();

            project.AppendChild(propertyGroup);

            var runtimeProperty = propertyGroup.AddProperty(RuntimeOSProperty, $"{osNameAndVersion}");

            runtimeProperty.Condition = $"'$({RuntimeOSProperty})' == ''";

            Log.LogMessage($"Running on OS with RID {rid}, so defaulting RuntimeOS to '{osNameAndVersion}'");
        }