JamesBB JamesBB - 1 month ago 14
C# Question

Get connectionstring from Registry LINQtoSQL

I am confused about how to get the connectionstring that is stored in the registry to be used by the DataContext.

Where and how do I go from this:

public DataClassesDataContext() :
base(global::DDSTime.Properties.Settings.Default.DDSTimeConnectionString, mappingSource)
{
OnCreated();
}


to not using Properties.Settings.Default.DDSTimeConnectionString but the value from the registry?

I want to do it this way, because the application is used at different locations, and I do not want to leave the connectionstring in the config file for all to see.
With just a little script, all the machines would insert the connectionstring key in their registry, and there would be no need to create different 'versions' as each locations uses their own SQL Server onsite.

Answer

If you don't already have a suitable constructor, then it should be easy to create one like :

public DataClassesDataContext(string connectionString) : 
        base(connectionString, mappingSource)
{
    OnCreated();
}

This means you need to pass the connectionString every time you create a new DataContext. If you prefer, you can change the current constructor to something like

private static string GetDefaultConnectionString()
{
    var connectionString = ... // Read value from registry
    if (String.IsNullOrEmpty(connectionString))
        connectionString = global::DDSTime.Properties.Settings.Default.DDSTimeConnectionString ;
    return connectionString;
}

public DataClassesDataContext() :
            base(GetDefaultConnectionString(), mappingSource)
{
    OnCreated();
}
Comments