Still having big problems with Object reference not set to an instance of an object in my solution but have nailed it down.

Anja 426 Reputation points
2021-03-19T15:56:29.38+00:00

Hi
I get the above error and when removing all try/catch stack trace sais the problem is in the method Conn in my Helper Class in the DAL project.

using System;
using System.Configuration;

namespace DAL
{
    public class Helper
    {
        private static readonly string ConnectionStringName = "AnsiBugDb";        

        public static string Conn()
        {
            return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
        }
    }
}

Can it be, that it is because the name AnsiBugDb is set in the UI project (in App.config) if so, what have I to do to set the db connection in the DAL project instead?

I have tried to copy/paste the text in the ConnectionStringName from the App.Config in the AnsiBug project with no success. I have tried to make a new App.config in the DAL project again without success.

So I'm totally lost in what to do.

I have also tried to set a .ToString() in the return

public static string Conn()
        {
            return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString.ToString();
        }

I'm using the string in the DalCategory.cs class

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Model.Account;
using System.ComponentModel;
using Dapper;
using System.Linq;
using System.Collections.ObjectModel;
using System.Configuration;

namespace DAL.Account
{
    public class DalCategory
    {
        #region Get
        public List<Category> GetCategories()
        {
            string connectionString = Helper.Conn();
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                var list = connection.Query<Category>("dbo.Category_GetAll").ToList();
                return list;
            }          
        }
        #endregion

        #region Insert
        #endregion

        #region Update
        #endregion

        #region Delete
        #endregion
    }
}

I hope someone of you can help me.

Best regards
SimsenVejle :-)

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,245 questions
0 comments No comments
{count} votes

12 answers

Sort by: Most helpful
  1. Duane Arnold 3,211 Reputation points
    2021-03-19T18:27:15.643+00:00

    Object reference not set to an instance

    The error means that your code is trying to access/reference an object that is a null valued object that is not there in memory.

    Have you used the VS debugger, found the line that is throwing the exception and use the debugger Quickwatch to find out what object on the line is a null valued object?

    Also, you should remove all try/catches in the solution in all layers and use centralized exception handling in the presentation layer that catches all exceptions thrown throughout your solution.

    You need to use something like Log4Net in the centralized exception handler to log the exception.message, stack trace and inner.exception.message if it is not null.

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


  2. Anja 426 Reputation points
    2021-03-19T21:18:04.327+00:00

    I have googled and found out that it's because the connectiongString doesn't exists in the namespace (which is correct. the connectionString is in the AnsiBug namespace (and project)

    I then googled it further and the pages I saw told me to make an App.Config in the DAL project. I have done that. But still it fails; I have used Quickwatch and this is a little bit funny. It still make an error on that line but when moving the mouse over ConnectionString, it gives me the connectionstring. So I'm still lost here.

    The line of code that gives the error: return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString; It's the last ConnectionString that gives me the error

    Is it because in the app.config the ConnectionString is with a little c and in the Helper.cs it is with a capital C? I have tried to make them with big C and litlle C but then I instant get an error.

    Best regards

    Simsen :-)

    The Helper class look like this:

        using System;
        using System.Configuration;
    
    
        namespace DAL
        {
            public class Helper
            {
                private static readonly string ConnectionStringName = "AnsiBugDb";        
    
                public static string Conn()
                {
                    return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
                }
            }
        }
    

    The App.config file in the DAL
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <connectionStrings>
    <add name="AnsiBugDb" connectionString="Server=.;Database=AnsiBug;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
    </connectionStrings>

          <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
          </startup>
        </configuration>
    
    0 comments No comments

  3. Duane Arnold 3,211 Reputation points
    2021-03-20T00:18:47.477+00:00

    Is it because in the app.config the ConnectionString is with a little c and in the Helper.cs it is with a capital C? I have tried to make them with big C and litlle C but then I instant get an error.

    The reason the connectionstring cannot be found is becuase it is in the wrong app.config.

    Any configuration information for the layered solution should be in the root project, and in this case, that would be the Windows form project. So a classlib project that produces an app.config that the root project has reference to the classlib project should have its content copied to the app.config in the root project so that .NET can find the configuration information.

    Also, read the 'Note' in the link concerning deployment of your solution and the deployment of app.config for your solution and the runtime config file that must be in the same location as the programname.exe so .NET can find the runtime config file.

    https://www.codeproject.com/Articles/6538/Configuration-Settings-File-for-providing-applicat


  4. Duane Arnold 3,211 Reputation points
    2021-03-20T13:45:27.61+00:00

    Well, you have not proven to me that the connectionstring not being found with a screen shot of the exception while running the program in debug mode is the problem.

    Also post the content of the app.config in the root project.

    0 comments No comments

  5. Karen Payne MVP 35,036 Reputation points
    2021-03-20T16:13:07.157+00:00

    Let's say you have a class project with the following class (kept it super simple).

    Class in class project

    namespace SqlLibrary
    {
        public class Operations
        {
            public static string ConnectionString;
            public static bool TestConnection()
            {
    
                try
                {
                    using (var cn = new SqlConnection(ConnectionString))
                    {
                        cn.Open();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
    
    
            }
        }
    }
    

    app.config in the WPF project

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
        </configSections>
        <connectionStrings>
            <add name="WpfApp1.Properties.Settings.NorthWindConnectionString"
                connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind2020;Integrated Security=True"
                providerName="System.Data.SqlClient" />
        </connectionStrings>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
        </startup>
    </configuration>
    

    Code behind

    using System;
    using System.Windows;
    using SqlLibrary;
    
    namespace WpfApp1
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                Operations.ConnectionString = Properties.Settings.Default.NorthWindConnectionString;
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                Console.WriteLine(Operations.TestConnection());
            }
        }
    }
    

    Personally I would use appsettings.json rather than app.config e.g. where in this case there is a dev and prod connection string and a property to indicate the environment and with the proper code you can alter, in this case Enviroment.Production as code to read this has a reload option.

    {
      "ConnectionStrings": {
        "DevelopmentConnection": "Server=.\\SQLEXPRESS;Database=School;Integrated Security=true",
        "ProductionConnection": "Server=ProdServerDoesNotExists;Database=School;Integrated Security=true"
      },
      "Environment": {
        "Production": false
      }
    }
    

    To read the above see the following project if using WPF .NET Core and access the connection string using Helper.GetConnectionString();.

    0 comments No comments