コード例 #1
0
        public static void SubscribeSessionEvent <T>(this IEventBus eventBus, EventSource source,
                                                     IEntityEventSubscriber subscriber, EntitySessionEventHandler <T> handler)
        {
            var wrapper = new HandlerWrapper <T>(handler);

            eventBus.SubscribeEvent <EntitySessionMessage <T> >(source, subscriber, wrapper.Invoke);
        }
コード例 #2
0
        /// <summary>
        /// Registers a listener on the handler for one request only. After it has completed the request/response cycle, the listener is removed from the handler
        /// and the response is returned from this method. This method blocks the calling thread until it returns; therefore, this is a synchronous call.
        /// </summary>
        /// <param name="handlerName">The name of the Handler to use for the request/response cycle.</param>
        /// <returns>The processed results.</returns>
        public ELM327ListenerEventArgs SyncQuery(string handlerName)
        {
            // Variables
            HandlerWrapper          handlerWrapper = null;
            ELM327ListenerEventArgs returnValue    = null;
            Stopwatch stopWatch = new Stopwatch();

            // Find a Handler with the provided name
            if (!(_loadedHandlers.TryGetValue(handlerName, out handlerWrapper)))
            {
                log.Error("An attempt was made to enqueue a handler for an AsyncQuery that could not be found using the provided name: " + handlerName);
                return(null);
            }

            // Add an anonymous listener that gets the value for us
            handlerWrapper.Handler.RegisterSingleListener(
                new Action <ELM327ListenerEventArgs>(
                    (ELM327ListenerEventArgs args) => {
                returnValue = args;
            }
                    )
                );

            // Wait no more than 100 milliseconds for a response
            stopWatch.Start();
            while (stopWatch.ElapsedMilliseconds < 100 && returnValue == null)
            {
                ;
            }
            stopWatch.Stop();

            return(returnValue);
        }
コード例 #3
0
        /// <summary>
        /// Publish specified event for registered subscribers
        /// </summary>
        /// <param name="sender">event source</param>
        /// <param name="eventArgs">event arguments</param>
        public virtual void Publish(object sender, EventArgs eventArgs)
        {
            if (eventArgs == null)
            {
                throw new ArgumentNullException("eventData");
            }
            if (Publishing != null)
            {
                Publishing(sender, eventArgs);
            }

            var eventDataType = eventArgs.GetType();

            while (eventDataType != null)
            {
                if (eventHandlers.ContainsKey(eventDataType))
                {
                    var matchedHandlers = new HandlerWrapper[eventHandlers[eventDataType].Count];
                    eventHandlers[eventDataType].CopyTo(matchedHandlers, 0);
                    foreach (var h in matchedHandlers)
                    {
                        h.Handler.DynamicInvoke(sender, eventArgs);
                    }
                }
                eventDataType = eventDataType.BaseType;
            }

            if (Published != null)
            {
                Published(sender, eventArgs);
            }
        }
コード例 #4
0
        /// <summary>
        /// Adds a handler to the list of available handlers. This is a necessary step before accepting and/or fulfilling any
        /// requests/responses that are processed by this handler.
        /// </summary>
        /// <param name="handlerType">The Type metaclass for the Handler to be added.</param>
        /// <returns>True if the Handler is successfully added; otherwise, false.</returns>
        public bool AddHandler(Type handlerType)
        {
            HandlerWrapper newHandlerWrapper = null;

            // Ensure the type provided is actually an IHandler type
            if (typeof(IHandler).IsAssignableFrom(handlerType))
            {
                // Create a new HandlerWrapper of the provided type
                try
                {
                    newHandlerWrapper = new HandlerWrapper(handlerType);
                }
                catch (Exception e)
                {
                    log.Error("An exception occurred while attempting to create a HandlerWrapper object from Type [" + handlerType.AssemblyQualifiedName + "].", e);
                    return(false);
                }

                // Ensure the Handler does not already exist in the handler dictionary and add it
                if (_loadedHandlers.ContainsKey(handlerType.Name) || !(_loadedHandlers.TryAdd(handlerType.Name, newHandlerWrapper)))
                {
                    log.Error("An attempt was made to add a preexisting Handler to the Dictionary of loaded handlers.");
                    return(false);
                }

                // If we made it here, we were successful
                return(true);
            }
            else
            {
                // Log a failed attempt
                log.Error("An attempt was made to add an object as a Handler that did not implement the IHandler interface.");
            }
            return(false);
        }
コード例 #5
0
        private static async Task Main(string[] args)
        {
            // Inicializa la configuración de la app.
            Configuration = ConfigurationBuilder(Environment.GetEnvironmentVariable("ENVIRONMENT")).Build();
            // envVariables = Configuration.GetSection("environmentDM").Get<EnvVariables>();
            GetVariablesEntorno();
            // Configura la colección de servicios para la app.
            var services = ConfigureServices(Configuration);
            // Genera un proveedor para iniciar el servicio AWSService.
            var serviceProvider = services.BuildServiceProvider();

            // Inicia el Proceso.
            initial = serviceProvider.GetService <IIniciaProceso>();

            Func <S3Event, ILambdaContext, string> func = FunctionHandler;


            // Para debuguear como app de consola:
            //     - Descomentar la región DEBUG.
            //     - Comentar la región AWS_LAMBDA.

            // #region DEBUG
            // var context = new TestLambdaContext();
            // var s3_event = JsonConvert.DeserializeObject<S3Event>(await File.ReadAllTextAsync("event.json"));
            // var upperCase = Program.FunctionHandler(s3_event, context);
            //#endregion
            //FIXME Descomentar para que funcione como lambda.
            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new Amazon.Lambda.Serialization.Json.JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #6
0
        public static void Main(string[] args)
        {
            // AWS Lambda will call the "bootstrap" shell script, which
            // will pass the string "lambda" as an argument
            if (args.Length > 0 && args[0] == "lambda")
            {
                var lambdaEntryPoint = new LambdaEntryPoint();

                // This explicit cast is needed with slightly older C# versions
                var lambdaFunctionHandler = (Func <APIGatewayProxyRequest, Amazon.Lambda.Core.ILambdaContext, Task <APIGatewayProxyResponse> >)lambdaEntryPoint.FunctionHandlerAsync;

                var handlerWrapper = HandlerWrapper.GetHandlerWrapper <APIGatewayProxyRequest, APIGatewayProxyResponse>(lambdaFunctionHandler, new JsonSerializer());
                using (handlerWrapper)
                {
                    using (var lambdaBootstrap = new LambdaBootstrap(handlerWrapper))
                    {
                        lambdaBootstrap.RunAsync().GetAwaiter().GetResult();
                    }
                }
            }
            // Otherwise, it gets called like most ASP.NET Core web apps
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }
コード例 #7
0
 //--- Class Methods ---
 public static async Task Main(string[] args)
 {
     // NOTE: this method is the entry point for Lambda functions with a custom runtime
     using var handlerWrapper = HandlerWrapper.GetHandlerWrapper(new Function().FunctionHandlerAsync);
     using var bootstrap      = new LambdaBootstrap(handlerWrapper);
     await bootstrap.RunAsync();
 }
コード例 #8
0
        private static async Task Main(string[] args)
        {
            Func <string, ILambdaContext, string> func = FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
            {
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    try
                    {
                        await bootstrap.RunAsync();
                    }

                    catch (Exception ex)
                    {
                        Console.WriteLine("An exception occured with message below:");
                        Console.WriteLine("----------------------------------------");
                        Console.WriteLine(ex.Message);

                        Console.WriteLine("Stack Trace:");
                        Console.WriteLine("------------");
                        Console.WriteLine(ex.StackTrace);

                        if (ex.InnerException != null)
                        {
                            Console.WriteLine("Inner Exception:");
                            Console.WriteLine("---------------");
                            Console.WriteLine(ex.InnerException.Message);
                        }
                    }
                }
            }
        }
コード例 #9
0
    public void AddMovieLoadHandler(
        string instanceName, MovieEventHandler handler, bool immortal = false)
    {
        AddLoadCallback((o) => {
            HandlerWrapper w    = new HandlerWrapper();
            MovieEventHandler h = (m) => {
                if (!immortal)
                {
                    lwf.RemoveMovieEventHandler(instanceName, w.id);
                }
                handler(m);
            };

            LWF.Movie movie = lwf[instanceName];
            if (movie != null)
            {
                handler(movie);
                if (immortal)
                {
                    w.id = lwf.AddMovieEventHandler(instanceName, load: h);
                }
            }
            else
            {
                w.id = lwf.AddMovieEventHandler(instanceName, load: h);
            }
        });
    }
コード例 #10
0
        public static async Task Main()
        {
            Func <string, ILambdaContext, Task> func = FunctionHandler;

            using var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new DefaultLambdaJsonSerializer());
            using var bootstrap      = new LambdaBootstrap(handlerWrapper);
            await bootstrap.RunAsync();
        }
コード例 #11
0
 public LambdaBootstrapTests()
 {
     _environmentVariables = new TestEnvironmentVariables();
     _testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables);
     _testInitializer      = new TestInitializer();
     _testFunction         = new TestHandler();
     _testWrapper          = HandlerWrapper.GetHandlerWrapper(_testFunction.HandlerVoidVoidSync);
 }
コード例 #12
0
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        private static async Task Main(string[] args)
        {
            Func <string, ILambdaContext, string> func = FunctionHandler;

            using var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer());
            using var bootstrap      = new LambdaBootstrap(handlerWrapper);
            await bootstrap.RunAsync();
        }
コード例 #13
0
    public static async Task RunAsync(HttpClient?httpClient = null, CancellationToken cancellationToken = default)
    {
        var serializer = new JsonSerializer();

        using var handlerWrapper = HandlerWrapper.GetHandlerWrapper <MathsRequest, MathsResponse>(Evaluate, serializer);
        using var bootstrap      = new LambdaBootstrap(httpClient ?? new HttpClient(), handlerWrapper);

        await bootstrap.RunAsync(cancellationToken);
    }
コード例 #14
0
            public void ReturnHandler()
            {
                var expectedHandlerMock = new Mock <IHandlerAsync <TestMessage> >();
                var sut = new HandlerWrapper <TestMessage>(expectedHandlerMock.Object);

                var actual = sut.GetHandler();

                actual.Should().Be(expectedHandlerMock.Object);
            }
コード例 #15
0
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        internal static async Task Main(string[] args)
        {
            var function = new Function();
            Func <string, ILambdaContext, Task <string> > func = function.FunctionHandler;

            using var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer());
            using var bootstrap      = new LambdaBootstrap(handlerWrapper);
            await bootstrap.RunAsync();
        }
コード例 #16
0
ファイル: Function.cs プロジェクト: wolfems/AMSales
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        private static async Task Main(string[] args)
        {
            Func <Newtonsoft.Json.Linq.JObject, ILambdaContext, string> func = FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #17
0
ファイル: LambdaHost.cs プロジェクト: Tyts-Software/Lambda
        public async Task RunAsync()
        {
            Func <TInput, ILambdaContext, Task <TOutput> > func = _handler.HandleAsync;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #18
0
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        private static async Task Main(string[] args)
        {
            Func <CloudWatchLogsEvent, Task> func = FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #19
0
        private static async Task Main(string[] args)
        {
            Func <APIGatewayProxyRequest, ILambdaContext, APIGatewayProxyResponse> func = Handler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, JsonSerializer))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #20
0
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        private static async Task Main(string[] args)
        {
            Func <ApplicationLoadBalancerRequest, ILambdaContext, ApplicationLoadBalancerResponse> func = FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new Amazon.Lambda.Serialization.Json.JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #21
0
        private static async Task Main(string[] args)
        {
            Action <FunctionInput, ILambdaContext> func = FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    await bootstrap.RunAsync();
                }
        }
コード例 #22
0
 public async Task TestVoid()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() =>
     {
         _checkpoint.Check();
     }))
     {
         await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false);
     }
 }
コード例 #23
0
        /// <summary>
        /// Follows the standard pattern for a Lambda fed from a SQS.
        /// See: https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.SQSEvents
        /// </summary>
        public static void TriggerFromSqs()
        {
            var lambdaEntry = new SqsLambdaFunction();
            Action <SQSEvent, ILambdaContext> func = lambdaEntry.FunctionHandler;

            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    bootstrap.RunAsync().Wait();
                }
        }
コード例 #24
0
 public async Task TestTask()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async() =>
     {
         await Task.Delay(0);
         _checkpoint.Check();
     }))
     {
         await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false);
     }
 }
コード例 #25
0
    internal static async Task RunAsync <T>(HttpClient?httpClient, CancellationToken cancellationToken)
        where T : MyHandler, new()
    {
        var handler    = new T();
        var serializer = new JsonSerializer();

        using var handlerWrapper = HandlerWrapper.GetHandlerWrapper <MyRequest, MyResponse>(handler.SumAsync, serializer);
        using var bootstrap      = new LambdaBootstrap(httpClient, handlerWrapper, handler.InitializeAsync);

        await bootstrap.RunAsync(cancellationToken);
    }
コード例 #26
0
 public async Task TestVoidPocoOutput()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() =>
     {
         _checkpoint.Check();
         return(PocoOutput);
     }, Serializer))
     {
         await TestHandlerWrapper(handlerWrapper, EmptyBytes, PocoOutputBytes, false);
     }
 }
コード例 #27
0
 public async Task TestVoidStream()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() =>
     {
         _checkpoint.Check();
         return(new MemoryStream(OutputBytes));
     }))
     {
         await TestHandlerWrapper(handlerWrapper, EmptyBytes, OutputBytes, true);
     }
 }
コード例 #28
0
 public async Task TestILambdaContextVoid()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((context) =>
     {
         _checkpoint.Check();
         Assert.NotNull(context.AwsRequestId);
     }))
     {
         await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false);
     }
 }
コード例 #29
0
 public async Task TestPocoInputVoid()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper <PocoInput>((input) =>
     {
         _checkpoint.Check();
         Assert.Equal(PocoInput, input);
     }, Serializer))
     {
         await TestHandlerWrapper(handlerWrapper, PocoInputBytes, EmptyBytes, false);
     }
 }
コード例 #30
0
 public async Task TestStreamVoid()
 {
     using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input) =>
     {
         _checkpoint.Check();
         AssertEqual(InputBytes, input);
     }))
     {
         await TestHandlerWrapper(handlerWrapper, InputBytes, EmptyBytes, false);
     }
 }
コード例 #31
0
ファイル: LWFObject.cs プロジェクト: dipyalov/lwf
    public void AddMovieLoadHandler(
		string instanceName, MovieEventHandler handler, bool immortal = false)
    {
        AddLoadCallback((o) => {
            HandlerWrapper w = new HandlerWrapper();
            MovieEventHandler h = (m) => {
                if (!immortal)
                    lwf.RemoveMovieEventHandler(instanceName, w.id);
                handler(m);
            };

            LWF.Movie movie = lwf[instanceName];
            if (movie != null) {
                handler(movie);
                if (immortal)
                    w.id = lwf.AddMovieEventHandler(instanceName, load:h);
            } else {
                w.id = lwf.AddMovieEventHandler(instanceName, load:h);
            }
        });
    }
コード例 #32
0
        public XmlParserResource(Encoding outputEncoding, bool processNamespaces, string namespaceSeparator)
            : base("XmlParser")
        {
            _outputEncoding = outputEncoding;
            _processNamespaces = processNamespaces;
            _namespaceSeparator = namespaceSeparator != null ? namespaceSeparator.Substring(0, 1) : ":";
            _defaultHandler = new HandlerWrapper(this, "default");
            _startElementHandler = new HandlerWrapper(this, "startElement");
            _endElementHandler = new HandlerWrapper(this, "endElement");
            _characterDataHandler = new HandlerWrapper(this, "characterDataHandler");
            _startNamespaceDeclHandler = new HandlerWrapper(this, "startNamespaceDeclHandler");
            _endNamespaceDeclHandler = new HandlerWrapper(this, "endNamespaceDeclHandler");
            _processingInstructionHandler = new HandlerWrapper(this, "processingInstructionHandler");

            _enableCaseFolding = true;
            _enableSkipWhitespace = false;
        }