How would I bind a SqlDatasource ConnectionString property to a function

I am trying to set the ConnectionString property to the return value of a function in the ASPX page.

Example:

<asp:SqlDataSource runat="server" id="blah"
    ConnectionString="<%= ServerSensing.GetConnectionStringByServer("someKey"); %>"
    >
    ...
</asp:SqlDataSource>

The above is obviously not going to work.. so.. what will?

Preemptive remarks:
* No, I can not use the Web.config binding

you should be able to set it in your Page_Load, something like:

blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey");

or if you dont have access to the code behind put some inline code on the page, like just before the markup for the SqlDataSource

<%
     blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey");
%>

The best way I’ve found about this question is using Expression Builder in your solution.

With this feature you can create a custom inline expression and use it in the SqlDataSource tag.

You’ll find some examples right here:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

That’s how I implemented in my apps:


[ExpressionPrefix("RepConnectionString")]
public class RepConnectionStringExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression(base.GetType());

        CodePrimitiveExpression expression = new CodePrimitiveExpression(entry.Expression.Trim().ToString());

        string evaluationMethod = "GetConnectionString";

        return new CodeMethodInvokeExpression(thisType, evaluationMethod, new CodeExpression[] { expression });
    }

    public static string GetConnectionString(string expression)
    {
        XmlDocument xmlDoc = new XmlDocument();
        string wPath = HttpContext.Current.Server.MapPath("~/XmlFile.xml");
        xmlDoc.Load(wPath);
        XmlNode wNode = xmlDoc.SelectSingleNode("Autenticacoes/Database[@id='" + expression + "']");

        string wConnString = "";
        if (wNode != null)
        {
            wConnString = "Data Source=" + wNode.Attributes["servidor"].Value + 
                          ";Initial Catalog=" + wNode.Attributes["db"].Value + 
                          ";Persist Security Info=True" + 
                          ";User ID=" + wNode.Attributes["login"].Value + 
                          ";Password=" + wNode.Attributes["senha"].Value;
        }

        return wConnString;
    }
}

in the web.config:

<compilation>
    <expressionBuilders>
        <add expressionPrefix="RepConnectionString" type="RepConnectionStringExpressionBuilder" />
    </expressionBuilders>
</compilation>

Can you set the connection string in the code behind?

Leave a Comment