Example #1
0
        void ProcessRequest(string name, string id, IMyHttpContext context)
        {
            var Request  = context.Request;
            var Response = context.Response;

            try
            {
                Firefly.Box.Context.Current.SetNonUIThread();
                var responseType = (System.Web.HttpContext.Current.Request.Params["_response"] ?? "J").ToUpper();

                if (!PrgnameTypeRequest && !PostOnly)
                {//fix id stuff
                    var url = Request.RawUrl;
                    var z   = url.IndexOf('?');
                    if (z >= 0)
                    {
                        url = url.Remove(z);
                    }
                    var x = url.Split('/');
                    id = null;
                    if (x[x.Length - 1] != name)
                    {
                        id = x[x.Length - 1];
                    }
                }
                ENV.IO.WebWriter.ThereWasAnOutput();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    ApiItem vmcFactory;
                    if (_controllers.TryGetValue(name.ToLower(), out vmcFactory))
                    {
                        var vmc = vmcFactory.Create();
                        {
                            Response.ContentType = "application/json";
                            var method = Request.HttpMethod.ToLower();

                            switch (method)
                            {
                            case "get":
                                if (!vmc.AllowRead)
                                {
                                    MethodNotAllowed(Response, vmc, method);
                                    return;
                                }
                                using (var sw = new System.IO.StringWriter())
                                {
                                    ISerializedObjectWriter w = new JsonISerializedObjectWriter(sw);
                                    if (responseType.StartsWith("X"))
                                    {
                                        w = new XmlISerializedObjectWriter(new XmlTextWriter(sw));
                                        Response.ContentType = "text/xml";
                                    }
                                    else if (responseType.StartsWith("C"))
                                    {
                                        w = new CSVISerializedObjectWriter(sw);
                                        Response.ContentType = "application/csv";
                                        Response.AddHeader("Content-Disposition", "attachment;filename=" + name + ".csv");
                                    }
                                    else if (responseType.StartsWith("H"))
                                    {
                                        ResponseIsHtml(Response);
                                        w = new HTMLISerializedObjectWriter(sw, name)
                                        {
                                            BodyAddition = optionalUrlParametersHtmlDoc
                                        };
                                    }
                                    if (responseType.StartsWith("D"))
                                    {
                                        Response.ContentType = "text/plain";
                                        sw.WriteLine("// /" + name + "?_responseType=" + responseType);
                                        sw.WriteLine();
                                        if (responseType.StartsWith("DE"))
                                        {
                                            vmc.Describe(sw, name);
                                        }
                                        else if (responseType.StartsWith("DCF"))
                                        {
                                            vmc.FullColumnList(sw);
                                        }
                                        else if (responseType.StartsWith("DC"))
                                        {
                                            vmc.ColumnKeys(sw);
                                        }
                                        else
                                        {
                                            vmc.CreateTypeScriptInterface(sw, name, Request.Path);
                                        }
                                    }
                                    else if (string.IsNullOrEmpty(id))
                                    {
                                        vmc.GetRows(Request).ToWriter(w);
                                    }
                                    else
                                    {
                                        try
                                        {
                                            vmc.GetRow(id).ToWriter(w);
                                        }
                                        catch (NotFoundException)
                                        {
                                            vmc.ModelState.ApplyNotFound(Response);
                                            return;
                                        }
                                    }
                                    w.Dispose();
                                    Response.Write(sw.ToString());
                                    break;
                                }

                            case "post":
                                PerformInsertOrUpdate(Response, Request, vmc, vmc.AllowInsert, "POST", di =>
                                {
                                    var r = vmc.Insert(di);
                                    if (r != null)
                                    {
                                        Response.StatusCode = 201;
                                    }
                                    return(r);
                                });
                                break;

                            case "put":
                                PerformInsertOrUpdate(Response, Request, vmc, vmc.AllowUpdate, "PUT", di => vmc.Update(id, di));
                                break;

                            case "delete":
                                PerformInsertOrUpdateOrDelete(Response, vmc, vmc.AllowDelete, "DELETE", () =>
                                {
                                    vmc.Delete(id);
                                    return(null);
                                });
                                break;

                            case "options":
                                var allowedMethods = "GET,HEAD,PATCH";
                                if (vmc.AllowUpdate)
                                {
                                    allowedMethods += ",PUT";
                                }
                                if (vmc.AllowInsert)
                                {
                                    allowedMethods += ",POST";
                                }
                                if (vmc.AllowDelete)
                                {
                                    allowedMethods += ",DELETE";
                                }
                                Response.AddHeader("Access-Control-Allow-Methods", allowedMethods);
                                Response.StatusCode = 204;
                                return;

                            case "default":
                            {
                                MethodNotAllowed(Response, vmc, Request.HttpMethod);
                            }
                            break;
                            }
                        }
                    }
                    else
                    {
                        Response.StatusCode = 404;
                        return;
                    }
                }
                else
                {
                    if (DisableDocumentation)
                    {
                        return;
                    }
                    ResponseIsHtml(Response);
                    Response.Write(HTMLISerializedObjectWriter.HTMLPageHeader);
                    Response.Write("<div class=\"container\">");
                    Response.Write($"<h1>{Request.Path} Documentation</h1>");
                    foreach (var item in _controllers.Values)
                    {
                        Response.Write("<h2>" + item.Name + "</h2>");
                        string url = Request.Path;
                        if (PrgnameTypeRequest)
                        {
                            url = Request.RawUrl + "&" + ApiParameterName + "=" + item.Name;
                        }
                        else
                        {
                            if (!url.EndsWith("/"))
                            {
                                url += "/";
                            }
                            url += item.Name;
                        }
                        var sw = new StringBuilder();
                        void x(string linkName, string linkResponseType)
                        {
                            var linkUrl = url;

                            if (!string.IsNullOrEmpty(linkResponseType))
                            {
                                if (linkUrl.Contains("?"))
                                {
                                    linkUrl += "&";
                                }
                                else
                                {
                                    linkUrl += "?";
                                }
                                linkUrl += "_response=" + linkResponseType;
                            }
                            if (sw.Length != 0)
                            {
                                sw.Append(" | ");
                            }
                            sw.Append($"<a href=\"{linkUrl}\">{linkName}</a> ");
                        };
                        x("JSON", "");
                        x("XML", "xml");
                        x("CSV", "csv");
                        x("HTML", "html");

                        Response.Write(sw.ToString());


                        try
                        {
                            var c = item.Create();



                            var dl = new DataList();
                            void addLine(string action, bool dontNeedId = false)
                            {
                                var i = dl.AddItem();

                                i.Set("HTTP Method", action);
                                i.Set("URL", url +
                                      (dontNeedId ? "" : (this.PrgnameTypeRequest ? "&" + IdParameterName + "={id}" : "/{id}")) +
                                      (!string.IsNullOrEmpty(HttpMethodParamName) ? "&" + HttpMethodParamName + "=" + action : ""));
                            }
                            if (c.AllowRead)
                            {
                                addLine("GET", true);
                            }
                            if (c.AllowInsert)
                            {
                                addLine("POST", true);
                            }
                            if (c.AllowRead)
                            {
                                addLine("GET");
                            }
                            if (c.AllowUpdate)
                            {
                                addLine("PUT");
                            }
                            if (c.AllowDelete)
                            {
                                addLine("DELETE");
                            }

                            string api = dl.ToHTML();



                            dl = new DataList();
                            c.ProvideMembersTo(dl);
                            string bodyParameters = dl.ToHTML();

                            string getCodeSnippet(Action <System.IO.TextWriter> method)
                            {
                                using (var tw = new System.IO.StringWriter())
                                {
                                    method(tw);
                                    return(ENV.UserMethods.Instance.XMLVal(tw.ToString()));
                                }
                            }

                            Response.Write($@"
<div>

  <!-- Nav tabs -->
  <ul class=""nav nav-tabs"" role=""tablist"">
    <li role=""presentation"" class=""active""><a href=""#{item.Name}_api"" aria-controls=""api"" role=""tab"" data-toggle=""tab"">API</a></li>
    <li role=""presentation""><a href=""#{item.Name}_parameters"" aria-controls=""profile"" role=""tab"" data-toggle=""tab"">Body Parameters</a></li>
    <li role=""presentation""><a href=""#{item.Name}_settings"" aria-controls=""messages"" role=""tab"" data-toggle=""tab"">Typescript Interface</a></li>
    <li role=""presentation""><a href=""#{item.Name}_interface"" aria-controls=""settings"" role=""tab"" data-toggle=""tab"">Typescript Radweb</a></li>
    <li role=""presentation""><a href=""#{item.Name}_keys"" aria-controls=""keys"" role=""tab"" data-toggle=""tab"">Typescript Column Keys</a></li>
  </ul>

  <!-- Tab panes -->
  <div class=""tab-content"">
    <div role=""tabpanel"" class=""tab-pane active"" id=""{item.Name}_api"">{ api}</div>
    <div role=""tabpanel"" class=""tab-pane"" id=""{item.Name}_parameters"">{bodyParameters}</div>
    <div role=""tabpanel"" class=""tab-pane"" id=""{item.Name}_interface""><pre>{getCodeSnippet(tw => c.CreateTypeScriptClass(tw, item.Name, url))}</pre></div>
    <div role=""tabpanel"" class=""tab-pane"" id=""{item.Name}_settings""><pre>{getCodeSnippet(tw => c.CreateTypeScriptInterface(tw, item.Name, url))}</pre></div>
    <div role=""tabpanel"" class=""tab-pane"" id=""{item.Name}_keys""><pre>{getCodeSnippet(c.ColumnKeys)}</pre></div>
  </div>

</div>
");
                        }
                        catch (Exception ex)
                        {
                            Response.Write("Error: " + ex.Message);
                        }
                    }

                    Response.Write(optionalUrlParametersHtmlDoc);
                    Response.Write("</div>");
                    Response.Write(@"<script>" + StoredStuff.JQuery + @"</script>");
                    Response.Write(@"<script >" + StoredStuff.BootstrapJs + "</script>");
                }
            }
            finally
            {
            }
        }
Example #2
0
 public WebHelper(bool postOnly = false)
 {
     _context = new HttpContextBridgeToIHttpContext(System.Web.HttpContext.Current, postOnly, null);
 }