eWorld.UI - Matt Hawley

Ramblings of Matt

Extending WikiPlex with Custom Renderers

July 30, 2009 13:22 by matthaw

Following up from my prior post on Extending WikiPlex with Custom Macros it's now time to talk about creating custom renderers. When we left off, we had created our title link macro and registered it with WikiPlex. If you had attempted to utilize the new macro in wiki content, you'd get the message "Cannot resolve macro, as no renderers were found." instead of a hyperlink. This was the expected behavior, because while you had identified your new scope via parsing, you were missing that critical link of turning the scope into actual content. Let's take a look at our scenario again to refresh what we're trying to achieve:


We would like to integrate WikiPlex into an existing application. The idea is to allow a user contributed area specifically for wiki content. The user should be allowed to use all out-of-the-box macros provided, but also have the ability to have inter-wiki links with the format of [Title of Page]. As you probably realized, there is currently no macro/renderer that will take that content and turn it into a inter-wiki link, so we'll have to extend WikiPlex adding this functionality.

Create a Renderer

Creating a renderer is actually the easiest portion of defining new wiki syntaxes, as it's as complicated as you need to make it. Again, a renderer simply takes in a scope (which is a contextual identifier), processes the content, and returns new content. Let's get started - so in your solution, create a class called TitleLinkRenderer and extend it from WikiPlex.Formatting.IRenderer. You'll then implement the members it requires (Id, CanExpand and Expand). The Id value is simply a string that is used as a key for static renderer registration, so it should be unique (follow the same rule of thumb for naming as the macros).


Next, you'll implement the CanExpand method. This method simply takes in a scope name and returns a boolean value indicating if this renderer can expand (or render) the scope successfully. As the formatter is processing all scopes, it goes through the list of renderers in the formatter and finds the first match that can expand that particular scope. There is no guarantee of the order of checking renderers, so always unregister a renderer you're overriding its implementation for. As you'll see below, the CanExpand method is fairly trivial, however should your renderer support a number of scopes, you'll need to change this code to include all of them.

public bool CanExpand(string scopeName)
   return scopeName == WikiScopeName.WikiLink;

Next, you'll implement the Expand method. This method will take in a scope name, the related input from the wiki source, and html / attribute encoding functions. The reason we're passing in html / attribute encoding functions, is so that you can utilize a consistent encoding scheme across all of the renderers. Out of the box, WikiPlex uses HttpUtility.HtmlEncode and HttpUtility.HtmlAttributeEncode, but by creating & supplying your own formatter, you can change these to use another library (like AntiXss). As previously stated, rendering is as hard as you need it to be. In the sample application example, we're just rendering a link utilizing the ASP.NET MVC UrlHelper (which is supplied via the constructor).

private const string LinkFormat = "<a href=\"{0}\">{1}</a>";

public string Expand(string scopeName, string input,
                     Func<string, string> htmlEncode, 
                     Func<string, string> attributeEncode)
   string url = urlHelper.RouteUrl("Default", new { slug = SlugHelper.Generate(input) });
   return string.Format(LinkFormat, attributeEncode(url), htmlEncode(input));

And now you have created your renderer, however it will still not be picked up when rendering your wiki content as you need to register the renderer with WikiPlex.


Registering a Renderer

Just as registering a macro, you have a static and a dynamic way to register your renderers. If your renderer requires only static dependencies (or no external runtime dependencies), you should opt for statically registering your renderer. To do this, have the following code in your application startup method


When you call the WikiEngine.Render("content"), it will automatically pick up all statically defined renderers and use them when formatting your scopes. As previously stated, if you have external runtime dependencies (like in our example), a little bit of extra work is required when calling WikiEngine.Render - as you'll need to pass in a MacroFormatter instead. However, if you utilize the overload to only take in a formatter, you'll need to union the statically defined renderers with yours.

private MacroFormatter GetFormatter()
   var siteRenderers = new IRenderer[] {new TitleLinkRenderer(Url)};
   IEnumerable<IRenderer> allRenderers = Renderers.All.Union(siteRenderers);
   return new MacroFormatter(allRenderers);

Now, when you call WikiEngine.Render, you'll utilize the overload that takes in an IFormatter as a parameter. After you've set all of this up, try re-loading your page and you should see your syntax of [Title Link] be converted into the html <a href="/title-link">Title Link</a>.



You now have a new fully functioning macro syntax. Obviously, this example is trivial - but I guarantee if you embed WikiPlex into your application and need any cross-page linking, you'll utilize this macro & renderer. Again, the possibilities are endless with what you can do, so long as you have a syntax, regex, and rendering code - you can allow your users to simply include expansive macros.


Download WikiPlex now!


kick it on DotNetKicks.com

Extending WikiPlex with Custom Macros

July 24, 2009 18:47 by matthaw

One of the very nice features of WikiPlex is the ability to extend it to your hearts desire. The API is completely open, and the entry points off of WikiEngine are merely wrappers. This means that, if you really wanted to, you could create your own parser and formatter - but the majority of extending WikiPlex will be done via macros and renderers. A summary of the extension points include:

  1. Macros encapsulate rules for matching segments of content.
  2. Macro rules are regular expressions that map matches to scopes.
  3. Scopes are contextual identifiers.
  4. Renderers take scopes and expand them into a HTML formatted representation of the macro.

We would like to integrate WikiPlex into an existing application. The idea is to allow a user contributed area specifically for wiki content. The user should be allowed to use all out-of-the-box macros provided, but also have the ability to have inter-wiki links with the format of [Title of Page]. As you probably realized, there is currently no macro/renderer that will take that content and turn it into a inter-wiki link, so we'll have to extend WikiPlex adding this functionality.


Create a Macro

When creating a macro, you're going to have to dust off that copy of RegexBuddy you probably don't have installed anymore. Why? Well, as previously stated, macro rules are regular expressions - and unless you're a regex guru, you won't be able to do this ad-hoc without a great tool. Let's get started - so in your solution, create a class called TitleLinkMacro, and extend it from WikiPlex.Compilation.Macros.IMacro. You'll then implement the members it requires (Id and Rules). The Id value is simply a string that is used as a key for static macro registration and macro compilation, so it should be unique (rule of thumb, give it the name of your class but with spaces). Now, it's time to define your macro rules.


As you may have noticed, I kept "rule" plural. The reason, is that the majority of macros you will create need to have an initial "escaped" rule. This rule basically stops the regex from matching within code blocks, between curly braces, and possibly between square brackets. Since our macro utilizes square brackets, we'll use the escape rule of CurlyBraceEscape.


Next, you'll define your regex (with extreme caution!) utilizing capturing groups to identify scopes. If you take a look at the code, you may not think that the scope identification is zero based - don't be fooled, it really is! Identifying an index 0 scope indicates the full match for that rule. When creating your capturing groups, you can have any number, allowing for fine granularity when rendering. So, let's take a look at the sample project's macro's rules.

public IList<MacroRule> {
   get {
      return new List<MacroRule> {
         new MacroRule(EscapeRegexPatterns.CurlyBraceEscape),
         new MacroRule(@"(?i)(\[)(?!\#|[a-z]+:)((?>[^\]]+))(\])",
                 new Dictionary<int, string> {
                    { 1, ScopeName.Remove },
                    { 2, WikiScopeName.WikiLink },
                    { 3, ScopeName.Remove }

As you can see, the regular expression is indicating that I should match 3 scopes per overall match. The scope "Remove" does just that. It removes the captured content when rendering. The WikiLink scope name is one that was created specifically for the sample. For the non-regex savvy developer, the regex reads:

  1. Use case insensitive matching from this point on
  2. Match the character "["
  3. Match any character until "]" is found
    1. But do not match if the character is preceded
      1. by the "#" character
      2. or by any character between a-z, one or more times, followed by a ":" character
  4. Match the character "]"

Our scope to step matching then is

  1. Remove "["
  2. WikiLink any content
  3. Remove "]"

Defining macro rules is a fairly straight forward process, just keep in mind that the order of the macro rules is important! You should also realize that if you wish to allow nesting of rules (for example, italicize bolded text) the italics and bold macro rules cannot be apart of the same macro. This, again, is because the macro rules are combined to build a large regular expression - and each rule is treated as an "or" statement.


Registering a Macro

After you have created your macro, you need to register it with WikiPlex. You have two ways of doing this - statically and dynamically. When statically registering macros, you simply need to have the following code in your application startup method


When you call the WikiEngine.Render("content"), it will automatically pick up your macro, compile it, and use it when parsing the wiki content. Dynamically loading your macros is useful when you require a different set of macros to be executed than what is normally registered. For example, in CodePlex - we have a different set of allowed macros between editing a project's wiki content and editing your personal statement. Dynamically loading is achieved by utilizing one of the WikiEngine.Render overloads:

WikiEngine.Render("content", new IMacro[] { new WikiTitleLinkMacro() });

The only caveat of this approach, is that it will only use that macro when parsing your wiki content.



This is just the tip of the extensibility for WikiPlex. Creating your own macro is a great. Simply be cautious of your regular expression as it could have negative side effects (catastrophic backtracking) that will bring your site to a screeching halt! In the next installment, we'll take this scenario to the next step by creating a renderer for your macro.


Download WikiPlex now!


kick it on DotNetKicks.com

Categories: .NET | CodePlex | WikiPlex
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

WikiPlex – An Embedded Wiki Engine

July 16, 2009 11:04 by matthaw

What and Why?

I'd like to introduce you to WikiPlex, which is CodePlex's wiki engine that we have re-written and made open source under the MS-PL license. I'm also happy to announce that our first public release is now available!


CodePlex previously had a decent wiki engine that was written eon's ago. On the average, that wiki engine worked relatively well, but had a very problematic performance bug that would cause rendering slowness occasionally. So, instead of attempting to fix the bug, we decided to re-write the entire thing with the intensions of making it available to everyone! This time, we chose a different approach for parsing the wiki markup (utilizing regular expressions) which has proven to give us a performance boost as well as a relatively simpler architecture!


The main question you may be asking yourself is - Why use WikiPlex over a different solution? Here's the simple answer: WikiPlex is great if you already have a .NET application you'd like to embed a wiki interface into. Be it as simple as allowing users to host their own homepage content, item descriptions, or comments - the possibilities are endless!



WikiPlex was built in a way that it can easily be added into your infrastructure. Whether your using dependency injection or not, the code is as simple as the following:

var engine = new WikiPlex.WikiEngine();
string output = engine.Render("This is my wiki source!");

If you take a look at the overloads for Render, you'll see that you have a lot of flexibility as far as rendering various wiki segments differently at runtime. (I'll describe the extensibility in the future)

public interface IWikiEngine
   string Render(string wikiContent);
   string Render(string wikiContent, IFormatter formatter);
   string Render(string wikiContent, IEnumerable<IMacro> macros);
   string Render(string wikiContent, IEnumerable<IMacro> macros, IFormatter formatter);

Supported Macros

The following are the macros supported out of the box for WikiPlex. If you'd like to see the description and usage, please visit the markup guide.

  • Text Formatting
    • Bold
    • Italics
    • Underline
    • Strikethrough
    • Superscript
    • Subscript
  • Headings
  • Images
  • Links
  • Tables
  • Left and Right Aligned Text
  • Ordered and Unordered Lists
  • RSS / Atom Feeds
  • Source Code Blocks (both syntax highlighted and not)
  • Silverlight
  • Videos (Flash, Quicktime, Real, Soapbox, Windows Media, and YouTube)

Enjoy! And don't forget to download WikiPlex now!


kick it on DotNetKicks.com

MEF + Factories Using an Export Provider

November 29, 2008 10:25 by matthaw

After my last post about MEF + Factories, I was chatting with Glenn Block (PM for MEF) about my approach. One of the first things he mentioned is why I hadn't used an ExportProvider. As you know, ExportProvider's are new in the latest drop, and provide an interception point for resolving an import to an export.


Taking a look back at the documentation on ComposablePart, I can see why Glenn mentioned this. In it, it states that a ComposoblePart must adhere to to Import/Export contracts. If you've looked at the prior example, you'll see that I'm explicitly violating that rule as I'm finding interfaces based on a base interface, not by Export! At this point, my mind started churning - mainly because there's not a lot of examples or descriptions of what an ExportProvider actually is - but because I wanted to do things "correctly" according to the framework provided. (As an aside, Glenn stated that a "What is an Export Provider" post or documentation is coming, maybe this'll boost that necessity!) What I ultimately came up with was a much cleaner solution than using a FactoryPartCatalog.


Introducing FactoryExportProvider:

   1:  public class FactoryExportProvider<T> : ExportProvider {
   2:     public FactoryExportProvider(Func<Type, T> resolutionMethod) { }
   3:     public FactoryExportProvider(Assembly assembly, Func<Type, T> resolutionMethod) { }
   4:     public FactoryExportProvider(IEnumerable<Type> types, Func<Type, T> resolutionMethod { }
   5:  }

What you'll see is again, it's very straight forward and provides a clean implementation in usage, just as the part catalog example did. Each constructor does just as it had done in the part catalog, so I'll not explain that again. One thing that I discussed with Glenn about was, is it appropriate to look for certain types within an Export Provider? His response was "absolutely you can do that". good, I think I've found the correct implementation, both from less code/object graph standpoint, but also from an intention standpoint.


Internally, the code is very simplistic. Since I'm finding these interfaces on-the-fly, and need more information than just the contract name, I needed to use a FactoryExportDefinition to store this information. I've you've looked at the prior example, you'll see this came back out of necessity.

   1:  public class FactoryExportDefinition<T> : ExportDefinition {
   2:     public FactoryExportDefinition(string contractName, Type type, Func<Type, T> resolutionMethod) { }
   4:     public override string ContractName { get { ... } }
   5:     public Type ServiceType { get; private set; }
   6:     public Func<Type, T> ResolutionMethod { get; private set; }
   7:  }

When finding all of the interfaces that implement the base interface specified in the FactoryExportProvider, I convert those into a list of FactoryExportDefinition objects. Reason being, is that the export provider compares an ImportDefinition to an ExportDefinition when finding all available exports. This comparison is done by implementing the GetExportsCore method. The idea of export providers, is that when resolving all dependencies, MEF will call into all of the registered ExportProviders to determine if they can supply the Export and will do a bunch of cardinality matching for you. Out of the box, MEF provides an export provider for it's registered part catalogs. Here's the FactoryExportProvider's implementation of GetExportsCore.

   1:  protected override IEnumerable<Export> GetExportsCore(ImportDefinition importDefinition) {
   2:     IList<Export> exports = new List<Export>();
   3:     var constraint = importDefinition.Constraint.Compile();
   4:     var foundExports = from d in definitions
   5:                        where constraint(d)
   6:                        select new Export(d, () => d.ResolutionMethod(d.ServiceType));
   8:     if (importDefinition.Cardinality == ImportCardinality.ZeroOrMore)
   9:        exports = foundExports.ToList();
  10:     else if (foundExports.Count() == 1)
  11:        exports.Add(foundExports.First());
  13:     return exports;
  14:  }

It's that simple. The Export's that are returned will have the resolution method called when the actual object is needed. When it comes down to including this within your application, it's just as easy as it was for the part catalog, you just register things a bit differently.

   1:  public interface IService { }
   2:  public interface IUserService : IService { }
   4:  [Export]
   5:  public class UserController {
   6:     [ImportingConstructor]
   7:     public UserController(IUserService userService) { }
   8:  }
  10:  // in your application
  11:  private void Compose() {
  12:     var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
  13:     var factoryProvider = new FactoryExportProvider<IService>(GetService);
  14:     var container = new CompositionContainer(catalog, factoryProvider);
  15:     container.AddPart(this);
  16:     container.Compose();
  17:  }
  19:  public IService GetService(Type type) { return ... }

And that's it. Ultimately, this leads to a cleaner implementation that uses less types that you have to manage, and, adheres to the correct intentions of the framework. Much thanks to Glenn who I chatted with for several hours last night! You can get the downloadable source here. Enjoy!


kick it on DotNetKicks.com

Categories: .NET | MEF | Programming
Actions: E-mail | Permalink | Comments (6) | Comment RSSRSS comment feed

MEF + Factories

November 27, 2008 13:47 by matthaw

Lately I've been really digging into MEF and have been looking at it's pros & cons, ease of use, extensibility, and the simple DI container that it can provide. I'm not going to give an overview of MEF, as others have done so already. What I am here to show off is a concept that may prove useful for some applications. Many of us use a DI container in very simplistic ways, as well as registering injection strategies during type resolution. If you have no needs of this latter, MEF is very simple and easily fits into your current architecture by not having to change anything but decorating things. For example:

   1:  public interface IUserService { }
   3:  [Export(typeof(IUserService))]
   4:  [CompositionOptions(CreationPolicy = CreationPolicy.Factory)]
   5:  public class UserService : IUserService { }
   7:  [Export]
   8:  public class UserController {
   9:     [ImportingConstructor]
  10:     public UserController(IUserService userService) { }
  11:  }

At MEF's simplistic nature, you see that during construction, our exported services are being imported for us, but only because we don't care about it's construction and assume that generic construction will work. So when we call resolve UserController using MEF, it'll create and inject a new instance of UserService for us.


Now, say we have a need where the construction of IUserService needs to go through a factory. For instance, maybe IUserService is a WCF endpoint, and you have custom logic built into properly constructing the proxy endpoint. Well, MEF can solve this issue for you by exporting methods, but what you have to do is ultimately change your code and have 2 constructors.

   1:  public interface IUserService { }
   3:  // in your application
   4:  [Export(typeof(IUserService))]
   5:  public IUserService ConstructUserService() { return ... }
   7:  [Export]
   8:  public class UserController {
   9:     [ImportingConstructor]
  10:     public UserController([Import(typeof(IUserService))] Func<IUserService> serviceMethod)
  11:         : this(serviceMethod())
  12:     { }
  14:     public UserController(IUserService userService) { }
  15:  }

As you can see, it's not that nice. We need both constructors because one is used in production and one is used for testability. It ultimately leads to a lot of confusion as to why we need it. So, with that in mind, I set out to determine how this pattern could be achieved using MEF, but also provide a seamless transition from a DI world to MEF. Enter, FactoryPartCatalog:

   1:  public class FactoryPartCatalog<T> : ComposablePartCatalog {
   2:     public FactoryPartCatalog(Func<Type, T> resolutionMethod) { }
   3:     public FactoryPartCatalog(Assembly assembly, Func<Type, T> resolutionMethod) { }
   4:     public FactoryPartCatalog(IEnumerable<Type> types, Func<Type, T> resolutionMethod) { }
   6:     public override IQueryable<ComposableDefinition> Parts { get { return ... } }
   7:  }

When we use this in our application, it brings back the simplicity of MEF. What it's doing during construction is looking through the assembly (first two constructors) to find all interfaces that implement type T. The interfaces that it finds will be created into ComposablePart's for MEF's container to utilize. Ultimately, when GetExportedObject<T> is called, it'll execute the resolution method you specified passing in the Type that was requested.


As you can see below, we're using a AggregatingComposablePartCatalog adding our new FactoryPartCatalog and AttributedAssemblyPartCatalog. We've told FactoryPartCatalog to look through the current assembly for all interfaces that derive from IService. Upon construction injection by MEF, it'll find that it's requesting an export of IUserService, find it in the FactoryPartCatalog, and call GetService(Type) to get it's instance.

   1:  public interface IService { }
   2:  public interface IUserService : IService { }
   4:  [Export]
   5:  public class UserController {
   6:     [ImportingConstructor]
   7:     public UserController(IUserService userService) { }
   8:  }
  10:  // in your application
  11:  private void Compose() {
  12:     var catalog = AggregatingComposablePartCatalog();
  13:     catalog.Catalogs.Add(new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
  14:     catalog.Catalogs.Add(new FactoryPartCatalog<IService>(GetService);
  15:     var container = new CompositionContainer(catalog);
  16:     container.AddPart(this);
  17:     container.Compose();
  18:  }
  20:  public IService GetService(Type type) { return ... }

Now, there's a lot more code behind the scenes that is required to get a new Part Catalog up and running, but I'll leave that for you to check out in the downloadable source. As this is purely a proof of concept, I'm sure there's more simplifications or additions that can be added, but for getting this running out of the box in this manner, it works great!


kick it on DotNetKicks.com

Categories: .NET | Development | MEF
Actions: E-mail | Permalink | Comments (6) | Comment RSSRSS comment feed

ASP.NET MVC: Simplified Localization via ViewEngines

October 22, 2008 16:56 by matthaw

Thanks to Brad, he identified a few areas that made things MUCH simpler from my prior implementation. Notably, while you still have your ViewEngine specify "here's your view's path" there's no longer a need for having a new helper, derived classes, etc. This implementation goes back to the simplified HtmlHelper extension in which you can use in any ViewEngine regardless. It also allows you to "replace" the implementation by just changing the namespace, just as you can do with Html and Ajax.


Simplified View Engine

As previously stated, you still need a new view engine and view, because this is the only point in which you can truly grab which view is being rendered. What's nice now, is that it has been simplified down to using the base implementation and only setting a ViewData field in which the Resource extension method picks up and uses.

   1:  public class LocalizationWebFormViewEngine : WebFormViewEngine
   2:  {
   3:      protected override IView CreateView(ControllerContext controllerContext, 
   4:                                                  string viewPath, string masterPath)
   5:      {
   6:          return new LocalizationWebFormView(viewPath, masterPath);
   7:      }
   9:      protected override IView CreatePartialView(ControllerContext controllerContext, 
  10:                                                                            string partialPath)
  11:      {
  12:          return new LocalizationWebFormView(partialPath, null);
  13:      }
  14:  }
  16:  public class LocalizationWebFormView : WebFormView
  17:  {
  18:      internal const string ViewPathKey = "__ViewPath__";
  20:      public LocalizationWebFormView(string viewPath) : base(viewPath)
  21:      {
  22:      }
  24:      public LocalizationWebFormView(string viewPath, string masterPath) 
  25:                : base(viewPath, masterPath)
  26:      {
  27:      }
  29:      public override void Render(ViewContext viewContext, TextWriter writer)
  30:      {
  31:          // there seems to be a bug with RenderPartial tainting the page's view data
  32:          // so we should capture the current view path, and revert back after rendering
  33:          string originalViewPath = (string) viewContext.ViewData[ViewPathKey];
  35:          viewContext.ViewData[ViewPathKey] = ViewPath;
  36:          base.Render(viewContext, writer);
  38:          viewContext.ViewData[ViewPathKey] = originalViewPath;
  39:      }
  40:  }

As you can see, it's much simpler now. Also, it seems as if there's a bug with the current Beta bits when you have a RenderPartial on your page, there's no isolation and the view's path is not correct later. Simple fix by simply grabbing the original view path, setting it to the new path, rendering, and then reverting back.


Getting back to Extension Methods

And now that we have our path again in our ViewData, we can revert back to using extension methods to extract the path when doing both Global and Local resources. As you can see below, should you be using any other ViewEngine it will always work for Global resources.

   1:  public static class ResourceExtensions
   2:  {
   3:      public static string Resource(this Controller controller, string expression, 
   4:                                                    params object[] args)
   5:      {
   6:          ResourceExpressionFields fields = GetResourceFields(expression, "~/");
   7:          return GetGlobalResource(fields, args);
   8:      }
  10:      public static string Resource(this HtmlHelper htmlHelper, 
  11:                                                    string expression, params object[] args)
  12:      {
  13:          string path = (string)htmlHelper.ViewData[LocalizationWebFormView.ViewPathKey];
  14:          if (string.IsNullOrEmpty(path))
  15:              path = "~/";
  17:          ResourceExpressionFields fields = GetResourceFields(expression, path);
  18:          if (!string.IsNullOrEmpty(fields.ClassKey))
  19:              return GetGlobalResource(fields, args);
  21:          return GetLocalResource(path, fields, args);
  22:      }
  24:      static string GetLocalResource(string path, ResourceExpressionFields fields, 
  25:                                                       object[] args)
  26:      {
  27:          return string.Format((string)HttpContext.GetLocalResourceObject(path, 
  28:                                 fields.ResourceKey, CultureInfo.CurrentUICulture), args);
  29:      }
  31:      static string GetGlobalResource(ResourceExpressionFields fields, object[] args)
  32:      {
  33:          return string.Format((string)HttpContext.GetGlobalResourceObject(
  34:               fields.ClassKey, fields.ResourceKey, CultureInfo.CurrentUICulture), args);
  35:      }
  37:      static ResourceExpressionFields GetResourceFields(string expression, 
  38:                                                                string virtualPath)
  39:      {
  40:          var context = new ExpressionBuilderContext(virtualPath);
  41:          var builder = new ResourceExpressionBuilder();
  42:          return (ResourceExpressionFields)builder.ParseExpression(
  43:                                            expression, typeof(string), context);
  44:      }
  45:  }

Again, thanks to Brad, this implementation seems "less dirty". You can download the source for this here.


kick it on DotNetKicks.com

ASP.NET MVC: Localization Delegated via View Engines

October 22, 2008 14:02 by matthaw

Update: Please see this newer post. It simplifies this solution drastically, and I don't recommend this version anymore!



I've previously blogged about how to add localization support within ASP.NET MVC before, but that codebase was based on Preview 3, and now that the beta is out there, the code just doesn't work anymore. Period. The concepts I had originally had put out there really don't fly well in the Beta world, or, within the "real" world in which people are using more than just the WebFormViewEngine for their rendering. So, why is there this big disconnect now? Well. it's not so much that global resources fail to work, it's more local resources don't really apply "generally" anymore.


While looking into a solution, and bouncing ideas off of Phil & Brad, I came to the realization that, just like in the Matrix, "There is no spoon" or rather, replace "spoon" with "view location" and you have your reasoning. Now, before you start ranting, let me explain. Yes, there are physical locations at which your views are located, but what if you're ViewEngine was pulling the view's from a database? No guarantee that a "general" solution could achieve local resource support based on a HtmlHelper extensino. However, if you left the local resource delegation up to a ViewEngine, you can now have a concept of a location in relevance to it. (And yes, the point may be moot if you use a different Resource Provider than the asp.net built-in one)


So where does that leave us? Well, we need a general way to access both global and local resources within a View, and global resources within a Controller. Ultimately, the code used to get the resources hasn't changed from my original implementation, however, because we no longer have that concept of a view location, the new implementation delegates this decision correctly to the view engine. Also, before I show the proof of concept, I want to warn you that the guts for my view rendering logic is nearly a copy from what is in the WebFormView source.


So here's the overall design is as follows:

  1. Any view engine / views can out-of-the-box use "global resources"
  2. A view engine can decide if it's views can participate in "local resources" by supplying it's own implementation.
  3. A controller can request "global resources" for messages it's setting within ViewData.

Now, because I wanted to provide a default implementation for the WebFormViewEngine, the implementation isn't nearly as clean as one would like, but it does work great, and falls back to using non-derived ViewPage's and ViewUserControl's when necessary.


View Implementation

We start by deriving ViewPage and ViewUserControl to support localization. These new implementations will add a ResourceHelper, just like Ajax / Html / Url, so that within your view, you can directly access a resource.

   1:  public class LocalizedViewPage : ViewPage, ILocalizedView
   2:  {
   3:      public ResourceHelper Resource { get; set; }
   4:  }
   6:  public class LocalizedViewPage<TModel> : ViewPage<TModel>, ILocalizedView
   7:      where TModel : class
   8:  {
   9:      public ResourceHelper Resource { get; set; }
  10:  }
  12:  public class LocalizedViewUserControl : ViewUserControl, ILocalizedView
  13:  {
  14:      public ResourceHelper Resource { get; set; }
  15:  }
  17:  public class LocalizedViewUserControl<TModel> : ViewUserControl<TModel>, ILocalizedView
  18:      where TModel : class
  19:  {
  20:      public ResourceHelper Resource { get; set; }
  21:  }

The interface ILocalizedView is simply an abstraction I put out so I could determine what type of View I was working with in the View Engine.


Resource Helper Implementation

The resource helper implementation is very straight forward. As previously stated, ResourceHelper is the base that adds support for global resources. The WebFormResourceHelper is what the new web form view engine implementation uses to add support for both global and local resources. As you'll see, WebFormResourceHelper is initialized with the virtual path of the currently rendering view so that it can correctly find the local resource.

   1:  public static class ResourceExtensions
   2:  {
   3:      public static string Resource(this Controller controller, 
   4:                                         string expression, params object[] args)
   5:      {
   6:          ResourceExpressionFields fields = GetResourceFields(expression, "~/");
   7:          return GetGlobalResource(fields, args);
   8:      }
  10:      internal static string GetGlobalResource(ResourceExpressionFields fields, object[] args)
  11:      {
  12:          return string.Format((string)HttpContext.GetGlobalResourceObject(
  13:                                                      fields.ClassKey, fields.ResourceKey, 
  14:                                                      CultureInfo.CurrentUICulture), args);
  15:      }
  18:      internal static ResourceExpressionFields GetResourceFields(
  19:                                    string expression, string virtualPath)
  20:      {
  21:          var context = new ExpressionBuilderContext(virtualPath);
  22:          var builder = new ResourceExpressionBuilder();
  23:          return (ResourceExpressionFields)builder.ParseExpression(
  24:                                    expression, typeof(string), context);
  25:      }
  26:  }
  28:  public class ResourceHelper
  29:  {
  30:      public virtual string GetString(string expression, params object[] args)
  31:      {
  32:          ResourceExpressionFields fields = GetResourceFields(expression, "~/");
  33:          if (string.IsNullOrEmpty(fields.ClassKey))
  34:              throw new InvalidOperationException(
  35:                       "The resource helper does not support local resources.");
  37:          return GetGlobalResource(fields, args);
  38:      }
  40:      protected string GetGlobalResource(ResourceExpressionFields fields, object[] args)
  41:      {
  42:          return ResourceExtensions.GetGlobalResource(fields, args);
  43:      }
  45:      protected ResourceExpressionFields GetResourceFields(string expression, string virtualPath)
  46:      {
  47:          return ResourceExtensions.GetResourceFields(expression, virtualPath);
  48:      }
  49:  }
  51:  public class WebFormResourceHelper : ResourceHelper
  52:  {
  53:      public WebFormResourceHelper(string virtualPath)
  54:      {
  55:          VirtualPath = virtualPath;
  56:      }
  58:      public string VirtualPath { get; private set; }
  60:      public override string GetString(string expression, params object[] args)
  61:      {
  62:          ResourceExpressionFields fields = GetResourceFields(expression, VirtualPath);
  63:          if (!string.IsNullOrEmpty(fields.ClassKey))
  64:              return GetGlobalResource(fields, args);
  66:          return string.Format((string) HttpContext.GetLocalResourceObject(
  67:                                                             VirtualPath, fields.ResourceKey, 
  68:                                                             CultureInfo.CurrentUICulture), args);
  69:      }
  70:  }

You'll also notice that I've included a controller extension method for extracting global resources. This hasn't changed from the original implementation, but it's straight forward to use.


View Engine Implementation

This is where the rubber meets the road. Since we're now delegating that a ViewEngine can choose to support local resources, the derived view engine implementation is where it supplies it's own ResourceHelper, if it so chooses. In my example, I derive from the WebFormViewEngine and WebFormView, and provide this implementation to supply the WebFormResourceHelper to my localized views. For brevity, and the fact that I didn't write the code for rendering, I'll leave it up to you to see the full implementation for the LocalizedWebFormView in the download. However, the critical portion that you'll see is the following:

   1:  var localizedPage = page as ILocalizedView;
   2:  if (localizedPage != null)
   3:      localizedPage.Resource = new WebFormResourceHelper(ViewPath);
   4:  page.RenderView(context);

And that's it. In your view, you can now derive from LocalizedViewPage and get access to your global and local resources by doing

   1:  // global resource
   2:  <%= Resource.GetString("MvcExample, Welcome") %>
   4:  // local resource
   5:  <%= Resource.GetString("Welcome") %>


How does this fit with other View Engines?

View engines need to simply add a reference to the ResourceHelper so that their view's can gain access to it. Obviously, they'll also need to change their ViewEngine to set an appropriate ResourceHelper when instantiating the view, but those view engines can explicitly determine how they would like to treat resources (even completely ignoring Global & Local resources).


And that's it, our View Engine now is completely in control of where my resources come from. They can use the baked-in ASP.NET resource provider, their own logic, or whatever! Again, this implementation is no where near baked, and I strongly urge you to look at your solution to see how this would fit in, and (obviously) make the code "production worthy". I'm hoping that some of these concepts make it into future MVC releases. You can also download the source for these files here. Enjoy!


kick it on DotNetKicks.com

Categories: .NET | ASP.NET | MVC | Programming
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

ASP.NET MVC Preview 4 New Finds

July 17, 2008 00:49 by matthaw

So I've been checking over the source code for the latest ASP.NET MVC P4 release out on CodePlex, and have found some very interesting things.

 1. There's a variant codebase that is very similar to my RedirectToAction via Lambda expressions contained within the Futures/MvcFutures/Internal directory, "ExpressionHelper.cs". With this futures drop, the call will return a RouteValueDictionary, in which you turn around and call RedirectToRoute. In my version, of RedirectToAction, this is all taken care of for you, as well as it supports not having to explicitly give the type of your controller. Either way, here's the example on how to use this if you prefer:

   1:  using Microsoft.Web.Mvc.Internal;
   2:  using System.Web.Routing;
   4:  public class HomeController : Controller
   5:  {
   6:     public ActionResult Index()
   7:     {
   8:        return View();
   9:     }
  11:     public ActionResult DoRedirect()
  12:     {
  13:        RouteValueDictionary values = 
  14:           ExpressionHelper.GetRouteValuesFromExpression<HomeController>(c => c.Index());
  15:        return RedirectToRoute(values);
  16:     }
  17:  }

2. The RedirectToAction bug I blogged about has been fixed.

3. They've introduced a helper extension method (MvcControlDataBinder.SourceToDictionary) to convert data sources to a dictionary of values. The supported data source types include

  1. DataSet
  2. DataTable
  3. IDataReader
  4. IList
  5. Array
  6. IQueryable
  7. IEnumerable

Below is an example on how to use this method. While I would never use this to convert a List of models normally, I could see where if you simply need to get truncated key/value list of data with various other sources like IDataReader or IQueryable, this would be beneficial.

   1:  public ActionResult Products()
   2:  {
   3:      List<Product> products = new List<Product>()
   4:      {
   5:          new Product(1, "16 Speed", 499.99m),
   6:          new Product(2, "24 Speed", 699.99m)
   7:      };
   9:      Dictionary<object, object> data = 
  10:          MvcControlDataBinder.SourceToDictionary(products, "Id", "Name");
  11:      ViewData["Data"] = data;
  13:      return View();
  14:  }

4. The new Ajax support. I'm not going to detail this as Scott Hanselman's post covered a good example and ScottGu will eventually give Part 2 which will be very detailed.

5. As ScottGu already indicated, the Mvc Framework comes with a bunch of new Action Filters, including

  1. AuthorizeAttribute - which uses the membership framework for user authentication and user & role based security.
  2. HandleErrorAttribute - which will enable you to handle exceptions that occur by rendering a specific view when an error occurs. This is equitable to the catch-all error page.
  3. OutputCacheAttribute - Yes, this is what it says it is. Think ASP.NET output caching, and thats what this is.

6. TempData is now "testing friendly"! Well, right out of the box now, that is. They've introduced a new interface ITempDataProvider (and subsequent SessionStateTempDataProvider) that will only be used only when Execute is called from the Controller. The reason TempData is now tester friendly, is that by default it uses TempDataDictionary as a backing field, and Execute will Load/Save from the TempDataProvider set to/from TempData.

kick it on DotNetKicks.com

Categories: .NET | ASP.NET | MVC | Programming
Actions: E-mail | Permalink | Comments (7) | Comment RSSRSS comment feed

Routing + WebForms + Auto “Binding” Properties

June 21, 2008 10:51 by matthaw

Just ran across this excellent post by Jeremy Skinner. Just shows on how much power & flexibility the new routing framework gives you. This really is making me want to really focus on my slack project of using Routing instead of Url Rewriting at work.

Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

At a loss for blog topics

June 21, 2008 01:36 by matthaw

For the life of me, I can't seem to come up with any new blogging topics. At this point, I've exhausted all that's in MVC Preview 3, and haven't been doing anything super fun or cool at work lately. Hmmm, toss some things out and maybe I'll come up with something. Anyone?


On the flip side, I've fallen in love with Twitter - allows me to output my thoughts immediately.

Categories: General
Actions: E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed

Copyright © 2000 - 2024 , Excentrics World