ODataActionFilter being called twice - breeze

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.

Related

DbSet.Find(id) in the BaseRepository hangs and never returned

I have a BaseRepository, where I have this function:
public T GetById(int id)
{
return DbSet.Find(id);
}
The issue is that the "return DbSet.Find(id)" hangs and never returned. I think that it is because of a deadlock. The framework tries to get the object from the database but nothings happen only the method hangs. The query never reach to the db. How can we track on which object we have problem. I know that we can simply use the where function instead of the find method.

GetRolesForUser returns null

In the background of my mvc 4 application i am running a scheduler that does some tasks.
When i want to get the roles from a specific user the functions returns a nullreference exception.
An unhandled exception of type 'System.NullReferenceException' occurred in System.Web.dll
The function does work with a normal request, but not outside a normal http request.
Why is GetRolesForUser not working outside a normal request (assuming that is the problem) and how can i fix it?
Note: Im using the parameter username, the user exists and has a role.
Im using the DefaultMembershipProvider.
Code:
public static string GetUserRoleByUsername(string username)
{
return System.Web.Security.Roles.GetRolesForUser(username).First();
}
Thanks in advance!
Edit:
I have fixed it by initializing the roleProvider, i am not sure why i need to initialize it.
Any ideas why i have to do this?
var roleProvider = System.Web.Security.Roles.Provider;

NullReferenceException in custom IModelBinder

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.

WebException NotFound received when using Silverlight with ASP.NET MVC

I'm not entirely sure how to explain this, but basically I am trying to use a Silverlight application hosted within an ASP.NET MVC application. I have a basic controller on the MVC side that contains a method which accepts some string parameter and returns an ActionResult (for the purpose of this program, that result is some Json data).
My problem arises when I handle the WebClient.OpenReadCompleted event within the Silverlight control. When the WebClient.OpenReadAsync method is called within this control, it successfully reaches the controller and then reports back to the relevant event handler as expected. However, when it is handled, the event arguments contain an error stating: "The remote server returned an error: NotFound.".
Previously, I have noticed this is caused when some part of my communication URL is incorrect - in this case it is not. From some Googling, I have also noticed that this is a generic error. As such, I'm rather stumped. To make matters more confusing, I use this exact same communication attempt in another part of the program, that retrieves an array of strings, and that works perfectly fine.
Please see the example code below (due to the nature of this program, I am unable to post the full code).
Silverlight Control
WebClient mClient = new WebClient();
public void RequestData()
{
mClient.OpenReadAsync(new Uri("http://localhost:51234/Home/GetData"));
mClient.OpenReadCompleted += new OpenReadCompletedEventHandler(mClient_OpenReadCompleted);
}
private void mClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if(!e.Cancelled && e.Error == null) // <-- e.Error here is a WebException
{
var serializer = new DataContractJsonSerializer(typeof(Data));
Data data = (Data)serializer.ReadObject(e.Result);
}
}
MVC Controller - named HomeController and accessed with "Home"
public ActionResult GetData()
{
return Json(new Data(), JsonRequestBehaviour.AllowGet);
}
Note
Here, Data contains three members of types; string, string and byte array. For the purpose of serialization, I have exposed all three members through public properties containing both get and set parts. I have also added a public constructor taking no arguments.
Any advice on this would be greatly appreciated.
Many thanks in advance.
UPDATE
I've just tried the same bit of code with different data, and it works fine. I wondered if it was the size of the data (as the first attempt was with very large data), but I don't understand why that would matter if the call managed to hit the controller.
If you want to see the real server-side exception, this may help you:
http://msdn.microsoft.com/en-us/library/ee844556(v=VS.95).aspx
Either approach described there would probably illuminate the real problem.

linq datacontext GetModifiedMembers in Attach scenario

I am trying to implement Optimistic Locking in an asp.net MVC application, as well as provide audit trailing.
The audit framework relies on being able to call DataContext.GetModifiedMembers during SubmitChanges, which makes good sense, i guess.
The optimistic locking uses ROWVERSION timestamps, serialized to base64 and put in a hidden field in the view.
My Edit action looks like this:
[AcceptVerb(HttpVerb.Post)]
public ActionResult Edit(MyType myType)
{
context.MyTypes.Attach(myType, true);
context.SubmitChanges(ConflictMode.FailOnFirstConflict);
}
When doing this, the DataContext.GetModifiedMembers will always return ALL the properties on MyType, rather than just the ones that are changed between the database and the values provided, which breaks the auditing.
Specifically it returns every property as having been changed from their new value to their new value, so its not even like I can do anything clever to the list.
I tried loading the object first, before attaching it, but this gives a duplicate key exception.
I then tried using UpdateModel, i.e.
[AcceptVerb(HttpVerb.Post)]
public ActionResult Edit(int id, FormCollection col)
{
var mt = context.MyTypes.Single( mt => mt.id = id);
UpdateModel(mt);
context.SubmitChanges(ConflictMode.FailOnFirstConflict);
}
This works with the auditing, but fails the optimistic locking.
Rather than a ChangeConflictException i get an InvalidOperationException because the UpdateModel is changing the concurrentTS field (which apparently is readonly).
What am I doing wrong?
Progress so far consists of doing the last part, and catching InvalidOperationException and looking for the text "Value of member 'ConcurrencyTimestamp'", and rethrowing that as a ChangeConflictException.
That seems to do the trick, but it is not pretty.

Resources