Link to home
Create AccountLog in
Avatar of Greg_L_WER
Greg_L_WERFlag for Canada

asked on

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

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;
}
Avatar of Arthur_Wood
Arthur_Wood
Flag of United States of America image

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
    }
}
Avatar of Greg_L_WER

ASKER

    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
ASKER CERTIFIED SOLUTION
Avatar of Arthur_Wood
Arthur_Wood
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Thanks for taking a look...
Glad to be of assistance.

AW