Beispiel #1
0
 private static void Repeat(IBusControl bus, string command, int times)
 {
     for (int i = 0; i < times; i++)
     {
         if (command == "approval")
         {
             bus.Publish<ReportApproval>(new ReportApprovalMessage
             {
                 Approved = (times % 2) == 0,
                 ApprovalNotes = "this is the " + i + " time "
             });
         }
         else if (command == "newref")
         {
             bus.Publish<NewReferral>(new NewReferralMessage
             {
                 Name = "Mr Michael Shanks the " + i,
                 DateOfBirth = DateTime.Now.AddYears(-20),
                 NoOfAuthorisations = i
             });
         }
         else
         {
             throw new Exception("Could not find command " + command);
         }
     }
 }
Beispiel #2
0
        static void Main(string[] args)
        {
            string rabbitMqAddress = "rabbitmq://localhost:5672";
            string virtualHost     = "/";
            string rabbitMqQueue   = "StayWell.SWIQ.CreateParticipant";

            Uri rabbitMqRootUri = new Uri(string.Concat(rabbitMqAddress, virtualHost));

            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                rabbit.Host(rabbitMqRootUri, settings =>
                {
                    settings.Password("guest");
                    settings.Username("guest");
                });
            });

            rabbitBusControl.Start();

            Task <ISendEndpoint> sendEndpointTask = rabbitBusControl.GetSendEndpoint(new Uri(string.Concat(rabbitMqAddress, virtualHost, rabbitMqQueue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;

            do
            {
                Console.WriteLine("Enter message type ('command', 'event', 'rpc') (or 'quit' to exit)");
                Console.Write("> ");
                string type = Console.ReadLine();

                if ("quit".Equals(type, StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }

                Console.WriteLine("Enter data");
                Console.Write("> ");
                string data = Console.ReadLine();

                if (type.ToLower() == "command")
                {
                    sendEndpoint.Send <ICreateParticipant>(new
                    {
                        CreationDate = DateTime.UtcNow,
                        Data         = data
                    });
                }
                else if (type.ToLower() == "event")
                {
                    rabbitBusControl.Publish <IParticipantUpdated>(new
                    {
                        DateUpdated = DateTime.UtcNow,
                        FirstName   = data
                    });
                }
                else if (type.ToLower() == "rpc")
                {
                    IRequestClient <ICreateParticipant, ICreateParticipantResponse> client =
                        rabbitBusControl.CreateRequestClient <ICreateParticipant, ICreateParticipantResponse>(new Uri(string.Concat(rabbitMqAddress, virtualHost, rabbitMqQueue)), TimeSpan.FromSeconds(10));

                    Task.Run(async() =>
                    {
                        ICreateParticipantResponse response = await client.Request(new CreateParticipant
                        {
                            CreationDate = DateTime.UtcNow,
                            Data         = data
                        });

                        Console.WriteLine("Participant creation response: ParticipantId: {0}, Data: {1}", response.ParticipantId, response.Data);
                    }).Wait();
                }
                else
                {
                    Console.WriteLine("Wrong message type!");
                    Console.Write("> ");
                }
            }while (true);

            rabbitBusControl.Stop();
        }
Beispiel #3
0
 /// <summary>
 ///  Generic method used to send message to all queues on this exchange (exchange type is Fan-out)
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="values"></param>
 public void Publish <T>(object values) where T : class
 {
     senderBus.Publish <T>(values);
 }
 public override Task PublisAsync(object ob, Type t = null, CancellationToken?token = null)
 {
     t = t ?? ob.GetType();
     return(Control?.Publish(ob, t, token ?? CancellationToken.None));
 }
Beispiel #5
0
        // ReSharper disable once ExcessiveIndentation
        private void ReceiveCallback(IAsyncResult result)
        {
            ConnectionInfo connection = (ConnectionInfo)result.AsyncState;

            try
            {
                //get a number of received bytes
                int bytesRead = connection.Socket.EndReceive(result);
                if (bytesRead > 0)
                {
                    //because device sends data with portions we need summary all portions to total buffer
                    if (connection.IsPartialLoaded)
                    {
                        connection.TotalBuffer.AddRange(connection.Buffer.Take(bytesRead).ToList());
                    }
                    else
                    {
                        if (connection.TotalBuffer != null)
                        {
                            connection.TotalBuffer.Clear();
                        }
                        connection.TotalBuffer = connection.Buffer.Take(bytesRead).ToList();
                    }
                    //-------- Get Length of current received data ----------
                    string hexDataLength = string.Empty;

                    //Skip four zero bytes an take next four bytes with value of AVL data array length
                    connection.TotalBuffer.Skip(4).Take(4).ToList().ForEach(delegate(byte b) { hexDataLength += String.Format("{0:X2}", b); });

                    int dataLength = Convert.ToInt32(hexDataLength, 16);
                    //
                    //bytesRead = 17 when parser receive IMEI  from device
                    //if datalength encoded in data > then total buffer then is a partial data a device will send next part
                    //we send confirmation and wait next portion of data
                    // ReSharper disable once ComplexConditionExpression
                    if (dataLength + 12 > connection.TotalBuffer.Count && bytesRead != 17)
                    {
                        connection.IsPartialLoaded = true;
                        connection.Socket.Send(new byte[] { 0x01 });
                        connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None,
                                                       ReceiveCallback, connection);
                        return;
                    }

                    bool isDataPacket = true;

                    //when device send AVL data first 4 bytes is 0
                    string firstRourBytes = string.Empty;
                    connection.TotalBuffer.Take(4).ToList().ForEach(delegate(byte b) { firstRourBytes += String.Format("{0:X2}", b); });
                    if (Convert.ToInt32(firstRourBytes, 16) > 0)
                    {
                        isDataPacket = false;
                    }

                    // if is true then is AVL data packet
                    // else that a IMEI sended
                    if (isDataPacket)
                    {
                        if (true)
                        {
                            //all data we convert this to string in hex format only for diagnostic
                            StringBuilder data = new StringBuilder();
                            connection.TotalBuffer.ForEach(delegate(byte b) { data.AppendFormat("{0:X2}", b); });
                            Console.WriteLine("<" + data);
                        }


                        var decAvl = new DevicesParser();
                        decAvl.OnDataReceive += decAVL_OnDataReceive;
                        //if CRC not correct number of data returned by AVL parser = 0;
                        var avlData = decAvl.Decode(connection.TotalBuffer, connection.Imei);
                        if (!connection.IsPartialLoaded)
                        {
                            // send to device number of received data for confirmation.
                            if (avlData.Count > 0)
                            {
                                connection.Socket.Send(new byte[] { 0x00, 0x00, 0x00, Convert.ToByte(avlData.Count) });
                                LogAvlData(avlData);
                                var events = new TLGpsDataEvents
                                {
                                    Id     = Guid.NewGuid(),
                                    Events = avlData
                                };
                                var lastGpsData = events.Events.Last();

                                var command = new CreateBoxCommand();
                                command.Imei                = connection.Imei;
                                command.Longitude           = lastGpsData.Long;
                                command.Latitude            = lastGpsData.Lat;
                                command.LastValidGpsDataUtc = lastGpsData.DateTimeUtc;
                                command.Speed               = lastGpsData.Speed;
                                _bus.Publish(command).ConfigureAwait(false);
                                Thread.Sleep(1000);
                                _bus.Publish(events).ConfigureAwait(false);
                            }
                            else
                            {
                                //send 0 number of data if CRC not correct for resend data from device
                                connection.Socket.Send(new byte[] { 0x00, 0x00, 0x00, 0x00 });
                            }
                        }

                        decAvl.OnDataReceive -= decAVL_OnDataReceive;
                        Console.WriteLine("Modem ID: " + connection.Imei + " send data");
                    }
                    else
                    {
                        //if is not data packet then is it IMEI info send from device
                        connection.Imei = Encoding.ASCII.GetString(connection.TotalBuffer.Skip(2).ToArray());
                        connection.Socket.Send(new byte[] { 0x01 });
                        Console.WriteLine("Modem ID: " + connection.Imei + " connected");
                    }
                    // Get next data portion from device
                    connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None,
                                                   ReceiveCallback, connection);
                }//if all data received then close connection
                else
                {
                    CloseConnection(connection);
                }
            }
            catch (SocketException exc)
            {
                CloseConnection(connection);
                Console.WriteLine("Socket exception: " + exc.SocketErrorCode);
            }
            catch (Exception exc)
            {
                CloseConnection(connection);
                Console.WriteLine("Exception: " + exc);
            }
        }
 public async Task Publish <T>(T message) where T : class
 {
     await _serviceBus.Publish <T>(message);
 }
Beispiel #7
0
 public async Task Publish <T>(T @event) where T : IIntegrationEvent
 {
     await massTransitBus.Publish(@event);
 }
 public Task Publish <TEvent>(TEvent @event) where TEvent : class, IUserEvent
 {
     return(_bus.Publish(@event, @event.GetType()));
 }
Beispiel #9
0
 public async Task QueueTaskAsync(ImgTask imgTask)
 {
     await _bc.Publish((object)imgTask);
 }
Beispiel #10
0
        static void Main()
        {
            ConfigureLogger();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();


            IBusControl busControl = CreateBus();

            TaskUtil.Await(() => busControl.StartAsync());

            Uri hostAddress = busControl.Address.GetHostSettings().HostAddress;

            string validateQueueName = ConfigurationManager.AppSettings["ValidateActivityQueue"];
            Uri    validateAddress   = new Uri(string.Concat(hostAddress, validateQueueName));

            string retrieveQueueName = ConfigurationManager.AppSettings["RetrieveActivityQueue"];
            Uri    retrieveAddress   = new Uri(string.Concat(hostAddress, retrieveQueueName));


            try
            {
                for (;;)
                {
                    Console.Write("Enter an address (quit exits): ");
                    string requestAddress = Console.ReadLine();
                    if (requestAddress == "quit")
                    {
                        break;
                    }

                    if (string.IsNullOrEmpty(requestAddress))
                    {
                        requestAddress = "http://www.microsoft.com/index.html";
                    }

                    int limit = 1;

                    if (requestAddress.All(x => char.IsDigit(x) || char.IsPunctuation(x)))
                    {
                        string[] values = requestAddress.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        requestAddress = values[0];
                        if (values.Length > 1)
                        {
                            limit = int.Parse(values[1]);
                            Console.WriteLine("Sending {0}", limit);
                        }
                    }

                    switch (requestAddress)
                    {
                    case "0":
                        requestAddress = "http://www.microsoft.com/index.html";
                        break;

                    case "1":
                        requestAddress = "http://i.imgur.com/Iroma7d.png";
                        break;

                    case "2":
                        requestAddress = "http://i.imgur.com/NK8eZUe.jpg";
                        break;
                    }

                    Uri requestUri;
                    try
                    {
                        requestUri = new Uri(requestAddress);
                    }
                    catch (UriFormatException)
                    {
                        Console.WriteLine("The URL entered is invalid: " + requestAddress);
                        continue;
                    }

                    IEnumerable <Task> tasks = Enumerable.Range(0, limit).Select(x => Task.Run(async() =>
                    {
                        var builder = new RoutingSlipBuilder(NewId.NextGuid());

                        builder.AddActivity("Validate", validateAddress);
                        builder.AddActivity("Retrieve", retrieveAddress);

                        builder.SetVariables(new
                        {
                            RequestId = NewId.NextGuid(),
                            Address   = requestUri,
                        });

                        RoutingSlip routingSlip = builder.Build();

                        await busControl.Publish <RoutingSlipCreated>(new
                        {
                            TrackingNumber = routingSlip.TrackingNumber,
                            Timestamp      = routingSlip.CreateTimestamp,
                        });

                        await busControl.Execute(routingSlip);
                    }));

                    Task.WaitAll(tasks.ToArray());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception!!! OMG!!! {0}", ex);
                Console.ReadLine();
            }
            finally
            {
                busControl.Stop();
            }
        }
        public async Task <BodyResponse <RegisterRewardVM> > Handle(QueryRegisterRewardCommand request, CancellationToken cancellationToken)
        {
            //获取列表

            //获取该玩家的注册时间,从注册的第二天起才能领取注册奖励
            var accountResponse = await _accountClient.GetResponseExt <GetAccountBaseInfoMqCommand, BodyResponse <GetAccountBaseInfoMqResponse> >
                                      (new GetAccountBaseInfoMqCommand(request.Id));

            var accountInfo = accountResponse.Message;

            if (accountInfo.StatusCode != StatusCodeDefines.Success)
            {
                return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Error));
            }
            if ((accountInfo.Body.Flags & GetAccountBaseInfoMqResponse.SomeFlags.RegisterReward) ==
                GetAccountBaseInfoMqResponse.SomeFlags.RegisterReward)
            {
                return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success,
                                                           null, new RegisterRewardVM(RegisterRewardVM.RewardState.Over, 0, _regsterConfig.DayRewards)));
            }
            if (_regsterConfig.DayRewards.Count == 0)
            {
                return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success,
                                                           null, new RegisterRewardVM(RegisterRewardVM.RewardState.None, 0, null)));
            }
            DateTime registerDate = accountInfo.Body.RegisterDate.DateOfDayBegin();
            DateTime nowDate      = DateTime.Now.DateOfDayBegin();

            if (registerDate == nowDate)
            {
                return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success,
                                                           null, new RegisterRewardVM(RegisterRewardVM.RewardState.NotBegin, 0, _regsterConfig.DayRewards)));
            }

            int  dayIndex    = 0;
            long rewardCoins = 0;
            var  rewardInfo  = await _redis.GetUserRegiserReward(request.Id);

            if (rewardInfo == null)
            {
                rewardInfo = await _registerRepository.GetByIdAsync(request.Id);
            }
            if (rewardInfo == null)
            {
                rewardCoins = _regsterConfig.DayRewards[dayIndex];
                dayIndex    = 0;
            }
            else
            {
                if (rewardInfo.DayIndex >= _regsterConfig.DayRewards.Count - 1)
                {
                    if (dayIndex >= _regsterConfig.DayRewards.Count - 1)
                    {
                        _ = _mqBus.Publish(new FinishedRegisterRewardMqEvent(request.Id));
                    }
                    return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success,
                                                               null, new RegisterRewardVM(RegisterRewardVM.RewardState.Over, 0, _regsterConfig.DayRewards)));
                }
                else if (rewardInfo.GetDate.DateOfDayBegin() == nowDate)
                {
                    return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success,
                                                               null, new RegisterRewardVM(RegisterRewardVM.RewardState.Getted, rewardInfo.DayIndex, _regsterConfig.DayRewards)));
                }
                else
                {
                    dayIndex    = rewardInfo.DayIndex + 1;
                    rewardCoins = _regsterConfig.DayRewards[dayIndex];
                }
            }
            return(new BodyResponse <RegisterRewardVM>(StatusCodeDefines.Success, null,
                                                       new RegisterRewardVM(RegisterRewardVM.RewardState.Available, dayIndex, _regsterConfig.DayRewards)));
        }
 public Task NewOrderPublishSample(INewOrder msg)
 {
     return(_busControl.Publish(msg));
 }
Beispiel #13
0
 /// <summary>
 /// 发布消息
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="message"></param>
 public void Publish <T>(T message) where T : Event.GMP.Event
 {
     _bus.Publish(message);
 }
        public async Task Consume(ConsumeContext <IDiscordGuildDelete> context)
        {
            var message      = context.Message;
            var discordGuild = await _work.GuildRepository.SingleOrDefaultAsync(i => i.DiscordId == message.GuildId);

            if (discordGuild == null)
            {
                return;
            }

            var discordChannels     = discordGuild.DiscordChannels;
            var discordRoles        = discordGuild.DiscordRoles;
            var streamSubscriptions = discordGuild.StreamSubscriptions;

            foreach (var streamSubscription in streamSubscriptions)
            {
                try
                {
                    await _work.SubscriptionRepository.RemoveAsync(streamSubscription.Id);
                }
                catch
                {
                    Log.Error($"Unable to remove Stream Subscription {streamSubscription.User.SourceID} {streamSubscription.User.Username} in {discordGuild.DiscordId} {discordGuild.Name}");
                    continue;
                }
            }

            foreach (var discordChannel in discordChannels)
            {
                try
                {
                    var channelContext = new DiscordChannelDelete {
                        GuildId = discordGuild.DiscordId, ChannelId = discordChannel.DiscordId
                    };
                    await _bus.Publish(channelContext);
                }
                catch
                {
                    Log.Error($"Unable to remove Channel {discordChannel.DiscordId} {discordChannel.Name}");
                    continue;
                }
            }

            foreach (var discordRole in discordRoles)
            {
                try
                {
                    var roleContext = new DiscordRoleDelete {
                        GuildId = discordGuild.DiscordId, RoleId = discordRole.DiscordId
                    };
                    await _bus.Publish(roleContext);
                }
                catch
                {
                    Log.Error($"Unable to remove Role {discordRole.DiscordId} {discordRole.Name}");
                    continue;
                }
            }

            try
            {
                await _work.GuildRepository.RemoveAsync(discordGuild.Id);
            }
            catch
            {
                Log.Error($"Unable to remove Guild {discordGuild.DiscordId} {discordGuild.Name}");
            }
        }
 public static void Publish(BryzxxCreatedMessage message)
 {
     CreateBus.Publish(message);
 }
 public static void Publish(BryzxxUpdatedMessage message)
 {
     UpdateBus.Publish(message);
 }
Beispiel #17
0
        public async Task <bool> Publish <T>(T eventMessage) where T : EventMessage
        {
            await _busControl.Publish(eventMessage);

            return(true);
        }
Beispiel #18
0
 public async Task Publish <TIntegrationEvent>(TIntegrationEvent IntegrationEvent) where TIntegrationEvent : IntegrationEvent
 {
     await _bus.Publish(IntegrationEvent);
 }
Beispiel #19
0
        public async Task Consume(ConsumeContext <IDiscordGuildAvailable> context)
        {
            try
            {
                var message = context.Message;
                var guild   = _client.GetGuild(message.GuildId);

                if (guild == null)
                {
                    return;
                }

                DiscordGuild discordGuild = new DiscordGuild()
                {
                    DiscordId = message.GuildId, Name = message.GuildName, IconUrl = guild.IconUrl
                };
                await _work.GuildRepository.AddOrUpdateAsync(discordGuild, (d => d.DiscordId == message.GuildId));

                discordGuild = await _work.GuildRepository.SingleOrDefaultAsync(d => d.DiscordId == message.GuildId);

                #region Handle Channels

                var dbChannels = await _work.ChannelRepository.FindAsync(i => i.DiscordGuild == discordGuild);

                foreach (SocketGuildChannel channel in guild.TextChannels)
                {
                    var existingChannels = dbChannels.ToList().Where(i => i.DiscordId == channel.Id && i.Name == channel.Name);
                    if (existingChannels.Count() > 0)
                    {
                        continue;
                    }
                    DiscordChannelUpdate channelUpdateContext = new DiscordChannelUpdate {
                        GuildId = guild.Id, ChannelId = channel.Id, ChannelName = channel.Name
                    };
                    await _bus.Publish(channelUpdateContext);
                }

                List <ulong> channelIDs = guild.TextChannels.Select(i => i.Id).Distinct().ToList();
                if (dbChannels.Count() > 0)
                {
                    foreach (var channelId in dbChannels.Select(i => i.DiscordId).Distinct().Except(channelIDs))
                    {
                        DiscordChannelDelete channelDeleteContext = new DiscordChannelDelete {
                            GuildId = guild.Id, ChannelId = channelId
                        };
                        await _bus.Publish(channelDeleteContext);
                    }
                }

                #endregion Handle Channels

                #region Handle Roles

                var dbRoles = await _work.RoleRepository.FindAsync(i => i.DiscordGuild == discordGuild);

                foreach (SocketRole role in guild.Roles)
                {
                    var existingRoles = dbRoles.ToList().Where(i => i.DiscordId == role.Id && i.Name == role.Name);
                    if (existingRoles.Count() > 0)
                    {
                        continue;
                    }
                    DiscordRoleUpdate roleUpdateContext = new DiscordRoleUpdate {
                        GuildId = guild.Id, RoleId = role.Id, RoleName = role.Name
                    };
                    await _bus.Publish(roleUpdateContext);
                }

                List <ulong> roleIDs = guild.Roles.Select(i => i.Id).Distinct().ToList();
                if (dbRoles.Count() > 0)
                {
                    foreach (var roleId in dbRoles.Select(i => i.DiscordId).Distinct().Except(roleIDs))
                    {
                        DiscordRoleDelete roleDeleteContext = new DiscordRoleDelete {
                            GuildId = guild.Id, RoleId = roleId
                        };
                        await _bus.Publish(roleDeleteContext);
                    }
                }

                #endregion Handle Roles
            }
            catch (Exception e)
            {
                Serilog.Log.Error($"{e}");
            }
        }
Beispiel #20
0
 public async Task PublishEventAsync <TEvent>(TEvent @event) where TEvent : class, IEvent
 {
     await _busClient.Publish(@event);
 }
Beispiel #21
0
 public Task Publish <T>(T message, CancellationToken cancellationToken = default)
     where T : class
 {
     return(_busControl.Publish(message, cancellationToken));
 }
 /// <summary>
 /// Послать сообщение в шину
 /// </summary>
 /// <typeparam name="TEvent">Тип события в шине</typeparam>
 /// <param name="eventModel">модель для посылки сообщения в шину</param>
 public async Task Publish <TEvent>(TEvent eventModel) where TEvent : class
 {
     CheckForNull(eventModel);
     InitBusAndThrowOnError();
     await _bus.Publish(eventModel);
 }
Beispiel #23
0
        private static async void ThreadProc(object state)
        {
            string        imei     = string.Empty;
            var           client   = ((TcpClient)state);
            NetworkStream nwStream = ((TcpClient)state).GetStream();

            byte[] buffer = new byte[client.ReceiveBufferSize];

            try
            {
                var gpsResult = new List <CreateTeltonikaGps>();
                while (true)
                {
                    int    bytesRead    = nwStream.Read(buffer, 0, client.ReceiveBufferSize) - 2;
                    string dataReceived = Encoding.ASCII.GetString(buffer, 2, bytesRead);
                    if (imei == string.Empty)
                    {
                        imei = dataReceived;
                        Console.WriteLine("IMEI received : " + dataReceived);

                        Byte[] b = { 0x01 };
                        nwStream.Write(b, 0, 1);
                        var command = new CreateBoxCommand();
                        command.Imei = imei;
                        await _endpoint.Result.Send(command);
                    }
                    else
                    {
                        int dataNumber = Convert.ToInt32(buffer.Skip(9).Take(1).ToList()[0]);
                        var parser     = new DevicesParser();
                        gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei));
                        var bytes = Convert.ToByte(dataNumber);
                        await nwStream.WriteAsync(new byte[] { 0x00, 0x0, 0x0, bytes }, 0, 4);

                        client.Close();
                    }

                    if (gpsResult.Count <= 0)
                    {
                        continue;
                    }
                    foreach (var gpSdata in gpsResult)
                    {
                        gpSdata.Address = await _reverseGeoCodingService.ReverseGoecode(gpSdata.Lat, gpSdata.Long);

                        Console.WriteLine("IMEI: " + imei + " Date: " + gpSdata.Timestamp + " latitude : " + gpSdata.Lat +
                                          " Longitude:" + gpSdata.Long + " Speed: " + gpSdata.Speed + " Direction:" + "" +
                                          " address " + gpSdata.Address + " milage :" + gpSdata.Mileage);
                        await _bus.Publish(gpSdata);
                    }
                    break;
                }
            }
            catch (Exception)
            {
                // Console.WriteLine(e);
                client.Close();
                //throw;
            }

            //throw new NotImplementedException();
        }
Beispiel #24
0
 public async Task PublishMessage <TMessage>(TMessage message) where TMessage : class
 {
     await _serviceBus.Publish(message);
 }
Beispiel #25
0
 public static void Forward(JcbgCreatedMessage message)
 {
     CreateBus.Publish(message);
 }
Beispiel #26
0
 public static void Forward(JcbgUpdatedMessage message)
 {
     UpdateBus.Publish(message);
 }
        public async Task Consume(ConsumeContext <IStreamUpdate> context)
        {
            ILiveBotStream  stream  = context.Message.Stream;
            ILiveBotMonitor monitor = _monitors.Where(i => i.ServiceType == stream.ServiceType).FirstOrDefault();

            if (monitor == null)
            {
                return;
            }

            ILiveBotUser user = stream.User ?? await monitor.GetUserById(stream.UserId);

            ILiveBotGame game = stream.Game ?? await monitor.GetGame(stream.GameId);

            Expression <Func <StreamGame, bool> > templateGamePredicate = (i => i.ServiceType == stream.ServiceType && i.SourceId == "0");
            var templateGame = await _work.GameRepository.SingleOrDefaultAsync(templateGamePredicate);

            var streamUser = await _work.UserRepository.SingleOrDefaultAsync(i => i.ServiceType == stream.ServiceType && i.SourceID == user.Id);

            var streamSubscriptions = await _work.SubscriptionRepository.FindAsync(i => i.User == streamUser);

            StreamGame streamGame;

            if (game.Id == "0" || string.IsNullOrEmpty(game.Id))
            {
                if (templateGame == null)
                {
                    StreamGame newStreamGame = new StreamGame
                    {
                        ServiceType  = stream.ServiceType,
                        SourceId     = "0",
                        Name         = "[Not Set]",
                        ThumbnailURL = ""
                    };
                    await _work.GameRepository.AddOrUpdateAsync(newStreamGame, templateGamePredicate);

                    templateGame = await _work.GameRepository.SingleOrDefaultAsync(templateGamePredicate);
                }
                streamGame = templateGame;
            }
            else
            {
                StreamGame newStreamGame = new StreamGame
                {
                    ServiceType  = stream.ServiceType,
                    SourceId     = game.Id,
                    Name         = game.Name,
                    ThumbnailURL = game.ThumbnailURL
                };
                await _work.GameRepository.AddOrUpdateAsync(newStreamGame, i => i.ServiceType == stream.ServiceType && i.SourceId == stream.GameId);

                streamGame = await _work.GameRepository.SingleOrDefaultAsync(i => i.ServiceType == stream.ServiceType && i.SourceId == stream.GameId);
            }

            if (streamSubscriptions.Count() == 0)
            {
                return;
            }

            List <StreamSubscription> unsentSubscriptions = new List <StreamSubscription>();

            foreach (StreamSubscription streamSubscription in streamSubscriptions)
            {
                if (streamSubscription.DiscordGuild == null || streamSubscription.DiscordChannel == null)
                {
                    await _work.SubscriptionRepository.RemoveAsync(streamSubscription.Id);

                    continue;
                }

                var discordChannel = streamSubscription.DiscordChannel;
                var discordRole    = streamSubscription.DiscordRole;
                var discordGuild   = streamSubscription.DiscordGuild;

                Expression <Func <StreamNotification, bool> > previousNotificationPredicate = (i =>
                                                                                               i.User_SourceID == streamUser.SourceID &&
                                                                                               i.DiscordGuild_DiscordId == discordGuild.DiscordId &&
                                                                                               i.DiscordChannel_DiscordId == discordChannel.DiscordId &&
                                                                                               i.Stream_StartTime == stream.StartTime &&
                                                                                               i.Stream_SourceID == stream.Id &&
                                                                                               i.Success == true
                                                                                               );

                var previousNotifications = await _work.NotificationRepository.FindAsync(previousNotificationPredicate);

                if (previousNotifications.Count() > 0)
                {
                    continue;
                }

                unsentSubscriptions.Add(streamSubscription);
            }

            if (unsentSubscriptions.Count() > 0)
            {
                await _bus.Publish <IStreamOnline>(new { Stream = stream });
            }
        }