Git Product home page Git Product logo

formo's Introduction

Formo

Formo allows you to use your configuration file as a dynamic object. Turn your web.config or application settings into a rich, dynamic object.

How to use it

Given you have a few of the following settings in your app.config file, you can new up a Configuration object and call those settings directly through a property.

The settings

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

The code

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // returns 5 if it exists in config, else userInput if not null, else 10

Both of the values userInput and 10 will be ignored if the value has already been set in your file.

The Configuration class also has the ability to call dynamic methods with type arguments. (I know, right?!) This lets you call your property and cast it to the type of your choice.

dynamic config = new Configuration();
var appBuildDate = config.ApplicationBuildDate<DateTime>();

Specifying Culture

If you have dates in your settings file that need to be bound to a specific culture, you can do this on creation of the Configuration class.

dynamic config = new Configuration(new CultureInfo("de"));

Property Binding

You can also use Formo to bind settings values to properties on an object:

given:

<appSettings>
    <add key="SessionTimeout" value="20" />
    <add key="WebsiteSettingsSiteTitle" value="Cat Facts" />
</appSettings>

and...

public class WebsiteSettings
{
    public int SessionTimeout { get; set; }
    public string SiteTitle { get; set; }
}

then...

dynamic config = new Configuration();
var settings = config.Bind<WebsiteSettings>();

resulting in...

settings.SessionTimeout = 20;
settings.SiteTitle = "Cat Facts";

Configuration Section

You can use Formo on Configuration Sections

<configuration>
    <configSections>
        <section name="customSection" type="System.Configuration.NameValueSectionHandler"/>
    </configSections>
    <customSection>
        <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
    </customSection>
    <appSettings>
    </appSettings>
</configuration>

This still works from the previous example:

dynamic config = new Configuration("customSection");
var appBuildDate = config.ApplicationBuildDate<DateTime>();

Remark the name of the section to load on the Configuration creation. So far the only suported sections are based on System.Configuration.NameValueSectionHandler.

The Property Binding feature also works on sections.

Connection Strings

You can also access connection strings by name like so:

dynamic config = new Configuration();
var devConnection = config.ConnectionString.Development;
var prodConnection = config.ConnectionString.Production;

Given that there are connection strings in the configuration that matches the following config:

<?xml version="1.0"?>
<configuration>
  <!-- stuff -->
  <connectionStrings>
    <add connectionString="<some dev connection...>" name="Development"/>
    <add connectionString="<the production connection...>" name="Production"/>
  </connectionStrings>
  <!-- more stuff -->
</configuration>

Connection Strings With Property Bindings

when using Formo to automatically bind settings values to properties on an object as described here, connection strings are automatically bound if the object contains properties of type "ConnectionStringSettings" :

given:

<appSettings>
    <add key="SessionTimeout" value="20" />
    <add key="WebsiteSettingsSiteTitle" value="Cat Facts" />
</appSettings>
  <!-- stuff -->
  <connectionStrings>
    <add connectionString="<some dev connection...>" name="Development"/>
    <add connectionString="<the production connection...>" name="Production"/>
  </connectionStrings>
  <!-- more stuff -->

and...

public class WebsiteSettings
{
    public int SessionTimeout { get; set; }
    public string SiteTitle { get; set; }

    public ConnectionStringSettings Development { get; set; }
    public ConnectionStringSettings Production { get; set; }
}

then...

dynamic config = new Configuration();
var settings = config.Bind<WebsiteSettings>();

resulting in...

settings.SessionTimeout = 20;
settings.SiteTitle = "Cat Facts";
settings.Development = "<some dev connection...>";
settings.Production = "<the production connection...>";

Access to Any Key/Value

Sometimes, you may need to access a value that contains special characters in the key and cannot be referenced like a property of function. When this is the case, you can still get the value by the string representation, like so:

dynamic config = new Configuration();
var specialValue = config.Get("Some:Value!");

Installation

To install Formo, please use NuGet (Formo NuGet Page):

PM> Install-Package Formo

Enhancements / Feedback

Use the issues link to get in touch with me about any improvements that could be made, or any bugs you encounter.

Contributors

formo's People

Contributors

chaitanyagurrapu avatar chrismissal avatar joaomatossilva avatar thomasvm avatar urig avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formo's Issues

Support configuration sources other than System.ConfigurationManager

Windows Azure applications use CloudConfigurationManager instead of System.ConfigurationManager to read configuration values. It would be nice if there was a way to inject a different setting provider (like the Azure one) to be used with Formo. It would also allow for mocking out config values in unit tests.

I'd be happy to help provide a pull request, I'm just not sure how you'd like the code to be structured. This feature could be accomplished via an interface and injected into the Formo Configuration object at some point. There could also be multiple versions of the Formo package, one for regular configuration manager, one for Azure, etc.

Support for connection string

Perhaps add support for connection strings, and/or other parts of the configuration file.

Possible api might be:

config.ConnectionString.SomeConnectionStringName

missing gitattributes file

I had a few issues with line endings on the csproj and sln file.
I'm using the global crlf to true.

It would be nice to have a gitattribute file so the project files can merge ok.

For the pull requests I made, I used this https://gist.github.com/kappy/5019660
I used crlf to true, but I don't think its a good practice to enforce it to everyone.

Binding connection strings

Is it possible, when binding to a class, to bind connection strings or does it only support appstring and config section?

A .NET 4.0 version would be nice

It'd be nice to have a .NET 4.0 version in the NuGet package since I don't see any 4.5 specific features (unless I missed something).

Add Binding Support for Period Separated Keys

A common convention is to use period separated strings. Looking for keys with the following might be useful, not sure if it breaks backwards compat.

DeclaringType.Name + "." + PropertyInfo.Name
DeclaringType.FullName + "." + PropertyInfo.Name

Support for chained properties

Look into adding support for chained properties:

Settings:

<add key="ThirdPartyApi.Key" value="something"/>
<add key="ThirdPartyApi.Secret" value="blah"/>

Usage:

new Configuration().ThirdPartyApi.Key

How do I use this thing?

Hello!

So after using NuGet to install Formo, adding some entries into the web.config to test, and recompiling, I still don't see any intellisence for the entries on my newed-up Configuration object.

dynamic config = new Formo.Configuration();

var result = config. ummm nothing here

What step in setting this up am I missing?

Thanks!
Dustin

Error when using fallback value with bool type argument.

When NoWait does not exist in config file:

config.NoWait<bool>(true)

produces

Unable to cast setting value 'True' to 'System.Boolean'
> This is most likely because a TypeConverter hasn't been defined for the type 'System.Boolean'.

Allow inheriting class to override ConfigurationManager.GetSection

How would you feel about providing a protected method that handles the ConfigurationManager invocation so it could be replaced by an inheriting class?
Example:

        public Configuration(string sectionName, CultureInfo cultureInfo, IEnumerable<TypeConverter> customConverters = null)
        {
            _sectionName = sectionName ?? AppSettingsSectionName;
            _section = GetSection(_sectionName);
            _cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture;
            if (customConverters != null)
            {
                conversions.AddRange(customConverters);
            }
        }

        protected virtual NameValueCollection GetSection(string sectionName)
        {
            return (NameValueCollection)ConfigurationManager.GetSection(sectionName);
        }

This would allow the inheriting class to supply its own implementation for populating the NameValueCollection.

Globalization Issue

If you run the tests with a culture where the date has not the month in the first place like some european cultures the date time test: Method_should_convert_to_DateTime() fails

It would be nice to be able to specify the culture as the last parameter in the call for the configuration item as in

var actual = configuration.ApplicationBuildDate("23/01/2013", culture);

Support Environment Variables

Formo should support environment variables. Rather than start coding, I'm using this as place for notes, thoughts, and ideas from others. I don't want to end up painting developers into a corner should they decide to use it.

Things to consider:

  • What should happen when a key exists in both config file and env variables? Throw exception, use config, force user to specify the strategy if using both, other?
  • Should this be added to Configuration.cs or should a new class be created?
  • Should there be strategies for duplicate keys having a preference on where to fetch the associated value?

Formo.Cloud Description

Formo.Cloud needs a better description - unclear how it's different from Formo other than the extra dependency

Shallow Property Model Binding

It would rad if you supported model binding to shallow auto properties on a POCO object

public class WebsiteSettings 
{
    public string Herp { get; set;}
    public string Derp { get; set; }
}
<appSettings>
    <add key="Herp" value="herp" />
    <add key="WebsiteSettingsDerp" value="derp" />
</appSettings>
WebsiteSettings settings = Configuration.Bind<WebsiteSettings>();

Strong naming

Is there any chance of signing the assembly with a strong name, so that those of us who are in an environment that uses strong names can use it?

(I know this whole issue can be a little contentious)

I get null for key "part1.part2.part3" - or how do you handle periods?

Hi Team,

Love your product by the way.

Just one little issue. I am trying to read in a section where I am have no control over the key names in it and the key names have periods e.g. "part1.part2" when I try to read the value I get null.

This section is a name value collection custom section

< mySection >
< add key="allofit" value="wholekey" />
< add key="part1.part2" value="dividedkey" />
< /mySection >

The following code attempts to read it

        dynamic mySection = new Configuration("mySection");
        var allofit = quartzSection.allofit;
        var dividedKey2 = quartzSection.part1_part2;  // returns null
        var dividedKey3 = quartzSection.part1part2; // returns null
        //var dividedKey1 = quartzSection.part1.part2; -- causes runtime error

Is this simply a no-go area and all keys must be alphanumeric or is this support for this and I just couldn't find it.

Any help appreciated

Stephen

Provide ability to get section as enumeration

Given a custom section, I would like to obtain a set of types for the entire section. The usage should look like this:

dynamic config = new Configuration("myFoos");
IEnumerable<Foo> foos = config.BindAll<Foo>();

and

dynamic config = new Configuration("myFoos");
IEnumerable<Foo> foos = config.BindAll<Foo>((k, v) => new Foo { Key = k, Value = v });

Or something similar.

Create a method for abnormal string keys

In the case of a key having a special character that can't be used in a Method or Property, allow for settings to still be retrieved. Something like:

config.Get("weird:key");

and

config.Get<DateTime>("start:date");

.NET Core support?

Does Formo support or plan to support .NET Core?

The configuration system has changed a lot but I really like how I can bind to a statically compiled object with Formo. Is Formo completely replaced by options objects or is there room for some advanced stuff? For example, connection strings.

Update Readme to show Access by String

The readme should be updated to show that you can access a value by string. This is necessary when the key name can't be a property name

Mentioned in this issue:
#37

ThrowIfNull forces class name in property binding?

Hi,

Thanks for making Formo so great. It's made life real easy for me on so many projects.

I have a question or possibly a bud report.

Given:

    <appSettings>
        <add key="SessionTimeout" value="20" />
    </appSettings>

and

public class WebsiteSettings
{
    public int SessionTimeout { get; set; }
}

then this

var config = new Configuration();
var settings = config.Bind<WebsiteSettings>();

yields settings.SessionTimeout == 20 which is very cool.

However, if you do this instead:

var config = new Configuration { ThrowIfNull = true };
var settings = config.Bind<WebsiteSettings>();

you get an InvalidOperationException saying:

{"Unable to locate a value for 'WebsiteSettingsSessionTimeout' from configuration file"}

Why does ThrowIfNull "force" me to include the name of the class I'm binding to as a prefix to the appSetting key? Is this by design?

Allow inheriting class to access sectionName parameter

Love the project, BTW. :)

When inheriting from Configuration no access is provided to the cstor parameter sectionName. The CloudConfiguration doesn't appear to use it, but it would be useful in other implementations.

Improve fallback values syntax with "Or"

Instead of using:

config.RetryAttempts(5);

for a fallback default, consider:

config.RetryAttemptsOr(5);

or

config.RetryAttempts.Or(5);

I'm not sure which I like more.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.