Showing posts with label Roslyn. Show all posts
Showing posts with label Roslyn. Show all posts

Tuesday, August 2, 2022

CSC : warning CS8032: An instance of analyzer RoslynBasics.MySourceGenerator cannot be created from. Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.2.0.0,

When we are developing .Net Compiler Platform (Roslyn)¹ related code and using it in Visual Studio there are chances of getting the below exception when compiling in Visual Studio 2022.

In my scenario, I got this exception when developing a SourceGenerator².

CSC : warning CS8032: An instance of analyzer RoslynBasics.MySourceGenerator cannot be created from C:\..\RoslynBasics\bin\Debug\netstandard2.0\RoslynBasics.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..

There are many resolutions available on google. Below is the one that worked for me.
Downgrade the Microsoft.CodeAnalysis to 4.1.00

Root cause

Though the latest version is 4.2.0.0 but the Visual Studio 2022 (17.1.1) is unaware of it. Hence it failed. We can check the version of Microsoft.CodeAnalysis that Visual Studio uses in the below folder location.

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Roslyn

The location of Visual Studio 2019 and other versions is different.

Solution

The right solution can be to upgrade Visual Studio to 17.2.x. 

Once VS 2022 is upgraded the nuget 4.2.0.0 started working fine. 

Above is the new dll version after the upgrade of Visual Studio

References


Tuesday, November 10, 2015

FIPS Again - VS 2015 - An unhandled exception of type 'System.TypeInitializationException' occurred in Microsoft.CodeAnalysis.Workspaces.dll

Error Context

Recently I got my machine upgraded/re-imaged to Windows 8. Since it is re-imaging with Win 8 image, I need to install Visual Studio versions. Since I am working with VS 2013 and some research is happening around VS 2015, installed both. One main research is going on around Azure Service Fabric. So installed its SDK too. Then tried to open an existing project in VS 2015. As always the first experience was not so smooth. 

The issue is Visual Studio just restarts when I open a code file in the project.

After 3-4 restarts the below exception comes.

An unhandled exception of type 'System.TypeInitializationException' occurred in Microsoft.CodeAnalysis.Workspaces.dll

Additional information: The type initializer for 'Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger' threw an exception.
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in Microsoft.CodeAnalysis.Workspaces.dll
Additional information: The type initializer for 'Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger' threw an exception.

Analysis

Step 1

The problem of being a developer caught me as usual. Attached VS 2015 process to VS 2013 for debugging. But it also gives same error.

Step 2

The TypeInitializationException says the type initializer failed. kind of clearly indication that there would be some static things which are getting executed for DiagnosticAnalyzerLogger. 

Since its coming from .Net Compiler Platform and that is open sourced, thought of looking at the source code of DiagnosticsAnalyzerLogger in git.

Yes. There are some smells of static variable initialization.

private static readonly SHA256CryptoServiceProvider s_sha256CryptoServiceProvider = new SHA256CryptoServiceProvider();

Yeah. Something related to security and Win 8 is known for its FIPS. But still don't know whether that is the reason and I should disable FIPS.

Step 3

Next thing obviously is to get the stack track and inner exceptions if any. Since debugging using VS 2013 is not giving more details, started to try with an internal debugger tool to attach into VS 2015 process.

It produced 500 KB of data (exception details) after I attached to VS and opened a project and C# file. Was able to reach to the exception quickly. But getting the inner exception was little difficult. After some time I was able to figure out that as well and it was clear.

Timestamp: 
Message: Type: System.InvalidOperationException
Method: System.Security.Cryptography.SHA256Managed..ctor
Message: "This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms."
Date Time: 

Stack Trace:
System.Security.Cryptography.SHA256Managed..ctor

System.Reflection.RuntimeConstructorInfo.Invoke
System.Security.Cryptography.CryptoConfig.CreateFromName
System.Security.Cryptography.SHA256.Create

System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal
System.Reflection.RuntimeMethodInfo.Invoke
Roslyn.Utilities.SHA256CryptoServiceProvider..ctor
Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger..cctor

As seen in the above log. Microsoft hard coded use of SHA256 Managed version and that is not part of the Windows Platform FIPS validated algorithm list. 

I am not sure whether everybody who install VS 2015 in Windows 8 facing the same issue.

Event Viewer logs

If I am not a developer, may be I would directly goes to the eventvwer and got the below exception immediately.

Application: devenv.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: System.TypeInitializationException: The type initializer for 'Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
   at System.Security.Cryptography.SHA256Managed..ctor()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Security.Cryptography.CryptoConfig.CreateFromName(String name, Object[] args)
   at System.Security.Cryptography.SHA256.Create()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Roslyn.Utilities.SHA256CryptoServiceProvider..ctor()
   at Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticAnalyzerLogger.AllowsTelemetry(DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer)
   at Microsoft.CodeAnalysis.Diagnostics.Log.DiagnosticLogAggregator.UpdateAnalyzerTypeCount(DiagnosticAnalyzer analyzer, AnalyzerActions analyzerActions)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerDriver.<GetAnalyzerActionsAsync>d__41.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerDriver.<GetAnalyzerActionsAsync>d__39.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Shared.Extensions.DiagnosticAnalyzerExtensions.<GetDiagnosticAnalyzerCategoryAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Shared.Extensions.DiagnosticAnalyzerExtensions.<SupportsSyntaxDiagnosticAnalysisAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer.<ShouldRunAnalyzerForStateTypeAsync>d__64.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer.<ShouldRunAnalyzerForStateTypeAsync>d__63.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer.<AnalyzeSyntaxAsync>d__49.MoveNext()
Stack:
   at System.Environment.FailFast(System.String, System.Exception)
   at Microsoft.CodeAnalysis.FailFast.OnFatalException(System.Exception)
   at Microsoft.CodeAnalysis.ErrorReporting.FatalError.Report(System.Exception, System.Action`1<System.Exception>)
   at Microsoft.CodeAnalysis.ErrorReporting.FatalError.ReportUnlessCanceled(System.Exception)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer+<AnalyzeSyntaxAsync>d__49.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer+<AnalyzeSyntaxAsync>d__49.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer+<ShouldRunAnalyzerForStateTypeAsync>d__63.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticIncrementalAnalyzer+<ShouldRunAnalyzerForStateTypeAsync>d__64.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Shared.Extensions.DiagnosticAnalyzerExtensions+<SupportsSyntaxDiagnosticAnalysisAsync>d__2.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerCategory, Microsoft.CodeAnalysis.Features, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerCategory, Microsoft.CodeAnalysis.Features, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Shared.Extensions.DiagnosticAnalyzerExtensions+<GetDiagnosticAnalyzerCategoryAsync>d__0.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerDriver+<GetAnalyzerActionsAsync>d__39.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetException(System.Object)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetException(System.Exception)
   at Microsoft.CodeAnalysis.Diagnostics.EngineV1.DiagnosticAnalyzerDriver+<GetAnalyzerActionsAsync>d__41.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetResult(System.__Canon)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetResult(System.__Canon)
   at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager+<GetAnalyzerActionsAsync>d__8.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetResult(System.__Canon)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].SetResult(System.__Canon)
   at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager+<GetCompilationAnalysisScopeAsync>d__5.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.Finish(Boolean)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.ExecuteEntry(Boolean)
   at System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Solution

The solution is same. Just disable FIPS. Earlier it was used as workaround. But now we need to consider as solution.
http://blogs.technet.com/b/secguide/archive/2014/04/07/why-we-re-not-recommending-fips-mode-anymore.aspx

Tuesday, June 23, 2015

Running Roslyn Analyzers from console application

This post requires prior knowledge from my earlier post. In the last post, we saw how our C# program can compile other C# program via Roslyn compiler. Yes it's without Visual Studio. If we are compiling without Visual Studio how a custom Roslyn DiagnosticAnalyzer can be invoked to do analysis on the code fragment which is getting compiled?

Here we are going to see how we can connect with Roslyn custom analyzers when our program is compiling another program using .Net compiler platform.
First, we are defining our custom analyzer which is nothing but a check to make sure the type names are starting with a capital letter. See the code below. Now let us move on to how this analyzer can be integrated into our programmatic compilation using Roslyn.
  1. GetSimpleCompilation()
    This is same as what is there in previous post about simple compilation.
  2. GetAnalyzerAwareCompilation
  3. Here we connect our compilation unit with custom Roslyn diagnostic analyzer.
  4. GetAllDiagnosticsAsync()
  5. This is Roslyn API to execute our custom analyzers on top of source code input and get the results back. The important point here is the compiler platform returns same type ImmutableArray<Diagnostic> every time. ie Regardless of whether its simple compilation or compilation with analyzers.

    If the result from GetAllDiagnosticsAsync is empty list, proceed to actual compilation which produces the assembly file.
  6. ShowDiagnostics()
    This is too same as previous post.

Updates

2022-08-10 - Added full sample to https://github.com/dotnet-demos/roslyn-compile-with-analyzers 

Tuesday, June 16, 2015

Using Roslyn to compile C# source code

Below are the steps write a program to compile C# code snippet using Roslyn (Now .Net Compiler Platform)to produce an assembly. Simply saying a C# program compiling another C# program using Roslyn compiler.

The Roslyn nuget version used here is 1.0.0-rc2. This tutorial is organized in zoom in/out fashion.

There are mainly 3 high level steps and they are getting a compilation unit, compiling the same and processing result / diagnostics it produced. The code snippet shows the steps.

  1. GetSimpleCompilation() Now lets look at what is happening in GetSimpleCompilation. As seen in the code we are getting the source code, creating syntax tree out of that then prepare the references needed for the compilation. Finally Creating CSharpCompilation using all the information.
    1. GetSourceCode()
    2. This method simply returns sample source code to compile.Can be replaced by any other code snippet.
    3. GetSyntaxTree()
    4. This method parses the input code and creates the CSharpSyntaxTree.
    5. GetReferences()
    6. Compilation always needs what are the references needed. Here its very basic as we are not using any advanced features.
  2. Compile()
  3. Now its the time to compile. It needs to get the assembly file name to proceed. Since the GetOutpuFilePath() is just simply returning the dll file path, omitting it.
  4. ShowDiagnostics()
  5. This method shows any warnings in compilation.
The compiled assembly can be kept in memory and execute from there. Please refer this link for more details.

Happy coding...

Tuesday, July 8, 2014

Why my Roslyn extension is not getting loaded?

Below is my experience when I started working with a Roslyn project which I got from my colleague. First thing

Is the Roslyn compiler enabled for the Visual Studio test instance?

Yes there is something called enabling Roslyn. As we know Roslyn is the new compiler. The Visual Studio can now support 2 compilers. Traditional and Roslyn. So how the Visual Studio knows, it needs to use Roslyn? 
The answer is the below command line argument which needs to be passed to Visual Studio process devenv.exe when its started.

/rootsuffix Roslyn

If we are building VSIX extension project, we can mention this command line argument in the project properties->debug tab. This will make sure the test Visual Studio instance will be using the Roslyn compiler.

If the visual studio test instance itself not starting when we run the extension project, make sure the below path is there in the Project properties->Debug -> Start external program text box.

<Drive>:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe

Is the VSIX extension actually loaded or there is any bug in my code?

First of all check whether the Visual studio test instance can start with Roslyn enabled. If yes, load a project in the test instance of Visual Studio. If so go back to parent Visual Studio where we write our extension code and look at Modules window.

Debug->Windows-Modules

If our assembly is listed there in indicate that the extension is loaded. Now we can go to next debugging step.

Why the VSIXManifest is copied to wrong Roslyn extensions folder

If we are not able to find our extension assembly in the modules window, it indicate that the Visual Studio is not able to locate our extension assembly. To understand this better we should understand how the Roslyn extension is working under the hood. When we press the run button on the Roslyn extension project from VS,

  • It is compiling the project and copying the dlls including the extension.VSIXManifest file to the below mentioned location
    • <Drive>:\Users\<name>\AppData\Local\Microsoft\VisualStudio\12.0Roslyn\Extensions
  • The above underlined folder name "12.0Roslyn" is controlled by a project property given below
    • <VSSDKTargetPlatformRegRootSuffix>Roslyn</VSSDKTargetPlatformRegRootSuffix>
If the property hold a wrong value, it may copy the compiled vsix extension to wrong folder and the Roslyn extension will not take effect when we load Visual Studio test instance.

Why my VSIX extension files are not getting copied to Roslyn extension folder

Sometimes we will be having proper value in the <VSSDKTargetPlatformRegRootSuffix> tag. But still the files may not be copied. That will be due to improper values in the below project properties.

<IncludeAssemblyInVSIXContainer> true </IncludeAssemblyInVSIXContainer>  
<IncludeDebugSymbolsInVSIXContainer> false </IncludeDebugSymbolsInVSIXContainer>
<IncludeDebugSymbolsInLocalVSIXDeployment>  false</IncludeDebugSymbolsInLocalVSIXDeployment>
<CopyBuildOutputToOutputDirectory>    true</CopyBuildOutputToOutputDirectory>
<CopyOutputSymbolsToOutputDirectory>    true </CopyOutputSymbolsToOutputDirectory>

Best solution is to remove all these properties so that it will take the default behavior and default will copy required dlls to extensions folder.

Can I change these VSIX project properties using the properties tab?

The answer is NO as the project properties tab don't have the UI to support these properties. There is already a bug raised to Microsoft.

Is there a real issue in my code?

If all these things are set properly and still our Roslyn VSIX extension is not working, there is something wrong in the code. Inspect the code for below scenarios.
  • Class level attributes.
  • The interfaces implemented 
  • Whether the SymbolKindsOfInterest property returns proper list?

More links


Happy debugging...

Monday, June 2, 2014

Project Type GUIDs - Why I am not able to open some project files in VS?

Sometime back I got a solution from one of my research team mate. That was related to using Roslyn for improving coding experience in Visual Studio. It was working fine until I got new machine from new office. The error is famous as the VS. All the .Net developers will be familiar with the below error message.

The sad thing is VS doesn't tell that which project type is missing. Either we need to ask the creator what he meant, or look at his blog to get details. In my case he is in our offshore team and as of my knowledge he don't have any blog. At least if the VS tells that, this is the project type you are missing we could install it easily. 

So now what can I do?

Finding out Visual Studio project type from project file.


  • Open the .csproj / .vbproj file in a text editor (notepad.exe)
  • Find out the <ProjectTypeGuids> tag
  • Then google the GUIDs present in the element, if you have internet access.
  • Once the project type is known install that feature. eg: If its ASP.Net MVC install MVC
  • There are some web site where people keep a list of Project Type GUIDs and corresponding project type.
    • http://www.mztools.com/articles/2008/mz2008017.aspx
    • http://onlinecoder.blogspot.com/2009/09/visual-studio-projects-project-type.html
    • http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs

But I don't think Microsoft is providing any list. Its very sad.