I have the following entity property defined as the following metadata shows:
{"name":"website","dataType":"String",
"validators":[
{"name":"string"},
{"messageTemplate":"'%displayName%' is not valid",
"pattern":"^$|(^http|^https)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/S*)?",
"name":"regExValidator"}]}
When I attempt to call entityAspect.validateProperty("website"), and the value of the website property is null, the call to the validateProperty() method throws the following exception:
"Unable to get property 'complexAspect' of undefined or null
reference"
I wouldn't expect this behavior since it's possible that the website entity property could be null. It looks like there may be a null reference handling bug in the validateProperty method:
In Breeze.debug.js:
proto.validateProperty = function (property, context) {
var value = this.getPropertyValue(property); // performs validations
if (value.complexAspect) { // THROWS EXCEPTION IF 'value' IS NULL
return validateTarget(value);
}
context = context || {};
context.entity = this.entity;
if (typeof(property) === 'string') {
context.property = this.entity.entityType.getProperty(property, true);
context.propertyName = property;
} else {
context.property = property;
context.propertyName = property.name;
}
return this._validateProperty(value, context);
};
Just curious if I'm doing something wrong, or if this is just a bug?
Thanks,
Richard
Edit: This was fixed in Breeze v1.3.0, available now.
This is a bug, and will be fixed in the next release, out later this week. ... and thx for finding and reporting it :)
Related
I have following code in asp.net core using multiple or in where statement. it always propmt error saying "An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
lambda_method"
if (!String.IsNullOrEmpty(searchString))
{
mTickets = from mt in mTickets
where
(mt.TicketServiceFullNo.Contains(searchString)) || (mt.DeviceNo.Contains(searchString)) select mt;
}
return View(await mTickets.AsNoTracking().ToListAsync());
However, If i just use one or condition in where. it will work. I have no idea why. Please help. thanks
this will work
if (!String.IsNullOrEmpty(searchString))
{
mTickets = from mt in mTickets
where
(mt.TicketServiceFullNo.Contains(searchString)) select mt;
}
return View(await mTickets.AsNoTracking().ToListAsync());
It's almost certain that mt.DeviceNo is null.
You'll need to replace:
(mt.DeviceNo.Contains(searchString))
with
(mt.DeviceNo != null && mt.DeviceNo.Contains(searchString))
or
(mt.DeviceNo?.Contains(searchString))
if you're using C# 6.0
In My MVC project, I am using session values like
var empId = Convert.ToInt32(Session["EmpId"].ToString());
I am getting Exception:
"An exception of type 'System.NullReferenceException' occurred in Project.Web.dll but was not handled in user code.
Additional information: Object reference not set to an instance of an object."
This error occurs when you call a method on the null object. In your case the value of Session["EmpId"] is NULL.
Which means you are calling NULL.ToString(), which is invaild hence it throws error.
You can avoid the error using null coaleascing operator or simply check null before performing any opearation on it.
Solution:
if(Session["EmpId"] == null)
//do something
else
var empId = Convert.ToInt32(Session["EmpId"].ToString());
Alternatively you can check my blog post on it
Before use first check is it null or not.
var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;
You have to check null as shown below :-
var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());
A more efficient way to accomplish your requirement :-
int temp = 0;
var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );
I am using ASP.NET WebAPI 2 with Breeze. I want to be able to return meaningful error messages when saving changes using SaveChanges() method. This is in case there is an error.
The current implementation returns SaveResult. How can return message e.g
var cardDetail = _membershipContextProvider.Context.Database.SqlQuery<CardDetail>("IssuedCardsGetVerificationDetails #CardNo", parameter).FirstOrDefault();
if (cardDetail == null)
{
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("The beneficiary with Card No. {0} was found in the NHIF database", CardNo)),
ReasonPhrase =string.Format("Card No. {0} Not Found in the NHIF Database!",CardNo)
};
throw new HttpResponseException(msg);
}
return cardDetail;
You need to throw an EntityErrorsException within the custom save method. This exception lets you both specify a top level message as well as a custom message for each failed entity.
[HttpPost]
public SaveResult MyCustomSaveMethod(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = SaveThatMightThrow;
return ContextProvider.SaveChanges(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> SaveThatMightThrow(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
// if this save tries to save ANY orders throw an exception.
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
var errors = orderInfos.Select(oi => {
return new EFEntityError(oi, "WrongMethod", "Entity level detail error - Cannot save orders with this save method", "OrderID");
});
var ex = new EntityErrorsException("Top level error - Orders should not be saved with this method", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
return saveMap;
}
Note that there is a bug in Breeze 1.4.16 where the top level error is not being propagated properly (it returns to the client as an empty string), however the entity level error messages will come thru just fine. This bug has been fixed in the latest GitHub repos, but you will need to get the fixed code from both the breeze.js and the breeze.server.net repos because the fix was to both the breeze.js client as well as the ContextProvider class in breeze.server.net. Or you can wait for the next breeze release in about a week.
These days,i have learned breezejs,durandaljs, so i made an spa application for excersizing,but breezejs(or q.js) often gives out errors
[Q] Unhandled rejection reasons (should be empty): ["proto.saveChanges#http:...s/jquery-1.9.1.js:2750\n"] (Firefox)
[Q] Unhandled rejection reasons (should be empty):(no stack) Error: Client side validation errors encountered - see the entityErrors collection on this object for more detail (IE10, but why deleteing an entity triggers validation ?)
I feel disappointed to use breezejs, what on earth am i doing!!!
I just do saving and deleting customer, sometimes error occured as above, sometimes works fine.(how confused i am feeling! :'( )
Here is part of my datacontext
var saveChanges = function () {
return manager.saveChanges()
.then(saveSuccess)
.fail(saveFailure); //.done() does not work either
//
function saveSuccess() {
console.log("Save Success!");
}
//
function saveFailure(error) {
console.log("Save Failure!");
throw error;
}
};
To save a customer:
define(['modules/dataService'], function (datacontext) {
var ctor = function () {
this.entity = ko.observable();
};
ctor.prototype.activate = function () {
//problem code --> [Q] Unhandled rejection reasons (should be empty)
//it will always create empty Customer when activate is called.
//so error occured when i switch in because of creating empty Customer every time.
this.entity(datacontext.createEntity('Customer'));
};
ctor.prototype.saveClick = function () {
if (this.entity().entityAspect.validateEntity())
datacontext.saveChanges();
else
console.log('validation error!');
};
return ctor;
});
To delete a customer
define(function (require) {
var datacontext = require('modules/dataService');
var vm = {
customers: ko.observableArray(),
activate: function () {
var self = this;
return datacontext.getCustomers(self.customers);
},
deleteCustomer: deleteCustomer
};
return vm;
//delete customer
function deleteCustomer(customer) {
vm.customers.remove(customer);
//Sets the entity to an EntityState of 'Deleted'
customer.entityAspect.setDeleted();
datacontext.saveChanges();
}
});
I think my code would work fine, but it can't!
Where is the fatal error i make? plz let me know.
Thanks in advance!
I know this thread has been here for more than a year now but I thought I could share my story.
I just got the same error while using breeze + angularJS. After some research, I figured it out:
I was passing null values in some of the entitie's properties while those fields in the database table where marked as NOT NULL.
Breeze - saveChanges
In the implementation of breeze.saveChanges, a check is done on a internal flag (line 12743 approx : if (this.validationOptions.validateOnSave) ...)
This is to enable verification of the entity against the database schema (aka the metadata).
Now most of the time we tend to call saveChanges without any parameters. And the error does not show otherwise then in the console as a general validation error message.
What have i done
We'll my fix was in 2 parts:
Add some code in my calls to saveChanges in order to trap these errors and display a better message in the console (see code below)
Fix either the DB schema (i.e. Relax NOT NULL fields to NULLABLE) OR set some default values OR enforce the business logic by adding required attributes to input controls.
Here's a snippet of the code I now use to trap the errors:
return manager.saveChanges(null, null, null, function (errors) {
console.log('breeze saveChanges returned some errors: ');
errors.entityErrors.forEach(function(e) {
console.log(e.errorMessage, e);
});
}); // return promise
i've a AccountController like this
public class AccountController : Controller
{
[Authorize]
public ActionResult MyProfile(string userEmail)
{
UserManager um = new UserManager();
UserProfile user = new UserProfile();
user = um.GetUserDetail(userEmail);
return View(user);
}
}
i've UserManager.cs Like this
public class UserManager
{
private ToLetDBEntities TLE = new ToLetDBEntities();
public UserProfile GetUserDetail(string uemail)
{
var userDetails = TLE.users.FirstOrDefault(x => x.email_add == uemail);
UserProfile up = new UserProfile();
up.cellno = userDetails.cellno.Trim();
up.email_add = userDetails.email_add.Trim();
up.name = userDetails.name.Trim();
up.password = userDetails.password.Trim();
return up;
}
}
When i'm debugging it gives error like
Object reference not set to an instance of an object
Null Reference Exception was Unhandled by User
At the line
up.cellno=userDetails.cellno.Trim();
Of the GetUserDetails function.
That error suggests that you don't have a userDetails instance, so you can't get the cellno property.
Are you sure that TLE.users.FirstOrDefault(x => x.email_add == uemail) is returning something? If you put a breakpoint on the line that gives you the error, then you can check what the value of userDetails is - it's probably null.
Most likely this query isn't returning anything:
TLE.users.FirstOrDefault(x => x.email_add == uemail);
The FirstOrDefault method won't give any kind of indication if no record is returned. The OrDefault part specifies this behavior. For any given return type, it will return the "default" for that type if no record is found.
For reference types (which yours is), the default is null. So this call would result in exactly that exception:
userDetails.cellno.Trim();
Since userDetails is null then it can't access a cellno property, hence the exception.
It's also possible in your case that userDetails isn't null but that the cellno property on it is. It's less likely, but possible. Looking at the runtime value while debugging would tell you if that's the case.
If userDetails is null, check your query conditions. Maybe the users collection has nothing in it? Maybe there are no records which match your x.email_add == uemail condition? (This is likely.)
If cellno is null then you'll want to check how that object is built, what the data in the database looks like, etc. Either way, you're not getting back the data you expect. The issue is in the data you're accessing.