-1

I know what nullreference means but having a problem pinpointing exactly what is causing the problem. I have a .NET C# Console Application that works perfectly in my development environment when run, but when deployed to a server, I get the NullReference object not set to an instance of an object... error message. I am unable to see the exact line because it is in the compiled executable console. I have tried to no avail to see where the error is occurring. My database connections are good, my SELECT queries return values when I test them directly in SQL Server Management Studio so I am at a pause for what is producing this error and it actually works without error when run in VS on my deve machine. Here is the code:

namespace BWC2Mailer
{
    class Program
    {
       static void Main(string[] args)
        {


            String constr = ConfigurationManager.ConnectionStrings["binddropdown3"].ConnectionString;

            SqlConnection con = new SqlConnection(constr);
            con.Open();          

                SqlCommand cmd1 = new SqlCommand("SELECT distinct TestEmail, TestBWC FROM TestTable2 WHERE CONVERT(CHAR(10), GETDATE(), 101) = DATEADD(day,-2, TestBWC) AND TestBWC <> '' AND TestEmail <> ''", con); // Test
                SqlDataReader rd1 = cmd1.ExecuteReader();

                if (rd1.HasRows)
                    {
                SqlConnection con3 = new SqlConnection(constr);

                while (rd1.Read())
                {

                  var EmailToSendPre = rd1["TestEmail"].ToString(); // Test Email


                    string EmailToSend = EmailToSendPre.Replace("`", "");

                  string ExpirationDate = rd1["TestBWC"].ToString();


                    if (emailIsValid(EmailToSend))
                    {


                        var TodayIs = DateTime.Today.ToString("MM/dd/yyyy");

                        con3.Open();

                        var QType = "BWC2";
                        var BWCSubject = "5th Notice-2 days prior";

                        string BWCBody = "<p>...</p>";

                        SqlCommand cmd3 = new SqlCommand("SELECT * From EmailNotificationStatus WHERE Email = '" + EmailToSend + "' AND SendDate = '" + TodayIs + "' AND QueryType ='" + QType + "'", con3);
                        SqlDataReader rd3 = cmd3.ExecuteReader();

                        if (!rd3.Read())
                        {

                            MailMessage mailObj = new MailMessage(
                                "noreply@xxxx.com", EmailToSend, BWCSubject, BWCBody);
                            SmtpClient SMTPServer = new SmtpClient("xxxx.xxxxx.com"); // 

                            MailAddress cc = new MailAddress("xxxx@xxxx.com");
                            mailObj.CC.Add(cc);

                            mailObj.IsBodyHtml = true;
                            try
                            {
                                SMTPServer.Send(mailObj);
                            }

                            catch (Exception ex)
                            {


                            }
                            var TodayNow = DateTime.Today.ToString("MM/dd/yyyy");


                            SqlConnection con2 = new SqlConnection(constr);

                            con2.Open();



                            SqlCommand cmd2 = new SqlCommand("Insert INTO EmailNotificationStatus(Email,Sent,QueryType,SendDate) values(@email,@Sent,@QueryType,@SendDate)", con2);
                            cmd2.Parameters.Add("@email", SqlDbType.VarChar).Value = EmailToSend;
                            cmd2.Parameters.Add("@Sent", SqlDbType.VarChar).Value = "YES";
                            cmd2.Parameters.Add("@QueryType", SqlDbType.VarChar).Value = "BWC2";
                            cmd2.Parameters.Add("@SendDate", SqlDbType.VarChar).Value = TodayNow;

                            cmd2.ExecuteNonQuery();

                            con2.Close();


                        }
                    }



                    con3.Close();
                }
            }

            }



public static bool emailIsValid(string email)
    {
        string expresion;
        expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        if (Regex.IsMatch(email, expresion))
        {
            if (Regex.Replace(email, expresion, string.Empty).Length == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
Jason
  • 612
  • 8
  • 20
  • 2
    Well, [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Mar 12 '15 at 14:56
  • 2
    Add logs before possible failing lines of code to help you identify where there issue is. – im1dermike Mar 12 '15 at 14:56
  • There could be so many things, but first check if you are connecting to right database. Implement some kind of logging for each step, Make sure you have right connection string for `ConnectionStrings["binddropdown3"]` Later use SQL profiler to see if your command is getting executed on the server. Without these steps it would be really hard *(if not impossible)* to know the exact cause. – Habib Mar 12 '15 at 14:57
  • You can use .pdbs with optimized ("Release") builds too. You can even include line numbers if you want, though they do sometimes wind up a little off. – Peter Duniho Mar 12 '15 at 14:58
  • @im1dermike have done that and I get the same generic null reference error in the log as what is written to the console – Jason Mar 12 '15 at 14:58
  • @PeterDuniho I will try that – Jason Mar 12 '15 at 14:59
  • @Jason I would start with the simplest thing for example ` ConfigurationManager.ConnectionStrings["binddropdown3"].ConnectionString;` what does the config file on the production server look like..? are you missing this entry on the production side..? if not then I would look at the SqlDataClient.dll's and see if you have those being references and or have the CopyToLocal=true property set.. It sounds to me like a reference issue that you do not have set and or installed on the target environemet – MethodMan Mar 12 '15 at 15:01
  • 5
    You've asked the wrong question. Your actual question should be "how do I get more detailed exception information from a production environment?", because that's the next thing you need to do in order to diagnose the problem. – spender Mar 12 '15 at 15:02
  • @Jason: you can figure out what line the exception is on. Add logs like "Opening DB connection..." etc. This is programming 101... – im1dermike Mar 12 '15 at 15:35

1 Answers1

1

Wrap your Program in:

try
{

}
catch (exception ex)
{
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@".\error.log",true))
     {
         sw.Write(String.Format("{0}/t {1}", DateTime.Now, ex.ToString()));
         sw.Write(String.Format("{0}/t {1}", DateTime.Now, ex.StackTrace.ToString()));
     }
}

Because a null reference exception in your program could literally be anything, there is no way for anyone to know where your error is. Logging will give you the exact line your error is occurring on making it simple to locate the error..

Also make sure you have the programs .pdb files in your deployment folder this will give your log more information about line numbers etc

user1
  • 15,594
  • 12
  • 96
  • 166
  • When a .NET program crashes, the relevant information is already output to the console (if present) and written to the event log. And the OP is already getting the crash information; their concern is that it lacks debug information (being an optimized build). I don't see how the above helps to even diagnose the problem, never mind actually solve the problem for the OP. **Which is a long way of saying: that's not an answer to this question.** – Peter Duniho Mar 12 '15 at 15:01
  • I tried wrapping my program and got this message which doesn't tell me much of what I already know: 3/12/2015 11:21:59 AM/t System.NullReferenceException: Object reference not set to an instance of an object. at BWC2Mailer.Program.Main(String[] args)3/12/2015 11:21:59 AM/t at BWC2Mailer.Program.Main(String[] args) – Jason Mar 12 '15 at 15:23
  • @Jason and you've definitely got the `.pdb` file in with your deployed program? – user1 Mar 12 '15 at 15:24
  • @user1 I am not deplying it via install, I have been taking the executable from the debug bin folder. I should still be able to run it correctly that way, right? – Jason Mar 12 '15 at 15:26
  • yes so when you take the program out of debug take all the .pdb files with it aswell.. This should provide more information about your exception (line numbers etc) – user1 Mar 12 '15 at 15:29
  • @user1 I've tried opening the PDB file via VS but there is a lot of gibberish there. Is there a native program for reading it? – Jason Mar 12 '15 at 15:44
  • You don't need to open it. Just drop it in the same folder with your deployed .exe program and then run your program (which will then crash with null reference exception as you said).. Your `error.log` should then give you more information such as line numbers for you to locate the error – user1 Mar 12 '15 at 15:45