public ExampleModule(IRepositoryOfId<int> repository, IMappingEngine engine, ISendOnlyBus bus)
        {
            Get["/examples"] = _ => repository.Query<ExampleEntity>()
                .Project().To<ExampleModel>()
                .ToList();

            Get["/example/{id:int}"] = _ => {
                var entity = repository.Load<ExampleEntity>(_.id);
                return engine.Map<ExampleEntity, ExampleModel>(entity);
            };

            Post["/examples"] = _ => {
                var model = this.BindAndValidateModel<NewExampleModel>();

                var entity = new ExampleEntity(model.Name);
                repository.Save(entity);

                return new NewExampleCreatedModel { Id = entity.ID };
            };

            Post["/examples/close"] = _ => {
                var model = this.BindAndValidateModel<CloseExampleModel>();
                bus.Send(new CloseExampleCommand {Id = model.Id});
                return HttpStatusCode.OK;
            };

            Delete["/example/{id:int}"] = _ => {
                repository.Delete<ExampleEntity>(_.id);
                return HttpStatusCode.OK;
            };
        }
Ejemplo n.º 2
0
        private static void RunOnce()
        {
            var cts = new CancellationTokenSource();

            EventWaitHandle sequentialStarter = new AutoResetEvent(true);

            Task[] tasks =
            {
                StartEndpoint(new FirstHandlerInSagaEndpoint(),  cts.Token, sequentialStarter),
                StartEndpoint(new SecondHandlerInSagaEndpoint(), cts.Token, sequentialStarter),
                StartEndpoint(new DoingSomethingElseEndpoint(),  cts.Token, sequentialStarter)
            };

            // let everything settle down
            Task.Delay(20000).Wait();

            // send a message that does something
            BusConfiguration config = new BusConfiguration();

            config.UseTransport <AzureServiceBusTransport>();
            using (ISendOnlyBus bus = Bus.CreateSendOnly(config))
            {
                bus.Send <RunBusinessActivity>(m => m.ProcessId = Guid.NewGuid().ToString());
            }

            // and then close the system down after another ten seconds
            cts.CancelAfter(10000);
            Task.WaitAll(tasks);
        }
        public ActionResult Submit()
        {
            _bus.Send(new SubmitOrderCommand
            {
                CustomerUsername = "******",
                DateSubmitted    = DateTime.UtcNow,
                ProductIds       = new[]
                {
                    new SubmitOrderCommand.Product
                    {
                        Id       = 100,
                        Quantity = 1
                    },
                    new SubmitOrderCommand.Product
                    {
                        Id       = 101,
                        Quantity = 2
                    },
                    new SubmitOrderCommand.Product
                    {
                        Id       = 102,
                        Quantity = 3
                    },
                },
            });

            return(RedirectToAction("OrderComplete"));
        }
Ejemplo n.º 4
0
        public void Run()
        {
            ConsoleKey?key = null;

            WriteWelcomeMessage();

            do
            {
                if (key == ConsoleKey.C)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Sending Create Application Command");
                    Console.ResetColor();

                    var command = new CreateApplicationCommand()
                    {
                        ApplicationId = Guid.NewGuid(),
                        FirstName     = "foo",
                        LastName      = "bar",
                        TTL           = DateTime.Now.AddSeconds(5)
                    };

                    _bus.Send(command);
                }

                key = Console.ReadKey().Key;
                Console.WriteLine();
            } while (key != ConsoleKey.Q);
        }
Ejemplo n.º 5
0
        public static async Task StartAsync(
            ISendOnlyBus bus,
            string track,
            string consumerKey,
            string consumerSecret,
            string accessToken,
            string accessTokenSecret)
        {
            var credentials = new TwitterCredentials(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            while (true)
            {
                try
                {
                    var stream = Stream.CreateFilteredStream(credentials);
                    stream.AddTrack(track);

                    var sessionId = Guid.NewGuid();
                    stream.StreamStarted += (sender, args) =>
                    {
                        sessionId = Guid.NewGuid();
                        ColorConsole.WriteLine(
                            $"{DateTime.UtcNow.ToLocalTime()}".DarkGray(),
                            " ",
                            $" {track} ".DarkCyan().OnWhite(),
                            " ",
                            "stream started with session ID".Gray(),
                            " ",
                            $"{sessionId}".White());
                    };

                    stream.StreamStopped += (sender, args) => ColorConsole.WriteLine(
                        $"{DateTime.UtcNow.ToLocalTime()} ".DarkGray(),
                        $" {track} ".DarkCyan().OnWhite(),
                        " stream stopped.".Red(),
                        args.Exception == null ? string.Empty : $" {args.Exception.Message}".DarkRed());

                    stream.MatchingTweetReceived += (sender, e) =>
                    {
                        var analyzeTweet = TweetMapper.Map(e.Tweet, track);
                        Writer.Write(analyzeTweet.Tweet);
                        bus.Send(analyzeTweet);

                        var tweetReceived = new TweetReceived()
                        {
                            SessionId = sessionId,
                            Track = track,
                            TweetId = e.Tweet.Id
                        };
                        bus.Publish(tweetReceived);
                    };

                    await stream.StartStreamMatchingAnyConditionAsync();
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine($"{DateTime.UtcNow.ToLocalTime()} ".DarkGray(), "Error listening to Twitter stream.".Red(), $" {ex.Message}".DarkRed());
                    Thread.Sleep(1000);
                }
            }
        }
 public ActionResult Index(BillingViewModel model)
 {
     Response.AppendHeader("Access-Control-Allow-Origin", "*");
     bus.Send <IBillTheUserCommand>((x) =>
     {
         x.Email    = model.Email;
         x.CCNumber = model.CCNumber;
     });
     return(Json(new {}));
 }
Ejemplo n.º 7
0
 public ActionResult Index(SignupViewModel model)
 {
     bus.Send <ISignupUserCommand>(x =>
     {
         x.Email    = model.Email;
         x.Name     = model.Name;
         x.Password = model.Password;
     });
     return(Json(new {}));
 }
 private void SendCommand(int brokerId)
 {
     sendOnlyBus.Send(
         new SubmitAgreementCommand
     {
         CorrelationId        = Guid.NewGuid(),
         BrokerId             = brokerId,
         AgreementDocumentUrl =
             "https://upload.wikimedia.org/wikipedia/en/f/f4/The_Best_Best_of_Fela_Kuti.jpg"
     });
 }
Ejemplo n.º 9
0
        public ActionResult Send(SendMessageCommand command)
        {
            if (ModelState.IsValid)
            {
                _bus.Send(command);

                return(View("Sent"));
            }

            return(View("Send"));
        }
    public SendMessageModule(ISendOnlyBus bus) : base("/sendmessage")
    {
        this.bus = bus;

        this.Get["/"] = r =>
        {
            var message = new MyMessage();
            bus.Send("Samples.Nancy.Endpoint", message);
            return("Message sent to endpoint");
        };
    }
Ejemplo n.º 11
0
        public ActionResult LogOn(CreateUserCommand command)
        {
            if (ModelState.IsValid)
            {
                _bus.Send(command);
                _formsAuthenticationService.SignIn(command.UserId.Value, false);

                return(RedirectToAction("Index", "Messages"));
            }

            return(View());
        }
Ejemplo n.º 12
0
        public ActionResult Produce()
        {
            using (var context = new ChocolateContext())
            {
                var lotNumber = Random.Next(1, 9999);

                bus.Send(new ProduceChocolateBar {
                    LotNumber = lotNumber
                });

                context.Productions.Add(new ChocolateProduction(lotNumber));

                context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
        static void Main(string[] args)
        {
            var config = new BusConfiguration();
            config.UsePersistence<InMemoryPersistence>();
            config.UseTransport<AzureStorageQueueTransport>();
            ServiceBus = Bus.CreateSendOnly(config);

            ReportStoreMessage message = new ReportStoreMessage();

            message.CompanyID = 50000;
            message.CompanyStoreID = 1;
            message.Identifier = "999243463345888";
            message.Timestamp = DateTime.Now;

            ServiceBus.Send("50000", message);

            Console.WriteLine("Message sent");
            Console.ReadLine();
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            BusConfiguration configuration = new BusConfiguration();

            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <JsonSerializer>();

            ConventionsBuilder conventions = configuration.Conventions();

            conventions.DefiningCommandsAs(c => c.Namespace != null && c.Namespace == "Messages" && c.Name.EndsWith("Command"));

            using (ISendOnlyBus bus = Bus.CreateSendOnly(configuration))
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("When you're ready, press 1 to send the command!");
                Console.WriteLine("Press any other key to exit");

                while (true)
                {
                    var keyPressed = Console.ReadKey();
                    Console.WriteLine();

                    if (keyPressed.Key == ConsoleKey.D1)
                    {
                        SendMessageCommand cmd = new SendMessageCommand()
                        {
                            EventId = Guid.NewGuid().ToString()
                        };
                        Console.WriteLine($"Sending SendMessageCommand with id {cmd.EventId}");
                        bus.Send(cmd);
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            BusConfiguration configuration = new BusConfiguration();

            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <JsonSerializer>();

            ConventionsBuilder conventions = configuration.Conventions();

            conventions.DefiningCommandsAs(t => t.Namespace != null && t.Namespace == "Messages" && t.Name.EndsWith("Command"));

            CancelOrderCommand cmd = new CancelOrderCommand();

            cmd.OrderId = Guid.NewGuid();

            Console.WriteLine("When you're ready, press a key to send the command!");
            Console.ReadKey();

            using (ISendOnlyBus bus = Bus.CreateSendOnly(configuration))
            {
                Console.WriteLine("Sending CancelOrderCommand");
                bus.Send(cmd);
            }
        }
Ejemplo n.º 16
0
 public void CloseExample(int id)
 {
     _bus.Send(new CloseExampleCommand {
         Id = id
     });
 }
Ejemplo n.º 17
0
        public static void Start(ISendOnlyBus bus)
        {
            var random = new Random();
            var countOfUsers = 15;
            while (true)
            {
                Thread.Sleep((int)Math.Pow(random.Next(6), 5));
                var now = DateTime.UtcNow;
                var hashtag = "Simulated";
                var track = $"#{hashtag}";
                var hashtagText = track;
                var secondaryHashtag = new string(char.ConvertFromUtf32(random.Next(65, 80)).ElementAt(0), 6);
                if (now.Millisecond % 3 == 0)
                {
                    hashtag = hashtag.ToLowerInvariant();
                    hashtagText = hashtagText.ToLowerInvariant();
                    secondaryHashtag = secondaryHashtag.ToLowerInvariant();
                }

                var userId = random.Next(countOfUsers);
                var userMentionId = random.Next(countOfUsers);
                var userMentionIndex = random.Next(31) + 1;
                var retweetedUserId = random.Next(countOfUsers);
                var text = string.Join(
                        string.Empty,
                        Enumerable.Range(0, userMentionIndex - 1).Select(i => char.ConvertFromUtf32(random.Next(65, 128)))) +
                    $" @johnsmith{userMentionId} " +
                    string.Join(
                        string.Empty,
                        Enumerable.Range(0, random.Next(32)).Select(i => char.ConvertFromUtf32(random.Next(65, 128)))) +
                    $" {hashtagText}" +
                    $" #{secondaryHashtag}";

                var message = new AnalyzeTweet
                {
                    Tweet = new Tweet
                    {
                        Track = track,
                        Id = now.Ticks,
                        CreatedAt = now,
                        CreatedById = userId,
                        CreatedByIdStr = $"{userId}",
                        CreatedByName = $"John Smith{userId}",
                        CreatedByScreenName = $"johnsmith{userId}",
                        Text = text,
                        UserMentions = new List<UserMention>
                        {
                            new UserMention
                            {
                                Id=userMentionId,
                                IdStr= $"{userMentionId}",
                                Indices = new List<int> { userMentionIndex, userMentionIndex + $"@johnsmith{userMentionId}".Length, },
                                Name = $"John Smith{userMentionId}",
                                ScreenName = $"johnsmith{userMentionId}",
                            },
                        },
                        Hashtags = new List<Hashtag>
                        {
                            new Hashtag
                            {
                                Text = hashtag,
                                Indices = new[] { text.Length - $"{hashtagText} #{secondaryHashtag}".Length, text.Length - $" #{secondaryHashtag}".Length, },
                            },
                            new Hashtag
                            {
                                Text = secondaryHashtag,
                                Indices = new[] { text.Length - $"#{secondaryHashtag}".Length, text.Length, },
                            },
                        },
                        RetweetedTweet = now.Millisecond % 3 == 0
                            ? new Tweet
                            {
                                Track = track,
                                Id = now.AddDays(-1000).Ticks,
                                CreatedAt = now.AddDays(-1000),
                                CreatedById = retweetedUserId,
                                CreatedByIdStr = $"{retweetedUserId}",
                                CreatedByName = $"John Smith{retweetedUserId}",
                                CreatedByScreenName = $"johnsmith{retweetedUserId}",
                                Text = text,
                                UserMentions = new List<UserMention>(),
                                Hashtags = new List<Hashtag>(),
                                RetweetedTweet = null,
                            }
                            : null,
                    }
                };

                Writer.Write(message.Tweet);
                bus.Send(message);
            }
        }
Ejemplo n.º 18
0
 public ICallback Send(object message)
 {
     return(sendOnlyBus.Send(message));
 }
 public void Ping(string sender)
 {
     _bus.Send(new PingCommand {
         Sender = sender
     });
 }
Ejemplo n.º 20
0
        public override async Task Handle(MessageContext <MyTopicMessage> messageContext, CancellationToken token)
        {
            Console.WriteLine("MyMessageTopicMessageHandle " + messageContext.Message.SomeString);

            await bus.Send(new MyQueueMessage { SomeString = " Resent!!" });
        }
Ejemplo n.º 21
0
        public static bool RequestMenu(ISendOnlyBus bus, int customerId, Guid requestId)
        {
            if (!RequestIsValid(customerId, requestId)) return false;

            Console.WriteLine(Environment.NewLine);
            using (Colr.Magenta())
            {
                Console.WriteLine(Environment.NewLine + "Request {0} Menu:", requestId);
                Console.WriteLine("(a)pprove");
                Console.WriteLine("(e)xtend acceptance timeout");
                Console.WriteLine("(r)educe acceptance timeout");
                Console.WriteLine("(b)ack to previous menu");
                Console.Write(" > ");
            }

            char input = Console.ReadKey().KeyChar;
            if (!RequestIsValid(customerId, requestId)) return false;

            switch (input)
            {
                case 'a':
                    bus.Send(new ApproveRmaRequest{CustomerId = customerId, RequestId = requestId});
                    return false;
                case 'e':
                    Console.WriteLine(Environment.NewLine);
                    int extendBy = GetNumericValue("Number of seconds to extend by or (0) to cancel: ");

                    if (extendBy > 0)
                    {
                        bus.Send(new ExtendAcceptanceTimeout
                        {
                            CustomerId = customerId,
                            RequestId = requestId,
                            ExtendBySeconds = extendBy
                        });
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'r':
                    Console.WriteLine(Environment.NewLine);
                    int reduceBy = GetNumericValue("Number of seconds to reduce by or (0) to cancel: ");

                    if (reduceBy > 0)
                    {
                        bus.Send(new ReduceAcceptanceTimeout
                        {
                            CustomerId = customerId,
                            RequestId = requestId,
                            ReduceBySeconds = reduceBy
                        });
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'b':
                    return false;
                default:
                    using (Colr.Red())
                        Console.WriteLine("I don't understand, try again...");
                    return true;
            }
        }
Ejemplo n.º 22
0
 private static Guid CreateNewRequest(ISendOnlyBus bus, int customerId, int acceptIn)
 {
     Guid requestId = Db.NewRequest(customerId);
     bus.Send(new CreateRmaRequest
     {
         CustomerId = customerId,
         RequestId = requestId,
         AcceptTimeoutSeconds = acceptIn
     });
     return requestId;
 }
Ejemplo n.º 23
0
        public static bool CustomerMenu(ISendOnlyBus bus, int customerId)
        {
            Guid[] requests = Db.AllRequests(customerId);

            Console.WriteLine(Environment.NewLine);
            using (Colr.Yellow())
            {
                Console.WriteLine(Environment.NewLine + "Customer {0} Menu:", customerId);
                Console.WriteLine("(n)ew request");
                Console.WriteLine("(e)xtend all acceptance timeouts");
                Console.WriteLine("(r)educe all acceptance timeouts");
                for (var i = 0; i < requests.Length; i++)
                {
                    Console.WriteLine("({0}) Request {1}", i, requests[i]);
                }
                Console.WriteLine("(b)ack to previous menu");
                Console.Write(" > ");
            }

            char input = Console.ReadKey().KeyChar;
            switch (input)
            {
                case 'n':

                    Console.WriteLine(Environment.NewLine);
                    int acceptIn = GetNumericValue("Number of seconds before auto accept or (0) to cancel: ");

                    if (acceptIn > 0)
                    {
                        Guid requestId = CreateNewRequest(bus, customerId, acceptIn);
                        while (RequestMenu(bus, customerId, requestId))
                        {
                        }
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'e':
                    Console.WriteLine(Environment.NewLine);
                    int extendBy = GetNumericValue("Number of seconds to extend by or (0) to cancel: ");

                    if (extendBy > 0)
                    {
                        bus.Send(new ExtendAllAcceptanceTimeouts {CustomerId = customerId, ExtendBySeconds = extendBy});
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'r':
                    Console.WriteLine(Environment.NewLine);
                    int reduceBy = GetNumericValue("Number of seconds to reduce by or (0) to cancel: ");

                    if (reduceBy > 0)
                    {
                        bus.Send(new ReduceAllAcceptanceTimeouts {CustomerId = customerId, ReduceBySeconds = reduceBy});
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'b':
                    return false;
                default:
                    int i;
                    if (int.TryParse(input.ToString(), out i))
                        if (i < requests.Length)
                        {
                            while (RequestMenu(bus, customerId, requests[i]))
                            {
                            }
                            return true;
                        }

                    using (Colr.Red())
                        Console.WriteLine("Unknown input '{0}', please try again" + Environment.NewLine, input);
                    return true;
            }
        }