NullReferenceException in custom IModelBinder - asp.net-mvc

I'm trying to implement my own custom ModelBinder using MVC4 in .NET 4.5, but get the weirdest error. My code looks approx. like this
TableViewModelModel : IModelBinder
public object BindModel(ControllerContext ctx, BindingContext btx)
{
IEnumerable<String> sSearch = ctx.HttpContext.Request.Params.Keys.OfType<String().Where(key => key.StartsWith("sSearch_"));
...
}
A NullReferenceException is thrown allready at the first line, but none of the properties are actually null (they all appear in the intellisense debug). In a desperate I decided to rid of some of the properties to get a better look at where the exception is thrown and I found the culprit to be the Params property. What's really strange is that all the keys from the querystring is listed in the debug window, but an exception is thrown nevertheless. I really need some help on this one people!
Thanks.

Found the error using Reflector and analyzing the stack trace. Turns out that somewhere along the call stack HttpRequest.Params tried to read the Identity property of my Principal object (HttpContext.User). I have a custom implementation of IPrincipal that doesn't initialize the Identity object - and there you have it.
A big thank you to those of you who took the time to read my question.

Related

Null exception in MVC model

I am getting the model values to an action in controller and trying to pass the values to another function in another class by setting it to another object . In the line of invoking the second function, the object throws null exception. It doesnt show null in the if condition check either.
Please find code below.
public ActionResult SearchBySecurity(SearchViewModel srchModel)
{
var searchDTO = new VisitorSearchDTO();
//_mapper.Map<SearchViewModel, VisitorSearchDTO>(srchModel,searchDTO);
searchDTO.VisitorFirstName = srchModel.VisitorFirstName;
searchDTO.VisitorContactNumber = srchModel.VisitorContactNumber;
searchDTO.VisitorCompany = srchModel.VisitorCompany;
searchDTO.VisitDate = srchModel.VisitDate;
if (searchDTO != null)
{
var searchResultsDTO = _searchVisitor.SearchForVisitors(searchDTO);
}
ModelState.Clear();
return View("SearchBySecurity",srchModel);
I am guessing you are getting null exception when you are trying to map your models. Are you using AutoMapper? What is _mapper? If AutoMapper, then it might be worth checking your mapping profile code once if you have used any custom (before, after) mappings.
Rest as everyone has suggested, debug your code and state more clearly where the probles is, what you have tried and give clear definition of your types and environment
Thanks Stephen and Jinish for your inputs.
I have managed to solve the issue.
The trouble was in initializing the controller with mapper and service parameters. Default parameter-less constructor was taken up in the code and hence mapper and service objects were not getting initialized. Solved this by proper implementation of interfaces and mapping profiles.

ODataActionFilter being called twice

This is my first attempt at using breeze.js so I probably have something setup incorrectly, but not sure what it is.
I am experiencing an error when executing a simple query. I'm using EF 5.0 DB first in a VS2012 project.
An error has occurred.
Value cannot be null. Parameter name: source
System.ArgumentNullException
at System.Linq.Queryable.Where[TSource](IQueryable1 source, Expression1 predicate) at lambda_method(Closure , IQueryable ) at Breeze.WebApi.ODataActionFilter.OnActionExecuted(HttpActionExecutedContext actionExecutedContext) at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecuted(HttpActionContext actionContext, HttpResponseMessage response, Exception exception) at System.Web.Http.Filters.ActionFilterAttribute.<>c_DisplayClass2.b_0(HttpResponseMessage response) at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass412.<Then>b__40(Task1 t) at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
In an attempt to determine what I was doing incorrectly, I download the breeze server source code and included the project in the solution so I could trace the error. The error is occurring in the OnActionExecuted event in ODataActionFilter.cs. The strange thing is that the function is called twice for the same query. The function is first called with the query in the responseObject. The 2nd time the event is called, the result of the query is in the responseObject. This is no longer a iQueryable object which results in the error. I cannot determine why the function is being called a 2nd time when it already has the correct result.
Has anyone seen this before and can tell point me in a direction to fix it?
thanks
I'm answering my own question.
The solution was that my api controller did not have the new BreezeController attribute applied to it. This is not in any of the documentation. I did, however, find it in the samples.
ie
from documentation: http://www.breezejs.com/documentation/web-api-controller
[JsonFormatter, ODataActionFilter]
public class TodosController : ApiController {
but, the current sample has this:
[BreezeController]
public class TodosController : ApiController {
this corrects the problem, but it was hard to find. It's also not entirely clear to me whether the new BreezeController attribute should be added to the original two attributes or if it entirely replaces them.

ASP.NET MVC Web API & StructureMap: "does not have a default constructor"

I configured an ASP.NET MVC 4 Web API project to use StructureMap 2.6.2.0 as described in this post, but accessing /api/parts returns the following error despite explicitly calling StructuremapMvc.Start(); in Application_Start():
{
"ExceptionType": "System.ArgumentException",
"Message": "Type 'MyProject.Web.Controllers.PartsController' does not have
a default constructor",
"StackTrace": " at System.Linq.Expressions.Expression.New(Type type)\r\n
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
I implemented IDependencyResolver and IDependencyScope and set the Web API dependency resolver as follows in ~/App_Start/StructureMapMvc.cs:
GlobalConfiguration.Configuration.DependencyResolver =
new StructureMapHttpDependencyResolver(container);
Why is Web API still complaining about a default consturctor?
Turns out the error description is just really bad. StructureMap is being called, but cannot inject a dependent constructor parameter due to a missing connection string.
Here's how I fixed it in IoC.cs:
x.For(typeof(IRepository<>)).Use(typeof(MongoRepository<>))
.CtorDependency<string>("connectionString")
.Is(yourConnectionString);
I was doing this (incorrectly):
x.For<IRepository<SomeEntity>>().Use<MongoRepository<SomeEntity>>();
There really should be a way to output inner StructureMap exceptions when they occur in the Web API.
It's clear that the DI is not called to provide a controller instance but I don't know why. Have you tried setting a debug break point in the structure map code provided by the post (i.e. the code that lives on github) to make sure that it is called?
If you hit this error on some controllers, but not others it is likely a different issue.
To get better exception information, add a try / catch in the GetService method override in your implementation of IDependencyScope and set a break point in the catch block. You'll be able to get better debug info.
I know OP already got an answer, this is just for anyone else who stumbles across this and finds it useful.

Puzzled about the ASP.NET MVC DefaultControllerFactory.cs Implementation

While investigating implementing my own IControllerFactory I looked into the the default implementation DefaultControllerFactory and was surprised to see the RequestContext property being set in the CreateController(...) method, and then being referenced in the GetControllerInstance(...) and GetControllerType(...) methods.
The reason for my surprise is that as the factory is instantiated at Application start-up that same instance is used for all requests, so if multiple requests are received at the same time you have no guarantee which requests RequestContext has been set to the property when you come to use it.
Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?
If I am missing something here please enlighten me, as the implementaiton of my controller will be simpler if I have state between method calls during a requests lifecycle.
Thanks.
EDIT:
The answers given are as I expected but miss the main point of the question. The fact is the DefautlControllerFactory supplied as a part of the MVC framework is storing the RequestContext as if it has state - look at the source.
I believe this to be wrong and am looking for clarification (which I think I have seeing as both answers agree with my thoughts). I have cross posted to thte ASP.NET MVC Forums.
Cross posting to the ASP.NET MVC forums reveals this to be a bug with the DefaultControllerFactory implementation.
See here for information:
http://forums.asp.net/t/1414677.aspx
http://forums.asp.net/t/1404189.aspx
The latter post however reveals that you can have a controller factory be instatiated on each request, in which case you can have state.
From the post...
ControllerBuilder.Current.SetControllerFactory(typeof(DefaultControllerFactory));
This will switch the mode of the
controller builder from instance-based
to type-based, and will create a new
instance of the controller factory on
every request.
Your question: Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?
Answer: No, you have to use locks to store state.
My question: Why do you want to store state in the controller factory?
No the Controller factory CreateController method is executed for each request. In application startup you are only suppose to set your default controller and creating a new controller factory is only three lines of code:
public class CommonServiceLocatorControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
return (controllerType == null) ? base.GetControllerInstance(controllerType)
: ServiceLocator.Current.GetInstance(controllerType) as IController;
}
}

Error when deploying ASP.NET MVC NHibernate app to IIS7

I have an Asp.Net MVC application that works in the vs.net development web server. When I publish to IIS7 I get the following error. I have spent many hours and still no solution!
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.PipelineStepManager.ResumeSteps(Exception error) +929
System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +91
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +508
Here is the Application_Start
protected void Application_Start()
{
ConfigureLogging();
ComponentRegistrar.RegisterComponents();
NHibernateSession.InitSqlServer2005(new WebSessionStorage(this), Settings.Default.DefaultConnString);
CacheManager.InitCaches();
}
}
I came late to this application and do not know the best practices of MVC and NHibernate
You cant configure nhibernate in application start. I don't exactly know why, but I also had this problem.
You can initialize it in Init(). Also you can see it is done here
http://code.google.com/p/sharp-architecture/source/checkout
Moving my nhibernate initialization code from Application_Start() to Init() still did not run late enough to fix the error. So I stumbled upon this. The solution I used was not from the original post, but the from first comment by jbland. Basically it moves initialization of nhibernate to occur on the first request.
One thing to note is his code does not give you the context of where webSessionStorage comes from. It is a member variable and must be instantiated in Init().

Resources