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 DuaneArnold-0443 commented

I assumed you were using .NET Core, because of the usage of appsettings.json file. The appsettings.json file is predominately used in .NET Core solutions. You are not using .NET Core you are using .NET Framework. They are two different types of .NET solution usages.

Now, l don't think you have a connectionstring problem. The error you are getting is related to something else. You need to set a debugger
breakpoint on a line where the exception was thrown, start single stepping until it blows up and then you use debugger Quickwarch and find out what object is null valued object meaning that the object is not in memory it doesn't exist.









,re




· 2
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.

I have to be sure now.

Using F11 when debugging is stepping into each single thing? If yes. I don't get any error at all I read the call stack nothing at all only show the things I am stepping into.

The error is just on the error list when focus on the MainWindow.xaml. I will now supress the error disabling the project code.

Thank you for your huge help. I'm so grateful and I've learned a lot from you the last few days.

Best regards
Simsen :-)

0 Votes 0 ·

I cannot say not to use WPF and MVVM. But to me, they both are a PITA to use together IMHO. The usage of MVVM is a Seperation of Duty.

The same can be achieved by using MVP and Windows forms solution, which is much simpler to use. It's something you may want to consider in future projects.

I am using MVP with the .NET Core Windows form solution presented on Github to you.

https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

http://polymorphicpodcast.com/shows/mv-patterns/

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

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

Your pretty confused, becuase you went off track trying to use .NET Core way of doing things concerning using configuration information that the program needs for a .NET Framework solution you are trying to apply it to.

You should have just used ConfigurationManager and gotten the connectionstring from the app.config that is used in the root project.

https://www.codeproject.com/Tips/416198/How-to-get-Connection-String-from-App-Config-in-Cs

That's it. What's in the link is that simple that can be used in any layer to get the connectionstring.

How you got to this Helper.Con() is a mystery using the ConfigurationBuilder class. How you got to an appsettings.json is questionable in a Windows desktop solution that is not a .NET Core solution. Maybe it's becuase you're trying to use Dapper that sent you down the path that you are on that is questionable IMHO.

If you look at the .NET Core Windows form app in the Startup.cs, it is using the ConfigurationBuilder class that is going to get the connectionstring information out of the appsettings.json with the connectionsting being sent to the DAL.Models. PublichingComnayContext.cs for using Entity Farmework that is using dependency injection to get the connectionstring information there.

https://github.com/darnold924/PubComanyWinCore

My take on this is that you should just simply use the ConfigurationManager that would have gotten the connectionstring out the app.config in the root project so that it could be used by any class in the project or a class in a layer like the DAL.

BTW, this not my first rodeo in using layered or n-tier in Windows desktop such as Windows form, WPF or ASP.NET Web solutions using .NET Core or .NET Framework. :)

https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

I discovered that if you want to see the link and not get q 404 not found, then you have to copy it and come completely out of Q&A and paste it into the browser's address line. It will display the info in the link.


· 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 again

I now using the ConfigurationManager to get the connectionstring but still got the error80460-stacktrace3.jpg



My App.Config connectionstring:

 <connectionStrings>
     <add name="AnsiBugDb" connectionString="Server=DESKTOP-HHUAD9Q;Database=AnsiBug;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
   </connectionStrings>


0 Votes 0 ·
stacktrace3.jpg (468.0 KiB)

And my GetCategories() method

 public List<Category> GetCategories()
         {
             string cnn = ConfigurationManager.ConnectionStrings["AnsiBugDb"].ConnectionString;
             using (IDbConnection connection = new SqlConnection(cnn))
             {
                 if (connection.State == ConnectionState.Closed)
                 {
                     connection.Open();
                 }
    
                 return connection.Query<Category>("dbo.Category_GetAll").ToList();
             }
         }

0 Votes 0 ·

I have just seen, that you use GitHub. So I have just make a profile and added my project -> https://github.com/SimsenVejle/AnsiBug

There's one thing that makes me wonder that is that you use the word Core around my project.

I do not know that I use Core. I chose (when I started up) to use wpf as UI and classes to build my mvvm model. Is there anything I do not get in terms of core application?

Best regards
Simsen :-)

0 Votes 0 ·
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.

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.

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.

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 ·
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.

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.

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.

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 ·