How to use Roslyn Code Analysis API with MVC 6 projects - c#

I intend to use the new Roslyn Code Analysis API with an MVC 6 project.
However, when I run this code:
string pathToSolution = #"..\..\..\WebApplicationComplex.sln";
const string projectName = "RoslynWebAPIProject";
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
Solution solutionToAnalyze = workspace.OpenSolutionAsync(pathToSolution).Result;
Project sampleProjectToAnalyze = solutionToAnalyze.Projects.Where((proj) => proj.Name == projectName).FirstOrDefault();
Compilation sampleToAnalyzeCompilation = sampleProjectToAnalyze.GetCompilationAsync().Result;
I only get the analyzer project and nothing of the MVC 6 project, so the sampleProjectToAnalyze remains null.
How should I analyze that type of projects?

You need to use the DNX Workspace.
Add a reference to that package, then create a new ProjectJsonWorkspace(jsonPath)

Related

Cake Build - Update NuGet package to the newest version

I have a solution with 5 projects in it. Every project is deployed via a nuget-push. Some projects reference other projects via nuget. In order to work properly these nuget-packages have to be updated before they are pushed.
For this we use Cake-Build but the nuget update is not working on core/standard projects. Instead it is necessary to use remove --> add, which is not working for me?
How can I handle this?
Example:
Project A v1.0.0
Project B v1.0.0
Project C v1.0.0
Reference to A v1.0.0
Reference to B v1.0.0
Now the Build-Script would compile A and B, increment the version to v1.0.1, and push the nuget-package. Before C is build the nuget packages to A & B needs to be updated.
Example:
Project A v1.0.1
Project B v1.0.1
Project C v1.0.1
Reference to A v1.0.1
Reference to B v1.0.1
How I'm able to update the packages via Cake-Build?!?
If you use project references and build as part of same solution, you should be able to get everything referenced correctly. That's how Cake itself is built.
Cake.exe / dll depends on
Cake.Core
Cake.Common which depends on
Cake.Core
When we i.e. build 0.30.0 we pass that version as common MSBuildSettings to Restore. Build and Pack. Rough example
string configuration = "Release",
version = "0.30.0",
semVersion = "0.30.0"; // for pre-release this is suffixed i.e. -alpha-001
DotNetCoreMSBuildSettings msBuildSettings = new DotNetCoreMSBuildSettings()
.WithProperty("Version", semVersion)
.WithProperty("AssemblyVersion", version)
.WithProperty("FileVersion", version);
DotNetCoreRestore("./src/Cake.sln", new DotNetCoreRestoreSettings
{
Verbosity = DotNetCoreVerbosity.Minimal,
Sources = new [] { "https://api.nuget.org/v3/index.json" },
MSBuildSettings = msBuildSettings
});
DotNetCoreBuild("./src/Cake.sln", new DotNetCoreBuildSettings()
{
Configuration = configuration,
NoRestore = true,
MSBuildSettings = msBuildSettings
});
var projects = GetFiles("./src/**/*.csproj");
foreach(var project in projects)
{
DotNetCorePack(project.FullPath, new DotNetCorePackSettings {
Configuration = configuration,
OutputDirectory = "./nuget,
NoBuild = true,
NoRestore = true,
IncludeSymbols = true,
MSBuildSettings = msBuildSettings
});
}
A project reference in .NET Core csproj looks like
<ProjectReference Include="..\Cake.Core\Cake.Core.csproj" />

Is there anyway to use the NDepend API to get a list of assemblies and their associated projects?

I am currently trying to get a list of 3rdParties shipped with each product and have come across the NDepend API. Based on the research I have done, it seems like you feed in a solution file and out comes a list of DLLs and EXE's associated with that solution. So far I have tried:
static void Main(string[] args)
{
var ndependServicesProvider = new NDependServicesProvider();
var projectManager = ndependServicesProvider.ProjectManager;
var visualStudioManager = ndependServicesProvider.VisualStudioManager;
var projPath = "C:\\code\\depot\\Captiva\\IA\\EIM\\_Trunk\\Src\\BuildInputAccel.Installers.sln";
var sln = projPath.ToAbsoluteFilePath();
var vsSlnOrProjFilePaths = new List<IAbsoluteFilePath> { sln };
var assembliesFilePath = (from vsSlnOrProjFilePath in vsSlnOrProjFilePaths
from assembliesFilePathTmp in visualStudioManager.GetAssembliesFromVisualStudioSolutionOrProject(vsSlnOrProjFilePath)
select assembliesFilePathTmp).Distinct().ToArray();
IProject project = projectManager.CreateTemporaryProject(assembliesFilePath, TemporaryProjectMode.Temporary);
project.CodeToAnalyze.SetApplicationAssemblies(assembliesFilePath);
projectManager.SaveProject(project);
IAnalysisResult analysisResult = project.RunAnalysis();
Console.Write(analysisResult.CodeBase);
}
And have gotten a An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Does anyone know what I am doing wrong here. I simply want to output a list of dll's and exes associated with each project within a solution. PS: I am very new to C# so sorry if this seems trivial!
At the end of the NDepend API getting started page you'll find instruction about what to do.
Actually can use the integrated Code Querying LINQ (CQLinq) facility to query live 3rd party assemblies referenced and their usage.
1) from the NDepend start page > Analyze VS solution
2) choose your solution
3) run analysis
Then you can just edit this code query:
from a in ThirdParty.Assemblies
select new { a, a.AssembliesUsingMe }
et voilĂ 
If some third-party assemblies are missing it is because they haven't been resolved at analysis time. Look at analysis error list and update the list of folder where NDepend will look for assemblies in NDepend Project Properties > Code to Analyze > Directories

Perform Roslyn conditional compilation with custom symbol (eg: "DEBUG") defined

I'm compiling a project using Roslyn with code resembling:
var workspace = MSBuildWorkspace.Create();
var project = await workspace.OpenProjectAsync("SomeProject.csproj");
var compilation = await project.GetCompilationAsync();
I need to set a compilation symbol (such as DEBUG or TRACE, but in my case something altogether custom). How can I do this with the API?
I saw that project has a CompilationOptions property, but I didn't see anything relevant there.
EDIT Thanks to #JoshVarty who pointed towards adding code like this prior to compilation:
project = project
.WithParseOptions(((CSharpParseOptions)project.ParseOptions)
.WithPreprocessorSymbols("SOME_SYMBOL"));
I think you're looking for Project.WithParseOptions() and WithPreprocessorSymbols()

Does Roslyn actually allow you to manipulate TreatWarningsAsErrors for a CSharp project?

I'm trying to retrieve the setting TreatWarningsAsErrors, but I'm unable to find it for a project of my loaded solution.
What I'm trying to accomplish, is to get the setting from the project files, and set it to true, if it's not already that. Next, I want to let Roslyn do a compilation with the new setting, so I can check if this will break the project.
I've looked at various places, among others, the Project.CompilationOptions. Most options to a project build are there, except this one.
The CompilationOptions contains all the build settings, such as warning level, etc. But TreatWarningsAsErrors is not there. Am I looking at the wrong place?
The way I'm opening the solution is similar to the FormatSolution sample:
var solutionFile = #"C:\ties\src\playground\EnforceTreatAllWarningsAsErrors\EnforceTreatAllWarningsAsErrors.sln";
var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync(solutionFile).Result;
var project = solution.Projects.Single();
// warning level is there
var warningLevel = project.CompilationOptions.WarningLevel;
// treat warnings as errors is not there... The following doesn't compile :(
bool treatWarningsAsErrors = project.CompilationOptions.TreatWarningsAsErrors;
You're looking for
compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Error)
Source

api to check for project variables and reference paths in a project file

I am working on a .net application (VS2010) with x no. of solutions and variable no. of projects in those solutions.
I need to check if the project properties (specific to a certain number of projects) are homogenous, and also check/validate the reference paths during the build.
Is there an API that does this? If not, how do i go about building one?
You can use MSBuild framework to do the parsing and perform evaluation of the project files. The main classes you need to use are ProjectCollection and Project.
But first you will need to deal with your .sln files. Since API cannot load .sln files directly, you will need first to convert your .sln files to projects files, that API can load. The method is described here. You will get a .sln.metaproj files after conversion, that are equivalent representation of .sln, but have MSBuild format. After that you can parse .sln.metaproj files and referenced projects and evaluate properties you need. This sample prints out the OutputPath property evaluation for Debug|AnyCPU configuration of all projects in the solution:
Dictionary<string, string> globalProperties = new Dictionary<string, string>();
globalProperties.Add("Configuraion", "Debug");
globalProperties.Add("Platform", "AnyCPU");
ProjectCollection pc = new ProjectCollection(globalProperties);
Project sln = pc.LoadProject(#"my_directory\My_solution_name.sln.metaproj", "4.0");
foreach (ProjectItem pi in sln.Items)
{
if (pi.ItemType == "ProjectReference")
{
Project p = pc.LoadProject(pi.EvaluatedInclude);
ProjectProperty pp = p.GetProperty("OutputPath");
if (pp != null)
{
Console.WriteLine("Project=" + pi.EvaluatedInclude + " OutputPath=" + pp.EvaluatedValue);
}
}
}

Categories

Resources