Scenario: in ASP.NET application, in run-time force all SqlDataSource instances connecting to a specified data source.
The basic usage of SqlDataSource control assumes assigning values to ConnectionString and ProviderName in HTML part of Web Form or Web User Control.
<asp:SqlDataSource ID="Source1" runat="server" ConnectionString="<%? ConnectionString:MyDataSource %" ProviderName="<%$ ConnectionStrings:MyDataSource.ProviderName %>" SelectCommand="..." />
Both values can also be assigned in the code-behind.
In my case, user selects a data source on start of the web application, and may switch to another available data source during the session. Following a data source selection all SqlDataSource instances must use this and only this data source. The connection string is stored in session variable "ActiveDbConnection".
This scenario can be quickly realized by subclassing the SqlDataSource control.
Apparently you cannot subclass it from Web User Control because the latter must inherit from System.Web.UI.UserControl, and thus cannot inherit from SqlDataSource.
But you can create ASP.NET Server Control and then change its superclass from WebControl to SqlDataSource. Following that replace the default constructor. Зresuming the class name is CustomSqlDataSource the replacement be the following one
public CustomSqlDataSource()
{
ConnectionString =
HttpContext.Current
.Session["ActiveDbConnection"];
ProviderName = "System.Data.OleDb";
}
In HTML part all asp:SqlDataSource tags need to be replaced with asp:CustomSqlDataSource, and the namespace for the class to be registered. And also -- this is very important -- all ConnectionString and ProviderName attributes are to be removed. Otherwise the default constructor we just added will not be called.
<asp:CustomSqlDataSource ID="Source1" runat="server" SelectCommand="..." />
No comments:
Post a Comment