From b35379b8fed204019dc059ec2d84f0dd7475e1ab Mon Sep 17 00:00:00 2001 From: "Valeriano A.R" Date: Sun, 24 May 2015 15:55:57 +0200 Subject: [PATCH] GlobalRouter: Route request to types. --- Scrummer/GlobalRouter.cs | 93 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/Scrummer/GlobalRouter.cs b/Scrummer/GlobalRouter.cs index 12396d3..c7bf997 100644 --- a/Scrummer/GlobalRouter.cs +++ b/Scrummer/GlobalRouter.cs @@ -1,4 +1,7 @@ using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; using System.Web; using Scrummer.Code; using Scrummer.Code.JSON; @@ -7,6 +10,77 @@ namespace Scrummer { public class GlobalRouter : IHttpHandler { + #region Handlers + + private static Dictionary _handlers = new Dictionary(); + + private static IHttpHandler GetHandler(string typeName) + { + if (string.IsNullOrEmpty(typeName)) { return null; } + Type type = null; + if (_handlers.ContainsKey(typeName)) + { + type = _handlers[typeName]; + IHttpHandler handler = Activator.CreateInstance(type) as IHttpHandler; + return handler; + } + + // Search type on executing assembly + Type[] types; + Assembly asm = Assembly.GetExecutingAssembly(); + types = asm.GetTypes(); + foreach (Type typeAux in types) + { + if (typeAux.FullName.EndsWith(typeName)) + { + type = typeAux; + break; + } + } + + // Search type on all loaded assemblies + if (type == null) + { + Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly asmAux in asms) + { + types = asmAux.GetTypes(); + foreach (Type typeAux in types) + { + if (typeAux.FullName.EndsWith(typeName)) + { + type = typeAux; + break; + } + } + if (type != null) { break; } + } + } + + // Use found type + if (type != null) + { + IHttpHandler handler = Activator.CreateInstance(type) as IHttpHandler; + if (handler != null) + { + lock (_handlers) + { + if (_handlers.ContainsKey(typeName) == false) + { + _handlers.Add(typeName, type); + } + } + } + return handler; + } + + return null; + } + + #endregion + + #region IHttpHandler + public bool IsReusable { get { return false; } @@ -16,12 +90,29 @@ namespace Scrummer { try { - context.Response.Write("Hello world!"); + string file = Path.GetFileName(context.Request.FilePath); + if (string.IsNullOrEmpty(file)) + { + // TODO: Default Handler + } + IHttpHandler handler = GetHandler(file); + if (handler == null) + { + // TODO: FrmNotFound + throw new Exception("NotFound"); + } + + // Use handler + context.Response.Clear(); + context.Handler = handler; + handler.ProcessRequest(context); } catch (Exception ex) { GlobalErrorHandler.HandleError(context, ex); } } + + #endregion } } \ No newline at end of file