public CustomHttpResponse(WebServerResponse webServerResponse)
 {
     _statusCode = webServerResponse.StatusCode;
     _headers    = webServerResponse.Headers;
     if (webServerResponse.BodyData != null)
     {
         _bodyData = webServerResponse.BodyData;
     }
     else
     {
         BodyString = webServerResponse.BodyString;
     }
 }
Beispiel #2
0
        public WebServerResponse generateResponse(WebServerRequest request)
        {
            System.Collections.Specialized.NameValueCollection extraHeaders = new System.Collections.Specialized.NameValueCollection();

            //Session handling
            Dictionary <string, object> sessionData;

            if (request.Cookies["SESSID"] != null && sessionsData.ContainsKey(request.Cookies["SESSID"]))
            {
                sessionData = sessionsData[request.Cookies["SESSID"]];
            }
            else
            {
                string sessionId = Guid.NewGuid().ToString("N");
                extraHeaders.Add("Set-Cookie", String.Format("{0}={1}; Path=/", "SESSID", sessionId));
                sessionData             = new Dictionary <string, object>();
                sessionsData[sessionId] = sessionData;
            }

            string            path = request.Path.Trim(new char[] { ' ', '/' });
            WebServerResponse response;

            if (path == "test")
            {
                response = new WebServerResponse();
                //Calculate response body
                string responseBody = "";
                responseBody       += "<html><head>\r\n";
                responseBody       += "\r\n</head><body>\r\n";
                responseBody       += "<h1>Successfully Connected</h1>";
                responseBody       += "\r\n</body></html>";
                response.BodyString = responseBody;
            }
            else if (path == "json" || path.StartsWith("json/"))
            {
                response = ServeJson(request, sessionData);
            }
            else
            {
                string filePath = Path.Combine(HtdocsPath.FullName, path.Replace('/', '\\'));
                response = ServeFile(filePath);
            }
            if (extraHeaders.Count > 0)
            {
                response.Headers.Add(extraHeaders);
            }

            return(response);
        }
Beispiel #3
0
        protected WebServerResponse ServeFile(string filePath)
        {
            WebServerResponse response    = new WebServerResponse();
            string            contentType = "text/html";

            if (Directory.Exists(filePath))
            {
                foreach (string indexPage in _indexPages)
                {
                    string path = Path.Combine(filePath, indexPage);
                    if (File.Exists(path))
                    {
                        filePath = path;
                        break;
                    }
                }
            }
            if (File.Exists(filePath))
            {
                Encoding fileEncoding;
                bool     isText = IsText(out fileEncoding, filePath);
                if (isText)
                {
                    StreamReader streamReader = new StreamReader(filePath);
                    response.BodyString = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                else
                {
                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    byte[]     data       = new byte[fileStream.Length];
                    fileStream.Read(data, 0, (int)fileStream.Length);
                    fileStream.Close();
                    response.BodyData = data;
                }
                contentType = MimeTypeHelper.GetMimeTypeByFilePath(filePath);
            }
            else
            {
                throw new HttpException(404, "Not Found");
            }

            //Set the content type
            response.Headers.Add("Content-Type", contentType);

            return(response);
        }
Beispiel #4
0
        protected WebServerResponse ServeJson(WebServerRequest request, Dictionary <string, object> sessionData)
        {
            string            contentType = "application/json";
            WebServerResponse response    = new WebServerResponse();

            string action = request.Path.Substring("/json".Length).ToLower().Trim(new char[] { '/' });

            if (action.Length > 0 && action != "compound")
            {
                if (JSONCallHandlers.ContainsKey(action))
                {
                    string requestData = null;
                    if (request.Data is string)
                    {
                        requestData = (string)request.Data;
                    }
                    response.BodyString = jsonSerializer.Serialize(JSONCallHandlers[action](requestData, sessionData));
                }
                else
                {
                    throw new HttpException(404, "Not Found");
                }
            }
            else
            {
                Dictionary <string, string> postData;
                if (request.Data is Dictionary <string, string> )
                {
                    postData = (Dictionary <string, string>)request.Data;
                }
                else if (request.Data is Dictionary <string, object> )
                {
                    try
                    {
                        postData = ((Dictionary <string, object>)request.Data).ToDictionary(k => k.Key, k => !(k.Value is string) ? "" : (string)k.Value);
                    }
                    catch
                    {
                        throw new HttpException(400, "Bad Request");
                    }
                }
                else
                {
                    throw new HttpException(400, "Bad Request");
                }

                Dictionary <string, object> returnData = new Dictionary <string, object>();
                foreach (KeyValuePair <string, string> pair in postData)
                {
                    string key = pair.Key.ToLower();
                    try
                    {
                        if (JSONCallHandlers.ContainsKey(key))
                        {
                            if (!(pair.Value is string))
                            {
                                returnData.Add(key, new { Error = true, ErrorCode = 400, ErrorMessage = "Bad Request" });
                                continue;
                            }
                            returnData.Add(key, JSONCallHandlers[key](pair.Value, sessionData));
                        }
                        else
                        {
                            returnData.Add(key, new { Error = true, ErrorCode = 404, ErrorMessage = "Not Found" });
                        }
                    }
                    catch (HttpException ex)
                    {
                        returnData.Add(key, new { Error = true, ErrorCode = ex.ErrorCode, ErrorMessage = ex.Message });
                    }
                    catch
                    {
                        returnData.Add(key, new { Error = true, ErrorCode = 500, ErrorMessage = "Internal Server Error" });
                    }
                }
                response.BodyString = jsonSerializer.Serialize(returnData);
            }

            //Set the content type
            response.Headers.Add("Content-Type", contentType);

            return(response);
        }
Beispiel #5
0
        protected void handleRequest(Dictionary <string, object> request)
        {
            processRequestThreads.Add(System.Threading.Thread.CurrentThread);
            if (!request.ContainsKey(idKey) || !request.ContainsKey(pathKey))
            {
                return;
            }
            int id = (int)request[idKey];

            object responceObj = null;

            try
            {
                WebServerRequest webServerRequest = new WebServerRequest();
                webServerRequest.Path = (string)request[pathKey];

                if (request.ContainsKey(dataKey))
                {
                    if (request[dataKey] is string)
                    {
                        webServerRequest.Data = (string)request[dataKey];
                    }
                    else if (request[dataKey] != null)
                    {
                        webServerRequest.Data = request[dataKey];
                    }
                }
                if (request.ContainsKey(cookiesKey) && request[cookiesKey] is Dictionary <string, object> )
                {
                    System.Collections.Specialized.NameValueCollection cookies = new System.Collections.Specialized.NameValueCollection();
                    foreach (KeyValuePair <string, object> cookie in (Dictionary <string, object>)request[cookiesKey])
                    {
                        if (!(cookie.Value is string))
                        {
                            continue;
                        }
                        cookies.Add(cookie.Key, (string)cookie.Value);
                    }
                    webServerRequest.Cookies = cookies;
                }


                WebServerResponse response = _webServer.generateResponse(webServerRequest);
                List <SerializableKeyValuePair <string, string> > headers = new List <SerializableKeyValuePair <string, string> >();
                for (int i = 0; i < response.Headers.AllKeys.Length; i++)
                {
                    string key = response.Headers.Keys[i];
                    foreach (string value in response.Headers.GetValues(i))
                    {
                        headers.Add(new SerializableKeyValuePair <string, string>(key, value));
                    }
                }
                responceObj = new { id = id, status = response.StatusCode, body = response.BodyString, headers = headers };
            }
            catch (HttpException ex)
            {
                responceObj = new { id = id, status = ex.GetHttpCode().ToString() + " " + ex.Message };
            }
            catch
            {
                responceObj = new { id = id, status = "500 Internal Server Error" };
            }
            reply(responceObj);
            processRequestThreads.Remove(System.Threading.Thread.CurrentThread);
        }