Is It Possible to Map to an Enum With an Alias? - c#

I have a http request coming that has a property for a value. There are 2 possible options for this value, let's say Standard and Boosted. I'm using an enum for this.
I also need to get the same value from my database, but in database this value is called something else. For example they are called TypeS and TypeB.
I'm looking for an easy way to map them to each other.
I've tried using an Alias but that doesn't seem to be working.
pubic enum RequestType
{
[Alias("TypeS")]
Standard,
[Alias("TypeB")]
Boosted
}
public class ReturnObject
{
public RequestType type {get; set;}
}
I'm getting the record from the database using a stored proc.
db.SqlList<ReturnObject>("EXEC SomeStoredProc #someParameter",
new { someParameter }).ToList();
ReturnObject.type is always Standard even tho the Database returns TypeB which tells me it instantiates the enum with the default value.

In the latest v5.5.1 on MyGet, OrmLite supports char enums, e.g
[EnumAsChar]
public enum SomeEnum
{
Value1 = 'A',
Value2 = 'B',
Value3 = 'C',
Value4 = 'D'
}
Otherwise the only other ways OrmLite supports persisting enums is by Name (default):
public enum SomeEnum
{
Value1,
Value2,
Value3,
Value4,
}
By Enum integer value:
[Flags] //or [EnumAsInt]
public enum SomeEnum
{
None = 0,
Value1 = 1 << 0,
Value2 = 1 << 1,
Value3 = 1 << 2,
Value4 = 1 << 3,
}
Or by char value as shown in my first example.
Alternatively you'd need to use the name it's stored in the database as, but you can have it serialized using a different value by annotating it with [EnumMember], e.g:
[DataContract]
public enum SomeEnum
{
[EnumMember(Value = "VALUE 1")]
Value1,
[EnumMember(Value = "VALUE 2")]
Value2,
[EnumMember(Value = "VALUE 3")]
Value3,
[EnumMember(Value = "VALUE 4")]
Value4,
}

Related

can not convert implicitly from string to int

In C#, I have used Enum to get the drop down values:
class Enum
{
public enum Fields
{
AssignedTo = "Assigned To",
CloseReason = "Close Reason",
CustomerId = "Customer ID",
CustomerName = "Customer Name",
CompanyID = "Company ID",
CompanyName = "Company Name",
}
}
When I build the solution. I am getting the error: cannot implicitly convert type 'string' to 'int'.
I have removed the double quotes but still it shows the same error. What do I do wrong?
In C# string are not allowed types for enums.
Quote from MSDN https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
The approved types for an enum are byte, sbyte, short, ushort, int,
uint, long, or ulong
If will have to do some kind of conversion (i.e. using [DisplayName] attribute) to use enum in dropdown.
i am not sure if it is because you are trying to display string to the enum then is because enum only use int 16 and 32 so we have to create an extension to make it show strings and then use the int value to call it
using System.Reflection;
public static class EnumExtensions
{
public static string DisplayName(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
EnumDisplayNameAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
as EnumDisplayNameAttribute;
return attribute == null ? value.ToString() : attribute.DisplayName;
}
}
public class EnumDisplayNameAttribute : Attribute
{
private string _displayName;
public string DisplayName
{
get { return _displayName; }
set { _displayName = value; }
}
}
class Enum
{
public enum Fields
{
[EnumDisplayName(DisplayName = "Assigned To"
AssignedTo,
[EnumDisplayName(DisplayName = "Close Reason"
CloseReason,
[EnumDisplayName(DisplayName = "Customer ID"
CustomerId,
[EnumDisplayName(DisplayName = "Customer Name"
CustomerName,
[EnumDisplayName(DisplayName = "Company ID"
CompanyID,
[EnumDisplayName(DisplayName = "Company Name"
CompanyName ,
}
}
just like i did for my group description for listview
this is syntactically invalid in c#
https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
you will need a workaround to create string enum in c#
https://www.google.com/?gfe_rd=cr&ei=sBwXV_XZDKO_wQOjmaqABw&gws_rd=ssl#q=string+enum+in+c%23
It is giving this error because by default the enum expects you to assign an integer value to the fields inside an enum.
public enum Fields
{
AssignedTo = 1,
CloseReason = 2,
CustomerId = 3,
CustomerName = 4,
CompanyID = 5,
CompanyName = 6
}
If you skip the assigning part , it will by default start assign the fields starting from integer 0.
I do not think you want to be using enum for a drop down. Try looking into Dictionary or DataTable or some other structures. Maybe we could help if you give us more detail about what exactly are you trying to do.
EDIT: Here is a simple example of using List<string> as data source for ComboBox
List<string> dsList = new List<string>();
dsList.Add("Assigned To");
dsList.Add("Close Reason");
dsList.Add("Customer ID");
dsList.Add("Customer Name");
dsList.Add("Company ID");
dsList.Add("Company Name");
comboBox1.DataSource = dsList;
Also, you can dynamicaly change the List based on what options you want to display to the user

C# Newbie needs help: convert enum to string

I am a programming novice. I would like to convert ComputerHand and PlayerHand to strings so I can then create an string array to write to a text file.
public enum Hand { Rock = 1, Paper, Scissors };
public enum Outcome { Win, Lose, Tie };
public Hand ComputerHand { get; set; }
public Hand PlayerHand { get; set; }
public char UserSelection { get; set; }
Given below Enum,
public enum AnEnum
{
Value1,
Value2,
Value3
}
Short answer: AnEnum.Value1.ToString()
If you want to give a different details (friendlier string) to enum value, you can use "Description" attribute to enum. See this: How can I assign a string to an enum instead of an integer value in C#?
If you are dealing with enum <-> string, you may sometime want to convert string to an enum, which can be done like this:
AnEnum AnEnumValue = (AnEnum ) Enum.Parse(typeof(AnEnum ), "Value1", true);
Just for someone's benefit who is working with enum ans strings, if you want to make an array of string from enum values,
string[] arrayOfEnumStrings
= Enum.GetValues(typeof(AnEnum)).Cast<AnEnum>()
.Select(enumVal=> enumVal.ToString()).ToArray();
Here, "Enum.GetValues(typeof(Foos)).Cast()" will get you enumurator of enum values. Then "Select" will convert those enum values to string.

Serialize Flags enum with two equal values

I want to define a flag enum like the following:
[Flags]
[Serializable]
public enum Numbers
{
[XmlEnum(Name = "One")]
One = 0x1,
[XmlEnum(Name = "Two")]
Two = 0x2,
[XmlEnum(Name = "Three")]
Three = 0x4,
[XmlEnum(Name = "OddNumbers")]
OddNumbers = One | Three,
[XmlEnum(Name = "EvenNumbers")]
EvenNumbers = Two,
[XmlEnum(Name = "AllNumbers")]
AllNumbers = One | Two | Three
}
Suppose I create an object which has a Numbers property and I set that property to EvenNumbers. Today, only Two is included in property, but I want to specify EvenNumbers so that if I add Four in the future it will be included in the property as well.
However, if I serialize this object using XmlSerializer.Serialize, the XML will say Two because today this is the same underlying value.
How can I force the serializer to serialize this property as EvenNumbers?
Do something like that: Mark the Number property as XmlIgnore and create another property type of string for return the string value of enum.
[Serializable]
public class NumberManager
{
[XmlIgnore]
public Numbers Numbers { get; set; }
[XmlAttribute(AttributeName="Numbers")]
public string NumbersString
{
get { return Numbers.ToString(); }
set { Numbers = (Numbers) Enum.Parse(typeof (Numbers), value); }
}
}
Then serialize the NumberManager.
I hope it helps.

ServiceStack.Text.EnumMemberSerializer not working with Swagger plugin

I'm using ServiceStack v 3.9.71 and the ServiceStack.Text.EnumMemberSerializer assembly to serialize enums into readable text.
This works great, my enum values are serialized into the name I've specified using the EnumMemberAttribute.
The problem, though, is Swagger does not use my names. My guess is it just calls the .ToString() method on the enum values rather than the EnumMemberAttribute value.
Here is the order in which I setup the serialization. (In AppHost):
new EnumSerializerConfigurator()
.WithEnumTypes(new Type[] { typeof(MyEnum) })
.Configure();
Plugins.Add(new SwaggerFeature());
It doesn't seem to matter if the enum serializer is set before or after the swagger feature is added.
You are correct that the Swagger code does not use ServiceStack.Text.EnumMemberSerializer when parsing enum values. It only uses an Enum.GetValues here. Note that this is still the same in v4.
You can submit a pull request to make this change, but I'm not familiar with EnumMemberSerialzer and how it allows for retrieving the list of enum options. You may instead be able to use a string property decorated with ApiAllowableValues to achieve the affect.
Here is the solution I came up with (with the help of bpruitt-goddard, thanks mate):
The enum:
public enum MyEnum
{
[EnumMember(Value = "Value One")]
Value1 = 1,
[EnumMember(Value = "Value Two")]
Value2 = 2,
[EnumMember(Value = "Value Three")]
Value3 = 3
}
The client object:
public class MyClientObject
{
[Description("The name")]
public string Name {get;set;}
[Description("The client object type")]
[ApiAllowableValues("MyEnum", "Value One", "Value Two", "Value Three")]
public MyEnum MyEnum { get; set; }
}
Inside the AppHost:
new EnumSerializerConfigurator()
.WithEnumTypes(new Type[] { typeof(MyEnum) })
.Configure();
Now the enum is serialized properly and the Swagger documentation is correct. The only issue with this is having the names in two different places. Perhaps there is a way to check the names match via a unit test.
I came up with, in my opinion, a better solution. I wrote a class that extends the ApiAllowableValuesAttribute:
public class ApiAllowableValues2Attribute : ApiAllowableValuesAttribute
{
public ApiAllowableValues2Attribute(string name, Type enumType)
: base(name)
{
List<string> values = new List<string>();
var enumTypeValues = Enum.GetValues(enumType);
// loop through each enum value
foreach (var etValue in enumTypeValues)
{
// get the member in order to get the enumMemberAttribute
var member = enumType.GetMember(
Enum.GetName(enumType, etValue)).First();
// get the enumMember attribute
var enumMemberAttr = member.GetCustomAttributes(
typeof(System.Runtime.Serialization.EnumMemberAttribute), true).First();
// get the enumMember attribute value
var enumMemberValue = ((System.Runtime.Serialization.EnumMemberAttribute)enumMemberAttr).Value;
values.Add(enumMemberValue);
}
Values = values.ToArray();
}
}
The client object:
public class MyClientObject
{
[Description("The name")]
public string Name {get;set;}
[Description("The client object type")]
[ApiAllowableValues2("MyEnum", typeof(MyEnum))]
public MyEnum MyEnum { get; set; }
}
Now you don't have to specify the names again or worry about a name change breaking your Swagger documentation.

Set one enum equal to another

I have 2 enums in 2 different objects. I want to set the enum in object #1 equal to the enum in object #2.
Here are my objects:
namespace MVC1 {
public enum MyEnum {
firstName,
lastName
}
public class Obj1{
public MyEnum enum1;
}
}
namespace MVC2 {
public enum MyEnum {
firstName,
lastName
}
public class Obj2{
public MyEnum enum1;
}
}
I want to do this, but this wont compile:
MVC1.Obj1 obj1 = new MVC1.Obj1();
MVC2.Obj2 obj2 = new MVC2.Obj2();
obj1.enum1 = obj2.enum1; //I know this won't work.
How do I set the enum in Obj1 equal to the enum in Obj2? Thanks
Assuming that you keep them the same, you can cast to/from int:
obj1.enum1 = (MVC1.MyEnum)((int)obj2.enum1);
Enums have an underlying integer type, which is int (System.Int32) by default, but you can explicitly specify it too, by using "enum MyEnum : type".
Because you're working in two different namespaces, the Enum types are essentially different, but because their underlying type is the same, you can just cast them:
obj1.enum1 = (MVC1.MyEnum) obj2.enum1;
A note: In C# you have to use parentheses for function calls, even when there aren't any parameters. You should add them to the constructor calls.
Best way to do it is check if it's in range using Enum.IsDefined:
int one = (int)obj2.enum1;
if (Enum.IsDefined(typeof(MVC1.MyEnum), one )) {
obj1.enum1 = (MVC1.MyEnum)one;
}
obj1.enum1 = (MVC1.MyEnum) Enum.Parse(typeof(MVC1.MyEnum),
((int)obj2.enum1).ToString());
or
int one = (int)obj2.enum1;
obj1.enum1 = (MVC1.MyEnum)one;

Categories