Using NancyFX with Razor view engine, how? - razor

I am using the latest NancyFX via nuget and have installed the Razor view engine also via nuget because the SSVE doesn't suit my needs (I need more conditional logic options).
The trouble is that all I can get is a 500 error anytime I call a Razor view:
Nancy.RequestExecutionException: Oh noes! ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Nancy.ViewEngines.DefaultViewCache.GetOrAdd[TCompiledView](ViewLocationResult viewLocationResult, Func`2 valueFactory)
at Nancy.ViewEngines.Razor.RazorViewEngine.GetOrCompileView(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Type passedModelType)
at System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
at CallSite.Target(Closure , CallSite , RazorViewEngine , ViewLocationResult , IRenderContext , Assembly , Object )
at Nancy.ViewEngines.Razor.RazorViewEngine.GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Object model)
at System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
at Nancy.ViewEngines.Razor.RazorViewEngine.<>c__DisplayClass27.b__26(Stream stream)
at Nancy.Responses.MaterialisingResponse.PreExecute(NancyContext context)
--- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
I call the view here:
return View["Content/views/IO/fileBrowser/ViewPage2.cshtml", dirListing];
There is no error till that point.
The view is totally blank, no code at all. I have also tried view a new view specifying layout, still a 500 error. I've tried referencing the model I am passing, also tried not passing the model. Its all the same. How are you meant to use Razor with Nancy? What is the null reference?..
Nancy's super fun path has been nothing but frustration for me, nothing works out of the box :(

In the root of your web application you should have a views folder, all paths are relative to the views folder.
Without knowing what your module looks like I will give you an example:
public class ProductsModule : NancyModule
{
public ProductsModule()
{
Get["/"] = _ =>
{
....
return ["index", mymodel];
}
}
}
By default, not including other conventions including localization, Nancy will look for a folder called products inside views for a view named index.
So your folder structure should be:
-root
--views
---products
----index.cshtml
If the view is not found, it will then look back 1 directory inside views. so if your directory structure was:
-root
--views
---index.cshtml
Then it would find your view and render it.
There's much more to the discovery of views but this is the general design that you would use most often.

Related

Unable to mock the local variable inside a method in java [duplicate]

I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have
final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(myResults);
The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.
MyClass is an interface and myInstance is an implementation of that, if that matters.
What do I need to do to correct this spying behaviour?
Let me quote the official documentation:
Important gotcha on spying real objects!
Sometimes it's impossible to use when(Object) for stubbing spies. Example:
List list = new LinkedList();
List spy = spy(list);
// Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
In your case it goes something like:
doReturn(resultsIWant).when(myClassSpy).method1();
In my case, using Mockito 2.0, I had to change all the any() parameters to nullable() in order to stub the real call.
My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package
package common;
public class AnimalĀ {
void packageProtected();
}
package instances;
class Dog extends Animal { }
and the test classes
package common;
public abstract class AnimalTest<T extends Animal> {
#Before
setup(){
doNothing().when(getInstance()).packageProtected();
}
abstract T getInstance();
}
package instances;
class DogTest extends AnimalTest<Dog> {
Dog getInstance(){
return spy(new Dog());
}
#Test
public void myTest(){}
}
The compilation is correct, but when it tries to setup the test, it invokes the real method instead.
Declaring the method protected or public fixes the issue, tho it's not a clean solution.
The answer by Tomasz Nurkiewicz appears not to tell the whole story!
NB Mockito version: 1.10.19.
I am very much a Mockito newb, so can't explain the following behaviour: if there's an expert out there who can improve this answer, please feel free.
The method in question here, getContentStringValue, is NOT final and NOT static.
This line does call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), isA( ScoreDoc.class ));
This line does not call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), any( ScoreDoc.class ));
For reasons which I can't answer, using isA() causes the intended (?) "do not call method" behaviour of doReturn to fail.
Let's look at the method signatures involved here: they are both static methods of Matchers. Both are said by the Javadoc to return null, which is a little difficult to get your head around in itself. Presumably the Class object passed as the parameter is examined but the result either never calculated or discarded. Given that null can stand for any class and that you are hoping for the mocked method not to be called, couldn't the signatures of isA( ... ) and any( ... ) just return null rather than a generic parameter* <T>?
Anyway:
public static <T> T isA(java.lang.Class<T> clazz)
public static <T> T any(java.lang.Class<T> clazz)
The API documentation does not give any clue about this. It also seems to say the need for such "do not call method" behaviour is "very rare". Personally I use this technique all the time: typically I find that mocking involves a few lines which "set the scene" ... followed by calling a method which then "plays out" the scene in the mock context which you have staged... and while you are setting up the scenery and the props the last thing you want is for the actors to enter stage left and start acting their hearts out...
But this is way beyond my pay grade... I invite explanations from any passing Mockito high priests...
* is "generic parameter" the right term?
One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.
Example
#Autowired
private MonitoringDocumentsRepository repository
void test(){
repository = Mockito.spy(repository)
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:
repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$
#SpyBean to the rescue
If instead #Autowired annotation we use #SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger
repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$
and here is the code:
#SpyBean
private MonitoringDocumentsRepository repository
void test(){
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
Important gotcha on spying real objects
When stubbing a method using spies , please use doReturn() family of methods.
when(Object) would result in calling the actual method that can throw exceptions.
List spy = spy(new LinkedList());
//Incorrect , spy.get() will throw IndexOutOfBoundsException
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
I've found yet another reason for spy to call the original method.
Someone had the idea to mock a final class, and found about MockMaker:
As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline
Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods
After I merged and brought that file to my machine, my tests failed.
I just had to remove the line (or the file), and spy() worked.
One way to make sure a method from a class is not called is to override the method with a dummy.
WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
#Override
public void select(TreeItem i) {
log.debug("SELECT");
};
});
As mentioned in some of the comments, my method was "static" (though being called on by an instance of the class)
public class A {
static void myMethod() {...}
}
A instance = spy(new A());
verify(instance).myMethod(); // still calls the original method because it's static
Work around was make an instance method or upgrade Mockito to a newer version with some config: https://stackoverflow.com/a/62860455/32453
Bit late to the party but above solutions did not work for me , so sharing my 0.02$
Mokcito version: 1.10.19
MyClass.java
private int handleAction(List<String> argList, String action)
Test.java
MyClass spy = PowerMockito.spy(new MyClass());
Following did NOT work for me (actual method was being called):
1.
doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());
2.
doReturn(0).when(spy , "handleAction", any(), anyString());
3.
doReturn(0).when(spy , "handleAction", null, null);
Following WORKED:
doReturn(0).when(spy , "handleAction", any(List.class), anyString());

jaxbcontext.newinstance() with eclipselink MOXy hangs

disclaimer: I'm incredibly amateur at all of this
I'm trying to get the project I'm working on to output JSON in addition the XML.
Originally the prior method to do so involved a method that took in an argument of Element and recursively inserted things into an object of type net.sf JSONObject to create the JSON output, and used the normal JAXBContext's Marshaller to marshal into XML.
What I wanted was to use MOXy as my JAXB provider, and then marshal out both XML and JSON from the bindings.
Originally, when the XML was marshalled, I had:
jc = JAXBContext.newInstance("packageA:packageB:packageC...etc.");
public static String marshal(JAXBContext context, JAXBElement<?> je) throws JAXBException {
StringWriter sout = new StringWriter();
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(je, sout);
return sout.toString();
}
and then
JAXBElement<myObject> jaxb =
new JAXBElement<myObject>(myObject_QNAME, myObject.class, null, value);
return XmlResponseMessage(marshal(jc, jaxb));
}
(this is probably important, so I should mention that the application I'm working on uses the spring framework.)
Also, I've read every single one of Blaise's blog posts regarding EclipseLink. Some multiple times. I just have a very shallow understanding of it and would appreciate if instead of linking me to one of his pages you explained whatever solution on it is and why it works
That being said, I tried just including the jaxb.properties file in one of the packages to try to get MOXy as opposed to JAXBElement to get my bindings.
however, JAXBContext.newInstance("my list of : delimited packages") just makes the program hang. not even an error, just hangs it. stepping through just shows the call to the EclipseLink newInstance method hanging.
I've looked for many hours for solutions online. I have much too many classes to just include in a Class[], and so can't set the property by using an array of classes. which is also the reason I couldn't use the native moxy API instead of using the property file. I think i have EclipseLink set up correctly: I've set eclipselink_home in my environment variables, and added the eclipselink.jar to my buildpath.
UPDATE #2
A fix for this issue has been checked into the EclipseLink 2.4.2 and 2.5.0 streams and a nightly build containing the fix can be downloaded from the following link starting March 12, 2013:
http://www.eclipse.org/eclipselink/downloads/nightly.php
UPDATE #1
After a couple of email exchanges I think the problem you are encountering is due to the following bug. You can use the link to track our progress on this issue.
http://bugs.eclipse.org/402801
I'll demonstrate how it manifests itself below:
ObjectFactory
For the problem to occur you need to have an #XmlElementDecl annotation where thename is the same as the substitutionHeadName.
#XmlRegistry
public class ObjectFactory {
#XmlElementDecl(name="foo", substitutionHeadName="foo")
public JAXBElement<Foo> createBar(Foo foo) {
return new JAXBElement<Foo>(new QName("foo"), Foo.class, foo);
}
}
Domain Object (Foo)
Then on one of your domain objects you need to have an #XmlElementRef annotation referencing the element we defined in the #XmlElementDecl.
public class Foo {
#XmlElementRef(name="foo")
public Foo foo;
}
Demo
You will see the problem when you create the JAXBContext.
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class, ObjectFactory.class);
System.out.println(jc.getClass());
}
}
Trace
MOXy gets in an infinite loop adding the reference element.
...
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
...
ORIGINAL ANSWER
You could try using the following to create your JAXBContext. It bypasses the standard JAXB impl lookup code by using native MOXy code.
JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext("packageA:packageB:packageC...etc.");
If that works we'll know the problem is related to the impl look up code and we can go from there.

Unable to cast object of type nullable(of object) using entity framework

I'm currently using a scenario of MVC 4 WebAPI w Entity Framework database first modelling. Within my apicontroller it is giving me an error of:
An error has occurred.
Unable to cast object of type
'WhereSelectEnumerableIterator2[VB$AnonymousType_42[System.Nullable1[System.Guid],System.Collections.Generic.IEnumerable1[CK5.Airline]],VB$AnonymousType_51[System.Nullable1[System.Guid]]]'
to type 'System.Collections.Generic.IEnumerable1[CK5.Airline]'.
</ExceptionMessage>
<ExceptionType>System.InvalidCastException</ExceptionType>
<StackTrace> at lambda_method(Closure , Object , Object[] ) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object
instance, Object[] methodParameters) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object
instance, Object[] arguments) at
System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func1
func, CancellationToken cancellationToken)
Public Class AirlineController
Inherits ApiController
' GET api/Airline
Function GetAirlines() As IEnumerable(Of Airline)
Using db As New DefaultEntities
Return From p In db.Airlines.AsEnumerable Order By {p.Name} Group By ParentID = p.ParentID Into parentIDGroup = Group Select New With {.ParentID = ParentID}
End Using
End Function
End Class
Within my entity model object the ParentID is a nullable(of guid) type and I believe causing the problem. I've had this working before using a Linq2Sql scenerio, but with the update, this is giving me a problem. I don't believe it's a problem with the web api structure, just w entity framework. Where am I going wrong?
i fixed it. 1) For some reason EF doesn't like to use the statement Using db as New DBContext, it closes the connection before use I think. 2) I'm not sure why either, but it also doesn't like using lambda statements. So it didn't like the Order By or Group By statement. I'll have to look in to that. 3) problem was a bit unrelated, but as this was being a database first EF, I had also put in the globabl.asax this statement: Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of DefaultEntities)()). Thinking it would update the model or database based on changes. It lied to me. =/

How to fix "type exists in both assemblies" failure when using DynamicProxy types in an assembly referencing NSubstitute?

I have an application that uses DynamicProxy 3.1 to do runtime interception. I have a test assembly that uses NSubstitute for mocking. I just wrote some "integration" tests against my fully bootstrapped container (StructureMap using InterceptWith to do the interception) so that I can assert that certain types coming out of the container are proxied properly.
[Subject(typeof(RobotBoard))]
public class When_resolving_an_intercepted_type : WithContainer<IRobotBoard>
{
It should_have_recovery = () => Subject.ShouldHaveInterceptor<RecoveryInterceptor>();
}
public static class TestExtensions
{
public static void ShouldHaveInterceptor<T>(this object obj)
where T : IInterceptor
{
((IProxyTargetAccessor)obj)
.GetInterceptors()
.ToList()
.Exists(x => x is T)
.ShouldBeTrue();
}
}
However, I get this error, indicating that DynamicProxy references are inside the NSubstitute assembly, too! (it appears to be ilmerged).
Error 11 MyCompany.MyModule.Specifications D:\code\source\tests\When_resolving_an_intercepted_type.cs
The type 'Castle.DynamicProxy.IProxyTargetAccessor' exists in both 'd:\code\packages\Castle.Core.3.1.0\lib\net40-client\Castle.Core.dll' and 'd:\code\packages\NSubstitute.1.4.2.0\lib\NET40\NSubstitute.dll'
Is there anyway around this conflict?
You could grab the NSubstitute source code and remove the ilmerge commands from the project's targets. I've opened issue 86 on their repository to address this.
<exec command=""$(MSBuildProjectDirectory)\..\..\ThirdParty\Ilmerge\ILMerge.exe" /internalize:"$(MSBuildProjectDirectory)\ilmerge.exclude" /keyfile:$(AssemblyOriginatorKeyFile) /out:#(MainAssembly) "#(IntermediateAssembly)" #(AssembliesToMerge->'"%(FullPath)"', ' ')" Condition=" '$(TargetFrameworkVersion)' == 'v3.5'" />
<exec command=""$(MSBuildProjectDirectory)\..\..\ThirdParty\Ilmerge\ILMerge.exe" /internalize:"$(MSBuildProjectDirectory)\ilmerge.exclude" /keyfile:$(AssemblyOriginatorKeyFile) /out:#(MainAssembly) /targetplatform:"v4,$(FrameworkReferenceAssemblyPath)." "#(IntermediateAssembly)" #(AssembliesToMerge->'"%(FullPath)"', ' ')" Condition=" '$(TargetFrameworkVersion)' == 'v4.0'" />
You could try using an alias to reference the NSubstitute or DynamicProxy assemblies.
See MSDN How to: Use the Global Namespace Alias (C# Programming Guide) for more info.
You can use the 'extern alias' directive as explained here:
http://blogs.msdn.com/b/ansonh/archive/2006/09/27/774692.aspx
basically
(1) in VS, go to the assembly reference for FooVersion1, and right click > Properties.
(2) change 'aliases' value to 'FooVersion1'
(3) in your .cs file use:
extern alias FooVersion1;
using foo = FooVersion1::FooVersion1;
...
var something = foo.FooClass();

Jibx always gives "Error during validation: null"

I'm really stumped on this incredibly simple mapping. It looks just like one of the examples even. If I comment out the internal structure, it'll run the binding compiler successfully. If I put the internal structure back in, it fails. Note that the internal structure is just defining the XML. This is basically example5 of the JIBX tutorial examples.
<binding>
<mapping name="RequestTransaction" class="TransactionRequest">
<value name="version" set-method="setVersion" get-method="getVersion" style="attribute" />
<structure name="transHeader">
<value name="requestCount" set-method="setRequestCount" get-method="getRequestCount"/>
</structure>
</mapping>
<binding>
Then I get the following error on the jibx compile:
Error: Error during validation: null; on mapping element at (line 2, col 97, in jibx-binding.xml)
I'm absolutely stumped and out of ideas. Google shows nothing useful.
The <structure> is arguably the most important concept in JiBX binding because it allows you to map arbitrary XML to your Java classes without forcing you to create bloated and ugly layers of nested Java objects and classes to match the XML design.
In this case your binding declares that you have an XML element named <transHeader> that will not be present in your Java class.
With some slight fixes to your XML format, your binding works perfectly. I assume the fact that your binding has two <binding> open tags rather than and open and close <binding></binding> is a typo, because you said you got it to work without the structure. Also add <?xml version="1.0"?> at the top of your binding file. Those two XML mods allow the JiBX 1.2 binding compiler to work with the following Java class:
(Note: you didn't provide the Java class this binding is for so I had to reconstruct it from the info you put in the binding file. The obvious side effect of this is that I reconstructed a class that will work with this binding. But the simple fact is that a JiBX binding by design contains all the info you need to know about the class and the XML.)
public class TransactionRequest {
private String version;
private int requestCount;
public void setVersion(String ver) {
version = ver;
}
public String getVersion() {
return version;
}
public void setRequestCount(int count) {
requestCount = count;
}
public int getRequestCount() {
return requestCount;
}
}
compile the class then run the binding compiler with:
>java -jar jibx-bind.jar jibx-binding.xml
To test it I used the following sample.xml:
(Note: you also didn't provide the XML you are trying to map so again I created a sample based on what you did provide)
<?xml version="1.0"?>
<RequestTransaction version="0.1">
<transHeader>
<requestCount>3</requestCount>
</transHeader>
</RequestTransaction>
Running the test uses the following code:
public static void main(String[] argz) {
String fileName = "./sample.xml";
IBindingFactory bfact = null;
IUnmarshallingContext uctx = null;
TransactionRequest sample = null;
try {
bfact = BindingDirectory.getFactory(TransactionRequest.class);
uctx = bfact.createUnmarshallingContext();
InputStream in = new FileInputStream(fileName);
sample = (TransactionRequest)uctx.unmarshalDocument(in, null);
System.out.println(sample.getRequestCount());
System.out.println(sample.getVersion());
}
catch (Exception e) {
e.printStackTrace();
}
}
And it runs successfully.
It's been a while now, but I found it was related to inheritance. I needed to give mappings for everything in the inheritance tree, including interfaces as I recall.
I ended up creating a wrapper object, which I've found seems to be the easiest way to use JIBX in general. Trying to map a true domain class causes tendrils into every class that class touches and I have to unjar everything so JIBX can find the classes, including 3rd party libs.