Exemple #1
0
        private static IDictionary <string, string> ParsePostData(HttpListenerRequest request)
        {
            var result = new Dictionary <string, string>();

            try
            {
                if (request.HasEntityBody)
                {
                    Stream       body     = request.InputStream;
                    Encoding     encoding = request.ContentEncoding;
                    StreamReader reader   = new System.IO.StreamReader(body, encoding);

                    if (request.ContentType == "application/x-www-form-urlencoded")
                    {
                        string   s     = reader.ReadToEnd();
                        string[] pairs = s.Split('&');

                        foreach (var p in pairs)
                        {
                            var pair = p.Split('=');
                            if (pair.Length == 2)
                            {
                                //Console.WriteLine(pair[0] + ": " + pair[1]);
                                result.Add(WebUtility.UrlDecode(pair[0]),
                                           WebUtility.UrlDecode(pair[1]));
                            }
                            else
                            {
                                ChatRuntime.Warn("BAD KV-PAIR: " + p);
                                //throw new Exception("BAD-PAIR: " + p);
                            }
                        }
                    }

                    body.Close();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                ChatRuntime.Warn(ex);
            }

            return(result);
        }
        public void Run()
        {
            while (listener.IsListening)
            {
                ThreadPool.QueueUserWorkItem(c =>
                {
                    var ctx = c as HttpListenerContext;
                    try
                    {
                        if (ctx == null)
                        {
                            return;
                        }

                        var buf = Encoding.UTF8.GetBytes(responder(ctx.Request));
                        ctx.Response.ContentLength64 = buf.Length;
                        ctx.Response.ContentType     = "application/json";
                        ctx.Response.AppendHeader("Access-Control-Allow-Origin", "*");
                        ctx.Response.AppendHeader("Access-Control-Allow-Methods", "POST.OPTIONS");
                        ctx.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");
                        ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                    }
                    catch (Exception e)
                    {
                        ChatRuntime.Warn(e.ToString());
                    }
                    finally
                    {
                        try
                        {
                            if (ctx != null)
                            {
                                ctx.Response.OutputStream.Close();
                            }
                        }
                        catch (Exception) { /* ignore */ }
                    }
                }, listener.GetContext());
            }
        }
Exemple #3
0
        public void Run()
        {
            while (listener.IsListening)
            {
                ThreadPool.QueueUserWorkItem(c =>
                {
                    var ctx = c as HttpListenerContext;
                    try
                    {
                        if (ctx == null)
                        {
                            return;
                        }

                        var rstr = responderFunc(ctx.Request);
                        var buf  = Encoding.UTF8.GetBytes(rstr);
                        ctx.Response.ContentLength64 = buf.Length;
                        ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                    }
                    catch (Exception e)
                    {
                        ChatRuntime.Warn(e.ToString());
                    }
                    finally
                    {
                        try
                        {
                            if (ctx != null)
                            {
                                ctx.Response.OutputStream.Close();
                            }
                        }
                        catch (Exception) { /* ignore */ }
                    }
                }, listener.GetContext());
            }
        }
        private static IDictionary <string, string> ParsePostData(HttpListenerRequest request)
        {
            Dictionary <string, string> result = null; //new Dictionary<string, string>();

            try
            {
                if (request.HasEntityBody)
                {
                    StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding);

                    if (request.ContentType.StartsWith("application/json",
                                                       StringComparison.InvariantCulture)) //== -> startsWith 11/10
                    {
                        string json = reader.ReadToEnd();
                        //Console.WriteLine("json: " + json);
                        result = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Content-type: " + request.ContentType);
                    }

                    request.InputStream.Close();
                    reader.Close();
                }
                else
                {
                    result = new Dictionary <string, string>(); // no-op
                }
            }
            catch (Exception ex)
            {
                ChatRuntime.Warn(ex);
            }

            return(result);
        }
Exemple #5
0
        public static string SendResponse(HttpListenerRequest request)
        {
            var html = IndexPageContent.Replace("%%URL%%", SERVER_URL);

            IDictionary <string, string> kvs = new Dictionary <string, string>();

            try
            {
                kvs = ParsePostData(request);
            }
            catch (Exception ex)
            {
                ChatRuntime.Warn(ex);
            }

            var path = kvs.ContainsKey("path") ? kvs["path"] : null;
            var code = kvs.ContainsKey("code") ? kvs["code"] : null;
            var mode = kvs.ContainsKey("mode") ? kvs["mode"] : "validate";

            if (!String.IsNullOrEmpty(path)) // fetch code from file
            {
                using (var wb = new WebClient()) code = wb.DownloadString(path);
            }

            if (String.IsNullOrEmpty(code))
            {
                return(html.Replace("%%CODE%%", "Enter your script here"));
            }

            html = html.Replace("%%CODE%%", WebUtility.HtmlEncode(code));
            html = html.Replace("%%CCLASS%%", "shown");

            // only process the selection if there is one
            if (kvs.ContainsKey("selectionStart"))
            {
                code = kvs["selection"];
                html = html.Replace("%%STARTINDEX%%", kvs["selectionStart"]);
                html = html.Replace("%%ENDINDEX%%", kvs["selectionEnd"]);
            }

            try
            {
                string content = String.Empty;
                var    globals = new Dictionary <string, object>();
                runtime            = new ChatRuntime(Client.AppConfig.TAC);
                runtime.strictMode = false;                                                                                      // allow unbound symbols/functions
                runtime.ParseText(code, kvs.ContainsKey("useValidators") && kvs["useValidators"].Equals("true") ? false : true); // true to disable validators
                runtime.Chats().ForEach(c => { content += c.ToTree() + "\n\n"; });

                var result = string.Empty;
                if (mode == "execute")
                {
                    // first run any chats marked with 'preload=true'
                    runtime.Preload(globals);

                    // run the first chat with all timing disabled
                    result = WebUtility.HtmlEncode(runtime.InvokeImmediate(globals));

                    if (result.IsNullOrEmpty())
                    {
                        result = "[empty-string]";
                    }
                }

                html = html.Replace("%%RESULT%%", WebUtility.HtmlEncode(content));
                html = html.Replace("%%EXECUTE%%", result);
                html = html.Replace("%%RCLASS%%", "success");
            }
            catch (ParseException ex)
            {
                OnError(ref html, ex, ex.lineNumber);
            }
            catch (Exception e)
            {
                OnError(ref html, e, -1);
            }

            return(html);
        }