Separate Config Files for Dll’s
December 16, 2011
Is it possible for a .NET dll to have it’s own configuration file? The answer is “yes”. Though people can discuss the merits and demerits of this approach, it is doable. In this post I will present a short example of what you need to do to get this going. I have a DLL that will call a windows service. My client doesn’t need to know where the wcf service is hosted.
Here’s my config file for the dll
Here’s the code for my Dll:
public class CallWcf
{
public static string UserId { get; set; }
public static string UserPassword { get; set; }
public static string EndPointUrl { get; set; }
public string LoadConfiguration()
{
var fileName = Assembly.GetExecutingAssembly().GetName().Name;
return fileName;
}
public void GetConfigValues(string fileName)
{
var dllConfigFile = Environment.CurrentDirectory.Trim() + "\\" + fileName.Trim() + ".dll";
try
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(dllConfigFile);
//So far we got the config file for the dll in here.
var appSettings = configuration.AppSettings.Settings;
foreach (KeyValueConfigurationElement keyValueConfigurationElement in appSettings)
{
switch (keyValueConfigurationElement.Key)
{
case "WSUser": UserId = keyValueConfigurationElement.Value;
break;
case "WSUserPassword": UserPassword = keyValueConfigurationElement.Value;
break;
case "endpointurl": EndPointUrl = keyValueConfigurationElement.Value;
break;
}
}
Console.WriteLine(string.Format("User:{0}\t Password:\t{1} \t{2}", UserId, UserPassword, EndPointUrl));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public string GetToken()
{
var obj = CreateWebServiceInstance(EndPointUrl);
var retval = obj.AuthenticateWithDetails(UserId, UserPassword);
return retval.AuthenticationKey;
}
internal static Authenticate.AuthenticateSvcClient CreateWebServiceInstance(string endpointurl)
{
var binding = new BasicHttpBinding
{
SendTimeout = TimeSpan.FromMinutes(1),
OpenTimeout = TimeSpan.FromMinutes(1),
CloseTimeout = TimeSpan.FromMinutes(1),
ReceiveTimeout = TimeSpan.FromMinutes(10),
AllowCookies = false,
BypassProxyOnLocal = false,
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = System.Text.Encoding.UTF8,
TransferMode = TransferMode.Buffered,
UseDefaultWebProxy = true
};
// I think most (or all) of these are defaults--I just copied them from app.config:
return new Authenticate.AuthenticateSvcClient(binding, new EndpointAddress(endpointurl));
}
}
Here’s the code for my executable:
static void Main(string[] args)
{
var obj = new VBFTestWCF.CallWcf();
var str = obj.LoadConfiguration();
Console.WriteLine(str);
obj.GetConfigValues(str);
var token = obj.GetToken();
Console.WriteLine(token);
}