private static void AddPackage(ReferenceSwitcherConfiguration configuration, ProjectInSolution solutionProject, Project project, string packageName, string packageVersion) { var projectName = Path.GetFileNameWithoutExtension(solutionProject.AbsolutePath); var switchedProject = ( from r in configuration.Restore where string.Equals(r.Name, projectName, StringComparison.OrdinalIgnoreCase) select r).FirstOrDefault(); if (switchedProject != null) { var reference = switchedProject.GetSwitchedPackage(packageName); if (!string.IsNullOrEmpty(reference.Include)) { project.AddItem("Reference", reference.Include, reference.Metadata); } else { var items = project.AddItem("PackageReference", packageName, new[] { new KeyValuePair <string, string>("Version", packageVersion) }); items.ToList().ForEach(item => { item.Metadata?.ToList().ForEach(metadata => metadata.Xml.ExpressedAsAttribute = true); }); } } }
public static NuggetedProject Load(ProjectInSolution project) { if (!File.Exists(project.AbsolutePath)) { return(new NuggetedProject { Exists = false }); } if (!project.AbsolutePath.EndsWith(".csproj")) { return(new NuggetedProject { IsSupported = false }); } try { return(new NuggetedProject(project)); } catch (Exception) { return(new NuggetedProject { IsValid = false }); } }
private static IReadOnlyDictionary <string, string> SwitchToProject(ReferenceSwitcherConfiguration configuration, ProjectInSolution solutionProject, ProjectInformation projectInformation, string packageName, string projectPath, IConsoleHost host) { var switchedProjects = new Dictionary <string, string>(); var project = projectInformation.Project; var projectDirectory = Path.GetFullPath(Path.GetDirectoryName(solutionProject.AbsolutePath)); foreach (var item in project.Items .Where(i => i.ItemType == "PackageReference" || i.ItemType == "Reference").ToList()) { var packageReference = item.EvaluatedInclude.Split(',').First().Trim(); if (packageReference == packageName) { var isPackageReference = (item.ItemType == "PackageReference"); var packageVersion = item.Metadata.SingleOrDefault(m => m.Name == "Version")?.EvaluatedValue ?? null; project.RemoveItem(item); project.AddItem("ProjectReference", PathUtilities.ToRelativePath(projectPath, projectDirectory)); SetRestoreProjectInformation(configuration, item, project.FullPath, isPackageReference, packageName, packageVersion); switchedProjects[solutionProject.AbsolutePath] = packageVersion; } } project.Save(); return(switchedProjects); }
private Assembly GetProjectAssembly(ProjectInSolution project) { var path = Path.GetDirectoryName(project.AbsolutePath); var fileName = project.ProjectName + ".dll"; var projectDlls = Directory.GetFiles(path, fileName, SearchOption.AllDirectories); if (projectDlls.Count() == 0) { return(null); } // else // { // fileName = project.ProjectName + ".exe"; // not sure how to make this work // projectDlls = Directory.GetFiles(path, fileName, SearchOption.AllDirectories); // } if (projectDlls.Count() == 0) { return(null); } //try //{ var result = Assembly.LoadFrom(projectDlls[0]); return(result); //} catch(Exception e) //{ // log? //return null; //} }
private Project( ProjectCollection projectCollection, ISolution solution, ProjectInSolution projectInSolution, Microsoft.Build.Evaluation.Project project, IMsBuildParsingConfiguration msBuildParsingConfiguration) { _projectCollection = projectCollection; Solution = solution; _msBuildParsingConfiguration = msBuildParsingConfiguration; Name = projectInSolution.ProjectName; BuildConfigurations = projectInSolution.ProjectConfigurations.Values.Select(c => new BuildConfiguration(c.ConfigurationName, c.PlatformName)).Distinct().ToArray(); Advanced = new AdvancedProject(this, project, projectInSolution); Guid = Guid.Parse(projectInSolution.ProjectGuid); NuGetPackages = BuildNuGetPackages(NuGetPackagesFile).ToArray(); _classifiedReferences = new Lazy <ClassifiedReferences>(() => ClassifyReferences(project, NuGetPackages, solution)); ProjectItems = BuildProjectItems(project.ItemsIgnoringCondition).ToArray(); ConfigurationProjectItem = BuildConfigurationProjectItem(); _projectXml = new Lazy <XDocument>(() => XDocument.Load(ProjectFile.FullName)); }
/// <summary> /// Writes the contents of a resx file (as key-value pairs) to project using the Android directory hierarchy and /// resource file standards. /// </summary> /// <param name="project"></param> /// <param name="strings"></param> /// <param name="sourceFile"></param> public static void WriteToTarget( ProjectInSolution project, IDictionary <string, string> strings, FileInfo sourceFile ) { // Generate the XML representation of the data var resourceType = sourceFile.GetResourceType(); // Bool resources must be lowercase ('true' not 'True') if (resourceType == ResourceType.Boolean) { strings = strings.ToDictionary(item => item.Key, item => item.Value.ToLower()); } // Create Android resource XML var content = GetXmlContent(resourceType, strings); // Setup output path and file name var outputFileName = $"{resourceType}s.xml"; var inputFileName = Path.GetFileNameWithoutExtension(sourceFile.Name); // Put translations in their appropriate directories (e.g. '/values-es/strings.xml') var valuesDir = "values/"; if ((resourceType == ResourceType.String) && !inputFileName.Equals("strings")) { valuesDir = $"values-{inputFileName}/"; } // Write to file, creating directories as necessary var targetDir = Path.Combine(project.ContainingDirectory(), $"resources/{valuesDir}"); FileHandler.WriteToFile(targetDir, outputFileName, content); }
/// <summary> /// Determines if the Project Type is Known Supported /// </summary> /// <param name="project">The project to evaluate.</param> /// <returns><c>true</c> if this project is supported by this tool; otherwise, <c>false</c>.</returns> private static bool IsSupportedProjectType(ProjectInSolution project) { bool supportedType = false; if (project.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat) { supportedType = true; } else { // You can add additional supported types here string[] knownMsBuildProjectTypes = new string[] { ".csproj", ".sqlproj", ".synproj", ".vbproj", }; string filePath = Path.GetExtension(project.AbsolutePath); supportedType = knownMsBuildProjectTypes.Any(knownProjectType => filePath.Equals(knownProjectType, System.StringComparison.InvariantCultureIgnoreCase)); } return(supportedType); }
private void ValidateProjectInSolution(Action <SlnProject, ProjectInSolution> customValidator, SlnProject[] projects, bool folders) { string solutionFilePath = GetTempFileName(); SlnFile slnFile = new SlnFile(); slnFile.AddProjects(projects); slnFile.Save(solutionFilePath, folders); SolutionFile solutionFile = SolutionFile.Parse(solutionFilePath); foreach (SlnProject slnProject in projects) { solutionFile.ProjectsByGuid.ContainsKey(slnProject.ProjectGuid.ToSolutionString()).ShouldBeTrue(); ProjectInSolution projectInSolution = solutionFile.ProjectsByGuid[slnProject.ProjectGuid.ToSolutionString()]; projectInSolution.AbsolutePath.ShouldBe(slnProject.FullPath); projectInSolution.ProjectGuid.ShouldBe(slnProject.ProjectGuid.ToSolutionString()); projectInSolution.ProjectName.ShouldBe(slnProject.Name); IEnumerable <string> configurationPlatforms = from configuration in slnProject.Configurations from platform in slnProject.Platforms select $"{configuration}|{platform}"; configurationPlatforms.ShouldBe(projectInSolution.ProjectConfigurations.Keys, ignoreOrder: true); customValidator?.Invoke(slnProject, projectInSolution); } }
private void ValidateProjectInSolution(Action <SlnProject, ProjectInSolution> customValidator, SlnProject[] projects, bool folders) { string solutionFilePath = GetTempFileName(); SlnFile slnFile = new SlnFile(); slnFile.AddProjects(projects); slnFile.Save(solutionFilePath, folders); SolutionFile solutionFile = SolutionFile.Parse(solutionFilePath); foreach (SlnProject slnProject in projects) { solutionFile.ProjectsByGuid.ContainsKey(slnProject.ProjectGuid.ToSolutionString()).ShouldBeTrue(); ProjectInSolution projectInSolution = solutionFile.ProjectsByGuid[slnProject.ProjectGuid.ToSolutionString()]; projectInSolution.AbsolutePath.ShouldBe(slnProject.FullPath); projectInSolution.ProjectGuid.ShouldBe(slnProject.ProjectGuid.ToSolutionString()); projectInSolution.ProjectName.ShouldBe(slnProject.Name); IEnumerable <string> expected = slnProject.Configurations.SelectMany(configuration => slnProject.Platforms, (configuration, platform) => $"{configuration}|{platform}"); IEnumerable <string> actual = projectInSolution.ProjectConfigurations.Where(i => i.Value.IncludeInBuild).Select(i => i.Key); expected.ShouldBe(actual, ignoreOrder: true); customValidator?.Invoke(slnProject, projectInSolution); } }
private static void AddPackage(ReferenceSwitcherConfiguration configuration, ProjectInSolution solutionProject, Project project, string packageName, string packageVersion) { var projectName = Path.GetFileNameWithoutExtension(solutionProject.AbsolutePath); var switchedProject = ( from r in configuration.Restore where string.Equals(r.Name, projectName, StringComparison.OrdinalIgnoreCase) select r).FirstOrDefault(); if (switchedProject != null) { var reference = switchedProject.GetSwitchedPackage(packageName); if (!string.IsNullOrEmpty(reference.Include)) { project.AddItem("Reference", reference.Include, reference.Metadata); } else { if (!project.Items.Any(i => i.ItemType == "PackageReference" && i.EvaluatedInclude == packageName)) // check that the reference is not already present { var items = project.AddItem("PackageReference", packageName, packageVersion == null ? Enumerable.Empty <KeyValuePair <string, string> >() : // this is the case if CentralPackageVersions is in use new[] { new KeyValuePair <string, string>("Version", packageVersion) }); items.ToList().ForEach(item => { item.Metadata?.ToList().ForEach(metadata => metadata.Xml.ExpressedAsAttribute = true); }); } } } }
private ProjectModel LoadProject(ProjectInSolution projectInfo) { XmlDocument doc = new XmlDocument(); doc.Load(projectInfo.AbsolutePath); ProjectModel model = new ProjectModel { Name = projectInfo.ProjectName, RelativePath = projectInfo.RelativePath, }; string projectDir = Path.GetDirectoryName(projectInfo.AbsolutePath); // note: all C# code files use the Compile task. foreach (XmlElement itemGroup in doc.GetElementsByTagName("ItemGroup", "*")) { foreach (XmlElement item in itemGroup.ChildNodes.OfType <XmlElement>() .Where(el => !IgnoreItems.Contains(el.LocalName))) { string path = item.GetAttribute("Include"); if (!string.IsNullOrWhiteSpace(path)) { AddItem(model, path, projectDir); } } } return(model); }
public static SolutionItem Parse(string solutionFilename) { SolutionFile solutionFile = SolutionFile.Parse(solutionFilename); List <ProjectItem> projects = solutionFile.ProjectsInOrder .Select(project => ProjectParser.Parse(project.AbsolutePath, project.ProjectGuid)).ToList(); Dictionary <ProjectItem, List <string> > projectContainer = new Dictionary <ProjectItem, List <string> >(); foreach (ProjectInSolution projectInSolution in solutionFile.ProjectsInOrder) { ProjectItem project = ProjectParser.Parse(projectInSolution.AbsolutePath, projectInSolution.ProjectGuid); List <string> dependencies = projectInSolution.Dependencies.ToList(); foreach (ProjectReferenceItem projectReference in project.ProjectReferences) { ProjectInSolution referredProject = solutionFile.ProjectsInOrder.FirstOrDefault(p => Path.Combine(p.AbsolutePath, p.ProjectName).ToLowerInvariant().Equals(Path .Combine(projectReference.AbsolutePath, projectReference.Name).ToLowerInvariant())); if (referredProject != null && !dependencies.Contains(referredProject.ProjectGuid)) { dependencies.Add(referredProject.ProjectGuid); } } projectContainer.Add(project, dependencies); } return(new SolutionItem(ResolveBuildOrder(projectContainer))); }
public void UpdateProject(ProjectInSolution project) { FileContent = FileContent.ReplaceIgnoreCase( project.RawValue, string.Format(ProjectFormat, project.TypeGuid, project.ProjectName, project.RelativePath, project.Guid, project.Content)); }
public AdvancedProject(Project project, Microsoft.Build.Evaluation.Project msBuildProject, ProjectInSolution msBuildProjectInSolution) { MsBuildProjectInSolution = msBuildProjectInSolution; _project = project; MsBuildProject = msBuildProject; Properties = ProcessProperties(MsBuildProject.Xml.Properties); }
static bool IsSupportedSolutionItemType(ProjectInSolution project) { if (project.ProjectType != SolutionProjectType.KnownToBeMSBuildFormat && project.ProjectType != SolutionProjectType.SolutionFolder) { Console.WriteLine($"{project.AbsolutePath} is not a supported solution item and will be skipped."); } return(project.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat); }
public void ProjectSolutionFolders() { string root = Path.GetTempPath(); string projectName1 = Path.GetFileName(Path.GetTempFileName()); string projectName2 = Path.GetFileName(Path.GetTempFileName()); string projectName3 = Path.GetFileName(Path.GetTempFileName()); string projectName4 = Path.GetFileName(Path.GetTempFileName()); Project[] projects = { new Project { FullPath = Path.Combine(root, "SubFolder1", "Project1", projectName1), }, new Project { FullPath = Path.Combine(root, "SubFolder2", "Project2", projectName2), }, new Project { FullPath = Path.Combine(root, "SubFolder3", "Project3", projectName3), }, new Project { FullPath = Path.Combine(root, "SubFolder4", "Project4", projectName4), }, }; projects[0].SetProperty(MSBuildPropertyNames.SlnGenSolutionFolder, "FolderA"); projects[1].SetProperty(MSBuildPropertyNames.SlnGenSolutionFolder, "FolderB"); projects[2].SetProperty(MSBuildPropertyNames.SlnGenSolutionFolder, "FolderB"); string solutionFilePath = GetTempFileName(); SlnFile slnFile = new SlnFile(); slnFile.AddProjects(projects, new Dictionary <string, Guid>(), projects[1].FullPath); slnFile.Save(solutionFilePath, useFolders: false); SolutionFile s = SolutionFile.Parse(solutionFilePath); ProjectInSolution project1 = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals(Path.GetFileNameWithoutExtension(projectName1))).Value; ProjectInSolution project2 = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals(Path.GetFileNameWithoutExtension(projectName2))).Value; ProjectInSolution project3 = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals(Path.GetFileNameWithoutExtension(projectName3))).Value; ProjectInSolution project4 = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals(Path.GetFileNameWithoutExtension(projectName4))).Value; ProjectInSolution folderA = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals("FolderA")).Value; ProjectInSolution folderB = s.ProjectsByGuid.FirstOrDefault(i => i.Value.ProjectName.Equals("FolderB")).Value; project1.ParentProjectGuid.ShouldBe(folderA.ProjectGuid); project2.ParentProjectGuid.ShouldBe(folderB.ProjectGuid); project3.ParentProjectGuid.ShouldBe(folderB.ProjectGuid); project4.ParentProjectGuid.ShouldBeNull(); folderA.ProjectType.ShouldBe(SolutionProjectType.SolutionFolder); folderB.ProjectType.ShouldBe(SolutionProjectType.SolutionFolder); }
private static string GetAbsoluteFilePath(ProjectInSolution project) { var path = project.AbsolutePath; if (string.IsNullOrEmpty(path)) { path = project.ProjectName; } return(path); }
private static ProjectPoco ComposeProjectPoco(ProjectInSolution x) { try { return(ProjectFileParser.Parse(x.AbsolutePath)); } catch (Exception e) { throw new ApplicationException($"error parsing project [{x.ProjectName}] -- [{x.AbsolutePath}]", e); } }
static void Action(SlnProject slnProject, ProjectInSolution projectInSolution) { if (slnProject.IsMainProject) { projectInSolution.ParentProjectGuid.ShouldBeNull(); } else { projectInSolution.ParentProjectGuid.ShouldNotBeNull(); } }
private void AddProjectDependecies(SolutionProject leaf, ProjectInSolution project) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(project.AbsolutePath); foreach (XmlElement projectReference in xmlDoc.GetElementsByTagName("ProjectReference")) { var dependency = Path.GetFileNameWithoutExtension(projectReference.GetAttribute("Include")); leaf.Dependencies.Add(dependency); } }
public static string ContainingDirectory(this ProjectInSolution project) { var path = project.AbsolutePath; var index = path.LastIndexOfAny(new[] { '/', '\\' }); if (Path.DirectorySeparatorChar == '/') { path = path.Replace('\\', '/'); } return(path.Substring(0, index + 1)); }
private void ValidateSolutionPlatformAndConfiguration(SlnProject project, SolutionFile solutionFile, string expectedConfiguration, string expectedPlatform, bool expectedIncludeInBuild = true) { ProjectInSolution projectInSolution = solutionFile.ProjectsByGuid[project.ProjectGuid.ToSolutionString()]; projectInSolution.AbsolutePath.ShouldBe(project.FullPath); ProjectConfigurationInSolution projectConfigurationInSolution = projectInSolution.ProjectConfigurations.ShouldHaveSingleItem().Value; projectConfigurationInSolution.ConfigurationName.ShouldBe(expectedConfiguration); projectConfigurationInSolution.PlatformName.ShouldBe(expectedPlatform); projectConfigurationInSolution.IncludeInBuild.ShouldBe(expectedIncludeInBuild); }
private static void HandleProject( ProjectInSolution solutionProject, ISet <string> allProjectsInSolution, Parameters parameters) { if (!File.Exists(solutionProject.AbsolutePath)) { Console.Out.WriteLine($"Project '{solutionProject.AbsolutePath}' doesn't exists."); return; } Console.Out.WriteLine($"Working with project '{solutionProject.ProjectName}'.."); var project = Project.FromFile(solutionProject.AbsolutePath, new ProjectOptions { LoadSettings = ProjectLoadSettings.IgnoreMissingImports }); if (ShouldIgnore(project)) { Console.Out.WriteLine( $"Ignore project '{solutionProject.ProjectName}' due to DotnetCementRefsExclude property in csproj."); return; } var references = FindProjectReferences(project); if (!references.Any()) { Console.Out.WriteLine($"No references found in project {solutionProject.ProjectName}."); return; } Console.Out.WriteLine( $"Found references in {solutionProject.ProjectName}: {Environment.NewLine}\t{string.Join(Environment.NewLine + "\t", references.Select(item => item.EvaluatedInclude))}"); Console.Out.WriteLine(); var version = project.GetProperty("Version"); Console.Out.WriteLine($"Future version of all NuGet packages is '{version}'"); Console.Out.WriteLine(); foreach (var reference in references) { HandleProjectReference(project, reference, version.EvaluatedValue, parameters); } project.Save(); Console.Out.WriteLine(); }
public static bool Validate(string fullPath) { SolutionFile file = Parse(fullPath); ProjectInSolution project = file.ProjectsInOrder.FirstOrDefault(x => x.RelativePath.Contains("..")); if (project != null) { return(false); } return(true); }
private static IReadOnlyList <(string ProjectPath, string PackageVersion)> SwitchToPackage( ReferenceSwitcherConfiguration configuration, ProjectInSolution solutionProject, ProjectInformation projectInformation, List <string> switchedProjectPaths, string switchedPackageName, List <string> mappedProjectFilePaths, IConsoleHost host) { var switchedProjects = new List <(string ProjectPath, string PackageVersion)>(); var absoluteProjectPaths = switchedProjectPaths.Select(p => PathUtilities.ToAbsolutePath(p, Directory.GetCurrentDirectory())).ToList(); var project = projectInformation.Project; var projectName = Path.GetFileNameWithoutExtension(solutionProject.AbsolutePath); var projectFileName = Path.GetFileName(solutionProject.AbsolutePath); var projectDirectory = Path.GetDirectoryName(solutionProject.AbsolutePath); // do not modify mapped projects unless we are always keeping them in the solution if (!mappedProjectFilePaths.Contains(projectFileName) || !configuration.RemoveProjects) { var restoreProjectInformation = ( from r in configuration.Restore where string.Equals(r.Name, projectName, StringComparison.OrdinalIgnoreCase) select r).FirstOrDefault(); if (restoreProjectInformation != null) { var count = 0; var matchingProjectReferences = project.Items.Where ( i => i.ItemType == "ProjectReference" && absoluteProjectPaths.Contains(PathUtilities.ToAbsolutePath(i.EvaluatedInclude, projectDirectory)) ).ToList(); foreach (var item in matchingProjectReferences) { project.RemoveItem(item); var packageVersion = GetPackageVersion(restoreProjectInformation, switchedPackageName); AddPackage(configuration, solutionProject, project, switchedPackageName, packageVersion); switchedProjects.Add((solutionProject.AbsolutePath, packageVersion)); count++; } if (count > 0) { ProjectExtensions.SaveWithLineEndings(projectInformation); } } } return(switchedProjects); }
private static void HandleProject(ProjectInSolution solutionProject) { if (!File.Exists(solutionProject.AbsolutePath)) { Console.Out.WriteLine($"Project '{solutionProject.AbsolutePath}' doesn't exists."); return; } Console.Out.WriteLine($"Working with project '{solutionProject.ProjectName}'.."); var projectRoot = ProjectRootElement.Open(solutionProject.AbsolutePath, ProjectCollection.GlobalProjectCollection, true); var project = Project.FromProjectRootElement(projectRoot, new ProjectOptions { LoadSettings = ProjectLoadSettings.IgnoreMissingImports }); var version = project.GetPropertyValue("VersionPrefix"); var changelog = File.ReadAllText("CHANGELOG.md"); if (!changelog.Contains($@"## {version} (")) { throw new Exception($"Describe changes for version {version} in CHANGELOG.md before release!"); } var latestNugetVersion = GetLatestNugetVersion(solutionProject.ProjectName, false); if (latestNugetVersion != null && latestNugetVersion.Version >= Version.Parse(version)) { throw new Exception($"Bump version first. Version {latestNugetVersion.Version.ToShortString()} found on nuget.org"); } Console.Out.WriteLine($"Release version {version}."); Exec("git tag release/" + version).exitCode.EnsureSuccess(); Exec("git push origin release/" + version).exitCode.EnsureSuccess(); var oldVersion = Version.Parse(version); var newVersion = new Version(oldVersion.Major, oldVersion.Minor, oldVersion.Build + 1, 0) .ToShortString(); Console.Out.WriteLine($"Bump version in csproj to {newVersion}."); project.SetProperty("VersionPrefix", newVersion); project.Save(); Exec($@"git add ""{solutionProject.ProjectName}""").exitCode.EnsureSuccess(); Exec($@"git commit -m ""Bumped version to {newVersion}"".").exitCode.EnsureSuccess(); Exec("git push").exitCode.EnsureSuccess(); Console.Out.WriteLine(); }
public ProjectView(SolutionView sol, ProjectInSolution sp) { solutionProject = sp; solution = sol; ProjectRootElement projectRootElt = ProjectRootElement.Open(solutionProject.AbsolutePath); project = new Project(solutionProject.AbsolutePath, null, null, sol.IDE.projectCollection); string [] props = { "EnableDefaultItems", "EnableDefaultCompileItems", "EnableDefaultNoneItems", "EnableDefaultEmbeddedResourceItems" }; foreach (string pr in props) { ProjectProperty pp = project.AllEvaluatedProperties.Where(ep => ep.Name == pr).FirstOrDefault(); if (pp == null) { project.SetGlobalProperty(pr, "true"); } } //ide.projectCollection.SetGlobalProperty ("DefaultItemExcludes", "obj/**/*;bin/**/*"); project.ReevaluateIfNecessary(); cmdSave = new Crow.Command(new Action(() => Save())) { Caption = "Save", Icon = new SvgPicture("#Icons.save.svg"), CanExecute = true }; cmdOpen = new Crow.Command(new Action(() => populateTreeNodes())) { Caption = "Open", Icon = new SvgPicture("#Icons.open.svg"), CanExecute = false }; cmdCompile = new Crow.Command(new Action(() => Compile("Restore"))) { Caption = "Restore", }; cmdSetAsStartProj = new Crow.Command(new Action(() => setAsStartupProject())) { Caption = "Set as Startup Project" }; cmdNewFile = new Crow.Command(new Action(() => AddNewFile())) { Caption = "Add New File", Icon = new SvgPicture("#Icons.blank-file.svg"), CanExecute = true }; Commands = new ObservableList <Crow.Command> (new Crow.Command [] { cmdOpen, cmdSave, cmdSetAsStartProj, cmdCompile, cmdNewFile }); populateTreeNodes(); }
private static List <CsClass> ParseProjectRoot(ProjectInSolution solutionProject, ProjectRootElement projectRoot) { var csFiles = projectRoot.AllChildren.OfType <ProjectItemElement>().Where(x => x.ItemType.Equals("Compile")); var projectClasses = new List <CsClass>(); foreach (var csFile in csFiles) { var csFileClasses = ParseCsFile(solutionProject, csFile); projectClasses.AddRange(csFileClasses); } return(projectClasses); }
private static List <string> GetParentFolderChain(SolutionFile solutionFile, ProjectInSolution project) { var parentFolderChain = new List <string>(); var parentGuid = project.ParentProjectGuid; while (!string.IsNullOrEmpty(parentGuid) && solutionFile.ProjectsByGuid.TryGetValue(parentGuid, out ProjectInSolution parentFolder) && parentFolder != null) { parentFolderChain.Add(parentFolder.ProjectName); parentGuid = parentFolder.ParentProjectGuid; } parentFolderChain.Reverse(); return(parentFolderChain); }
private static List <CsClass> ParseCsFile(ProjectInSolution solutionProject, ProjectItemElement csFile) { var filePath = csFile.Include; var fileAbsolutePath = Path.Combine(Path.GetDirectoryName(solutionProject.AbsolutePath), filePath); var source = File.ReadAllText(fileAbsolutePath); SyntaxTree projectSyntaxTree = CSharpSyntaxTree.ParseText(source); var projectTree = (CompilationUnitSyntax)projectSyntaxTree.GetRoot(); var namespaceTree = projectTree.Members.OfType <NamespaceDeclarationSyntax>().SingleOrDefault(); var csFileClasses = new List <CsClass>(); if (namespaceTree == null) { return(csFileClasses); } foreach (var classTree in namespaceTree.Members.OfType <ClassDeclarationSyntax>()) { if (classTree.BaseList?.Types == null) { continue; } foreach (var baseType in classTree.BaseList?.Types.OfType <SimpleBaseTypeSyntax>()) { var props = classTree.Members.OfType <PropertyDeclarationSyntax>() .Select(x => new CsProperty() { Name = x.Identifier.ToString(), Type = x.Type.ToString() }); var methods = classTree.Members.OfType <MethodDeclarationSyntax>() .Select(x => ParseMethod(x)); var csClass = new CsClass() { Name = classTree.Identifier.ToString(), ParentName = baseType?.Type.ToString(), Properties = props, Methods = methods }; csFileClasses.Add(csClass); } } return(csFileClasses); }
internal void ParseEtpProject(ProjectInSolution etpProj) { XmlDocument xmlDocument = new XmlDocument(); string filename = Path.Combine(this.solutionFileDirectory, etpProj.RelativePath); string directoryName = Path.GetDirectoryName(etpProj.RelativePath); try { xmlDocument.Load(filename); foreach (XmlNode xmlNode1 in xmlDocument.DocumentElement.SelectNodes("/EFPROJECT/GENERAL/References/Reference")) { string innerText = xmlNode1.SelectSingleNode("FILE").InnerText; if (innerText != null) { ProjectInSolution projectInSolution1 = new ProjectInSolution(this); projectInSolution1.RelativePath = Path.Combine(directoryName, innerText); this.ValidateProjectRelativePath(projectInSolution1); projectInSolution1.ProjectType = SolutionProjectType.EtpSubProject; ProjectInSolution projectInSolution2 = projectInSolution1; string relativePath = projectInSolution2.RelativePath; projectInSolution2.ProjectName = relativePath; XmlNode xmlNode2 = xmlNode1.SelectSingleNode("GUIDPROJECTID"); projectInSolution1.ProjectGuid = xmlNode2 == null ? string.Empty : xmlNode2.InnerText; this.AddProjectToSolution(projectInSolution1); if (this.IsEtpProjectFile(innerText)) this.ParseEtpProject(projectInSolution1); } } } catch (SecurityException ex) { string code; string helpKeyword; this.solutionParserWarnings.Add((object) ResourceUtilities.FormatResourceString(out code, out helpKeyword, "Shared.ProjectFileCouldNotBeLoaded", (object) etpProj.RelativePath, (object) ex.Message)); this.solutionParserErrorCodes.Add((object) code); } catch (NotSupportedException ex) { string code; string helpKeyword; this.solutionParserWarnings.Add((object) ResourceUtilities.FormatResourceString(out code, out helpKeyword, "Shared.ProjectFileCouldNotBeLoaded", (object) etpProj.RelativePath, (object) ex.Message)); this.solutionParserErrorCodes.Add((object) code); } catch (IOException ex) { string code; string helpKeyword; this.solutionParserWarnings.Add((object) ResourceUtilities.FormatResourceString(out code, out helpKeyword, "Shared.ProjectFileCouldNotBeLoaded", (object) etpProj.RelativePath, (object) ex.Message)); this.solutionParserErrorCodes.Add((object) code); } catch (UnauthorizedAccessException ex) { string code; string helpKeyword; this.solutionParserWarnings.Add((object) ResourceUtilities.FormatResourceString(out code, out helpKeyword, "Shared.ProjectFileCouldNotBeLoaded", (object) etpProj.RelativePath, (object) ex.Message)); this.solutionParserErrorCodes.Add((object) code); } catch (XmlException ex) { string code; string helpKeyword; this.solutionParserWarnings.Add((object) ResourceUtilities.FormatResourceString(out code, out helpKeyword, "Shared.InvalidProjectFile", (object) etpProj.RelativePath, (object) ex.Message)); this.solutionParserErrorCodes.Add((object) code); } }
private void AddProjectToSolution(ProjectInSolution proj) { if (!string.IsNullOrEmpty(proj.ProjectGuid)) this.projects[(object) proj.ProjectGuid] = (object) proj; this.projectsInOrder.Add((object) proj); }
private void ValidateProjectRelativePath(ProjectInSolution proj) { ErrorUtilities.VerifyThrow(proj.RelativePath != null, "Project relative path cannot be null."); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile((proj.RelativePath.IndexOfAny(Path.GetInvalidPathChars()) == -1 ? 1 : 0) != 0, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile, this.currentLineNumber, 0), "SolutionParseInvalidProjectFileNameCharacters", new object[2] { (object) proj.ProjectName, (object) proj.RelativePath }); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile((proj.RelativePath.Length > 0 ? 1 : 0) != 0, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile, this.currentLineNumber, 0), "SolutionParseInvalidProjectFileNameEmpty", (object) proj.ProjectName); }
private void ParseAspNetCompilerProperty(ProjectInSolution proj, string propertyName, string propertyValue) { int length = propertyName.IndexOf('.'); if (length != -1) { string str1 = propertyName.Substring(0, length); string str2 = propertyName.Length - length > 0 ? propertyName.Substring(length + 1, propertyName.Length - length - 1) : ""; propertyValue = this.TrimQuotes(propertyValue); object obj = proj.AspNetConfigurations[(object) str1]; AspNetCompilerParameters compilerParameters; if (obj == null) { compilerParameters = new AspNetCompilerParameters(); compilerParameters.aspNetVirtualPath = string.Empty; compilerParameters.aspNetPhysicalPath = string.Empty; compilerParameters.aspNetTargetPath = string.Empty; compilerParameters.aspNetForce = string.Empty; compilerParameters.aspNetUpdateable = string.Empty; compilerParameters.aspNetDebug = string.Empty; compilerParameters.aspNetKeyFile = string.Empty; compilerParameters.aspNetKeyContainer = string.Empty; compilerParameters.aspNetDelaySign = string.Empty; compilerParameters.aspNetAPTCA = string.Empty; compilerParameters.aspNetFixedNames = string.Empty; } else compilerParameters = (AspNetCompilerParameters) obj; if (str2 == "AspNetCompiler.VirtualPath") compilerParameters.aspNetVirtualPath = propertyValue; else if (str2 == "AspNetCompiler.PhysicalPath") compilerParameters.aspNetPhysicalPath = propertyValue; else if (str2 == "AspNetCompiler.TargetPath") compilerParameters.aspNetTargetPath = propertyValue; else if (str2 == "AspNetCompiler.ForceOverwrite") compilerParameters.aspNetForce = propertyValue; else if (str2 == "AspNetCompiler.Updateable") compilerParameters.aspNetUpdateable = propertyValue; else if (str2 == "AspNetCompiler.Debug") compilerParameters.aspNetDebug = propertyValue; else if (str2 == "AspNetCompiler.KeyFile") compilerParameters.aspNetKeyFile = propertyValue; else if (str2 == "AspNetCompiler.KeyContainer") compilerParameters.aspNetKeyContainer = propertyValue; else if (str2 == "AspNetCompiler.DelaySign") compilerParameters.aspNetDelaySign = propertyValue; else if (str2 == "AspNetCompiler.AllowPartiallyTrustedCallers") compilerParameters.aspNetAPTCA = propertyValue; else if (str2 == "AspNetCompiler.FixedNames") compilerParameters.aspNetFixedNames = propertyValue; proj.AspNetConfigurations[(object) str1] = (object) compilerParameters; } else if (string.Compare(propertyName, "ProjectReferences", StringComparison.OrdinalIgnoreCase) == 0) { string str1 = propertyValue; char[] separator = new char[1] { ';' }; int num1 = 1; foreach (string str2 in str1.Split(separator, (StringSplitOptions) num1)) { if (str2.IndexOf('|') != -1) { int startIndex = str2.IndexOf('{'); if (startIndex != -1) { int num2 = str2.IndexOf('}', startIndex); if (num2 != -1) { string str3 = str2.Substring(startIndex, num2 - startIndex + 1); proj.Dependencies.Add((object) str3); proj.ProjectReferences.Add((object) str3); } } } } } else { if (string.Compare(propertyName, "TargetFrameworkMoniker", StringComparison.OrdinalIgnoreCase) != 0) return; string escapedString = this.TrimQuotes(propertyValue); proj.TargetFrameworkMoniker = EscapingUtilities.UnescapeAll(escapedString); } }
internal void ParseFirstProjectLine(string firstLine, ProjectInSolution proj) { Match match = SolutionParser.crackProjectLine.Match(firstLine); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(match.Success, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile, this.currentLineNumber, 0), "SolutionParseProjectError", new object[0]); string strA = match.Groups["PROJECTTYPEGUID"].Value.Trim(); proj.ProjectName = match.Groups["PROJECTNAME"].Value.Trim(); proj.RelativePath = match.Groups["RELATIVEPATH"].Value.Trim(); proj.ProjectGuid = match.Groups["PROJECTGUID"].Value.Trim(); this.ValidateProjectRelativePath(proj); if (string.Compare(strA, "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", StringComparison.OrdinalIgnoreCase) == 0 || (string.Compare(strA, "{F2A71F9B-5D33-465A-A702-920D77279786}", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "{C8D11400-126E-41CD-887F-60BD40844F9E}", StringComparison.OrdinalIgnoreCase) == 0) || string.Compare(strA, "{E6FDF86B-F3D1-11D4-8576-0002A516ECE8}", StringComparison.OrdinalIgnoreCase) == 0) proj.ProjectType = SolutionProjectType.KnownToBeMSBuildFormat; else if (string.Compare(strA, "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", StringComparison.OrdinalIgnoreCase) == 0) proj.ProjectType = SolutionProjectType.SolutionFolder; else if (string.Compare(strA, "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", StringComparison.OrdinalIgnoreCase) == 0) { if (string.Equals(proj.Extension, ".vcxproj", StringComparison.OrdinalIgnoreCase)) { proj.ProjectType = SolutionProjectType.KnownToBeMSBuildFormat; } else { if (this.parsingForConversionOnly) return; ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(this.SolutionFile), "ProjectUpgradeNeededToVcxProj", (object) proj.RelativePath); } } else if (string.Compare(strA, "{E24C65DC-7377-472B-9ABA-BC803B73C61A}", StringComparison.OrdinalIgnoreCase) == 0) { proj.ProjectType = SolutionProjectType.WebProject; this.solutionContainsWebProjects = true; } else if (string.Compare(strA, "{2CFEAB61-6A3B-4EB8-B523-560B4BEEF521}", StringComparison.OrdinalIgnoreCase) == 0) { proj.ProjectType = SolutionProjectType.WebDeploymentProject; this.solutionContainsWebDeploymentProjects = true; } else proj.ProjectType = SolutionProjectType.Unknown; }
private void ParseProject(string firstLine) { ErrorUtilities.VerifyThrow(firstLine != null && (uint) firstLine.Length > 0U, "ParseProject() got a null firstLine!"); ErrorUtilities.VerifyThrow(this.reader != null, "ParseProject() got a null reader!"); ProjectInSolution projectInSolution = new ProjectInSolution(this); this.ParseFirstProjectLine(firstLine, projectInSolution); label_10: string str1; while ((str1 = this.ReadLine()) != null && !(str1 == "EndProject")) { if (str1.StartsWith("ProjectSection(ProjectDependencies)", StringComparison.Ordinal)) { string input = this.ReadLine(); while (true) { if (input != null && !input.StartsWith("EndProjectSection", StringComparison.Ordinal)) { Match match = SolutionParser.crackPropertyLine.Match(input); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile((match.Success ? 1 : 0) != 0, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile, this.currentLineNumber, 0), "SolutionParseProjectDepGuidError", (object) projectInSolution.ProjectName); string str2 = match.Groups["PROPERTYNAME"].Value.Trim(); projectInSolution.Dependencies.Add((object) str2); input = this.ReadLine(); } else goto label_10; } } else if (str1.StartsWith("ProjectSection(WebsiteProperties)", StringComparison.Ordinal)) { string input = this.ReadLine(); while (true) { if (input != null && !input.StartsWith("EndProjectSection", StringComparison.Ordinal)) { Match match = SolutionParser.crackPropertyLine.Match(input); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile((match.Success ? 1 : 0) != 0, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile, this.currentLineNumber, 0), "SolutionParseWebProjectPropertiesError", (object) projectInSolution.ProjectName); string propertyName = match.Groups["PROPERTYNAME"].Value.Trim(); string propertyValue = match.Groups["PROPERTYVALUE"].Value.Trim(); this.ParseAspNetCompilerProperty(projectInSolution, propertyName, propertyValue); input = this.ReadLine(); } else goto label_10; } } } ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile((str1 != null ? 1 : 0) != 0, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(this.SolutionFile), "SolutionParseProjectEofError", (object) projectInSolution.ProjectName); if (projectInSolution == null) return; this.AddProjectToSolution(projectInSolution); if (!this.IsEtpProjectFile(projectInSolution.RelativePath)) return; this.ParseEtpProject(projectInSolution); }