"System.NullReferenceException" for Using Session in MVC - asp.net-mvc

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 );

Related

Glass Mapper "Unrecognized Guid format" error on MapPropertiesToObject

I'm getting an error from GlassMapper on certain pages in my Sitecore solution.
public override void Execute(ObjectConstructionArgs args)
{
// check that no other task has created an object and that this is a dynamic object
if (args.Result != null || args.Configuration.Type.IsAssignableFrom(typeof(IDynamicMetaObjectProvider))) return;
// create instance using your container
var obj = ServiceLocator.ServiceProvider.GetService(args.Configuration.Type);
// map properties from item to model
args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);
// set the new object as the returned result
args.Result = obj;
}
The error is occurring on args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext); - System.FormatException: Unrecognized Guid format.. This error is only occurring on pages of a particular template, but not ALL pages of that template and I'm not sure how to track down which field is causing the guid error
I experienced the same error when a General Link field didn't contain any id="{xxx}" attribute or had it empty like id="". So, I suggest to check the raw value of the link fields on the failing pages.

ASP.NET LINQ MULTIPLE OR IN WHERE

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

Value cannot be null error in processing OData from Web API

I have a WebAPI method that returns OData:
[HttpGet]
public PageResult<Students> GetStudents(ODataQueryOptions<Students> queryOptions, string ClassId)
{
var allStudents = (from s in new OStudentContext(Convert.ToInt64(ClassId)).Student select s).ToList();
var results = queryOptions.ApplyTo(allStudents.AsQueryable());
return new PageResult<Students>(results as IEnumerable<Students>, Request.GetNextPageLink(), Request.GetInlineCount());
}
The request URL is like so:
http://localhost:3333/api/odata/GetStudents?StudentId=40932&$inlinecount=allpages&$filter=((IsDeleted%20eq%20null)or(IsDeleted%20eq%20false))&$select=StudentId,FirstName,LastName,EmailID
The value in results is there and I can see the records returned. The count is actually 7 to be precise.
The problem is the the return statement throws this exception:
Value cannot be null.Parameter name: data
Request.GetNextPageLink() is null as there is no next page link.
Request.GetInlineCount() is 7.
So what is null & what does the error mean about data?
Thanks in advance.
The element type after applying ODataQueryOptions is no longer Students if there is some $select or $expand.
It changes to SelectExpandWrapper instead.
So the result can't be cast to IEnumerable<Students>.
For the structure of SelectExpandWrapper, you can refer to https://aspnetwebstack.codeplex.com/wikipage?title=%24select%20and%20%24expand%20support

Breeze throws Null reference exception when calling EntityAspect.validateProperty() method

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 :)

asp.net MVC 3 Error: "Object reference not set to an instance of an object"

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.

Resources