Ejemplo n.º 1
0
        public async Task StartAsync()
        {
            try
            {
                HttpListener.Start();
                isFinished = new ManualResetEvent(false);
                logger?.LogInformation("HttpListener for requests on [{0}] running!", string.Join(", ", UriPrefixes));

                while (!isFinished.WaitOne(0) && HttpListener.IsListening)
                {
                    var ctx = await HttpListener.GetContextAsync();

                    Request  request  = new Request(ctx);
                    Response response = new Response(ctx);
                    // logger?.LogDebug("{0}: {1} {2}", DateTime.Now, request.Method, request.Endpoint);
                    Console.WriteLine("HttpListener {0}: {1} {2}", DateTime.Now, request.Method, request.Endpoint);

                    OnRequest?.Invoke(request, response);
                }
            }
            catch (Exception e)
            {
                logger?.LogError("HttpListener StartAsync Error:{0}", e.Message);
            }
            finally
            {
                HttpListener = null;
            }

            logger?.LogInformation("HttpListener for requests on {0} FINISHED", string.Join(", ", UriPrefixes));
        }
Ejemplo n.º 2
0
        public static object Request(RequestType what, RequestProperty want)
        {
            object r;

            r = OnRequest?.Invoke(what, want);
            return(r);
        }
Ejemplo n.º 3
0
 private static void ConfigureRejuicer()
 {
     OnRequest.ForJs("~/Combined-{0}.js").Combine
     .File("~/Scripts/jquery-1.7.2.js")
     .File("~/Scripts/jquery-ui-1.8.19")
     .File("~/Scripts/jquery.mobile-1.1.0")
     .File("~/Scripts/jquery.unobtrusive-ajax.js")
     .File("~/Scripts/jquery.validate.js")
     .File("~/Scripts/jquery.validate.unobtrusive.js")
     .File("~/Scripts/SyntaxHighlighter/shCore.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushBash.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushCss.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushCSharp.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushJScript.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushPowerShell.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushRuby.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushSql.js")
     .File("~/Scripts/SyntaxHighlighter/shBrushXml.js")
     .File("~/Scripts/modernizr-2.5.3.js")
     .File("~/Scripts/FileUploader/fileuploader.js")
     .File("~/Scripts/mblog/mblog.js")
     .Configure();
     OnRequest.ForCss("~/Combined-{0}.css").Compact
     .File("~/Content/Styles/reset.css")
     .File("~/Content/SyntaxHighlighter/shCore.css")
     .File("~/Content/SyntaxHighlighter/shThemeRDark.css")
     .File("~/Content/fileuploader/fileuploader.css")
     .Configure();
 }
Ejemplo n.º 4
0
        /// <summary>
        /// This method is called to process an incoming payload.
        /// </summary>
        /// <param name="rq">The message to process.</param>
        /// <param name="responses">The return path for the message.</param>
        public virtual async Task ProcessRequest(TransmissionPayload rq, List <TransmissionPayload> responses)
        {
            int start = StatisticsInternal.ActiveIncrement();

            try
            {
                var header = rq.Message.ToServiceMessageHeader();

                H handler;
                if (!SupportedResolve(header, out handler))
                {
                    OnRequestUnresolved?.Invoke(this, rq);
                    throw new CommandNotSupportedException(rq.Id, header, GetType());
                }

                OnRequest?.Invoke(this, rq);
                //Call the registered command.
                await handler.Execute(rq, responses);
            }
            catch (Exception)
            {
                StatisticsInternal.ErrorIncrement();
                //throw any errors back out to the dispatcher.
                throw;
            }
            finally
            {
                StatisticsInternal.ActiveDecrement(start);
            }
        }
Ejemplo n.º 5
0
        public void ReadCallback(IAsyncResult ar)
        {
            var state     = (HubState)ar.AsyncState;
            var bytesRead = state.WorkSocket.EndReceive(ar);

            if (bytesRead <= 0)
            {
                return;
            }
            bool recv;

            try
            {
                recv = state.Receive(bytesRead);
            }
            catch (Exception e)
            {
                state.SendError(e);
                recv = true;
            }

            if (recv)
            {
                OnRequest?.Invoke(this, state);
                Send(state);
            }
            else
            {
                state.WorkSocket.BeginReceive(state.Buffer, state.BufferLen, Config.BufferSize, 0,
                                              ReadCallback, state);
            }
        }
Ejemplo n.º 6
0
        public void FluentConfiguration_Configure_AddsRejuicerModelToConfiguration()
        {
            OnRequest.ForJs("~/Scripts/Combined-Test.js").Combine
            .FilesIn("~/Scripts/").Matching("*.js").Configure();

            Assert.AreEqual(1, RejuicerEngine._configurations.Count);
        }
Ejemplo n.º 7
0
        private async void ListenAsyncImpl()
        {
            //if this method fails due to an access denied error, run visual studio as an administrator
            _listener.Start();
            while (_listener.IsListening)
            {
                HttpListenerContext ctx = null;

                try
                {
                    ctx = await _listener.GetContextAsync().ConfigureAwait(false);
                }
                catch (HttpListenerException e)
                {
                    OnError?.Invoke(this, e);
                }

                if (ctx == null)
                {
                    return;
                }

                OnRequest?.Invoke(this, ctx);
            }
        }
Ejemplo n.º 8
0
        public Website(string[] prefixes, OnRequest request)
        {
            this.Prefixes  = prefixes;
            this.onRequest = request;

            issipmle = false;
        }
Ejemplo n.º 9
0
        void ProcessRequest(HttpListenerContext context, OnRequest callback)
        {
            var    request    = context.Request;
            var    response   = context.Response;
            string outputHtml = null;

            try             // ユーザ処理でコケたら500返す。それ以外は200にしちゃってるがマズければ番号ももらうようにした方がいいのかも。
            {
                var bodyData = request.InputStream;
                callback(out outputHtml, request.QueryString, bodyData);
                bodyData.Close();
                if (outputHtml != null)
                {
                    var outputData = System.Text.Encoding.UTF8.GetBytes(outputHtml);
                    response.Close(outputData, willBlock: false);
                }
                else
                {
                    response.Close();
                }
            }
            catch (System.Exception e)
            {
                Debug.LogException(e);
                response.StatusCode = (int)HttpStatusCode.InternalServerError;
                response.Close();
            }
        }
Ejemplo n.º 10
0
        // For recieving and sending replies to host as far as I can tell
        private static bool ApiReceiver(SoapAPI api)
        {
            try
            {
                // Based on what myApi.MessageType is
                switch (api.MessageType)
                {
                case MessageTypes.Request:                         // Did we recieve a request for a reply from the host?
                    OnRequest?.Invoke(api, new VmsRequestEventArgs
                    {
                        Request = new VmsCommand(api)
                    });

                    break;

                case MessageTypes.Reply:                         // Did we recieve a reply from the host?
                    OnReply?.Invoke(api, new VmsReplyEventArgs
                    {
                        Reply = new VmsCommand(api)
                    });
                    break;

                default:
                    break;
                }
                return(true);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error: " + ex.ToString());
                return(false);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Process a request.
        /// </summary>
        /// <param name="context"></param>
        private void Process(HttpListenerContext context)
        {
            OnRequest?.Invoke(context.Request);

            var filename = context.Request.Url.AbsolutePath.Substring(1);

            if (string.IsNullOrEmpty(filename))
            {
                foreach (var indexFile in indexFiles)
                {
                    if (!File.Exists(Path.Combine(root, indexFile)))
                    {
                        continue;
                    }

                    filename = indexFile;
                    break;
                }
            }

            filename = Path.Combine(root, filename);

            string mime;

            if (File.Exists(filename) && mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime))
            {
                try
                {
                    Stream input = new FileStream(filename, FileMode.Open);

                    context.Response.ContentType     = mime;
                    context.Response.ContentLength64 = input.Length;
                    context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                    context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));

                    int    nbytes;
                    byte[] buffer = new byte[1024 * 16];

                    while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        context.Response.OutputStream.Write(buffer, 0, nbytes);
                    }

                    input.Close();

                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    context.Response.OutputStream.Flush();
                }
                catch
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                }
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }

            context.Response.OutputStream.Close();
        }
Ejemplo n.º 12
0
        void ProcessRequest(HttpListenerContext context)
        {
            UnityEngine.Profiling.Profiler.BeginSample("DebugServer.ProcessRequest");
            var request = context.Request;
            var path    = DebugServerUtil.RemoveQueryString(request.RawUrl);          // QueryStringいらない

            if (path.StartsWith(fileService.pathPrefix))
            {
                Debug.Log("FileService.ProcessReq");
                fileService.ProcessRequest(context);
            }
            else
            {
                OnRequest callback = null;
                if (callbacks.TryGetValue(path, out callback))
                {
                    ProcessRequest(context, callback);
                }
                else
                {
                    var response = context.Response;
                    response.StatusCode = 404;
                    response.Close();
                }
            }
            UnityEngine.Profiling.Profiler.EndSample();
        }
Ejemplo n.º 13
0
        public static void HasConfigurationFor_WithOneLambdaPlaceholderConfigurationNotMatching_DoesNotMatch()
        {
            OnRequest.ForCss(x => "~/TestFile-" + x + ".css")
            .Compact
            .Configure();

            Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/OtherFile-{0}.css"));
        }
Ejemplo n.º 14
0
        public static void HasConfigurationFor_WithOnePlaceholderConfigurationMatching_Matches()
        {
            OnRequest.ForCss("~/TestFile-{0}.css")
            .Compact
            .Configure();

            Assert.IsTrue(RejuicerEngine.HasConfigurationFor("~/TestFile-{0}.css"));
        }
Ejemplo n.º 15
0
        public static void HasConfigurationFor_WithNoPlaceholderConfigurations_DoesNotMatchPlaceholder()
        {
            OnRequest.ForCss("~/TestFile.css")
            .Compact
            .Configure();

            Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/TestFile{0}.css"));
        }
Ejemplo n.º 16
0
        public static void HasConfigurationFor_WithOneConfigurationNotMatching_NoMatch()
        {
            OnRequest.ForCss("~/TestFile.css")
            .Compact
            .Configure();

            Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/OtherFile.css"));
        }
Ejemplo n.º 17
0
 protected override void ProcessRequest(HttpRequest request)
 {
     OnRequest?.Invoke(request);
     if (OnRequest.GetInvocationList().Length == 0)
     {
         request.Respond("This request is not handled.", System.Net.HttpStatusCode.BadRequest);
     }
 }
Ejemplo n.º 18
0
        public void FluentConfiguration_File_AddsFileToConfig()
        {
            var config = GetModelFor(OnRequest.ForJs("~/Scripts/Combined-Test.js").Combine
                                     .File("~/Scripts/myfile.js"));

            Assert.AreEqual(1, config.Count);
            Assert.AreEqual("~/Scripts/myfile.js", ((PhysicalFileSource)config[0]).VirtualPath);
        }
Ejemplo n.º 19
0
        public TransferAnswer SendRequest(TransferRequest request)
        {
            var src = request.Source;
            var dst = request.Destination;

            OnRequest?.Invoke(this, EventArgs.Empty);

            return(new TransferAnswer());
        }
Ejemplo n.º 20
0
            protected override Task Process(HttpListenerContext context, ILogger logger, CancellationToken cancellation)
            {
                if (OnRequest != null)
                {
                    return(OnRequest.Invoke(context, cancellation));
                }

                return(base.Process(context, logger, cancellation));
            }
Ejemplo n.º 21
0
        private void Listen()
        {
            Console.WriteLine("Started listening on {0}", Address);

            while (listener.IsListening)
            {
                var context = listener.GetContext();
                OnRequest?.Invoke(this, context);
            }

            Console.WriteLine("Stopped listening");
        }
Ejemplo n.º 22
0
            /// <summary>收到客户端发来的数据。子类可通过重载该方法来修改数据</summary>
            /// <param name="e"></param>
            protected override void OnReceive(ReceivedEventArgs e)
            {
                // 解析请求头
                var stream = e.Packet.GetStream();
                var entity = HttpHeader.Read(stream, HttpHeaderReadMode.Request);

                if (entity == null)
                {
                    base.OnReceive(e);
                    return;
                }

                WriteLog("{3}请求:{0} {1} [{2}]", entity.Method, entity.Url, entity.ContentLength, ID);

                Request = entity;
                OnRequest?.Invoke(this, e);

                var pxy  = Host as HttpReverseProxy;
                var host = entity.Url.IsAbsoluteUri ? entity.Url.Host : pxy.RemoteServer.Host;

                RemoteHost  = host;
                RawHost     = entity.Host;
                entity.Host = host;

                // 引用
                var r = entity.Referer;

                if (!String.IsNullOrEmpty(r))
                {
                    var ri = new Uri(r, UriKind.RelativeOrAbsolute);
                    if (ri.IsAbsoluteUri && ri.Authority == RawHost)
                    {
                        r = r.Replace(RawHost, host);
                        entity.Referer = r;
                    }
                }

                //// 取消压缩
                //var key = "Accept-Encoding";
                //if (entity.Headers.ContainsKey(key)) entity.Headers.Remove(key);

                // 重新构造请求
                var ms = new MemoryStream();

                entity.Write(ms);
                stream.CopyTo(ms);
                ms.Position = 0;

                //e.Stream = ms;
                e.Packet = ms.ToArray();

                base.OnReceive(e);
            }
Ejemplo n.º 23
0
        private void RequestOneTimeToken(OnRequest request, string cardNumber, string expMonth, string expYear, string cvv)
        {
            WWWForm form = new WWWForm();

            form.AddField("public_key", this.publicKey);
            form.AddField("card[number]", cardNumber);
            form.AddField("card[exp_month]", expMonth);
            form.AddField("card[exp_year]", "20" + expYear);
            form.AddField("card[cvv]", cvv);
            WWW www = new WWW(PWBase.TOKEN_URL, form);

            StartCoroutine(request(www));
        }
 private void onMessage(object sender, MessageEventArgs e)
 {
     Log.Trace("onMessage: " + e.Data);
     if (e.IsText)
     {
         var command   = CommandBase.FromJson(e.Data);
         var receivers = OnRequest.GetInvocationList();
         foreach (EventHandler <CommandBase> receiver in receivers)
         {
             OnRequest?.BeginInvoke(this, command, null, null);
         }
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// 监听到请求时
        /// </summary>
        private void ListenedRequest(IAsyncResult result)
        {
            var context = listener.EndGetContext(result);

            if (OnRequest != null)
            {
                try
                {
                    OnRequest.Invoke(context);
                }
                catch { }
            }
            listener.BeginGetContext(ListenedRequest, null);
        }
Ejemplo n.º 26
0
        public static void Configure()
        {
            OnRequest.ForJs("~/Combined-{0}.js")
            .Compact
            .FilesIn("~/Scripts/")
            .Matching("*.js")
            .Configure();

            OnRequest.ForCss("~/Combined.css")
            .Compact
            .FilesIn("~/Styles/")
            .Matching("*.css")
            .Configure();
        }
Ejemplo n.º 27
0
        private void SendCallback(IAsyncResult ar)
        {
            var state = (AgentState)ar.AsyncState;

            try
            {
                state.WorkSocket.EndSend(ar);
                SendDone.Set();
                OnRequest?.Invoke(this, state);
            }
            catch (Exception e)
            {
                Abort(state, e);
            }
        }
Ejemplo n.º 28
0
        public void FluentConfiguration_File_IncludesWildCardFiles()
        {
            var configurator = OnRequest.ForJs("~/Scripts/Combined-Test.js")
                               .Combine
                               .FilesIn("~/Scripts/")
                               .Matching("*.js");

            configurator.Configure();
            var model = GetModelFor(configurator);

            Assert.AreEqual(1, RejuicerEngine._configurations.Count);
            Assert.AreEqual(3, model.Count);
            Assert.AreEqual("~/Scripts/one.js", ((PhysicalFileSource)model[0]).VirtualPath);
            Assert.AreEqual("~/Scripts/three.js", ((PhysicalFileSource)model[1]).VirtualPath);
            Assert.AreEqual("~/Scripts/two.js", ((PhysicalFileSource)model[2]).VirtualPath);
        }
Ejemplo n.º 29
0
        private void RequestCharge(OnRequest request, string token)
        {
            WWWForm form    = new WWWForm();
            var     headers = form.headers;

            headers ["X-ApiKey"] = this.privateKey;
            form.AddField("token", token, Encoding.UTF8);
            form.AddField("amount", this.amount.ToString());
            form.AddField("currency", this.currency);
            form.AddField("email", txtEmail.text);
            form.AddField("fingerprint", "your fingerprint here");
            form.AddField("description", "your description here");

            WWW www = new WWW(PWBase.GetChargeURL(), form.data, headers);

            StartCoroutine(request(www));
        }
Ejemplo n.º 30
0
        private async Task ProcessTranslation(HttpListenerRequest req, HttpListenerResponse resp)
        {
            string?japanese = GetTextParam(req);

            OnRequest?.Invoke(req.RemoteEndPoint, japanese);
            if (japanese == null)
            {
                return;
            }

            string?korean = await Translator.Translate(japanese ?? "").ConfigureAwait(false);

            resp.ContentType = "text/plain; charset=utf-8";
            byte[] buf = Encoding.UTF8.GetBytes(korean);
            resp.ContentLength64 = buf.LongLength;
            await resp.OutputStream.WriteAsync(buf, 0, buf.Length);
        }