예제 #1
0
        public void Throw_If_Control_Throws()
        {
            // arrange
            var mock = new Mock <IComposite>();

            mock.Setup(composite =>
                       composite.Execute(It.IsAny <DEBUG_OUTCTL>(), It.IsAny <string>(), It.IsAny <DEBUG_EXECUTE>()))
            .Throws <Exception>();
            var    proxy      = new DebuggerProxy(mock.Object);
            Action mightThrow = () => proxy.Execute("whatever");

            // act
            // assert
            mightThrow.Should().Throw <COMException>();
        }
예제 #2
0
        public void Only_Add_Text_On_Non_Warning_Or_Error_Masks()
        {
            // arrange
            var mock  = new Mock <IComposite>();
            var proxy = new DebuggerProxy(mock.Object);

            // act
            ((IDebugOutputCallbacks)proxy).Output(DEBUG_OUTPUT.ERROR, "a");
            ((IDebugOutputCallbacks)proxy).Output(DEBUG_OUTPUT.WARNING, "b");
            ((IDebugOutputCallbacks)proxy).Output(DEBUG_OUTPUT.EXTENSION_WARNING, "c");
            ((IDebugOutputCallbacks)proxy).Output(DEBUG_OUTPUT.SYMBOLS, "d");
            ((IDebugOutputCallbacks)proxy).Output(DEBUG_OUTPUT.NORMAL, "e");

            // assert
            proxy.Builder.ToString().Should().Be("e");
        }
예제 #3
0
        public void Throw_If_The_Wait_Timeout_Expired()
        {
            // arrange
            var mock = new Mock <IComposite>();
            Func <DEBUG_OUTCTL, string, DEBUG_EXECUTE, int> valueFunction = (o, c, e) =>
            {
                Thread.Sleep(1000);
                return(0);
            };

            mock.Setup(
                client => client.Execute(It.IsAny <DEBUG_OUTCTL>(), It.IsAny <string>(), It.IsAny <DEBUG_EXECUTE>()))
            .Returns(valueFunction);
            var  proxy     = new DebuggerProxy(mock.Object);
            bool isSuccess = false;

            // act
            var tasks = Enumerable.Range(0, 3).Select(i => Task.Run(() =>
            {
                proxy.Execute("whatever", TimeSpan.FromMilliseconds(10));
            }));

            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(exception =>
                {
                    if (exception is TimeoutException || exception.InnerException is TimeoutException)
                    {
                        isSuccess = true;
                    }
                    return(true);
                });
            }
            // assert
            isSuccess.Should().BeTrue();
        }
예제 #4
0
        public void Only_Allow_One_Thread_To_Use_It_At_A_Time()
        {
            // arrange
            var mock = new Mock <IComposite>();

            Func <DEBUG_OUTCTL, string, DEBUG_EXECUTE, int> valueFunction = (o, c, e) =>
            {
                Thread.Sleep(1000);
                return(0);
            };

            mock.Setup(
                client => client.Execute(It.IsAny <DEBUG_OUTCTL>(), It.IsAny <string>(), It.IsAny <DEBUG_EXECUTE>()))
            .Returns(valueFunction);
            var proxy = new DebuggerProxy(mock.Object);
            int count = 0;

            var start = DateTime.Now;

            // act
            for (int i = 0; i < 3; i++)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    proxy.Execute("whatever");
                    Interlocked.Increment(ref count);
                });
            }

            while (count != 3)
            {
                Thread.Sleep(500);
            }

            // assert
            (DateTime.Now - start).Should().BeGreaterThan(TimeSpan.FromSeconds(2));
        }
예제 #5
0
        public static IApplicationBuilder UseDebugProxy(
            this IApplicationBuilder app,
            ProxyOptions options,
            Func <Dictionary <string, string>, HttpContext, Uri, Dictionary <string, string> > mapFunc)
        {
            Uri devToolsHost = options.DevToolsUrl;

            app.UseRouter(router =>
            {
                router.MapGet("/", Copy);
                router.MapGet("/favicon.ico", Copy);
                router.MapGet("json", RewriteArray);
                router.MapGet("json/list", RewriteArray);
                router.MapGet("json/version", RewriteSingle);
                router.MapGet("json/new", RewriteSingle);
                router.MapGet("devtools/page/{pageId}", ConnectProxy);
                router.MapGet("devtools/browser/{pageId}", ConnectProxy);

                string GetEndpoint(HttpContext context)
                {
                    HttpRequest request    = context.Request;
                    PathString requestPath = request.Path;
                    return($"{devToolsHost.Scheme}://{devToolsHost.Authority}{request.Path}{request.QueryString}");
                }

                async Task Copy(HttpContext context)
                {
                    using (var httpClient = new HttpClient {
                        Timeout = TimeSpan.FromSeconds(5)
                    })
                    {
                        HttpResponseMessage response = await httpClient.GetAsync(GetEndpoint(context));
                        context.Response.ContentType = response.Content.Headers.ContentType.ToString();
                        if ((response.Content.Headers.ContentLength ?? 0) > 0)
                        {
                            context.Response.ContentLength = response.Content.Headers.ContentLength;
                        }
                        byte[] bytes = await response.Content.ReadAsByteArrayAsync();
                        await context.Response.Body.WriteAsync(bytes);
                    }
                }

                async Task RewriteSingle(HttpContext context)
                {
                    Dictionary <string, string> version = await ProxyGetJsonAsync <Dictionary <string, string> >(GetEndpoint(context));
                    context.Response.ContentType        = "application/json";
                    await context.Response.WriteAsync(
                        JsonSerializer.Serialize(mapFunc(version, context, devToolsHost)));
                }

                async Task RewriteArray(HttpContext context)
                {
                    Dictionary <string, string>[] tabs        = await ProxyGetJsonAsync <Dictionary <string, string>[]>(GetEndpoint(context));
                    Dictionary <string, string>[] alteredTabs = tabs.Select(t => mapFunc(t, context, devToolsHost)).ToArray();
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(JsonSerializer.Serialize(alteredTabs));
                }

                async Task ConnectProxy(HttpContext context)
                {
                    if (!context.WebSockets.IsWebSocketRequest)
                    {
                        context.Response.StatusCode = 400;
                        return;
                    }

                    var endpoint  = new Uri($"ws://{devToolsHost.Authority}{context.Request.Path}");
                    int runtimeId = 0;
                    if (context.Request.Query.TryGetValue("RuntimeId", out StringValues runtimeIdValue) &&
                        int.TryParse(runtimeIdValue.FirstOrDefault(), out int parsedId))
                    {
                        runtimeId = parsedId;
                    }
                    try
                    {
                        using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
                                                                                  builder.AddSimpleConsole(options =>
                        {
                            options.SingleLine      = true;
                            options.TimestampFormat = "[HH:mm:ss] ";
                        })
                                                                                  .AddFilter(null, LogLevel.Information)
                                                                                  );

                        context.Request.Query.TryGetValue("urlSymbolServer", out StringValues urlSymbolServerList);
                        var proxy = new DebuggerProxy(loggerFactory, urlSymbolServerList.ToList(), runtimeId);

                        System.Net.WebSockets.WebSocket ideSocket = await context.WebSockets.AcceptWebSocketAsync();

                        await proxy.Run(endpoint, ideSocket);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("got exception {0}", e);
                    }
                }
            });
            return(app);
        }
예제 #6
0
        public static IApplicationBuilder UseDebugProxy(
            this IApplicationBuilder app,
            ProxyOptions options,
            Func <Dictionary <string, string>, HttpContext, Uri, Dictionary <string, string> > mapFunc)
        {
            var devToolsHost = options.DevToolsUrl;

            app.UseRouter(router => {
                router.MapGet("json", RewriteArray);
                router.MapGet("json/list", RewriteArray);
                router.MapGet("json/version", RewriteSingle);
                router.MapGet("json/new", RewriteSingle);
                router.MapGet("devtools/page/{pageId}", ConnectProxy);
                router.MapGet("devtools/browser/{pageId}", ConnectProxy);

                string GetEndpoint(HttpContext context)
                {
                    var request     = context.Request;
                    var requestPath = request.Path;
                    return($"{devToolsHost.Scheme}://{devToolsHost.Authority}{request.Path}{request.QueryString}");
                }

                async Task Copy(HttpContext context)
                {
                    using (var httpClient = new HttpClient {
                        Timeout = TimeSpan.FromSeconds(5)
                    })
                    {
                        var response = await httpClient.GetAsync(GetEndpoint(context));
                        context.Response.ContentType = response.Content.Headers.ContentType.ToString();
                        if ((response.Content.Headers.ContentLength ?? 0) > 0)
                        {
                            context.Response.ContentLength = response.Content.Headers.ContentLength;
                        }

                        var bytes = await response.Content.ReadAsByteArrayAsync();
                        await context.Response.Body.WriteAsync(bytes);
                    }
                }

                async Task RewriteSingle(HttpContext context)
                {
                    var version = await ProxyGetJsonAsync <Dictionary <string, string> >(GetEndpoint(context));
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(
                        JsonSerializer.Serialize(mapFunc(version, context, devToolsHost)));
                }

                async Task RewriteArray(HttpContext context)
                {
                    var tabs        = await ProxyGetJsonAsync <Dictionary <string, string>[]>(GetEndpoint(context));
                    var alteredTabs = tabs.Select(t => mapFunc(t, context, devToolsHost)).ToArray();
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(JsonSerializer.Serialize(alteredTabs));
                }

                async Task ConnectProxy(HttpContext context)
                {
                    if (!context.WebSockets.IsWebSocketRequest)
                    {
                        context.Response.StatusCode = 400;
                        return;
                    }

                    var endpoint = new Uri($"ws://{devToolsHost.Authority}{context.Request.Path.ToString()}");
                    try
                    {
                        using var loggerFactory = LoggerFactory.Create(
                                  builder => builder.AddConsole().AddFilter(null, LogLevel.Trace));
                        var proxy     = new DebuggerProxy(loggerFactory);
                        var ideSocket = await context.WebSockets.AcceptWebSocketAsync();

                        await proxy.Run(endpoint, ideSocket);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("got exception {0}", e);
                    }
                }
            });
            return(app);
        }