How to bind SqlDatasource ConnectionString property to function

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

Example:

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

The above will obviously not work .. so .. what will happen?

Preventive notes: * No, I cannot use the Web.config binding

+3
source share
3 answers

you can set it to your Page_Load, something like:

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

or if you do not have access to the code behind the embedded code on the page, for example, before markup for SqlDataSource

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

The best way to find this question is to use Expression Builder in your solution.

Using this function, you can create your own inline expression and use it in the SqlDataSource tag.

:

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

:


[ExpressionPrefix("RepConnectionString")]

RepConnectionStringExpressionBuilder: ExpressionBuilder {   public override CodeExpression GetCodeExpression ( BoundPropertyEntry, parsedData, ExpressionBuilderContext)   {       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;
}

}


web.config:

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

+1

Can you set the connection string in code?

0
source

Source: https://habr.com/ru/post/1706084/


All Articles