ASP.NET MVC 2, re-use of SQL-Connection string - asp.net

so I'm very very far from an expert on MVC or ASP.NET. I just want to make a few simple Controllers in C# at the moment, so I have the following question;
Right now I have the connection string used by the controller, -inside- the controller itself. Which is kind of silly when there are multiple controllers using the same string. I'd like to be able to change the connection string in just one place and have it affect all controllers.
Not knowing a lot about asp.net or the 'm' and 'v' part of MVC, what would be the best (and simplest) way of going about accomplishing just this?
I'd appreciate any input on this, examples would be great too.

Put it in your web.config file like so:
<connectionStrings>
<add name="ConnectionName" connectionString="TheConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
<connectionStrings> is just a child of the root <configuration> element.
Then you can read it like:
string myConnStr = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
HTHs,
Charles

You may add a connection string to the web.config file like this:
<configuration>
<appSettings>
<add key="ConnectionString"
value="server=localhost;database=Northwind;uid=sa;password=secret;"/>
</appSettings>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
and use it in your code like this:
strConnection = ConfigurationSettings.AppSettings("ConnectionString") // <-----
sqlConn = New SqlConnection(strConnection)
sqlCmd = New SqlCommand("SELECT * FROM Customers WHERE " & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn)
Notice the first line. This example is for VB but you should be able to do the same in C#.
The example is taken from this link http://www.dotnetjohn.com/articles.aspx?articleid=3, but there are tons of them everywhere.
Hope this helps.

Related

Easy way to secure connectionstring

So i remember that my teacher once taught us how to secure connectionstrings in web.config.
Unfortunately, now when i need to know it, i have forgotten all about it.
I have been looking around in here, and found some different questions regarding this, where all of which seemed to have a slightly complicated solution.
Im asking, because i remember that my teacher secured his password in the connectionstring with just a few signs/glyphs, instead of encrypting the entire string.
So my question is obviously how i can secure (doesn't have to be very strong) my connectionstring in one easy way.
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
For all above, thanks to Oscar Rivera answer as well. Hope this helps!

Split appSettings into multiple sections / files?

Can I split appSettings into multiple external config files and include them in main web.config?
Here is what I have tried, but its not working :(
In web.config I defined a new section:
<configSections>
<section name="ssoConfiguration" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
below I have this section:
<ssoConfiguration>
<add key="SSOEnabled" value="true"/>
</ssoConfiguration>
When I call System.Configuration.ConfigurationManager.AppSettings["SSOEnabled"] it returns null.
Any ideas why?
Also, I will have multiple sections with such appSettins - is it possible to define them in multiple external config files and get them included in main web.config?
Thank you.
Because you're accessing AppSettings, but the "SSOEnabled" setting is in another section ("ssoConfiguration"). Try
var ssoConfiguration = (NameValueCollection)ConfigurationManager.GetSection("ssoConfiguration")
var ssoEnabled = ssoConfiguration["SSOEnabled"];

How to read system value from web.config and use in ASP.NET MVC C# method

I'm working on a ASP.NET MVC3 web application (not written by me) which has a max upload size of 100MB. Now this web application gets installed on server machines for customers so it would be nice if this value max upload size was configurable for each customer. They have access to edit the web.config for the web application if need be.
Now there's a value in the web.config like so:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
Also there's another value here which appears to be similar:
<system.web>
<httpRuntime maxRequestLength="104857600" executionTimeout="360" />
</system.web>
That 104857600 bytes appears to be the 100MB file upload limit. However on changing the value I discovered that this isn't the authoritative value and it wasn't obeying the new limit. So after some more digging I found somewhere else in the C# code was a hardcoded value public const double MaxContentSize = 104857600 and another C# method was using that value to accept/deny the Ajax file upload.
So what I think I'd like to do is replace that hard coded number in the code so it reads from the value in the web.config. Then at least anyone can change that value in the web.config when they deploy the website.
Can you do something like this?
MaxContentSize = ConfigurationManager.systemWeb.httpRuntime['maxRequestLength'];
I've seen some examples using appSettings in the web.config e.g.
<appSettings><add key="MySetting" value="104857600" /></appSettings>
then accessing it like:
ConfigurationManager.AppSettings["MySetting"]
But that would mean adding a custom value in there and now we'd have 3 places to change it in the web.config. Anyone got an idea how to do it properly?
Many thanks
You can do something like:
int maxRequestLength = 0;
HttpRuntimeSection section =
ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section != null)
maxRequestLength = section.MaxRequestLength;
There seems to be no easy way to read the system.webServer section, because it is marked as "ignored" from machine.config.
One way is to parse the XML of the web.config file directly:
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
var section = config.GetSection("system.webServer");
var xml = section.SectionInformation.GetRawXml();
var doc = XDocument.Parse(xml);
var element = doc.Root.Element("security").Element("requestFiltering").Element("requestLimits");
string value = element.Attribute("maxAllowedContentLength").Value;
Try:
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/")
var section = (System.Web.Configuration.SystemWebSectionGroup)config.GetSectionGroup("system.web")
var maxRequestLength = section.HttpRuntime.MaxRequestLength

Is it possible to have an ampersand sign in an appSettings key? error: web.config value is not defined

I have the following appSettings section
<appSettings>
<add key="Foo" value="http://foo.bar.com/?app=xxx&FormName=yyy" />
</appSettings>
But the IDE is giving me two errors:
Error 25 Entity 'FormName' not defined.
Error 26 Expecting ';'.
It seems the & is causing a problem. I'd like to not have to splt the values up into seperate keys. Is there an elegant way around this issue?
You just need to use XML encoding here I believe - so & becomes &
Try &
<appSettings>
<add key="Foo" value="http://foo.bar.com/?app=xxx&FormName=yyy" />
</appSettings>

Retriving a setting in a Web.Config <configSections>

I have this code in my Web.Config file:
<configSections>
<section name="myWebAppSettings" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<myWebAppSettings isTestEnvironment="true"/>
I need retrieve my value isTestEviroment from Global.asax
At the moment I use with no sucess:
bool isTestEnvironment = ConfigurationManager.AppSettings.GetValues["isTestEnvironment"];
What I'm doing wrong here?
NOTES: I do not assume my Web.Config file is right so please feel free to change it if I did not written correctly. Thanks for your help on this!
ConfigurationManager.AppSettings retrieves values from the AppSettings configuration element, not your custom section.
You need to use:
var section = (HashTable)ConfigurationManager.GetSection("myWebAppSettings");
bool isTest = Boolean.Parse(section["isTestEnvironment"].ToString());

Resources