Giter Club home page Giter Club logo

smartenums's Introduction

SmartEnums

GitHub license NuGet Badge Lates release

Info

SmartEnums is a simple library, written in C#.NET, which enables you to enhancing the capabilities of standard enum.

Installation

Either checkout this Github repository or install SmartEnums via NuGet Package Manager.

If you want to use NuGet just search for SmartEnums or run the following command in the NuGet Package Manager console:

PM> Install-Package SmartEnums

Usage

SmartEnums works on the basis of attributes, which means that now it becomes possible to store custom data for enumeration fields without resorting to writing classes.

Enum Values:

Enum Tags:

More useful features

Adding fields

First, let's describe the enumeration we want to work with:

public enum UserSubscription
{
  OneMonth,
  SixMonth, 
  Year,
}

Now using attribute

EnumValueAttribute(string key, object value)

adding custom information in enumeration:

public enum UserSubscription
{
    [EnumValue("Price", 169.0)]
    [EnumValue("Description", "One month subscribe")]
    [EnumValue("Subscribe period", 31)]
    OneMonth,
    
    [EnumValue("Price", 600.50)]
    [EnumValue("Description", "Six month subscribe")]
    [EnumValue("Subscribe period", 31 * 6)]
    SixMonth, 
    
    [EnumValue("Price", 1000.0)]
    [EnumValue("Description", "One year subscribe")]
    [EnumValue("Subscribe period", 31 * 12)]
    Year,
}
//I know that the date count is incorrect, I just gave an example that you can store any data

Now you add custom fields in enumeration.

An attribute can store expressions. It's means that you can hold simple value types, typeof() expressions and other enum.

public enum Gender
{
    [EnumValue("Description", "he/him")]
    Male,
    
    [EnumValue("Description", "she/her")]
    Female,
}

public enum TemplateUser
{
    [EnumValue("Age", 20)]
    [EnumValue("Gender", Gender.Male)]
    Jhon,

    [EnumValue("Age", 25)]
    [EnumValue("Gender", Gender.Male)]
    Claus,

    [EnumValue("Age", 15)]
    [EnumValue("Gender", Gender.Female)]
    Elza
}

Getting value

In order to get the value of a custom field, you need to use the extension method

public static T GetValueOf<T>(this Enum element, string key)

In order not to duplicate the code, let's take the enumeration declared above:

var age = TemplateUser.Claus.GetValueOf<int>("Age"); //return 25
var genderDescription = TemplateUser.Claus.GetValueOf<Gender>("Gender").GetValueOf<string>("Description"); //return "he/him"

And now you got values of custom attribute fields.

Searching enum elements via enum value

It is possible to check if an enum element contains the desired key using the extension method

public static bool ContainKey(this Enum obj, string key)

This is useful when you have enum elements containing a different number of attributes and you need to check if the enum element contains the required key.

var isContain = TemplateUser.Claus.ContainKey(key);

It is also possible to get all elements of the enumeration containing the desired key:

public static IEnumerable<T> FindByKey<T>(string key) where T : Enum

var elements = SmartEnum.FindByKey<TemplateUser>(key);

And the ability to find all elements that contain the desired key with the desired value:

public static IEnumerable<T> FindByValue<T, TK>(string key, TK value) where T: Enum

var elements = SmartEnum.FindByValue<TamplateUser, Gender>("Gender", Gender.Male);

Attribute versions

You can add your versions for attributes using same attribute with string version parameter

public enum UserSubscription
{
    [EnumValue("Price", 169.0, "1.0.0")]
    [EnumValue("Price", 300.0, "2.0.0")]
    [EnumValue("Price", 169.0, "2.0.1")]
    [EnumValue("Price", 300.0, "3.0.0")]
    OneMonth,
}

Versions implemented just as string type and you can make your own versions. But must remember that versions use standard strings comparison.

Getting versioned value

In order to get the versioned value of a custom field, you need to use the same extension method like without version but add version parameter

public static T GetValueOf<T>(this Enum element, string key, string version)

and get needed versioned value:

var price = UserSubscription.OneMonth.GetValueOf<double>("Price", "1.0.0"); //return 169.0

If you use method GetValueOf<T> without version for field that has some versions it return value of newest version.

Also you can get newest versions using keyword implemented in config class.

There are two keywords for get newest versions:

"latest",
"newest"

If you need to get a specific version or newer, you can use the ^ sign at the beginning of the parameter.

With this knowledge, you can get the value for the desired version.

var priceLatest = UserSubscription.OneMonth.GetValueOf<double>("Price", "latest"); //return 300.0
var priceNewest = UserSubscription.OneMonth.GetValueOf<double>("Price", "newest"); //return 300.0
var price = UserSubscription.OneMonth.GetValueOf<double>("Price", "^2.0.0"); //return 300.0

Adding tags attributes

In SmartEnums also provides work with tags. It's very useful when you need to mark certain elements of an enum with certain values. As an example, I mark items that are deprecated or that are used only in the release/debug version.

Again, let's describe the enumeration we want to work with:

public enum UserSubscription
{
  OneMonth,
  SixMonth, 
  Year,
  TwoYears,
}

Now using attribute

EnumTagAttribute(string value)

adding custom tag in enumeration:

public enum UserSubscription
{
    [EnumTag("new users")]
    OneMonth,
    
    [EnumTag("new users")]
    SixMonth, 
    
    [EnumTag("deprecated")]
    Year,
    
    [EnumTag("new users")]
    [EnumTag("test")]
    TwoYears
}

Now you add custom tags in enumeration.

Getting tags

In order to get tags of an enum element, you need to use the extension method

public static IEnumerable<string>? GetEnumTags(this Enum obj)

Let's take the enumeration declared above:

var tags = UserSubscription.TwoYears.GetEnumTags(); //return { "new users", "test" }

Searching via tags

For searching via tags in enum you need to use helper class SmartEnum. It contain overloaded method to search elements in enum whith certain tags.

public static IEnumerable<T> FindByTag<T>(string tag)
public static IEnumerable<T> FindByTag<T>(IEnumerable<string> tags, TagSearchingFlag flag = TagSearchingFlag.Any)

Need to make note to flag parameter. TagSearchFlag has two implemented values:

public enum TagSearchingFlag
    {
        /// <summary>
        /// Indicated to need to search elements where any
        /// tags is match with searching tags list.
        /// </summary>
        Any,
        /// <summary>
        /// Indicated to need to search elements where all
        /// tags is match with searching tags list.
        /// </summary>
        All,
    }

Using this flag, as you might guess from the description, you can explain how exactly searching using tags:

var elements = SmartEnum.FindByTag<UserSubscription>("new users"); // return { OneMonth, SixMonth, TwoYears }
var elements = SmartEnum.FindByTag<UserSubscription>(new [] { "new users", "deprecated", "test" }, TagSearchingFlag.Any); // return { OneMonth, SixMonth, Year, TwoYears }
var elements = SmartEnum.FindByTag<UserSubscription>(new [] { "new users", "test" }, TagSearchingFlag.All); // return { TwoYears }

Searching excluding tags

Sometimes need to searching excluding certain tags. For this situatuion SmartEnum contain overloaded method to search elements that excluding certain tags.

public static IEnumerable<T> FindExcludingByTag<T>(string tag)
public static IEnumerable<T> FindExcludingByTag<T>(IEnumerable<string> tags, TagSearchingFlag flag = TagSearchingFlag.Any)

This works inversely to the overloaded method described above and next code explain it:

var elements = SmartEnum.FindExcludingByTag<TestEnumTag>("new users"); // return { Year }
var elements = SmartEnum.FindExcludingByTag<TestEnumTag>(new [] { "new users", "test" }, TagSearchingFlag.Any); // return { Year }
var elements = SmartEnum.FindExcludingByTag<TestEnumTag>(new [] { "new users", "test" }, TagSearchingFlag.All); // return { OneMonth, SixMonth, Year }

Enumeration

By default, C# does not have an enumeration for enums. I suggest this big omission and added a method that implements this functionality.

public static IEnumerable<T> GetEnumerator<T>()

//example
public enum Gender
{
  Male,
  Female
}

var genders = SmartEnum.GetEnumerator<Gender>(); //return IEnumerable<Gender> [Male, Female]

Metadata

Sometimes need get full information about used EnumValueAttribute in enum. For this situations you can get metadata of enum serialized to json or xml:

For get metadata in json format use next extension method:

public static string GetJsonMetadata(this Enum obj) 

For get metadata in xml format use next extansion method:

public static string GetXmlMetadata(this Enum obj)

That's all Folks!

smartenums's People

Contributors

clausstolz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

smartenums's Issues

SmartEnum.GetEnumerator FieldNotImplementException

Given these enums I would like to be able to do the following but I can't:
var eventTypesCluster2 = SmartEnum.GetEnumerator<EventType>().Where(x => x.GetValueOf<Cluster>("Cluster") == Cluster.Two).ToList();

The goal here as you can see is to get a subset of valid enum values for a given situation but if just one enum value does not have the EnumValue with the specified key the whole enumeration fails??? That makes no sense!

I can demonstrate that issue more clearly like this:
var test = EventType.Status.GetValueOf<Cluster>("Cluster");
My expectation would be that this should return null since the EnumValue doesn't exist.

but I could kinda understand your apprehension there since it doesn't really make sense for non-nullable types like enum Cluster in this case.

A possible solution would be to keep allowing GetValueOf<> to throw the FieldNotImplementException for non-nullable types but to return null for nullable types. With that solution by adding the ? now any variable can be nullable and would return null rather than the FieldNotImplementException:
var test = EventType.Status.GetValueOf<Cluster?>("Cluster");

If you're not so keen on my previous suggestion hopefully you'll like this potential solution because it should feel familiar. Make a TryGetValueOf<> method.
An example might look like this:
var test = EventType.Status.TryGetValueOf<Cluster>("Cluster", out var clusterValue);

In my opinion I would say you should strongly consider implementing both options because being able to enumerate the enum without throwing an exception should be valuable in many cases.

public enum Cluster
{
	Unknown = -1,
	Zero = 0,
	One = 1,
	Two = 2
}

public enum EventType
{
	[EnumValue("Code", "T")]
	[EnumValue("Cluster", Cluster.One)]
	Trade,

	[EnumValue("Code", "Q")]
	[EnumValue("Cluster", Cluster.One)]
	Quote,

	[EnumValue("Code", "A")]
	[EnumValue("Cluster", Cluster.Two)]
	AggregatePerSecond,

	[EnumValue("Code", "AM")]
	[EnumValue("Cluster", Cluster.Two)]
	AggregatePerMinute,

	[EnumValue("Code", "I")]
	[EnumValue("Cluster", Cluster.Two)]
	Imbalance,

	[EnumValue("Code", "Status")]
	Status,
}

Add ability to Search by EnumValue (similar to search by tag)

I have this enum (see below) and I need a way to lookup the enum from the Code's value so I can use the enum to get the Cluster's value. It would be nice if this was a builtin feature like FindByTag.

I've found that I can do it like this:
return SmartEnum.GetEnumerator<EventType>().Single(x => x.GetValueOf<string>("Code") == code);
but it would be nice to have a simpler syntax that is an extension method (again like FindByTag).

public enum EventType
{
	[EnumValue("Code", "T")]
	[EnumValue("Cluster", 1)]
	Trade,

	[EnumValue("Code", "Q")]
	[EnumValue("Cluster", 1)]
	Quote,

	[EnumValue("Code", "A")]
	[EnumValue("Cluster", 2)]
	AggregatePerSecond,

	[EnumValue("Code", "AM")]
	[EnumValue("Cluster", 2)]
	AggregatePerMinute,

	[EnumValue("Code", "I")]
	[EnumValue("Cluster", 2)]
	Imbalance,

	[EnumValue("Code", "Status")]
	[EnumValue("Cluster", 0)]
	Status,
}

SmartEnums 4.0 (generated enums)

  • Realize enum generator;
  • Realize adding enumValues to generated enums;
  • Realize adding tags to generated enums;
  • Realize work with extensions;
  • Realize work with SmartEnum class;
  • Realize tests;
  • Update documentation;

Fix summary in nuget package

There are summary docs for main methods in project but when build source to package in new version has not summary.

Improve error handling

Now versions in EnumValueAttribute can be null and sometimes it can throw null exception. Need to fix it.

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.