Last active
May 3, 2020 14:28
-
-
Save EdCharbeneau/674219074709983064d81a473a45547c to your computer and use it in GitHub Desktop.
Create a menu from Application components.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Components; | |
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text.RegularExpressions; | |
public static class ExampleMetadata | |
{ | |
public static IEnumerable<MenuItem> GetItems() | |
{ | |
return Assembly | |
.GetExecutingAssembly() | |
.ExportedTypes | |
.Select(t => MenuItem.From(t)) | |
.Where(ri => !string.IsNullOrEmpty(ri.Route)); | |
} | |
public class MenuItem | |
{ | |
public string Route { get; private set; } | |
public string ComponentName { get; private set; } | |
public string Name { get; private set; } | |
public string ShortName { get; private set; } | |
public static MenuItem From(Type type) | |
{ | |
var routeAttribute = type.GetCustomAttribute<RouteAttribute>(); | |
var displayAttribute = type.GetCustomAttribute<DisplayAttribute>(); | |
bool hasName = !string.IsNullOrEmpty(displayAttribute?.Name); | |
var hasShortName = !string.IsNullOrEmpty(displayAttribute?.ShortName); | |
static string FromCamelCase(string s) => Regex.Replace(s, "(\\B[A-Z])", " $1"); | |
return new MenuItem | |
{ | |
Route = routeAttribute?.Template, | |
ComponentName = type.Name, | |
Name = hasName ? displayAttribute.Name : FromCamelCase(type.Name), | |
ShortName = hasShortName ? displayAttribute.ShortName : type.Name | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment