question

Anja-7727 avatar image
0 Votes"
Anja-7727 asked DuaneArnold-0443 commented

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

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 :-)

dotnet-csharpwindows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered karenpayneoregon edited

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




· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,
I'm little confused - but now I will try what you say.

II don't get any error with the word ConnectionString anymore (I had to change it back from appsettings.json). I used Watch1 and Call Stack - not any errors to see - except of the one in Error List when not running the code.

Where to put the code from your link - in the MainWindow (from my UI/AnsiBug project) or in the usercontrols?

Best regards
Simsen :-)

But in the Exception Setting of the Call Stack under Win32 Exceptions there is some

0x40010005 Control-C
0x40010008 Control-Break
0xc0000005 Access violation
0xc0000008 An invalid handle was specified
0xc0000420 Assertion failed
0xe073616e Sanitizer error detected

I have added a screendump where you can see the error

80244-objectreference.jpg


0 Votes 0 ·
objectreference.jpg (371.5 KiB)

Ohhhh I forgot it again - screendumps for the App.Config in the UI/AnsiBug project

80301-app-config.jpg


0 Votes 0 ·
app-config.jpg (277.1 KiB)

Did you get a chance to try the code sample I posted several hours ago? Also why not use Framework 4.8 ??? This is what my new code sample uses.

0 Votes 0 ·
Anja-7727 avatar image
0 Votes"
Anja-7727 answered

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>
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered Anja-7727 commented

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

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, thank you for your answer.

This was what I started out with. I have tried it out right now with no success.

So If you have any tips I will be very glad

Best regards
Simsen :-)

Helper.cs
using System;
using System.Configuration;

 namespace DAL
 {
     public class Helper
     {
         private static readonly string dbPath = ConfigurationManager.AppSettings["AnsiBugDb"];
    
         public static string Conn()
         {
             return ConfigurationManager.ConnectionStrings[dbPath].ConnectionString;
         }
     }
 }
0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

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();.




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Anja-7727 avatar image
0 Votes"
Anja-7727 answered Anja-7727 published

Thank You Karen,
I have tried to use appsettings.json that gives me an error exactly the same spot - just another error (The ConnectionString property has not been initialized).

I cann't find the error - except on the Error List in VS. which is on line 109 in the MainWindow:

<views:CategoryView x:Name="CategoryView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />

I have almost given up but I appreciate when you help me. I learn a little every time.

It works perfect running the program. But gets me an error on design time.

Best regards

My appsettings.json
{
"exclude": [
"/bin",
"
/bower_components",
"/jspm_packages",
"
/node_modules",
"/obj",
"
/platforms"
],

   "Data": {
     "AnsiBugDb": "Server=.;Database=AnsiBug;Trusted_Connection=True;"
   }
 }

My helper class

 using Microsoft.Extensions.Configuration;
 using System.IO;
 using System.Configuration;
 using System.Data.SqlClient;
    
 namespace DAL
 {
     public class Helper
     {
         public string ConnectionString { get; set; }
    
         public Helper()
         {
             var configuration = GetConfiguration();
             ConnectionString = configuration.GetSection("Data").GetSection("AnsiBugDb").Value;
         }
           
         public static string ConnectionStringName = "AnsiBugDb";
    
         public IConfigurationRoot GetConfiguration()
         {
             var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional:true, reloadOnChange:true);
    
             return builder.Build();
         }
     }
 }

and my DalCategory

 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()
         {
             Helper helper = new Helper();
             string test = helper.ConnectionString;
             using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(@test))
             {
                 if (connection.State == ConnectionState.Closed)
                 {
                     connection.Open();
                 }
    
                 return connection.Query<Category>("dbo.Category_GetAll").ToList();
             }
         }
         #endregion
    
         #region Insert
         #endregion
    
         #region Update
         #endregion
    
         #region Delete
         #endregion
     }
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered Anja-7727 commented

@Anja-7727

And somehow, you forget to mention you are using Core?

What I have been explaining only works for non Core solution.

I have use this technique in getting the connectionstring to a DAL in an ASP.NET Core project that is using Core classlib project DAL. It should work for a Core classlib project where the root project WPF Core solution.

https://corderoski.wordpress.com/2017/09/18/how-to-read-appsettings-json-from-class-library-in-asp-net-core


string connectstring = SqlDataConnection;

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Now I'm lost?

I'm pretty sure I have made the solution and the UI project for wpf .framework.

I then have classes 4 of them, which on (the Views class) is an usercontrol class the others are staight forward class: DAL, Model and ViewModel.

In the DAL I have my connections and methods to get data from the DB. I here use Dapper to get the Data.

Is these 3 classes called Core solution?

Best regards
Simsen :-)

0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered DuaneArnold-0443 edited

@Anja-7727

You are apparently using ..NET Framework and not .NET Core. So i don't understand how appsettings.jason is being talked about in this thread, which has to do with using a ,NET Core WPF solution.

Your efforts should be about the correct use of an app,config file in a non .NET Core solution that I have explained to you and given you a .link about it too.

I have asked you to post the content of app.config you are using in the root project.

So you are not using a classlib project called DAL and you have a class in the WPF project named DAL?


.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon edited

Here is code to get a connection string using appsettings.json with .NET Framework 4.8 rather than .NET Core.

appsettings.json

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

Test code

 using System;
 using System.Data.SqlClient;
 using Connections;
    
 namespace ConnectionsFrontEnd.Classes
 {
     public class DataOperations
     {
         public static bool TestConnection()
         {
             try
             {
                 using (var cn = new SqlConnection() {ConnectionString = Helper.GetConnectionString()})
                 {
                     cn.Open();
                     return true;
                 }
             }
             catch (Exception)
             {
                 /*
                  * Make sure to do logging or some other form
                  * of recovery.
                  */
                 return false;
             }
         }
     }
 }

80231-connect.png





connect.png (8.1 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Anja-7727 avatar image
0 Votes"
Anja-7727 answered Anja-7727 published

Thank you karenpayneoregon

I'm pretty confused right now, so I've decided to stick with the app.settings approach. It's too much for me to run back and forth between json and app.settings

Right now I finally find the stack trace error (this time another than the last many days). 2 errors
DAL.Account.DalCategory.GetCategories()
ViewModel.Account.CategoryViewModel.LoadCategories();

Best regards to you both
Simsen :-)

My GetCategories look like this

 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;
 using DAL;
    
 namespace DAL.Account
 {
     public class DalCategory
     {
         #region Get
         public List<Category> GetCategories()
         {
             string conn = Helper.Conn();
             using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(conn))
             {
                 if (connection.State == ConnectionState.Closed)
                 {
                     connection.Open();
                 }
    
                 return connection.Query<Category>("dbo.Category_GetAll").ToList();
             }
         }
         #endregion
    
         #region Insert
         #endregion
    
         #region Update
         #endregion
    
         #region Delete
         #endregion
     }
 }

And my LoadCategories() code look like this
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Model.Account;
using DAL.Account;
using System.ComponentModel;

 namespace ViewModel.Account
 {
     public class CategoryViewModel
     {
         //private Category _selectedCategory;
         //public MyICommand DeleteCommand { get; set; }
         //public Category SelectedCategory
         //{
         //    get
         //    {
         //        return _selectedCategory;
         //    }
    
         //    set
         //    {
         //        _selectedCategory = value;
         //        DeleteCommand.RaiseCanExecuteChanged();
         //    }
         //}
    
         public CategoryViewModel()
         {
             LoadCategories();
             //DeleteCommand = new MyICommand(OnDelete, CanDelete);
         }
    
         public List<Category> Categories_GetAll { get; set; }
    
         public void LoadCategories()
         {
             DalCategory dalCategory = new DalCategory();
             Categories_GetAll = new List<Category>();
             var categories = dalCategory.GetCategories();
    
             if (categories != null)
             {
                 Categories_GetAll = categories;
             }
         }
    
         #region Delete
         //private void OnDelete()
         //{
         //    Categories_GetAll.Remove(SelectedCategory);
         //}
    
         //private bool CanDelete()
         //{
         //    return SelectedCategory != null;
         //}
         #endregion       
     }
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.