WebApi uncaught error when calling SaveChanges() for breezeJs - entity-framework

Have Breeze setup with WebAPI and EntityFramework.
EntityManager queries working fine.
SaveChanges() working fine on all entities, EXCEPT...
I have an entity with an optional related entity:
Public Class Payment
Public Property Id As Integer
Public Overridable Property Registree As Registree
Public Property RegistreeId as Integer?
Public Property Amount as Double
End Class
Here is my WebAPI action for SaveChanges()
<HttpPost()>
Public Function SaveChanges(bundle As JObject) As SaveResult
Dim result As SaveResult
Try
result = breezeDb.SaveChanges(bundle)
Catch ex As Exception
Dim err = ex
End Try
Return result
End Function
When I create a new Payment entity in Breeze and call SaveChanges, everything works fine UNLESS my payment entity has a value for RegistreeId.
If RegistreeId has a value, the following happens:
SaveChanges() on the WebAPI is successfully called.
No errors are caught in my Try/Catch.
The "result" returned to the client has no errors associated with it.
However, on client side, the manager.saveChanges() fails, giving an error object with NO details, just "The response had HTTP status code 500."
return manager.saveChanges()
.then(function(saveResult){
return saveResult;
})
.catch(errorOnSave); //this gets called, no breakpoints get hit in the "then" function
NOTE: The entity IS getting saved correctly to the database, related entity and all. So this is not a foreign key constraint or other database problem.
So it seems something is breaking on the server and no error message is getting to client. But my try/catch is not getting it, and the error ONLY happens if that optional foreign key field is NOT null.
Any ideas?

Found the problem...didn't realize I had not turned off Custom Errors in web.config.
<system.web>
<customErrors mode="Off" />
...
</system.web>
Then I was able to see that Json.Net was running into null exception error when parsing the saveresult.

Related

MVC FoolProof Validation showing exception while calling SaveChange method

This question mayt sound duplicate but I am not satisfied with any of the answers as some are suggesting MVC Foolproof validaiton for conditional validaiton and some tells it dont work well with entity framework
I am using MVC Foolproof RequiredIf validation in my project.It works well on clientside and is validation is working on server side as well.
[RequiredIf("STCompulsory",Operator.EqualTo,true,ErrorMessage="Please enter Registration No")]
public string STRegNo { get; set; }
But when i call db.Savechanges() to insert data an exception is coming
An unexpected exception was thrown during validation of 'STRegNo' when invoking
Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
InnerException
The method or operation is not implemented.
You do not need the Operator.EqualTo parameter and it can be simply
[RequiredIf("STCompulsory", true, ErrorMessage="Please enter Registration No")
public string STRegNo { get; set; }
You are correct in that the foolproof [RequiredIf] attribute does have some problems with EF and it is discussed in detail in this work issue (along with some suggested changes).
The easiest solution is to use a view model rather than your data model in the view, and apply the attribute to the view model property.

ProviderIncompatibleException with Entity Framework

I always get this error when I issue this command
http://localhost:19572/api/courses
This method is generating the exception
public IQueryable GetAllCourses()
{
return _ctx.Courses
.Include(“CourseSubject”)
.Include(“CourseTutor”)
.AsQueryable();
}
Exception:
System.Data.Entity.CoreProviderIncompatibleExceptionoccurred inEntityFramework.dll` but was not handled in user code
Additional information An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
and when I inspect the JSON element in Fiddler I always get this
ExceptionMessage=The system cannot find the file specified
ExceptionType=System.ComponentModel.Win32Exception
Message=An error has occurred.
I am using Entity Framework 6.0.1, and I have tried 5 but it didn’t work so I there any thing wrong with Entity Framework version or what?

"Entity does not have a key defined" error in working production code

We are running into a very odd problem: We are using entity framework 4 and ria services for a silverlight 5 appliation hosted in IIS 6.1. For long periods of time, everything is running smoothly, but occasionally the application fails with the following error message in the event log:
WebHost failed to process a request. Sender Information:
System.ServiceModel.Activation.HostedHttpRequestAsyncResult/56703158
Exception: System.ServiceModel.ServiceActivationException: The service
'/Services/EcoFleet-DomainServices-Repository-EcofleetRepository.svc'
cannot be activated due to an exception during compilation. The
exception message is: The Entity 'DeviceData' in DomainService
'EcofleetRepository' does not have a key defined. Entity types exposed
by DomainService operations must have at least one public property
marked with the KeyAttribute.. ---> System.InvalidOperationException:
The Entity 'DeviceData' in DomainService 'EcofleetRepository' does not
have a key defined. Entity types exposed by DomainService operations
must have at least one public property marked with the
KeyAttribute. at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.ValidateEntityTypes()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.Initialize()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.CreateDescription(Type
domainServiceType) at
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.GetDescription(Type
domainServiceType) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHost..ctor(Type
domainServiceType, Uri[] baseAddresses) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHostFactory.CreateServiceHost(Type
serviceType, Uri[] baseAddresses) at
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity)
at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity)
--- End of inner exception stack trace --- at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) Process Name: w3wp Process ID: 2300
The application still responds, but no entities can be loaded from the server. After stopping and starting the site, everything works again.
The entity in this case (DeviceData) is a database table, and it does have a key, and regardless it seems to be random which entity fails. Furthermore I would only expect to see the "key not defined" error at compile time. Does anyone have a clue what the problem is, and how to fix it?
Your DeviceData entity do not have key defined, which is required. You should create property with name Id or DeviceDataId which will be treated as key by convention (Entity Framework currently looks for these properties). Also you can use mappings to set other property as key. This can be achieved with data annotations attributes:
[Key]
public int Foo { get; set; }
Or with fluent mappings:
modelBuilder.Entity<DeviceData>().HasKey(d => d.Foo);
First you won't have an error at compile time because it is not a mandatory thing, but not having one might give you quite the headache, because EF use it in many ways. so you have to redefine your key by naming it Id or DeviceDataId(Using the convention) or define a one from the model.
It seems from your question that there is a key defined for DeviceData, in that case I advice you to relook the properties of the key column in your model.
remember also that not having a key column might reduce the performance of your app.

RequestFactory service inheritance on the client in GWT 2.4

GWT 2.4 brings service inheritance on the client (issue 6234, issue 6035).
I've been waiting for this future for a long time, as it saves a lot of duplicated code on the client. I've started implementing it, but so for with mixed success.
This is my code:
public interface BaseEntityRequest<T>
{
Request<Void> put(T entity);
Request<List<T>> getAllOrderBy(String propertyName);
Request<List<T>> getRangeAndFilter(int limit,int offset, QueryInfoProxy queryInfo);
}
#Service(value = EgdDao.class, locator = DaoServiceLocator.class)
public interface EgdRequest extends RequestContext, BaseEntityRequest<EgdProxy>
{
Request<Void> exportToExcel(QueryInfoProxy queryInfo, String userName);
}
So far getAllOrderBy and getRangeAndFilter work fine, but put(T entity) does not.
I get the following error in the console:
[ERROR] Unexpected error
java.util.NoSuchElementException
and this gets returned in the receiver onFailure ServerFailure message:
Error 500 INTERNAL_SERVER_ERROR
HTTP ERROR 500
Problem accessing /gwtRequest. Reason:
INTERNAL_SERVER_ERROR
The only cause, that I can see, for the put method not to work, when the others do, is that it uses the generic parameter T. When I move the put method in the EgdRequest interface (using EgdProxy as a parameter instead of T) it starts to work, so I know my server code is fine.
Does anybody have any idea how to implement this correctly?
Thanks!
It's a GWT bug. See http://code.google.com/p/google-web-toolkit/issues/detail?id=6794

SaveTempData called even though session is disabled

I've disabled sessionState in my mvc2 app via the web.config and also created my own controllerfactory and dummy tempdata provider, as described here:
How can I disable session state in ASP.NET MVC?
Only I've made it so that SaveTempData throws an exception:
public void SaveTempData(ControllerContext controllerContext,
IDictionary<string, object> values)
{
throw new NotImplementedException(
"Cannot set tempdata, no session state is available.");
}
I've made sure that no code is ever using either the Session or the TempData objects, but I still see this exception getting thrown after the "OnResultExecuted" event has been raised. I used to use this very same pattern on my mvc1 site and never saw the exception. Any ideas?
If I change my "SaveTempData" implementation to this:
public void SaveTempData(ControllerContext controllerContext,
IDictionary<string, object> values)
{
if (values.Count != 0)
{
throw new NotImplementedException(
"Cannot set tempdata, no session state is available.");
}
}
Everything works as expected - I'm just hoping to learn why SaveTempData is called at all when I'm not using it anywhere.
Update
Discovered this article: http://www.gregshackles.com/2010/07/asp-net-mvc-do-you-know-where-your-tempdata-is/
Which explains that ExecuteCore calls PossiblyLoadTempData and PossiblySaveTempData around an action - which is what was causing my issue. Is this a new addition in mvc2 vs. mvc1?
That's how it is implemented in the Controller.ExecuteCore method. The LoadTempData and SaveTempData methods will always be called before and after each action so make sure that they do not throw an exception. In order to disable the session effectively I would recommend you putting the following in your web.config:
<sessionState mode="Off" />
Discovered this article: http://www.gregshackles.com/2010/07/asp-net-mvc-do-you-know-where-your-tempdata-is/
Which explains that ExecuteCore calls PossiblyLoadTempData and PossiblySaveTempData around an action - which is what was causing my issue. Is this a new addition in mvc2 vs. mvc1?