Exemple #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Business Central Agent");
            CommandLineArguments arguments = CommandLineParser.Parse(args, AppContext.BaseDirectory);

            // TODO: argument validating and exit on invalid.

            Console.WriteLine("Press 'q' to quit.");
            var cts = new CancellationTokenSource();

            Task.Run(() => RequestDispatcher.Start(
                         arguments.RelayNamespace,
                         arguments.HybridConnectionName,
                         arguments.KeyName,
                         arguments.SharedAccessKey,
                         arguments.PluginFolder,
                         new ConsoleLogger(), // TODO: LogLevel support
                         cts.Token
                         ), cts.Token);

            while (Console.ReadKey().KeyChar != 'q')
            {
            }

            cts.Cancel();
        }
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            RequestDispatcher  rd      = GetServletContext().GetNamedDispatcher("default");
            HttpServletRequest wrapped = new _HttpServletRequestWrapper_46(req);

            rd.Forward(wrapped, resp);
        }
        public Task <VSProjectContextList?> GetProjectContextsAsync(VSGetProjectContextsParams textDocumentWithContextParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <VSGetProjectContextsParams, VSProjectContextList?>(Queue, VSMethods.GetProjectContextsName,
                                                                                                             textDocumentWithContextParams, _clientCapabilities, ClientName, cancellationToken));
        }
        public Task <VSInternalDocumentOnAutoInsertResponseItem?> GetDocumentOnAutoInsertAsync(VSInternalDocumentOnAutoInsertParams autoInsertParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <VSInternalDocumentOnAutoInsertParams, VSInternalDocumentOnAutoInsertResponseItem?>(Queue, VSInternalMethods.OnAutoInsertName,
                                                                                                                                             autoInsertParams, _clientCapabilities, ClientName, cancellationToken));
        }
        public Task <VSCodeAction> ResolveCodeActionAsync(VSCodeAction vsCodeAction, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <VSCodeAction, VSCodeAction>(Queue, MSLSPMethods.TextDocumentCodeActionResolveName,
                                                                                      vsCodeAction, _clientCapabilities, ClientName, cancellationToken));
        }
Exemple #6
0
        public static async Task <InProcLanguageServer> CreateAsync(
            AbstractInProcLanguageClient languageClient,
            Stream inputStream,
            Stream outputStream,
            RequestDispatcher requestDispatcher,
            Workspace workspace,
            IDiagnosticService?diagnosticService,
            IAsynchronousOperationListenerProvider listenerProvider,
            ILspWorkspaceRegistrationService lspWorkspaceRegistrationService,
            VSShell.IAsyncServiceProvider?asyncServiceProvider,
            string?clientName,
            CancellationToken cancellationToken)
        {
            var jsonMessageFormatter = new JsonMessageFormatter();

            VSExtensionUtilities.AddVSExtensionConverters(jsonMessageFormatter.JsonSerializer);

            var jsonRpc        = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter));
            var serverTypeName = languageClient.GetType().Name;
            var logger         = await CreateLoggerAsync(asyncServiceProvider, serverTypeName, clientName, jsonRpc, cancellationToken).ConfigureAwait(false);

            return(new InProcLanguageServer(
                       languageClient,
                       requestDispatcher,
                       workspace,
                       diagnosticService,
                       listenerProvider,
                       lspWorkspaceRegistrationService,
                       serverTypeName,
                       clientName,
                       jsonRpc,
                       logger));
        }
Exemple #7
0
        public async Task TestLauncher()
        {
            var serviceCollection = new ServiceCollection();
            var messageHandler    = new Mock <IMessageHandler>(MockBehavior.Strict);
            var botService        = new Mock <IBotService>(MockBehavior.Strict);

            botService.Setup(m => m.InitAsync()).Returns(Task.CompletedTask);
            botService.Setup(m => m.RunAsync()).Returns(Task.CompletedTask);
            botService.Setup(m => m.ShutdownAsync()).Returns(Task.CompletedTask);
            serviceCollection.AddSingleton(typeof(IMessageHandler), messageHandler.Object);
            serviceCollection.AddSingleton(typeof(IBotService), botService.Object);
            var requestDispatcher = new RequestDispatcher("(test)");

            serviceCollection.AddSingleton(typeof(IRequestDispatcher), requestDispatcher);
            Launcher launcher = new Launcher();

            Program.ServiceProvider = serviceCollection.BuildServiceProvider();
            await launcher.RunAsync().ConfigureAwait(false);

            launcher.IsRunning.Should().BeTrue();
            botService.Verify(m => m.RunAsync(), Times.Once);
            var envMock = new Mock <BotEnvironment>(MockBehavior.Strict);

            envMock.Setup(m => m.Exit(It.IsAny <int>()));
            launcher.SetEnv(envMock.Object);
            await launcher.ShutdownAsync();
        }
        public Task <LinkedEditingRanges?> GetLinkedEditingRangesAsync(LinkedEditingRangeParams renameParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <LinkedEditingRangeParams, LinkedEditingRanges?>(Queue, Methods.TextDocumentLinkedEditingRangeName,
                                                                                                          renameParams, _clientCapabilities, ClientName, cancellationToken));
        }
Exemple #9
0
        public ContentResult Post(string tag, string signature, string timestamp, string nonce, string encrypt_type = "")
        {
            var client = ApiClient.GetInstance(tag);

            if (client == null)
            {
                return(null);
            }

            var useAes = encrypt_type.Equals("aes", StringComparison.OrdinalIgnoreCase);

            if (this.CheckSignature(useAes, client, signature, timestamp, nonce))
            {
                using (StreamReader reader = new StreamReader(Request.InputStream)) {
                    var data = reader.ReadToEnd();
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        var msg = client.Parse(data, useAes);
                        if (msg != null)
                        {
                            var reply = RequestDispatcher.Dispatch(tag, msg);
                            if (reply != null)
                            {
                                var str = client.Encrypt(reply, nonce, useAes);
                                return(Content(str, "text/xml", UTF8Encoding.UTF8));
                            }
                        }
                    }
                }
            }

            return(Content(""));
        }
Exemple #10
0
        public void Setup()
        {
            _testScheduler = new TestScheduler();
            IMemCache cache = new MemCache(capacity: 100);

            _requestDispatcher = new RequestDispatcher(_testScheduler, cache, Service.Service.GetRequestHandlers(_testScheduler, cache));
        }
        internal override void OnPostAuthorizeRequest(object sender, EventArgs e)
        {
            bool flag = false;

            if (this.onPostAuthorizeRequestChain != null)
            {
                flag = this.onPostAuthorizeRequestChain.ExecuteRequestFilterChain(sender, e, RequestEventType.PostAuthorizeRequest);
            }
            if (flag)
            {
                return;
            }
            HttpApplication httpApplication = (HttpApplication)sender;

            if (UrlUtilities.IsWacRequest(httpApplication.Context.Request))
            {
                return;
            }
            try
            {
                RequestDispatcher.DispatchRequest(OwaContext.Get(httpApplication.Context));
            }
            catch (ThreadAbortException)
            {
                OwaContext.Current.UnlockMinResourcesOnCriticalError();
            }
        }
Exemple #12
0
        public static void Config()
        {
            //从数据库获取配置信息
            //var cfgs = DependencyResolver.Current.GetService<IApiConfig>().GetConfigs()
            //    .Select(c => new ApiConfig(c.TAG, c.APPID, c.APPSECRET, c.AESKEY, c.TOKEN));
            IEnumerable <ApiConfig> cfgs = new List <ApiConfig> {
                new ApiConfig("test", "your appID", "your Secret Code", "your aes key,if not set can be null", "your token")
            };

            ApiClient.Init(cfgs);

            //Dispatcher 的依赖注入
            RequestDispatcher.GetService = t => DependencyResolver.Current.GetService(t);

            #region 注册处理程序
            RequestDispatcher.Regist <TextHandler>();
            RequestDispatcher.Regist <VoiceHandler>();
            RequestDispatcher.Regist <LinkHandler>();


            RequestDispatcher.Regist <ClickHandler>();
            RequestDispatcher.Regist <SubscribeHandler>();
            RequestDispatcher.Regist <UnsubscribeHandler>();
            //RequestDispatcher.Regist<TextHandler>(RequestTypes.Text);
            //RequestDispatcher.Regist<VoiceHandler>(RequestTypes.Voice);
            //RequestDispatcher.Regist<LinkHandler>(RequestTypes.Link);


            //RequestDispatcher.Regist<ClickHandler>(RequestTypes.Event, EventTypes.Click);
            //RequestDispatcher.Regist<SubscribeHandler>(RequestTypes.Event, EventTypes.Subscribe);
            //RequestDispatcher.Regist<UnsubscribeHandler>(RequestTypes.Event, EventTypes.Unsubscribe);
            #endregion
        }
        public Task <DocumentOnTypeRenameResponseItem?> GetTypeRenameAsync(DocumentOnTypeRenameParams renameParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <DocumentOnTypeRenameParams, DocumentOnTypeRenameResponseItem?>(Queue, MSLSPMethods.OnTypeRenameName,
                                                                                                                         renameParams, _clientCapabilities, ClientName, cancellationToken));
        }
Exemple #14
0
 public Builder WithAsyncRequestHandler <TRequest, TResponse>(AsyncRequestHandlerDelegate <TRequest, TResponse> handler)
     where TRequest : class
     where TResponse : class
 {
     RequestDispatcher.RegisterAsync(handler);
     return(this);
 }
Exemple #15
0
        public static async Task ConsoleUI()
        {
            string uAgent = "";
            string nName  = "";

            Console.Title = "Dispatch Backup Tool";
            // Introduction.
            Console.WriteLine("\n\nNationStates Dispatch Backup Tool\nVersion 0.0 (Development)\n--------\n\nPress Enter to continue...");
            Console.ReadKey();
            Console.WriteLine("\n\n");

            // Request uAgent and Nation Name
            Console.WriteLine("Enter the User Agent:");
            uAgent = Console.ReadLine();

            Console.WriteLine("Enter the Nation Name:");
            nName = Console.ReadLine();

            // Send Request
            ConfigureLogging();
            requestDispatcher = new RequestDispatcher(uAgent, Log.Logger);
            requestDispatcher.Start();
            await IdsRequest(uAgent, nName);
            await TextRequest();

            await File.WriteAllTextAsync("dispatches.txt", string.Join("", dispatchResult));
        }
Exemple #16
0
 public Builder WithRequestHandler <TRequest, TResponse>(IRequestHandler <TRequest, TResponse> handler)
     where TRequest : class
     where TResponse : class
 {
     RequestDispatcher.Register(handler);
     return(this);
 }
Exemple #17
0
        private RequestDispatcher BuildRequestDispatcher(IModuleContainer container)
        {
            var moduleCatalog = new ModuleCatalog(
                () => { return(container.GetAllModules()); },
                (Type moduleType) => { return(container.GetModule(moduleType)); }
                );

            var routeSegmentExtractor    = new RouteSegmentExtractor();
            var routeDescriptionProvider = new RouteDescriptionProvider();
            var routeCache = new RouteCache(routeSegmentExtractor, routeDescriptionProvider);

            routeCache.BuildCache(moduleCatalog.GetAllModules());

            var trieNodeFactory = new TrieNodeFactory();
            var routeTrie       = new RouteResolverTrie(trieNodeFactory);

            routeTrie.BuildTrie(routeCache);

            var serializers = new List <ISerializer>()
            {
                new JsonSerializer(), new XmlSerializer()
            };
            var responseFormatterFactory = new ResponseFormatterFactory(serializers);
            var moduleBuilder            = new ModuleBuilder(responseFormatterFactory);

            var routeResolver = new RouteResolver(moduleCatalog, moduleBuilder, routeTrie);

            var negotiator        = new ResponseNegotiator();
            var routeInvoker      = new RouteInvoker(negotiator);
            var requestDispatcher = new RequestDispatcher(routeResolver, routeInvoker);

            return(requestDispatcher);
        }
        public static void includeServlet(String servletPath, Object writer, Object aspPage, Object [] servletParams)
        {
            // Need to define logic for resolving the servletPath. Share code with portlet createRenderUrl.
            HttpContext       context    = HttpContext.Current;
            HttpWorkerRequest wr         = (HttpWorkerRequest)((IServiceProvider)context).GetService(typeof(HttpWorkerRequest));
            RequestDispatcher dispatcher = ((ServletContext)((IServiceProvider)wr).GetService(typeof(ServletContext))).getRequestDispatcher(SERVLET_INCLUDE_HELPER_PATH);
            ServletResponse   response   = (ServletResponse)((IServiceProvider)wr).GetService(typeof(ServletResponse));
            ServletRequest    request    = (ServletRequest)((IServiceProvider)wr).GetService(typeof(ServletRequest));

            // Setup params for the include call.
            String oldServletPath = (String)setAttribute(request, SERVLET_PATH_ATTRIBUTE_NAME, servletPath);
            Object oldAspPage     = setAttribute(request, ASPPAGE_ATTRIBUTE_NAME, aspPage);

            Object [] oldServletParams = (Object [])setAttribute(request, SERVLET_PARAMS_ATTRIBUTE_NAME, servletParams);
            Object    oldWriter        = setAttribute(request, TEXT_WRITER_ATTRIBUTE_NAME, writer);

            // Do the include call.
            dispatcher.include(request, response);

            // Restore previous attribute values after the call.
            request.setAttribute(SERVLET_PATH_ATTRIBUTE_NAME, oldServletPath);
            request.setAttribute(ASPPAGE_ATTRIBUTE_NAME, oldAspPage);
            request.setAttribute(SERVLET_PARAMS_ATTRIBUTE_NAME, oldServletParams);
            request.setAttribute(TEXT_WRITER_ATTRIBUTE_NAME, oldWriter);
        }
Exemple #19
0
        public LocalRequestHandlerWithTestScheduler()
        {
            _scheduler = new TestScheduler();
            _cache     = new MemCache(capacity: 100);
            var requestHandlers = Service.Service.GetRequestHandlers(_scheduler, _cache);

            _requestDispatcher = new RequestDispatcher(_scheduler, _cache, requestHandlers);
        }
        public Task <VSInternalWorkspaceDiagnosticReport[]?> GetWorkspacePullDiagnosticsAsync(VSInternalWorkspaceDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport[]?>(
                       Queue, VSInternalMethods.WorkspacePullDiagnosticName,
                       diagnosticsParams, _clientCapabilities, ClientName, cancellationToken));
        }
        public Task <DiagnosticReport[]?> GetDocumentPullDiagnosticsAsync(DocumentDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <DocumentDiagnosticsParams, DiagnosticReport[]?>(
                       Queue, MSLSPMethods.DocumentPullDiagnosticName,
                       diagnosticsParams, _clientCapabilities, ClientName, cancellationToken));
        }
Exemple #22
0
        public SharpShark(String p_SecretKey, String p_BaseURL)
        {
            BaseURL           = p_BaseURL;
            RequestDispatcher = new RequestDispatcher(this, p_SecretKey);

            InitComponents();
            RegisterEventHandlers();
        }
        public async Task TestRegisterAndThrowOnDispatch()
        {
            RequestDispatcher dispatcher = new RequestDispatcher();
            var request = new Request(RequestType.GetBasicNationStats, ResponseFormat.XmlResult, DataSourceType.NationStatesAPI);
            await Assert.ThrowsAsync <ArgumentNullException>(() => dispatcher.Dispatch(null)).ConfigureAwait(false);

            await Assert.ThrowsAsync <InvalidOperationException>(() => dispatcher.Dispatch(request)).ConfigureAwait(false);
        }
Exemple #24
0
        public void FailsWhenNoFactoryTypeIsNull()
        {
            Request r = new Request();

            RequestDispatcher dispatcher = new RequestDispatcher();

            DispatchResult result = dispatcher.Dispatch(r, "Network");
        }
Exemple #25
0
        override protected void service(HttpServletRequest req, HttpServletResponse resp)
        {
            string                     servletPath = ServletIncludeUtils.getServletPath(req);
            TextWriter                 writer      = (TextWriter)ServletIncludeUtils.getTextWriter(req);
            RequestDispatcher          dispatcher  = getServletContext().getRequestDispatcher(servletPath);
            HttpServletResponseWrapper wrapper     = new AspxResponseWrapper(resp, writer);

            dispatcher.include(req, wrapper);
        }
Exemple #26
0
        public SharpShark(String p_SecretKey)
        {
            BaseURL           = "http://grooveshark.com";
            RequestDispatcher = new RequestDispatcher(this, p_SecretKey);
            m_EventHandlers   = new Dictionary <ClientEvent, List <Action <SharkEvent> > >();

            InitComponents();
            RegisterEventHandlers();
        }
 public void WhenIReadTheResponseFromTheServerRequestDispatcher()
 {
     try {
         Response = RequestDispatcher.ReceiveResponse <GetClientInformationResponse>();
     }
     catch (Exception ex) {
         Error = ex;
     }
 }
Exemple #28
0
        // Token: 0x06000FDD RID: 4061 RVA: 0x00062EB8 File Offset: 0x000610B8
        private void OnEndRequest(object sender, EventArgs e)
        {
            ExTraceGlobals.CoreCallTracer.TraceDebug(0L, "OwaModule.OnEndRequest");
            HttpApplication httpApplication = (HttpApplication)sender;

            if (this.ShouldInterceptRequest(httpApplication.Context, false))
            {
                if (!Globals.IsInitialized)
                {
                    return;
                }
                HttpContext context    = httpApplication.Context;
                OwaContext  owaContext = OwaContext.Get(context);
                if (owaContext == null)
                {
                    return;
                }
                try
                {
                    this.requestInspector.OnEndRequest(owaContext);
                }
                finally
                {
                    if (Globals.FilterETag && VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).OwaDeployment.FilterETag.Enabled)
                    {
                        context.Response.Headers.Remove("ETag");
                    }
                    long requestLatencyMilliseconds = owaContext.RequestLatencyMilliseconds;
                    if (Globals.OwaVDirType == OWAVDirType.OWA && Globals.ArePerfCountersEnabled)
                    {
                        if (RequestDispatcher.IsUserInitiatedRequest(context.Request))
                        {
                            PerformanceCounterManager.UpdateResponseTimePerformanceCounter(requestLatencyMilliseconds, OwaContext.Current.RequestExecution == RequestExecution.Proxy);
                        }
                        OwaSingleCounters.TotalRequests.Increment();
                        if (owaContext.ErrorInformation != null)
                        {
                            OwaSingleCounters.TotalRequestsFailed.Increment();
                            Exception exception = owaContext.ErrorInformation.Exception;
                            this.UpdateExceptionsPerfCountersQueues(exception);
                        }
                        else
                        {
                            this.UpdateExceptionsPerfCountersQueues(null);
                        }
                        if (owaContext.RequestExecution == RequestExecution.Proxy)
                        {
                            OwaSingleCounters.ProxiedUserRequests.Increment();
                        }
                    }
                    ExTraceGlobals.RequestTracer.TraceDebug <string, long>((long)owaContext.GetHashCode(), "Response: HTTP {0}, time:{1} ms.", owaContext.HttpContext.Response.Status, requestLatencyMilliseconds);
                    OwaDiagnostics.ClearThreadTracing();
                }
            }
        }
Exemple #29
0
        public void ReturnsFailedIfCannotGetProxyInstance()
        {
            RequestDispatcher dispatcher = new RequestDispatcher();
            Request           request    = new Request();

            request.Behavior = new OfflineBehavior();
            request.Behavior.ProxyFactoryType = typeof(MockProxyFactory);
            DispatchResult result = dispatcher.Dispatch(request, "Network");

            Assert.AreEqual(DispatchResult.Failed, result);
        }
Exemple #30
0
        public void Start()
        {
            RequestRepository.Clear();

            var buffer         = new Buffer(BufferSize);
            var sourceService  = new SourceService(RequestAmount, SourceAmount, SourceMinArg, SourceMaxArg);
            var handlerService = new HandlerService(HandlerAmount, HandlerMinArg, HandlerMaxArg);
            var dispatcher     = new RequestDispatcher(buffer, sourceService, handlerService, RequestRepository);

            dispatcher.Start();
        }
 public RequestDispatcherTestsState()
 {
     RequestDispatcher = new RequestDispatcher(null, null);
 }
 public void GivenAServerRequestDispatcher()
 {
     RequestDispatcher = new RequestDispatcher(ServerConnection, new JsonRequestParser());
 }
 public override void Setup()
 {
     RequestDispatcher = new RequestDispatcher(null, null);
     ClearUsedTypes();
 }