private async Task UpgradeProjectPackagesAsync(IConsoleHost host, string projectPath, Regex packageRegex, string version) { try { using (var projectInformation = ProjectExtensions.LoadProject(projectPath)) { var packages = projectInformation.Project.Items .Where(i => i.ItemType == "PackageReference" && packageRegex.IsMatch(i.EvaluatedInclude) && i.EvaluatedInclude != "Microsoft.NETCore.App") .Select(i => i.EvaluatedInclude) .ToList(); foreach (var package in packages) { await ExecuteCommandAsync("dotnet add \"" + projectPath + "\" package \"" + package + "\"" + (version != null ? " -v " + version : ""), host); } } } catch (Exception e) { host.WriteError(e + "\n"); } }
public void GetTargetFrameworkForXnaProjectReturnsWindowsPhoneTargetFramework() { // Arrange var project = new Mock <Project>(); var xnaProperty = new Mock <Property>(); xnaProperty.Setup(x => x.Value).Returns("Windows Phone OS 7.1"); project.Setup(p => p.Properties.Item(It.Is <object>(v => "Microsoft.Xna.GameStudio.CodeProject.WindowsPhoneProjectPropertiesExtender.XnaRefreshLevel".Equals(v)))) .Returns(xnaProperty.Object); var fxProperty = new Mock <Property>(); fxProperty.Setup(x => x.Value).Returns(".NETFramework,Version=v4.0"); project.Setup(p => p.Properties.Item(It.Is <object>(v => "TargetFrameworkMoniker".Equals(v)))) .Returns(fxProperty.Object); // Act string targetFramework = ProjectExtensions.GetTargetFramework(project.Object); // Assert Assert.Equal("Silverlight,Version=v4.0,Profile=WindowsPhone71", targetFramework); }
public void GetTargetFrameworkForWrongTargetFrameowrkVersionInXnaProjectDoesNotReturnWindowsPhoneTargetFramework(string framework) { // Arrange var project = new Mock <Project>(); var xnaProperty = new Mock <Property>(); xnaProperty.Setup(x => x.Value).Returns("Windows Phone OS 7.1"); project.Setup(p => p.Properties.Item(It.Is <object>(v => "Microsoft.Xna.GameStudio.CodeProject.WindowsPhoneProjectPropertiesExtender.XnaRefreshLevel".Equals(v)))) .Returns(xnaProperty.Object); var fxProperty = new Mock <Property>(); fxProperty.Setup(x => x.Value).Returns(framework); project.Setup(p => p.Properties.Item(It.Is <object>(v => "TargetFrameworkMoniker".Equals(v)))) .Returns(fxProperty.Object); // Act string targetFramework = ProjectExtensions.GetTargetFramework(project.Object); // Assert Assert.Equal(framework, targetFramework); }
private static void SetMsBuildExePath() { try { // See https://github.com/Microsoft/msbuild/issues/2532#issuecomment-381096259 var process = Process.Start(new ProcessStartInfo("dotnet", "--list-sdks") { UseShellExecute = false, RedirectStandardOutput = true }); process.WaitForExit(1000); var output = process.StandardOutput.ReadToEnd(); var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]").OfType <Match>() .Select(m => Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll")); var sdkPath = sdkPaths.LastOrDefault() ?? Path.Combine(ProjectExtensions.GetToolsPath(), "msbuild.exe"); Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath); } catch (Exception exception) { ConsoleUtilities.Write("Could not set MSBUILD_EXE_PATH: " + exception + "\n\n"); } }
private async Task CompileProject(IConsole console, IStandardProject superProject, IStandardProject project, List <CompileResult> results = null) { if (project == superProject) { superProject.ToolChain?.ProvisionSettings(project); } if (project.Type == ProjectType.Executable && superProject != project) { await Build(console, project); } else { if (!terminateBuild) { if (results == null) { results = new List <CompileResult>(); } foreach (var reference in project.References) { var standardReference = reference as IStandardProject; if (standardReference != null) { await CompileProject(console, superProject, standardReference, results); } } var outputDirectory = project.GetOutputDirectory(superProject); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } var doWork = false; lock (resultLock) { if (!project.IsBuilding) { project.IsBuilding = true; doWork = true; } } if (doWork) { var objDirectory = project.GetObjectDirectory(superProject); if (!Directory.Exists(objDirectory)) { Directory.CreateDirectory(objDirectory); } var compileResults = new CompileResult(); compileResults.Project = project; results.Add(compileResults); var tasks = new List <Task>(); var numLocalTasks = 0; var sourceFiles = project.SourceFiles.ToList(); foreach (var file in sourceFiles) { if (terminateBuild) { break; } if (SupportsFile(file)) { var outputName = Path.GetFileNameWithoutExtension(file.Location) + ".o"; var dependencyFile = Path.Combine(objDirectory, Path.GetFileNameWithoutExtension(file.Location) + ".d"); var objectFile = Path.Combine(objDirectory, outputName); var dependencyChanged = false; if (System.IO.File.Exists(dependencyFile)) { var dependencies = new List <string>(); dependencies.AddRange(ProjectExtensions.GetDependencies(dependencyFile)); foreach (var dependency in dependencies) { if (!System.IO.File.Exists(dependency) || System.IO.File.GetLastWriteTime(dependency) > System.IO.File.GetLastWriteTime(objectFile)) { dependencyChanged = true; break; } } } if (dependencyChanged || !System.IO.File.Exists(objectFile)) { while (numTasks >= Jobs) { Thread.Yield(); } lock (resultLock) { numLocalTasks++; numTasks++; console.OverWrite(string.Format("[CC {0}/{1}] [{2}] {3}", ++buildCount, fileCount, project.Name, Path.GetFileName(file.Location))); } new Thread(() => { var compileResult = Compile(console, superProject, project, file, objectFile); lock (resultLock) { if (compileResults.ExitCode == 0 && compileResult.ExitCode != 0) { terminateBuild = true; compileResults.ExitCode = compileResult.ExitCode; } else { compileResults.ObjectLocations.Add(objectFile); compileResults.NumberOfObjectsCompiled++; } numTasks--; numLocalTasks--; } }).Start(); } else { buildCount++; compileResults.ObjectLocations.Add(objectFile); } } } } } } }
protected void CreateAppStartFiles(string configFileName, string productNamespace) { string str = configFileName; int num = 2; while (true) { Project activeProject = this.Context.ActiveProject; CodeType codeType = this.CodeTypeService.GetCodeType(activeProject, string.Concat(ProjectExtensions.GetDefaultNamespace(activeProject), ".", configFileName)); string str1 = string.Concat(configFileName, ".", ProjectExtensions.GetCodeLanguage(this.Context.ActiveProject).CodeFileExtension); string str2 = Path.Combine(ProjectExtensions.GetFullPath(this.Context.ActiveProject), "App_Start", str1); if (!File.Exists(Path.Combine(ProjectExtensions.GetFullPath(this.Context.ActiveProject), "App_Start", str1)) && codeType == null) { this.AppStartFileNames.Add(str, configFileName); this.GenerateT4File(str, configFileName, "App_Start"); return; } if (codeType != null && !codeType.Name.StartsWith("BundleConfig", StringComparison.OrdinalIgnoreCase) && CodeTypeFilter.IsProductNamespaceImported(codeType, productNamespace)) { this.AppStartFileNames.Add(str, configFileName); return; } if (codeType != null && codeType.Name.StartsWith("BundleConfig", StringComparison.OrdinalIgnoreCase) && AddDependencyUtil.IsSearchTextPresent(str2, "ScriptBundle(\"~/bundles/jquery\")")) { break; } configFileName = string.Concat(str, num); num++; } this.AppStartFileNames.Add(str, configFileName); }
protected override void CreateStaticFilesAndFolders() { base.CreateStaticFilesAndFolders(); base.ActionsService.AddFolder(base.Context.ActiveProject, "Models"); if (!base.Context.Items.ContainsProperty("MVC_IsControllersFolderCreated") && !Directory.Exists(Path.Combine(ProjectExtensions.GetFullPath(base.Context.ActiveProject), "Controllers"))) { base.Context.Items.AddProperty("MVC_IsControllersFolderCreated", true); } base.ActionsService.AddFolder(base.Context.ActiveProject, "Controllers"); base.ActionsService.AddFolder(base.Context.ActiveProject, "Views"); }
private async Task CompileProject(IConsole console, IStandardProject superProject, IStandardProject project, List <CompileResult> results = null) { if (project.Type == ProjectType.Executable && superProject != project) { if (project.ToolChain == null) { terminateBuild = true; console.WriteLine($"Project: {project.Name} does not have a toolchain set."); } await project.ToolChain?.Build(console, project); } else { if (!terminateBuild) { if (results == null) { results = new List <CompileResult>(); } foreach (var reference in project.References) { var standardReference = reference as IStandardProject; if (standardReference != null) { await CompileProject(console, superProject, standardReference, results); } } var outputDirectory = project.GetOutputDirectory(superProject); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } var doWork = false; lock (resultLock) { if (!project.IsBuilding) { project.IsBuilding = true; doWork = true; } } if (doWork) { var objDirectory = project.GetObjectDirectory(superProject); if (!Directory.Exists(objDirectory)) { Directory.CreateDirectory(objDirectory); } var compileResults = new CompileResult(); compileResults.Project = project; results.Add(compileResults); var tasks = new List <Task>(); var sourceFiles = project.SourceFiles.ToList(); _statusBar?.SetText($"Building Project: {project.Name}"); foreach (var file in sourceFiles) { if (terminateBuild) { break; } if (SupportsFile(file)) { var outputName = Path.ChangeExtension(file.Name, ".o"); var objectPath = Path.Combine(objDirectory, project.CurrentDirectory.MakeRelativePath(file.CurrentDirectory)); var objectFile = Path.Combine(objectPath, outputName); var dependencyFile = Path.ChangeExtension(objectFile, ".d"); if (!Directory.Exists(objectPath)) { Directory.CreateDirectory(objectPath); } var dependencyChanged = false; if (System.IO.File.Exists(dependencyFile)) { var dependencies = new List <string>(); dependencies.Add(file.Location); dependencies.AddRange(ProjectExtensions.GetDependencies(dependencyFile)); foreach (var dependency in dependencies) { if (!System.IO.File.Exists(dependency) || System.IO.File.GetLastWriteTime(dependency) > System.IO.File.GetLastWriteTime(objectFile)) { dependencyChanged = true; break; } } } if (dependencyChanged || !System.IO.File.Exists(objectFile)) { while (numTasks >= Jobs) { Thread.Sleep(10); } lock (resultLock) { if (terminateBuild) { break; } numTasks++; } Task.Run(() => { var stringBuilderConsole = new StringBuilderConsole(); var compileResult = Compile(stringBuilderConsole, superProject, project, file, objectFile); lock (resultLock) { if (compileResults.ExitCode == 0 && compileResult.ExitCode != 0) { terminateBuild = true; compileResults.ExitCode = compileResult.ExitCode; } else { compileResults.ObjectLocations.Add(objectFile); compileResults.NumberOfObjectsCompiled++; } numTasks--; } console.OverWrite($"[CC {++buildCount}/{fileCount}] [{project.Name}] {file.Project.Location.MakeRelativePath(file.Location)}"); var output = stringBuilderConsole.GetOutput(); if (!string.IsNullOrEmpty(output)) { console.WriteLine(output); } }).GetAwaiter(); } else { buildCount++; compileResults.ObjectLocations.Add(objectFile); } } } _statusBar?.ClearText(); } } } }
public static void UpdateProperties(Project project, ProjectItem projectItem) { if (project != null) { object projObject; try { projObject = project.Object; } catch (Exception ex) { ex.TraceUnknownException(); projObject = null; } try { if (projObject == null) { projectItem.UniqueName = project.UniqueName; projectItem.Name = project.Name; return; } UpdateNameProperties(project, projectItem); projectItem.Language = project.GetLanguageName(); projectItem.CommonType = ProjectExtensions.GetProjectType(project.Kind, project.DTE.Version /* "12.0" */); } catch (Exception ex) { ex.TraceUnknownException(); } #region Set ActiveConfiguration (Configuration and Platform) Configuration config; try { config = project.ConfigurationManager.ActiveConfiguration; } catch (Exception ex) { ex.TraceUnknownException(); config = null; } if (config != null) { projectItem.Configuration = config.ConfigurationName; projectItem.Platform = config.PlatformName; } else { projectItem.Configuration = @"N\A"; projectItem.Platform = @"N\A"; } #endregion try { projectItem.Framework = project.GetFrameworkString(); var flavourTypes = project.GetFlavourTypes().ToList(); projectItem.FlavourType = string.Join("; ", flavourTypes); projectItem.MainFlavourType = flavourTypes.FirstOrDefault(); projectItem.OutputType = project.GetOutputType(); projectItem.ExtenderNames = project.GetExtenderNames(); projectItem.RootNamespace = project.GetRootNamespace(); } catch (Exception ex) { ex.TraceUnknownException(); } } }
private async Task OnExecuteAsync(DTE dte, AsyncPackage package) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var result = EnterOpenApiSpecDialog.GetResult(); if (result == null) { return; } var selectedItem = ProjectExtensions.GetSelectedItem(); var folder = FindFolder(selectedItem, dte); if (string.IsNullOrWhiteSpace(folder)) { Trace.WriteLine("Unable to get folder name"); return; } var contents = result.OpenApiSpecification; var filename = result.OutputFilename + ".json"; if (CodeGenerator == SupportedCodeGenerator.NSwagStudio) { var outputNamespace = ProjectExtensions.GetActiveProject(dte)?.GetTopLevelNamespace(); contents = await NSwagStudioFileHelper.CreateNSwagStudioFileAsync( result.OpenApiSpecification, result.Url, new NSwagStudioOptions(), outputNamespace); filename = filename.Replace(".json", ".nswag"); } var filePath = Path.Combine(folder, filename); File.WriteAllText(filePath, contents); var fileInfo = new FileInfo(filePath); var project = ProjectExtensions.GetActiveProject(dte); var projectItem = project.AddFileToProject(dte, fileInfo, "None"); projectItem.Properties.Item("BuildAction").Value = prjBuildAction.prjBuildActionNone; if (CodeGenerator != SupportedCodeGenerator.NSwagStudio) { var customTool = CodeGenerator.GetCustomToolName(); projectItem.Properties.Item("CustomTool").Value = customTool; } else { var generator = new NSwagStudioCodeGenerator(filePath, new CustomPathOptions()); generator.GenerateCode(null); dynamic nswag = JsonConvert.DeserializeObject(contents); var nswagOutput = nswag.codeGenerators.swaggerToCSharpClient.output.ToString(); project.AddFileToProject(dte, new FileInfo(Path.Combine(folder, nswagOutput))); } await project.InstallMissingPackagesAsync(package, CodeGenerator); }
public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { if (string.IsNullOrEmpty(TargetFramework)) { return(Task.FromResult <object>(null)); } foreach (var projectPath in GetProjectPaths()) { try { using (var projectInformation = ProjectExtensions.LoadProject(projectPath)) { var project = projectInformation.Project; ProjectProperty targetFrameworksProperty = null; List <string> targetFrameworks = null; var targetFrameworkProperty = project.GetProperty("TargetFramework"); if (targetFrameworkProperty != null) { var value = targetFrameworkProperty.EvaluatedValue; if (!string.IsNullOrEmpty(value)) { targetFrameworks = new List <string> { targetFrameworkProperty.EvaluatedValue }; } project.RemoveProperty(targetFrameworkProperty); } else { targetFrameworksProperty = project.GetProperty("TargetFrameworks"); if (targetFrameworksProperty != null) { targetFrameworks = targetFrameworksProperty.EvaluatedValue .Split(';') .Where(f => !string.IsNullOrEmpty(f)) .ToList(); } } if (targetFrameworks != null) { if (!targetFrameworks.Contains(TargetFramework)) { targetFrameworks.Add(TargetFramework); if (targetFrameworksProperty != null) { targetFrameworksProperty.UnevaluatedValue = string.Join(";", targetFrameworks); } else { project.SetProperty("TargetFrameworks", string.Join(";", targetFrameworks)); } host.WriteMessage("[x] Added target framework " + TargetFramework + " to " + System.IO.Path.GetFileName(projectPath) + "\n"); } else { host.WriteMessage("[ ] Target framework " + TargetFramework + " already in project " + System.IO.Path.GetFileName(projectPath) + "\n"); } } else { host.WriteMessage("[ ] Could not add target framework " + TargetFramework + " to " + System.IO.Path.GetFileName(projectPath) + "\n"); } project.Save(); } } catch (Exception e) { host.WriteError(e + "\n"); } } return(Task.FromResult <object>(null)); }
protected override FrameworkDependencyStatus GenerateConfiguration() { if (base.TryCreateGlobalAsax()) { return(FrameworkDependencyStatus.InstallSuccessful); } MvcMinimalDependencyReadMe mvcMinimalDependencyReadMe = new MvcMinimalDependencyReadMe(ProjectExtensions.GetCodeLanguage(base.Context.ActiveProject), base.Context.ActiveProject.Name, base.AppStartFileNames); return(FrameworkDependencyStatus.FromReadme(mvcMinimalDependencyReadMe.CreateReadMeText())); }
public string GetErrorIfInvalidIdentifier(string text) { return(ValidationUtil.GetErrorIfInvalidIdentifier(text, ProjectExtensions.GetCodeLanguage(this.ActiveProject))); }
public ModuleMetric Calculate(Project project) { Compilation compilation = ProjectExtensions.GetCompilation(project); IModuleSymbol moduleSymbol = compilation.Assembly.Modules.FirstOrDefault <IModuleSymbol>(); NamespaceMetrics namespaceMetric = ModuleMetricsCalculator.CalculateNamespaceMetrics(project, this.IgnoreGeneratedCode); NamespaceMetrics namespaceMetric1 = namespaceMetric; if (namespaceMetric == null) { return(null); } IEnumerable <string> strs = ModuleMetricsCalculator.CalculateClassCoupling(namespaceMetric1); double num = ModuleMetricsCalculator.CalculateMaintainabilityIndex(namespaceMetric1); int num1 = ModuleMetricsCalculator.CalculateCyclomaticComplexity(namespaceMetric1); int num2 = this.CalculateDepthOfInheritance(namespaceMetric1); int num3 = ModuleMetricsCalculator.CalculateLinesOfCode(namespaceMetric1); int num4 = namespaceMetric1.Results.Count <NamespaceMetric>(); int num5 = ModuleMetricsCalculator.CalculateNumberOfTypes(namespaceMetric1); int num6 = ModuleMetricsCalculator.CalculateNumberOfMethods(namespaceMetric1); ModuleMetric moduleMetric = new ModuleMetric(); moduleMetric.ModuleName = moduleSymbol.Name; moduleMetric.ProjectFile = project.FilePath ?? string.Empty; moduleMetric.AssemblyVersion = string.Empty; moduleMetric.FileVersion = string.Empty; moduleMetric.NamespaceMetrics = namespaceMetric1; List <MetricResult> metricResults = new List <MetricResult>(); moduleMetric.AddMetricResult(new MetricResult() { Name = "MaintainabilityIndex", Value = num }); moduleMetric.AddMetricResult(new MetricResult { Name = "CyclomaticComplexity", Value = num1 }); moduleMetric.AddMetricResult(new ClassCouplingMetricResult { Name = "ClassCoupling", Value = strs.Count <string>(), Types = strs }); moduleMetric.AddMetricResult(new MetricResult { Name = "DepthOfInheritance", Value = num2 }); moduleMetric.AddMetricResult(new MetricResult { Name = "LinesOfCode", Value = num3 }); moduleMetric.AddMetricResult(new MetricResult { Name = "NumberOfNamespaces", Value = num4 }); moduleMetric.AddMetricResult(new MetricResult { Name = "NumberOfTypes", Value = num5 }); moduleMetric.AddMetricResult(new MetricResult { Name = "NumberOfMethods", Value = num6 }); return(moduleMetric); }
protected HashSet <string> GetRequiredNamespaces(IEnumerable <CodeType> codeTypes) { string fullName; if (codeTypes == null) { throw new ArgumentNullException("codeTypes"); } SortedSet <string> strs = ControllerScaffolder <TFramework> .CreateHashSetBasedOnCodeLanguage(ProjectExtensions.GetCodeLanguage(base.Context.ActiveProject)); strs.Add(base.Model.ControllerNamespace); foreach (CodeType codeType in codeTypes) { if (codeType.Namespace == null) { fullName = null; } else { fullName = codeType.Namespace.FullName; } string str = fullName; if (string.IsNullOrEmpty(str)) { if (string.Equals(codeType.FullName, codeType.Name, StringComparison.OrdinalIgnoreCase)) { continue; } int num = codeType.FullName.LastIndexOf(string.Concat(".", codeType.Name), StringComparison.Ordinal); string str1 = codeType.FullName.Remove(num); strs.Add(str1); } else { strs.Add(str); } } strs.Remove(base.Model.ControllerNamespace); return(new HashSet <string>(strs)); }
public void CanReadSchemaWithNoValues() { var extensions = new ProjectExtensions(GetExtensionsStringWithNoValues()); Assert.NotNull(extensions); }
private static bool IsApplicableProject(CodeGenerationContext context) { FrameworkName targetFramework; bool flag; if (context == null) { throw new ArgumentNullException("context"); } if ((object)ProjectLanguage.CSharp == (object)ProjectExtensions.GetCodeLanguage(context.ActiveProject) || (object)ProjectLanguage.VisualBasic == (object)ProjectExtensions.GetCodeLanguage(context.ActiveProject)) { targetFramework = null; try { targetFramework = ProjectExtensions.GetTargetFramework(context.ActiveProject); goto Label0; } catch { flag = false; } return(flag); } return(false); Label0: if (targetFramework != null && targetFramework.Identifier == ".NETFramework" && targetFramework.Version >= new Version(4, 5)) { return(true); } else { return(false); } }
public string GenerateDefaultDataContextTypeName() { Project activeProject = base.ActiveProject; string defaultModelsNamespace = MvcProjectUtil.GetDefaultModelsNamespace(ProjectExtensions.GetDefaultNamespace(activeProject)); CodeDomProvider codeDomProvider = ValidationUtil.GenerateCodeDomProvider(ProjectExtensions.GetCodeLanguage(activeProject)); string str = codeDomProvider.CreateValidIdentifier(ProjectExtensions.GetDefaultNamespace(activeProject).Replace(".", string.Empty)); this.DataContextName = string.Concat(defaultModelsNamespace, ".", str, MvcProjectUtil.DataContextSuffix); return(this.DataContextName); }