Question

Connectionstring in app.config

Asked by: johny_bravo1

Hi Experts,
I have created a Outlook Shared Add-in.I am creating coneection to my sql database.
I am able to create connection but how to store it in a config file and access the connectionstring from there?
Currently I am trying below code but it is throwing an exception.

<configuration>	
  <appSettings>
     <add key="ConnectionString" value="Data Source=192.168.40.46;Initial Catalog=Spot;Persist Security Info=True;User ID=sa;Password=sqlad;Min Pool Size=05;Max Pool Size=160;Connection Timeout = 250" />
</appSettings>
</configuration>
 
 string connectionstr = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
                SqlConnection PacktSQLConnection = new SqlConnection(connectionstr);

                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-13 at 04:25:05ID24316859
Tags

.Net

,

C#

,

Outlook

Topics

.NET Framework 3.x versions

,

.NET Framework 2.x

,

Microsoft Visual C#.Net

Participating Experts
3
Points
500
Comments
38

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Store SQL Query in App.Config
    I'm trying to store a long sql query in my app.config file. I'm not worried about security, more about being open about what we're querying for and making the query easy to update. With the first iteration of my query, it worked fine. The second iteration isn't working so...
  2. non-traditional App.config needed
    Hi, I am deploying an assembly that is configured at runtime from an app.config file. The app.config file is named after the entry point EXE like: myexe.exe.config I would like to do away with the current config file and either embed the config file as an embeded resource...
  3. Writing to app.config
    Hi experts, I used this resource http://ryanfarley.com/blog/archive/2004/07/13/879.aspx (now in vb.net) to write to my app.config at runtime. so far there are no errors only that the app.config file is not updated at runtime. here is the code ===============================...
  4. app.config manipulation across projects.
    I have a Visual Basic Solution with two projects, a Windows Service (DiskService) and a Windows Application (DiskServiceConfig). I am using the app.config file in the Windows Service for a few custom settings such as SMTP server to send email and a few integers. What I am t...
  5. How to access app.config file in class library type project?
    I have created Add-In project for outlook in .Net 3.5 using Shared Add In project. This project downloads attachments from selected mail in outlook and save it in our database. I want to store connection string for Sql Server and physical path to the folder where I want to...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: MrClyfarPosted on 2009-04-13 at 04:31:33ID: 24129025

Hi there.

Try this instead.

Cheers.
Jas.

Imports System.Configuration
 
Module Module1
 
    Sub Main()
        Console.WriteLine("Connection string = {0}", ConfigurationManager.ConnectionStrings("MyConnection"))
    End Sub
 
End Module
 
App Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" 
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>
 
  <connectionStrings>
    <add name="MyConnection" connectionString="this is a test"/>
  </connectionStrings>
</configuration>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:

Select allOpen in new window

 

by: johny_bravo1Posted on 2009-04-13 at 04:32:23ID: 24129030

In the line
string connectionstr = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;

that ConnectionString1 is ConnectionString.

And the Exception I am getting is
"Object Reference Not set to an instance of the object"

 

by: johny_bravo1Posted on 2009-04-13 at 04:38:01ID: 24129052

I  tried changing this,
string connectionstr = ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString();

But still getting same exception.

 

by: gauthampjPosted on 2009-04-13 at 04:50:16ID: 24129098

string connectionstr = ConfigurationManager.ConnectionString.["MyConnection"].ConnectionString;

<configuration>
  <connectionStrings>
    <add name="MyConnection" connectionString="this is a test"/>
  </connectionStrings>
</configuration>
                                              
1:
2:
3:
4:
5:

Select allOpen in new window

 

by: johny_bravo1Posted on 2009-04-13 at 04:57:28ID: 24129123

Thanks gauthampj, it works in normal application but in shared add-in where all my code is in Connect.cs file
I am still getting the same exception.What could be the reason?

 

by: T0niPosted on 2009-04-13 at 04:58:08ID: 24129125

Hi johny_bravo1,
I don't think that is the best way to go with storing connection strings, a safer way would be to hard code the connection string.

Here is the code to do it, just create a static class and call it whenever you need the connection string:

    static class Connection
    {
        public static SqlConnection conn()
        {
            return new SqlConnection("Data Source=192.168.40.46;Initial Catalog=Spot;Persist Security Info=True;User ID=sa;Password=sqlad;Min Pool Size=05;Max Pool Size=160;Connection Timeout = 250");
        }
    }
 
//To get the connection string from another class or form simply call it using the following line of code.
 
SqlConnection conn = Connection.conn();

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: MrClyfarPosted on 2009-04-13 at 04:59:55ID: 24129137

Hi there.

I just used the name 'MyConnectionString' in the code as an example, but to copy your code, you should rename this:

<configuration>
    <connectionStrings>
           <add name="MyConnection" connectionString="this is a test"/>
    </connectionStrings>
</configuration>

to this:


<configuration>
    <connectionStrings>
           <add name="ConnectionString" connectionString="Data Source=192.168.40.46;Initial Catalog=Spot;Persist Security Info=True;User ID=sa;Password=sqlad;Min Pool Size=05;Max Pool Size=160;Connection Timeout = 250"/>
    </connectionStrings>
</configuration>  

As per gauthampj's advice.

Cheers

Jas.

 

by: MrClyfarPosted on 2009-04-13 at 05:03:18ID: 24129148

Hi.

In response to t0ni's comment, the best way to store the connection string is to encrypt it in the config file. Here's a link that explains this:

http://www.4guysfromrolla.com/articles/021506-1.aspx

Having the connection string in the code is suicide unless the code is obfuscated, since using .NET Reflector would allow anyone to view the code for the app and get the connection string details.

Also storing the connection string in the app.config file unencrypted is risky, since anyone can open the file in the Notepad and have a look.

Cheers.
Jas.

 

by: johny_bravo1Posted on 2009-04-13 at 05:04:22ID: 24129152

Thanks MrClyfar,
it's working in other applications but not here.

 

by: T0niPosted on 2009-04-13 at 05:06:39ID: 24129168

That's right MrClyfar, I didn't mean to say it's the best way to store sensitive data, but it's by far safer than storing in config file unencrypted.

 

by: gauthampjPosted on 2009-04-13 at 05:14:10ID: 24129194

can u try this

<configuration>	
  <appSettings>
     <add key="ConnectionString" value="Data Source=192.168.40.46;Initial Catalog=Spot;Persist Security Info=True;User ID=sa;Password=sqlad;Min Pool Size=05;Max Pool Size=160;Connection Timeout = 250" />
</appSettings>
</configuration>
 
string connectionstr = ConfigurationSettings.AppSettings["ConnectionString1"];
                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: johny_bravo1Posted on 2009-04-13 at 05:14:59ID: 24129200

I just need to clear this again that I am developing a Shared add-in and I am still not able to read values any value from app.config.
It's working getting it through class but I need to get it from config file.

 

by: johny_bravo1Posted on 2009-04-13 at 05:15:43ID: 24129204

Thanks gauthampj, already tried with it.

 

by: gauthampjPosted on 2009-04-13 at 05:19:38ID: 24129224

how are u testing the add in ?  are u installing it with a installer package ? if the app.config file is copied to the insatall directore i think it shud work no matter what

 

by: MrClyfarPosted on 2009-04-13 at 05:27:13ID: 24129256

Hi there.

The app.config way of reading the config should work, if it;s not, then I also think that the app.config is in the wrong folder and your code cannot find it.

One other way to get around this is to put your connection string in the machine.config file. I have to go now, but here is a link that explains how to use machine.config:

http://msdn.microsoft.com/en-us/library/ms229697.aspx

http://forums.asp.net/p/1117776/1736929.aspx

Cheers.
Jas.

 

by: johny_bravo1Posted on 2009-04-13 at 06:00:07ID: 24129430

Yes te app.config was not installed on the machine when I set up installer package.
Now I added app.config to setup folder.
But still the error is there?

 

by: gauthampjPosted on 2009-04-13 at 06:07:06ID: 24129475

name shud be urdllname.config not app.config

 

by: johny_bravo1Posted on 2009-04-13 at 06:14:30ID: 24129529

You mean where my dll is copied there shud b urdllname.config file instead of app.config

 

by: gauthampjPosted on 2009-04-13 at 06:18:07ID: 24129555

s..

 

by: johny_bravo1Posted on 2009-04-13 at 06:23:46ID: 24129594

I renamed app.config as urdllname and copied it physically to installation folder but it is still throwing exception

 

by: gauthampjPosted on 2009-04-13 at 06:29:20ID: 24129634

:-( wierd..what is the name of the ur dll/project  and that of the  app config file ?

 

by: johny_bravo1Posted on 2009-04-13 at 06:34:53ID: 24129663

it is 'TestAddIn" and now as u said config is TestAddin.config

 

by: johny_bravo1Posted on 2009-04-13 at 06:47:13ID: 24129754

any  other idea?

 

by: gauthampjPosted on 2009-04-13 at 07:21:19ID: 24129982

no idea what going on. it seems that u wont be able to read from app config from an add in. u can use this class which can be used instead of the configuration amanger to read values from a xml config file.

public class ConfigurationSettings
{
 
  public static NameValueCollection AppSettings;
 
  public static void LoadConfig()
  { 
    try
    {
 
        string AppPath = Path.GetDirectoryName( Assembly.GetExecutingAssembly().GetName().CodeBase);
        string ConfigFile = Path.Combine(AppPath,"App.config");
 
        if(File.Exists(ConfigFile) == false)
        {
          System.Windows.Forms.MessageBox.Show("Config file does not exist");
          Application.Exit(); 
          return;
        }
				 
        XmlDocument oXml = new XmlDocument();
 
        oXml.Load(ConfigFile);
				
        XmlNodeList oList =  oXml.GetElementsByTagName("appSettings"); 
 
        AppSettings = new NameValueCollection();
 
        foreach(XmlNode oNode in oList)
        {
           foreach(XmlNode oKey in oNode.ChildNodes)
           {
              AppSettings.Add(oKey.Attributes["key"].Value, oKey.Attributes["value"].Value);
           }
        }
 
        System.Windows.Forms.MessageBox.Show(ConfigurationSettings.AppSettings["Item1"]);  
 
    }
    catch (Exception) { throw; }
  }
 
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

Select allOpen in new window

 

by: johny_bravo1Posted on 2009-04-14 at 05:06:59ID: 24137227

what is the best way of putting connectionstring when I will install that add-in on client machine?

 

by: gauthampjPosted on 2009-04-14 at 05:11:47ID: 24137256

u can store as an encrypted string in the app.config file or in a registry value; if u are going to use app.config file then u will have to use the class i posted above to read the values

 

by: johny_bravo1Posted on 2009-04-14 at 05:56:58ID: 24137602

I have created a new class named ConfigurationSettings.
I have made little modification to it.
as my app.config looks like
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <connectionStrings>
            <add name="MyConnection" connectionString="coneection to database"/>

      </connectionStrings>
</configuration>
Now what next?

using System;
using System.Collections.Generic;
using System.Text;
 
namespace TestAddin
{
    public class ConfigurationSettings
    {
        public static NameValueCollection AppSettings;
 
        public static void LoadConfig()
        {
            try
            {
 
                string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                string ConfigFile = Path.Combine(AppPath, "App.config");
 
                if (File.Exists(ConfigFile) == false)
                {
                    System.Windows.Forms.MessageBox.Show("Config file does not exist");
                    Application.Exit();
                    return;
                }
 
                XmlDocument oXml = new XmlDocument();
 
                oXml.Load(ConfigFile);
 
                XmlNodeList oList = oXml.GetElementsByTagName("connectionStrings");
 
                AppSettings = new NameValueCollection();
 
                foreach (XmlNode oNode in oList)
                {
                    foreach (XmlNode oKey in oNode.ChildNodes)
                    {
                        AppSettings.Add(oKey.Attributes["name"].Value, oKey.Attributes["connectionString"].Value);
                    }
                }
 
                System.Windows.Forms.MessageBox.Show(ConfigurationSettings.AppSettings["Item1"]);
 
            }
            catch (Exception) { throw; }
        }
 
 
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:

Select allOpen in new window

 

by: gauthampjPosted on 2009-04-14 at 06:02:06ID: 24137652

u can access the information in app.config as ConfigurationSettings.AppSettings ["MyConnection"]; the file name of the app config file shud be "urdllName.dll.App.config"

 

by: johny_bravo1Posted on 2009-04-14 at 06:11:41ID: 24137729

Ok according to you I just need to implement that class exactly as it is.Create a config file with my dllname.dll.App.Config
and access the Appsetting in code.
That's it.

 

by: gauthampjPosted on 2009-04-14 at 06:17:58ID: 24137788

s use this to access the conection string -> TestAddin.ConfigurationSettings.AppSettings["MyConnection"]

 

by: johny_bravo1Posted on 2009-04-14 at 06:19:19ID: 24137803

I will work on it tomorrow and inform you about it.
Let me know if I need to know something to get it work.
Thanks.Have a nice day :)

 

by: johny_bravo1Posted on 2009-04-15 at 02:48:41ID: 24146174

In ur class code I am getting error for 'Path' and 'Assembly'

 

by: gauthampjPosted on 2009-04-15 at 06:24:07ID: 24147664

what is the error ?

 

by: johny_bravo1Posted on 2009-04-15 at 06:33:21ID: 24147752

'Path' / 'Assembly' does not exist in current context

 

by: johny_bravo1Posted on 2009-04-15 at 06:38:31ID: 24147798

ok that error is resolved now.let me try after installing it.
The config file should be named as mydllname.dll.App.config.Right?

 

by: johny_bravo1Posted on 2009-04-15 at 06:54:25ID: 24147951

I chaged my app.config file to TestAddin.dll.App.config and set its properties Build Action=Compile,
Copy To Output Directory=Always.
Now it is throwing error for it.
A namespace doesnot directly contain members such as fields or methods.
:(

 

by: gauthampjPosted on 2009-04-15 at 07:28:11ID: 24148350

build action shud be content

 

by: johny_bravo1Posted on 2009-04-16 at 01:28:34ID: 24155457

Ya tha's done now but still it's not working.
I don't understand what I am doing wrong?but still I m getting the same exception 'Object reference not set for instance of the object'.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...