public void Images(IManosContext ctx, int index) { var images = new ImageList(); var image = images[index]; ctx.Response.End("Image: {0}, size {1} x {2}", image.Name, image.Width, image.Height); }
public void Content(IManosContext ctx) { string path = ctx.Request.Path; // Double check path start with route-prefix if (path.StartsWith(route_prefix, StringComparison.InvariantCultureIgnoreCase) && path.IndexOf("..") < 0) { // Strip off the route prefix and leading slash path = path.Substring(route_prefix.Length); if (path.StartsWith("/")) path = path.Substring(1); // Locate the file path = Path.Combine(content_folder, path); // Check it exists if (File.Exists(path)) { // Send it ctx.Response.Headers.SetNormalizedHeader("Content-Type", ManosMimeTypes.GetMimeType(path)); ctx.Response.SendFile(path); ctx.Response.End(); return; } } ctx.Response.StatusCode = 404; ctx.Response.End(); }
public void Images(IManosContext ctx) { Console.WriteLine("Got /images request"); var images = new ImageList(); ctx.Response.End(string.Format("{{\"count\" : {0} }}", images.Count)); }
public static bool TryConvertUnsafeString(IManosContext ctx, Type type, ParameterInfo param, UnsafeString unsafe_str_value, out object data) { if (type == typeof(UnsafeString)) { data = unsafe_str_value; return(true); } string str_value = unsafe_str_value == null ? null : unsafe_str_value.SafeValue; if (TryConvertFormData(type, str_value, out data)) { return(true); } if (str_value == null && param.DefaultValue != DBNull.Value) { data = param.DefaultValue; return(true); } try { data = Convert.ChangeType(str_value, type); } catch { Console.Error.WriteLine("Error while converting '{0}' to '{1}'.", str_value, type); data = null; return(false); } return(true); }
public void TestSubmitLink(IManosContext ctx, string link) { var template = new RazorTemplate { Model = link }; ctx.Response.End(template.TransformText()); }
public static bool TryGetDataForParamList(ParameterInfo [] parameters, ManosApp app, IManosContext ctx, out object [] data) { data = new object [parameters.Length]; int param_start = 1; data [0] = ctx; if (typeof(ManosApp).IsAssignableFrom(parameters [1].ParameterType)) { data [1] = app; ++param_start; } for (int i = param_start; i < data.Length; i++) { string name = parameters [i].Name; if (!TryConvertType(ctx, name, parameters [i], out data [i])) { return(false); } } return(true); }
public void SubmitLink(IManosContext ctx, Shorty app, string link) { string id = GenerateHash (link, 5); Cache [id] = new LinkData (link); ctx.Response.Redirect ("/r/" + id + "~"); }
public IManosTarget OnPreProcessTarget(IManosContext ctx) { if (AppHost.Pipes == null) { return(null); } foreach (IManosPipe pipe in AppHost.Pipes) { try { var found = pipe.OnPreProcessTarget(ctx); if (found != null) { return(found); } if (ctx.Transaction.Aborted) { return(null); } } catch (Exception e) { Console.Error.WriteLine("Exception in {0}::OnPreProcessTarget.", pipe); Console.Error.WriteLine(e); } } return(null); }
public void HandShake(IManosContext ctx) { var id = GenerateId(); int heartbeat_timeout = 15; int close_timeout = 25; string[] supported_transports = new string[] { "websocket" }; //websocket ctx.Response.End(id + ":" + heartbeat_timeout.ToString() + ":" + close_timeout.ToString() + ":" + string.Join(",", supported_transports)); }
public void SaveSessionState(IManosContext ctx, SessionState state) { if (!state.Modified) return; // Just store it m_ActiveSessions[state.SessionID] = state; }
public void Echo(IManosContext ctx, String value, int id) { ctx.Response.SetHeader("Content-Type","text/html"); for(; id > 0; id--) { ctx.Response.Write(value + "<br/>"); } ctx.Response.End(); }
public void SubmitLink(IManosContext ctx, Shorty app, string link, bool show_info) { string id = GenerateHash (link, 5); if (show_info) ctx.Response.SetCookie ("show_info", "true"); Cache [id] = new LinkData (link); ctx.Response.Redirect ("/r/" + id + "~"); }
public void UploadFile(IManosContext ctx, string name) { UploadedFile file = ctx.Request.Files.Values.First(); byte [] data = new byte [file.Contents.Length]; file.Contents.Read(data, 0, data.Length); ctx.Response.End(data); }
public void OnError(IManosContext ctx) { foreach (IManosPipe pipe in AppHost.Pipes) { try { pipe.OnError (ctx); } catch (Exception e) { Console.Error.WriteLine ("Exception in {0}::OnError", pipe); Console.Error.WriteLine (e); } } }
public static void RenderStache(this ManosModule mod, IManosContext ctx, string template, object obj) { var t = new Template (); var path = Path.Combine (TEMPLATE_DIR, template); using (var r = new StreamReader (path)) { t.Load (r); } t.Render (obj, new StreamWriter (ctx.Response.Stream), locator.GetTemplate); ctx.Response.End (); }
public void Manual(IManosContext ctx, string manual) { string md_page; if (!manuals.TryGetValue (manual, out md_page)) { ctx.Response.StatusCode = 404; return; } WriteMarkdownDocsPage (ctx.Response, md_page); }
public void Index(IManosContext ctx) { ctx.Response.WriteLine (@"<html> <head><title>Welcome to Shorty</title></head> <body> <form method='POST' action='submit-link'> <input type='text' name='link' /> <input type='submit' /> </form> </body>"); }
public void GetItemData(IManosContext ctx) { var ratings = MyRecommender.Instance.Data; var user_mapping = MyRecommender.Instance.UserMapping; var item_mapping = MyRecommender.Instance.ItemMapping; int item_id = ctx.GetItemID("items"); if (item_id < 0 || item_id > ratings.MaxItemID) { ctx.Response.StatusCode = 404; // TODO maybe different error ctx.Response.End(); return; } var match = new Regex(@"items/\d+/(\w+)").Match(ctx.Request.Path); string command = match.Success ? match.Groups[1].Value : string.Empty; switch(command) { case "statistics": ctx.Response.WriteLine("iid={0} num_ratings={1}", item_mapping.ToOriginalID(item_id), ratings.ByItem[item_id].Count); break; case "events": var users_string = ctx.Request.QueryData.GetString("users"); if (users_string == null) { foreach (int index in ratings.ByItem[item_id]) ctx.Response.WriteLine("eid={0} uid={1} value={2}", index, user_mapping.ToOriginalID(ratings.Users[index]), ratings[index]); } else { var requested_users = new HashSet<int>(from u in users_string.Split(',') select user_mapping.ToInternalID(int.Parse(u))); foreach (int index in ratings.ByItem[item_id]) { int user_id = ratings.Users[index]; if (requested_users.Contains(user_id)) ctx.Response.WriteLine("eid={0} uid={1} value={2}", index, user_mapping.ToOriginalID(user_id), ratings[index]); } } break; case "events/ratings": goto case "events"; case "": ctx.Response.WriteLine("no item metadata available"); // TODO break; default: ctx.Response.StatusCode = 404; // TODO maybe different error break; } ctx.Response.End(); }
public static void Content(IManosContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; }
public void Index(IManosContext ctx) { ctx.Response.End(@"<html> <head><title>Welcome to Aqrubik</title></head> <body> <form method='POST' action='TestSubmit'> <input type='text' name='link'> <input type='submit'> </form> </body> </html>"); }
public static void RenderStache(this ManosModule mod, IManosContext ctx, string template, object obj) { var t = new Template(); var path = Path.Combine(TEMPLATE_DIR, template); using (var r = new StreamReader(path)) { t.Load(r); } t.Render(obj, new StreamWriter(ctx.Response.Writer), locator.GetTemplate); ctx.Response.End(); }
public void Content(IManosContext ctx) { var recommender = MyRecommender.Instance.Predictor; var ratings = MyRecommender.Instance.Data; Log.Info("stats"); ctx.Response.WriteLine("MyMediaLite recommender: {0}", recommender); ctx.Response.WriteLine("Rating statistics: " + ratings.Statistics()); ctx.Response.End(); }
public void Index(IManosContext ctx) { ctx.Response.End(@"<html> <head><title>" + ManosConfig.Get("shorty.title") + @"</title></head> <body> <form method='POST' action='submit-link'> <input type='text' name='link' /><br /> <input type='checkbox' name='show_info' /> Show me the info page, instead of redirecting.<br /> <input type='submit' /> </form> </body> </html>" ); }
public void InvokeMvcController(IManosContext ctx) { if (useThreadPool) { // Invoke the action on the thread pool System.Threading.ThreadPool.QueueUserWorkItem(o=>InvokeControllerInternal((IManosContext)ctx), ctx); } else { // Invoke the controller on the event loop thread InvokeControllerInternal(ctx); } }
public void Invoke(ManosApp app, IManosContext ctx) { object [] data; if (!TryGetDataForParamList(parameters, app, ctx, out data)) { // TODO: More graceful way of handling this? ctx.Transaction.Abort(400, "Can not convert parameters to match Action argument list."); return; } action(target, data); }
public void Manual(IManosContext ctx, string manual) { string md_page; if (!manuals.TryGetValue(manual, out md_page)) { ctx.Response.StatusCode = 404; ctx.Response.End(); return; } WriteMarkdownDocsPage(ctx.Response, md_page); }
public void Index(IManosContext ctx) { ctx.Response.WriteLine (@"<html> <head><title>Welcome to Shorty</title></head> <body> <form method='POST' action='submit-link'> <input type='text' name='link' /><br /> <input type='checkbox' name='show_info' /> Show me the info page, instead of redirecting.<br /> <input type='submit' /> </form> </body> </html>"); }
public void SubmitLink(IManosContext ctx, Shorty app, string link, bool show_info) { string id = GenerateHash(link, 5); if (show_info) { ctx.Response.SetCookie("show_info", "true"); } Cache.Set(id, new LinkData(link), (name, item) => { ctx.Response.Redirect("/r/" + id + "~"); }); }
public void Tutorial(IManosContext ctx, string page) { string md_page; if (!tutorial_pages.TryGetValue(page, out md_page)) { ctx.Response.StatusCode = 404; ctx.Response.End(); return; } WriteMarkdownDocsPage(ctx.Response, md_page); }
public static bool TryConvertType(IManosContext ctx, Type type, string str_value, out object data) { try { data = Convert.ChangeType (str_value, type); } catch (Exception e) { Console.Error.WriteLine ("Error while converting '{0}' to '{1}'.", str_value, type); data = null; return false; } return true; }
public void ReverseString(IManosContext ctx, string the_string) { // This is intentionally awful, as its trying to test the stream // Write it normally, then try to overwrite it with the new value ctx.Response.Write (the_string); ctx.Response.Stream.Position = 0; byte [] data = Encoding.Default.GetBytes (the_string); for (int i = data.Length; i >= 0; --i) { ctx.Response.Stream.Write (data, i, 1); } }
public void MakeMoo(IManosContext ctx) { string cowPath = ctx.Request.Data["cowfile"]; string face = ctx.Request.Data["face"]; string isThink = ctx.Request.Data["isThink"]; string columns = ctx.Request.Data["columns"]; string message = ctx.Request.Data["message"] ?? string.Empty; string cow = ProxyCowsay (cowPath, face, isThink, columns, message); ctx.Response.ContentEncoding = encoding; // Allow anyone to use the API from another instance ctx.Response.Headers.SetNormalizedHeader ("Access-Control-Allow-Origin", "*"); ctx.Response.End (cow); }
public void MultiplyString(IManosContext ctx, string the_string, int amount) { // Create all the data for the string, then do all the writing long start = ctx.Response.Stream.Position; ctx.Response.Write (the_string); long len = ctx.Response.Stream.Position - start; ctx.Response.Stream.SetLength (len * amount); ctx.Response.Stream.Position = start; for (int i = 0; i < amount; i++) { ctx.Response.Write (the_string); } }
public void ProcessCount(IManosContext ctx) { WebSocket ws = WebSocket.Upgrade(ctx.Request); Random rand = new Random(); var t = AddTimeout(TimeSpan.FromSeconds(0.5), RepeatBehavior.Forever, (app, data) => { int r = rand.Next(10, 100); ws.Send(r.ToString()); }); ws.Closed += delegate { t.Stop(); }; }
public void LinkInfo(IManosContext ctx, Shorty app, string id) { LinkData info = Cache [id] as LinkData; if (info == null) { ctx.Response.StatusCode = 404; return; } ctx.Response.WriteLine (@"<html> <head><title>Welcome to Shorty</title></head> <body> {0} was clicked {1} times. </body>", info.Link, info.Clicks); }
public void RandomCount(IManosContext ctx) { WebSocket ws = WebSocket.Upgrade (ctx.Request); Random rand = new Random (); var t = AddTimeout (TimeSpan.FromSeconds (0.5), RepeatBehavior.Forever, (app, data) => { int r = rand.Next (10, 100); ws.Send (r.ToString ()); }); ws.Closed += delegate { t.Stop (); }; }
public void Content(IManosContext ctx) { string path = ctx.Request.Path; if (path.StartsWith ("/")) path = path.Substring (1); if (string.Equals (ctx.Request.QueryData.Get ("v"), "small", StringComparison.Ordinal)) { path = EnsureSmallAvailable (ctx, path); if (path == null) return; } ServeImage (ctx, path); }
public void Content(IManosContext ctx) { string path = ctx.Request.Path; if (path.StartsWith ("/")) path = path.Substring (1); if (ValidFile (path)) { ctx.Response.Headers.SetNormalizedHeader ("Content-Type", ManosMimeTypes.GetMimeType (path)); ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; ctx.Response.End (); }
public void Predict(IManosContext ctx) { var recommender = MyRecommender.Instance.Predictor; var ratings = MyRecommender.Instance.Data; var item_mapping = MyRecommender.Instance.ItemMapping; int user_id = ctx.GetUserID("users", "predictions"); if (user_id < 0 || user_id > recommender.MaxUserID) { ctx.Response.StatusCode = 404; // TODO maybe different error ctx.Response.End(); return; } var query_data = ctx.Request.QueryData; // TODO do this in a more elegant way var items_string = query_data.GetString("items"); var requested_items = items_string != null ? from i in items_string.Split(',') select item_mapping.ToInternalID(int.Parse(i)) : Enumerable.Range(0, ratings.MaxItemID + 1); // TODO do this in a more elegant way var override_value = query_data.GetString("useStoredRatings"); bool show_stored_ratings = override_value != null ? override_value.Equals("true", StringComparison.InvariantCultureIgnoreCase) : false; // TODO sort results if (show_stored_ratings) { var known_items = new HashSet<int>( from index in ratings.ByUser[user_id] select ratings.Items[index]); foreach (int item_id in requested_items) if (known_items.Contains(item_id)) ctx.Response.WriteLine("iid={0} value={1}", item_mapping.ToOriginalID(item_id), ratings[user_id, item_id]); else ctx.Response.WriteLine("iid={0} value={1}", item_mapping.ToOriginalID(item_id), recommender.Predict(user_id, item_id).ToString(CultureInfo.InvariantCulture)); } else foreach (int item_id in requested_items) ctx.Response.WriteLine("iid={0} value={1}", item_mapping.ToOriginalID(item_id), recommender.Predict(user_id, item_id).ToString(CultureInfo.InvariantCulture)); ctx.Response.End(); }
public static bool TryGetDataForParamList(ParameterInfo [] parameters, ManosApp app, IManosContext ctx, out object [] data) { data = new object [parameters.Length]; data [0] = app; data [1] = ctx; for (int i = 2; i < data.Length; i++) { string name = parameters [i].Name; string strd = ctx.Request.Data.Get (name); if (!TryConvertType (ctx, parameters [i].ParameterType, strd, out data [i])) return false; } return true; }
public void OnError(IManosContext ctx) { if (AppHost.Pipes == null) { return; } foreach (IManosPipe pipe in AppHost.Pipes) { try { pipe.OnError(ctx); } catch (Exception e) { Console.Error.WriteLine("Exception in {0}::OnError", pipe); Console.Error.WriteLine(e); } } }
public static void Content(IManosContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { if (path.IndexOf ("/img/") != -1) ctx.Response.Headers.SetNormalizedHeader ("Content-Type", "image/jpeg"); else ctx.Response.Headers.SetNormalizedHeader ("Content-Type", ManosMimeTypes.GetMimeType (path)); ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; ctx.Response.End (); }
public void ReverseString(IManosContext ctx, string the_string) { // This is intentionally awful, as its trying to test the stream // Write it normally, then try to overwrite it with the new value ctx.Response.Write(the_string); ctx.Response.Stream.Position = 0; byte [] data = Encoding.Default.GetBytes(the_string); for (int i = data.Length; i >= 0; --i) { ctx.Response.Stream.Write(data, i, 1); } ctx.Response.End(); }
public void Redirector(IManosContext ctx, Shorty app, string id) { LinkData info = Cache [id] as LinkData; if (info == null) { ctx.Response.StatusCode = 404; return; } // // Because multiple http transactions could be occuring at the // same time, we need to make sure this shared data is incremented // properly // Interlocked.Increment (ref info.Clicks); ctx.Response.Redirect (info.Link); }
void AsyncCounter(IManosContext ctx) { try { for (var count = 0; count < 60; count++) { System.Threading.Thread.Sleep(1000); ctx.Synchronize((c, o) => { var line = "Alive " + count + " seconds"; c.Response.WriteLine(line); }, null); } ctx.Synchronize((c, o) => { c.Response.End(); }, null); } catch (InvalidOperationException e) { Console.WriteLine("Sync block died:"); Console.WriteLine(e); } }
public void MultiplyString(IManosContext ctx, string the_string, int amount) { // Create all the data for the string, then do all the writing long start = ctx.Response.Stream.Position; ctx.Response.Write(the_string); long len = ctx.Response.Stream.Position - start; ctx.Response.Stream.SetLength(len * amount); ctx.Response.Stream.Position = start; for (int i = 0; i < amount; i++) { ctx.Response.Write(the_string); } ctx.Response.End(); }
public void Redirector(IManosContext ctx, Shorty app, string id) { if (ctx.Request.Cookies.Get("show_info") != null) { LinkInfo(ctx, app, id); return; } Cache.Get(id, (name, item) => { LinkData info = item as LinkData; if (info == null) { ctx.Response.StatusCode = 404; return; } ++info.Clicks; ctx.Response.Redirect(info.Link); }); }
public static void Synchronize <T> (Action <IManosContext, T> action, IManosContext context, T arg) { if (action == null) { throw new ArgumentNullException("action"); } if (context == null) { throw new ArgumentNullException("context"); } if (context.Transaction.ResponseReady && context.Transaction.Response == null) { throw new InvalidOperationException("Response stream has been closed"); } waitingSyncBlocks.Enqueue(new SynchronizedBlock <T> (action, context, arg)); syncBlockWatcher.Send(); }
public void LinkInfo(IManosContext ctx, Shorty app, string id) { Cache.Get(id, (name, item) => { LinkData info = item as LinkData; if (info == null) { ctx.Response.StatusCode = 404; ctx.Response.End(); return; } ctx.Response.End(@"<html> <head><title>Welcome to Shorty</title></head> <body> <a href='{0}'>{0}</a> was clicked {1} times. </body> </html>" , info.Link, info.Clicks); }); }
public static void Content(IManosContext ctx) { string path = ctx.Request.Path; if (path.StartsWith("/")) { path = path.Substring(1); } if (ValidFile(path)) { ctx.Response.Headers.SetNormalizedHeader("Content-Type", ManosMimeTypes.GetMimeType(path)); ctx.Response.SendFile(path); } else { ctx.Response.StatusCode = 404; } ctx.Response.End(); }
public void OnPostProcessTarget(IManosContext ctx, IManosTarget target) { if (AppHost.Pipes == null) { return; } foreach (IManosPipe pipe in AppHost.Pipes) { try { pipe.OnPostProcessTarget(ctx, target); if (ctx.Transaction.Aborted) { return; } } catch (Exception e) { Console.Error.WriteLine("Exception in {0}::OnPostProcessTarget.", pipe); Console.Error.WriteLine(e); } } }
private static void FakeAction2(IManosContext ctx) { }
public void Route3(TestApp app, IManosContext ctx, String name, int age) { ctx.Response.Write("'{0}', you are '{1}'", name, age); ctx.Response.End(); }
public void Route1(IManosContext ctx) { ctx.Response.Write("Route1"); ctx.Response.End(); }
public virtual void OnPreProcessTarget(IManosContext ctx, Action <IManosTarget> changeHandler) { // default: don't change the handler }
public virtual void OnPostProcessTarget(IManosContext ctx, IManosTarget target, Action complete) { complete(); }
public virtual void OnError(IManosContext ctx, Action complete) { complete(); }
public static bool TryConvertType(IManosContext ctx, string name, ParameterInfo param, out object data) { Type dest = param.ParameterType; if (dest.IsArray) { var list = ctx.Request.Data.GetList(name); if (list != null) { Type element = dest.GetElementType(); IList arr = Array.CreateInstance(element, list.Count); for (int i = 0; i < list.Count; i++) { object elem_data; if (!TryConvertUnsafeString(ctx, element, param, list [i], out elem_data)) { data = null; return(false); } arr [i] = elem_data; } data = arr; return(true); } } if (dest.GetInterface("IDictionary") != null) { var dict = ctx.Request.Data.GetDict(name); if (dict != null) { Type eltype = typeof(UnsafeString); IDictionary dd = (IDictionary)Activator.CreateInstance(dest); if (dest.IsGenericType) { Type [] args = dest.GetGenericArguments(); if (args.Length != 2) { throw new Exception("Generic Dictionaries must contain two generic type arguments."); } if (args [0] != typeof(string)) { throw new Exception("Generic Dictionaries must use strings for their keys."); } eltype = args [1]; // ie the TValue in Dictionary<TKey,TValue> } foreach (string key in dict.Keys) { object elem_data; if (!TryConvertUnsafeString(ctx, eltype, param, dict [key], out elem_data)) { data = null; return(false); } dd.Add(key, elem_data); } data = dd; return(true); } } UnsafeString strd = ctx.Request.Data.Get(name); return(TryConvertUnsafeString(ctx, dest, param, strd, out data)); }
public void Default(IManosContext ctx, string default_value = "I AM DEFAULT") { ctx.Response.End(default_value); }