• Stars
    star
    178
  • Rank 214,989 (Top 5 %)
  • Language
    C#
  • Created about 12 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Strongly typed, code-first configuration classes for .NET applications

West Wind Application Configuration

Strongly typed configuration classes for .NET Applications###

This is a .NET library for code-first configuration settings using strongly typed .NET classes. Create a class, add properties for configuration values, instantiate and automatically read and optionally write your strongly typed configuration values from various configuration stores.

Configuration data can be stored in various configuration formats and can auto-sync from store to class and vice versa. You can use standard .NET config files (default), including custom sections and external files, or other custom stores including JSON, plain XML files, strings or a database. It's also easy to create your own configuration providers to store config data in some other format or you can use the generic StringConfigurationProvider to capture configuration data and store it as you like.

Unlike the built-in .NET Configuration Manager, the classes you create are strongly typed and automatically convert config store values to strong types. You can also write configuration data from the class to the configuration store and if a store or store value doesn't exist it's automatically created in the store (provided permissions allow it).

To install and use it, you can use NuGet:

PM> Install-Package Westwind.Utilities.Configuration

This library provides:

  • Strongly typed classes for configuration values
  • Automatic type conversion from configuration store to class properties
  • Default values for configuration values (never worry about read failures)
  • Optional encryption of individual keys
  • Automatic creation of configuration store if it doesn't exist
  • Automatic addition of values that don't exist in configuration store (your store stays in sync with your class automatically)
  • Support for multiple configuration objects simultaneously
  • Works in any kind of .NET application: Web, Desktop, Console, Service...

Provided Configuration Storage formats:

  • Standard .NET .config files
    • AppSettings
    • Custom Configuration Sections
    • External Configuration Files
  • Standalone, plain XML files
  • JSON files (explicit JSON.NET reference required)
  • Strings
  • Sql Server Tables
  • Customizable to create your own Configuration Providers

More detailed documentation is available as part of the Westwind.Toolkit here:

West Wind Application Configuration is also part of: West Wind Toolkit's Westwind.Utilities library

Getting Started

Start by adding the Westwind.Utilities.Configuration NuGet package to your project. Use either the Package Manager Explorer or the Console:

PM> Install-Package Westwind.Utilities.Configuration

To create configurations, simply create a class that holds properties for each configuration value. The class maps configuration values stored in the configuration file. Values are stored as string in the configuration store, but are accessed as strongly typed values in your class.

The library allows for reading and writing of configuration data (assuming you have permissions) and assignment of default values if values don't exist in the configuration store. Your class ALWAYS has default values.

To use you simply create a class derived from AppConfiguration and add properties:

public class ApplicationConfiguration : Westwind.Utilities.Configuration.AppConfiguration
{    
	public string ApplicationTitle { get; set; }
	public string ConnectionString {get; set; }
	public DebugModes DebugMode {get; set; }  // enum
	public int MaxPageItems {get; set; }   // number

	public ApplicationConfiguration()
	{
	        ApplicationTitle = "West Wind Web Toolkit Sample";
	        DebugMode = DebugModes.ApplicationErrorMessage;
	        MaxPageItems = 20;
	}
}

Each property maps to a configuration store setting.

To use the class you simply create an instance and call Initialize() then read configuration values that were read from the configuration store, or default values if store values don't exist:

// Create an instance - typically you'd use a static singleton instance
var config = new ApplicationConfiguration();
config.Initialize();  

// Now read values retrieved from web.config/ApplicationConfiguration Section
// If write access is available, the section is auto-created if it doesn't exist
string title = config.ApplicationTitle;
DebugModes modes = config.DebugMode;  
	
// You can also update values
config.MaxPageItems = 15;
config.DebugMode = DebugModes.ApplicationErrorMessage;  
	
// Save values to configuration store if permissions allow
config.Write();

The above instantiation works, but typically in an application you'll want to reuse the configuration object without having to reinstantiate it each time.

More effectively, create a static instance in application scope and initialize it once, then re-use everywhere in your application or component:

public class App
{
	// static property on any class in your app or component
	public static ApplicationConfiguration Configuration { get; set; }
	
	// static constructor ensures this code runs only once 
	// the first time any static property is accessed
	static App()
	{
	    /// Load the properties from the Config store
	    Configuration = new ApplicationConfiguration();
	    Configuration.Initialize();
	}
}

You can then use the configuration class anywhere, globally without recreating:

int maxItems = App.Configuration.MaxPageItems;
DebugModes mode = App.Configuration.DebugMode;

Once instantiated you can also use Read() and Write() to re-read or write values to the underlying configuration store.

Note that you can easily create multiple application configuration classes, which is great for complex apps that need to categorize configuration, or for self-contained components that need to handle their own internal configuration settings.

Configuration Providers

By default configuration information is stored in standard config files. When calling the stock Initialize() method with no parameters, you get configuration settings stored in an app/web.config file with a section that matches the class name.

To customize the configuration provider you can create an instance and pass in one of the providers with customizations applied:

public static App 
{
	App.Config = new AutoConfigFileConfiguration();

	// Create a customized provider to set provider options
	// Note: several different providers are available    
	var provider = new ConfigurationFileConfigurationProvider<AutoConfigFileConfiguration>()
	{
		ConfigurationSection = "CustomConfiguration",
		EncryptionKey = "seekrit123",
		PropertiesToEncrypt = "MailServer,MailServerPassword"                
	};

	App.Config.Initialize(provider);  
}

Alternately you can abstract the above logic directly into your configuration class by overriding the OnInitialize() method to provide your default initialization logic which keeps all configuration related logic in one place.

The following creates a new configuration using the Database provider to store the configuration information:

public class DatabaseConfiguration : Westwind.Utilities.Configuration.AppConfiguration
{
    public DatabaseConfiguration()
    {
        ApplicationName = "Configuration Tests";
        DebugMode = DebugModes.Default;
        MaxDisplayListItems = 15;
        SendAdminEmailConfirmations = false;
        Password = "seekrit";
        AppConnectionString = "server=.;database=hosers;uid=bozo;pwd=seekrit;";
    }

    public string ApplicationName { get; set; }
    public DebugModes DebugMode { get; set; }
    public int MaxDisplayListItems { get; set; }
    public bool SendAdminEmailConfirmations { get; set; }
    public string Password { get; set; }
    public string AppConnectionString { get; set; }
        
    /// <summary>
    /// Override this method to create the custom default provider - in this case a database
    /// provider with a few options. Config data can be passed in for connectionstring and table
    /// </summary>
    protected override IConfigurationProvider OnCreateDefaultProvider(string sectionName, object configData)
    {
        // default connect values
        string connectionString =  "LocalDatabaseConnection";
        string tableName = "ConfigurationData";

        // ConfigData: new { ConnectionString = "...", Tablename = "..." }
        if (configData != null)
        {
            dynamic data = configData;
            connectionString = data.ConnectionString;
            tableName = data.Tablename;                       
        }

        var provider = new SqlServerConfigurationProvider<DatabaseConfiguration>()
        {
            ConnectionString = connectionString,
            Tablename = tableName,
            ProviderName = "System.Data.SqlServerCe.4.0",
            EncryptionKey = "ultra-seekrit",  // use a generated value here
            PropertiesToEncrypt = "Password,AppConnectionString"
            // UseBinarySerialization = true                     
        };

        return provider;
    }    

    /// <summary>
    /// Optional - simplify Initialize() for database provider default
    /// </summary>
    public void Initialize(string connectionString, string tableName = null)
    {
        base.Initialize(configData: new { ConnectionString = connectionString, Tablename = tableName });
    }
}

You can override the OnCreateDefaultProfile() method and configure a provider, or the slightly higher level OnInitialize() which creates a provider and then reads the content. Either one allows customization of the default Initialization when Initialize() is called with no explicit Provider.

Multiple Configuration Stores

To create multiple configuration stores simply create multiple classes and access each class individually. A single app can easily have multiple configuration classes to separate distinct sections or tasks within an application. Ideally you store the configuration objects on a global static instance like this:

App.Configuration = new MyApplicationConfiguration();
App.Configuration.Initialize();

App.AdminConfiguration = new AdminConfiguration();
App.AdminConfiguration.Initialize();

This allows for nice compartmentalization of configuration settings and also for multiple components/assemblies to have their own private configuration settings.

Configuration Property Encryption

Application Configuration supports encryption of single keys of the stored configuration values. To enable encryption you specify the fields that are to be encrypted using the Provider's PropertiesToEncypt property.

App.Config = new AutoConfigFileConfiguration();

// Create a customized provider to set provider options
// Note: several different providers are available    
var provider = new ConfigurationFileConfigurationProvider<AutoConfigFileConfiguration>()
{
	ConfigurationSection = "CustomConfiguration",
	EncryptionKey = "seekrit123",
	PropertiesToEncrypt = "MailServer,MailServerPassword,License.LicenseKey"                
};

You can encrypt any single property including nested properties using '.' syntax for any child properties of nested objects. There's no support for encrypting list values at this time.

Encryption occurs prior to writing the object to its provider store. Decryption occurs when the config object is read from the provider store. Note that the in-memory object is always un-encrypted - on the data stored on disk or in the provider store is encrypted.

Complex Type Serialization

If you're using a configuration store other than .NET .config files you can easily create complex hierarchical types as these types are serialized using either XML or JSON serialization - anything those serialization formats support you can write out to.

If you're using the .config format you're limited to key value pairs in configuration sections, so your configuration objects have to preferrably be single level without child types.

However, the ConfigurationFileConfigurationProvider does support serialization of some complex types and IList-based lists.

####Complex Types using ToString()/FromString() One of the easiest way to serialize configuration child objects is to create a custom type that implements a ToString() and static FromString() method that effectively provides two-way serialization.

Here's an example:

public class LicenseInformation
{
    public string Name { get; set; }
    public string Company { get; set; }
    public int LicenseKey { get; set; }

    public static LicenseInformation FromString(string data)
    {
        return StringSerializer.Deserialize<LicenseInformation>(data,",");
    }

    public override string ToString()
    {
        return StringSerializer.SerializeObject(this, ",");
    }
}

Here a StringSerializer helper is used that basically does a string.Join()/string.Split() to create a serialized string with a separator of an object in the ToString() and FromString() methods. You can of course use any mechanism to create a string that represents the serialized object data but StringSerializer is a quick and easy way to do so.

If you now add this to a configuration object like this:

public class CustomConfigFileConfiguration : Westwind.Utilities.Configuration.AppConfiguration
{
    public string ApplicationName { get; set; }      
    public LicenseInformation ComplexType { get; set; }

    public CustomConfigFileConfiguration()
    {
        ApplicationName = "Configuration Tests";
        ComplexType = new LicenseInformation()
        {
            Name = "Rick", 
            Company = "West Wind",
            LicenseKey = 10
        };
    }
}

you get a serialized configuration section like this:

<CustomConfig>
    <add name="ApplicationName" value="Configuration Tests" />
    <add key="ComplexType" value="Rick,West Wind,10" />
</CustomConfig>

TypeConverters

You can also use custom type converters on the object to serialize which is a bit more involved. You can find out more here: http://west-wind.com/westwindtoolkit/docs/_1cx0ymket.htm

IList Types

In addition to complex objects you can also serialize IList values or objects in .config files. List values are enumerated and read/written with indexes such as ItemList1, ItemList2, ItemList3 etc. with each item representing either a single value such as string, or a complex object that supports either the ToString()/FromString() or TypeConverter serialization discussed in the previous section.

public class CustomConfigFileConfiguration : Westwind.Utilities.Configuration.AppConfiguration
{
        public string ApplicationName { get; set; }
        public List<string> ServerList { get; set;  }

        public CustomConfigFileConfiguration()
        {
            ApplicationName = "Configuration Tests";
            ServerList = new List<string>()
            {
                "DevServer",
                "Maximus",
                "Tempest"
            };
        }
}

produces the following .config:

<CustomConfigFileConfiguration>
   <add key="ApplicationName" value="Configuration Tests" />   
   <add key="ServerList1" value="DevServer" />
   <add key="ServerList2" value="Maximus" />
   <add key="ServerList3" value="Tempest" />
</CustomConfigFileConfiguration>

##Class Structure This library consists of the main AppConfiguration class plus provider logic. Providers are based on a IConfigurationProvider interface with a ConfigurationProviderBase class providing base functionality.

Here's the complete class layout: Classes

##Many More Options Many more configuration options are available. Please check the full documentation for more information.

More Repositories

1

MarkdownMonster

An extensible Markdown Editor, Viewer and Weblog Publisher for Windows
HTML
1,584
star
2

Westwind.Globalization

Database driven resource localization for .NET applications
C#
543
star
3

AlbumViewerVNext

West Wind Album Viewer ASP.NET Core and Angular Sample
JavaScript
505
star
4

Westwind.AspnetCore.LiveReload

ASP.NET Core Live Reload Middleware that monitors file changes in your project and automatically reloads the browser's active page
C#
470
star
5

WestWindWebSurge

Quick and easy URL and Load Testing for your Web applications on Windows
388
star
6

WestwindToolkit

A utility toolkit for .NET development from Core to Web
C#
273
star
7

Westwind.Utilities

A general purpose utility and helper library for .NET development
C#
255
star
8

Westwind.AspNetCore.Markdown

An ASP.NET Core Markdown support library that provides Markdown parsing, a Markdown TagHelper and Markdown Page Handler Middleware
C#
248
star
9

jquery-resizable

A small jQuery plug-in to make DOM components resizable
PowerShell
234
star
10

Westwind.Scripting

Small C# library to provide dynamic runtime code compilation from source code for code and expressions execution
C#
205
star
11

Westwind.RazorHosting

Hosting the Razor Runtime outside of ASP.NET/MVC for use in non-Web .NET applications.
C#
144
star
12

jquery-watch

A jQuery plug-in to watch CSS style and attribute changes and get notified when a change occurs
JavaScript
133
star
13

SetResolution

Quickly set Windows Display Resolution via Command Line
C#
128
star
14

Westwind.AspNetCore

ASP.NET Core Helpers and Utilities
C#
126
star
15

Expando

Extensible dynamic types for .NET
C#
108
star
16

LiveReloadServer

A self-contained, local, cross-platform, static file Web Server based on .NET with automatic Live Reloading, Markdown rendering and loose Razor Pages support.
CSS
100
star
17

json.date-extensions

Date parsing extensions for the JavaScript JSON parser to provide real dates from JSON.parse()
JavaScript
93
star
18

wwDotnetBridge

.NET Interop for Visual FoxPro made easy
C#
73
star
19

AspNetWebApiArticle

Source code for ASP.NET WebApi Article for Code Magazine
JavaScript
66
star
20

DeleteFiles

Windows Console Utility to delete files and folders recursively with optional date filtering
C#
62
star
21

CodePaste.NET

CodePaste.NET site code
JavaScript
58
star
22

highlightjs-badge

Addon component to highlightjs that lets you copy code snippets to the clipboard and displays the active syntax
CSS
46
star
23

HtmlSanitizer

A base Html Sanitizer for .NET
C#
35
star
24

Westwind.HtmlPackager

A small utility class used to package HTML content into a self contained HTML document both as a single file, or a folder with all dependencies copied to local.
C#
35
star
25

AspNetFrameworksPerformance

ASP.NET Raw Throughput Performance Post Sample
C#
31
star
26

AspNetCoreRawRequestSample

Sample code for Accepting Raw Request Body in Asp.NET Core Applications
C#
31
star
27

CordovaAlbumViewer

Sample code for "Taming Mobile Apps with Cordova and Visual Studio" CODE magazine article
JavaScript
30
star
28

Westwind.plUploadHandler

An ASP.NET base HttpHandler library to handle plUpload content on the server.
JavaScript
28
star
29

wwMongoDb

Access MongoDb from Visual FoxPro
xBase
25
star
30

WestWind.WebView.HtmlToPdf

Creating Pdf output from Html with .NET on Windows using the WebView2 control
HTML
25
star
31

Westwind.Wpf.Statusbar

A small WPF library to provide animated status bar operations
C#
24
star
32

VisualStudioSnippetConverter

Utility to convert Visual Studio Code Snippets to VS Code and Rider.
C#
22
star
33

vue-mover

A 2 list mover component implemented as a VueJs Component
JavaScript
19
star
34

Westwind.Web.Markdown

Markdown support for ASP.NET WebForms and MVC applications
C#
19
star
35

DotnetDesktopRuntimeInstaller

A tiny Windows console executable that can be distributed with an application and called from an installer to download and install the .NET runtime.
C#
18
star
36

GistIntegration-MarkdownMonster-Addin

Markdown Monster addin to create embeddable Gists for Markdown documents, and to load and save documents from Gists.
C#
17
star
37

Westwind.QueueMessageManager

.NET Library to provide a simple, two-way messaging queue for enabling offloading of long running operations to other processes/machines.
JavaScript
16
star
38

Westwind.WebView

A .NET support library for the `Microsoft.Web.WebView2` control to aid with common operations and .NET / JavaScript interop.
HTML
14
star
39

AspNetCoreFromScratchSample

Working example to experiment with building Asp.net core from scratch
C#
14
star
40

SignalrChatSample

Sample SignalR Chat application that demonstrates VueJs, Angular, FoxPro and .NET clients to SignalR
JavaScript
12
star
41

Westwind.AspNetCore.HostedWebServer

Sample that demonstrates how to create a minmal ASP.NET Web Server that can be hosted in a desktop (or other non-Web) application easily.
C#
12
star
42

Westwind.Data.EfCore

Lightweight Business Object wrapper for Entity framework that handles CRUD operations and error handling.
C#
12
star
43

BlogPosts

HTML
11
star
44

MarkdownMonsterAddinsRegistry

Markdown Monster Addin Registry
10
star
45

Pandoc-MarkdownMonster-Addin

A Pandoc Markdown Parser and Pandoc Operations Library for Markdown Monster
C#
10
star
46

Commander-MarkdownMonster-Addin

Commander C# Scripting Addin that can be used to automate simple tasks in Markdown Monster without creating an Addin. Launch external tools, update documents or mail merge content into the editor.
C#
10
star
47

WpfWebView2Playground

JavaScript
9
star
48

DI2017-AspNet-Core-Angular

Session Materials for Dev Intersection ASP.NET Core and Angular Session
TypeScript
9
star
49

CodeMagazine-DotnetTools

Code Magazine Article Materials for Dotnet Tools Article
C#
8
star
50

VirtualFoxFest2021-FoxProRest

JavaScript
8
star
51

SaveToAzureBlob-MarkdownMonster-Addin

Markdown Monster Addin to open or paste images from your local machine and save them in Azure Blob Storage and embed link into your post.
C#
8
star
52

anti-trust-guilty-album

Anti-Trust Guilty Album - Punk Rock Music
JavaScript
7
star
53

Westwind.Webstore

West Wind Web Store Sample application
JavaScript
7
star
54

HelpBuilderReleases

West Wind Html Help Builder Releases and Bug Reporting
6
star
55

MarkdownMonsterReleases

6
star
56

Snippets-MarkdownMonster-Addin

A Snippet Expansion Manager for embedding templated text into Markdown Monster Markdown documents
C#
6
star
57

West-Wind-Message-Board

West Wind Message Board Web Connection (FoxPro) Sample Application
JavaScript
6
star
58

AspetCoreIISInprocessHostingSample

Simple test project optimized for Hello World style controller ops for comparison of hosting options on Windows
C#
5
star
59

DI2017-ASP.NET-Core-Localization

Session materials for DevIntersection 2017 - ASP.NET Core Localization
JavaScript
5
star
60

Padnug-2016-Angular-AspNet

Sample application and Slides from Rick's May 2nd, 2016 Angular ASP.NET Core Presentation
TypeScript
5
star
61

Console-MarkdownMonster-Addin

A simple Console/Terminal addin for Markdown Monster that displays a terminal window attached to the main Markdown Monster Window
C#
5
star
62

Westwind.Ai

Sample project that demonstrates OpenAI Image Generation
C#
5
star
63

datepicker-native

JavaScript and Vue helper components to make it easier to bind dates to the input/date control and a date button picker.
JavaScript
5
star
64

Westwind.AI

C#
4
star
65

Blazor_Playground

Blazor Sample Application
C#
4
star
66

WestwindWebSurgeReleases

Repository that holds releases for West Wind WebSurge
4
star
67

GithubRespositoryParser

C# Github Repository and Content Retrieval Examples using regular and GraphQL APIs.
C#
3
star
68

MarkdownMonsterAddinProjectTemplate

A Visual Studio Project Template for creating a Markdown Monster Addin
C#
3
star
69

Base64

C#
3
star
70

QfxToQboConverter

A small utility to fix up Quicken QIF files (.qfx) so they can be opened as QBO in Quickbooks.
C#
3
star
71

VirtualFoxFest2022-FoxProDotnet

Session Notes and Samples for Virtual FoxFest FoxPro .NET Interop Session
xBase
3
star
72

Live-Writer-SnagIt-Screen-Capture-Plugin

A Live Writer plug-in to provide screen capturing using TechSmith's SnagIt
C#
3
star
73

SWFOX2019_Vue

JavaScript
3
star
74

SWFOX18_WebConnectionSecurity

2
star
75

samples.west-wind.com

West Wind Samples Web Site
HTML
2
star
76

ChromiumPreview-MarkdownMonster-Addin

A Chromium Preview Browser Addin for the Markdown Monster Markdown Editor
C#
2
star
77

Westwind.Weblog

Source for Westwind Weblog
C#
2
star
78

KavaDocs-MarkdownMonster-Addin

KavaDocs Integration for Markdown Monster
C#
2
star
79

EmptyWebContentProjectTemplate

Empty Content Web Site Project that publishes from the root folder and works optionally with WebDeploy
HTML
2
star
80

SWFOX2019_DotnetCore

JavaScript
2
star
81

CODE.Framework.Core.ServiceHandler

C#
1
star
82

MarkdownMonsterDocumentation

JavaScript
1
star
83

swfox2024-wwdotnetbridge-revisited

Samples, Session Notes and Slides for Southwest Fox 2024 Sessions
HTML
1
star
84

dotnet-tools-padnug2020

1
star
85

WebSurgeDocumentation

Documentation for West Wind WebSurge
JavaScript
1
star
86

WebConnection-WebDemo

Web Connection Sample Application for the Getting Started Walk Through
JavaScript
1
star
87

HighPerformanceAspNet

C#
1
star
88

SWFOX2019_WebConnectionDeployment

PowerShell
1
star
89

SWFOX2018_MarkdownWithFoxPro

JavaScript
1
star