Tag Archives: web.config

Different ways for setting Connection Strings in Asp.net / Various ways to use Connection Strings

There are various ways to declare and use connections strings like Web.config file, Application variables,Hardcoded strings, components etc.

There are many ways where we can keep the connection strings in web.config file , as it is completely safe.One cant access the web.config file by request from fronend/browser.It is been avoided using IIS.But there can be the case that if the user gets the direct access to Server and can able to see the files and more info.In this case we can use Encryption & descryption facility provided by .Net.

1) First of all & simple is use Connection string using in Web.config we can access the same in code behind C# as follows

string conn = ConfigurationManager.ConnectionStrings[“ConnectionString”].ConnectionString;

quite easy to use !!!!

2) we can also store connectionstrings into .you need to add an AppSettings section, like this one:we can access the same in code behind C# as follows
string connstring = ConfigurationManager.AppSettings[“ConnectionString”];

3) You can keep Connection Settings in web.config file with the protection of Encryption & descryption of particular sections.Then read it in your program and decrypt it before Editing. Check out the encryption/decryption APIs in .net.
e.g. IF we want to encrpt “connectionStrings> section then do the following/write following at command prompt of visual studio-
aspnet_regiis -pe “connectionStrings” -app “/YourApplicationName

The -pe option and the string “connectionStrings” to encrypt the connectionStrings element of the Web.config file for your application.
The -app option and the name of your application.

open web.config then and check the encryption completed !!!

For decryption of the same file
aspnet_regiis -pd “connectionStrings” -app “/YourApplicationName
Detail Reference

4) If we are having multiple connection strings then we can declare them in web.config and for accessing them easily & securily we can create one static class file in App_Code folder. I am explaining it with one sample example.

In the Web.Config –
<connectionStrings>

<add name=”NewConnectionString” connectionString=”Data Source=TestSource;Persist Security Info=True;User ID=username;Password=password;” providerName=”your data provider”/>
</connectionStrings>

Static Class file under App_Code e.g. ConnectionSettings.cs –

public static class ConnectionSettings
{
public static string ConnectionString
{
get
{

// code for accessing the connection string from web.config we can do it directly or using any other method //depends upon needs
string conn = ConfigurationManager.ConnectionStrings[“ConnectionString”].ConnectionString;

return conn;
}
}

}

Then we can able to access connection string settings as ConnectionSettings.ConnectionString

5) we can also read the connection string in Global.asax and store it in a applictaion level variable. and then we can read connection string from application variable so accessing web.config multiple times while accessing DB can be avoided.
Detail Reference

6)Also Last but not least I read recently that we can also create Dll with all Data Connection and run dotfuscator for more security if we are going to put connection settings part at client side.

There can be many more ways to use it …

Advertisements

Web.config – New in Asp.net 2.0 / New additions in .Net 2.0

There are many changes done at web.config in .Net 2.0 compared to  .Net 1x, I am listing few of them which I encountered while working … There may be some more I may have missed !!!!

1)   pageBaseType –  We can enable all the page will inherit from particular base page other than system.web , but this will work only for Page-Inline model not for Code-Behind model

<system.web>

<pages pageBaseType=”MyWeb.UI.MyPageBase” />

</system.web>

Now all pages in site will inherit from MyWeb.UI.MyPageBase, unless otherwise specified,and we don’t have to change the base class on every page created in the web app

2) <Imports> – If you want to import the same set of namespaces on every page, you just add them to an Imports sections under the pages.
<system.web>
<pages>
<imports>
<add namespace=”MyWeb.UI” />
</imports>
</pages>
</system.web>

3)  Also In ASP.NET 2.0 you can now add default namespaces into your web.Config files like this: –
<system.web>
<pages>
<namespaces>
<add namespace =”System.IO” />
<add namespace=”System.Text”/>
</namespaces>
</pages>
</system.web>

4)  Also we can add reference to Controls.

<system.web>
<pages>
<controls>
<add tagPrefix=”CC1″ namespace=”AjaxControlToolkit” assembly=”AjaxControlToolkit” />
</controls>
</pages>
</configuration>
</system.web>

and we can use the same in aspx as follows
<html>
<body>
<form id=”form1″ runat=”server”>
<cc1:CalendarExtender ID=”CalendarExtender1″ Animated=”true” Enabled=”true” Format=”MM/dd/yyyy”
runat=”server” TargetControlID=”txtDate”>
</cc1:CalendarExtender>
</form>
</body>
</html>
5)  Same is available for Custom controls/UserControls as follows.
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix=”userControls” src=”~/Controls/Menus.ascx” tagName=”menu”/>
</controls>
</pages>
</system.web>
</configuration>

and we can use above as follows
<html>
<body>
<form id=”form1″ runat=”server”>
<userControls:menu ID=”Menu1″ runat=”server” />
</form>
</body>
</html>

Also there is also more tag “registerTagPrefixes” used for the same but I am not sure about this tag. havnt used this much ,Lately I heard that it is removed

from during beta to final version.

<registerTagPrefixes>
<add tagPrefix=”CC1″ namespace=”ControlNameSpace” />
</registerTagPrefixes>
6)  In 2.0 we can also modify the web.config file using the Website Administration tool. In this we can do changes on following level
Security,Application,Provider,Internals etc.

7)  <connectionStrings> is newly added in 2.o prior to that we used to store Connection string infor under <appSettings> as key.
<connectionStrings>
<add name=”LocalSqlServer” connectionString=”data source=.\SQLEXPRESS;Integrated Security=SSPI;User                 Instance=true” providerName=”System.Data.SqlClient”/>
</connectionStrings>

ConnectionStrings can be read from Code Behind as following
string conn = ConfigurationManager.ConnectionStrings[“name”].ConnectionString;

8)  <pages> which is the new section added in .net 2.0 , using this we can set global theme or Stylesheet for the same.
<configuration>
<system.web>
<pages theme=”Default” />
</system.web>
</configuration>
or
<configuration>
<system.web>
<pages StyleSheetTheme=”Default” />
</system.web>
</configuration>

9)  <compilation> – Configures all compilation settings that ASP.NET uses to compile applications.
<compilation
debug=”[true|false]”
batch=”[true|false]”
batchTimeout=”number of seconds”
defaultLanguage=”language”
explicit=”[true|false]”
maxBatchSize=”maximim number of pages”
maxBatchGeneratedFileSize=”maximum combined size”
numRecompilesBeforeAppRestart=”number”
strict=”[true|false]”
tempDirectory=”temporary files directory”
urlLinePragmas=”[true|false]”
assemblyPostProcessorType=”assembly post processor, assembly” >
<assemblies>…</assemblies>
<buildproviders>…</buildproviders>
<codeSubDirectories>…</codeSubDirectories>
<compilers>…</compilers>
<expressionBuilders>…</expressionBuilders>
</compilation>

check MSDN for details

10) <Caching> – This new section is provided to facilitate global cache settings of the web application.
Under caching we are having 4 sections <cache> ,<outputCache>,<outputCacheSettings>,<sqlCacheDependency>

If some one who worked on caching worked using ASP.NET 1.0,must agree with me that managing cache directions for all your pages could some time headache. Here ASP.NET 2.0 introduces Cache Profiles that helps us centrally manage cache. In ASP.NET 2.0, you can define what are called cache profiles. which  allows us to create named sets of settings which are defined in web.config file. Cache settings can be inherited by pages, and overridden if required by using the OutputCache directive.

The page directive looks pretty much the same, expect this time it references a cache profile that you defined in your web.config file.

in aspx page

<%@ Page Language=”C#” %>
<%@ OutputCache CacheProfile=”TestCacheProfile” VaryByParam=”none” %>

in web.config

<?xml version=”1.0″?>
<configuration>
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name=”TestCacheProfile” duration=”60″ />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
</configuration>

11)  Using web.config we can configure application for Role Management, for that <roleManager>  is provided.
Using role manager the task of managing roles and performing role-based authorization in your application become much easier.
Using Role Manager we can configure the 3 different role providers for use with your Web application,create new roles, add a user to a role, and  use the role management API for roles-based authorization.

3 types of role providers are supported by 2.0
SqlRoleProvider, WindowsTokenRoleProvider, AuthorizationStoreRoleProvider

<system.web>
<roleManager enabled=”true” />
<rpoviders>
</providers>
</system.web>

12)  HTTP-only cookies – HTTP-only is a flag that you can append to cookies and helps to reduce harvesting attacks  on authentication or session cookies.  HTTP-only is a property that can be set on the HttpCookie class in .net 2.0

By default .NET 2.0 sets the HTTPOnly attribute for Session ID ,Forms Authentication cookie

In Web.config
<system.web>
<httpCookies httpOnlyCookies=”true”>
</system.web>

HTTPOnly can also be set via the HttpCookie object for all custom application cookies programatically
HttpCookie TestCookie = new HttpCookie(“TestCookie”);
TestCookie.HttpOnly = true;
Response.AppendCookie(TestCookie);

In 1.0 previously System.Net.Cookie class does not support the HttpOnly property so it used to accomplied following way.
Response.Cookies[cookie].Path += “;HTTPOnly”;

13)   New Attributes in Web.config for tracing  – “writeToDiagnosticsTrace” & “mostRecent”
writeToDiagnosticsTrace –
There are two types of tracing available in .NET Framework. One is httpcontext.trace class which is used to write trace messages in asp.net.  Second is system.diagonstics.trace class used in other components to write trace messages.
Httpcontext.trace is controlled by trace settings in config file,  but diagnostics.trace class is controlled by debug compilation code while compiling any dll in .NET
For forwarding httpcontext.trace class trace messages to diagnostics.trace class listeners,  we need to set new attribute “writeToDiagnosticsTrace” in the trace section in .config file like this,

<trace enabled=”true” pageOutput=”true” localOnly=”true” writeToDiagnosticsTrace =”true”/>

mostRecent – New attribute “mostRecent” is introduced in Trace configuration settings in  web.config file for specifying which trace messages to keep in the trace store if the requestLimit value exceeds.
In ASP.NET 1.x, if the requestLimit exceeds, it will stop collecting trace messages in trace store unless until you clear trace store or restart that application appdomain. Now When you set this attribute value to true and if the requestLimit values exceeds, Trace store will keep the most recent trace messages in the store and old message are discarded.
If you set this attribute value to false, trace store will stop collecting trace message once its requestLimit value exceeds.

<trace enabled=”false” localOnly=”true”
mostRecent=”true”  pageOutput=”false”
requestLimit=”10″  traceMode=”SortByTime” />

Ref – Extreme Experts

14) New attribute named descryption is added for element <machineKey> element in version 2.0,specifies the symmetric encryption algorithm used to encrypt and decrypt forms authentication tickets you can more on MSDN – http://msdn.microsoft.com/en-us/library/ms998288.aspx

15) New attributes are added for FormsAuthentication                                                                                                                      cookieless – supports cookieless forms authentication.                                                                                                                      defaultURL – This will redirect to specified url if no redirect URL is specified.                                                                                domain – property indicates the domain with which the cookie is associated with default value is null.

enableCrossAppRedirects – true/false – values indicate automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

Ref –  MSDN