Browse Source

initial commit

master
Scott Barker 8 years ago
commit
c52a10ec99
4 changed files with 283 additions and 0 deletions
  1. 4
    0
      .gitignore
  2. 36
    0
      Properties/AssemblyInfo.cs
  3. 183
    0
      RouteCollectionExtensions.cs
  4. 60
    0
      RouteCollectionExtensions.csproj

+ 4
- 0
.gitignore View File

@@ -0,0 +1,4 @@
obj
bin
packages/*
!packages/repositories.config

+ 36
- 0
Properties/AssemblyInfo.cs View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RouteCollectionExtensions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("RouteCollectionExtensions")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b22aff0-350d-4b1a-a72c-07442e3e040b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

+ 183
- 0
RouteCollectionExtensions.cs View File

@@ -0,0 +1,183 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Reflection;
using System.Web;
using System.Web.Routing;
namespace Sdbarker.Extensions.RouteCollectionExtenions {
public static class RouteCollectionExtensions {
/// <summary>
/// Maps a URL route and sets the default values.
/// </summary>
/// <typeparam name="TController"></typeparam>
/// <param name="action">The method that this route will call on the specified controller.</param>
/// <param name="name">Optional: A string that specifies the name of the route (automatically generated as ControllerMethod if null or empty)</param>
/// <param name="url">Optional: A string that specifies the URL for the route (automatically generated as Controller/Method if null or empty)</param>
/// <param name="defaults">Optional: An object that contains default route values.</param>
/// <param name="constraints">Optional: An object that specifies the contraints of the route.</param>
/// <returns>The generated Route object.</returns>
public static Route MapDefaultRoute(this RouteCollection routes) {
return routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
public static Route MapRoute<TController>(this RouteCollection routes, Expression<Func<TController, ActionResult>> action, string name = null, string url = null, object defaults = null, object constraints = null) where TController : IController {
MethodCallExpression m = (MethodCallExpression)action.Body;
if (m.Method.ReturnType != typeof(ActionResult)) {
throw new ArgumentException("ControllerAction method '" + m.Method.Name + "' does not return type ActionResult");
}
if (string.IsNullOrEmpty(name)) {
name = typeof(TController).Name + m.Method.Name;
}
if (string.IsNullOrEmpty(url)) {
url = string.Format("{0}/{1}", typeof(TController).Name.RemoveLastInstanceOf("Controller"), m.Method.Name);
}
if (defaults == null) {
defaults = new { action = m.Method.Name };
}
else {
defaults = new RouteValueDictionary(defaults);
(defaults as RouteValueDictionary).Add("action", m.Method.Name);
}
return routes.MapRoute<TController>(name, url, defaults, constraints);
}
private static Route MapRoute<TController>(this RouteCollection routes, string name, string url, object defaults, object constraints) where TController : IController {
Route route = new Route(url, new MvcRouteHandler()) {
Defaults = (defaults is RouteValueDictionary) ? (defaults as RouteValueDictionary) : new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints)
};
// If a controller property was specified in the defaults, argument exception; someone is doing something that they're not aware of
string controller = typeof(TController).Name.RemoveLastInstanceOf("Controller");
if (route.Defaults.ContainsKey("controller")) {
throw new ArgumentException("Defaults contains key 'controller', but using a strongly typed route.");
// route.Defaults["controller"] = controller;
}
else {
route.Defaults.Add("controller", controller);
}
// Move the original action (which is really a ControllerAction) to the controllerAction key
// and then specify our own action value, otherwise routing will flip out
object action = null;
if (route.Defaults.TryGetValue("action", out action)) {
if (action.GetType().IsGenericType && action.GetType().GetGenericTypeDefinition() == typeof(ControllerAction<>)) {
route.Defaults.Add("controllerAction", route.Defaults["action"]);
route.Defaults["action"] = route.Defaults["controllerAction"].ToString();
}
}
routes.Add(name, route);
return route;
}
private static string RemoveLastInstanceOf(this string text, string remove) {
return text.Remove(text.LastIndexOf(remove));
}
}
public class ControllerAction<TController> where TController : IController {
public string Action { get; private set; }
public override string ToString() {
return Action;
}
public static implicit operator string(ControllerAction<TController> controllerAction) {
return controllerAction.Action;
}
public ControllerAction(Expression<Func<TController, ActionResult>> action) {
MethodCallExpression m = (MethodCallExpression)action.Body;
if (m.Method.ReturnType != typeof(ActionResult)) {
throw new ArgumentException("ControllerAction method '" + m.Method.Name + "' does not return type ActionResult");
}
Action = m.Method.Name;
}
}
}
/*
public interface IFluentRoute<TController> {
IFluentRoute<TController> WithAction(Expression<Func<TController, ActionResult>> action);
IFluentRoute<TController> WithName(string name);
IFluentRoute<TController> WithUrl(string url);
IFluentRoute<TController> WithDefault(string key, object value);
Route MapRoute();
}
public class FluentRoute<TController> : IFluentRoute<TController> {
private string _name;
public string Name {
get {
return _name;
}
}
private string _url;
public string Url {
get {
return _url;
}
}
private RouteValueDictionary _defaults = new RouteValueDictionary();
public RouteValueDictionary Defaults {
get {
return _defaults;
}
}
public FluentRoute() {
}
public IFluentRoute<TController> WithAction(Expression<Func<TController, ActionResult>> action) {
MethodCallExpression m = (MethodCallExpression)action.Body;
if (m.Method.ReturnType != typeof(ActionResult)) {
throw new ArgumentException("ControllerAction method '" + m.Method.Name + "' does not return type ActionResult");
}
_name = typeof(TController).Name + m.Method.Name;
_url = string.Format("{0}/{1}", typeof(TController).Name.RemoveLastInstanceOf("Controller"), m.Method.Name);
_defaults.Add("controller", typeof(TController).Name.RemoveLastInstanceOf("Controller"));
_defaults.Add("action", m.Method.Name);
return this;
}
public IFluentRoute<TController> WithName(string name) {
_name = name;
return this;
}
public IFluentRoute<TController> WithUrl(string url) {
_url = url;
return this;
}
public IFluentRoute<TController> WithDefault(string key, object value) {
_defaults.Add(key, value);
return this;
}
public Route MapRoute() {
RouteCollection routes = RouteTable.Routes;
Route r = routes.MapRoute(this.Name, this.Url, this.Defaults);
return r;
}
}
public static class StringExtensions {
public static string RemoveLastInstanceOf(this string text, string remove) {
return text.Remove(text.LastIndexOf(remove));
}
}
*/

+ 60
- 0
RouteCollectionExtensions.csproj View File

@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{73F1C5A6-D968-47E9-96F0-CB23FD22AAD8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RouteCollectionExtensions</RootNamespace>
<AssemblyName>RouteCollectionExtensions</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.Routing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RouteCollectionExtensions.cs" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Loading…
Cancel
Save