Solved

Intermittent "Object reference not set to an instance of an object" Error

Posted on 2013-05-14
5
937 Views
Last Modified: 2013-05-16
I'm having a problem trying to identify what is causing this intermittent object reference in the attached code. I've tried replicating it multiple ways with no luck. This code is called every time an order is completed and we only encounter the issue from time to time. The Elmah error isn't very helpful...

Object reference not set to an instance of an object.
System.NullReferenceExceptionObject reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at RequestRepo.Complete(Int32 Rid, Int32 CompletedBy_Uid, String notes, Boolean ReSendEmail, Boolean ReSendEmailIncludeResults)

and I have added in some logging at the beginning of the code to check that all the required parameters have been passed when the error has occurred. Today I have multiple occurances of this error in our Elmah log and the cooresponding log entry has all the parameters passed as required... any help/tricks to track the culprit down would be appreciated.

Thanks,
Greg

----------------------------------------------------------------------------------------


public Request Complete(int Rid, int CompletedBy_Uid, string notes, bool ReSendEmail, bool ReSendEmailIncludeResults) {
Request r = ViewOne( Rid );


// LOG VALUES

try {
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();

System.Reflection.MethodBase method = stackTrace.GetFrame(1).GetMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;

// get calling method name
string callingMethod = callingMethod = className + "." + methodName;

ErrorTracking etr = new ErrorTracking() {
Created = DateTime.Now,
FunctionRequirements = "Request Complete(int Rid, int CompletedBy_Uid, string notes, bool ReSendEmail, bool ReSendEmailIncludeResults)",
ParametersPassed = Rid + " / " + CompletedBy_Uid + " / " + notes + " / " + ReSendEmail + " / " + ReSendEmailIncludeResults,
Notes = "Called By: " + callingMethod
};
db.ErrorTrackings.AddObject(etr);
db.SaveChanges();
}
catch { }

// LOG VALUES - END


if ( r != null ) {
DateTime date = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0 );
if ( r.CompletedDate == null && db.ServiceDetails.Count( x => x.Rid == r.Rid && x.Created < date ) > 0 ) {
List<ServiceDetail> sds = db.ServiceDetails.Where( x => x.Rid == r.Rid && x.Created < date ).ToList();
foreach ( ServiceDetail sd in sds ) {
sd.Created = DateTime.Now;
}
}

r.Status = "Completed";
r.SignedOut = false;
r.SignedOut_Uid = null;
r.SignedOutDate = null;

r.Completed = true;
r.CompletedBy_Uid = CompletedBy_Uid;
r.CompletedDate = DateTime.Now;
r.Notes = notes;

r.Canceled = false;
r.CanceledBy_Uid = null;

bool sendEmail = false;
bool includeResults = ReSendEmailIncludeResults;

if (ReSendEmail)
sendEmail = true;
else {
if (r.EmailNotification.HasValue) {
if (r.EmailNotification.Value) {
if (r.SentEmails.Where(x => x.EmailSent).Count() == 0)
sendEmail = true;
}
}
}

if (sendEmail) {
if (ReSendEmailIncludeResults)
includeResults = true;
else {
if (r.EmailNotificationIncludeResults.HasValue) {
if (r.EmailNotificationIncludeResults.Value) {
if (r.SentEmails.Where(x => x.EmailSent).Count() == 0)
includeResults = true;
}
}
}
}

r.EmailNotificationIncludeResults = false;

db.SaveChanges();


if ( r.ServiceSubmitted != null ) {
try {
if (r.ServiceSubmitted.Value) {
Accounts_UserRepo aur = new Accounts_UserRepo((EntityConnection)db.Connection);
Accounts_User au = aur.ViewOne(r.Auid);
if (au != null) {
if (au.Account.ServiceAccessible) {
if (au.Account.ReturnMethod == "Email") {
if (au.Account.ServiceEmail != string.Empty) {
bool send = true;

if (au.Aid == 163 && r.Rcrtid == 3) {
send = false;
}

if (send) {
//Send email
string email = "";


MailMessage message = new MailMessage();
message.To.Add(au.Account.ServiceEmail);

if (au.Account.AccountKey == "9876543" || au.Account.AccountKey == "1234567")
message.Subject = r.ServiceUploadReference;
else
message.Subject = "Service Request Results: Order # - " + r.OrderNumber;

message.IsBodyHtml = true;
message.Body = email;

Requests_FileRepo rfr = new Requests_FileRepo((EntityConnection)db.Connection);
List<Requests_File> files = rfr.ViewByRid(Rid);

if (files.Count() > 0) {
string filesDir = ConfigurationManager.AppSettings["FileDir"].ToString();
foreach (Requests_File file in files) {
string fileFileDir = file.Dir;

string path = filesDir + fileFileDir + file.FileName;

path = path.Replace(@"files\files", "files").Replace(@"files/files", "files").Replace(@"files../files", "files");
path = path.Replace(@"files\../files", "files");

if (File.Exists(path)) {
message.Attachments.Add(new Attachment(path));
}
}
}
rfr.Dispose();

#region sendEmail
int emailcount = 0;
bool emailSent = false;

string error = "";

while (!emailSent && emailcount < 5) {
SmtpClient client = new SmtpClient();
emailcount++;
try {
client.Send(message);
emailSent = true;
}
catch (Exception ex) {
error += "<br /></br />-----------------------------------------------------------------<br /></br />";
error += "Message: " + ex.Message + "<br /></br />";
try {
error += "Inner Exception: " + ex.InnerException.Message;
}
catch (Exception) { }
}

SentEmail se = new SentEmail() {
Created = DateTime.Now,
Auid = r.Auid,
Rid = r.Rid,
EmailSent = emailSent,
EmailTo = message.To.ToString()
};
db.SentEmails.AddObject(se);

Thread.Sleep(TimeSpan.FromSeconds(1.5 * emailcount));
}

if (!emailSent) {
SmtpClient client = new SmtpClient();

MailMessage msgAdmin = new MailMessage();
msgAdmin.Subject = "Email Failure";
msgAdmin.IsBodyHtml = true;
msgAdmin.Body = "Email failed on rid=" + Rid.ToString() + "<br />";
msgAdmin.Body += "<br />";
msgAdmin.Body += "To = " + message.To.ToString() + "<br />";
msgAdmin.Body += "Message = " + message.Body;
msgAdmin.Body += error;
msgAdmin.To.Add("a@abc.com");

try { client.Send(msgAdmin); }
catch (Exception) { }
}
#endregion
}
}
}
else {
ReturnRequest rr = new ReturnRequest();
rr.ReturnCompletedRequest(r);
}
}
}
aur.Dispose();
}
}
catch (Exception ex) {
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}

if (sendEmail) {
try {
string email = "";
bool SiteAccount = r.Accounts_User.Account.SiteAccount;

MailMessage message = new MailMessage();
message.Subject = "Results ready for Order No: " + r.OrderNumber + ", your Reference No: " + r.ReferenceNumber;
message.IsBodyHtml = true;
message.Body = email;
message.To.Add(r.Accounts_User.Email);

if (!r.Accounts_User.Account.SiteAccount) {
message.From = new MailAddress("DoNotReply@abc.com");
}

string nl = "<br />";

#region Email Text
if (SiteAccount) {
if (includeResults) {
message.Subject = "Request Results Attached -- Order No: " + r.OrderNumber + ", Reference No: " + r.ReferenceNumber;

email += "<b>Request Date: </b>" + string.Format("{0:" + ConfigurationManager.AppSettings["jurisdictionDefaultFormat"].ToString() + "}", r.Received) + nl;
email += "<b>Order No: </b>" + r.OrderNumber + nl;
email += "<b>Reference No: </b>" + r.ReferenceNumber + nl + nl + nl;
}
else {
message.Subject = "Results ready for Order No: " + r.OrderNumber + ", your Reference No: " + r.ReferenceNumber;

email += "<b>Request Date: </b>" + string.Format("{0:" + ConfigurationManager.AppSettings["jurisdictionDefaultFormat"].ToString() + "}", r.Received) + nl;
email += "<b>Order No: </b>" + r.OrderNumber + nl;
email += "<b>Reference No: </b>" + r.ReferenceNumber + nl + nl + nl;
}
}
else {
message.Subject = "Request Results Attached -- Order No: " + r.OrderNumber + ", Reference No: " + r.ReferenceNumber;

email += "<b>Request Date: </b>" + string.Format("{0:" + ConfigurationManager.AppSettings["jurisdictionDefaultFormat"].ToString() + "}", r.Received) + nl;
email += "<b>Order No: </b>" + r.OrderNumber + nl;
email += "<b>Reference No: </b>" + r.ReferenceNumber + nl + nl + nl;
}
#endregion

if ((sendEmail && includeResults) || !SiteAccount) {
Requests_FileRepo rfr = new Requests_FileRepo((EntityConnection)db.Connection);
List<Requests_File> rfs = rfr.ViewByRid(Rid).ToList();
rfr.Dispose();

InvoiceRepo ir = new InvoiceRepo((EntityConnection)db.Connection);
string html = ir.GetInvoice(r, true);
ir.Dispose();

System.IO.MemoryStream mstr = PDFGeneratorRepo.ConvertHtml(html);

if (mstr.Length > 0) {
mstr.Position = 0;
message.Attachments.Add(new Attachment(mstr, "Invoice.pdf"));
}

string rootDir = ConfigurationManager.AppSettings["FileDir"].ToString();
foreach (Requests_File rf in rfs) {
string file = rootDir + rf.Dir + rf.FileName;

file = file.Replace(@"files\files", "files").Replace(@"files/files", "files").Replace(@"files../files", "files");
file = file.Replace(@"files\../files", "files");

try {
message.Attachments.Add(new Attachment(file));
}
catch (Exception ex) {
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}



}

#region sendEmail

message.Body = email;

int emailcount = 0;
bool emailSent = false;

string error = "";

while (!emailSent && emailcount < 5) {
SmtpClient client = new SmtpClient();
emailcount++;
try {
client.Send(message);
emailSent = true;
}
catch (Exception ex) {
error += "<br /></br />-----------------------------------------------------------------<br /></br />";
error += "Message: " + ex.Message + "<br /></br />";
try {
error += "Inner Exception: " + ex.InnerException.Message;
}
catch (Exception ex1) {
Elmah.ErrorSignal.FromCurrentContext().Raise(ex1);
}
}

SentEmail se = new SentEmail() {
Created = DateTime.Now,
Auid = r.Auid,
Rid = r.Rid,
EmailSent = emailSent,
EmailTo = message.To.ToString()
};
db.SentEmails.AddObject(se);

Thread.Sleep(TimeSpan.FromSeconds(1.5 * emailcount));
}
if (!emailSent) {
SmtpClient client = new SmtpClient();

MailMessage msgAdmin = new MailMessage();
msgAdmin.Subject = " Email Failure";
msgAdmin.IsBodyHtml = true;
msgAdmin.Body = "Email failed on rid=" + Rid.ToString() + "<br />";
msgAdmin.Body += "<br />";
msgAdmin.Body += "To = " + message.To.ToString() + "<br />";
msgAdmin.Body += "Message = " + message.Body;
msgAdmin.Body += error;
msgAdmin.To.Add("a@abc.com");

try { client.Send(msgAdmin); }
catch (Exception ex) {
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
#endregion
}
catch (Exception ex) {
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
//ser.Dispose();
db.SaveChanges();

if (r.FaxResults)
FaxResults(r);
}

return r;
}
0
Comment
Question by:Greg_L_WER
  • 3
  • 2
5 Comments
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
Your error could possibly be arising in the following block of code:

if ( r != null ) {
DateTime date = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0 );
if ( r.CompletedDate == null && db.ServiceDetails.Count( x => x.Rid == r.Rid && x.Created < date ) > 0 ) {
List<ServiceDetail> sds = db.ServiceDetails.Where( x => x.Rid == r.Rid && x.Created < date ).ToList();
foreach ( ServiceDetail sd in sds ) {
sd.Created = DateTime.Now;
}
}

r.Status = "Completed";
r.SignedOut = false;
r.SignedOut_Uid = null;
r.SignedOutDate = null;

You are testing to make sure that r is not null within the first block, but then after that block, you assign values ro r (r.Status, r.SignedOut etc) which will fail if r IS null, and will generate the error message that you are seeing.

The very first line of the code

Request r = ViewOne( Rid );

I would suggest testing to see if r has a value there, and returning a null value if ViewOne(Rid) is null.

public Request Complete(int Rid, int CompletedBy_Uid, string notes, bool ReSendEmail, bool ReSendEmailIncludeResults) {
      Request r = ViewOne( Rid );
      if (r = null)
    {
          return null;
    }
    else
    {
     ... the body of the existing code
    }
}
0
 

Author Comment

by:Greg_L_WER
Comment Utility
    public Request Complete(int Rid, int CompletedBy_Uid, string notes, bool ReSendEmail, bool ReSendEmailIncludeResults) 
    {
        Request r = ViewOne(Rid);

        if (r != null) 
        {
            //  All code within this block

            DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            if (r.CompletedDate == null && db.ServiceDetails.Count(x => x.Rid == r.Rid && x.Created < date) > 0) 
            {
                List<ServiceDetail> sds = db.ServiceDetails.Where(x => x.Rid == r.Rid && x.Created < date).ToList();
                foreach (ServiceDetail sd in sds) 
                {
                    sd.Created = DateTime.Now;
                }
            }

        }

        return r;
    }

Open in new window

  Hi Arthur,

Thanks for the idea... it's hard to tell once the formatting is lost when posting code here (just noticed the embeded code button which definitely makes it much easier to read)... the code block you mention in the beginning actually contains all the code within this method... it's essentially what you're suggesting except that the return null is at the end instead of the beginning... I've culled out the code in the middle to make it easier to see here.  Passing a bad Rid to the ViewOne method returns null which should in turn returns it to the Complete code caller code... any other ideas by chance?

Thanks again,
Greg
0
 
LVL 44

Accepted Solution

by:
Arthur_Wood earned 500 total points
Comment Utility
as I noted in my original answer, the only glaring issue that I noticed had to do with the local Request object being null.  I did not look through all of your code, to see f there might be other objects that could also possibly be null.  Other than that, I can't see any other obvious points of contention.

AW
0
 

Author Comment

by:Greg_L_WER
Comment Utility
Thanks for taking a look...
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
Glad to be of assistance.

AW
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to count occurrences of each item in an array.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now