Get/Set app.config values for WPF and Windows forms using C#

In Windows forms developers sometimes need a place to store information like connection strings or data binding to controls. This is typically done usually under project properties by creating a setting which generates xml e.g.

<userSettings>
  <WindowsFormsApp1.Properties.Settings>
    <setting name="Author" serializeAs="String">
      <value>Karen Payne</value>
    </setting>
  </WindowsFormsApp1.Properties.Settings>
</userSettings>

Although this works sometimes we want more control so we can have

<appSettings>
  <add key="DatabaseServer" value=".\SQLEXPRESS" />
  <add key="Catalog" value="NorthWind2020" />
  <add key="SortColumn" value="CompanyName" />
  <add key="SortDirection" value="Descending" />
</appSettings>

For both setting and connection strings. When looking at connection strings this works well for Entity Framework Core and the server (DatabaseServer) and Catalog (the default catalog) can be composed in the DbContext/ This way if the catalog is the same on dev, test and prod we only need to update the server. In short more flexibility but nothing stopping a developer to combine server and catalog.

Simple example for settings, using Entity Framework Core we are dynamically sorting.

public static List<T> SortByPropertyName<T>(this List<T> list, string propertyName, SortDirection sortDirection)
{
 
    var param = Expression.Parameter(typeof(T), "item");
 
    Expression<Func<Tobject>> sortExpression = Expression.Lambda<Func<Tobject>>(
        Expression.Convert(Expression.Property(param, propertyName), typeof(object)), param);
 
    list = sortDirection == SortDirection.Ascending ? 
        list.AsQueryable().OrderBy(sortExpression).ToList() : 
        list.AsQueryable().OrderByDescending(sortExpression).ToList();
 
    return list;
 
}

Screenshot













A developer may write code in a project such as in this code sample but that is only good for a single project. A better solution is to use a class project as done in this project which means a project which needs this functionality need only to include the compiled project as a project reference to their Windows form or WPF project.

To test, use a unit test as seen in the first two unit test in this project

Using the code, download the following project, add a reference to your project. Add one or more setting to app.config as per above then use the SetValue method or write a wrapper e.g.

AssemblyHelpers.SetDefaultCatalog("NorthWind2020");

And to get the value

AssemblyHelpers.GetDefaultCatalog()

So if you need a more in control of settings give the library a try.

Code written in Visual Studio 2017 Framework 4.7.2

Comments

Popular posts from this blog

VB.NET Working with Delegate and Events

Coders asking questions in online forums

GitHub download partial repository