Thursday 14 June 2012

Add Connection String to webconfig.xml

You know you should never modify the webconfig.xml file manually, so lets talk about how to add a connection string through XML. Now keep in mind that this technique can be used to add or remove anything to your webconfig.

First thing you need to do is map the config folder to your project:
  • right click on your project in the solution explore
  • scroll over Add
  • Click on SharePoint Mapped Folder
The "Add SharePoint Mapped Folder" dialogue should pop up, select the config folder.
Once you click OK, the mapped folder should appear in your solution explorer

 
 With the CONFIG mapped folder press ctrl+shift+a to add a new item.
  • in the left hand pane select Data
  • in the middle pane select XML File
  • at the bottom make sure to name your file webconfig.*.xml; it is imperative that you follow this naming format. (webconfig.addConnections.xml)
Once you click the add button you will get an empty xml file to add webconfig modification to
 
add the following to your xml file

<actions>
  <add id ="{BE573280-EDD2-4E9D-9C53-2B943A118F63}" path = "configuration" >
    <connectionStrings />
  </add>
  
  <add id ="{6B92AB06-90B9-4464-BEF5-C0F5B14FABA6}" path = "configuration/connectionStrings" >
    <add name="ConnectionStringName" 
         connectionString="Data Source=myServer;Initial Catalog=INTERNET;User ID=userID;password=Password;" />
  </add>
</actions> 
 
Make sure to use unique id's for your actions otherwise you'll get multiple entries everytime you update your webconfig.
  1. With your XML ready to go, deploy the project.
  2. Once you've deployed your project successfully open up windows powershell (not the ISE) and run the command "stsadm -o copyappbincontent"
 

Presto, all should be well

But if it's not continue to read.

Should you get an error that says "expression must evaluate to a node-set"
that means that you didn't build the path correctly, notice:
first i add the connectionStrings element
  <add id ="{BE573280-EDD2-4E9D-9C53-2B943A118F63}" path = "configuration" >
    <connectionStrings />
  </add>
Second I add the connection string to the the connectionStrings element
  <add id ="{6B92AB06-90B9-4464-BEF5-C0F5B14FABA6}" path = "configuration/connectionStrings" >
    <add name="ConnectionStringName" 
         connectionString="Data Source=myServer;Initial Catalog=INTERNET;User ID=userID;password=Password;" />
  </add>
 
 Finnally if you see this
 
Somewhere there is a duplication, it doesn't necessarily have to be what you did, it could have been someone else breaking the number one law of webconfigs: Thou Shalt Not Manually Edit.