InvalidProgramException when trying to parse VB.Net code with Roslyn - vb.net

I'm trying to parse VB.Net code using Roslyn, but it keeps throwing the InvalidProgramException (Jit compiler encountered a limitation..). A similar code works perfectly with C#.
This is my code:
var source = "Public Module Module1 \r\n Public Sub X() \r\n End Sub \r\n End Module";
var syntaxTree = Roslyn.Compilers.VisualBasic.SyntaxTree.ParseText(source);
var compilation = Roslyn.Compilers.VisualBasic.Compilation.Create("MyCompilation", syntaxTrees: new[] {syntaxTree});
var semanticModel = compilation.GetSemanticModel(syntaxTree);
The exception is thrown on the last line.
Update Here's the stack trace:
System.InvalidProgramException: JIT Compiler encountered an internal limitation.
HResult: -2146233030
в Roslyn.Compilers.VisualBasic.SeparatedSyntaxList`1..ctor(SyntaxNode node, Int32 index)
в Roslyn.Compilers.VisualBasic.CompilationUnitSyntax.get_Members()
в Roslyn.Compilers.VisualBasic.DeclarationTreeBuilder.VisitCompilationUnit(CompilationUnitSyntax node)
в Roslyn.Compilers.VisualBasic.CompilationUnitSyntax.Accept[TResult](SyntaxVisitor`1 visitor)
в Roslyn.Compilers.VisualBasic.SyntaxVisitor`1.Visit(SyntaxNode node)
в Roslyn.Compilers.VisualBasic.DeclarationTreeBuilder.ForDeclaration(SyntaxNode node)
в Roslyn.Compilers.VisualBasic.DeclarationTreeBuilder.ForTree(SyntaxTree tree, ReadOnlyArray`1 rootNamespace, String scriptClassName, Boolean isSubmission)
в Roslyn.Compilers.VisualBasic.Compilation.ForTree(SyntaxTree tree, CompilationOptions options, Boolean isSubmission)
в Roslyn.Compilers.VisualBasic.Compilation._Closure$__11._Lambda$__59()
в System.Lazy`1.CreateValue()
в System.Lazy`1.LazyInitValue()
в System.Lazy`1.get_Value()
в Roslyn.Compilers.VisualBasic.DeclarationTable.GetLatestRootDeclarationIfAny(Boolean includeEmbedded)
в Roslyn.Compilers.VisualBasic.DeclarationTable.GetMergedReferenceDirectives()
в System.Lazy`1.CreateValue()
в System.Lazy`1.LazyInitValue()
в System.Lazy`1.get_Value()
в Roslyn.Compilers.VisualBasic.DeclarationTable.get_ReferenceDirectives()
в Roslyn.Compilers.VisualBasic.Compilation.get_ReferenceDirectives()
в Roslyn.Compilers.CommonAssemblyManager`3.GetCompilationReferences(TCompilation compilation, DiagnosticBag diagnostics, List`1 references, IDictionary`2& boundReferenceDirectives, List`1& referenceDirectiveLocations)
в Roslyn.Compilers.CommonAssemblyManager`3.ResolveMetadataReferences(TCompilation compilation, List`1 references, IDictionary`2& boundReferenceDirectiveMap, ReadOnlyArray`1& boundReferenceDirectives, List`1 assemblies, List`1 modules, DiagnosticBag diagnostics)
в Roslyn.Compilers.VisualBasic.Compilation.AssemblyManager.CreateSourceAssemblyForCompilation(Compilation compilation, Dictionary`2& referencedAssembliesMap, Dictionary`2& referencedModulesMap, IDictionary`2& boundReferenceDirectiveMap, ReadOnlyArray`1& boundReferenceDirectives, SourceAssemblySymbol& assemblySymbol, DiagnosticBag& diagnostics)
в Roslyn.Compilers.VisualBasic.Compilation.AssemblyManager.CreateSourceAssemblyForCompilation(Compilation compilation)
в Roslyn.Compilers.VisualBasic.Compilation.EnsureSourceAssemblyCreated()
в Roslyn.Compilers.VisualBasic.Compilation.get_SourceAssembly()
в Roslyn.Compilers.VisualBasic.Compilation.get_Assembly()
в Roslyn.Compilers.VisualBasic.Compilation.get_SourceModule()
в Roslyn.Compilers.VisualBasic.Compilation.GetSemanticModel(SyntaxTree syntaxTree)

This exception typically indicates that the program itself is corrupt. If you're able to provide a crash dump file, please do so.
Also, verify that your assemblies haven't been corrupted in some way. All Roslyn binaries we ship are digitially signed, so check if your Roslyn.Compilers.VisualBasic.dll has a valid signature. Find the DLL, go under File Properties in Windows Explorer, Digital Signatures tab, and hit details. Verify you see "the signature is OK."

It turned out that the exception is being thrown when I use the code on my Web site only, and then the Web site runs on either VisualStudio Development Server or IIS Express. Also running it via TestDriven.net and Gallio (might be just old versions). The code runs fine with a Console app or IIS full.
I still consider this a bug, since a similar code that uses the CSharp compiler runs just fine.

Related

Error in running default Web Application .Net Core 3

I am choosing Empty template while creating a new asp.net core web application (.net core 3) as a option.
When I run project, I face with this error
System.TypeInitializationException: 'The type initializer for 'Microsoft.Extensions.Logging.EventSource.LoggingEventSource' threw an exception.'
Stack Trace:
at Microsoft.Extensions.Hosting.Host.<>c.<CreateDefaultBuilder>b__1_2(HostBuilderContext hostingContext, ILoggingBuilder logging)
at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.<>c__DisplayClass4_1.<ConfigureLogging>b__1(ILoggingBuilder builder)
at Microsoft.Extensions.DependencyInjection.LoggingServiceCollectionExtensions.AddLogging(IServiceCollection services, Action`1 configure)
at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.<>c__DisplayClass4_0.<ConfigureLogging>b__0(HostBuilderContext context, IServiceCollection collection)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at WebApplication2.Program.Main(String[] args) in D:\WebApplication2\WebApplication2\Program.cs:line 16
Stack Trace in Inner Exception:
at System.Globalization.CompareInfo.CompareString(ReadOnlySpan`1 string1, ReadOnlySpan`1 string2, CompareOptions options)
at System.Globalization.CompareInfo.Compare(String string1, String string2, CompareOptions options)
at System.Globalization.TextInfo.PopulateIsAsciiCasingSameAsInvariant()
at System.Globalization.TextInfo.ChangeCaseCommon[TConversion](String source)
at System.Globalization.TextInfo.ToUpper(String str)
at System.String.ToUpperInvariant()
at System.Diagnostics.Tracing.EventSource.GetGuid(Type eventSourceType)
at System.Diagnostics.Tracing.EventSource..ctor(EventSourceSettings settings, String[] traits)
at System.Diagnostics.Tracing.EventSource..ctor(EventSourceSettings settings)
at Microsoft.Extensions.Logging.EventSource.LoggingEventSource..cctor()
What is this and how can I resolve it.
Thanks.
The problem was solved for me when I run the application on IIS instead of IIS Express.

SimpleInjector is throwing ThrowMissingInstanceProducerException when injecting delegates into services

I am converting my ASP.Net application from MC3 to MVC4. I have Simpleinjector code from old MVC3 days as below
WebContainer.Instance.Container.GetInstance<Func<HttpRequestBase>>();
Now this line of code is throwing exception in the new SimpleInjector version 2.8.0. My application is in .Net framework 4.0. Please advise on the stack trace below
Message: No registration for type Func could be found.
Exception type: SimpleInjector.ActivationException
Stack Trace:
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
at SimpleInjector.Container.GetInstance[TService]()
at Aon.Exchange.Web.UserControlBase..ctor()
at ASP.cmswebparts_aonexchange_help2_ascx..ctor()
at __ASP.FastObjectFactory_app_web_help2_ascx_f5d8491b_aknegnyf.Create_ASP_cmswebparts_aonexchange_help2_ascx()
at System.Web.UI.TemplateControl.LoadControl(IWebObjectFactory objectFactory, VirtualPath virtualPath, Type t, Object[] parameters)
at System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
at CMS.PortalControls.CMSWebPartZone.LoadWebPart(Control container, CMSWebPartZone zone, WebPartInstance part, Boolean reloadData, Boolean isVariant)
The code for WebContainer is listed as below
this.Container = new Container();
SimpleInjectorWebInitializer.Initialize();
this.Container.RegisterPackages(GetAssemblies());
this.Container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
this.Container.RegisterMvcIntegratedFilterProvider();
this.RegisterGlobalFilters();
//this.Container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(this.Container));
//this.VerifyPages();
The registration of this func is as below
container.RegisterPerWebRequest<Func<HttpRequestBase>>(() => () => new HttpRequestWrapper(HttpContext.Current.Request));

Xaml Designer not loading

today i've installed Visual Studio Community 2015 with Update 1 and when it try to load the Xaml Designer (even of a new project) it throws an exception:
An unhandled exception has occured
System.Runtime.InteropServices.COMException
The app did not start. (Exception from HRESULT: 0x8027025B)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.AppPackageNativeMethods.IApplicationActivationManager.ActivateApplication(String appUserModelId, String activationContext, ActivateOptions options, Int32& processId)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.DesignerWrtUtility.ActivateApplication(String appUserModelId, String activationContext, Object site, Boolean isRunningElevated)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.ActivateApplicationInternal(String appUserModelId, String activationContext, Object site)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateDesignerProcess(String applicationPath, String clientPort, Uri hostUri, IDictionary environmentVariables, Int32& processId, Object& processData)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, IIsolationTarget isolationTarget, String baseDirectory)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func'2 func, CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0'1.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
I had the same problem, this fixed it:
uninstall Visual Studio
uninstall all Windows SDKs/Emulators
install everything again
After that everything worked fine again.
If you're using an HP:
Delete the "Platform" environment variable in Control Panel > System > Advanced System Settings > Environment Variables [...] =HPD. (source)
If you're not using an HP, try following these steps:
Close any instance of Visual Studio
Open Visual Studio and create a new C# UWP empty project (name it whatever you want)
Run the newly created "useless" project, then close it as Visual Studio
Re-open your previous project. (source)
If you recently upgraded to the Windows 10 SDK from 10240 to 10586, then try setting the project Properties > Application > "Target version" to Windows 10 (10.0; Build 10240). (source)
Let me know if this helps!

GeoLocation data type incompatibility between odata service and it's .Net generated client side proxy

I am trying to do a proof of concept with the odata compliant cloud database feature of JayStorm. So far it's going great, but I have one big problem that fits in the category of odata service client proxy serialization category.
My odata service url is: https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/
I create a simple .Net console app and add a service reference to this service. It all looks fine at first, however there is an incompatibility between the server side data type for GeoLocation (json payload is: {"type":"Point","coordinates":[-71.56236648559569,42.451074707889646],"crs":{"properties":{"name":"EPSG:4326"}) and the client side type the add reference wizard chooses. It seems they are very different data types and just client side select queries or client side insert/updates don't work. For example the below code throws an exception on line SaveChanges();
System.Data.Services.Client.DataServiceRequestException was unhandled
HResult=-2146233079
Message=An error occurred while processing this request.
Source=Microsoft.Data.Services.Client
StackTrace:
at System.Data.Services.Client.SaveResult.HandleResponse()
at System.Data.Services.Client.BaseSaveResult.EndRequest()
at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
at System.Data.Services.Client.DataServiceContext.SaveChanges()
at JumpSeatDataImporter.Program.Main(String[] args) in c:\Projects\JumpSeat\Dev\JumpSeatWeb\JumpSeatDataImporter\Program.cs:line 24
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.Services.Client.DataServiceClientException
HResult=-2146233079
Message=Format Exception: Invalid 'Point' format!
at Function.$data.GeographyBase.validateGeoJSON (/usr/lib/node_modules/jaydata/lib/TypeSystem/Types/Geography.js:75:29)
at GeographyPoint.GeographyBase (/usr/lib/node_modules/jaydata/lib/TypeSystem/Types/Geography.js:6:25)
at new GeographyPoint (/usr/lib/node_modules/jaydata/lib/TypeSystem/Types/Geography.js:94:29)
at $data.oDataConverter.fromDb.$data.GeographyPoint (/usr/lib/node_modules/jaydata/lib/Types/StorageProviders/oData/oDataConverter.js:55:64)
at Airport.$data.Entity.$data.Class.define.constructor (/usr/lib/node_modules/jaydata/lib/Types/Entity.js:189:41)
at Airport.Entity (eval at <anonymous> (/usr/lib/node_modules/jaydata/lib/TypeSystem/TypeSystem.js:463:20))
at new Airport (eval at <anonymous> (/usr/lib/node_modules/jaydata/lib/TypeSystem/TypeSystem.js:463:20))
at EntitySetProcessor.$data.Class.define.invoke (/usr/lib/node_modules/jaydata/lib/JayService/OData/EntitySetProcessor.js:61:38)
at JSObjectAdapter.$data.Class.define.processRequest (/usr/lib/node_modules/jaydata/lib/JayService/JSObjectAdapter.js:89:37)
at JSObjectAdapter.$data.Class.define.handleRequest (/usr/lib/node_modules/jaydata/lib/JayService/JSObjectAdapter.js:165:26)
StatusCode=500
InnerException:
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Spatial;
using System.Text;
using System.Threading.Tasks;
namespace AirportDataImporter
{
class Program
{
static void Main(string[] args)
{
var db = new AirprotDB.mydatabaseService(new Uri("https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/"));
//{"Name":"sfd","Abbrev":"sd","GeoLocation":{"type":"Point","coordinates":[-71.56236648559569,42.451074707889646],"crs":{"properties":{"name":"EPSG:4326"},"type":"name"}}}
var airport = new JumpSeatDB.Airport();
airport.Abbrev = "Foo";
airport.Name = "Bar";
airport.GeoLocation = GeographyPoint.Create(51.87796, -176.64603);
db.AddToAirport(airport);
db.SaveChanges();
//var foo = db.Airport.ToList();
}
}
}
What can I do to have the client side proxy use a fitting (custom declared?) class which will allow me to round trip data, including the GeoLocation property? Without this, I can't upload/update data from sql server and files to JayStorm...
You should be able to emulate my issue fully by adding a service to a console app and running the above provided code. Don't worry about messing up the data.
Thanks
The geo types are exposed only via JSON format right now (this might change in the mid-term) and .NET uses XML by default, which leaves three options:
make your .NET app to work in JSON format with Data Services Client 5.5.0 and Data Services Tools 5.3 (this generates a new proxy, which accepts the Format property on the context) - I wasn't able to achieve this in .NET, but I do hope you are better than me :)
you use a HTML5 page or node.js to import your POIs with JayData library
you post you csv file to a JayStorm service operation, which processes the file. You post to the service operation with HttpRequest

Visual Studio Express 2012 - Silverlight-Enabled WCF Service?

I just started a new Silverlight project with Visual Studio Express 2012 for Web.
I created a Silverlight-enabled WCF service to access a SQL Server database, with EF 5.
The problem I'm having is that the service doesn't seem to be able to return any entity retrieved from the database. A new entity or any old object is returned just fine, but when I try to return an entity from the context I get the following exception:
{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.DataServiceClientChannel.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.NewProj.DataSvcRef.DataService.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.OnEndGetAgency(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}
The service method code couldn't be simpler:
[OperationContract]
public Contact GetContact(int aID)
{
Contact res = null;
using (var db = new OFBEntities())
{
try
{
res = db.Contacts.Find(aID);
}
catch (Exception ex)
{
res = null;
}
return res;
}
}
As I mentioned, if I return a newly created object (return new Contact(){ name="test contact};), or return a type that is not in context (say an integer for example), everything works fine.
Is this a limitation of the express version, or am I forgetting some settings? In the past I have created some Silverlight apps that consumed data services with VS 2010, Silverlight 4, and I don't remember having to set anything special, but maybe I just forgot that I did?
Any help is appreciated!
EDIT:
Could it have anything to do with DbContext and the way it is serialized? I've never used DbContext before, I always used the default ObjectContext in EF 4...
EDIT2: SOLUTION
It's been a while, but I had other things to work :o)
In case anybody is in the same boat, the problem was in the serialization by the service. DbContext by default creates proxies, which don't agree with serialization. I am not sure why yet - indeed, I need to educate myself about those proxies - but disabling them solves my serialization issue.
Thanks for the comment Pawel, I mistakenly thought my serialization was going OK, rechecking the server-side error put me back on the right track.
The problem was with automatic proxy creation by the DBContext, which interfered with the serialization.
Proxies are on by default in DBContext, you can disable them in the class constructor
this.Configuration.ProxyCreationEnabled = false;
or after creating an instance of your DBContext
using (var db = new myDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
...
}
Not sure why yet, but it works. Time to go read up on that!