public CSharpProject(Solution solution, string title, string fileName)
		{
			this.Solution = solution;
			this.Title = title;
			this.FileName = fileName;
			
			var p = new Microsoft.Build.Evaluation.Project(fileName);
			this.AssemblyName = p.GetPropertyValue("AssemblyName");
			this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false;
			this.CompilerSettings.CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false;
			foreach (string symbol in p.GetPropertyValue("DefineConstants").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
				this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
			}
			foreach (var item in p.GetItems("Compile")) {
				Files.Add(new CSharpFile(this, Path.Combine(p.DirectoryPath, item.EvaluatedInclude)));
			}
			List<IAssemblyReference> references = new List<IAssemblyReference>();
			string mscorlib = FindAssembly(Program.AssemblySearchPaths, "mscorlib");
			if (mscorlib != null) {
				references.Add(Program.LoadAssembly(mscorlib));
			} else {
				Console.WriteLine("Could not find mscorlib");
			}
			bool hasSystemCore = false;
			foreach (var item in p.GetItems("Reference")) {
				string assemblyFileName = null;
				if (item.HasMetadata("HintPath")) {
					assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath"));
					if (!File.Exists(assemblyFileName))
						assemblyFileName = null;
				}
				if (assemblyFileName == null) {
					assemblyFileName = FindAssembly(Program.AssemblySearchPaths, item.EvaluatedInclude);
				}
				if (assemblyFileName != null) {
					if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
						hasSystemCore = true;
					references.Add(Program.LoadAssembly(assemblyFileName));
				} else {
					Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
				}
			}
			if (!hasSystemCore && FindAssembly(Program.AssemblySearchPaths, "System.Core") != null)
				references.Add(Program.LoadAssembly(FindAssembly(Program.AssemblySearchPaths, "System.Core")));
			foreach (var item in p.GetItems("ProjectReference")) {
				references.Add(new ProjectReference(solution, item.GetMetadataValue("Name")));
			}
			this.ProjectContent = new CSharpProjectContent()
				.SetAssemblyName(this.AssemblyName)
				.SetCompilerSettings(this.CompilerSettings)
				.AddAssemblyReferences(references)
				.UpdateProjectContent(null, Files.Select(f => f.ParsedFile));
		}
Exemple #2
0
        public CSharpProject(Solution solution, string title, string fileName)
        {
            this.Solution = solution;
            this.Title    = title;
            this.FileName = fileName;

            var p = new Microsoft.Build.Evaluation.Project(fileName);

            this.AssemblyName              = p.GetPropertyValue("AssemblyName");
            this.AllowUnsafeBlocks         = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false;
            this.CheckForOverflowUnderflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false;
            this.PreprocessorDefines       = p.GetPropertyValue("DefineConstants").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in p.GetItems("Compile"))
            {
                Files.Add(new CSharpFile(this, Path.Combine(p.DirectoryPath, item.EvaluatedInclude)));
            }
            List <IAssemblyReference> references = new List <IAssemblyReference>();
            string mscorlib = FindAssembly(Program.AssemblySearchPaths, "mscorlib");

            if (mscorlib != null)
            {
                references.Add(Program.LoadAssembly(mscorlib));
            }
            else
            {
                Console.WriteLine("Could not find mscorlib");
            }
            foreach (var item in p.GetItems("Reference"))
            {
                string assemblyFileName = null;
                if (item.HasMetadata("HintPath"))
                {
                    assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath"));
                    if (!File.Exists(assemblyFileName))
                    {
                        assemblyFileName = null;
                    }
                }
                if (assemblyFileName == null)
                {
                    assemblyFileName = FindAssembly(Program.AssemblySearchPaths, item.EvaluatedInclude);
                }
                if (assemblyFileName != null)
                {
                    references.Add(Program.LoadAssembly(assemblyFileName));
                }
                else
                {
                    Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
                }
            }
            foreach (var item in p.GetItems("ProjectReference"))
            {
                references.Add(new ProjectReference(solution, item.GetMetadataValue("Name")));
            }
            this.ProjectContent = new CSharpProjectContent()
                                  .SetAssemblyName(this.AssemblyName)
                                  .AddAssemblyReferences(references)
                                  .UpdateProjectContent(null, Files.Select(f => f.ParsedFile));
        }
Exemple #3
0
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            this.Solution = solution;
            this.Title    = title;
            this.FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);

            // Figure out some compiler settings
            this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
            this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
            this.CompilerSettings.CheckForOverflow  = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
            string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");

            foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
            }

            // Initialize the unresolved type system
            IProjectContent pc = new CSharpProjectContent();

            pc = pc.SetAssemblyName(this.AssemblyName);
            pc = pc.SetProjectFileName(fileName);
            pc = pc.SetCompilerSettings(this.CompilerSettings);
            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile"))
            {
                var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
                Files.Add(file);
            }
            // Add parsed files to the type system
            pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));

            // Add referenced assemblies:
            foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject))
            {
                IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
                pc = pc.AddAssemblyReferences(new [] { assembly });
            }

            // Add project references:
            foreach (var item in msbuildProject.GetItems("ProjectReference"))
            {
                string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
                // Normalize the path; this is required to match the name with the referenced project's file name
                referencedFileName = Path.GetFullPath(referencedFileName);
                pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
            }
            this.ProjectContent = pc;
        }
Exemple #4
0
        protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
        {
            if (_documents == null)
            {
                _documents = new Dictionary <string, MSB.Evaluation.ProjectItem>();
                foreach (var item in _loadedProject.GetItems(ItemNames.Compile))
                {
                    _documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item;
                }
            }

            return(!_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec)));
        }
Exemple #5
0
        public ArrayList GetItems(Microsoft.Build.Evaluation.Project pc, string name, bool folds)
        {
            ArrayList L = new ArrayList();


            if (pc == null)
            {
                return(L);
            }

            string folder = Path.GetDirectoryName(FileName);

            ICollection <Microsoft.Build.Evaluation.ProjectItem> s = pc.GetItems(name);


            foreach (Microsoft.Build.Evaluation.ProjectItem p in s)
            {
                string file = Path.GetFullPath(folder + "\\" + p.EvaluatedInclude);

                if (folds == false)
                {
                    file = p.EvaluatedInclude;
                }

                L.Add(file);
            }

            pc.ProjectCollection.UnloadAllProjects();

            return(L);
        }
Exemple #6
0
        public ArrayList GetProjectReferences(string name)
        {
            ArrayList L = new ArrayList();

            Microsoft.Build.Evaluation.Project pc = new Microsoft.Build.Evaluation.Project(FileName);

            if (pc == null)
            {
                return(L);
            }

            string folder = Path.GetDirectoryName(FileName);

            ICollection <Microsoft.Build.Evaluation.ProjectItem> s = pc.GetItems(name);



            foreach (Microsoft.Build.Evaluation.ProjectItem p in s)
            {
                string file = Path.GetFullPath(folder + "\\" + p.EvaluatedInclude);

                string project = Path.GetFileNameWithoutExtension(file);


                file = project;

                L.Add(file);
            }

            pc.ProjectCollection.UnloadAllProjects();

            return(L);
        }
Exemple #7
0
        public Microsoft.Build.Evaluation.ProjectItem GetReference(string name, string refs)
        {
            ArrayList L = new ArrayList();

            Microsoft.Build.Evaluation.Project pc = null;

            try
            {
                pc = new Microsoft.Build.Evaluation.Project(FileName);
            }
            catch (Exception e) { }
            if (pc == null)
            {
                return(null);
            }

            string folder = Path.GetDirectoryName(FileName);

            ICollection <Microsoft.Build.Evaluation.ProjectItem> s = pc.GetItems(name);



            foreach (Microsoft.Build.Evaluation.ProjectItem p in s)
            {
                if (p.EvaluatedInclude == refs)
                {
                    return(p);
                }
            }

            pc.ProjectCollection.UnloadAllProjects();

            return(null);
        }
Exemple #8
0
        private static void AddStepDefinitonToIntelliSenseProject(List <NodeFeature> features, string pathToFeatureFile, string pathToIntelliSenseProject)
        {
            foreach (var feature in features)
            {
                List <StepInstance> si = new List <StepInstance>();
                var steps = new List <NodeStep>();
                feature.Scenarios.ForEach(s => steps.AddRange(s.Steps));
                var uniqueSteps = GeneratorHelper.FindUniqueSteps(new List <NodeStep>(), steps);

                foreach (var step in uniqueSteps)
                {
                    StepDefinitionType    type;
                    StepDefinitionKeyword keyword;
                    string stepNameWithoutType;

                    if (step.Name.StartsWith("Given"))
                    {
                        type                = StepDefinitionType.Given;
                        keyword             = StepDefinitionKeyword.Given;
                        stepNameWithoutType = step.Name.Substring("Given".Length);
                    }
                    else if (step.Name.StartsWith("When"))
                    {
                        type                = StepDefinitionType.When;
                        keyword             = StepDefinitionKeyword.When;
                        stepNameWithoutType = step.Name.Substring("When".Length);
                    }
                    else
                    {
                        type                = StepDefinitionType.Then;
                        keyword             = StepDefinitionKeyword.Then;
                        stepNameWithoutType = step.Name.Substring("Then".Length);
                    }
                    string scenarioName = feature.Scenarios.First(scenario => scenario.Steps.Contains(step)).Name;
                    si.Add(new StepInstance(type, keyword, stepNameWithoutType, stepNameWithoutType, new StepContext(feature.Name, scenarioName, new List <string>(), CultureInfo.CurrentCulture)));
                }

                var stepDefSkeleton = new StepDefinitionSkeletonProvider(new SpecFlowCSkeletonTemplateProvider(), new StepTextAnalyzer());
                var template        = stepDefSkeleton.GetBindingClassSkeleton(TechTalk.SpecFlow.ProgrammingLanguage.CSharp, si.ToArray(), "CppUnitTest", feature.Name, StepDefinitionSkeletonStyle.MethodNamePascalCase, CultureInfo.CurrentCulture);

                string basePathToFeatures            = Path.GetDirectoryName(pathToFeatureFile);
                string basePathToIntelliSenseProject = Path.GetDirectoryName(pathToIntelliSenseProject);
                _csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);

                var stepDefinitionDirPathInProj = string.Format("Steps\\{0}\\", PROJECT_NAME);
                var stepDefinitionDirPath       = string.Format("{0}\\{1}", basePathToIntelliSenseProject, stepDefinitionDirPathInProj);

                var filePathInProjFile = string.Format("{0}{1}_step.cs", stepDefinitionDirPathInProj, feature.Name);
                var filePath           = string.Format("{0}{1}_step.cs", stepDefinitionDirPath, feature.Name);

                if (!_csProj.GetItems("Compile").Any(item => item.UnevaluatedInclude == filePathInProjFile))
                {
                    Console.WriteLine(string.Format("Generating Step Definition file for IntelliSense support: {0}", filePathInProjFile));
                    Directory.CreateDirectory(stepDefinitionDirPath);
                    File.WriteAllText(filePath, template);
                    _csProj.AddItem("Compile", filePathInProjFile);
                    _isDirtyCsProj = true;
                }
            }
        }
Exemple #9
0
        void AddCSharpFiles(Microsoft.Build.Evaluation.Project p)
        {
            foreach (var item in p.GetItems("Compile"))
            {
                try
                {
                    string path = _fileSystem.Path.Combine(p.DirectoryPath, item.EvaluatedInclude).ForceNativePathSeparator();

                    if (_fileSystem.File.Exists(path))
                    {
                        string file = _fileSystem.FileInfo.FromFileName(path).FullName;
                        _logger.Debug("Loading " + file);
                        Files.Add(new CSharpFile(this, file));
                    }
                    else
                    {
                        _logger.Error("File does not exist - " + path);
                    }
                }
                catch (NullReferenceException e)
                {
                    _logger.Error(e);
                }
            }
        }
Exemple #10
0
 public void BuildSyntTree()
 {
     foreach (var item in msbuildProject.GetItems("Compile"))
     {
         var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
         Files.Add(file);
     }
 }
Exemple #11
0
 void AddProjectReferences(Microsoft.Build.Evaluation.Project p)
 {
     foreach (Microsoft.Build.Evaluation.ProjectItem item in p.GetItems("ProjectReference"))
     {
         var projectName   = item.GetMetadataValue("Name");
         var referenceGuid = Guid.Parse(item.GetMetadataValue("Project"));
         _logger.Debug("Adding project reference {0}, {1}", projectName, referenceGuid);
         AddReference(new ProjectReference(_solution, projectName, referenceGuid));
     }
 }
Exemple #12
0
        public async Task Basic_EmptyProjectCannotBuild()
        {
            // This test focuses on a completely empty project.
            nuproj.RemoveItems(nuproj.GetItems("Content"));

            var result = await MSBuild.ExecuteAsync(nuproj.CreateProjectInstance(), this.logger);

            // Verify that the build fails and tells the user why.
            Assert.Equal(BuildResultCode.Failure, result.Result.OverallResult);
            Assert.NotEqual(0, result.ErrorEvents.Count());
        }
        private static void RemoveProjectJsonReference(Microsoft.Build.Evaluation.Project buildProject, string projectJsonFilePath)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var projectJsonItem = buildProject.GetItems("None")
                                  .Where(t => string.Equals(t.EvaluatedInclude, Path.GetFileName(projectJsonFilePath), StringComparison.OrdinalIgnoreCase))
                                  .FirstOrDefault();

            if (projectJsonItem != null)
            {
                buildProject.RemoveItem(projectJsonItem);
            }
        }
Exemple #14
0
        void AddProjectReferences(Microsoft.Build.Evaluation.Project p)
        {
            foreach (Microsoft.Build.Evaluation.ProjectItem item in p.GetItems("ProjectReference"))
            {
                var projectName = item.HasMetadata("Name")
                    ? item.GetMetadataValue("Name")
                    : Path.GetFileNameWithoutExtension(item.EvaluatedInclude);

                var referenceGuid = Guid.Parse(item.GetMetadataValue("Project"));
                _logger.Debug("Adding project reference {0}, {1}", projectName, referenceGuid);
                AddReference(new ProjectReference(_solution, projectName, referenceGuid));
            }
        }
Exemple #15
0
        private static void AddFilesToCppProject(string pathToFile, string featureDir, string pathToCppProject)
        {
            _cppProj = _cppProj ?? GetUnloadedProject(pathToCppProject);

            pathToFile = MakeFeatureDirRelativeToCppProject(pathToFile, featureDir);

            string type = CppFileType(pathToFile);

            if (!_cppProj.GetItems(type).Any(item => item.UnevaluatedInclude == pathToFile))
            {
                _cppProj.AddItem(type, pathToFile);
                _isDirtyCppProj = true;
            }
        }
Exemple #16
0
        private static void AddFilesToCppProject(string pathToFile, string featureDir, string pathToCppProject)
        {
            _cppProj = _cppProj ?? GetUnloadedProject(pathToCppProject);

            pathToFile = MakeFeatureDirRelativeToCppProject(pathToFile, featureDir);

            string type = CppFileType(pathToFile);

            if (!_cppProj.GetItems(type).Any(item => item.UnevaluatedInclude == pathToFile))
            {
                _cppProj.AddItem(type, pathToFile);
                _isDirtyCppProj = true;
            }
        }
Exemple #17
0
        IReadOnlyList <AttributeData> EvaluateAssemblyAttributes()
        {
            // note: the reason we open the project and examine the items rather than just emumerate the
            // file system is that the process would miss linked files. we should be able to assemble the
            // assembly attributes from all assembly info files, even they are linked files or imported
            // from a source that cannot be evaluated by looking at the file system alone.
            var regex         = new Regex(assemblyInfoFilePattern, IgnoreCase | Singleline);
            var assemblyInfos = from item in project.GetItems("Compile")
                                let include = item.EvaluatedInclude
                                              where regex.IsMatch(include)
                                              let itemPath                       = GetFullPath(Combine(project.DirectoryPath, include))
                                                                        let code = ReadAllText(itemPath)
                                                                                   select ParseText(code);

            var references  = new[] { CreateFromFile(typeof(object).Assembly.Location) };
            var compilation = Create(project.GetPropertyValue("AssemblyName"), assemblyInfos, references);

            return(compilation.Assembly.GetAttributes().ToArray());
        }
Exemple #18
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Microsoft.Build.Evaluation.Project buildProject = buildProjectInfo.GetValue(testEnv.Project, new object[0]) as Microsoft.Build.Evaluation.Project;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                MethodInfo itemMapGetter           = typeof(VisualStudio.Project.ProjectNode).GetProperty("ItemIdMap", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true);
                Microsoft.VisualStudio.Shell.EventSinkCollection itemMap = (Microsoft.VisualStudio.Shell.EventSinkCollection)itemMapGetter.Invoke(testEnv.Project, new object[0]);
                uint itemID = itemMap.Add(node);

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
        /// <summary>
        /// The resolved type system for this project.
        /// This field is initialized once all projects have been loaded (in Solution constructor).
        /// </summary>
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            this.Solution = solution;
            this.Title = title;
            this.FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
            // Figure out some compiler settings
            this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");

            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile"))
            {
                var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
                Files.Add(file);
            }
        }
        private Configuration ImportConfiguration(Microsoft.Build.Evaluation.Project msbuildProject)
        {
            Configuration config = new Configuration()
            {
                Name = "Release"
            };

            var files = msbuildProject.GetItems("ClCompile");

            config.Defines  = ImportMetaData("PreprocessorDefinitions", files);
            config.Includes = ImportMetaData("AdditionalIncludeDirectories", files).ConvertAll(i => i);

            foreach (var file in files)
            {
                if (file.DirectMetadata.FirstOrDefault(m => m.Name == "PrecompiledHeader") != null)
                {
                    config.PrecompiledHeader = Path.GetFullPath(Path.Combine(msbuildProject.DirectoryPath, file.EvaluatedInclude));
                }
            }

            return(config);
        }
Exemple #21
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                Microsoft.Build.Evaluation.Project buildProject = testEnv.Project.BuildProject;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                uint itemID = node.Id;

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Exemple #22
0
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            this.Solution = solution;
            this.Title = title;
            this.FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
            // Figure out some compiler settings
            this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
            this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
            this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
            string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
            foreach (string symbol in defineConstants.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());

            // Initialize the unresolved type system
            IProjectContent pc = new CSharpProjectContent();
            pc = pc.SetAssemblyName(this.AssemblyName);
            pc = pc.SetProjectFileName(fileName);
            pc = pc.SetCompilerSettings(this.CompilerSettings);
            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile")) {
                var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
                Files.Add(file);
            }
            // Add parsed files to the type system
            pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));

            // Add referenced assemblies:
            foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) {
                IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
                pc = pc.AddAssemblyReferences(new [] { assembly });
            }

            // Add project references:
            foreach (var item in msbuildProject.GetItems("ProjectReference")) {
                string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
                // Normalize the path; this is required to match the name with the referenced project's file name
                referencedFileName = Path.GetFullPath(referencedFileName);
                pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
            }
            this.ProjectContent = pc;
        }
        public CSharpProject(ISolution solution, string title, string fileName, Guid id)
        {
            _solution = solution;
            Title = title;
            FileName = fileName.ForceNativePathSeparator();
            ProjectId = id;
            Files = new List<CSharpFile>();

            var p = new Microsoft.Build.Evaluation.Project(FileName);
            AssemblyName = p.GetPropertyValue("AssemblyName");

            _compilerSettings = new CompilerSettings
                {
                    AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false,
                    CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false,
                };
            string[] defines = p.GetPropertyValue("DefineConstants").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string define in defines)
                _compilerSettings.ConditionalSymbols.Add(define);

            foreach (var item in p.GetItems("Compile"))
            {
                try
                {
                    string path = Path.Combine(p.DirectoryPath, item.EvaluatedInclude).ForceNativePathSeparator();
                    if (File.Exists(path))
                    {
                        Files.Add(new CSharpFile(this, new FileInfo(path).FullName));
                    }
                    else
                    {
                        Console.WriteLine("File does not exist - " + path);
                    }
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine(e);
                }
            }

            References = new List<IAssemblyReference>();
            string mscorlib = FindAssembly(AssemblySearchPaths, "mscorlib");
            if (mscorlib != null)
                AddReference(LoadAssembly(mscorlib));
            else
                Console.WriteLine("Could not find mscorlib");

            bool hasSystemCore = false;
            foreach (var item in p.GetItems("Reference"))
            {

                string assemblyFileName = null;
                if (item.HasMetadata("HintPath"))
                {
                    assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath")).ForceNativePathSeparator();
                    if (!File.Exists(assemblyFileName))
                        assemblyFileName = null;
                }
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                    assemblyFileName = FindAssembly(AssemblySearchPaths, item.EvaluatedInclude);

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null)
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);

                if (assemblyFileName != null)
                {
                    if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                        hasSystemCore = true;

                    Console.WriteLine("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                }
                else
                    Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
            }
            if (!hasSystemCore && FindAssembly(AssemblySearchPaths, "System.Core") != null)
                AddReference(LoadAssembly(FindAssembly(AssemblySearchPaths, "System.Core")));

            foreach (var item in p.GetItems("ProjectReference"))
                AddReference(new ProjectReference(_solution, item.GetMetadataValue("Name")));

            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddAssemblyReferences(References)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));
        }
Exemple #24
0
        private static void AddStepDefinitonToIntelliSenseProject(List<NodeFeature> features, string pathToFeatureFile, string pathToIntelliSenseProject)
        {
            foreach (var feature in features)
            {
                List<StepInstance> si = new List<StepInstance>();
                var steps = new List<NodeStep>();
                feature.Scenarios.ForEach(s => steps.AddRange(s.Steps));
                var uniqueSteps = GeneratorHelper.FindUniqueSteps(new List<NodeStep>(), steps);

                foreach (var step in uniqueSteps)
                {
                    StepDefinitionType type;
                    StepDefinitionKeyword keyword;
                    string stepNameWithoutType;

                    if (step.Name.StartsWith("Given"))
                    {
                        type = StepDefinitionType.Given;
                        keyword = StepDefinitionKeyword.Given;
                        stepNameWithoutType = step.Name.Substring("Given".Length);
                    }
                    else if (step.Name.StartsWith("When"))
                    {
                        type = StepDefinitionType.When;
                        keyword = StepDefinitionKeyword.When;
                        stepNameWithoutType = step.Name.Substring("When".Length);
                    }
                    else
                    {
                        type = StepDefinitionType.Then;
                        keyword = StepDefinitionKeyword.Then;
                        stepNameWithoutType = step.Name.Substring("Then".Length);
                    }
                    string scenarioName = feature.Scenarios.First(scenario => scenario.Steps.Contains(step)).Name;
                    si.Add(new StepInstance(type, keyword, stepNameWithoutType, stepNameWithoutType, new StepContext(feature.Name, scenarioName, new List<string>(), CultureInfo.CurrentCulture)));
                }

                var stepDefSkeleton = new StepDefinitionSkeletonProvider(new SpecFlowCSkeletonTemplateProvider(), new StepTextAnalyzer());
                var template = stepDefSkeleton.GetBindingClassSkeleton(TechTalk.SpecFlow.ProgrammingLanguage.CSharp, si.ToArray(), "CppUnitTest", feature.Name, StepDefinitionSkeletonStyle.MethodNamePascalCase, CultureInfo.CurrentCulture);

                string basePathToFeatures = Path.GetDirectoryName(pathToFeatureFile);
                string basePathToIntelliSenseProject = Path.GetDirectoryName(pathToIntelliSenseProject);
                _csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);

                var stepDefinitionDirPathInProj = string.Format("Steps\\{0}\\", PROJECT_NAME);
                var stepDefinitionDirPath = string.Format("{0}\\{1}", basePathToIntelliSenseProject, stepDefinitionDirPathInProj);

                var filePathInProjFile = string.Format("{0}{1}_step.cs", stepDefinitionDirPathInProj, feature.Name);
                var filePath = string.Format("{0}{1}_step.cs", stepDefinitionDirPath, feature.Name);

                if (!_csProj.GetItems("Compile").Any(item => item.UnevaluatedInclude == filePathInProjFile))
                {
                    Console.WriteLine(string.Format("Generating Step Definition file for IntelliSense support: {0}", filePathInProjFile));
                    Directory.CreateDirectory(stepDefinitionDirPath);
                    File.WriteAllText(filePath, template);
                    _csProj.AddItem("Compile", filePathInProjFile);
                    _isDirtyCsProj = true;
                }
            }
        }
Exemple #25
0
        public CSharpProject(ISolution solution,
                             IFileSystem fileSystem,
                             Logger logger,
                             string title,
                             string fileName,
                             Guid id)
            : base(fileSystem, logger)
        {
            _fileSystem = fileSystem;
            _logger     = logger;
            _solution   = solution;
            Title       = title;
            if (fileSystem is FileSystem)
            {
                fileName = fileName.ForceNativePathSeparator();
            }
            FileName  = fileName;
            ProjectId = id;
            Files     = new List <CSharpFile>();
            Microsoft.Build.Evaluation.Project project;

            try
            {
                project = new Microsoft.Build.Evaluation.Project(_fileSystem, fileName);
            }
            catch (DirectoryNotFoundException)
            {
                logger.Error("Directory not found - " + FileName);
                return;
            }
            catch (FileNotFoundException)
            {
                logger.Error("File not found - " + FileName);
                return;
            }

            AssemblyName = project.GetPropertyValue("AssemblyName");

            SetCompilerSettings(project);

            AddCSharpFiles(project);

            References          = new List <IAssemblyReference>();
            this.ProjectContent = new CSharpProjectContent()
                                  .SetAssemblyName(AssemblyName)
                                  .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));

            AddMsCorlib();

            bool hasSystemCore = false;

            foreach (var item in project.GetItems("Reference"))
            {
                var assemblyFileName = GetAssemblyFileNameFromHintPath(project, item);
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                {
                    assemblyFileName = FindAssembly(item.EvaluatedInclude);
                }

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null && PlatformService.IsWindows)
                {
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);
                }

                if (assemblyFileName != null)
                {
                    if (_fileSystem.Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                    {
                        hasSystemCore = true;
                    }

                    _logger.Debug("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e);
                    }
                }
                else
                {
                    _logger.Error("Could not find referenced assembly " + item.EvaluatedInclude);
                }
            }
            if (!hasSystemCore && FindAssembly("System.Core") != null)
            {
                AddReference(LoadAssembly(FindAssembly("System.Core")));
            }


            AddProjectReferences(project);
        }
Exemple #26
0
        public CSharpProject(ISolution solution, string title, string fileName, Guid id)
        {
            _solution = solution;
            Title     = title;
            FileName  = fileName;
            ProjectId = id;
            Files     = new List <CSharpFile>();

            var p = new Microsoft.Build.Evaluation.Project(FileName);

            _assemblyName = p.GetPropertyValue("AssemblyName");

            _compilerSettings = new CompilerSettings()
            {
                AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false,
                CheckForOverflow  = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false,
            };
            string[] defines = p.GetPropertyValue("DefineConstants").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string define in defines)
            {
                _compilerSettings.ConditionalSymbols.Add(define);
            }

            foreach (var item in p.GetItems("Compile"))
            {
                try
                {
                    string path = Path.Combine(p.DirectoryPath, item.EvaluatedInclude).FixPath();
                    if (File.Exists(path))
                    {
                        Files.Add(new CSharpFile(this, new FileInfo(path).FullName));
                    }
                }
                catch (NullReferenceException)
                {
                }
            }

            References = new List <IAssemblyReference>();
            string mscorlib = FindAssembly(AssemblySearchPaths, "mscorlib");

            if (mscorlib != null)
            {
                AddReference(LoadAssembly(mscorlib));
            }
            else
            {
                Console.WriteLine("Could not find mscorlib");
            }

            bool hasSystemCore = false;

            foreach (var item in p.GetItems("Reference"))
            {
                string assemblyFileName = null;
                if (item.HasMetadata("HintPath"))
                {
                    assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath")).FixPath();
                    if (!File.Exists(assemblyFileName))
                    {
                        assemblyFileName = null;
                    }
                }
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                {
                    assemblyFileName = FindAssembly(AssemblySearchPaths, item.EvaluatedInclude);
                }

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null)
                {
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);
                }

                if (assemblyFileName != null)
                {
                    if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                    {
                        hasSystemCore = true;
                    }

                    Console.WriteLine("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                else
                {
                    Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
                }
            }
            if (!hasSystemCore && FindAssembly(AssemblySearchPaths, "System.Core") != null)
            {
                AddReference(LoadAssembly(FindAssembly(AssemblySearchPaths, "System.Core")));
            }

            foreach (var item in p.GetItems("ProjectReference"))
            {
                AddReference(new ProjectReference(_solution, item.GetMetadataValue("Name")));
            }

            this.ProjectContent = new CSharpProjectContent()
                                  .SetAssemblyName(this._assemblyName)
                                  .AddAssemblyReferences(References)
                                  .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));
        }
        /// <summary>
        /// Loads each MSBuild project in this solution and looks for its project-to-project references so that
        /// we know what build order we should use when building the solution. 
        /// </summary>
        private void ScanProjectDependencies(string childProjectToolsVersion, string fullSolutionConfigurationName)
        {
            // Don't bother with all this if the solution configuration doesn't even exist.
            if (fullSolutionConfigurationName == null)
            {
                return;
            }

            foreach (ProjectInSolution project in _solutionFile.ProjectsInOrder)
            {
                // We only need to scan .wdproj projects: Everything else is either MSBuildFormat or 
                // something we don't know how to do anything with anyway
                if (project.ProjectType == SolutionProjectType.WebDeploymentProject)
                {
                    // Skip the project if we don't have its configuration in this solution configuration
                    if (!project.ProjectConfigurations.ContainsKey(fullSolutionConfigurationName))
                    {
                        continue;
                    }

                    try
                    {
                        Project msbuildProject = new Project(project.AbsolutePath, _globalProperties, childProjectToolsVersion);

                        // ProjectDependency items work exactly like ProjectReference items from the point of 
                        // view of determining that project B depends on project A.  This item must cause
                        // project A to be built prior to project B.
                        //
                        // This has the format 
                        // <ProjectDependency Include="DependentProjectRelativePath">
                        //   <Project>{GUID}</Project>
                        // </Project>
                        IEnumerable<ProjectItem> references = msbuildProject.GetItems("ProjectDependency");

                        foreach (ProjectItem reference in references)
                        {
                            string referencedProjectGuid = reference.GetMetadataValue("Project");
                            AddDependencyByGuid(project, referencedProjectGuid);
                        }

                        // If this is a web deployment project, we have a reference specified as a property
                        // "SourceWebProject" rather than as a ProjectReference item.  This has the format
                        // {GUID}|PATH_TO_CSPROJ
                        // where
                        // GUID is the project guid for the "source" project
                        // PATH_TO_CSPROJ is the solution-relative path to the csproj file.
                        //
                        // NOTE: This is obsolete and is intended only for backward compatability with
                        // Whidbey-generated web deployment projects.  New projects should use the
                        // ProjectDependency item above.
                        string referencedWebProjectGuid = msbuildProject.GetPropertyValue("SourceWebProject");
                        if (!string.IsNullOrEmpty(referencedWebProjectGuid))
                        {
                            // Grab the guid with its curly braces...
                            referencedWebProjectGuid = referencedWebProjectGuid.Substring(0, 38);
                            AddDependencyByGuid(project, referencedWebProjectGuid);
                        }
                    }
                    catch (Exception e)
                    {
                        // We don't want any problems scanning the project file to result in aborting the build.
                        if (ExceptionHandling.IsCriticalException(e))
                        {
                            throw;
                        }

                        _loggingService.LogWarning
                            (
                            _projectBuildEventContext,
                            "SubCategoryForSolutionParsingErrors",
                            new BuildEventFileInfo(project.RelativePath),
                            "SolutionScanProjectDependenciesFailed",
                            project.RelativePath,
                            e.Message
                            );
                    }
                }
            }
        }
        public CSharpProject(ISolution solution,
                             IFileSystem fileSystem,
                             Logger logger, 
                             string title, 
                             string fileName, 
                             Guid id)
            : base(fileSystem, logger)
        {
            _fileSystem = fileSystem;
            _logger = logger;
            _solution = solution;
            Title = title;
            if (fileSystem is FileSystem)
            {
                fileName = fileName.ForceNativePathSeparator();
            }
            FileName = fileName;
            ProjectId = id;
            Files = new List<CSharpFile>();
            Microsoft.Build.Evaluation.Project project;

            try
            {
                project = new Microsoft.Build.Evaluation.Project(_fileSystem, fileName);
            }
            catch (DirectoryNotFoundException)
            {
                logger.Error("Directory not found - " + FileName);
                return;
            }
            catch (FileNotFoundException)
            {
                logger.Error("File not found - " + FileName);
                return;
            }

            AssemblyName = project.GetPropertyValue("AssemblyName");

            SetCompilerSettings(project);

            AddCSharpFiles(project);

            References = new List<IAssemblyReference>();
            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));

            AddMsCorlib();

            bool hasSystemCore = false;
            foreach (var item in project.GetItems("Reference"))
            {
                var assemblyFileName = GetAssemblyFileNameFromHintPath(project, item);
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                    assemblyFileName = FindAssembly(item.EvaluatedInclude);

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null && PlatformService.IsWindows)
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);

                if (assemblyFileName != null)
                {
                    if (_fileSystem.Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                        hasSystemCore = true;

                    _logger.Debug("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e);
                    }

                }
                else
                    _logger.Error("Could not find referenced assembly " + item.EvaluatedInclude);
            }
            if (!hasSystemCore && FindAssembly("System.Core") != null)
                AddReference(LoadAssembly(FindAssembly("System.Core")));

            AddProjectReferences(project);
        }