Search code examples
c#.netoopvisual-studio-2012telerik-open-access

Calling base constructor after body of current constructor


I am customizing one of the code generating templates for my Telerik OpenAccess ORM library. Due to business rules, I am having to put my user name and password to connect to the database in a config file as an encrypted string. I don't have the authority over this requirement and as such I cannot avoid it.

What I have done is create a singleton class that provides the decrypted credentials and modified the code generation template to use it. Here is part of the template I am modifying:

public <#= contextClass.Name #>()
        :base(connectionStringName, backend, metadataSource)
{
    Credentials credentials = Credentials.Instance;
    string connectionString = String.Format("DATA SOURCE={0};PASSWORD={1};PERSIST SECURITY INFO=True;USER ID={2}", 
                                             credentials.DatabaseServer,
                                             credentials.DatabasePassword,
                                             credentials.DatabaseUser);

}

public <#= contextClass.Name #>(string connection)
    :base(connection, backend, metadataSource)
{ }

public <#= contextClass.Name #>(BackendConfiguration backendConfiguration)
    :base(connectionStringName, backendConfiguration, metadataSource)
{ }

//More constructors.....

All of the templates generate constructors with no code inside the body. What I want is to create my connection string and then use that for the constructor of the base class (OpenAccessContext). I would like this to be my default constructor as you can tell by the parameterless constructor I modified -- public <#= contextClass.Name #>()

What has me stumped is how to create this string and then use it in the constructor of my base class. Any ideas?


Solution

  • You can't call base(...) at the end of your constructor, but you should be able to do something like this: (note that the method must be static)

    static string GetConnString() { /* insert credentials and conn string code here */ }
    
    public <#= contextClass.Name #>()
        :base(GetConnString(), ...
    

    Or if I'm misunderstanding your question, maybe this is what you need?

    public <#= contextClass.Name #>(string connection)
      :this()
    { /* handle connection */ }
    
    public <#= contextClass.Name #>(BackendConfiguration backendConfiguration)
      :this()
    { /* handle backendConfiguration */ }