Okay, first, I wanted to say a few things.
- Weather or not your connection string contains passwords: DO NOT EVER store your connection string in your code… …not even for just a moment! Even if what you are coding is a web part. In some companies this will lead to write ups and possible termination!
- You must guard the web.config file by giving this area special access because often times it will contain really critical passwords.
As you can tell from the above statements, that I have some experience things going wrong. I have lost my temper so many times regarding people hard coding their connection string in the source code because it often contains passwords and the passwords are linked to so many other areas. This is even bad if you have a source control system where once you change and remove the password from your code and do it the right way, it will still be in older versions of your code.
You can use .NET Reflector to decompile source code, and here is a sample of what it looks like:
I wanted to show you the right way to do this.
First navigate to your web config file…
C:\inetpub\wwwroot\wss\VirtualDirectories\<sp site name:port name>
Add your configurationstring in your appSettings location under its own key/value pair:
Add the following to your code to get connectionstring.
string connectionString = GetConnectoinString("YourDataConnectionStringKeyName");
private string GetConnectoinString(string key)
{
string connectionString = string.Empty;SPSite site = SPContext.Current.Site;
System.Configuration.Configuration
config = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name);
AppSettingsSection appSettings = config.AppSettings;connectionString = appSettings.Settings[key].Value;
return connectionString;
}
Additional security measures you can take is to encrypt your connection string, however I don’t really see the point because if a programmer wants your connectionstring they will get it via a unit test, or a breakpoint. So if you don’t want your connection string to become parent to the programmers, you will want to use a different username password in the production environment, and only the person who should know the password should also have exclusive access to the SP Server.
Hope this helps. I really am not a mean guy as I may have sounded above, however this is one of my major pet peeves.
Bill
Thank you very much …Awesome article …..
I disagree – only having one person with exclusive access to the SP server and password – is a disaster waiting to happen – a single point of failure is never an option is a large company – it’s ok for little itty-bitty companies.