9 Replies - 19721 Views - Last Post: 24 January 2012 - 11:42 AM Rate Topic: -----

#1 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Modifying config during runtime

Posted 23 January 2012 - 08:33 AM

Hey,

The below code isnt working and i was hoping someone could explain why?
static void Main(string[] args)
        {
            string saveText = "Save this text in the config file";
            string resultCall;
            Console.WriteLine("Enter the connection name");

            resultCall = ConfigurationManager.AppSettings["ApplicationTitle"];
            resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString = saveText;
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
        }



The odd thing is the following code does work
static void Main(string[] args)
        {
            string saveText = "Save this text in the config file";
            string resultCall;
            Console.WriteLine("Enter the connection name");

            resultCall = ConfigurationManager.AppSettings["ApplicationTitle"];
            resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            saveText = config.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
        }



Any help would be appreciated

Is This A Good Question/Topic? 0
  • +

Replies To: Modifying config during runtime

#2 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Modifying config during runtime

Posted 23 January 2012 - 09:49 AM

Update: I modified it to the write the ConnectionString into a new string variable and it does save the new string yet the config files doesnt show these changes. Does anyone knwo why this happens? I havent built anything, im just running it in debug atm
Was This Post Helpful? 0
  • +
  • -

#3 RexGrammer   User is offline

  • Coding Dynamo
  • member icon

Reputation: 183
  • View blog
  • Posts: 785
  • Joined: 27-October 11

Re: Modifying config during runtime

Posted 23 January 2012 - 11:48 AM

Some links that will help you:

Modifying Configuration Settings at Runtime
C#: Modify App.config file at run time

NOTE: The main problem is that it doesn't work while debugging. Try to build the release version and run it outside VS. See the result. ;)

This post has been edited by RexGrammer: 23 January 2012 - 11:50 AM

Was This Post Helpful? 1
  • +
  • -

#4 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Modifying config during runtime

Posted 24 January 2012 - 03:33 AM

Morning.
I tried to build the release version but it throws an exception after the first writeline. Could someone have a look at the following code and point out where ive made a mistake?

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Xml;


namespace ProjectAppConfig
{
    class Program
    {
        static void Main(string[] args)
        {
            string saveText = "Save this text in the config file";
            string resultCall;
            Console.WriteLine("Enter the connection name");

//throws error here. Doesnt  throw error in debug mode.

            resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            Console.WriteLine(resultCall);
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString = saveText;
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
            resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            Console.WriteLine("result call is equal to: {0}", resultCall);
        }
    }
}



config file is as follows
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>


    <add name="Test" connectionString ="testing 123"/>


    <add name="ConnectionString" connectionString ="Server = OPHIUCHUS; Database = AutoLot;
                User ID = InitialConnection; Password = InitialConnection;
                Trusted_Connection = False"/>


  </connectionStrings>

</configuration>



i tried building the solution into the release folder. Ive physically copied the app.config file into that folder since it wasnt there after the build....

any help would be appreciated.
Was This Post Helpful? 0
  • +
  • -

#5 RexGrammer   User is offline

  • Coding Dynamo
  • member icon

Reputation: 183
  • View blog
  • Posts: 785
  • Joined: 27-October 11

Re: Modifying config during runtime

Posted 24 January 2012 - 04:40 AM

What's the error?

Did I understand you: the program crashes at this line
Console.WriteLine("Enter the connection name");


?

Then it has nothing to do with your code. It's something else. (That is if it crashes on that line.)
Was This Post Helpful? 1
  • +
  • -

#6 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Modifying config during runtime

Posted 24 January 2012 - 04:46 AM

Nah its just after that line. ie that line gets printed on the console but then no other lines get written to the console window.

Im in the process of testing a winforms project using the same code to see if its the code or something to do with it being a console app.

[Question] will setup->add->Project Output-> Primary output contain a config file as well?
Was This Post Helpful? 0
  • +
  • -

#7 RexGrammer   User is offline

  • Coding Dynamo
  • member icon

Reputation: 183
  • View blog
  • Posts: 785
  • Joined: 27-October 11

Re: Modifying config during runtime

Posted 24 January 2012 - 04:51 AM

What's the error? And on what line exactly does it crash?

Add a try{} catch{} statement for this part of your code:
try
{
resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
Console.WriteLine(resultCall);
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString = saveText;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
resultCall = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
Console.WriteLine("result call is equal to: {0}", resultCall);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}



Then tell me what's the error and on what line does it crash... ;)
Was This Post Helpful? 1
  • +
  • -

#8 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Modifying config during runtime

Posted 24 January 2012 - 05:20 AM

Posted Image

Thats a screen shot of it running outside of visual studio. I get no exception message. When i remove the try-catch block, i get a "Visual Studio JIT Debugger" with text saying "An unhandled Microsoft .NET Framework exception occured in ProjectModifyCONFIG.exe [5420]."

then it asks me to pick a debugger. No source Available is the title in VS and there is an error box in the centre saying NullReferenceException was unhandled.


I have just finished messing with the WinForms example i wrote and it works there. One question though, why does the config file look so different after running it? I only asked it to add "Additional Text" to the connection String.

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

  <appSettings>
    <add key="ApplicationTitle" value="Sample Console Application" />
    <add key="ConnectionString"
         value="Server=localhost;Database=Northwind;Integrated
                  Security=false;User Id=sa;Password=;" />


  </appSettings>

  <connectionStrings>


    <add name="Test" connectionString ="testing 123"/>


    <add name="ConnectionString" connectionString ="Server = OPHIUCHUS; Database = AutoLot;
                User ID = InitialConnection; Password = InitialConnection;
                Trusted_Connection = False"/>


  </connectionStrings>

</configuration>



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

  <configProtectedData />
  <system.diagnostics />
  <system.windows.forms />
  <uri />
  <appSettings>
    <add key="ApplicationTitle" value="Sample Console Application" />
    <add key="ConnectionString" value="Server=localhost;Database=Northwind;Integrated&#xD;&#xA;                  Security=false;User Id=sa;Password=;" />
  </appSettings>

  <connectionStrings>
    <add name="Test" connectionString="testing 123" />
    <add name="ConnectionString" connectionString="Server = OPHIUCHUS; Database = AutoLot;&#xD;&#xA;                User ID = InitialConnection; Password = InitialConnection;&#xD;&#xA;                Trusted_Connection = False ADDITIONAL TEXT" />
  </connectionStrings>

  <system.net>
    <authenticationModules />
    <connectionManagement />
    <defaultProxy />
    <requestCaching />
    <settings />
    <webRequestModules />
    <mailSettings>
      <smtp />
    </mailSettings>
  </system.net>
  <system.runtime.caching>
    <memoryCache />
  </system.runtime.caching>
  <system.runtime.serialization>
    <dataContractSerializer />
  </system.runtime.serialization>
  <system.serviceModel>
    <behaviors />
    <bindings />
    <client />
    <comContracts />
    <diagnostics />
    <extensions />
    <protocolMapping />
    <routing />
    <serviceHostingEnvironment />
    <services />
    <standardEndpoints />
    <tracking />
  </system.serviceModel>
  <system.serviceModel.activation>
    <diagnostics />
    <net.pipe />
    <net.tcp />
  </system.serviceModel.activation>
  <system.transactions>
    <defaultSettings />
  </system.transactions>
  <system.web>
    <anonymousIdentification />
    <authentication />
    <authorization />
    <clientTarget />
    <compilation />
    <customErrors />
    <deployment />
    <deviceFilters />
    <fullTrustAssemblies />
    <globalization />
    <healthMonitoring />
    <hostingEnvironment />
    <httpCookies />
    <httpHandlers />
    <httpModules />
    <httpRuntime />
    <identity />
    <machineKey />
    <membership />
    <mobileControls />
    <pages />
    <partialTrustVisibleAssemblies />
    <processModel />
    <profile />
    <protocols />
    <roleManager />
    <securityPolicy />
    <sessionPageState />
    <sessionState />
    <siteMap />
    <trace />
    <trust level="Full" />
    <urlMappings />
    <webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
    <webParts />
    <webServices />
    <xhtmlConformance />
    <caching>
      <cache />
      <outputCache />
      <outputCacheSettings />
      <sqlCacheDependency />
    </caching>
  </system.web>
  <system.web.extensions>
    <scripting>
      <scriptResourceHandler />
      <webServices>
        <authenticationService />
        <jsonSerialization />
        <profileService />
        <roleService />
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.xaml.hosting>
    <httpHandlers />
  </system.xaml.hosting>
  <system.xml.serialization>
    <dateTimeSerialization />
    <schemaImporterExtensions />
    <xmlSerializer />
  </system.xml.serialization>
</configuration>




Thanks again for your help Rex

This post has been edited by scolty: 24 January 2012 - 05:21 AM

Was This Post Helpful? 0
  • +
  • -

#9 scolty   User is offline

  • D.I.C Regular

Reputation: 3
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Modifying config during runtime

Posted 24 January 2012 - 05:33 AM

And do you know why the database field in the config file went from
...database = AutoLot;



to

Database = AutoLot;&#xD;&#xA;


Was This Post Helpful? 0
  • +
  • -

#10 RexGrammer   User is offline

  • Coding Dynamo
  • member icon

Reputation: 183
  • View blog
  • Posts: 785
  • Joined: 27-October 11

Re: Modifying config during runtime

Posted 24 January 2012 - 11:42 AM

Did a quick google about it, and it seems that this is the replacement for carriage return and line feed characters.

My Google
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1