Why do I need nhibernate.dll referenced in my asp.net mvc project? - visual-studio

All my data logic is in another data layer project that I reference in my asp.net mvc project.
Now if I call:
CategoryDAO.GetById(1);
Everything works fine.
If I call:
CategoryDAO.GetBlah(1);
VS.NET complains saying
"Error 102: The type 'NHibernate.Criterion.Order' is defined in an assembly
that is not referenced. You must add a reference to assembly 'NHibernate,
Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4'."
If I add nhibernate.dll as a reference in my web project, it works.
Why is this? The logic/code is in my data layer, it is return the same as the call to GetById(1), why do I need to add the reference?

I'm guessing it's because of the lazy-loading that comes build into your objects. NHibernate creates proxy objects that inherit from your class (which is why you need to declare your methods as virtual). I'm guessing the reference is needed because of the proxy objects.

Related

Use custom model binder from different assembly and instantiate object from same

I have a class library which includes a custom MVC model binder to instantiate various concrete types which derive from an abstract class. The model binder is almost identical to the one described in this post.
It works fine when using it from within the same Visual Studio Solution that also includes an MVC web application for testing.
My problem is that having created a nuget package from the assembly and included it in a totally separate MVC application the model binder no longer works, despite having configured it correctly in Global.asax.cs.
After some hair pulling I recreated the model binder directly in the separate MVC app, and as I was doing so I noticed that the overridden CreateModel() method in the binder is protected. It now gets executed and I suspect the protected keyword has something to do with it but I would like someone to explain why exactly.
Even with the 'local' modelbinder there are more problems. When it executes, and tries to instantiate the concrete object, I get an exception Could not load type XXXX from assembly { separate MVC project assembly name} so it seems the model binder is unable to load types from outside its own assembly.
Can anyone give me more information on why this happens and what I can do to work around it? Bearing in mind I need the model binder and models to reside in the class library not in the MVC assembly.
I had the same problem as you did, binding to models in a different assembly, but I needed a different solution. I used the same model binding example that you linked to, and I also got the same exception: Could not load type XXXX from assembly
I ended up needing to use the AssemblyQualifiedName for each concrete type. So my views contain this:
#Html.Hidden("ModelType", Model.GetType().AssemblyQualifiedName)
Instead of this:
#Html.Hidden("ModelType", Model.GetType())
I'm still wondering why this was necessary, since the default model binder can load types from the assembly in question.
OK so I was being stupid. It turns out that a few assumptions led me on a wild goose chase.
The ModelBinder was executing correctly to start with. My viewmodel had nested properties which were also abstract base types and required the model binder but I hadn't put the hidden fields in the view to identify their concrete type, nor had I added them to the Global.asax configuration. Once I did this everything started to work as expected.

Webapi DefaultHttpControllerSelector does not properly resolve my controller

I have an WebApi application that contains some controllers (they are registered using the extension method RegisterApiControllers). This application references another assembly that contains other controllers that I don't want to expose(I have checked that they are not registered in the container). It happens that both have an OrderController, and when I try to access the /api/Order url, I get an exception "Multiple types were found that match the controller named 'order'." and the stack trace shows that I was in DefaultHttpControllerSelector.
I have seen that AutofacControllerFactory used to exist and there was even a ConfigureWebApi that registered it, but it is not anymore present in the default branch.(you can see it here http://alexmg.com/post/2012/03/09/Autofac-ASPNET-Web-API-(Beta)-Integration.aspx)
It seems also that we can not filter the namespace of the route definition in WebApi (it is possible to MVC).
So any idea on how I can use only the Controller registered in my Autofac container and not use the DefaultHttpControllerSelector that seems to scan all referenced assemblies to discover controller?
Thanks
The problem is that registering the controller with autofac is not really related to the routing process. Only once the routing process has identified which controller to dispatch to will Autofac be called to resolve the type.
It looks like, from digging around in the source, that you would need to write a replacement IHttpControllerSelector in order to handle two controllers with the same name. (which really sucks BTW).
You might be able replace the DefaultHttpControllerTypeResolver with an instance that is passed a predicate that filters out the controllers from the assembly that you want to ignore. It's a bit of a kludgy solution but might work.
Actually, you might be able to replace the DefaultHttpControllerTypeResolver completely with one that is based on registrations in your Autofac container. It is a very simple interface, so as long as Autofac have a some kind of discovery mechanism, you should be golden.
public interface IHttpControllerTypeResolver
{
ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver);
}

How do you add htmlHelpers into the Spark virew

I want to use the htmlHelpers in my spark view but I keep getting the following errors.
error CS0234: The type or namespace name 'Mvc' does not exist in the
namespace 'System.Web' (are you missing an assembly reference?)
I have added the System.Web.Mvc assembly into the project. I have also added the following code into the module (just for the sake of getting it working - I'll probably need to add this code to the bootstrapper --- not sure how to do that yet!)
var settings = new SparkSettings()
.SetDebug(true)
.SetAutomaticEncoding(true)
.AddAssembly("System.Web")
.AddAssembly("System.Web.Mvc")
.AddNamespace("System.Web.Mvc")
.AddNamespace("System.Web.Mvc.Html");
I also tried adding the namespace to a _global.spark file
Can someone tell me exactly what I must do to use the htmlHelpers in my spark view please.
The default Spark base view for Nancy doesn't include the public HtmlHelper Html { get; set; } property.
You can see the default view here.
The Spark view implemented for MVC integration is here, and you'll see the Html property exposed, which allows your Spark view to access it and invoke helpers.
In theory, you can inherit from NancySparkView, and specify that as your base view in your Spark settings, and add that property along with references to System.Web.Mvc etc in that class and your views should then be able to call into the helpers assuming everything is referenced correctly.
I'm not a Nancy expert, but I'm sure the type of the View is different than that of Asp.Net MVC. So, theoretically, you shouldn't be able to use MVC helpers, since they require the Html property on the View.

System.Collections.Generic.IEnumerable

when trying to query my database with entityframework i get the following error:
The navigation property of type 'System.Collections.Generic.IEnumerable1[[TASK.Warehouses.Domain.NoteProducts.NoteProduct, TASK.Warehouses.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not a single implementation of 'System.Collections.Generic.ICollection1[T]'.
what could be the problem and how could i fix it
You wrote Code-First classes that have IEnumerable<T> navigation properties.
Entity Framework requires that your navigation properties be of type ICollection<T>.
Sounds like you have many classes named "TASK.Warehouses.Domain.NoteProducts.NoteProduct, , TASK.Warehouses.Domain]. If this is the case, you are confusing CLR with violations of OO.

System.ComponentModel.DataAnnotations MethodAccessException in Automated Controller Unit Test, MVC

First of all I'd like to say that I wouldn't doubt if this is a configuration error, because it's only happening on our CI build server and not on anyone's local development machine. So if anyone has a seemingly obvious configuration suggestion please feel free to point it out, my team doesn't configure the build server so there could be something simply not set up correctly.
I'm running into an issue with one of my automated tests, I'm having this issue in any test that involves the (System.ComponentModel.)DataAnnotations on the Entity that is being used. It seems to only occur with any test that involves the Controller calling TryUpdateModel.
Before I provide the entire error message, here’s a list of some of the things we’ve already tried:
Adding the main MVC assemblies to the “fullTrustAssemblies” section of the app.config of the Test project
Adding the System.ComponentModel.DataAnnotations assembly to the “partialTrustVisibleAssemblies” section of the app.config of the Test project
Adding the System.ComponentModel.DataAnnotations assembly to the AppDomainSetup PartialTrustVisibleAssemblies in code
Trying to use ReflectionPermission.Demand to see if there was a problem with permissions
Ensuring that .NET Framework 4 and MVC3 were installed on the machine
Checking for the registry key(s) talked about in this article
Here's the full error:
Test method qTrade.UnitTests.Web.Controllers.Maintenance.TypeLookupControllerTest.CreatePostSaveInvalidEntityAndModelState threw exception:
System.MethodAccessException: Attempt by security transparent method 'System.Web.Mvc.TypeDescriptorHelper.Get(System.Type)' to access security critical method 'System.ComponentModel.DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider..ctor(System.Type)' failed.
Assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is a conditionally APTCA assembly which is not enabled in the current AppDomain. To enable this assembly to be used by partial trust or security transparent code, please add assembly name 'System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9' to the the PartialTrustVisibleAssemblies list when creating the AppDomain
Test method qTrade.UnitTests.Web.Controllers.Maintenance.TypeLookupControllerTest.CreatePostSaveInvalidEntityAndModelState threw exception:
System.MethodAccessException: Attempt by security transparent method 'System.Web.Mvc.TypeDescriptorHelper.Get(System.Type)' to access security critical method 'System.ComponentModel.DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider..ctor(System.Type)' failed.
Assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is a conditionally APTCA assembly which is not enabled in the current AppDomain. To enable this assembly to be used by partial trust or security transparent code, please add assembly name 'System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9' to the the PartialTrustVisibleAssemblies list when creating the AppDomain.<br> at System.Web.Mvc.TypeDescriptorHelper.Get(Type type)
at System.Web.Mvc.ModelBinders.GetBinderFromAttributes(Type type, Func`1 errorMessageAccessor)
at System.Web.Mvc.ModelBinderDictionary.GetBinder(Type modelType, IModelBinder fallbackBinder)
at System.Web.Mvc.ModelBinderDictionary.GetBinder(Type modelType, Boolean fallbackToDefault)
at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
at qTrade.UI.Web.Controllers.Maintenance.TypeLookupController.Create(FormCollection collection) in d:\cibuild\qTrade\qTradeCI\Sources\source\UI\qTrade.UI.Web\Controllers\Maintenance\TypeLookupController.cs:line 55
at qTrade.UnitTests.Web.Controllers.Maintenance.TypeLookupControllerTest.CreatePostSaveInvalidEntityAndModelState() in d:\cibuild\qTrade\qTradeCI\Sources\source\Tests\qTrade.UnitTests\Web\Controllers\Maintenance\TypeLookupControllerTest.cs:line 178
at System.Web.Mvc.TypeDescriptorHelper.Get(Type type)
at System.Web.Mvc.ModelBinders.GetBinderFromAttributes(Type type, Func`1 errorMessageAccessor)
at System.Web.Mvc.ModelBinderDictionary.GetBinder(Type modelType, IModelBinder fallbackBinder)
at System.Web.Mvc.ModelBinderDictionary.GetBinder(Type modelType, Boolean fallbackToDefault)
at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
at qTrade.UI.Web.Controllers.Maintenance.TypeLookupController.Create(FormCollection collection) in d:\cibuild\qTrade\qTradeCI\Sources\source\UI\qTrade.UI.Web\Controllers\Maintenance\TypeLookupController.cs:line 55
at qTrade.UnitTests.Web.Controllers.Maintenance.TypeLookupControllerTest.CreatePostSaveInvalidEntityAndModelState() in d:\cibuild\qTrade\qTradeCI\Sources\source\Tests\qTrade.UnitTests\Web\Controllers\Maintenance\TypeLookupControllerTest.cs:line 178
Any suggestions would be greatly appreciated, thanks!
I Fixed the problem !
This is a combination of running in Medium Trust, having MVC installed in the GAC and using "dynamic" (or a shape) as a ViewModel. Only (and only if) these 3 conditions are true you run into this error. The solution is to change your controller code: instead of returning "View(model)", return "View((object)model)".

Resources