Mono.CSharp.Evaluator.ReferenceAssembly() throwing NullReferenceException - c#

Using Mono.CSharp.dll version 2.0 targeting .Net 3.5.
Using the Unity Editor version 5.6.3p1.
There is a using statement for .
Here is my code:
Evaluator.Init(new string[] { });
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
Evaluator.ReferenceAssembly(assembly);
(not shown: using Mono.CSharp;)
Here is the error (throwing on that third line):
NullReferenceException: Object reference not set to an instance of an object
Mono.CSharp.TypeManager.IsThisOrFriendAssembly (System.Reflection.Assembly assembly)
Mono.CSharp.Namespace.RegisterExternalExtensionMethodClass (System.Type type)
Mono.CSharp.RootNamespace.RegisterExtensionMethodClass (System.Type t)
Mono.CSharp.RootNamespace.ComputeNamespaces (System.Reflection.Assembly assembly, System.Type extensionType)
Mono.CSharp.RootNamespace.ComputeNamespace (Mono.CSharp.CompilerContext ctx, System.Type extensionType)
Mono.CSharp.GlobalRootNamespace.ComputeNamespaces (Mono.CSharp.CompilerContext ctx)
Mono.CSharp.Driver.LoadReferences ()
Mono.CSharp.Evaluator.InitAndGetStartupFiles (System.String[] args)
Mono.CSharp.Evaluator.Init (System.String[] args)
CharlesOlinerCommandConsole.CommandConsole.Start () (at Assets/CommandConsole/Scripts/CommandConsole.cs:123)
I tried elevating the permissions of the Unity Editor, but it did not work.
I also tried putting Mono.CSharp.dll in the plugins folder, but that also did not work.
Any help is appreciated.

Related

Getting System.InvalidProgramException: Invalid IL code exception

I've got a Xamarin Forms project using EF Core 2.2.4 with SQLite. In a number of different places in my code I get a transient error (maybe 1% of the time?) that seems like an EF Core bug, but I can't say for sure.
One sample of code where I get this is:
var context = new DatabaseContext();
var dbItem = await context.MobileErrors.FirstOrDefaultAsync(me => me.Id.Equals(item.Id)).ConfigureAwait(false);
DatabaseContext inherits from DbContext. The exception also happens with ToListAsync() and other EF calls. The exception is:
System.InvalidProgramException: Invalid IL code in (wrapper
dynamic-method) object:lambda_method
(System.Runtime.CompilerServices.Closure): method body is empty.
at (wrapper managed-to-native)
System.Delegate.CreateDelegate_internal(System.Type,object,System.Reflection.MethodInfo,bool)
at System.Delegate.CreateDelegate (System.Type type, System.Object
firstArgument, System.Reflection.MethodInfo method, System.Boolean
throwOnBindFailure, System.Boolean allowClosed) [0x002f0] in
<58604b4522f748968296166e317b04b4>:0 at
System.Delegate.CreateDelegate (System.Type type, System.Object
firstArgument, System.Reflection.MethodInfo method) [0x00000] in
<58604b4522f748968296166e317b04b4>:0 at
System.Reflection.Emit.DynamicMethod.CreateDelegate (System.Type
delegateType, System.Object target) [0x0001a] in
<58604b4522f748968296166e317b04b4>:0 at (wrapper dynamic-method)
System.Object.lambda_method(System.Runtime.CompilerServices.Closure,Microsoft.EntityFrameworkCore.Query.QueryContext)
at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult]
(Microsoft.EntityFrameworkCore.Query.QueryContext queryContext,
System.Func2[T,TResult] compiledQuery,
Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger1[TLoggerCategory]
logger, System.Type contextType) [0x000d6] in
:0 at
Mobile.Services.MobileErrorsService.UpdateLocalAsync
(Mobile.Data.Models.DatabaseContext context,
Mobile.Data.Models.MobileError item) [0x00133] in
:0 at
Mobile.Services.MobileErrorsService+<>c__DisplayClass8_0.b__0 ()
[0x00115] in :0
Any ideas of changes I could try to resolve this issue? Thanks!

Assembly loading under TextTransform.exe, Mono

I have a .NET assembly, written in C#, which references the Microsoft.CodeAnalysis, Microsoft.CodeAnalysis.CSharp and System.Collections.Immutable assemblies and contains this function:
public string GetFirstNamespace(string code)
{
var tree = CSharpSyntaxTree.ParseText (code);
var root = tree.GetRoot ();
var #using = root.DescendantNodes ().OfType<UsingDirectiveSyntax> ();
var #types = root.DescendantNodes ().OfType<TypeDeclarationSyntax> ();
var #enums = root.DescendantNodes ().OfType<EnumDeclarationSyntax> ();
var #namespaces = root.DescendantNodes ().OfType<NamespaceDeclarationSyntax> ();
return #namespaces.First ().GetText ().ToString();
}
I can call this function from a command-line program written in C#:
public static void Main(string[] args)
{
string code = "using System; namespace Foo { public class Program { public static void Main(string[] args) { Console.WriteLine(\"Hello, World\"); } } }";
Utilities u = new Utilities();
string ns = u.GetFirstNamespace(code);
Console.WriteLine (ns);
}
But if I try to invoke the same method from a T4 template, run using TextTransform.exe, I get into all sorts of bother. Initially, there are a long list of assemblies that it cannot find:
$ /usr/lib/monodevelop/AddIns/MonoDevelop.TextTemplating/TextTransform.exe -P=./bin/Debug T4Template.tt
Processing 'T4Template.tt' failed.
(0,0): ERROR Metadata file `System.Runtime.dll' could not be found
(0,0): ERROR Metadata file `System.Collections.dll' could not be found
(0,0): ERROR Metadata file `System.Runtime.InteropServices.dll' could not be found
(0,0): ERROR Metadata file `System.Resources.ResourceManager.dll' could not be found
(0,0): ERROR Metadata file `System.Globalization.dll' could not be found
(0,0): ERROR Metadata file `System.Linq.dll' could not be found
(0,0): ERROR Metadata file `System.Diagnostics.Debug.dll' could not be found
(0,0): ERROR Metadata file `System.Runtime.Extensions.dll' could not be found
(0,0): ERROR Metadata file `System.Threading.dll' could not be found
(0,0): ERROR Metadata file `System.Diagnostics.Tools.dll' could not be found
(0,0): ERROR Metadata file `System.Reflection.dll' could not be found
Adding one of the installed Mono directories to the assembly search path fixes these, but leads to other problems:
$ /usr/lib/monodevelop/AddIns/MonoDevelop.TextTemplating/TextTransform.exe -P=./bin/Debug -P=/usr/lib/mono/4.5/Facades T4Template.tt
Invalid type Microsoft.CodeAnalysis.SyntaxTree for instance field Microsoft.CodeAnalysis.SyntaxNode:_syntaxTree
Processing 'T4Template.tt' failed.
(0,0): ERROR Error running transform: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeLoadException: Failure has occurred while loading a type.
at T4CSTest.Utilities.GetFirstNamespace (System.String code) <0x4047b4e0 + 0x0002f> in <filename unknown>:0
at Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation21eb083a.TransformText () <0x4047afa0 + 0x0009b> in <filename unknown>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x7f7d1d530780 + 0x000a1> in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x7f7d1d530780 + 0x000ef> in <filename unknown>:0
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) <0x7f7d1d368cf0 + 0x0002a> in <filename unknown>:0
at Mono.TextTemplating.CompiledTemplate.Process () <0x4047a520 + 0x0036f> in <filename unknown>:0
The same thing works under Visual Studio 2013 on Windows.
I've tried this using the referenced assemblies got from NuGet and also using the Microsoft.CodeAnalysis.* assemblies from https://github.com/mono/roslyn, built using Mono 4.2.1 (with a one-line patch to fix a build error).
My basic question here is, how can I get this to work?
A subsidiary question is, why doesn't it find all those System.* assemblies without help? Shouldn't it find them anyway? Is this because those Microsoft.CodeAnalysis.* assemblies are built against the PCL? Adding in the PCL directory to the search path causes an even longer list of problems, mostly with multiply-defined classes (not too unexpected, really).
Edit Full demonstration code is available at https://github.com/tomkcook/T4CSTest

Xamarin Binding "Wrapper type '' is missing its native ObjectiveC Class

I am trying to bind an external accessory MSR SDK to Xamarin. Note, this is ON the device. It does not work in the simulator at all. I keep getting this error:
Wrapper type 'iMagProII.IMag' is missing its native ObjectiveC class 'IMag'.
Here is my .cs with my linker flags:
[assembly: LinkWith ("libiMagSDK.a", LinkTarget = LinkTarget.ArmV6 | LinkTarget.ArmV7 | LinkTarget.Simulator, SmartLink = true, ForceLoad = true, IsCxx = true, Frameworks = "CoreGraphics ExternalAccessory", LinkerFlags="-lsqlite3.0 -lc++")]
Here is the Stack Trace:
at MonoTouch.Registrar.DynamicRegistrar.OnRegisterType (MonoTouch.Registrar.ObjCType type) [0x00334] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pmcs-compat.DynamicRegistrar.cs:573
at MonoTouch.Registrar.Registrar.RegisterTypeUnsafe (System.Type type, System.Collections.Generic.List`1& exceptions) [0x009a4] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pmcs-compat.Registrar.cs:1027
at MonoTouch.Registrar.Registrar.RegisterType (System.Type type, System.Collections.Generic.List`1& exceptions) [0x00011] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pmcs-compat.Registrar.cs:680
at MonoTouch.Registrar.DynamicRegistrar.Register (System.Type type) [0x00002] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pmcs-compat.DynamicRegistrar.cs:839
at MonoTouch.ObjCRuntime.Class.Register (System.Type type) [0x00000] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pmcs-compat.Class.cs:126
at MonoTouch.ObjCRuntime.Class.GetHandle (System.Type type) [0x00000] in <filename unknown>:0
at MonoTouch.Foundation.NSObject.AllocIfNeeded () [0x00015] in /Developer/MonoTouch/Source/maccore/src/Foundation/.pmcs-compat.NSObject2.cs:390
at MonoTouch.Foundation.NSObject..ctor (MonoTouch.Foundation.NSObjectFlag x) [0x00006] in /Developer/MonoTouch/Source/maccore/src/Foundation/.pmcs-compat.NSObject2.cs:102
at iMagProII.IMag..ctor () [0x00000] in /Users//Projects/Xamarin/Bindings/Unimag/iMagProII/obj/Debug/ios/iMagProII/IMag.g.cs:112
at iMagProII.iOS.ImagViewController.ViewDidLoad () [0x0005c] in /Users//Projects/Xamarin/Bindings/Unimag/iMagProII.iOS/ImagViewController.cs:46
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:IntPtr_objc_msgSendSuper (intptr,intptr)
at MonoTouch.UIKit.UIViewController.get_View () [0x00030] in /Developer/MonoTouch/Source/monotouch/src/build/compat/UIKit/.pmcs-compat.UIViewController.g.cs:2232
at iMagProII.iOS.ImagViewController..ctor () [0x00008] in /Users//Projects/Xamarin/Bindings/Unimag/iMagProII.iOS/ImagViewController.cs:23
at iMagProII.iOS.AppDelegate.FinishedLaunching (MonoTouch.UIKit.UIApplication app, MonoTouch.Foundation.NSDictionary options) [0x00016] in /Users//Projects/Xamarin/Bindings/Unimag/iMagProII.iOS/AppDelegate.cs:33
at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0004c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/.pmcs-compat.UIApplication.cs:38
at iMagProII.iOS.Application.Main (System.String[] args) [0x00008] in /Users//Projects/Xamarin/Bindings/Unimag/iMagProII.iOS/Main.cs:17
Any help on getting this library bound would be greatly appreciated. I have been banging my head at it for hours now.
This occurs when the class IMag can't be found in the final executable.
The most common reasons for this are:
A typo in the class name.
The native library does not include the architecture you're building for. For instance the native library needs to contain i386 code to run in the simulator. You can use the lipo tool to list the architectures in the native library:
$ lipo -info /path/to/libiMagSDK.a
You also need to know the architecture you're using for the app, you can check this in the project's iOS Build settings, on the Advanced page. Select one that the native library includes.
The native library in the binding project depends on another native library which is not in the binding project (and the IMag class is in that other library). All non-platform dependencies must be included.
The native library is incorrectly built, and doesn't include the class you're trying to bind (this is not frequent, but I've still seen it several times). You can use the nm tool to check what's included in a native library:
$ nm -arch armv7 /path/to/libiMagSDK.a | grep IMag
0x0000f00d S _OBJC_CLASS_$_IMag
[other results]
The above result would indicate that the class is included in the native library.

System.Collections.Generic.KeyNotFoundException with Mono, but not Microsoft's .NET

I found a really strange problem while creating unit tests that only occurs with the Mono runtime (Xamarin on Mac included), but runs fine within Visual Studio. I isolated it as far as I could, and I reached a point that I can't tell if it is a bug with Mono, Moq or Castle DinamicProxy, although it only crashes when using the Mono runtime.
This is the code:
using System;
using System.Collections.Generic;
using Moq;
namespace ConsoleApplication1
{
public interface ISomething<T>
{
List<T> DoSomething<U>(/*Func<T, U> expression*/);
}
public class Foo { }
public class Program
{
public static void Main(string[] args) {
var mock = new Mock<ISomething<Foo>>();
Console.WriteLine(mock.Object);
}
}
}
Here's that I know:
It compiles and run with within Visual Studio 2012. The output is "Castle.Proxies.ISomething`1Proxy"
It does not work when running with the Mono runtime. An exception is thrown (see below)
If I change the declaration from an interface to an abstract class, it works with Mono
If I change the return type from List<T> to anything else, it works with Mono
If I remove the generic type <U>, it works with mono
Got the same results under Windows, Mac and Linux using the command line build from http://mono-project.com
In Windows it fails with Mono 2.10.9, but works within Xamarin.Studio (4.0.10)
In Mac, it fails within Xamarin.Studio (4.0.10)
I recompiled Moq linking agains the latest DynamicProxy release (Castle.Core.3.2.0), with no changed to the behaviour.
Although I've found this problem when using Moq, but I can't tell if it's related to it or even DynamicProxy. The partial exception is below, complete can be found at http://pastie.org/8203093
mono ConsoleApplication1.exe
[ERROR] FATAL UNHANDLED EXCEPTION: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2[System.String,System.Reflection.Emit.GenericTypeParameterBuilder].get_Item (System.String key) [0x00000] in <filename unknown>:0
at Castle.DynamicProxy.Internal.TypeUtil.CloseGenericParametersIfAny (Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter emitter, System.Type[] arguments) [0x00000] in <filename unknown>:0
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget (System.Type interfaceToProxy, System.Type[] additionalInterfacesToProxy, Castle.DynamicProxy.IInterceptor[] interceptors) [0x00000] in <filename unknown>:0
at Moq.Proxy.CastleProxyFactory.CreateProxy[ISomething`1] (ICallInterceptor interceptor, System.Type[] interfaces, System.Object[] arguments) [0x00000] in <filename unknown>:0
[....]
at Moq.Mock`1[ConsoleApplication1.ISomething`1[ConsoleApplication1.Foo]].<InitializeInstance>b__0 () [0x00000] in <filename unknown>:0
at Moq.PexProtector.Invoke (System.Action action) [0x00000] in <filename unknown>:0
at Moq.Mock`1[ConsoleApplication1.ISomething`1[ConsoleApplication1.Foo]].InitializeInstance () [0x00000] in <filename unknown>:0
at Moq.Mock`1[ConsoleApplication1.ISomething`1[ConsoleApplication1.Foo]].OnGetObject () [0x00000] in <filename unknown>:0
at Moq.Mock.GetObject () [0x00000] in <filename unknown>:0
at Moq.Mock.get_Object () [0x00000] in <filename unknown>:0
at Moq.Mock`1[ConsoleApplication1.ISomething`1[ConsoleApplication1.Foo]].get_Object () [0x00000] in <filename unknown>:0
at ConsoleApplication1.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0

Mono TypeLoadException in ChannelFactory<>.CreateChannel, no exception on .NET/Windows

I am creating a net.tcp based WCF service to control one of our backend applications. During development and testing on a Windows machine everything worked as expected.
However when I tried to run the very same application using Mono on either the same Windows box (Mono 2.10.6) or on Debian Squeeze (with Mono 2.10.5), I suddenly get a TypeLoadException in the ChannelFactory.
In the end it comes down to just this call that fails:
controlHost = ChannelFactory<IControlServiceContract>.CreateChannel(
new NetTcpBinding(SecurityMode.None),
new EndpointAddress(endpointAddress)
);
With this definition for IControlServiceContract in another assembly:
[ServiceContract]
public interface IControlServiceContract
{
[OperationContract(IsOneWay = true)]
void Ping ();
[OperationContract(IsOneWay = true)]
void Shutdown ();
[OperationContract]
int GetCommandCount ();
}
Which runs fine when started directly (i.e. using .NET).
When executed using mono --debug --runtime=v4.0 though it crashes with this super sweet stack trace:
! Ein Fehler ist beim Erzeugen des Kanals auf net.tcp://localhost:34684/watchdog/watchdog.ctrl/ aufgetreten
A type load exception has occurred.
at System.Linq.Enumerable.Union[Object] (IEnumerable`1 first, IEnumerable`1 second, IEqualityComparer`1 comparer) [0x00014] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.Core\System.Linq\Enumerable.cs:2948
at System.Linq.Enumerable.Union[Object] (IEnumerable`1 first, IEnumerable`1 second) [0x00007] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.Core\System.Linq\Enumerable.cs:2938
at System.ServiceModel.Description.ContractDescriptionGenerator.GetOrCreateOperation (System.ServiceModel.Description.ContractDescription cd, System.Reflection.MethodInfo mi, System.Reflection.MethodInfo serviceMethod, System.ServiceModel.OperationContractAttribute oca, System.Type asyncReturnType, Boolean isCallback, System.Type givenServiceType) [0x001f2] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:314
at System.ServiceModel.Description.ContractDescriptionGenerator.FillOperationsForInterface (System.ServiceModel.Description.ContractDescription cd, System.Type exactContractType, System.Type givenServiceType, Boolean isCallback) [0x00131] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:240
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContractInternal (System.Type givenContractType, System.Type givenServiceType, System.TypeserviceTypeForCallback) [0x00296] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:197
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType, System.Type serviceTypeForCallback) [0x00000] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:136
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType) [0x00000] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:131
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type contractType) [0x00000] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescriptionGenerator.cs:101
at System.ServiceModel.Description.ContractDescription.GetContract (System.Type contractType) [0x00017] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel.Description\ContractDescription.cs:66
at System.ServiceModel.ChannelFactory`1[com.derixx.dll.controlservicehost.ServiceBase.IControlServiceContract].CreateDescription () [0x00000] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel\ChannelFactory_1.cs:185
at System.ServiceModel.ChannelFactory`1[com.derixx.dll.controlservicehost.ServiceBase.IControlServiceContract]..ctor (System.Type type) [0x00033] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel\ChannelFactory_1.cs:56
at System.ServiceModel.ChannelFactory`1[com.derixx.dll.controlservicehost.ServiceBase.IControlServiceContract]..ctor (System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) [0x00000] in <filename unknown>:0
at System.ServiceModel.ChannelFactory`1[com.derixx.dll.controlservicehost.ServiceBase.IControlServiceContract].CreateChannel (System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress address) [0x00000] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.10.6\mcs\class\System.ServiceModel\System.ServiceModel\ChannelFactory_1.cs:130
at applicationframework.ControlApplicationBase.ConnectionCreate (IControlServiceContract& controlHost, System.String endpointHost, Int32 endpointPort, System.String endpointPath) [0x00000] in <filename unknown>:0
All assemblies used int his project are either our own ones targeted at Framework 4.0, core assemblies and log4net 1.2.10/2.0.50727.
Does anyone have a clue what this could be and where I should start digging?
Well, if it works on .NET and not Mono it's definitely a bug.
I would go ahead and first thing submit it in http://bugzilla.xamarin.com/
Then maybe hangout in irc://irc.gnome.org/mono , and poke Atsushi Enomoto (nick "eno") which is the maintainer of WCF, to see what he thinks.

Categories

Resources