Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

Object reference not set to an instance of an object.

Hi experts,

i am build a console app to test for database connection,---i have checked my codes but can't find any errors. can u see y it fails

thanks

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;

namespace DirectorySweeper
{
    class Program
    {
        static void Main(string[] args)
        {
            String strConnectionString = ConfigurationManager.ConnectionStrings["DB_CONN_STRING"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

this is the connectionstring

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key="DB_CONN_STRING" value="Database=AD10MACEL;Data Source=FINANCESQL\FINANCE;Persist Security Info=True;User ID=xxxxxx;Password=xxxxx;providerName;System.Data.SqlClient"/>
  </appSettings>
</configuration>
0
SirReadAlot
Asked:
SirReadAlot
  • 16
  • 9
  • 7
  • +2
1 Solution
 
gjutrasCommented:
ConfigurationManager.AppSettings["DB_CONN_STRING"] instead of ConfigurationManager.ConnectionStrings["DB_CONN_STRING"].ConnectionString;
0
 
SirReadAlotAuthor Commented:
i will try this
0
 
gjutrasCommented:
and appSettings in web.config needs to be outside the config section
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
gjutrasCommented:
sorry I misread it, it needs to be in configuration section.  I glanced and thought it was in a configSection.
0
 
SirReadAlotAuthor Commented:
thanks, i tried that before so i got this error

System.InvalidOperationException: The ConnectionString property has not been initialized.
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
0
 
gjutrasCommented:
debug and step through it and see if the strConnectionString is getting set appropriately.
0
 
SirReadAlotAuthor Commented:
strConnectionString is null

what can i do?  is the connection wrong?
0
 
gjutrasCommented:
sorry my bad
System.Configuration.ConfigurationSettings.AppSettings[]
is the 1.1 method of accessing appsettings.  Give that a try.
0
 
SirReadAlotAuthor Commented:
this is 2.0
0
 
SirReadAlotAuthor Commented:
with this...........

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;

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


            String strConnectionString = System.Configuration.ConfigurationSettings.AppSettings["DB_CONN_STRING"];
            SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}


i got this

System.InvalidOperationException: The ConnectionString property has not been initialized.
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
0
 
YZlatCommented:
try replacing

String strConnectionString = ConfigurationManager.ConnectionStrings["DB_CONN_STRING"].ConnectionString;

with

String strConnectionString = ConfigurationSettings.AppSettings["DB_CONN_STRING"];
0
 
gjutrasCommented:
I should have seen it before
<add key="DB_CONN_STRING" value="Database=AD10MACEL;Data Source=FINANCESQL\FINANCE;Persist Security Info=True;User ID=xxxxxx;Password=xxxxx;"/>
because your using .net and sql provider you don't need them here.
0
 
YZlatCommented:
also try

strConnectionString = ConfigurationSettings.AppSettings.Get("DB_CONN_STRING");

or

string strConnectionString = ConfigurationSettings.AppSettings["DB_CONN_STRING"].ToString();
0
 
SirReadAlotAuthor Commented:
hi, i don't need what
I should have seen it before
<add key="DB_CONN_STRING" value="Database=AD10MACEL;Data Source=FINANCESQL\FINANCE;Persist Security Info=True;User ID=xxxxxx;Password=xxxxx;"/>
because your using .net and sql provider you don't need them here.


0
 
SirReadAlotAuthor Commented:
does anyone know what to do
0
 
gjutrasCommented:
did you try changing the value of your connection string in your web.config?
0
 
Snarf0001Commented:
The same code works perfectly fine for me, so let's verify basics:
SInce this is a console app, you do have your configuration file named "app.config", not "web.config", right?
0
 
SirReadAlotAuthor Commented:
called it  app.config
0
 
Mihai StancescuSoftware Engineer Commented:
You can try this String strConnectionString =  Settings.Default.DB_CONN_STRING;



Hope this helps!

Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
HI,  i got this now----

The type or namespace name 'Settings' does not exist in the namespace 'System' (are you missing an assembly reference?)      


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

           // String strConnectionString = ConfigurationManager.ConnectionStrings["DB_CONN_STRING"].ConnectionString;
            String strConnectionString = Settings.Default.DB_CONN_STRING;
            SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
0
 
Mihai StancescuSoftware Engineer Commented:
You have to add the reference to your namespace.Settings
Or
After you type Settings a small line appears just like Word when capitalising the first word, or press Shift+Alt+F10 and there should be a menu with the first reference that you need.


Hope this helps!

Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
hi,

this is wht i have done
namespace DirectorySweeper.Settings.Default

but i get this

The type or namespace name 'DB_CONN_STRING' does not exist in the namespace 'DirectorySweeper.Settings.Default' (are you missing an assembly reference?)      
0
 
Mihai StancescuSoftware Engineer Commented:
Set there the exact Setting name instead of 'DB_CONN_STRING' that you use to store the connection string.


Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
i tried this

namespace DirectorySweeper.Settings.Default.appSettings

 <appSettings>
    <add key="DB_CONN_STRING" value="Database=xxxx;Data Source=xxx\xxx;User ID=rxxxral;Password=xxxx;"/>
  </appSettings>
0
 
Mihai StancescuSoftware Engineer Commented:
Then try this String strConnectionString = Settings.Default.appSettings.DB_CONN_STRING;



Hope this helps!

Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
thanks for your help, but still can't get past this

The type or namespace name 'appSettings' does not exist in the namespace 'DirectorySweeper.Settings.Default' (are you missing an assembly reference?)      


namespace DirectorySweeper.Settings.Default.appSetting
{
    class Program
    {
        static void Main(string[] args)
        {

       
             String strConnectionString = Settings.Default.appSettings.DB_CONN_STRING;
             SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
0
 
Mihai StancescuSoftware Engineer Commented:
DirectorySweeper.Settings.Default.appSetting is the name of your namespace?

If it does then it's like this :
using DirectorySweeper.Settings.Default.appSetting;

namespace DirectorySweeper.Settings.Default.appSetting
{
    class Program
    {
        static void Main(string[] args)
        {

       
             String strConnectionString = Settings.Default.DB_CONN_STRING;
             SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

You must provide in the using clause the exact namespace that is using the current configuration settings, afterwards you can use the Settings (Class) : Settings.Defaul.DB_CONN_STRING

Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
I have trie dthis

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using DirectorySweeper.Settings.Default.appSettings;

namespace DirectorySweeper.Settings.Default.appSettings
{
    class Program
    {
        static void Main(string[] args)
        {
                 
            String strConnectionString = Settings.Default.appSettings.DB_CONN_STRING;
            SqlConnection conn = new SqlConnection(strConnectionString);
            try
            {
                conn.Open();
                Console.WriteLine("Connection Open Successfully");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
0
 
Mihai StancescuSoftware Engineer Commented:
And, it works?


What version of .NET framework do you use?

Mishu
0
 
SirReadAlotAuthor Commented:
using 2.0, and does not work
0
 
Mihai StancescuSoftware Engineer Commented:
Can you post the config file?
I'm interested only in the name of settings not values, to make a clear picture.

Thanks,
Mishu
0
 
SirReadAlotAuthor Commented:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DB_CONN_STRING" value="Database=XX;Data Source=XXX;User ID=XXX;Password=XXX;"/>
  </appSettings>
</configuration>


it is a console app. so i just created an xml file and those are its contents
0
 
Mihai StancescuSoftware Engineer Commented:
So you dindn't use Visual Studio to generate the application config?

If so you need to parse the xml file with an XmlReader.


Hope this helps,

Regards,
Mishu
0
 
SirReadAlotAuthor Commented:
ok,

thanks for your help
0
 
Mihai StancescuSoftware Engineer Commented:
No problem!

Glad I could help


The best,
Mishu
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 16
  • 9
  • 7
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now