none
Object Reference Not Set to and Instance of an Object Error? RRS feed

  • Question

  • Hi all,

    I'm getting the object reference not set to an instance of an object error in teh following code...

     private void AddRewriteRule(string port, string avPort, string ruleName, string ruleUrlMatch)
            {
                using (ServerManager serverManager = new ServerManager())
                {
                    Site site = serverManager.Sites.FirstOrDefault(s => s.Bindings.ElementAt(0).EndPoint.Port == Int32.Parse(port));
                    string siteName = site.Name;

    I think its blowing up at the highlighted code and may have something to do with Int32.Parse. ??

    I had a troubleshooting message right after that code and it never reached it.  The port is coming into the function as a string, as you can see.

    Any idea what is wrong here?  This is code from a widget where we haven't seen this issue yet so it was working.  Scratching my head.

    Any help or points to what else I could look at/for would be greatly appreciated!!

    THANKS!!!!

    Thursday, October 10, 2019 5:57 PM

All replies

  • Hello,

    • Are you sure port passed to the Parse method is properly set?
    • try the following with a breakpoint on Console.WriteLine and when hit using the Local window inspect Bindings and properties leading to Port for null.



    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, October 10, 2019 7:27 PM
    Moderator
  • Hello,

    • Are you sure port passed to the Parse method is properly set?
    • try the following with a breakpoint on Console.WriteLine and when hit using the Local window inspect Bindings and properties leading to Port for null.

    I wasn't sure if you posted some code to try, but I'm going to troubleshoot what is coming into the function to ensure everything is as expected.
    Thursday, October 10, 2019 7:32 PM
  • when you use a current version of VisualStudio (2017 and newer), the debugger should display what object is null (Null Reference Analysis):
    Highlights of the New Exception Helper
    Thursday, October 10, 2019 7:44 PM
  • when you use a current version of VisualStudio (2017 and newer), the debugger should display what object is null (Null Reference Analysis):
    Highlights of the New Exception Helper

    This is actually occurring in a live, production environment and we can't debug remotely.  I'm just passing off the utility with various message boxes to troubleshoot.


    • Edited by NitLions Thursday, October 10, 2019 7:48 PM
    Thursday, October 10, 2019 7:48 PM
  • analyzing a dump file (minidump is enough, even for a release build), Visual Studio is still marking the correct variable:
    Thursday, October 10, 2019 8:22 PM
  • when you use a current version of VisualStudio (2017 and newer), the debugger should display what object is null (Null Reference Analysis):
    Highlights of the New Exception Helper

    This is actually occurring in a live, production environment and we can't debug remotely.  I'm just passing off the utility with various message boxes to troubleshoot.


    Try logging e.g.

    Add this to app.config (log file name is log.log)

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
        </startup>
      <system.diagnostics>
        <trace autoflush="true" indentsize="4">
          <listeners>
            <add name="NitLionsListener" type="System.Diagnostics.TextWriterTraceListener" 
                 initializeData="log.log" />
            <remove name="Default" />
          </listeners>
        </trace>
      </system.diagnostics>
    </configuration>

    Add this class to the project

    using System;
    using System.Diagnostics;
    
    namespace LogLibrary
    {
        public static class Logger
        {
            /// <summary>
            /// Initialize trace for logging
            /// </summary>
            /// <param name="pFileType"></param>
            public static void CreateLog()
            {
                var listener = new TextWriterTraceListener("applicationLog.txt", 
                    "NitLionsListener");
    
                Trace.Listeners.Add(listener);
            }
            /// <summary>
            /// Write trace information to disk
            /// </summary>
            public static void Close()
            {
                Trace.Flush();
            }
    
            public static void Error(string message, string module)
            {
                WriteEntry(message, "error", module);
            }
            public static void Error(Exception ex, string module)
            {
                WriteEntry(ex.Message, "error", module);
            }
            public static void Warning(string message, string module)
            {
                WriteEntry(message, "warning", module);
            }
            public static void Info(string message, string module)
            {
                WriteEntry(message, "info", module);
            }
            /// <summary>
            /// Writes an empty line to separate sections in a log file
            /// </summary>
            public static void EmptyLine()
            {
                Trace.WriteLine("");
            }
    
            private static void WriteEntry(string message, string type, string module)
            {
                Trace.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},{type},{module},{message}");
            }
        }
    }
    

    Example usage

    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                Logger.CreateLog();
                Logger.Info("Starting","Main");
                try
                {
                    var exception = new Exception("Demo");
                    throw exception;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Logger.Error(e,"Here we are");
                   
                }
            }
        }
    }
    
    Have the user email you the log file.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, October 10, 2019 9:25 PM
    Moderator
  • I will definitely try the logging!   THANKS!!
    Thursday, October 10, 2019 9:28 PM
  • OK, got around to trying the logging.  I added the snippet to the App.config with some changes...

     <add name="SSLConfigListener" type="System.Diagnostics.TextWriterTraceListener" 
                 initializeData="troubleshooting.log" />

    I then added the class with the following change...

    var listener = new TextWriterTraceListener("applicationLog.txt",
                    "SSLConfigListener");

    However, when I run the application to error, I get a blank applicationLog.txt.  I tried changing the applicationLog.txt above to match what is in the app.config, but that doesn't work either.  

    Currently I have this...

    Logger.CreateLog();
    Logger.Info("Starting", "btnConfigure_Click");

    With this in the catch...

    Logger.Error(e, "btnConfigure_Click");

    What am I doing wrong.  And what is this going to show me other than the message I'm already displaying to my UI as ex.Message?

    Monday, October 28, 2019 4:57 PM
  • What am I doing wrong.  And what is this going to show me other than the message I'm already displaying to my UI as ex.Message?

    If you're trying to catch the exception message and log it, then consider what is in the links.

    https://www.codeproject.com/Articles/43182/Centralised-Exception-Handling-in-C-Windows-Applic

    You can also setup logging of the error too to a logfile, like getting the stacktrace (ex.stacktrace) and the inner.execption.message, becuase you don't want show the stacktrace at the UI.

    https://pisquare.osisoft.com/community/developers-club/blog/2016/05/10/adding-logging-to-a-net-application-using-log4net

    This also means that by using the Centralized or Global Exception Handler is that you don't need a try/catch anywhere in any code, becuase when the exception is thrown, the GEH will catch the error.

    Monday, October 28, 2019 6:50 PM
  • I'll definitely check out those links. 

    With your response, is that to say that the earlier example will not work?

    Tuesday, October 29, 2019 1:39 PM
  • I'll definitely check out those links. 

    With your response, is that to say that the earlier example will not work?

    It's just a tried and true method of having centralized/global exception handling where any exception thrown is caught at one spot, and you don't need a try/catch anywhere in the code.

    Log4net, Nlog, Serilog and others are tried and true logging frameworks.

    https://stackify.com/csharp-catch-all-exceptions/

    Tuesday, October 29, 2019 2:29 PM