Example #1
0
        public MvcErrorLog(string application, ExceptionContext exceptionContext) : base(application, exceptionContext.Exception)
        {
            var context = exceptionContext.HttpContext;

            if (context == null)
            {
                return;
            }

            Host = Host ?? TryGetMachineName(context);

            var user = context.User;

            if (!(user == null || string.IsNullOrWhiteSpace(user.Identity.Name)))
            {
                User = user.Identity.Name;
            }

            var request = context.Request;

            ServerVariables.Add(request.ServerVariables);
            QueryString.Add(request.QueryString);
            Form.Add(request.Form);
            Cookies.Add(request.Cookies);
        }
Example #2
0
        public void should_return_expected_rule_given_name()
        {
            // given
            var serverVariables = new ServerVariables()
            {
                ServerVariablesList = new[]
                {
                    new ServerVariable {
                        Name = "not-me"
                    },
                    new ServerVariable {
                        Name = "not-me"
                    },
                    new ServerVariable {
                        Name = "not-me"
                    },
                    new ServerVariable {
                        Name = "me"
                    },
                }
            };

            // when
            ServerVariable rule = serverVariables["me"];

            // then
            Assert.That(rule, Is.EqualTo(serverVariables.ServerVariablesList[3]));
        }
Example #3
0
        public void CheckServerVariableFeatureHasPrecedenceWhenEnabled(string variable, string expected, int uriMatchPart)
        {
            // Arrange and Act
            var testParserContext = new ParserContext("test");
            var serverVar         = ServerVariables.FindServerVariable(variable, testParserContext, (UriMatchPart)uriMatchPart, false);
            var httpContext       = CreateTestHttpContext();

            httpContext.Features.Set <IServerVariablesFeature>(new TestServerVariablesFeature(new Dictionary <string, string>
            {
                ["CONTENT_LENGTH"]   = "20",
                ["CONTENT_TYPE"]     = "text/xml",
                ["HTTP_ACCEPT"]      = "other-accept",
                ["HTTP_COOKIE"]      = "other-cookie",
                ["HTTP_HOST"]        = "otherexample.com",
                ["HTTP_REFERER"]     = "other-referer",
                ["HTTP_USER_AGENT"]  = "other-useragent",
                ["HTTP_CONNECTION"]  = "other-connection",
                ["HTTP_URL"]         = "http://otherexample.com/other-foo?bar=2",
                ["QUERY_STRING"]     = "bar=2",
                ["REQUEST_FILENAME"] = "/other-foo",
                ["REQUEST_URI"]      = "/other-foo",
                ["REQUEST_METHOD"]   = "POST"
            }));

            var rewriteContext = CreateTestRewriteContext(httpContext);
            var lookup         = serverVar.Evaluate(rewriteContext, CreateTestRuleMatch().BackReferences, CreateTestCondMatch().BackReferences);

            // Assert
            Assert.Equal(expected, lookup);
        }
Example #4
0
 public override void OnInspectorGUI()
 {
     base.OnInspectorGUI();
     if (GUILayout.Button("Get Values"))
     {
         ((StreamingTest)target).settings = ServerVariables.GetPlayerMovementValues();
     }
 }
Example #5
0
        public static string GetServerVariables(ServerVariables value)
        {
            string str = Request.ServerVariables[value.ToString()];

            if (str == "::1")
            {
                return("127.0.0.1");
            }
            return(str);
        }
Example #6
0
 private void StopServer()
 {
     if (variablesInstance != null)
     {
         NetworkServer.Destroy(variablesInstance.gameObject);
         variablesInstance = null;
     }
     nwManager.StopServer();
     isRunning = false;
 }
Example #7
0
        public void CheckServerVariableParsingAndApplication(string variable, string expected, int uriMatchPart)
        {
            // Arrange and Act
            var testParserContext = new ParserContext("test");
            var serverVar         = ServerVariables.FindServerVariable(variable, testParserContext, (UriMatchPart)uriMatchPart, true);
            var lookup            = serverVar.Evaluate(CreateTestRewriteContext(), CreateTestRuleMatch().BackReferences, CreateTestCondMatch().BackReferences);

            // Assert
            Assert.Equal(expected, lookup);
        }
Example #8
0
 private void StartServer()
 {
     if (variablesPrefab != null)
     {
         nwManager.PrepareLevelStart();
         nwManager.StartServer();
         variablesInstance = Instantiate(variablesPrefab.gameObject).GetComponent <ServerVariables>();
         NetworkServer.Spawn(variablesInstance.gameObject);
         isRunning = true;
     }
 }
Example #9
0
        private void EmptyQueryStringCheck()
        {
            var context        = new DefaultHttpContext();
            var rewriteContext = new RewriteContext {
                HttpContext = context
            };
            var testParserContext = new ParserContext("test");
            var serverVar         = ServerVariables.FindServerVariable("QUERY_STRING", testParserContext, UriMatchPart.Path, true);
            var lookup            = serverVar.Evaluate(rewriteContext, CreateTestRuleMatch().BackReferences, CreateTestCondMatch().BackReferences);

            Assert.Equal(string.Empty, lookup);
        }
Example #10
0
    /// <summary>
    /// Obtains the condition parameter, which could either be a condition variable or a
    /// server variable. Assumes the current character is immediately after the '%'.
    /// context, on return will be on the last character of variable captured, such that after
    /// Next() is called, it will be on the character immediately after the condition parameter.
    /// </summary>
    /// <param name="context">The ParserContext</param>
    /// <param name="results">The List of results which the new condition parameter will be added.</param>
    /// <returns>true </returns>
    private static void ParseConditionParameter(ParserContext context, IList <PatternSegment> results)
    {
        // Parse { }
        if (context.Current == OpenBrace)
        {
            // Start of a server variable
            if (!context.Next())
            {
                // Dangling {
                throw new FormatException(Resources.FormatError_InputParserMissingCloseBrace(context.Index));
            }
            context.Mark();
            while (context.Current != CloseBrace)
            {
                if (!context.Next())
                {
                    throw new FormatException(Resources.FormatError_InputParserMissingCloseBrace(context.Index));
                }
                else if (context.Current == Colon)
                {
                    // Have a segmented look up Ex: HTTP:xxxx
                    // Most of these we can't handle
                    throw new NotImplementedException("Segmented Lookups no implemented");
                }
            }

            // Need to verify server variable captured exists
            var rawServerVariable = context.Capture() !;
            results.Add(ServerVariables.FindServerVariable(rawServerVariable, context));
        }
        else if (context.Current >= '0' && context.Current <= '9')
        {
            // means we have a segmented lookup
            // store information in the testString result to know what to look up.
            context.Mark();
            context.Next();
            var rawConditionParameter = context.Capture() !;

            // Once we leave this method, the while loop will call next again. Because
            // capture is exclusive, we need to go one past the end index, capture, and then go back.
            context.Back();
            var parsedIndex = int.Parse(rawConditionParameter, CultureInfo.InvariantCulture);
            results.Add(new ConditionMatchSegment(parsedIndex));
        }
        else
        {
            // illegal escape of a character
            throw new FormatException(Resources.FormatError_InputParserInvalidInteger(context.Template, context.Index));
        }
    }
Example #11
0
        private void FilterServerVariables()
        {
            // Filter server variables
            if (_serverVarLogFilters?.Count > 0 && ServerVariables?.Count > 0)
            {
                foreach (var k in _serverVarLogFilters.Keys)
                {
                    if (ServerVariables[k] != null)
                    {
                        var replaceWith = _serverVarLogFilters[k];
                        if (replaceWith == "")
                        {
                            ServerVariables.Remove(k);                    // Discard form value
                        }
                        else
                        {
                            ServerVariables[k] = replaceWith;
                        }
                    }
                }
            }

            if (_serverVarRegexLogFilters?.Count > 0 && ServerVariables?.Count > 0)
            {
                foreach (var key in _serverVarRegexLogFilters.Keys)
                {
                    var matchKeys =
                        ServerVariables?.AllKeys?.Where(
                            k => Regex.IsMatch(k, key, RegexOptions.IgnoreCase | RegexOptions.Singleline));
                    foreach (var k in matchKeys)
                    {
                        if (ServerVariables[k] != null)
                        {
                            var replaceWith = _serverVarRegexLogFilters[key];
                            if (replaceWith == "")
                            {
                                ServerVariables.Remove(k);                    // Discard form value
                            }
                            else
                            {
                                ServerVariables[k] = replaceWith;
                            }
                        }
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="area"></param>
        /// <param name="province"></param>
        /// <param name="city"></param>
        public static void GetAreaInfo(out string area, out string province, out string city)
        {
            area     = "";
            province = "";
            city     = "";

            try
            {
                string clientIP = ServerVariables.GetIPAddress();
                if (!string.IsNullOrEmpty(clientIP))
                {
                    area = GetIpAddr(clientIP);

                    Match m = Regex.Match(area, @"(?<pro>.*?)省(?<city>.*?)市");
                    if (m.Success)
                    {
                        province = m.Groups["pro"].Value;
                        city     = m.Groups["city"].Value;
                    }
                    else
                    {
                        m = Regex.Match(area, @"(?<pro>.*?)市(?<city>.*?)区");
                        if (m.Success)
                        {
                            province = m.Groups["pro"].Value;
                            city     = m.Groups["city"].Value;
                        }
                        else
                        {
                            m = Regex.Match(area, @"(?<pro>.*?)市");

                            if (m.Success)
                            {
                                province = m.Groups["pro"].Value;
                                city     = m.Groups["pro"].Value;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
            }
        }
Example #13
0
        public void should_return_expected_rule_given_index()
        {
            // given
            var serverVariables = new ServerVariables()
            {
                ServerVariablesList = new[]
                {
                    new ServerVariable(),
                    new ServerVariable(),
                    new ServerVariable(),
                    new ServerVariable()
                }
            };

            // when
            ServerVariable rule = serverVariables[3];

            // then
            Assert.That(rule, Is.EqualTo(serverVariables.ServerVariablesList[3]));
        }
Example #14
0
    protected override void OnUpdate()
    {
        EntityManager entityManager = EntityManager;

        Entities.WithStructuralChanges().WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            entityManager.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(System.String.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();


            var ghostId = PlayersGhostSerializerCollection.FindGhostType <PilotSnapshotData>();
            var prefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
            var player  = entityManager.Instantiate(prefab);
            entityManager.SetComponentData(player, new PilotData {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });
            entityManager.AddBuffer <PilotInput>(player);

            entityManager.SetComponentData(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });

            entityManager.DestroyEntity(reqEnt);
            Debug.Log("Spawend Player");

            var command = entityManager.CreateEntity();
            entityManager.AddComponent <SetServerVars>(command);
            ServerVariables.pilotSettings = ServerVariables.GetPlayerMovementValues();
            entityManager.SetComponentData(command, new SetServerVars {
                pilotSettings = ServerVariables.pilotSettings.ToFloatArray()
            });
            entityManager.AddComponent <SendRpcCommandRequestComponent>(command);
            entityManager.SetComponentData(command, new SendRpcCommandRequestComponent {
                TargetConnection = reqSrc.SourceConnection
            });
        }).Run();
    }
                                                                 [Authorize] public async Task <IHttpActionResult> Create([FromBody] BitacoraITFConsulta model)
                                                                 {
                                                                     if (model == null ||
                                                                         String.IsNullOrEmpty(model.InformeTecnicoFinalId) || String.IsNullOrEmpty(model.ClavePersona))
                                                                     {
                                                                         return(BadRequest(ModelState));
                                                                     }
                                                                     model.FechaMovimiento = DateTime.Now;
                                                                     model.Ip = "indefinida";
                                                                     ServerVariables sv    = new ServerVariables();
                                                                     var             datos = await sv.GetIPasync();

                                                                     try { log.Info(new MDCSet(this.ControllerContext.RouteData));
                                                                           model.Ip = String.IsNullOrEmpty(datos.RemoteAddr) ? datos.ClientIP : datos.RemoteAddr; }
                                                                     catch (Exception e) { log.Error(new MDCSet(this.ControllerContext.RouteData), e); }

                                                                     try { log.Info(new MDCSet(this.ControllerContext.RouteData));
                                                                           await _entityRepo.Create(model);

                                                                           return(Ok("Registro creado exitosamente!")); }
                                                                     catch (Exception e) { log.Error(new MDCSet(this.ControllerContext.RouteData), e);
                                                                                           return(InternalServerError(e)); }
                                                                 }
Example #16
0
 public static string ValidateUrl(ServerVariables variable, UrlFlags flags, RegExpOptions options)
 {
     throw new NotImplementedException();
 }
Example #17
0
 public static bool ValidateBoolean(ServerVariables variable, bool defaultValue)
 {
     throw new NotImplementedException();
 }
Example #18
0
        public IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            var taskCompletionSource = new TaskCompletionSource<Action>(state);
            if (callback != null)
                taskCompletionSource.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously);

            var call = new CallParameters();

            var httpRequest = httpContext.Request;
            var serverVariables = new ServerVariables(httpRequest.ServerVariables);

            var pathBase = httpRequest.ApplicationPath;
            if (pathBase == "/" || pathBase == null)
                pathBase = "";

            var path = httpRequest.Path;
            if (path.StartsWith(pathBase))
                path = path.Substring(pathBase.Length);

            call.Headers = httpRequest.Headers.AllKeys
                .ToDictionary(x => x, x => httpRequest.Headers.GetValues(x), StringComparer.OrdinalIgnoreCase);

            call.Body = httpRequest.InputStream;

            call.Environment = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)
            {
                {OwinConstants.Version, "1.0"},
                {OwinConstants.RequestMethod, httpRequest.HttpMethod},
                {OwinConstants.RequestScheme, httpRequest.Url.Scheme},
                {OwinConstants.RequestPathBase, pathBase},
                {OwinConstants.RequestPath, path},
                {OwinConstants.RequestQueryString, serverVariables.QueryString},
                {OwinConstants.RequestProtocol, serverVariables.ProtocolVersion},
                {"aspnet.HttpContextBase", httpContext},
                {OwinConstants.CallCompleted, taskCompletionSource.Task},
            };
            foreach (var kv in serverVariables.AddToEnvironment())
            {
                call.Environment["server." + kv.Key] = kv.Value;
            }

            try
            {
                _app.Invoke(call)
                    .Then(result =>
                    {
                        try
                        {
                            httpContext.Response.BufferOutput = false;

                            httpContext.Response.StatusCode = result.Status;
                            // TODO: Reason phrase
                            foreach (var header in result.Headers)
                            {
                                foreach (var value in header.Value)
                                {
                                    httpContext.Response.AddHeader(header.Key, value);
                                }
                            }

                            if (result.Body != null)
                            {
                                result.Body(httpContext.Response.OutputStream)
                                    .Then(() =>
                                    {
                                        taskCompletionSource.TrySetResult(() => { });
                                    })
                                    .Catch(errorInfo =>
                                    {
                                        taskCompletionSource.TrySetException(errorInfo.Exception);
                                        return errorInfo.Handled();
                                    });
                            }
                        }
                        catch (Exception ex)
                        {
                            taskCompletionSource.TrySetException(ex);
                        }
                    })
                    .Catch(errorInfo =>
                    {
                        taskCompletionSource.TrySetException(errorInfo.Exception);
                        return errorInfo.Handled();
                    });
            }
            catch (Exception ex)
            {
                taskCompletionSource.TrySetException(ex);
            }

            return taskCompletionSource.Task;
        }
Example #19
0
        public void CancelChanges()
        {
            if (Element == null)
            {
                return;
            }

            Name           = (string)Element["name"];
            Enabled        = (bool)Element["enabled"];
            PatternSyntax  = (long)Element["patternSyntax"];
            StopProcessing = (bool)Element["stopProcessing"];
            ConfigurationElement matchElement = Element.ChildElements["match"];

            PatternUrl = (string)matchElement["url"];
            Negate     = (bool)matchElement["negate"];
            ConfigurationElement actionElement = Element.ChildElements["action"];

            Type              = (long)actionElement["type"];
            ActionUrl         = (string)actionElement["url"];
            AppendQueryString = (bool)actionElement["appendQueryString"];
            LogRewrittenUrl   = (bool)actionElement["logRewrittenUrl"];
            var redirect = (long)actionElement["redirectType"];

            switch (redirect)
            {
            case 301:
                RedirectType = 0;
                break;

            case 302:
                RedirectType = 1;
                break;

            case 303:
                RedirectType = 2;
                break;

            case 307:
                RedirectType = 3;
                break;
            }

            StatusCode        = (uint)actionElement["statusCode"];
            SubStatusCode     = (uint)actionElement["subStatusCode"];
            StatusReason      = (string)actionElement["statusReason"];
            StatusDescription = (string)actionElement["statusDescription"];

            var conditions = Element.ChildElements["conditions"];

            TrackAllCaptures = (bool)conditions["trackAllCaptures"];
            LogicalGrouping  = (long)conditions["logicalGrouping"];

            foreach (ConfigurationElement condition in conditions.GetCollection())
            {
                var item = new ConditionItem(condition);
                Conditions.Add(item);
            }

            var variables = Element.ChildElements["serverVariables"];

            foreach (ConfigurationElement variable in variables.GetCollection())
            {
                var item = new ServerVariableItem(variable);
                ServerVariables.Add(item);
            }
        }
Example #20
0
        public void Init(HttpApplication init)
        {
            init.AddOnBeginRequestAsync(
                (sender, args, callback, state) =>
            {
                var taskCompletionSource = new TaskCompletionSource <Action>(state);
                if (callback != null)
                {
                    taskCompletionSource.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously);
                }

                var httpContext     = ((HttpApplication)sender).Context;
                var httpRequest     = httpContext.Request;
                var serverVariables = new ServerVariables(httpRequest.ServerVariables);

                var appRelCurExeFilPat = httpRequest.AppRelativeCurrentExecutionFilePath.Substring(1);

                var env = new Dictionary <string, object>();
                new Environment(env)
                {
                    Version    = "1.0",
                    Method     = httpRequest.HttpMethod,
                    UriScheme  = httpRequest.Url.Scheme,
                    ServerName = serverVariables.ServerName,
                    ServerPort = serverVariables.ServerPort,
                    BaseUri    = "",
                    RequestUri = appRelCurExeFilPat + "?" + serverVariables.QueryString,
                    Headers    = httpRequest.Headers.AllKeys.ToDictionary(x => x, x => httpRequest.Headers.Get(x)),
                    Body       = (next, error, complete) =>
                    {
                        var stream       = httpContext.Request.InputStream;
                        var buffer       = new byte[4096];
                        var continuation = new AsyncCallback[1];
                        bool[] stopped   = { false };
                        continuation[0]  = result =>
                        {
                            if (result != null && result.CompletedSynchronously)
                            {
                                return;
                            }
                            try
                            {
                                for (;;)
                                {
                                    if (result != null)
                                    {
                                        var count = stream.EndRead(result);
                                        if (stopped[0])
                                        {
                                            return;
                                        }
                                        if (count <= 0)
                                        {
                                            complete();
                                            return;
                                        }
                                        var data = new ArraySegment <byte>(buffer, 0, count);
                                        if (next(data, () => continuation[0](null)))
                                        {
                                            return;
                                        }
                                    }

                                    if (stopped[0])
                                    {
                                        return;
                                    }
                                    result = stream.BeginRead(buffer, 0, buffer.Length, continuation[0], null);
                                    if (!result.CompletedSynchronously)
                                    {
                                        return;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                error(ex);
                            }
                        };
                        continuation[0](null);
                        return(() => { stopped[0] = true; });
                    },
                };
                Host.Call(
                    env,
                    taskCompletionSource.SetException,
                    (status, headers, body) =>
                {
                    try
                    {
                        httpContext.Response.Status = status;
                        foreach (var header in headers.SelectMany(kv => kv.Value.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(v => new { kv.Key, Value = v })))
                        {
                            httpContext.Response.AddHeader(header.Key, header.Value);
                        }
                        if (body == null)
                        {
                            taskCompletionSource.SetResult(() => httpContext.Response.End());
                            return;
                        }
                        var stream = httpContext.Response.OutputStream;
                        body(
                            (data, continuation) =>
                        {
                            try
                            {
                                if (continuation == null)
                                {
                                    stream.Write(data.Array, data.Offset, data.Count);
                                    return(false);
                                }
                                var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar =>
                                {
                                    if (ar.CompletedSynchronously)
                                    {
                                        return;
                                    }
                                    try
                                    {
                                        stream.EndWrite(ar);
                                    }
                                    catch (Exception ex)
                                    {
                                        taskCompletionSource.SetException(ex);
                                    }
                                    continuation();
                                }, null);
                                if (sr.CompletedSynchronously)
                                {
                                    stream.EndWrite(sr);
                                    return(false);
                                }

                                return(true);
                            }
                            catch (Exception ex)
                            {
                                taskCompletionSource.SetException(ex);
                                return(false);
                            }
                        },
                            taskCompletionSource.SetException,
                            () => taskCompletionSource.SetResult(() => httpContext.Response.End()));
                    }
                    catch (Exception ex)
                    {
                        taskCompletionSource.SetException(ex);
                    }
                });
                return(taskCompletionSource.Task);
            },
                ar => ((Task <Action>)ar).Result());
        }
Example #21
0
 public static string ValidateEmail(ServerVariables variable, EmailOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #22
0
 public static string ValidateInt(ServerVariables variable, IntFlags flags)
 {
     throw new NotImplementedException();
 }
Example #23
0
 public static string ValidateUrl(ServerVariables variable, UrlFlags flags, RegExpOptions options)
 {
     throw new NotImplementedException();
 }
Example #24
0
        public void Init(HttpApplication init)
        {
            init.AddOnBeginRequestAsync(
                (sender, args, callback, state) =>
                {
                    var taskCompletionSource = new TaskCompletionSource<Action>(state);
                    if (callback != null)
                        taskCompletionSource.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously);

                    var httpContext = ((HttpApplication) sender).Context;
                    var httpRequest = httpContext.Request;
                    var serverVariables = new ServerVariables(httpRequest.ServerVariables);

                    var appRelCurExeFilPat = httpRequest.AppRelativeCurrentExecutionFilePath.Substring(1);

                    var env = new Dictionary<string, object>();
                    new Environment(env)
                    {
                        Version = "1.0",
                        Method = httpRequest.HttpMethod,
                        UriScheme = httpRequest.Url.Scheme,
                        ServerName = serverVariables.ServerName,
                        ServerPort = serverVariables.ServerPort,
                        BaseUri = "",
                        RequestUri = appRelCurExeFilPat + "?" + serverVariables.QueryString,
                        Headers = httpRequest.Headers.AllKeys.ToDictionary(x => x, x => httpRequest.Headers.Get(x)),
                        Body = (next, error, complete) =>
                        {
                            var stream = httpContext.Request.InputStream;
                            var buffer = new byte[4096];
                            var continuation = new AsyncCallback[1];
                            bool[] stopped = {false};
                            continuation[0] = result =>
                            {
                                if (result != null && result.CompletedSynchronously) return;
                                try
                                {
                                    for (;;)
                                    {
                                        if (result != null)
                                        {
                                            var count = stream.EndRead(result);
                                            if (stopped[0]) return;
                                            if (count <= 0)
                                            {
                                                complete();
                                                return;
                                            }
                                            var data = new ArraySegment<byte>(buffer, 0, count);
                                            if (next(data, () => continuation[0](null))) return;
                                        }

                                        if (stopped[0]) return;
                                        result = stream.BeginRead(buffer, 0, buffer.Length, continuation[0], null);
                                        if (!result.CompletedSynchronously) return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    error(ex);
                                }
                            };
                            continuation[0](null);
                            return () => { stopped[0] = true; };
                        },
                    };
                    Host.Call(
                        env,
                        taskCompletionSource.SetException,
                        (status, headers, body) =>
                        {
                            try
                            {
                                httpContext.Response.Status = status;
                                foreach (var header in headers.SelectMany(kv => kv.Value.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(v => new {kv.Key, Value = v})))
                                {
                                    httpContext.Response.AddHeader(header.Key, header.Value);
                                }
                                if (body == null)
                                {
                                    taskCompletionSource.SetResult(() => httpContext.Response.End());
                                    return;
                                }
                                var stream = httpContext.Response.OutputStream;
                                body(
                                    (data, continuation) =>
                                    {
                                        try
                                        {
                                            if (continuation == null)
                                            {
                                                stream.Write(data.Array, data.Offset, data.Count);
                                                return false;
                                            }
                                            var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar =>
                                            {
                                                if (ar.CompletedSynchronously) return;
                                                try
                                                {
                                                    stream.EndWrite(ar);
                                                }
                                                catch (Exception ex)
                                                {
                                                    taskCompletionSource.SetException(ex);
                                                }
                                                continuation();
                                            }, null);
                                            if (sr.CompletedSynchronously)
                                            {
                                                stream.EndWrite(sr);
                                                return false;
                                            }

                                            return true;
                                        }
                                        catch (Exception ex)
                                        {
                                            taskCompletionSource.SetException(ex);
                                            return false;
                                        }
                                    },
                                    taskCompletionSource.SetException,
                                    () => taskCompletionSource.SetResult(() => httpContext.Response.End()));
                            }
                            catch (Exception ex)
                            {
                                taskCompletionSource.SetException(ex);
                            }
                        });
                    return taskCompletionSource.Task;
                },
                ar => ((Task<Action>) ar).Result());
        }
Example #25
0
        public IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var taskCompletionSource = new TaskCompletionSource<Action>(state);
            if (callback != null)
                taskCompletionSource.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously);

            var httpRequest = httpContext.Request;
            var serverVariables = new ServerVariables(httpRequest.ServerVariables);

            var pathBase = httpRequest.ApplicationPath;
            if (pathBase == "/" || pathBase == null)
                pathBase = "";

            var path = httpRequest.Path;
            if (path.StartsWith(pathBase))
                path = path.Substring(pathBase.Length);

            var requestHeaders = httpRequest.Headers.AllKeys
                .ToDictionary(x => x, x => (IEnumerable<string>)httpRequest.Headers.GetValues(x), StringComparer.OrdinalIgnoreCase);

            var env = new Dictionary<string, object>
            {
                {OwinConstants.Version, "1.0"},
                {OwinConstants.RequestMethod, httpRequest.HttpMethod},
                {OwinConstants.RequestScheme, httpRequest.Url.Scheme},
                {OwinConstants.RequestPathBase, pathBase},
                {OwinConstants.RequestPath, path},
                {OwinConstants.RequestQueryString, serverVariables.QueryString},
                {OwinConstants.RequestHeaders, requestHeaders},
                {OwinConstants.RequestBody, RequestBody(httpRequest.InputStream)},
                {"host.CallDisposed", cancellationTokenSource.Token},
                {"aspnet.HttpContextBase", httpContext},
            };
            foreach (var kv in serverVariables.AddToEnvironment())
            {
                env["server." + kv.Key] = kv.Value;
            }

            try
            {
                _app.Invoke(
                    env,
                    (status, headers, body) =>
                    {
                        try
                        {
                            httpContext.Response.BufferOutput = false;

                            httpContext.Response.Status = status;
                            foreach (var header in headers)
                            {
                                foreach (var value in header.Value)
                                {
                                    httpContext.Response.AddHeader(header.Key, value);
                                }
                            }

                            ResponseBody(
                                body,
                                httpContext.Response.OutputStream,
                                ex => taskCompletionSource.TrySetException(ex),
                                () => taskCompletionSource.TrySetResult(() => httpContext.Response.End()));
                        }
                        catch (Exception ex)
                        {
                            taskCompletionSource.TrySetException(ex);
                        }
                    },
                    ex => taskCompletionSource.TrySetException(ex));
            }
            catch(Exception ex)
            {
                taskCompletionSource.TrySetException(ex);
            }

            if (taskCompletionSource.Task.IsCompleted)
            {
                cancellationTokenSource.Cancel(false);
            }
            else
            {
                taskCompletionSource.Task.ContinueWith(t => cancellationTokenSource.Cancel(false));
            }

            return taskCompletionSource.Task;
        }
Example #26
0
 public static string ValidateFloat(ServerVariables variable, bool ALLOW_THOUSAND, FloatOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #27
0
 public static string ValidateEmail(ServerVariables variable, EmailOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #28
0
 public static bool ValidateBoolean(ServerVariables variable, bool defaultValue)
 {
     throw new NotImplementedException();
 }
Example #29
0
 public static string ValidateRegexp(ServerVariables variable, RegExpOptions options)
 {
     throw new NotImplementedException();
 }
Example #30
0
 public static bool?ValidateBoolean(ServerVariables variable)
 {
     throw new NotImplementedException();
 }
Example #31
0
 public static string ValidateIp(ServerVariables variable, IpFlags flags = 0, IpOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #32
0
        public IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            var taskCompletionSource = new TaskCompletionSource<Action>(state);
            if (callback != null)
                taskCompletionSource.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously);

            var httpRequest = httpContext.Request;
            var serverVariables = new ServerVariables(httpRequest.ServerVariables);

            var pathBase = httpRequest.ApplicationPath;
            if (pathBase == "/" || pathBase == null)
                pathBase = "";

            var path = httpRequest.Path;
            if (path.StartsWith(pathBase))
                path = path.Substring(pathBase.Length);

            var requestHeaders = httpRequest.Headers.AllKeys
                .ToDictionary(x => x, x => httpRequest.Headers.Get(x), StringComparer.OrdinalIgnoreCase);

            var env = new Environment()
            {
                Version = "1.0",
                Method = httpRequest.HttpMethod,
                Scheme = httpRequest.Url.Scheme,
                PathBase = pathBase,
                Path = path,
                QueryString = serverVariables.QueryString,
                Headers = requestHeaders,
                Body = Body.FromStream(httpRequest.InputStream),
            };
            env["aspnet.HttpContextBase"] = httpContext;
            foreach (var kv in serverVariables.AddToEnvironment())
            {
                env["server." + kv.Key] = kv.Value;
            }

            _app.Invoke(
                env,
                (status, headers, body) =>
                {
                    try
                    {
                        httpContext.Response.BufferOutput = false;

                        httpContext.Response.Status = status;
                        foreach (var header in headers.SelectMany(kv => kv.Value.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(v => new {kv.Key, Value = v})))
                        {
                            httpContext.Response.AddHeader(header.Key, header.Value);
                        }

                        body.WriteToStream(
                            httpContext.Response.OutputStream,
                            taskCompletionSource.SetException,
                            () => taskCompletionSource.SetResult(() => httpContext.Response.End()));
                    }
                    catch (Exception ex)
                    {
                        taskCompletionSource.SetException(ex);
                    }
                },
                taskCompletionSource.SetException);
            return taskCompletionSource.Task;
        }
Example #33
0
 public GlobalVariableLibrary()
 {
     serverVariables = new ServerVariables();
 }
 public FakeHttpRequest WithQueryString(string value)
 {
     ServerVariables.Add(QueryStringVariable, value);
     return(this);
 }
Example #35
0
 public static bool? ValidateBoolean(ServerVariables variable)
 {
     throw new NotImplementedException();
 }
Example #36
0
 public static string ValidateRegexp(ServerVariables variable, RegExpOptions options)
 {
     throw new NotImplementedException();
 }
Example #37
0
 public static string ValidateInt(ServerVariables variable, IntFlags flags)
 {
     throw new NotImplementedException();
 }
Example #38
0
 public static string ValidateFloat(ServerVariables variable, bool ALLOW_THOUSAND, FloatOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #39
0
 public static string ValidateIp(ServerVariables variable, IpFlags flags = 0, IpOptions options = null)
 {
     throw new NotImplementedException();
 }
Example #40
0
        /// <summary>
        /// Register the exception handler and api endpoints. This method should be
        /// configure after UseRouting method
        /// </summary>
        /// <param name="app"></param>
        public static void UseFluidem(this IApplicationBuilder app)
        {
            app.ApplicationServices.GetService <IProvider>().BootstrapProvider();

            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var contextFeature          = context.Features.Get <IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        var baseException = contextFeature.Error.GetBaseException();
                        var detailError   = new ErrorDetail
                        {
                            Id            = Guid.NewGuid(),
                            Host          = context.Request.Host.ToString(),
                            ExceptionType = baseException.GetType().FullName,
                            StatusCode    = context.Response.StatusCode,
                            Message       = baseException.Message,
                            StackTrace    = baseException.StackTrace,
                            Source        = baseException.Source,
                            TimeUtc       = DateTimeOffset.UtcNow,
                            User          = context.User.Claims
                                            .SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value ?? string.Empty,
                            DetailJson = await ServerVariables.AsJson(context)
                        };
                        var provider = context.RequestServices.GetService <IProvider>();
                        try
                        {
                            await provider.SaveExceptionAsync(detailError);
                        }
                        catch (Exception e)
                        {
                            var logger = context.RequestServices.GetService <ILogger <IProvider> >();
                            logger.LogError($"Error saving exception: {e.Message}", e);
                        }
                    }
                });
            });

            // Configure api endpoints to return exceptions info
            app.UseEndpoints(endpoints =>
            {
                var options = app.ApplicationServices.GetService <IOptions <FluidemOptions> >();
                endpoints.MapGet(options.Value.ErrorLogApiUrl, async context =>
                {
                    var provider = context.RequestServices.GetService <IProvider>();
                    var list     = await provider.GetExceptionsAsync();
                    await context.Response.WriteAsJsonAsync(list);
                });

                endpoints.MapGet(options.Value.ErrorLogApiUrl + "/{id}", async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    var provider = context.RequestServices.GetService <IProvider>();
                    var id       = context.Request.RouteValues.GetValueOrDefault("id");

                    if (id == null)
                    {
                        return;
                    }
                    if (!Guid.TryParse(id.ToString(), out var guid))
                    {
                        return;
                    }

                    var ex = await provider.GetExceptionAsync(guid);
                    if (ex == null)
                    {
                        return;
                    }

                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    await context.Response.WriteAsJsonAsync(ex);
                });
            });
        }