Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created July 8, 2018 06:42
Show Gist options
  • Save danielplawgo/ddb40a4da31c8ffc1879d7e7ca0b00ea to your computer and use it in GitHub Desktop.
Save danielplawgo/ddb40a4da31c8ffc1879d7e7ca0b00ea to your computer and use it in GitHub Desktop.
Lokalizacja Enum
public class EnumDescriptionAttribute : Attribute
{
public Type ResourceType { get; set; }
public EnumDescriptionAttribute(Type resourceType)
{
ResourceType = resourceType;
}
}
public static class EnumExtensions
{
public static string ToDisplayString(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string description = value.ToString();
EnumDescriptionAttribute[] attributes = (EnumDescriptionAttribute[])value.GetType().GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
Type resourceType = attributes[0].ResourceType;
if (resourceType != null)
{
var property = resourceType.GetProperty(description);
if (property != null)
{
var propertyValue = property.GetValue(null);
if (propertyValue != null)
{
description = propertyValue.ToString();
}
}
}
}
return description;
}
}
public class EnumsProfile : Profile
{
public EnumsProfile()
{
CreateMap<Enum, string>()
.ConvertUsing<EnumToStringConverter>();
}
}
public class EnumToStringConverter : ITypeConverter<Enum, string>
{
public string Convert(Enum source, string destination, ResolutionContext context)
{
return source.ToDisplayString();
}
}
public class Order
{
public string Number { get; set; }
public OrderStatus Status { get; set; }
}
public class OrdersController : Controller
{
private static IEnumerable<Order> _orders;
static OrdersController()
{
int orderNumber = 0;
_orders = new Faker<Order>()
.StrictMode(true)
.RuleFor(u => u.Status, (f, u) => f.PickRandom<OrderStatus>())
.RuleFor(u => u.Number, (f, u) => (++orderNumber).ToString())
.Generate(10);
}
private Lazy<IMapper> _mapper;
protected IMapper Mapper
{
get { return _mapper.Value; }
}
public OrdersController(Lazy<IMapper> mapper)
{
_mapper = mapper;
}
// GET: Orders
public ActionResult Index()
{
var viewModel = new IndexViewModel();
viewModel.Items = Mapper.Map<IEnumerable<OrderViewModel>>(_orders);
return View(viewModel);
}
}
public class OrdersProfile : Profile
{
public OrdersProfile()
{
CreateMap<Order, OrderViewModel>();
}
}
public enum OrderStatus
{
Created,
Completed,
Canceled
}
[EnumDescription(typeof(OrderStatusResources))]
public enum OrderStatus
{
Created,
Completed,
Canceled
}
public class OrderViewModel
{
public string Number { get; set; }
public string Status { get; set; }
}
var status = OrderStatus.Completed;
var display = status.ToDisplayString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment