Skip to content

Instantly share code, notes, and snippets.

@EdCharbeneau
Last active May 3, 2020 14:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdCharbeneau/674219074709983064d81a473a45547c to your computer and use it in GitHub Desktop.
Save EdCharbeneau/674219074709983064d81a473a45547c to your computer and use it in GitHub Desktop.
Create a menu from Application components.
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