I am trying to find a user in my database, searching for email and phonenumber.
How ever, if I use a List or IEnumerable I'm getting a null refence exception. If I don't use any of those, an "Not supported by SQL ... " is thrown.
My method:
public List<tblMember> getAllMembers()
{
return db.tblMembers.ToList();
}
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email.Equals(email, StringComparison.OrdinalIgnoreCase) && x.phoneNumber == phoneNumber); //This line throws exception, around email.Equals()
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
If I perform the search like this, no exception is thrown:
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email == email && x.phoneNumber == phoneNumber);
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
How can this be?
In the first case you are calling Equals() on an object that is null.
x.email.Equals(...)
This throws an exception.
In the second case you are comparing two things one of which might be null
x.email == email
Here is the most current based on comments:
private void confirmMembership(string email, int phoneNumber)
{
tblMember member = tblMembers.FirstOrDefault((x) => {
if (x.email == null) return false;
return SqlMethods.Like(x.email,email) && x.phoneNumber == phoneNumber);
}
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
Here is another way that won't throw an exception:
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault((x) => {
if (x.email == null) return false;
return x.email.Equals(email, StringComparison.OrdinalIgnoreCase) && x.phoneNumber == phoneNumber);
}
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
This is probably because x.email is null. If it is null, calling a member of it throws an exception.
x.email.Equals(...) ==> exception
However, you are allowed to compare two values that may be null
x.email == email ==> OK.
I suspect it's because x.email is null for some value of x.
Try:
tblMember member = db.tblMembers
.FirstOrDefault(x => x.email != null
&& x.email.Equals(email, StringComparison.OrdinalIgnoreCase)
&& x.phoneNumber == phoneNumber);
EDIT: I've only just noticed that getAllMembers() returns a List<T> so you don't have to worry about the expression tree conversion I was talking about before - but your current code is fetching all the data from the database each time you call this method. Do you really want that? The code I've provided above will do the filtering in the database which is surely what you'd be interested in.
Related
I've got a legacy service that I need to emulate that uses Soap as the message format. Unfortunately, due to various circumstances, I'm stuck using asmx and .Net Framework (due to it's Soap handling capabilities)
My problem is that I now need to call a certain API from within the service, and having used NSWAG to auto generate the client api, I'm finding that when I try and call it, it's giving a 500 error. This isn't necessairly a problem, as I'm sort of expecting that at the moment.
The issue is that when it throws the auto generated ApiException message as part of the 500 processing, it's jumping to the 'Finally' section for the response and the client, and then just throws an object reference exception...somewhere.
There's very little detail at all in the Exception, with the only bit of interest (I think) being that it says "This exception was originally thrown at this call stack:
System.Web.ThreadContext.AssociateWithCurrentThread(bool)"
I'm sort of lost on where to start with this one, but I'm hoping it's a common enough problem that there's a solution out there somewhere!
[Edit - updated to include code]
public System.Threading.Tasks.Task<SomeDto> RetrieveAsync(string someIdentifier, string includePermissibleActions)
{
return RetrieveAsync(someIdentifier, includePermissibleActions, System.Threading.CancellationToken.None);
}
public async System.Threading.Tasks.Task<SomeDto> RetrieveAsync(string someIdentifier, string includePermissibleActions, System.Threading.CancellationToken cancellationToken)
{
if (someIdentifier == null)
throw new System.ArgumentNullException("someIdentifier");
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/someName/{someIdentifier}?");
urlBuilder_.Replace("{someIdentifier}", System.Uri.EscapeDataString(ConvertToString(someIdentifier, System.Globalization.CultureInfo.InvariantCulture)));
if (includePermissibleActions != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("includePermissibleActions") + "=").Append(System.Uri.EscapeDataString(ConvertToString(includePermissibleActions, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
}
urlBuilder_.Length--;
var client_ = _httpClient;
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
ProcessResponse(client_, response_);
var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<SomeDto>(response_, headers_).ConfigureAwait(false);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
return objectResponse_.Object;
}
else
if (status_ == 401)
{
string responseText_ = (response_.Content == null) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("Unauthorized", status_, responseText_, headers_, null);
}
else
if (status_ == 403)
{
string responseText_ = (response_.Content == null) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("Forbidden", status_, responseText_, headers_, null);
}
else
if (status_ == 404)
{
string responseText_ = (response_.Content == null) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("NotFound", status_, responseText_, headers_, null);
}
else
if (status_ == 500)
{
string responseText_ = (response_.Content == null) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("InternalServerError", status_, responseText_, headers_, null);
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}
I have login controller and in this i get my session values
[HttpPost]
public ActionResult Login(Models.AdminUsers adminUsers)
{
try
{
if (Session["iUserId"] != null || GetCookie("iUserId") != null)
{
return Redirect("/Home/Index");
}
if (ModelState.IsValid)
{
using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
{
var resultUsers =
(from tableAdminUsers in dc.AdminUsers
where
tableAdminUsers.cEmail == adminUsers.cEmail &&
tableAdminUsers.cPassaword == new Class.AesCryption().Encryption(adminUsers.cPassaword) &&
tableAdminUsers.iActive == 1
select new Models.AdminUsers
{
iUserId = tableAdminUsers.iUserId,
cEmail = tableAdminUsers.cEmail,
cUserName = tableAdminUsers.cUserName,
cUserSurname = tableAdminUsers.cUserSurname,
cImage = tableAdminUsers.cImage
}).FirstOrDefault();
if (resultUsers != null)
{
if (adminUsers.lBeniHatirla == false)
{
Session.Add("iUserId", resultUsers.iUserId);
Session.Add("cEmail", resultUsers.cEmail);
Session.Add("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
Session.Add("cUserSurname", resultUsers.cUserSurname.ToUpper());
Session.Add("cImage", resultUsers.cImage);
}
else
{
CreateCookie("iUserId", resultUsers.iUserId.ToString());
CreateCookie("cEmail", resultUsers.cEmail);
CreateCookie("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
CreateCookie("cUserSurname", resultUsers.cUserSurname.ToUpper());
CreateCookie("cImage", resultUsers.cImage);
}
return Redirect("/Home/Index");
}
else
{
ViewBag.iSonuc = -7;
}
}
}
else
{
ViewBag.iSonuc = -6;
}
}
catch (Exception Ex)
{
new Class.Log().Hata("AdminUsers", "AdminUsers_Post", Ex.Message);
}
return View();
}
And i want to control to session in another controller but my session value return null. My control like this :
if (Session["iUserId"] == null && GetCookie("iUserId") == null)
{
return Redirect("/AdminUsers/Login");
}
int iUserLogin = 0;
if (Session["iUserId"] != null && Convert.ToInt32(Session["iUserId"]) > 0)
{
iUserLogin = Convert.ToInt32(Session["iUserId"]);
}
else if (GetCookie("iUserId") != null && Convert.ToInt32(GetCookie("iUserId")) > 0)
{
iUserLogin = Convert.ToInt32(GetCookie("iUserId"));
}
if (Session["iUserId"] == null && GetCookie("iUserId") == null) this row return true and redict to login page again.But i getting cookie correctly Why session value return null?
Where am I making mistakes? Can you help me?
If it is a .net core, use httpcontext. You can solve it using a distribution cache such as Redis. https://learn.microsoft.com/tr-tr/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
If you want to develop a User Manager
Use a thirty part nuget like Jwt. What it does is sso logic gives you a token for the user you use it
Try using Session with HttpContext as below:-
HttpContext.Current.Session["iUserId"]=value;
Alternativly, you can try using TempData rather then Session.
TempData["iUserId"]=value;
There is a localization function that I use for language change, in this function I am changing the value of the culture using thread, I realized that this function resets my session value.
I'm trying to figure out what is causing a crash in our Outlook plugin. We're seeing this error:
System.Runtime.InteropServices.COMException (0x8E640201): An internal support function returned an error.
at Microsoft.Office.Interop.Outlook.AddressEntry.get_AddressEntryUserType()
at DropSendOutlook.RecipientAddressGetter.GetSmtpAddress(AddressEntry addressEntry)
at DropSendOutlook.RecipientAddressGetter.<Get>b__0(Recipient recipient)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
at System.String.Join(String separator, IEnumerable`1 values)
at DropSendOutlook.RecipientAddressGetter.Get(MailItem mail)
at DropSendOutlook.ThisAddIn.outlookApp_ItemSend(Object item, Boolean& cancel)
Based on this stack trace, it's clear the problem is in this function:
private static string GetSmtpAddress(AddressEntry addressEntry)
{
var addressEntryUserType = addressEntry.AddressEntryUserType;
Log.Info(addressEntryUserType);
//Now we have an AddressEntry representing the Sender
if (addressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry
|| addressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
//Use the ExchangeUser object PrimarySMTPAddress
ExchangeUser exchUser = addressEntry.GetExchangeUser();
return exchUser != null ? exchUser.PrimarySmtpAddress : GetSmtpAddressExchangeOld(addressEntry);
}
if (addressEntryUserType == OlAddressEntryUserType.olSmtpAddressEntry)
{
return addressEntry.Address;
}
if (addressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry)
{
// Could throw System.Runtime.InteropServices.COMException (0x8004010F), possible reasons with permissions.
try
{
try
{
var contact = addressEntry.GetContact();
if (contact != null && contact.Email1AddressType == "EX")
{
var currentDisplayName = contact.Email1DisplayName;
contact.Email1DisplayName = string.Empty;
var separators = new[] { '(', ')' };
var eMailParse = contact.Email1DisplayName.Split(separators);
contact.Email1DisplayName = currentDisplayName;
return eMailParse[1];
}
}
catch
{
var ms = new FrmMessage();
ms.SetMessage("Contact was not found!");
ms.Show();
throw;
}
}
catch (System.Exception ex)
{
Log.Error(ex.ToString());
}
return addressEntry.Address;
}
if (addressEntryUserType == OlAddressEntryUserType.olExchangeDistributionListAddressEntry)
{
var exchDistribution = addressEntry.GetExchangeDistributionList();
return exchDistribution != null
? exchDistribution.PrimarySmtpAddress
: GetSmtpAddressExchangeOld(addressEntry);
}
if (addressEntryUserType == OlAddressEntryUserType.olOutlookDistributionListAddressEntry)
{
var addresses = from AddressEntry member in addressEntry.Members select GetSmtpAddress(member);
return string.Join(";", addresses);
}
return addressEntry.Address;
}
And appears to be coming from this line specifically:
var addressEntryUserType = addressEntry.AddressEntryUserType;
What is causing this? Is there some kind of check we should be making before accessing AddressEntryUserType to avoid this error?
We have the following code to check if the given username and password exists in database:
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
}
If we have the username and password in database this works fine but throws an error if username or password is wrong and no records found.
This might be simple but as I am new to lambda could not get get it right.
How can I change the lambda query so we can handle nulls?
Thanks
Use SingleOrDefault, which will return only one record or null if none exists.
return Mapper.Map(context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword));
Later you can check:
User returnedObject = GetUserByUserNameAndPassword(username,password)
if(returnedObject == null)
{
//User doesn't exist
}
Remember Single/SingleOrDefault will throw an exception if multiple records exist against the criteria.
You should change from Single to SingleOrDefault, it returns null when no data match
context.UserEntities.SingleOrDefault(u => u.UserName == userName &&
u.UserPassword == userPassword)
.Any() will return true if a matching record is found or false if no record is found.
So a slight modifcation to you existing code will work.
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
if (context.UserEntities.Any(u => u.UserName == userName && u.UserPassword == userPassword))
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
else
{
//Deal with no user here through chosen method
}
}
}
Make use of FirstOrDefault or SingleOrDefualt and check for null like as below
var user =context.UserEntities.SingleOrDefault(u => u.UserName == userName
&&
u.UserPassword == userPassword);
if(user!=null)
{
//do code
}
Use SingleOrDefault and check for Null prior to calling Map
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
var user = context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword);
return user !=null ? Mapper.Map(user) : null;
}
}
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
linq query and nulls
This throws a null exception if is some of elements in xml file missing - I don't want to get this exception - I would like just add empty string to list data beside missing element
InstrumentDescription inputFile = InstrumentDescription.Load(openFileDialog1.FileName);
var queryManufacturer = from dataManufaturer in
inputFile.Identification.Manufacturers.Manufacturer
select new
{
dataManufaturer.name,
dataManufaturer.cageCode,
dataManufaturer.FaxNumber,
dataManufaturer.URL.OriginalString
};
foreach (var a in queryManufacturer)
{
data.Add(a.name);
if (a.cageCode == null) data.Add("");
else data.Add(a.cageCode);
if (a.FaxNumber == null) data.Add("");
else data.Add(a.FaxNumber);
if (a.OriginalString == null) data.Add("");
else data.Add(a.OriginalString);
}
I tried somenthing like this - but it doesn't work
select new
{
name = dataManufaturer.name ?? "",
cageCode = dataManufaturer.cageCode ?? "",
FaxNumber = dataManufaturer.FaxNumber ?? "",
OriginalString = dataManufaturer.URL!=null ? dataManufaturer.URL.OriginalString : ""
};
I want to have a empty string if some of elements are missing, not to get exception.
I SOLVE IT !!!
In select I only use select new { dataManufacturer } not these all possible elements and when I am adding to list just test if for example dataManufacturer.name is null or not
I'm going to post this "comment" here as a CW to help give you a nudge in the right direction in finding the source of the problem.
There are way too many potential causes for where the null reference exception will happen here in this block of code alone. Looking at your responses in your other question, it's clear you have no idea how to find out where the problem is. So try this to find out. This is a rewritten form of the code you have shown us to facilitate finding out where the null is. Run it to find out where this happens and hopefully you'll be able to fix it yourself. If not, then please share the results of this test with us so we can better understand your problem and give you a better answer to help you fix your problem.
This assumes you are making a Windows Forms application or WPF application.
var dialog = openFileDialog1;
if (dialog == null)
{
MessageBox.Show("openFileDialog1 is null");
}
var filename = dialog.FileName;
if (filename == null)
{
MessageBox.Show("openFileDialog1.FileName is null");
}
InstrumentDescription input;
try
{
input = InstrumentDescription.Load(filename);
}
catch (NullReferenceException e)
{
MessageBox.Show("NullReferenceException in InstrumentDescription.Load():\n" + e.Message);
}
if (input == null)
{
MessageBox.Show("inputFile is null");
}
var id = input.Identification;
if (id == null)
{
MessageBox.Show("inputFile.Identification is null");
}
var mans = id.Manufacturers;
if (mans == null)
{
MessageBox.Show("inputFile.Identification.Manufacturers is null");
}
var man = mans.Manufacturer;
if (man == null)
{
MessageBox.Show("inputFile.Identification.Manufacturers.Manufacturer is null");
}
var i = 0L;
foreach (var dm in man)
{
if (dm == null)
{
MessageBox.Show("dataManufaturer at index "+i+" is null");
}
if (dm.name == null)
{
MessageBox.Show("dataManufaturer.name at index " + i + " is null");
}
if (dm.cageCode == null)
{
MessageBox.Show("dataManufaturer.cageCode at index " + i + " is null");
}
if (dm.FaxNumber == null)
{
MessageBox.Show("dataManufaturer.FaxNumber at index " + i + " is null");
}
var u = dm.URL;
if (u == null)
{
MessageBox.Show("dataManufaturer.URL at index " + i + " is null");
}
if (u.OriginalString == null)
{
MessageBox.Show("dataManufaturer.URL.OriginalString at index " + i + " is null");
}
i++;
}
How about
var queryManufacturer = from dataManufaturer in input.Identification.Manufacturers.Manufacturer
where dataManufaturer != null
select {...}