Geeks With Blogs
.Nettuce Code Salad
public class RouteFor<T>
{
    readonly string path;
    string verbs;
 
    public static string Path
    {
        get
        {
            return GetRouteAttribute().Path;
        }
    }
 
    public static string Verbs
    {
        get
        {
            return GetRouteAttribute().Verbs;
        }
    }
 
    static RouteAttribute GetRouteAttribute()
    {
        var routeAttribute = TypeDescriptor.GetAttributes(typeof(T)).OfType<RouteAttribute>().SingleOrDefault();
        if (routeAttribute == null)
            throw new NullReferenceException(string.Format("Route not defined for {0}"typeof(T).Name));
        return routeAttribute;
    }
 
    RouteFor(string path)
    {
        this.path = path;
        AndVerbs(HttpMethods.AllVerbs.ToArray());
        AddOrUpdateAttribute();
    }
 
    public static RouteFor<T> WithDefaultPath()
    {
        return new RouteFor<T>("/" + typeof(T).Name);
    }
 
    public static RouteFor<T> WithPath(string path)
    {
        return new RouteFor<T>(path);
    }
 
    public static RouteFor<T> WithPath(string path, params Expression<Func<T, object>>[] expressions)
    {
        return WithPath(FormatRoute(path, expressions));
    }
 
    static string FormatRoute(string path, params Expression<Func<T, object>>[] propertyExpressions)
    {
        path = Regex.Replace(path, "({\\D*})""{${1}}");
        var properties = propertyExpressions.Select(x => string.Format("{{{0}}}", PropertyName(x))).ToArray();
        return string.Format(path, properties);
    }
 
    public RouteFor<T> AndVerbs(params string[] verbs)
    {
        this.verbs = string.Join(",", verbs);
        AddOrUpdateAttribute();
        return this;
    }
 
    void AddOrUpdateAttribute()
    {
 
        var attribute = TypeDescriptor.GetAttributes(typeof(T)).OfType<RouteAttribute>().SingleOrDefault();
        if (attribute == null)
            TypeDescriptor.AddAttributes(typeof(T), new RouteAttribute(path, verbs));
        else
        {
            attribute.Path = path;
            attribute.Verbs = verbs;
        }
    }
 
    public void Create()
    {
        if (EndpointHostConfig.Instance.ServiceManager != null)
            EndpointHostConfig.Instance.ServiceManager.ServiceController.RegisterRestPaths(typeof(T));
    }
 
    static string PropertyName(LambdaExpression propertyExpression)
    {
        return (propertyExpression.Body is UnaryExpression ? (MemberExpression)((UnaryExpression)propertyExpression.Body).Operand : (MemberExpression)propertyExpression.Body).Member.Name;
    }
}
Posted on Wednesday, June 12, 2013 7:17 PM | Back to top


Comments on this post: ServiceStack dynamic Route Attribute creator

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net