Beispiel #1
0
 /// <summary>
 /// Class XtrmAddons Net Http Web Server Request Route Constructor
 /// </summary>
 /// <param name="uri"></param>
 public WebServerRequestRoute(WebServerRequestUrl uri)
 {
     Uri      = uri;
     Response = new WebServerResponseData(Uri.RelativeUrl)
     {
         ContentType = "text/html"
     };
 }
Beispiel #2
0
        /// <summary>
        /// Method to get the default response of the server.
        /// </summary>
        private WebServerResponseData GetDefaultResponse()
        {
            log.Warn("Trying to serve default Http response for default or special requests.");

            WebServerResponseData response = null;

            try
            {
                // Check for special ico request.
                if (Uri.ComponentName == "Index" && Uri.Extension == ".ico")
                {
                    log.Debug("Serving Http response for special .ico request.");

                    response = new WebServerResponseData(Uri.RelativeUrl);
                    response.ServeFile(@"Assets\Images\Icons\Favicon.ico");
                    return(response);
                }

                // Create url filename.
                string filename = Uri.RelativeUrl;

                // Check valid url default format.
                if (Uri.RelativeUrl == "" || Uri.RelativeUrl == "/")
                {
                    log.Debug($"Initialize default filename format.");
                    filename = "/index.html";
                }

                // Serve direct link.
                if (Uri.Extension != "" || filename == "/index.html")
                {
                    log.Debug("Serving Http response for default server link [Empty | / | index.html].");

                    response = new WebServerResponseData(Uri.RelativeUrl);
                    response.ServeFile(filename, "Public");
                    return(response);
                }
            }
            catch (Exception ex)
            {
                log.Info(ex.Output(), ex);
                return(null);
            }

            return(response);
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private WebServerResponseData GetResponseData()
        {
            log.Info($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {Uri.RelativeUrl}");
            log.Debug($"Uri.ComponentName : {Uri.ComponentName}");;
            log.Debug($"Uri.Extension : {Uri.Extension}");

            // Try to get default server response.
            WebServerResponseData response = GetDefaultResponse();

            if (response != null)
            {
                return(response);
            }

            log.Warn("Trying to serve Http response for generated URL document.");

            try
            {
                object[] post = null;

                if (IsPOST)
                {
                    post = new object[] { _POST };

                    log.Info($"Http method invoke : {ComponentMethodRoute}, {Component}, {_POST.Count}, {post.Length}");
                }
                else
                {
                    log.Info($"Http method invoke : {ComponentMethodRoute}, {Component}");
                }

                _router = ComponentMethodRoute.Invoke(Component, post);
            }
            catch (Exception e)
            {
                log.Debug("Invoke component method failed.");
                log.Debug(e.Output(), e);
                log.Debug($"URI AbsoluteUrl : {Uri.AbsoluteUrl}");
                log.Debug($"URI ComponentName : {Uri.ComponentName}");
                log.Debug($"Component : {Component}");
                log.Debug($"ComponentMethodRoute : {ComponentMethodRoute}");

                if (Uri.Params != null)
                {
                    log.Debug($"URI Params Length : {Uri.Params.Length}");
                }
                else
                {
                    log.Debug($"URI Params Length : 0");
                }

                log.Debug("End server request processed with error...");

                throw new InvalidDataException(e.Message, e);
            }

            log.Debug("End server request process...");

            response = (WebServerResponseData)_router;

            return(response);



            /*
             * try
             * {
             *  log.Debug("Serving Http response for direct link.");
             *
             *  string filename = Uri.RelativeUrl;
             *
             *  if (Uri.RelativeUrl == "" || Uri.RelativeUrl == "/")
             *  {
             *      log.Debug("Empty or / URL => /index.html");
             *
             *      filename = "/index.html";
             *  }
             *
             *  if (Uri.Extension != "" || filename == "/index.html")
             *  {
             *      log.Debug("Empty or / URL => [Public]/index.html");
             *
             *      response = new WebServerResponseData(Uri.RelativeUrl);
             *      response.ServeFile(filename, "Public");
             *      return response;
             *  }
             *
             *  log.Info("Serving Http response for direct link => FileNotFoundException.");
             *
             *  throw new FileNotFoundException();
             * }
             *
             * // Try to generate URL document if file is not found.
             #pragma warning disable CS0168
             * catch (FileNotFoundException fe)
             * {
             *  log.Info("Serving Http response for generated URL document", fe);
             *
             *  try
             *  {
             *      object[] post = new object[] { };
             *
             *      if (IsPOST)
             *      {
             *          string data = _POST;
             *          post = new object[] { data };
             *      }
             *
             *
             *      if (IsPOST)
             *          _router = ComponentMethodRoute.Invoke(Component, post);
             *      else
             *          _router = ComponentMethodRoute.Invoke(Component, null);
             *  }
             *  catch (Exception e)
             *  {
             *      log.Debug("Invoke component method failed.");
             *      log.Debug(e.GetType() + " : " + e.Message);
             *      log.Debug(string.Format("URL : {0}", Uri.AbsoluteUrl));
             *      log.Debug(string.Format("URI : {0}", Uri.RelativeUrl));
             *      log.Debug(string.Format("ComponentName : {0}", Uri.ComponentName));
             *      log.Debug(string.Format("ViewName : {0}", Uri.MethodName));
             *      log.Debug(string.Format("Component : {0}", Component));
             *      log.Debug(string.Format("ComponentMethodRoute : {0}", ComponentMethodRoute));
             *      if (Uri.Params != null)
             *          log.Debug(string.Format("Params : {0}", Uri.Params.Length));
             *      else
             *          log.Debug("Params : 0");
             *
             *      log.Debug("End server request process with error...");
             *
             *      throw new InvalidDataException(e.Message, e);
             *  }
             *
             *  log.Debug("End server request process...");
             * }
             *
             * // Return Response error server 500.
             * catch (Exception e)
             * {
             *  return null;
             * }
             */
        }
Beispiel #4
0
        /// <summary>
        /// Method to run the web server.
        /// </summary>
        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                log.Info("Web server is running...");
                try
                {
                    while (Listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            HttpListenerContext ctx = c as HttpListenerContext;

                            try
                            {
                                WebServerResponseData response = GetResponse(ctx);
                                byte[] buffer;

                                if (response == null)
                                {
                                    throw new FileNotFoundException("Null response.");
                                }

                                // Add content type to response.
                                ctx.Response.Headers[HttpResponseHeader.ContentType] = response.ContentType;

                                // Set content to byte buffer.
                                if (response.ContentType.Contains("text") || response.ContentType.Contains("html"))
                                {
                                    //buffer = Encoding.Unicode.GetBytes(WPFString.ConvertByteToString(response.Content));
                                    buffer = Encoding.UTF8.GetBytes(response.Content.ConvertByteToString(Encoding.Unicode));
                                    //buffer = Encoding.Convert(Encoding.Unicode, Encoding.Default, buffer);
                                }
                                else
                                {
                                    buffer = response.Content;
                                }

                                // Add content length to response.
                                ctx.Response.ContentLength64 = buffer.Length;

                                // Add status code.
                                ctx.Response.StatusCode = response.StatusCode;

                                ctx.Response.Cookies = response.Cookies;

                                // Write output to buffer.
                                ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
                            }

                            catch (FileNotFoundException e)
                            {
                                log.Error("Server response error :", e);

                                Output(ctx, string.Format(
                                           "<html><head>"
                                           + "<meta http-equiv=\"Content - Type\" content=\"text/html; charset=UTF-8\">"
                                           + "<charset=\"utf-8\">"
                                           + "</head><body><center>"
                                           + "404 Error : Page not found !<br>{0}<br>{1}<br>{2}</center></body></html>"

                                           , DateTime.Now
                                           , e.GetType() + " : " + e.Message
                                           , e.StackTrace)
                                       );
                            }

                            catch (Exception e)
                            {
                                log.Error("Server response error :", e);

                                Output(ctx, string.Format(
                                           "<html><head>"
                                           + "<meta http-equiv=\"Content - Type\" content=\"text/html; charset=UTF-8\">"
                                           + "<charset=\"utf-8\">"
                                           + "</head><body><center>"
                                           + "500 Error : Bad server request !<br>{0}<br>{1}<br>{2}</center></body></html>"

                                           , DateTime.Now
                                           , e.GetType() + " : " + e.Message
                                           , e.StackTrace)
                                       );
                            }

                            // always close the stream
                            finally
                            {
                                ctx.Response.OutputStream.Close();
                            }
                        }, Listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }
Beispiel #5
0
        /// <summary>
        /// Method to get a list of associated Sections of an User.
        /// </summary>
        /// <returns>WPF Web Server response data of list of Sections.</returns>
        public override WebServerResponseData Index()
        {
            log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name}");
            log.Info($"{MethodBase.GetCurrentMethod().Name} : Serving Picture request. Please wait...");

            if (!IsAuth())
            {
                log.Info($"{MethodBase.GetCurrentMethod().Name} : Return response user not auth.");
                return(ResponseNotAuth());
            }

            try
            {
                var a = Uri.QueryString;

                // Check if request params are correct.
                if (Uri.QueryString.Count == 0)
                {
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : The Request is empty.");
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : Return response => Picture not found or doesn't exists.");
                    return(ResponseError404("Picture not found or doesn't exists."));
                }

                // Check if request params are correct.
                if (!Uri.QueryString.Keys.Cast <string>().Contains("id"))
                {
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : Request param [id] not found.");
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : Return response => Picture not found or doesn't exists.");
                    return(ResponseError404("Picture not found or doesn't exists."));
                }

                int    id   = int.Parse(Uri.QueryString["id"]);
                string type = Uri.QueryString["type"];

                // Get user and dependencies.
                UserEntity    user   = GetAuthUser();
                PictureEntity entity = RouteHelper.GetUserPicture(id, user);

                var aa = entity;

                // Check if request params are correct.
                if (entity == null)
                {
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : Request Picture not found.");
                    log.Info($"{MethodBase.GetCurrentMethod().Name} : Return response => Picture not found or doesn't exists.");
                    return(ResponseError404("Picture not found or doesn't exists."));
                }

                Response = new WebServerResponseData(Uri.AbsoluteUrl);

                if (File.Exists(entity.PicturePath))
                {
                    Response.ServeFileUnSafe(entity.PicturePath);
                }
                else
                {
                    // Convert the image to byte[]
                    MemoryStream stream = new MemoryStream();
                    Properties.Images.error_404.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] imageBytes = stream.ToArray();

                    // Add the bytes to the response.
                    Response.SetContentType("error-404.png");
                    Response.ContentAppend(imageBytes);
                }

                return(Response);
            }
            catch (Exception e)
            {
                log.Fatal($"{MethodBase.GetCurrentMethod().Name} : Serving picture request failed.", e);
                return(ResponseError500());
            }
        }