Esempio n. 1
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // Creating a FabricRuntime connects this host process to the Service Fabric runtime.
                using (FabricRuntime fabricRuntime = FabricRuntime.Create())
                {
                    CqrsApplication.SetService <IDeserializer>(new Deserializer());
                    CqrsApplication.SetService(new QueryRepository());

                    // The ServiceManifest.XML file defines one or more service type names.
                    // RegisterServiceType maps a service type name to a .NET class.
                    // When Service Fabric creates an instance of this service type,
                    // an instance of the class is created in this host process.
                    fabricRuntime.RegisterServiceType("QueryModelBuilderServiceType", typeof(QueryModelBuilderService));

                    ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(QueryModelBuilderService).Name);

                    Thread.Sleep(Timeout.Infinite); // Prevents this host process from terminating to keep the service host process running.
                }
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
                throw;
            }
        }
        /// <summary>
        /// This is the main entry point for your service's partition replica.
        /// RunAsync executes when the primary replica for this partition has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric terminates this partition's replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var queryModelBuilder = GetQueryModelBuilder();
            var queue             = await StateManager.GetOrAddAsync <IReliableQueue <string> >("queryModelBuilderQueue");

            var count = (int)await queue.GetCountAsync();

            if (count > 0)
            {
                _semaphore.Release(count);
            }

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                using (ITransaction tx = StateManager.CreateTransaction())
                {
                    ConditionalResult <string> dequeueReply = await queue.TryDequeueAsync(tx);

                    if (dequeueReply.HasValue)
                    {
                        string message = dequeueReply.Value;
                        await queryModelBuilder.Handle(CqrsApplication.GetService <IDeserializer>().CreateEvent(JObject.Parse(message)));

                        await tx.CommitAsync();
                    }
                }

                await _semaphore.WaitAsync(cancellationToken);
            }
        }
        public override async Task Invoke(IOwinContext context)
        {
            if (context.Request.Method.Equals("post", StringComparison.OrdinalIgnoreCase) &&
                context.Request.Path.GetExtension().Equals("command", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // Deserialize the command and dispatch it
                    var command = DeserializeFromBody(context.Request.Body);
                    await CqrsApplication.GetService <CommandBus>().Dispatch(command);

                    context.Response.StatusCode = 200;
                    await context.Response.WriteAsync("{ \"commandAccepted\": true }");
                }
                catch (AggregateException aEx)
                {
                    var ex = aEx.InnerExceptions.FirstOrDefault();
                    ExceptionHandler(ex ?? aEx);
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync($"{{ \"commandAccepted\": false, \"error\": \"{ex?.Message}\" }}");
                }
                catch (Exception ex)
                {
                    ExceptionHandler(ex);
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync($"{{ \"commandAccepted\": false, \"error\": \"{ex.Message}\" }}");
                }
            }
            else
            {
                await Next.Invoke(context);
            }
        }
Esempio n. 4
0
        public override async Task Invoke(IOwinContext context)
        {
            if (context.Request.Method.Equals("get", StringComparison.OrdinalIgnoreCase) &&
                context.Request.Path.GetExtension().Equals("query", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // Deserialize the querystring and dispatch it
                    var query  = DeserializeFromQueryString(context.Request.Path.ToString(), context.Request.Query);
                    var result = await CqrsApplication.GetService <QueryBus>().Dispatch(query);

                    context.Response.StatusCode = 200;
                    await context.Response.WriteAsync(result?.ToString() ?? "null");
                }
                catch (AggregateException aEx)
                {
                    var ex = aEx.InnerExceptions.FirstOrDefault();
                    ExceptionHandler(ex ?? aEx);
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync($"{{ \"queryAccepted\": false, \"error\": \"{ex?.Message}\" }}");
                }
                catch (Exception ex)
                {
                    ExceptionHandler(ex);
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync($"{{ \"queryAccepted\": false, \"error\": \"{ex.Message}\" }}");
                }
            }
            else
            {
                await Next.Invoke(context);
            }
        }
 private Command DeserializeFromBody(Stream body)
 {
     using (var sr = new StreamReader(body))
     {
         using (JsonReader jsonReader = new JsonTextReader(sr))
         {
             return(CqrsApplication.GetService <IDeserializer>().CreateCommand(JObject.Load(jsonReader)));
         }
     }
 }
Esempio n. 6
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // Creating a FabricRuntime connects this host process to the Service Fabric runtime on this node.
                using (FabricRuntime fabricRuntime = FabricRuntime.Create())
                {
                    CqrsApplication.SetService <IDeserializer>(new Deserializer());

                    // This line registers your actor class with the Fabric Runtime.
                    // The contents of your ServiceManifest.xml and ApplicationManifest.xml files
                    // are automatically populated when you build this project.
                    // For information, see http://aka.ms/servicefabricactorsplatform
                    fabricRuntime.RegisterActor <AggregateRootActor>();

                    Thread.Sleep(Timeout.Infinite); // Prevents this host process from terminating so services keeps running.
                }
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
Esempio n. 7
0
        private static async Task RunInProcessSample()
        {
            CqrsApplication.Bootstrap(
                Handlers.CommandHandlers,
                Handlers.QueryHandlers,
                Handlers.QueryModelBuilders);

            var iphoneId = Guid.Parse("d0174342-71b0-4deb-b5b8-d1064d07ec3c");

            await CqrsApplication.GetService <CommandBus>().Dispatch(new CreateArticleCommand
            {
                ArticleId   = iphoneId,
                Description = "iPhone 6S 64GB Space Gray",
                Price       = 850.99m
            });

            var document = await CqrsApplication.GetService <QueryBus>().Dispatch(new GetArticleQuery
            {
                ArticleId = iphoneId
            });

            System.Console.WriteLine(document ?? "null");
            System.Console.ReadKey();
        }
Esempio n. 8
0
        /// <summary>
        ///   The Configuration method for the Owin application
        /// </summary>
        /// <param name="appBuilder">The appBuilder.</param>
        public void Configuration(IAppBuilder appBuilder)
        {
            try
            {
                CqrsApplication.Bootstrap(
                    new ServiceFabricAggregateRootRepository(),
                    new ServiceFabricQueryRepository(),
                    Handlers.CommandHandlers, Handlers.QueryHandlers, new QueryModelBuilder[0]);

                CqrsApplication.SetService <IDeserializer>(new Deserializer());

                ServicePointManager.DefaultConnectionLimit = 1000;
                ThreadPool.SetMaxThreads(4096, 1000);

                Action <Exception> exceptionHandler = ex => ServiceEventSource.Current.ErrorMessage("WebService - Middleware failed", ex);
                appBuilder.Use <CommandMiddleware>(exceptionHandler);
                appBuilder.Use <QueryMiddleware>(exceptionHandler);
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.ErrorMessage("WebService - Startup.Configure failed", ex);
                throw;
            }
        }
        public async Task <string> Get(Guid id)
        {
            var result = await CqrsApplication.GetService <QueryRepository>().Get(id);

            return(result?.ToString());
        }
Esempio n. 10
0
 private static Command Deserialize(string command)
 {
     return(CqrsApplication.GetService <IDeserializer>().CreateCommand(JObject.Parse(command)));
 }
Esempio n. 11
0
 private Query DeserializeFromQueryString(string name, IReadableStringCollection query)
 {
     return(CqrsApplication.GetService <IDeserializer>().CreateQuery(name, query.Select(kv => new KeyValuePair <string, IEnumerable <string> >(kv.Key, kv.Value))));
 }