Last active
August 29, 2015 14:20
-
-
Save CrazyMORF/56454d04a1247fa68465 to your computer and use it in GitHub Desktop.
Combres filter that provides content using generators
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 Combres; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Web.Helpers; | |
namespace WebApplication7 | |
{ | |
/// <summary> | |
/// Provides content using generators described in JSON like | |
/// { generators: [ "WebApplication7.HelloGenerator, WebApplication7" ] } | |
/// </summary> | |
public sealed class GeneratedContentFilter : ISingleContentFilter | |
{ | |
public interface IContentGenerator | |
{ | |
string Generate(); | |
} | |
public class GeneratedContentFilterSettings | |
{ | |
public List<string> Generators { get; set; } | |
} | |
public string TransformContent(ResourceSet resourceSet, Resource resource, string content) | |
{ | |
if (!resource.Path.EndsWith(".json", System.StringComparison.OrdinalIgnoreCase)) | |
{ | |
return content; | |
} | |
try | |
{ | |
var settings = Json.Decode<GeneratedContentFilterSettings>(content); | |
var generators = settings.Generators | |
.Select(s => Activator.CreateInstance(Type.GetType(s))) | |
.OfType<IContentGenerator>(); | |
var sb = new StringBuilder(); | |
foreach (var generator in generators) | |
{ | |
sb.AppendLine(generator.Generate()); | |
} | |
return sb.ToString(); | |
} | |
catch (Exception) | |
{ | |
return content; | |
} | |
} | |
public bool CanApplyTo(ResourceType resourceType) | |
{ | |
return true; | |
} | |
} | |
public class HelloGenerator : GeneratedContentFilter.IContentGenerator | |
{ | |
public string Generate() | |
{ | |
return "alert('Hello');"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment