Mono and Extension Methods with MonoDevelop 2.8.5 - mono

I have written a unit test with MD 2.8.5 in a project that includes System.Core and with build target Mono/.NET 3.5. I really like the Assert.Throws of the newer NUnit, so decided to write an extension method for it. I created a new file with this as its content in the same namespace as the test. Can anyone see my error?
public delegate void TestDelegate();
public static class AssertThrows
{
public static T Throws<T>(this Assert assert, TestDelegate td)
where T : Exception
{
try
{
td();
}
catch(T e)
{
return e;
}
catch
{
throw new AssertionException("Wrong exception type.");
}
throw new AssertionException("Did not throw an error.");
}
}
MonoDevelop "sees" the extension method through its code completion. However, the compiler reports:
Performing main compilation...
/Users/shamwow/dev/EngineTests.cs(19,37): error CS0117:
`NUnit.Framework.Assert' does not contain a definition for `Throws'
/Applications/MonoDevelop.app/Contents/MacOS/lib/monodevelop/AddIns/NUnit/nunit.framework.dll (Location of the symbol related to previous error)
Build complete -- 1 error, 0 warnings
(I know MD and Mono are not the same.)

I assume you're trying to use it just as:
Assert.Throws<FooException>(() => ...);
Extension methods don't work like that - they appear to be instance methods on the extended type. As you won't have an instance of Assert, you can't call your extension method like that.

Related

Executing a Jpype file

I am trying to implement a example given in the following tutorial:
enter link description here
I have been trying to execute this program.However I am stuck on an step which is to "Then place the .class file in the (current_directory)/org/wg3i/test/ directory.".So, when I made a Java file from BlueJ I have the .class file however I am not sure how I can place that file in (current_directory)/org/wg3i/test/ directory.Also where exactly is this directory located.
Additional Question:
I am trying to implement the following code.
import org.nlogo.headless.HeadlessWorkspace;
public class Example2 {
public static void main(String[] argv) {
HeadlessWorkspace workspace =
HeadlessWorkspace.newInstance() ;
try {
workspace.open(
"models/Sample Models/Earth Science/"
+ "Fire.nlogo");
workspace.command("set density 62");
workspace.command("random-seed 0");
workspace.command("setup");
workspace.command("repeat 50 [ go ]") ;
System.out.println(
workspace.report("burned-trees"));
workspace.dispose();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
which is given in the following linkenter link description here
However, whenever I try to execute this java code using javac I get an error saying package org.nlogo.headless.HeadlessWorkspace doesn't exist and also says HeadlessWorkspace doesn't exist for line 4th.
I know that the link I inserted says this:
In order to compile and run this, NetLogo.jar must be in your classpath. The lib directory, containing additional required libraries, must also be present.
But I am not sure what it exactly asks me to do.
Also, I am working in Linux.

Can't get sample code to work

I am new to JavaFX coding (in IntelliJ IDEA), and have been reading / searching all over on how to swap scenes in the main controller / container. I found jewelsea's answer in another thread (Loading new fxml in the same scene), but am receiving an error on the following code.
public static void loadVista(String fxml) {
try {
mainController.setVista(
FXMLLoader.load(VistaNavigator.class.getResource(fxml)));
} catch (IOException e) {
e.printStackTrace();
}
}
The error I am receiving is the following:
Error:(56, 27) java: method setVista in class sample.MainController cannot be applied to given types;
required: javafx.scene.Node
found: java.lang.Object
reason: actual argument java.lang.Object cannot be converted to javafx.scene.Node by method invocation conversion
I know other people have gotten this to work, but all I have done is create a new project and copy the code. Can anyone help me?
It looks like you are trying to compile this with JDK 1.7: the code will only work in JDK 1.8 (the difference here being the enhanced type inference for generic methods introduced in JDK 1.8).
You should configure IntelliJ to use JDK 1.8 instead of 1.7.
If you want to try to revert the code to be JDK 1.7 compatible, you can try to replace it with
public static void loadVista(String fxml) {
try {
mainController.setVista(
FXMLLoader.<Node>load(VistaNavigator.class.getResource(fxml)));
} catch (IOException e) {
e.printStackTrace();
}
}
(with the appropriate import javafx.scene.Node ;, if needed). Of course, there may be other incompatibilities since the code you are using is targeted at JDK 1.8.

How do I get 100% code coverage for "catch with rethrow" block in VB.NET in Visual Studio 2010 Ultimate?

I am unable to achieve 100% code coverage for a "catch with rethrow" block in my VB.NET source code. My workplace IDE is Visual Studio 2010 Ultimate. Below example represents a simplified version of my actual problem.
Source in C#: (light-blue background indicates full code coverage)
Equivalent source in VB.NET: (yellow background indicates partial code coverage)
MSTests for both C# and VB.NET source (intended to achieve 100% code coverage)
Code Coverage Report
The code coverage report shows 100% for C#, but only 91.67% for VB.NET. It also shows 1 block of code with 0 lines being uncovered in VB.NET.
Is this an issue with the tool? Or am I missing something obvious?
EDIT #1: Sharing source code as requested by #Raptor
Source code in C#
public class CodeCoverage
{
public void DoWork(bool flag = false)
{
try
{
Thread.Sleep(1);
if (flag)
{
throw new Exception("test");
}
}
catch (Exception ex)
{
throw new Exception(string.Format("something happened: {0}", ex.Message));
}
}
}
Source code in VB.NET
Public Class CodeCoverage2
Public Sub DoWork(Optional ByVal flag As Boolean = False)
Try
Thread.Sleep(1)
If flag Then
Throw New Exception("test")
End If
Catch ex As Exception
Throw New Exception(String.Format("something happened: {0}", ex.Message))
End Try
End Sub
End Class
Source code for MSTests
[TestClass]
public class CodeCoverageTest
{
[TestMethod]
public void DoWorkTest()
{
var obj = new CodeCoverage();
obj.DoWork();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void DoWorkTest2()
{
var obj = new CodeCoverage();
obj.DoWork(true);
}
[TestMethod]
public void DoWorkTest3()
{
var obj = new CodeCoverage2();
obj.DoWork();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void DoWorkTest4()
{
var obj = new CodeCoverage2();
obj.DoWork(true);
}
}
If you look at the IL generated for the VB project in debug mode, you will see the following in the catch block:
IL_002f: call string [mscorlib]System.String::Format(string, object)
IL_0034: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0039: throw
IL_003a: call void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()
IL_003f: leave.s IL_0041
Since IL_0039 throws, you would never hit IL_003a, so you have code that never gets executed.
In release mode, the IL for ClearProjectError is not generated.
Not enough reputation to comment on John Koerner's reply, which is correct, but to add - we solved this by having our test target run in release mode. This causes code coverage to work properly.
EG:
DEBUG Configuration:
MyApplication - RELEASE ANY CPU
MyTests - DEBUG ANY CPU
Results:
Old: DEBUG/DEBUG - 1 line missed N-1/N % coverage
New: RELEASE/DEBUG - 0 lines missed, 100 % coverage
Thank you John for pointing us in the right direction of looking at the IL.

Rename "params" parameter in Java Bindings Library with Mono for Android?

I'm trying to create a Java Binding Library for BugSense, but one of the methods has a parameter named "params" which is a reserved word in C#. I've tried to use the Metadata.xml file to rename it, but I can't figure out how to access the class, let alone the method or it's parameter.
Here is the problem code it's generating:
namespace Com.Bugsense.Trace {
[global::Android.Runtime.Register ("com/bugsense/trace/ActivityAsyncTask", DoNotGenerateAcw=true)]
internal partial class ActivityAsyncTaskInvoker : ActivityAsyncTask {
static IntPtr id_doInBackground_arrayLjava_lang_Object_;
[Register ("doInBackground", "([Ljava/lang/Object;)Ljava/lang/Object;", "GetDoInBackground_arrayLjava_lang_Object_Handler")]
protected override global::Java.Lang.Object DoInBackground (global::Java.Lang.Object[] params)
{
if (id_doInBackground_arrayLjava_lang_Object_ == IntPtr.Zero)
id_doInBackground_arrayLjava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "doInBackground", "([Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr native_params = JNIEnv.NewArray (params);
global::Java.Lang.Object __ret = Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (Handle, id_doInBackground_arrayLjava_lang_Object_, new JValue (native_params)), JniHandleOwnership.TransferLocalRef);
if (params != null) {
JNIEnv.CopyArray (native_params, params);
JNIEnv.DeleteLocalRef (native_params);
}
return __ret;
}
}
}
Here is my mapping, which I feel should work, but just refuses to.
<attr path="/api/package[#name='com.bugsense.trace']/class[#name='ActivityAsyncTaskInvoker']/method[#name='doInBackground']/parameter[#name='params']" name="managedName">#params</attr>
I've tried everything I can think of. Please, HELP!
So, turns out it's just a bug in the current version of Mono for Android. If you update to the 4.2.4 build, which is in beta, everything compiles fine.

Exposing a managed COM local server - E_NOINTERFACE

Im trying to expose a local server that is written in C# to unmanaged code to allow interop! The managed code looks like that:
[Guid("A0D470AF-0618-40E9-8297-8C63BAF3F1C3")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyLocalInterface
{
void LogToServer(string message);
}
[Guid("9E9E5403-7993-49ED-BAFA-FD9A63A837E3")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class MyLocalClass : IMyLocalInterface
{
public MyLocalClass()
{
Console.WriteLine("Object created!");
}
public void LogToServer(string message)
{
Console.WriteLine("Log > " + message);
}
}
class Program
{
[MTAThread]
static void Main(string[] args)
{
var srv = new RegistrationServices();
var cookie = srv.RegisterTypeForComClients(typeof(MyLocalClass), RegistrationClassContext.LocalServer | RegistrationClassContext.RemoteServer, RegistrationConnectionType.MultipleUse);
Console.ReadLine();
srv.UnregisterTypeForComClients(cookie);
}
}
And my unmanaged code does the following:
#import "ManagedLocServer.tlb" no_namespace raw_interfaces_only
int _tmain(int argc, _TCHAR* argv[])
{
CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
IMyLocalInterfacePtr ptr;
ptr.CreateInstance(__uuidof(MyLocalClass));
ptr->LogToServer(L"Initializing...");
}
CoUninitialize();
return 0;
}
After debugging ive seen that CoCreateInstance works without any problems, that means "Object created" is printed into the managed servers console. But then QueryInterface on that object fails with E_NOINTERFACE. Im a bit confused why this happens. Is it a problem with registration (i only have a LocalServer32 entry for my CLSID)? Is it a problem within my managed code? Would be nice if someone could give me a hint :)
Greetings
Joe
You are using out-of-process COM. That requires marshaling support, to make a method call the arguments of the method need to be serialized. That's normally done by building the proxy/stub DLL from the code generated by midl.exe from the .idl file. Or by using the standard marshaller which works with the type library. Both require registry entries in HKCR\Interface
You get the E_NOINTERFACE because COM cannot find a marshaller. This is trivial to solve if you have an .idl file but you don't, the server is implemented in .NET. No idea how to solve this, I never tried to make this work. A remote possibility is that the CLR interop layer provides marshaling support. But you'd surely at least have to use ComInterfaceType.InterfaceIsDual. This is just a guess. If I tried to make this work, I'd start from an .idl first.