Exemple #1
0
 public RtspServer(int port, IRequestDispatcher dispatcher)
 {
     _port       = port;
     _dispatcher = dispatcher;
     _stop       = new ManualResetEvent(false);
     _listeners  = new Dictionary <string, RtspListener>();
 }
        public static Request <T> Add <T>(this IRequestDispatcher dispatcher, Func <T> func)
        {
            var request = new FuncRequest <T>(func);

            dispatcher.Add(request);
            return(request);
        }
Exemple #3
0
 public void Setup()
 {
     requestDispatcher = mockRequestDispatcher.Object;
     topicDispatcher   = mockTopicDispatcher.Object;
     monitor           = mockMonitor.Object;
     messageFactory    = mockMessageFactory.Object;
 }
Exemple #4
0
        private static void CallTheServiceSynchronously()
        {
            IRequestDispatcher requestDispatcher = null;

            try
            {
                // NOTE: i'm using Agatha's IOC wrapper here directly... you could just as well resolve the IRequestDispatcher component
                // through _your_ container
                LogInfo("Calling the service synchronously...");
                requestDispatcher = IoC.Container.Resolve <IRequestDispatcher>();
                var response = requestDispatcher.Get <HelloWorldResponse>(new HelloWorldRequest {
                    Name = "World"
                });
                Console.WriteLine(response.Message);

                LogInfo("Sending HelloWorldCommand");
                requestDispatcher.Send(new HelloWorldCommand());
            }
            finally
            {
                // not really necessary in this silly example, but it's recommended to release each RequestDispatcher instance once you're
                // done with it
                if (requestDispatcher != null)
                {
                    IoC.Container.Release(requestDispatcher);
                }
            }
        }
        public static Request <T> Add <T>(this IRequestDispatcher dispatcher, Func <T> func, CancellationToken cancellationToken)
        {
            var request = new FuncRequest <T>(func, cancellationToken);

            dispatcher.Add(request);
            return(request);
        }
        public static Request Add(this IRequestDispatcher dispatcher, Action action, CancellationToken cancellationToken)
        {
            var request = new ActionRequest(action, cancellationToken);

            dispatcher.Add(request);
            return(request);
        }
Exemple #7
0
        public void Add(string pathTemplate, IRequestDispatcher dispatcher)
        {
            if (pathTemplate == null) throw new ArgumentNullException("pathTemplate");
            if (dispatcher == null) throw new ArgumentNullException("dispatcher");

            _dispatchers.Add(new Tuple<string, IRequestDispatcher>(pathTemplate, dispatcher));
        }
Exemple #8
0
 public GameInstance(GameState state, GameCamera camera, IRequestDispatcher requestDispatcher)
 {
     State             = state;
     Camera            = camera;
     RequestDispatcher = requestDispatcher;
     Cursor            = new CursorState(this); // bad.
 }
Exemple #9
0
        public NancyEngineFixture()
        {
            this.resolver          = A.Fake <IRouteResolver>();
            this.response          = new Response();
            this.route             = new FakeRoute(response);
            this.context           = new NancyContext();
            this.errorHandler      = A.Fake <IErrorHandler>();
            this.requestDispatcher = A.Fake <IRequestDispatcher>();

            A.CallTo(() => this.requestDispatcher.Dispatch(A <NancyContext> ._)).Invokes(x => this.context.Response = new Response());

            A.CallTo(() => errorHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false);

            contextFactory = A.Fake <INancyContextFactory>();
            A.CallTo(() => contextFactory.Create()).Returns(context);

            A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null, null));

            var applicationPipelines = new Pipelines();

            this.routeInvoker = A.Fake <IRouteInvoker>();

            A.CallTo(() => this.routeInvoker.Invoke(A <Route> ._, A <DynamicDictionary> ._, A <NancyContext> ._)).ReturnsLazily(arg =>
            {
                return((Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1]));
            });

            this.engine =
                new NancyEngine(this.requestDispatcher, contextFactory, new[] { this.errorHandler }, A.Fake <IRequestTracing>())
            {
                RequestPipelinesFactory = ctx => applicationPipelines
            };
        }
Exemple #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="diagnosticsConfiguration"></param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        public NancyEngine(IRequestDispatcher dispatcher, INancyContextFactory contextFactory, IEnumerable<IStatusCodeHandler> statusCodeHandlers, IRequestTracing requestTracing, DiagnosticsConfiguration diagnosticsConfiguration, IStaticContentProvider staticContentProvider)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            this.dispatcher = dispatcher;
            this.contextFactory = contextFactory;
            this.statusCodeHandlers = statusCodeHandlers;
            this.requestTracing = requestTracing;
            this.diagnosticsConfiguration = diagnosticsConfiguration;
            this.staticContentProvider = staticContentProvider;
        }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="diagnosticsConfiguration"></param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        public NancyEngine(IRequestDispatcher dispatcher, INancyContextFactory contextFactory, IEnumerable <IStatusCodeHandler> statusCodeHandlers, IRequestTracing requestTracing, DiagnosticsConfiguration diagnosticsConfiguration, IStaticContentProvider staticContentProvider)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            this.dispatcher               = dispatcher;
            this.contextFactory           = contextFactory;
            this.statusCodeHandlers       = statusCodeHandlers;
            this.requestTracing           = requestTracing;
            this.diagnosticsConfiguration = diagnosticsConfiguration;
            this.staticContentProvider    = staticContentProvider;
        }
Exemple #12
0
        public NancyEngineFixture()
        {
            this.resolver = A.Fake<IRouteResolver>();
            this.response = new Response();
            this.route = new FakeRoute(response);
            this.context = new NancyContext();
            this.errorHandler = A.Fake<IErrorHandler>();
            this.requestDispatcher = A.Fake<IRequestDispatcher>();

            A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._)).Invokes(x => this.context.Response = new Response());

            A.CallTo(() => errorHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);

            contextFactory = A.Fake<INancyContextFactory>();
            A.CallTo(() => contextFactory.Create()).Returns(context);

            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null, null));

            var applicationPipelines = new Pipelines();

            this.routeInvoker = A.Fake<IRouteInvoker>();

            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
            {
                return (Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1]);
            });

            this.engine =
                new NancyEngine(this.requestDispatcher, contextFactory, new[] { this.errorHandler }, A.Fake<IRequestTracing>())
                {
                    RequestPipelinesFactory = ctx => applicationPipelines
                };
        }
Exemple #13
0
        public NancyEngineFixture()
        {
            this.resolver = A.Fake<IRouteResolver>();
            this.response = new Response();
            this.route = new FakeRoute(response);
            this.context = new NancyContext();
            this.statusCodeHandler = A.Fake<IStatusCodeHandler>();
            this.requestDispatcher = A.Fake<IRequestDispatcher>();
            this.diagnosticsConfiguration = new DiagnosticsConfiguration();

            A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)).Invokes((x) => this.context.Response = new Response());

            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);

            contextFactory = A.Fake<INancyContextFactory>();
            A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);

            var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };
            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);

            var applicationPipelines = new Pipelines();

            this.routeInvoker = A.Fake<IRouteInvoker>();

            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
            {
                return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result;
            });

            this.engine =
                new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider())
                {
                    RequestPipelinesFactory = ctx => applicationPipelines
                };
        }
Exemple #14
0
        private static void CallTheServiceSynchronously()
        {
            IRequestDispatcher requestDispatcher = null;

            try
            {
                // NOTE: i'm using Agatha's IOC wrapper here directly... you could just as well resolve the IRequestDispatcher component
                // through _your_ container
                Console.WriteLine("Calling the service synchronously...");
                requestDispatcher = IoC.Container.Resolve <IRequestDispatcher>();

                Console.WriteLine("requesting a hello world... (synchronously)");
                requestDispatcher.Add(new HelloWorldRequest());
                Console.WriteLine("asking the server to reverse this string... (synchronously)");
                requestDispatcher.Add(new ReverseStringRequest {
                    StringToReverse = "asking the server to reverse this string"
                });

                Console.WriteLine(requestDispatcher.Get <HelloWorldResponse>().Message);
                Console.WriteLine(requestDispatcher.Get <ReverseStringResponse>().ReversedString);

                Console.WriteLine("Sending HelloWorldCommand");
                requestDispatcher.Send(new HelloWorldCommand());
            }
            finally
            {
                // not really necessary in this silly example, but it's recommended to release each RequestDispatcher instance once you're
                // done with it
                if (requestDispatcher != null)
                {
                    IoC.Container.Release(requestDispatcher);
                }
            }
        }
 /// <summary>
 /// Creates a new instance of the <see cref="ChatEngine"/> class.
 /// </summary>
 /// <param name="dispatcher"></param>
 /// <param name="contextFactory">A factory for creating contexts</param>
 public ChatEngine(
     IRequestDispatcher dispatcher,
     IChatContextFactory contextFactory)
 {
     this.dispatcher        = dispatcher ?? throw new ArgumentNullException("dispatcher");
     this.contextFactory    = contextFactory ?? throw new ArgumentNullException("contextFactory");
     this.engineDisposedCts = new CancellationTokenSource();
 }
Exemple #16
0
        /// <summary>
        /// Initializes a new instance of <see cref="NetMQReceiver"/>
        /// </summary>
        /// <param name="socket">Inner NetMQ <see cref="RouterSocket"/></param>
        /// <param name="messageFactory">Factory for creating <see cref="NetMQMessage"/>s</param>
        /// <param name="requestDispatcher"><see cref="IRequestDispatcher"/> that will route incoming messages</param>
        public NetMQReceiver(RouterSocket socket, INetMQMessageFactory messageFactory, IRequestDispatcher requestDispatcher)
            : base(socket, messageFactory)
        {
            this.socket            = socket ?? throw new ArgumentNullException(nameof(socket));
            this.requestDispatcher = requestDispatcher ?? throw new ArgumentNullException(nameof(requestDispatcher));

            socket.ReceiveReady += OnRequestReceived;
        }
Exemple #17
0
 public RequestDispatcherWrapper([NotNull] IRequestDispatcher dispatcher)
 {
     if (dispatcher == null)
     {
         throw new ArgumentNullException(nameof(dispatcher));
     }
     _dispatcher = dispatcher;
 }
 /// <summary>Creates a new instance of the RequestLifeCycleHandler class.</summary>
 /// <param name="webContext">The web context wrapper.</param>
 public RequestLifecycleHandler(IWebContext webContext, EventBroker broker, InstallationManager installer, IRequestDispatcher dispatcher, IErrorHandler errors, AdminSection editConfig, HostSection hostConfig)
     : this(webContext, broker, installer, dispatcher, errors)
 {
     checkInstallation = editConfig.Installer.CheckInstallationStatus;
     //installerUrl = editConfig.Installer.InstallUrl;
     rewriteMethod = hostConfig.Web.Rewrite;
     _adminConfig = editConfig;
 }
        public static IRemoteResourceService At(string uri, IRequestDispatcher dispatcher, bool useDefaultFeatures = true)
        {
            IRemoteResourceService service = new Restfulie(uri, dispatcher).EntryPointService;

            if (useDefaultFeatures)
                service = service.With(new FollowRedirects());

            return service;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
		private RequestManager()
		{
            this.requestQueue = new MemoryRequestQueue();
            this.deadLetterQueue = new MemoryRequestQueue();
            this.connectionManager = new ConnectionManager(new WinNetDetectionStrategy(), 1);
            this.dispatchCommands = new Queue<Command>();
            this.requestDispatcher = new OfflineRequestDispatcher();
            this.connectionManager.Start();
		}
 /// <summary>Creates a new instance of the RequestLifeCycleHandler class.</summary>
 /// <param name="webContext">The web context wrapper.</param>
 public RequestLifecycleHandler(IWebContext webContext, EventBroker broker, InstallationManager installer, IRequestDispatcher dispatcher, IErrorHandler errors)
 {
     this.webContext = webContext;
     this.broker = broker;
     this.errors = errors;
     this.installer = installer;
     this.dispatcher = dispatcher;
     _adminConfig = null;
 }
Exemple #22
0
 /// <summary>
 /// 构造函数
 /// </summary>
 private RequestManager()
 {
     this.requestQueue      = new MemoryRequestQueue();
     this.deadLetterQueue   = new MemoryRequestQueue();
     this.connectionManager = new ConnectionManager(new WinNetDetectionStrategy(), 1);
     this.dispatchCommands  = new Queue <Command>();
     this.requestDispatcher = new OfflineRequestDispatcher();
     this.connectionManager.Start();
 }
        public static IRequestDispatcher GetInstance()
        {
            lock (_threadsafeLock)
            {
                if (_instance == null)
                    _instance = new RequestDispatcher();

                return _instance;
            }
        }
Exemple #24
0
        public static IRemoteResourceService At(string uri, IRequestDispatcher dispatcher, bool useDefaultFeatures = true)
        {
            IRemoteResourceService service = new Restfulie(uri, dispatcher).EntryPointService;

            if (useDefaultFeatures)
            {
                service = service.With(new FollowRedirects());
            }

            return(service);
        }
 public BotService(IServiceProvider serviceProvider)
 {
     _serviceProvider           = serviceProvider;
     _messageHandler            = _serviceProvider.GetRequiredService <IMessageHandler>();
     _requestDispatcher         = _serviceProvider.GetRequiredService <IRequestDispatcher>();
     _userRepo                  = _serviceProvider.GetRequiredService <IUserRepository>();
     _logger                    = Log.Logger.ForContext <BotService>();
     _responseBuilder           = _serviceProvider.GetRequiredService <IResponseBuilder>();
     _appSettings               = _serviceProvider.GetRequiredService <IOptions <AppSettings> >().Value;
     _backgroundServiceRegistry = _serviceProvider.GetRequiredService <IBackgroundServiceRegistry>();
 }
        internal static string DiscoverDispatcherName(this IRequestDispatcher dispatcher)
        {
            var name = dispatcher.ToString();

            if (name == dispatcher.GetType().FullName)
            {
                name = dispatcher.GetType().Name;
            }

            return(name);
        }
Exemple #27
0
        public static IRequestDispatcher GetInstance()
        {
            lock (_threadsafeLock)
            {
                if (_instance == null)
                {
                    _instance = new RequestDispatcher();
                }

                return(_instance);
            }
        }
Exemple #28
0
        public void Add(string pathTemplate, IRequestDispatcher dispatcher)
        {
            if (pathTemplate == null) throw new ArgumentNullException(nameof(pathTemplate));
            if (dispatcher == null) throw new ArgumentNullException(nameof(dispatcher));

            if (!pathTemplate.StartsWith("/"))
                pathTemplate = "/" + pathTemplate;

            if (Exists(pathTemplate))
                Remove(pathTemplate);
            Dispatchers.Add(new Tuple<string, IRequestDispatcher>(pathTemplate, dispatcher));
        }
Exemple #29
0
        public void Add([NotNull] string pathTemplate, [NotNull] IRequestDispatcher dispatcher)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException(nameof(pathTemplate));
            }
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            _dispatchers.Add(new Tuple <string, IDashboardDispatcher>(pathTemplate, new RequestDispatcherWrapper(dispatcher)));
        }
Exemple #30
0
        public void Add([NotNull] string pathTemplate, [NotNull] IRequestDispatcher dispatcher)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException("pathTemplate");
            }
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            _dispatchers.Add(new Tuple <string, IRequestDispatcher>(pathTemplate, dispatcher));
        }
        public static async Task <object> RunNonGenericAsync(this IRequestDispatcher dispatcher, IRequest query)
        {
            var   method    = runAsyncMethod.MakeGenericMethod(FindGenericArgument(query.GetType()));
            var   queryTask = (Task)method.Invoke(dispatcher, new[] { query });
            await queryTask;
            var   result = queryTask
                           .GetType()
                           .GetProperty(nameof(Task <object> .Result))
                           .GetGetMethod()
                           .Invoke(queryTask, Array.Empty <object>());

            return(result);
        }
Exemple #32
0
        private void InitializeOffline()
        {
            var endPoint = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
            var address  = endPoint.Endpoints[0].Address;

            connectionMonitor = new ConnectionMonitor(address.AbsoluteUri, new HttpConnectionStrategy());//http://www.somed34.ru/

            queueRepository   = new QueueRepository();
            requestDispatcher = new RequestDispatcher(queueRepository, new Base64EncryptorEx());
            queue             = queueRepository.Load();

            queueManager = QueueManager <ActivityMessage> .Instance;
            queueManager.Initialize(queue, requestDispatcher, connectionMonitor, queueRepository);
        }
 public BotService(IMessageHandler messageHandler)
 {
     if (messageHandler is null)
     {
         throw new ArgumentNullException(nameof(messageHandler));
     }
     _messageHandler             = messageHandler;
     _logger                     = ApplicationLogging.CreateLogger(typeof(BotService));
     _userRepo                   = Program.ServiceProvider.GetService <IUserRepository>();
     _requestDispatcher          = Program.ServiceProvider.GetService <IRequestDispatcher>();
     _httpDataService            = Program.ServiceProvider.GetService <IHttpDataService>();
     _nationStatesApiDataService = new NationStatesApiDataService(_httpDataService);
     _nationStatesApiQueue       = new NationStatesApiRequestQueue(_nationStatesApiDataService);
 }
Exemple #34
0
        public PomonaClient(ClientTypeMapper typeMapper, IRequestDispatcher dispatcher)
        {
            if (typeMapper == null)
            {
                throw new ArgumentNullException(nameof(typeMapper));
            }
            dispatcher = dispatcher ?? CreateDefaultRequestDispatcher(typeMapper);

            this.typeMapper = typeMapper;
            this.dispatcher = dispatcher;

            Settings = new ClientSettings();

            dispatcher.RequestCompleted += (s, e) => RaiseRequestCompleted(e.Request, e.Response, e.ThrownException);
        }
Exemple #35
0
        public void Initialize(ObservableQueue <T> queue, IRequestDispatcher dispatcher, IConnectionMonitor connectionManager, IQueueRepository <T> queueRepository)
        {
            pendingData                 = queue;
            requestDispatcher           = dispatcher;
            connectionMonitor           = connectionManager;
            this.queueRepository        = queueRepository;
            pendingData.ItemAddedEvent += PendingDataItemAddedEvent;

            connectionManager.ConnectionStatusChangedEvent += ConnectionManagerConnectionStatusChangedEvent;
            SetUpBackgroundWorker();
            if ((connectionManager.IsConnected) && (!backgroundWorker.IsBusy) && ((PendingData.Count > 0)))
            {
                backgroundWorker.RunWorkerAsync();
            }
        }
 public NancyEngineWithAsyncCancellation(
     IRequestDispatcher requestDispatcher,
     INancyContextFactory nancyContextFactory,
     IEnumerable <IStatusCodeHandler> statusCodeHandlers,
     IRequestTracing requestTracing,
     DiagnosticsConfiguration diagnosticsConfiguration,
     IStaticContentProvider staticContentProvider)
 {
     this.engine = new NancyEngine(
         requestDispatcher,
         nancyContextFactory,
         statusCodeHandlers,
         requestTracing,
         diagnosticsConfiguration,
         staticContentProvider);
 }
		public NancyEngineWithAsyncCancellation(
			IRequestDispatcher requestDispatcher,
			INancyContextFactory nancyContextFactory,
			IEnumerable<IStatusCodeHandler> statusCodeHandlers,
			IRequestTracing requestTracing,
			DiagnosticsConfiguration diagnosticsConfiguration,
			IStaticContentProvider staticContentProvider)
		{
			this.engine = new NancyEngine(
				requestDispatcher,
				nancyContextFactory,
				statusCodeHandlers,
				requestTracing,
				diagnosticsConfiguration,
				staticContentProvider);
		}
Exemple #38
0
        public InternalBotService(SessionManager sessionManager,
                                  ITelegramUpdateReceiver telegramUpdateReceiver,
                                  IUpdateDispatcher updateDispatcher,
                                  IRequestDispatcher requestDispatcher,
                                  IWakeUpService wakeUpService,
                                  ILogger <InternalBotService> logger)
        {
            _sessionManager    = sessionManager;
            _updateDispatcher  = updateDispatcher;
            _requestDispatcher = requestDispatcher;
            _wakeUpService     = wakeUpService;
            _logger            = logger;

            telegramUpdateReceiver.SetUpdateReceivedHandler(HandleTelegramMessageReceived);
            telegramUpdateReceiver.Start();
        }
        public RoutingManager(HttpServer server, Assembly[] assemblies)
        {
            Server = server;

            var qAppMiddleware = from assembly in assemblies
                                 from type in assembly.ExportedTypes
                                 from attr in type.GetCustomAttributes <MiddlewareAttribute>()
                                 orderby attr.Order
                                 select type;
            var appMiddleware = qAppMiddleware.SelectMany(ParseMiddlewareClass).ToArray();

            var qCntr = from assembly in assemblies
                        from type in assembly.ExportedTypes
                        from attr in type.GetCustomAttributes <ControllerAttribute>()
                        let controller = new ControllerDefinition(attr, type)
                                         from method in type.GetMethods()
                                         where method.GetCustomAttribute <MiddlewareAttribute>() == null
                                         let actionDef = new ActionDefinition(controller, method)
                                                         where actionDef.IsSynchronous || (actionDef.ReturnType == typeof(Task <HttpResponse>))
                                                         orderby actionDef.Signature
                                                         group actionDef by controller into grouped
                                                         orderby grouped.Key.Info.Prefix
                                                         select grouped;
            var byController = qCntr.ToArray();

            foreach (var controller in byController)
            {
                controller.Key.Actions = controller.ToArray();
            }

            // We compose using '|', '`', '\n' because these are invalid in URLs.
            // Of course you could still screw things up here but frankly, why would you (other than to shoot your own foot)?
            // The data here comes straight from attributes and class names - there is literally no way to hijack this.
            // Even then, all you get is a simple and obvious DoS.
            var fullHash = String.Join("\n", byController.Select(x => x.Key))
                           + "\n\nMiddleware:\n" + String.Join("\n", appMiddleware.Select(x => $"{x.DeclaringType.FullName}.{x.Name}"));

            var manager       = new DynamicMsilManager(CharizardDynamic, CharizardDynamic);
            var compileParams = new CodegenInfo
            {
                Controllers   = byController.Select(x => x.Key).ToArray(),
                AppMiddleware = appMiddleware,
            };
            var ass = manager.Generate(fullHash, CompileDynamicCode, compileParams);

            Dispatcher = (IRequestDispatcher)Activator.CreateInstance(ass.GetType(RequestDispatcher));
        }
Exemple #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        /// <param name="negotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyEngine(IRequestDispatcher dispatcher,
            INancyContextFactory contextFactory,
            IEnumerable<IStatusCodeHandler> statusCodeHandlers,
            IRequestTracing requestTracing,
            IStaticContentProvider staticContentProvider,
            IResponseNegotiator negotiator,
            INancyEnvironment environment)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            if (negotiator == null)
            {
                throw new ArgumentNullException("negotiator");
            }

            this.dispatcher = dispatcher;
            this.contextFactory = contextFactory;
            this.statusCodeHandlers = statusCodeHandlers.ToArray();
            this.requestTracing = requestTracing;
            this.staticContentProvider = staticContentProvider;
            this.negotiator = negotiator;
            this.engineDisposedCts = new CancellationTokenSource();
            this.traceConfiguration = environment.GetValue<TraceConfiguration>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        /// <param name="negotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyEngine(IRequestDispatcher dispatcher,
                           INancyContextFactory contextFactory,
                           IEnumerable <IStatusCodeHandler> statusCodeHandlers,
                           IRequestTracing requestTracing,
                           IStaticContentProvider staticContentProvider,
                           IResponseNegotiator negotiator,
                           INancyEnvironment environment)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            if (negotiator == null)
            {
                throw new ArgumentNullException("negotiator");
            }

            this.dispatcher            = dispatcher;
            this.contextFactory        = contextFactory;
            this.statusCodeHandlers    = statusCodeHandlers.ToArray();
            this.requestTracing        = requestTracing;
            this.staticContentProvider = staticContentProvider;
            this.negotiator            = negotiator;
            this.engineDisposedCts     = new CancellationTokenSource();
            this.traceConfiguration    = environment.GetValue <TraceConfiguration>();
        }
        public NancyEngineFixture()
        {
            this.environment =
                new DefaultNancyEnvironment();

            this.environment.Tracing(
                enabled: true,
                displayErrorTraces: true);

            this.resolver          = A.Fake <IRouteResolver>();
            this.response          = new Response();
            this.route             = new FakeRoute(response);
            this.context           = new NancyContext();
            this.statusCodeHandler = A.Fake <IStatusCodeHandler>();
            this.requestDispatcher = A.Fake <IRequestDispatcher>();
            this.negotiator        = A.Fake <IResponseNegotiator>();

            A.CallTo(() => this.requestDispatcher.Dispatch(A <NancyContext> ._, A <CancellationToken> ._))
            .Returns(Task.FromResult(new Response()));

            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false);

            contextFactory = A.Fake <INancyContextFactory>();
            A.CallTo(() => contextFactory.Create(A <Request> ._)).Returns(context);

            var resolveResult = new ResolveResult {
                Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null
            };

            A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(resolveResult);

            var applicationPipelines = new Pipelines();

            this.routeInvoker = A.Fake <IRouteInvoker>();

            A.CallTo(() => this.routeInvoker.Invoke(A <Route> ._, A <CancellationToken> ._, A <DynamicDictionary> ._, A <NancyContext> ._)).ReturnsLazily(arg =>
            {
                return(((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A <CancellationToken> ._).Result);
            });

            this.engine =
                new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake <IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)
            {
                RequestPipelinesFactory = ctx => applicationPipelines
            };
        }
Exemple #43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="errorHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        public NancyEngine(IRequestDispatcher dispatcher, INancyContextFactory contextFactory, IEnumerable<IErrorHandler> errorHandlers, IRequestTracing requestTracing)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (errorHandlers == null)
            {
                throw new ArgumentNullException("errorHandlers");
            }

            this.dispatcher = dispatcher;
            this.contextFactory = contextFactory;
            this.errorHandlers = errorHandlers;
            this.requestTracing = requestTracing;
        }
Exemple #44
0
        /// <summary>
        /// Initializes a new instance of a Server composed of the specified IReceiverManager to receive client connections,
        /// IMessageFactory to wrap requests in the Smoke message protocol and IRequestDispatcher to handle incoming messages
        /// </summary>
        /// <param name="receiverManager">Manages client connections</param>
        /// <param name="messageFactory">Wraps requests in the Smoke message protocol</param>
        /// <param name="requestDispatcher">Handles incoming messages</param>
        public Server(IReceiverManager receiverManager, IMessageFactory messageFactory, IRequestDispatcher requestDispatcher, String name)
        {
            if (messageFactory == null)
                throw new ArgumentNullException("IMessageFactory");

            if (receiverManager == null)
                throw new ArgumentNullException("IReceiverManager");

            if (requestDispatcher == null)
                throw new ArgumentNullException("IRequestHandlerFactory");

            if (name == null || name == default(String) || name.Length == 0)
                throw new ArgumentNullException("Name");

            this.messageFactory = messageFactory;
            this.receiverManager = receiverManager;
            this.requestDispatcher = requestDispatcher;
            this.serverInfo.Name = name;

            // Initialize dependencies
            requestDispatcher.Init(this);
        }
        public NancyEngineFixture()
        {
            this.environment =
                new DefaultNancyEnvironment();

            this.environment.Tracing(
                enabled: true,
                displayErrorTraces: true);

            this.resolver = A.Fake<IRouteResolver>();
            this.response = new Response();
            this.route = new FakeRoute(response);
            this.context = new NancyContext();
            this.statusCodeHandler = A.Fake<IStatusCodeHandler>();
            this.requestDispatcher = A.Fake<IRequestDispatcher>();
            this.negotiator = A.Fake<IResponseNegotiator>();

            A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._))
                .Returns(Task.FromResult(new Response()));

            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);

            contextFactory = A.Fake<INancyContextFactory>();
            A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);

            var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };
            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);

            var applicationPipelines = new Pipelines();

            this.routeInvoker = A.Fake<IRouteInvoker>();

            this.engine =
                new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)
                {
                    RequestPipelinesFactory = ctx => applicationPipelines
                };
        }
 private Restfulie(string uri, IRequestDispatcher dispatcher)
 {
     EntryPointService = new EntryPointService(uri, dispatcher);
 }
 public Request(IRemoteResourceService service, IRequestDispatcher dispatcher)
 {
     _dispatcher = dispatcher;
     _stack = new RequestStack(service);
 }
Exemple #48
0
 public ChefController(IRequestDispatcher dispatcher)
 {
     _dispatcher = dispatcher;
 }
 public FooController()
 {
     var container = new UnityContainer();
     var registry = new UnityServiceRegistry(container);
     dispatcher = new RequestDispatcher(registry);
 }
 public WaitStaffController(IRequestDispatcher dispatcher)
 {
     _dispatcher = dispatcher;
 }
 public EntryPointService(string uri, IRequestDispatcher dispatcher)
 {
     _entryPointUri = uri;
     _dispatcher = dispatcher;
 }
 public RequestDispatcherWrapper([NotNull] IRequestDispatcher dispatcher)
 {
     if (dispatcher == null) throw new ArgumentNullException(nameof(dispatcher));
     _dispatcher = dispatcher;
 }
 public WelcomePresenter(IRequestDispatcher requestDispatcher)
 {
     _requestDispatcher = requestDispatcher;
 }
        private IRemoteResourceService CreateService(HttpRemoteResponse response = null, IRequestDispatcher dispatcher = null)
        {
            if (response == null)
                response = TestHelper.CreateResponse();
            if (dispatcher == null)
                dispatcher = TestHelper.CreateDispatcher(response).Object;

            return new EntryPointService("file://NotImportant", dispatcher);
        }
 public IncludeLayoutDataAttribute()
 {
     _dispatcher = DependencyResolver.Current.GetService<IRequestDispatcher>();
 }