protected void ProcessFileRequest(ISemanticProcessor semProc, HttpListenerContext context) { bool handled = false; string path = context.Request.RawUrl.LeftOf("?").RightOf("/").LeftOfRightmostOf('.'); string ext = context.Request.RawUrl.RightOfRightmostOf('.'); if (String.IsNullOrEmpty(path)) { path = "index"; } if (String.IsNullOrEmpty(ext)) { ext = "html"; } path = path + "." + ext; // Hardcoded folder path for the website! path = Path.Combine("Website", path); if (File.Exists(path)) { switch (ext) { case "html": semProc.ProcessInstance <WebServerMembrane, ST_HtmlResponse>(r => { r.Context = context; r.Html = ReadTextFile(path); }); break; case "js": semProc.ProcessInstance <WebServerMembrane, ST_JavascriptResponse>(r => { r.Context = context; r.Javascript = ReadTextFile(path); }); break; case "css": semProc.ProcessInstance <WebServerMembrane, ST_CssResponse>(r => { r.Context = context; r.Css = ReadTextFile(path); }); break; } handled = true; } if (!handled) { semProc.ServiceManager.Get <ILoggerService>().Log("Route not found."); semProc.ProcessInstance <WebServerMembrane, ST_RouteNotFound>(r => r.Context = context); } }
protected void ProcessFileRequest(ISemanticProcessor semProc, HttpListenerContext context) { bool handled = false; string path = context.Request.RawUrl.LeftOf("?").RightOf("/").LeftOfRightmostOf('.'); string ext = context.Request.RawUrl.RightOfRightmostOf('.'); if (String.IsNullOrEmpty(path)) { path = "index"; } if (String.IsNullOrEmpty(ext)) { ext = "html"; } path = path + "." + ext; // Hardcoded folder path for the website! path = Path.Combine("Website", path); if (File.Exists(path)) { switch (ext) { case "html": semProc.ProcessInstance<WebServerMembrane, ST_HtmlResponse>(r => { r.Context = context; r.Html = ReadTextFile(path); }); break; case "js": semProc.ProcessInstance<WebServerMembrane, ST_JavascriptResponse>(r => { r.Context = context; r.Javascript = ReadTextFile(path); }); break; case "css": semProc.ProcessInstance<WebServerMembrane, ST_CssResponse>(r => { r.Context = context; r.Css = ReadTextFile(path); }); break; } handled = true; } if (!handled) { semProc.ServiceManager.Get<ILoggerService>().Log("Route not found."); semProc.ProcessInstance<WebServerMembrane, ST_RouteNotFound>(r => r.Context = context); } }
// Ex: http://localhost/renderContext?ContextName=MeaningExplorer.PersonContext // Ex: http://localhost/renderContext?ContextName=MeaningExplorer.PersonContext&isSearch=true public void Process(ISemanticProcessor proc, IMembrane membrane, RenderContext msg) { try { Type t = Type.GetType(msg.ContextName); Clifton.Meaning.IContext context = (Clifton.Meaning.IContext)Activator.CreateInstance(t); string html; try { Parser parser = new Parser(); parser.Log = logMsg => Console.WriteLine(logMsg); parser.Parse(context); if (parser.AreDeclarationsValid) { ShowGroups(parser.Groups); // The CVD is needed for rendering lookup values. ContextValueDictionary cvd = CreateOrGetContextValueDictionary(proc, msg.Context); html = Renderer.CreatePage(parser, msg.IsSearch ? Renderer.Mode.Search : Renderer.Mode.NewRecord, cvd); } else { html = "<p>Context declarations are not valid. Missing entities:</p>" + String.Join("<br>", parser.MissingDeclarations.Select(pt => pt.Name)); } } catch (Exception ex) { html = "<p>Context declarations are not valid.</p><p>" + ex.Message + "</p>"; html = html + "<p>" + ex.StackTrace.Replace("\r\n", "<br>"); } proc.ProcessInstance <WebServerMembrane, HtmlResponse>(r => { r.Context = msg.Context; r.Html = html; }); } catch (Exception ex) { proc.ProcessInstance <WebServerMembrane, HtmlResponse>(r => { r.Context = msg.Context; r.Html = ex.Message + "<br>" + ex.StackTrace.Replace("\r\n", "<br>"); }); } }
// Ex: http://localhost/dictionary // Ex: http://localhost/dictionary?showInstanceIds=true public void Process(ISemanticProcessor proc, IMembrane membrane, GetDictionary msg) { StringBuilder sb = new StringBuilder(); sb.StartHtml(); sb.StartHead(). Script("/js/wireUpValueChangeNotifier.js"). Stylesheet("/css/styles.css"). EndHead(); sb.StartBody(); sb.StartParagraph().Append("<b>Dictionary:</b>").EndParagraph(); sb.StartParagraph().StartDiv().ID("dictionary").EndDiv().EndParagraph(); sb.StartParagraph().Append("<b>Type Nodes:</b>").EndParagraph(); sb.StartParagraph().StartDiv().ID("nodes").EndDiv().EndParagraph(); sb.StartScript().Javascript("(function() {getDictionaryHtml(" + msg.ShowInstanceIDs.ToString().ToLower() + ");})();").EndScript(); sb.EndBody().EndHtml(); proc.ProcessInstance <WebServerMembrane, HtmlResponse>(r => { r.Context = msg.Context; r.Html = sb.ToString(); }); }
protected void ProcessRoute(HttpListenerContext context, string data) { semProc.ProcessInstance <WebServerMembrane, Route>(r => { r.Context = context; r.Data = data; }); }
protected void ProcessRoute(IContext context, string data) { semProc.ProcessInstance <WebServerMembrane, Route>(r => { r.Context = context; r.Data = data; }); // , false, PROCESS_TIMEOUT); }
static void Main(string[] args) { InitializeBootstrap(); Bootstrap((e) => Console.WriteLine(e.Message)); ISemanticProcessor semProc = serviceManager.Get <ISemanticProcessor>(); // Stateless subscriber: semProc.Register <SurfaceMembrane, Subscriber>(); semProc.ProcessInstance <SurfaceMembrane, ST_Message>(); semProc.ProcessInstance <SurfaceMembrane, ST_Message>(m => m.Text = "Hello World", true); // Stateful subscriber: semProc.Register <SurfaceMembrane>(new StatefulSubscriber()); semProc.ProcessInstance <SurfaceMembrane, ST_Message2>(m => m.Text = "Hello World", true); semProc.ProcessInstance <SurfaceMembrane, ST_Message2>(m => m.Text = "Hello World", true); }
public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Url url) { SyndicationFeed sf = GetFeed(url.Url); sf.Items.ForEach(si => proc.ProcessInstance(membrane, new ST_RssFeedItem() { Text = si.Summary.Text })); }
protected virtual void RouteNotFoundResponse(ISemanticProcessor proc, HttpListenerContext context) { proc.ProcessInstance <WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "Route not found"; r.StatusCode = 500; }); }
protected virtual void RouteNotFoundResponse(ISemanticProcessor proc, HttpListenerContext context) { proc.ProcessInstance<WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "Route not found"; r.StatusCode = 500; }); }
protected void ProcessRoute(IContext context, string data) { // Must be processed on the IIS caller thread, otherwise we exit the EndRequest handler too soon. semProc.ProcessInstance <WebServerMembrane, Route>(r => { r.Context = context; r.Data = data; }, true); }
protected void JsonResponse(ISemanticProcessor proc, SemanticRoute packet) { proc.ProcessInstance <WebServerMembrane, JsonResponse>(r => { r.Context = packet.Context; r.Json = ""; r.StatusCode = 200; }); }
protected void JsonResponse(ISemanticProcessor proc, SemanticRoute packet, object data) { string json = JsonConvert.SerializeObject(data); proc.ProcessInstance <WebServerMembrane, JsonResponse>(r => { r.Context = packet.Context; r.Json = json; r.StatusCode = 200; }); }
protected virtual void RouteNotFoundResponse(ISemanticProcessor proc, IContext context) { proc.ProcessInstance <WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "Route not found"; r.StatusCode = 500; }); proc.ServiceManager.Get <IWebServerService>().RouteNotFound(context); }
protected void JsonResponse(ISemanticProcessor proc, SemanticRoute packet, string jsonResp) { proc.ProcessInstance <WebServerMembrane, JsonResponse>(r => { r.Context = packet.Context; // Here we return the key and value with single quotes. If we use double quotes, jQuery post will fail! // But the resulting value cannot be parsed in Javascript because a JSON string must have double-quotes for the key and value. // WTF???? r.Json = jsonResp.ExchangeQuoteSingleQuote(); r.StatusCode = 200; }); }
public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type) { // Don't log our log message, otherwise we get an infinite loop! if (!(type is ST_Log)) { // One way, with instances: // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() }); // Another way, strictly with types: proc.ProcessInstance <LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString()); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type) { // Don't log our log message, otherwise we get an infinite loop! if (!(type is ST_Log)) { // One way, with instances: // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() }); // Another way, strictly with types: proc.ProcessInstance<LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString()); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, RegistrationToken token) { IDbContextService db = proc.ServiceManager.Get <IDbContextService>(); List <UserAccount> uas = db.Context.Query <UserAccount>(r => r.RegistrationToken == token.Token); bool validated = uas.Count == 1; proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "TokenValidated", validated); if (validated) { uas[0].RegistrationToken = null; uas[0].Registered = true; db.Context.Update(uas[0]); } // Continue processing the get request to display the /account/finishRegistration page. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = token.Context); }
public void Process(ISemanticProcessor proc, IMembrane membrane, ForgotPasswordToken token) { IDbContextService db = proc.ServiceManager.Get <IDbContextService>(); List <UserAccount> uas = db.Context.Query <UserAccount>(r => r.PasswordRecoveryToken == token.Token); bool validated = uas.Count == 1; if (validated) { proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "UserPasswordRecoveryId", uas[0].Id); uas[0].PasswordRecoveryToken = null; db.Context.Update(uas[0]); } else { proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "UserPasswordRecoveryId", null); } // Continue processing the get request to display the /account/passwordRecovery page. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = token.Context); }
public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Url url) { SyndicationFeed sf = GetFeed(url.Url); sf.Items.ForEach(si => proc.ProcessInstance(membrane, new ST_RssFeedItem() { Text = si.Summary.Text })); }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IPublicRouterService routerService = proc.ServiceManager.Get <IPublicRouterService>(); HttpListenerContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); RouteInfo routeInfo; // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { string data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd(); Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); } else { // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, keyVal[1]); } } } } else if (verb.Value == "GET") { // Parse parameters NameValueCollection nvc = context.Request.QueryString; foreach (string key in nvc.AllKeys) { PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, nvc[key]); } } } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; proc.ProcessInstance <WebServerMembrane>(semanticRoute, true); // TODO: Why execute on this thread? } else if (verb.Value == "GET") { // Only issue the UnhandledContext if this is not an authenticated route. if (!proc.ServiceManager.Get <IAuthenticatingRouterService>().IsAuthenticatedRoute(searchRoute)) { // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = context); } } else { proc.ProcessInstance <WebServerMembrane, ExceptionResponse>(e => { e.Context = context; e.Exception = new Exception("Route " + searchRoute + " not defined."); }); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IPublicRouterService routerService = proc.ServiceManager.Get<IPublicRouterService>(); HttpListenerContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); RouteInfo routeInfo; // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { string data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd(); Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); } else { // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, keyVal[1]); } } } } else if (verb.Value == "GET") { // Parse parameters NameValueCollection nvc = context.Request.QueryString; foreach(string key in nvc.AllKeys) { PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, nvc[key]); } } } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; proc.ProcessInstance<WebServerMembrane>(semanticRoute, true); // TODO: Why execute on this thread? } else if (verb.Value == "GET") { // Only issue the UnhandledContext if this is not an authenticated route. if (!proc.ServiceManager.Get<IAuthenticatingRouterService>().IsAuthenticatedRoute(searchRoute)) { // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance<WebServerMembrane, UnhandledContext>(c => c.Context = context); } } else { proc.ProcessInstance<WebServerMembrane, ExceptionResponse>(e => { e.Context = context; e.Exception = new Exception("Route " + searchRoute + " not defined."); }); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IAuthenticatingRouterService routerService = proc.ServiceManager.Get<IAuthenticatingRouterService>(); HttpListenerContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); string data = route.Data; RouteInfo routeInfo; // TODO: Session manager may not exist. How do we handle services that are missing? IWebSessionService session = proc.ServiceManager.Get<IWebSessionService>(); // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { // Public routes always authenticate. bool authenticatedRoute = true; bool authorizedRoute = true; if (routeInfo.RouteType == RouteType.AuthenticatedRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); } if (routeInfo.RouteType == RouteType.RoleRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); // User must be authenticated and have the correct role setting. if (authenticatedRoute) { // Any bits that are set with a binary "and" of the route's role mask and the current role passes the authorization test. uint mask = session.GetSessionObject<uint>(context, "RoleMask"); authorizedRoute = (mask & routeInfo.RoleMask) != 0; } } if (authenticatedRoute && authorizedRoute) { Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? // NOTE: "JSON" is passed in as a string, not object. So this is what it looks like in the Javascript: // $.post("/geeks/createProfile", '{ "profileName": "foobar" }' // Note the surrounding ' marks if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); } else { // Instead here, the data is passed in as an object, which comes in as params. The Javascript for this looks like: // $.post("/geeks/createProfile", { "profileName": profileName } // Note the lack of surrounding ' around the { } // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(keyVal[1].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } } else if (verb.Value == "GET") { // Parse parameters NameValueCollection nvc = context.Request.QueryString; foreach (string key in nvc.AllKeys) { PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // pi.SetValue(semanticRoute, Uri.UnescapeDataString(nvc[key].Replace('+', ' '))); // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(nvc[key].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; proc.ProcessInstance<WebServerMembrane>(semanticRoute, true); } else { // Deal with expired or requires authentication. switch (session.GetState(context)) { case SessionState.New: // TODO: Oh man, this is application specific!!! session.SetSessionObject(context, "OneTimeBadAlert", "Please Sign In"); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "authenticationRequired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 403; //}); break; case SessionState.Authenticated: proc.ProcessInstance<WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "notAuthorized"; // used in clifton.spa.js to handle SPA error responses r.StatusCode = 401; }); break; case SessionState.Expired: session.SetSessionObject(context, "OneTimeBadAlert", "Session expired. Please sign in again."); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "sessionExpired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 401; //}); break; } } } else { proc.ProcessInstance<LoggerMembrane, ST_Log>(msg => msg.Message = "Using default handler: " + verb.Value + ": " + path.Value); // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance<WebServerMembrane, UnhandledContext>(c => c.Context = context); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IAuthenticatingRouterService routerService = proc.ServiceManager.Get <IAuthenticatingRouterService>(); IContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); string data = route.Data; RouteInfo routeInfo; IPAddress addr = context.Request.RemoteEndPoint.Address; string ip = addr.ToString(); // Handle localhost format. if (ip == "::1") { addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); } Console.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt ") + "IP: " + addr.ToString() + " URL: " + route.Context.Request.Url); // TODO: Session manager may not exist. How do we handle services that are missing? IWebSessionService session = proc.ServiceManager.Get <IWebSessionService>(); // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { // Public routes always authenticate. bool authenticatedRoute = true; bool authorizedRoute = true; if (routeInfo.RouteType == RouteType.AuthenticatedRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); } if (routeInfo.RouteType == RouteType.RoleRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); // User must be authenticated and have the correct role setting. if (authenticatedRoute) { // Any bits that are set with a binary "and" of the route's role mask and the current role passes the authorization test. uint mask = session.GetSessionObject <uint>(context, "RoleMask"); authorizedRoute = (mask & routeInfo.RoleMask) != 0; } } if (authenticatedRoute) // user is authenticated { session.UpdateLastTransaction(context); } if (authenticatedRoute && authorizedRoute) { Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? // NOTE: "JSON" is passed in as a string, not object. So this is what it looks like in the Javascript: // $.post("/geeks/createProfile", '{ "profileName": "foobar" }' // Note the surrounding ' marks if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); SetUrlParameters(context.Request.Url.ToString(), semanticRoute, receptorSemanticType); } else if (MultiPartParser.IsMultiPart(data)) { MultiPartParser.ContentType ct = MultiPartParser.GetContentType(data); string content = MultiPartParser.GetContent(data); if (!(semanticRoute is IFileUpload)) { throw new RouterException("Semantic route class must implement IFileUpload"); } ((IFileUpload)semanticRoute).Content = content; } else { // Instead here, the data is passed in as an object, which comes in as params. The Javascript for this looks like: // $.post("/geeks/createProfile", { "profileName": profileName } // Note the lack of surrounding ' around the { } // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" // Use $.post(url, JSON.stringify(data) to convert to JSON string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(keyVal[1].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } } else if (verb.Value == "GET") { SetUrlParameters(context.Request.Url.ToString(), semanticRoute, receptorSemanticType); } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; // TODO: Why are we doing this on the caller thread, except for debugging??? proc.ProcessInstance <WebServerMembrane>(semanticRoute, true); } else { // Deal with expired or requires authentication. switch (session.GetState(context)) { case SessionState.New: // TODO: Oh man, this is application specific!!! session.SetSessionObject(context, "OneTimeBadAlert", "Please Sign In"); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "authenticationRequired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 403; //}); break; case SessionState.Authenticated: proc.ProcessInstance <WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "notAuthorized"; // used in clifton.spa.js to handle SPA error responses r.StatusCode = 401; }); break; case SessionState.Expired: session.SetSessionObject(context, "OneTimeBadAlert", "Session expired. Please sign in again."); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "sessionExpired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 401; //}); break; } } } else { // proc.ProcessInstance<LoggerMembrane, ST_Log>(msg => msg.Message = "Using default handler: " + verb.Value + ": " + path.Value); // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = context); } }
public void Process(ISemanticProcessor pool, IMembrane membrane, IOneType obj) { Console.WriteLine("Chaining OneType on thread ID " + Thread.CurrentThread.ManagedThreadId); pool.ProcessInstance(membrane, new SecondType()); }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IAuthenticatingRouterService routerService = proc.ServiceManager.Get <IAuthenticatingRouterService>(); HttpListenerContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); string data = route.Data; RouteInfo routeInfo; // TODO: Session manager may not exist. How do we handle services that are missing? IWebSessionService session = proc.ServiceManager.Get <IWebSessionService>(); // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { // Public routes always authenticate. bool authenticatedRoute = true; bool authorizedRoute = true; if (routeInfo.RouteType == RouteType.AuthenticatedRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); } if (routeInfo.RouteType == RouteType.RoleRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); // User must be authenticated and have the correct role setting. if (authenticatedRoute) { // Any bits that are set with a binary "and" of the route's role mask and the current role passes the authorization test. uint mask = session.GetSessionObject <uint>(context, "RoleMask"); authorizedRoute = (mask & routeInfo.RoleMask) != 0; } } if (authenticatedRoute && authorizedRoute) { Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? // NOTE: "JSON" is passed in as a string, not object. So this is what it looks like in the Javascript: // $.post("/geeks/createProfile", '{ "profileName": "foobar" }' // Note the surrounding ' marks if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); } else { // Instead here, the data is passed in as an object, which comes in as params. The Javascript for this looks like: // $.post("/geeks/createProfile", { "profileName": profileName } // Note the lack of surrounding ' around the { } // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(keyVal[1].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } } else if (verb.Value == "GET") { // Parse parameters NameValueCollection nvc = context.Request.QueryString; foreach (string key in nvc.AllKeys) { PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // pi.SetValue(semanticRoute, Uri.UnescapeDataString(nvc[key].Replace('+', ' '))); // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(nvc[key].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; proc.ProcessInstance <WebServerMembrane>(semanticRoute, true); } else { // Deal with expired or requires authentication. switch (session.GetState(context)) { case SessionState.New: // TODO: Oh man, this is application specific!!! session.SetSessionObject(context, "OneTimeBadAlert", "Please Sign In"); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "authenticationRequired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 403; //}); break; case SessionState.Authenticated: proc.ProcessInstance <WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "notAuthorized"; // used in clifton.spa.js to handle SPA error responses r.StatusCode = 401; }); break; case SessionState.Expired: session.SetSessionObject(context, "OneTimeBadAlert", "Session expired. Please sign in again."); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "sessionExpired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 401; //}); break; } } } else { proc.ProcessInstance <LoggerMembrane, ST_Log>(msg => msg.Message = "Using default handler: " + verb.Value + ": " + path.Value); // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = context); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, ViewAccountInfo token) { // Thought we'd have to do something here to fill in the form, but nope. The current UserAccount is set in the session store, so we don't have to do anything here. // Continue processing the get request to display the /account/passwordRecovery page. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = token.Context); }