Esempio n. 1
0
        public static async Task HandleMessage <T>(QueueElement <T> message)
        {
            Console.WriteLine("Message received through HandleMessage()");
            var imageUrl = "";

            //var message = await serviceBus.GetMessage<QueueElement<object>>(m);
            switch (message.Type)
            {
            case "TelemetrySend":     // FROM OTHER WORKER
                var telemetrySendModel = ForceCast <Telemetry>(message.Data);
                telemetryRepository.Insert(telemetrySendModel);
                break;

            case "ActivityClose":     // TO WORKER TRIO
                var closeData = ForceCast <QueueElement <ActivityIdViewModel> >(message);
                activityRepository.Close(closeData.Data.Id);
                //--
                closeData.Data.FromOrganizer = true;
                await queueToOtherWorker.SendMessage(closeData);

                //--
                break;

            case "ActivityStart":
                var startData = ForceCast <QueueElement <ActivityIdViewModel> >(message);  // GetValue<int>(message.Data);
                activityRepository.Start(startData.Data.Id);
                //--
                startData.Data.FromOrganizer = true;
                await queueToOtherWorker.SendMessage(startData);

                //--

                break;

            case "ActivityCreate":
                var activityCreateModel = ForceCast <ActivityCreateViewModel>(message.Data);
                activityRepository.Insert(new Activity()
                {
                    //    Id = 0,
                    CreationDate = DateTime.Now,
                    EndDate      = null,
                    Location     = activityCreateModel.Location,
                    Name         = activityCreateModel.Name,
                    RaceUrl      = "", //$"https://localhost/raceSample/{new Random().Next(0, 1000)}",
                    IdUser       = activityCreateModel.IdUser,
                    Status       = 0,
                    Type         = activityCreateModel.Type,
                });
                break;

            case "ActivityJoin":
                var activityJoinModel = ForceCast <ActivityIdViewModel>(message.Data);
                activityRepository.AddRunner(
                    activityJoinModel.Id,
                    activityJoinModel.IdUser
                    );
                break;
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> Close(ActivityActionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var userId = _userRepository.GetIdByIdentity(user.Id);

                var id       = model.Id;
                var activity = _activityRepository.Get(id);
                if (activity.Status == 1)
                {
                    var queue = new ServiceBusManager(_configuration["ServiceBusConnectionString"], _configuration["ServiceBusQueueName"]);
                    await queue.SendMessage(new QueueElement <object>
                    {
                        Type = "ActivityClose",
                        Data = new ActivityIdViewModel()
                        {
                            Id = id, IdUser = userId
                        },
                    });
                }
            }
            return(RedirectToAction("Index"));
        }
        public async Task TestMethod1()
        {
            ServiceBusConfiguration config = new ServiceBusConfiguration();

            //config.ConnectionString = "Endpoint=sb://restorder.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xwradxwyM1GusLWGxwOYXjLwMOoFRWQUyMK3XwOvObM=";
            config.ConnectionString = "Endpoint=sb://restorder2.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=u7jx+8mXYgSIDu4zL6TXayqkIy/F/tqW/mAAxggHvZs=";
            config.Topic            = new TopicConfiguration()
            {
                Name         = "order",
                Subscription = new SubscriptionConfiguration()
                {
                    Name               = "outofstock",
                    AutoComplete       = false,
                    MaxConcurrentCalls = 1
                }
            };

            ServiceBusTopicSender       serviceBusTopicSender       = new ServiceBusTopicSender(config);
            ServiceBusTopicSubscription serviceBusTopicSubscription = new ServiceBusTopicSubscription(config);
            IServiceBusManager          mgr = new ServiceBusManager(serviceBusTopicSender, serviceBusTopicSubscription);

            try
            {
                ICollection <OrderMenu> menus = new List <OrderMenu>();
                menus.Add(new OrderMenu {
                    MenuId = 1, Price = 10
                });

                for (int i = 1; i <= 2; i++)
                {
                    //mgr.SendMessage<OrderEntity>(new OrderEntity
                    //{
                    //    CustomerId = i,
                    //    DeliveryAddress = "Subramanyapura",
                    //    OrderMenuDetails = menus,
                    //    RestaurantId = i
                    //});
                    await mgr.SendMessage <string>("First message");
                }

                //mgr.RecieveMessage<OrderEntity>(async order =>
                //{
                //    Console.WriteLine("Order received", order.RestaurantId, order.OrderMenuDetails.First().MenuId);
                //    await Task.CompletedTask;
                //});

                mgr.RecieveMessage <string>(async order =>
                {
                    Console.WriteLine("Order received", order);
                    await Task.CompletedTask;
                });
                Assert.IsTrue(true);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Excpetion occured", ex);
                throw;
            }
        }
Esempio n. 4
0
        public void SendMessage_WithMessageLabelAndContent_NotThrowsAnyException()
        {
            // Arrange
            string messageLabel   = "TestLabel";
            string messageContent = @"{'Name':'James'}";

            // Act
            Action comparison = async() => { await serviceBusManager.SendMessage(messageLabel, messageContent); };

            // Assert
            comparison.ShouldNotThrow <Exception>();
        }
Esempio n. 5
0
        public async Task <ActionResult> Join(ActivityJoinViewModel model)
        {
            if (ModelState.IsValid)
            {
                //await _client.GetRequest<object>($"Activity/{model.IdActivity}/Join"); // Post
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var userId = _userRepository.GetIdByIdentity(user.Id);
                var id     = model.IdActivity;
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                //model.IdUser = userId;


                if (Program.UseEventHub)
                {
                    await _eventHub.SendMessage(new QueueElement <ActivityJoinViewModel>
                    {
                        Type = "ActivityJoin",
                        Data = new ActivityJoinViewModel()
                        {
                            IdActivity = id,
                            IdUser     = userId
                        },
                    });
                }
                else
                {
                    var queue = new ServiceBusManager(_configuration["ServiceBusConnectionString"], _configuration["ServiceBusQueueName"]);
                    await queue.SendMessage(new QueueElement <ActivityJoinViewModel>
                    {
                        Type = "ActivityJoin",
                        Data = new ActivityJoinViewModel()
                        {
                            IdActivity = id,
                            IdUser     = userId
                        },
                    });
                }



                return(RedirectToAction("Index"));
            }
            return(BadRequest(ModelState));
        }
Esempio n. 6
0
        public async Task <IActionResult> Create(ActivityCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                //await _client.PostRequest<object>($"Activity/Create", model);
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var userData = _userRepository.GetUserByIdentity(user.Id);
                model.IdUser = userData.Id;

                // Failsafe
                if (model.Type != 2 || !userData.IsOrganizer)
                {
                    model.Type = 1;
                }


                if (Program.UseEventHub)
                {
                    await _eventHub.SendMessage(new QueueElement <ActivityCreateViewModel>
                    {
                        Type = "ActivityCreate",
                        Data = model,
                    });
                }
                else
                {
                    var queue = new ServiceBusManager(_configuration["ServiceBusConnectionString"], _configuration["ServiceBusQueueName"]);
                    await queue.SendMessage(new QueueElement <ActivityCreateViewModel>
                    {
                        Type = "ActivityCreate",
                        Data = model,
                    });
                }



                return(RedirectToAction("Index"));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> EditProfile(UserPhotoUpdateFormViewModel model)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            var userId = _userRepository.GetIdByIdentity(user.Id);

            // Placeholder permissions check
            if (model.IdUser != userId)
            {
                return(Unauthorized());
            }

            // Sanity checks
            var validUser = _userRepository.Get(model.IdUser);

            if (!ModelState.IsValid || validUser?.Id == null || validUser?.Id != userId)
            {
                return(RedirectToAction("Index"));
                //return BadRequest();
            }



            // Informazioni foto
            var fileExtension = Path.GetExtension(model.Image.FileName);
            // Sistema il content type
            var contentType = "";

            new FileExtensionContentTypeProvider().TryGetContentType(model.Image.FileName, out contentType);

            // Converti stream in base64
            var base64 = "";

            using (var stream = model.Image.OpenReadStream())
            {
                var outStream = new MemoryStream();
                stream.CopyTo(outStream);
                var bytes = outStream.ToArray();
                base64 = Convert.ToBase64String(bytes);
            }

            // Invia risultati

            if (Program.UseEventHub)
            {
                await _eventHub.SendMessage(new QueueElement <UserPhotoUpdateViewModel>
                {
                    Type = "UserPhotoUpdate",
                    Data = new UserPhotoUpdateViewModel()
                    {
                        ContentType = contentType,
                        IdUser      = model.IdUser,
                        Image       = base64,
                    },
                });
            }
            else
            {
                var queue = new ServiceBusManager(_configuration["ServiceBusConnectionString"], _configuration["ServiceBusQueueName"]);
                await queue.SendMessage(new QueueElement <UserPhotoUpdateViewModel>
                {
                    Type = "UserPhotoUpdate",
                    Data = new UserPhotoUpdateViewModel()
                    {
                        ContentType = contentType,
                        IdUser      = model.IdUser,
                        Image       = base64,
                    },
                });
            }



            return(NoContent());
            // await _client.PostRequest<object>($"User/{model.IdUser}/UpdatePhoto", );

            //return RedirectToAction("Index");
        }
Esempio n. 8
0
        public static async Task HandleMessage <T>(QueueElement <T> message)
        {
            Console.WriteLine("Message received through HandleMessage()");
            var imageUrl = "";
            //var message = await serviceBus.GetMessage<QueueElement<object>>(m);
            int redirectId = 0;

            switch (message.Type)
            {
            case "TelemetrySend":     // EVENT HUB EVENT
                imageUrl = "";
                var telemetrySendModel = ForceCast <TelemetrySendViewModel>(message.Data);
                if (telemetrySendModel.Image.Length > 0)
                {
                    var imageData = Convert.FromBase64String(FixBase64(telemetrySendModel.Image));
                    imageUrl = blobStorage.UploadByteBlob(
                        blobSend,
                        $"{telemetrySendModel.IdActivity}/{telemetrySendModel.IdUser}/{DateTime.Now}_{new Random().Next(0, 20)}.png",
                        "image/png",
                        imageData
                        ).GetAwaiter().GetResult();
                }

                var telemetryModel = new Telemetry()
                {
                    Longitude  = telemetrySendModel.Longitude,
                    Latitude   = telemetrySendModel.Latitude,
                    IdActivity = telemetrySendModel.IdActivity,
                    IdUser     = telemetrySendModel.IdUser,
                    ImageUrl   = imageUrl,
                    Instant    = telemetrySendModel.Instant
                };
                telemetryRepository.Insert(telemetryModel);
                //--
                telemetryModel.IdActivity = telemetrySendModel.IdActivityOrganizer;
                await eventHubSendToOrganizer.SendMessage(new QueueElement <Telemetry>() {
                    Type = "TelemetrySend",
                    Data = telemetryModel
                });

                //--
                break;

            // The organizer events cannot be closed by the client
            case "ActivityClose":
                var closeData = ForceCast <ActivityIdViewModel>(message.Data);
                if (closeData.FromOrganizer)
                {
                    closeData.Id = activityRepository.GetIdFromOrganizerId(closeData.Id);
                }

                activityRepository.Close(closeData.Id);
                redirectId = closeData.IdUser;
                break;

            case "ActivityStart":
                var startData = ForceCast <ActivityIdViewModel>(message.Data);    // GetValue<int>(message.Data);
                if (startData.FromOrganizer)
                {
                    startData.Id = activityRepository.GetIdFromOrganizerId(startData.Id);
                }
                activityRepository.Start(startData.Id);
                redirectId = startData.IdUser;
                break;

            case "ActivityCreate":
                var activityCreateModel = ForceCast <ActivityCreateViewModel>(message.Data);
                activityRepository.Insert(new Activity()
                {
                    //    Id = 0,
                    CreationDate = DateTime.Now,
                    EndDate      = null,
                    Location     = activityCreateModel.Location,
                    Name         = activityCreateModel.Name,
                    RaceUrl      = "",
                    IdUser       = activityCreateModel.IdUser,
                    Status       = 0,
                    Type         = activityCreateModel.Type,
                });


                redirectId = activityCreateModel.IdUser;
                break;

            case "ActivityJoin":
                var activityJoinModel = ForceCast <ActivityIdViewModel>(message.Data);
                activityRepository.AddRunner(
                    activityJoinModel.Id,
                    activityJoinModel.IdUser
                    );
                //--
                var activityStat = activityRepository.Get(activityJoinModel.Id);
                if (activityStat.Type == 2)
                {
                    await eventHubSendToOrganizer.SendMessage(message);
                }
                //--
                redirectId = activityJoinModel.IdUser;
                break;

            case "UserPhotoUpdate":
                imageUrl = "";
                var userPhotoUpdateModel = ForceCast <UserPhotoUpdateViewModel>(message.Data);
                if (userPhotoUpdateModel.Image.Length > 0)
                {
                    var imageData = Convert.FromBase64String(FixBase64(userPhotoUpdateModel.Image));
                    imageUrl = blobStorage.UploadByteBlob(
                        userpicSend,
                        $"{userPhotoUpdateModel.IdUser}/{DateTime.Now}_{new Random().Next(0, 20)}.png",
                        "image/png",
                        imageData
                        ).GetAwaiter().GetResult();
                }

                userRepository.UpdateImage(userPhotoUpdateModel.IdUser, imageUrl);

                redirectId = userPhotoUpdateModel.IdUser;

                break;
            }
            if (redirectId > 0)
            {
                // Alert for redirect

                //if (UseEventHub)
                //{

                /*
                 * await eventHubSend.SendMessage(new QueueElement<SignalRRedirectViewModel>
                 * {
                 *  Type = "SignalRRedirectResponse",
                 *  Data = new SignalRRedirectViewModel()
                 *  {
                 *      Username = userRepository.Get(redirectId).Name
                 *  },
                 * });*/
                //}
                // else
                // {
                await responseClient.SendMessage(new QueueElement <SignalRRedirectViewModel>
                {
                    Type = "SignalRRedirectResponse",
                    Data = new SignalRRedirectViewModel()
                    {
                        Username = userRepository.Get(redirectId).Name
                    },
                });

                //}
            }
        }