예제 #1
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        CallQueueItem cqi = null;
                        try
                        {
                            cqi = ObjectSerialization.Deserialize <CallQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.DeadLetter();
                            await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                        }

                        if (cqi != null && cqi.Call != null && cqi.Call.HasAnyDispatches())
                        {
                            try
                            {
                                await ProcessCallQueueItem(cqi);
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                //message.Abandon();
                                await _client.DeadLetterAsync(message.SystemProperties.LockToken);

                                success = false;
                                result  = ex.ToString();
                            }
                        }
                    }
                    else
                    {
                        success = false;
                        result  = "Message body is null or empty";
                    }

                    try
                    {
                        //message.Complete();
                        await _client.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();

                    Logging.LogException(ex);
                    //message.Abandon();
                    await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
예제 #2
0
        public override void Listen(Route route, Action <object>[] routingactions, string channelpath)
        {
            var queueclient = new QueueClient(route.ToConnectionString, route.ToPath);

            var options = CreateOptions(channelpath);

            Action <Message> @action = message =>
            {
                foreach (var routingaction in routingactions)
                {
                    var clone = message.Clone();

                    routingaction(clone);
                }
            };

            queueclient.RegisterMessageHandler(async(message, token) =>
            {
                await OnMessageAsync(channelpath, message.MessageId, () => @action(message), () => queueclient.CompleteAsync(message.SystemProperties.LockToken));
            }, options);

            route.ShutdownAction = () => { queueclient.CloseAsync().GetAwaiter().GetResult(); };
        }
        public async Task ReceiveMessagesAsync(Message message, CancellationToken token)
        {
            Console.WriteLine($"Received message: {Encoding.UTF8.GetString(message.Body)}");

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
예제 #4
0
 private async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
     await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
 }
예제 #5
0
        private async Task OnMessageReveived(Message message, CancellationToken token)
        {
            Console.WriteLine($"Message {message.MessageId} received: {Encoding.UTF8.GetString(message.Body)}");

            await _QueueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
예제 #6
0
 public Task CompleteAsync(string id)
 {
     Interlocked.Increment(ref _completedCount);
     return(_queueClient.CompleteAsync(new Guid(id)));
 }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            string serviceBusConnectionString = new ServiceBusConnectionStringBuilder(servicebusEndpoint, String.Empty, sharedAccessKeyName, sharedAccessKey).ToString();

            queueClient       = new QueueClient(serviceBusConnectionString, queueName, ReceiveMode.PeekLock);
            cameraQueueClient = new QueueClient(serviceBusConnectionString, cameraQueueName, ReceiveMode.PeekLock);

            // Handle messages received from the Service Bus patrol car queue
            queueClient.RegisterMessageHandler(
                async(message, token) =>
            {
                // Deserialize the data as patrol car data
                string data = Encoding.UTF8.GetString(message.Body);

                // Remove any leading preamble, before the start of the JSON text
                int pos = data.LastIndexOf('{');
                data    = data.Substring(pos);
                // Remove any extraneous content after the closing } of the JSON text
                pos = data.LastIndexOf('}');
                if (pos != 0)
                {
                    data = data.Substring(0, pos + 1);
                }

                PatrolCarData patrolCarData = JsonConvert.DeserializeObject <PatrolCarData>(data);

                // Plot the position of the patrol car on the map
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              () =>
                {
                    BasicGeoposition patrolCarPosition = new BasicGeoposition()
                    {
                        Latitude  = patrolCarData.LocationLatitude,
                        Longitude = patrolCarData.LocationLongitude
                    };

                    // If the patrol car already exists then just update its location
                    MapIcon car = (MapIcon)MapControl.MapElements.FirstOrDefault(m => String.Compare((m as MapIcon).Title, patrolCarData.CarID) == 0);
                    if (car != null)
                    {
                        car.Location = new Geopoint(patrolCarPosition);
                    }
                    // Otherwise create a new icon and add it to the map
                    else
                    {
                        car          = new MapIcon();
                        car.Location = new Geopoint(patrolCarPosition);
                        car.NormalizedAnchorPoint = new Point(0.5, 1.0);
                        car.Title  = patrolCarData.CarID;
                        car.ZIndex = 0;
                        car.Image  = patrolCarImage;
                        MapControl.MapElements.Add(car);
                    }
                });
                await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }, new MessageHandlerOptions(async(args) =>
            {
                // Error handling - discard the message
            })
                );

            // Handle messages received from the Service Bus speed camera queue
            cameraQueueClient.RegisterMessageHandler(
                async(message, token) =>
            {
                // Deserialize the data as speed camera data
                string data = Encoding.UTF8.GetString(message.Body);

                // Remove any leading preamble, before the start of the JSON text
                int pos = data.LastIndexOf('{');
                data    = data.Substring(pos);
                // Remove any extraneous content after the closing } of the JSON text
                pos = data.LastIndexOf('}');
                if (pos != 0)
                {
                    data = data.Substring(0, pos + 1);
                }

                SpeedCameraData speedCameraData = JsonConvert.DeserializeObject <SpeedCameraData>(data);

                // Plot the position of the speed camera on the map
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              () =>
                {
                    BasicGeoposition speedCameraPosition = new BasicGeoposition()
                    {
                        Latitude  = speedCameraData.LocationLatitude,
                        Longitude = speedCameraData.LocationLongitude
                    };

                    // If the speed camera already exists then just update its observation
                    MapIcon speedCamera = (MapIcon)MapControl.MapElements.FirstOrDefault(m => String.Compare((m as MapIcon).Title, speedCameraData.CameraID) == 0);
                    if (speedCamera != null)
                    {
                        speedCamera.Title = $"Speed: {speedCameraData.Speed.ToString()} mph";
                    }
                    // Otherwise create a new icon and add it to the map
                    else
                    {
                        speedCamera          = new MapIcon();
                        speedCamera.Location = new Geopoint(speedCameraPosition);
                        speedCamera.NormalizedAnchorPoint = new Point(0.5, 1.0);
                        speedCamera.Title  = $"Speed: {speedCameraData.Speed.ToString()} mph";
                        speedCamera.ZIndex = 0;
                        speedCamera.Image  = speedCameraImage;
                        MapControl.MapElements.Add(speedCamera);
                    }
                });
                await cameraQueueClient.CompleteAsync(message.SystemProperties.LockToken);
            }, new MessageHandlerOptions(async(args) =>
            {
                // Error handling - discard the message
            })
                );
        }
예제 #8
0
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var body = Encoding.UTF8.GetString(message.Body);

            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{body}");

            var analyzeMessage = JsonConvert.DeserializeObject <AnalyzeMessage>(body);
            await core.UpdateStatus(analyzeMessage.AnalyzeId);

            var dicomFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            await core.DownloadToFolder(analyzeMessage.RecordId, dicomFolder);

            var picsFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(picsFolder);
            var picturePathesTasks = Directory
                                     .EnumerateFiles(dicomFolder)
                                     .Select <string, Task <(Stream picStream, double deep)> >(async(p, i) =>
            {
                var bitMap = await DicomRenderer.Render(File.OpenRead(p), out var localMeta);
                var deep   = double.TryParse(localMeta.FirstOrDefault(m => m.Description?.Contains("Slice Location") == true).Value, out var calcDeep)
                        ? calcDeep : 0;
                return(bitMap, deep);
            })
                                     .ToList();
            await Task.WhenAll(picturePathesTasks);

            var results = picturePathesTasks
                          .Select(t => t.Result)
                          .OrderBy(t => t.deep)
                          .Select(async(t, i) =>
            {
                var picPath = Path.Combine(picsFolder, $"{i}.png");
                using (var picStream = File.OpenWrite(picPath))
                    await t.picStream.CopyToAsync(picStream);
                return(picPath);
            })
                          .ToList();
            await Task.WhenAll(results);

            var targetDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(targetDir);
            var meta = new InputMeta
            {
                Photos = results.Select(p => new PhotoMeta {
                    Path = p.Result
                }).ToList(),
                TargetDir = targetDir
            };
            var metaFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".json");

            File.WriteAllText(metaFilePath, JsonConvert.SerializeObject(meta));
            var proccess = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName  = cppExePath,
                    Arguments = metaFilePath
                }
            };

            proccess.Start();
            proccess.WaitForExit();
            Console.WriteLine(string.Join(',', Directory.GetFiles(targetDir)));


            await core.SendAnswer(analyzeMessage.AnalyzeId, Directory.EnumerateFiles(targetDir).Select(File.OpenRead));

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
예제 #9
0
 private static async Task MessageHandler(Message arg1, CancellationToken arg2)
 {
     Console.WriteLine(arg1);
     await queueClient.CompleteAsync(arg1.SystemProperties.LockToken);
 }
예제 #10
0
        private async Task ProcessMessageInternalAsync <TMessage>(Message message, Func <TMessage, IServiceBusClient, CancellationToken, Task <QueueItemProcessResult> > receiver, CancellationToken token)
        {
            Activity activity = null;

            // if Activity.Current is not empty, it means that Service Bus library restored it.
            // It happens when App Insights DependencyTrackingTelemetryModule is configured with 'Microsoft.Azure.ServiceBus'
            // <IncludeDiagnosticSourceActivities>
            //   <Add>Microsoft.Azure.ServiceBus</Add>
            // </IncludeDiagnosticSourceActivities>
            if (Activity.Current == null)
            {
                activity = new Activity("Process");
                if (message.CorrelationId != null)
                {
                    activity.SetParentId(message.CorrelationId);
                }
            }

            if (activity != null)
            {
                activity.Start();
            }

            string messageString = null;

            try
            {
                messageString = Encoding.UTF8.GetString(message.Body);
                TMessage tMessage             = JsonConvert.DeserializeObject <TMessage>(messageString);
                QueueItemProcessResult result = await receiver(tMessage, this, token);

                switch (result.ResultAction)
                {
                case QueueItemProcessResult.Action.Complete:
                    await queueClient.CompleteAsync(message.SystemProperties.LockToken);

                    break;

                case QueueItemProcessResult.Action.Retry:
                    if (result.RetryDelay != default(TimeSpan))
                    {
                        message.ScheduledEnqueueTimeUtc = DateTime.UtcNow.Add(result.RetryDelay);
                    }

                    await queueClient.AbandonAsync(message.SystemProperties.LockToken);

                    break;
                }

                logger.LogDebug(
                    "Message processing completed: queueName={queueName}, type={type}, messageId={messageId}, action={action}, message=\n{message}",
                    QueueName,
                    typeof(TMessage).Name,
                    message.MessageId,
                    result.ResultAction,
                    messageString);
            }
            catch (Exception ex)
            {
                logger.LogError(
                    ex,
                    "Message processing failed: queueName={queueName}, type={type}, id={id}, message=\n{message}",
                    QueueName,
                    typeof(TMessage).Name,
                    message.MessageId,
                    messageString);
            }
            finally
            {
                activity?.Stop();
            }
        }
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string messageAsString = "";
            Task   completionTask;

            try {
                if (!(logger is null))
                {
                    logger.LogInformation("===================== Processing Message =====================");
                }
                completionTask  = queueClient.CompleteAsync(message.SystemProperties.LockToken);
                messageAsString = Encoding.Default.GetString(message.Body);
                if (!(logger is null))
                {
                    logger.LogInformation(messageAsString);
                    logger.LogInformation("==============================================================");
                }
            } catch (Exception ex) {
                if (!(logger is null))
                {
                    logger.LogError("ERROR while receiving message from queue: " + ex.Message + ex.StackTrace);
                }
                throw new ApplicationException(ex.Message);
            }

            try {
                ProcessMessage(message, messageAsString);
            } catch (Exception ex) {
                if (!(logger is null))
                {
                    logger.LogError("ERROR processing message from queue: " + ex.Message + ex.StackTrace);
                }
                throw new ApplicationException(ex.Message);
            }

            try {
                IList <Task> tasksList = new List <Task>();
                await sLock.WaitAsync();

                tasksList.Add(completionTask);
                if (tasksList.Count > 0)
                {
                    await Task.WhenAll(tasksList).ContinueWith((t) => sLock.Release());
                }
            } catch (Exception ex) {
                sLock.Release();
                if (!(logger is null))
                {
                    logger.LogError("ERROR completing message on queue: " + ex.Message + ex.StackTrace);
                }
                throw new ApplicationException(ex.Message);
            }
            // --- Send message
            //await TopicSender.MainAsync(jsonResult); //.GetAwaiter().GetResult();

            // --- Complete the message
            //await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            // Complete the message so that it is not received again.
            // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
            //await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
예제 #12
0
        /// <summary>
        /// CallBack method which will be invoked for each message
        /// </summary>
        /// <param name="message">The messageEvent, or message</param>
        /// <param name="token">A cancellation token instructing the method to stop</param>
        private async Task ProcessMessage(Message message, CancellationToken token)
        {
            // This code block is the callback that is invoked for each published event.
            // It is invoked for each message placed in the subscription.
            // Start by getting event type which is included as a metadata property for the event
            if (message.UserProperties.TryGetValue("Command", out var eventTypeOut))
            {
                // Get eventType by name
                string @command = eventTypeOut?.ToString() ?? throw new ArgumentNullException($"Command is null in MessagePump in ServiceBusProvider");

                // Set message type for internal logging
                _currentCommandType = @command;

                // Extract Correlation Token for request -- used for internal logging
                message.UserProperties.TryGetValue("_correlationToken", out var correlationToken);

                // Set correlationToken for internal logging
                _correlationToken = correlationToken != null?correlationToken.ToString() : "Correlation Token Unavailable";

                // Deserialize EventMessage
                var commandType = _commands[@command];

                if (commandType == null)
                {
                    var errorMessage =
                        $"Missing Command for {@command} in ProcessMessage for Service {_boundServiceName} for CorrelationToken {_correlationToken}";
                    _logger.LogError(errorMessage);

                    throw new MissingMemberException(errorMessage);
                }

                // Deserailize message here so that the eventHandler has no dependency on Azure Service Bus
                var body           = Encoding.UTF8.GetString(message.Body);
                var commandMessage = JsonConvert.DeserializeObject(body, commandType) as Command;

                // Obtain reference to EventHandler
                var commandHandler = _commandHandlers[@command];

                if (commandHandler == null)
                {
                    var errorMessage =
                        $"Missing EventHandler for {@command} in ProcessMessage for Service {_boundServiceName} for CorrelationToken {_correlationToken}";
                    _logger.LogError(errorMessage);

                    throw new MissingMemberException(errorMessage);
                }

                _logger.LogInformation(
                    $"Processing event {@command} for Service {_boundServiceName} for CorrelationToken {_correlationToken}");

                // Invoke EventHandler
                await commandHandler.HandleAsync(commandMessage);

                _logger.LogInformation(
                    $"Processed event {@command} for Service {_boundServiceName} for CorrelationToken {_correlationToken}");

                ////TODO: Ensure that event type and event message is valid for this subscription

                ////var commandHandler = JsonConvert.DeserializeObject(body, commandHandlerType) as ICommandHandler;

                //if (commandHandler == null)
                //{
                //    var errorMessage =
                //        $"Missing EventHandler for {@command} in ProcessMessage for Service {_boundServiceName} for CorrelationToken {_correlationToken}";
                //    _logger.LogError(errorMessage);

                //    throw new MissingMemberException(errorMessage);
                //}

                //_logger.LogInformation(
                //    $"Processing event {@command} for Service {_boundServiceName} for CorrelationToken {_correlationToken}");

                //// Invoke EventHandler
                //await commandHandler.HandleAsync(commandMessage);

                //_logger.LogInformation(
                //    $"Processed event {@command} for Service {_boundServiceName} for CorrelationToken {_correlationToken}");

                // Complete the message so that it is not received again.
                await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }
        }
예제 #13
0
        static async Task Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile(
                "appsettings.json",
                optional: true,
                reloadOnChange: true);
            var configuration = builder.Build();

            string sqlConnectionString = configuration["ConnectionStrings:SqlDb"];
            IActivityRepository  activityRepository  = new ActivityRepository(sqlConnectionString);
            IRunnerRepository    runnerRepository    = new RunnerRepository(sqlConnectionString);
            ITelemetryRepository telemetryRepository = new TelemetryRepository(sqlConnectionString);

            string       serviceBusConnectionString = configuration["ConnectionStrings:ServiceBus"];
            string       queueName             = configuration["ServiceBusQueueName"];
            IQueueClient queueClient           = new QueueClient(serviceBusConnectionString, queueName);
            var          messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            queueClient.RegisterMessageHandler(
                async(message, cancellationToken) =>
            {
                var bytes         = message.Body;
                var json          = Encoding.UTF8.GetString(bytes);
                var content       = JsonConvert.DeserializeObject <JObject>(json);
                var requestType   = content.Value <string>("RequestType");
                Boolean completed = false;

                switch (requestType)
                {
                case "NewTrainingRequest":
                    {
                        var runnerUsername = content.Value <string>("RunnerUsername");
                        Runner runner      = runnerRepository.GetByUsername(runnerUsername);
                        var activity       = new Activity()
                        {
                            Name         = content.Value <string>("Name"),
                            IdRunner     = runner.Id,
                            CreationDate = content.Value <DateTime>("Date"),
                            Location     = content.Value <string>("Location"),
                            UriMatch     = content.Value <string>("UriMatch"),
                            Type         = 1,
                            State        = 0
                        };
                        activityRepository.Insert(activity);
                        completed = true;
                        break;
                    }

                case "StartTrainingRequest":
                    {
                        var idActivity = content.Value <int>("IdActivity");
                        var activity   = activityRepository.Get(idActivity);
                        activity.State = 1;
                        activityRepository.Update(activity);
                        completed = true;
                        break;
                    }

                /*case "ListTrainingRequest":
                 *  {
                 *      var runnerUsername = content.Value<string>("RunnerUsername");
                 *      var response = new ListTrainingResponse()
                 *      {
                 *          Activities = activityRepository.GetByTypeAndUsername(1, runnerUsername),
                 *          RunnerUsername = runnerUsername
                 *      };
                 *      var notificationJson = JsonConvert.SerializeObject(response);
                 *      var notificationBytes = Encoding.UTF8.GetBytes(notificationJson);
                 *      var topicMessage = new Message(notificationBytes);
                 *
                 *      string serviceBusTopicConnectionString = configuration["ConnectionStrings:ServiceBusTopic"];
                 *      string topicName = configuration["ServiceBusTopicName"];
                 *      var topicClient = new TopicClient(serviceBusTopicConnectionString, topicName);
                 *      await topicClient.SendAsync(topicMessage);
                 *      await topicClient.CloseAsync();
                 *      completed = true;
                 *      break;
                 *  }*/
                case "DeleteActivityRequest":
                    {
                        var idActivity = content.Value <int>("IdActivity");
                        activityRepository.Delete(idActivity);
                        completed = true;
                        break;
                    }

                case "UpdateSelfieRequest":
                    {
                        var uriPic     = content.Value <string>("UriPic");
                        var idActivity = content.Value <int>("IdActivity");
                        var instant    = content.Value <DateTime>("Instant");
                        telemetryRepository.Update(uriPic, idActivity, instant);
                        completed = true;
                        break;
                    }

                default:
                    await queueClient.AbandonAsync(message.SystemProperties.LockToken);
                    break;
                }
                if (completed)
                {
                    await queueClient.CompleteAsync(message.SystemProperties.LockToken);
                }
                else
                {
                    await queueClient.AbandonAsync(message.SystemProperties.LockToken);
                }
            }, messageHandlerOptions);
            //insert an option to don't make the worker always active with no messages in the queue
            await Task.Delay(Timeout.Infinite);

            //await queueClient.CloseAsync();
        }
예제 #14
0
 public async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     // process message here
     await queueClient.CompleteAsync(message.SystemProperties.LockToken);
 }
예제 #15
0
        /// <summary>
        /// The actual method to process the received message from complex service.
        /// Receives and deserializes the message from complex service.  Based on what they send
        /// us this method will determine what CRUD operations to do on the Room service.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task ProcessRoomDUCAsync(Message message, CancellationToken token)
        {
            // Dispose of this scope after done using repository service
            //   Necessary due to singleton service (bus service) consuming a scoped service (repo)
            using var scope = _services.CreateScope();
            var repo = scope.ServiceProvider.GetRequiredService <IRepository>();

            try
            {
                _logger.LogInformation("Attempting to deserialize complex message from service bus consumer: {message}", message.Body);

                var receivedMessage = JsonSerializer.Deserialize <ComplexMessage>(message.Body);

                _logger.LogInformation("Showing RoomNumber: {message}", receivedMessage.RoomNumber);

                //Did not put deleting complex in switch statement because of the constraints we ran into,
                //so we put it in an if-else statement instead
                if (receivedMessage.QueOperator == 3)
                {
                    _logger.LogInformation("Deserialized with this operator: {message}", receivedMessage.QueOperator);

                    _logger.LogInformation("Attempting to DELETE COMPLEX!!! {0}", receivedMessage.ComplexId);

                    IEnumerable <Guid> listOfRooms = await repo.DeleteComplexRoomAsync(receivedMessage.ComplexId);

                    _logger.LogInformation("Oh my, you DELETED a COMPLEX!: {message}", receivedMessage.ComplexId);

                    _logger.LogInformation("Sending LIST of deleted room Ids!!! {0}", listOfRooms);

                    foreach (var r in listOfRooms)
                    {
                        await _serviceSender.SendDeleteMessage(r);
                    }

                    _logger.LogInformation("Sent the list of rooms back to complex service!", listOfRooms);
                }
                //If not deleting complex then do the other operations with rooms
                else
                {
                    var myRoom = new Room()
                    {
                        RoomId            = receivedMessage.RoomId,
                        RoomNumber        = receivedMessage.RoomNumber,
                        ComplexId         = receivedMessage.ComplexId,
                        NumberOfBeds      = receivedMessage.NumberOfBeds,
                        RoomType          = receivedMessage.RoomType,
                        NumberOfOccupants = 0,
                    };

                    myRoom.SetLease(receivedMessage.LeaseStart, receivedMessage.LeaseEnd);

                    _logger.LogInformation("Deserialized your room!: {message}", myRoom.RoomNumber);


                    _logger.LogInformation("Deserialized with this operator: {message}", receivedMessage.QueOperator);
                    // Persist our new data into the repository but not if Deserialization throws an exception
                    //Operation type is the CUD that you want to implement like create, update, or delete
                    // Case 0 = create, Case 2 = update, Case 1 = delete
                    // We will listen for what the complex service will send us and determine
                    // what CRUD operation to do based on the OperationType
                    switch ((OperationType)receivedMessage.QueOperator)
                    {
                    case OperationType.Create:
                        _logger.LogInformation("Attempting to CREATE a room!!!", myRoom.RoomNumber);
                        await repo.CreateRoomAsync(myRoom);

                        _logger.LogInformation("Created a room!!!: {message}", myRoom.RoomNumber);
                        break;

                    case OperationType.Update:
                        _logger.LogInformation("Attempting to UPDATE a room!!!", myRoom.RoomNumber);
                        await repo.UpdateRoomAsync(myRoom);

                        _logger.LogInformation("Updated a room!!!: {message}", myRoom);
                        break;

                    case OperationType.Delete:
                        _logger.LogInformation("Attempting to DELETE a room!!!", myRoom.RoomNumber);
                        await repo.DeleteRoomAsync(myRoom.RoomId);

                        _logger.LogInformation("DELETED a room!!!: {message}", myRoom);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Message did not convert properly: {message}", ex);
            }
            finally
            {
                // Alert bus service that message was received
                await _roomDUCQueue.CompleteAsync(message.SystemProperties.LockToken);
            }
        }
예제 #16
0
        private const string FromId         = "B9CP104JZ:T9CNR3GRK"; // cachebot's id
//        public static string toName;

        public static void RegisterQueue()
        {
            var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            if (connectionString == null)
            {
                throw new Exception("Connection String not there");
            }

            var builder = new ServiceBusConnectionStringBuilder(connectionString)
            {
                EntityPath = "Responses"
            };
            var client = new QueueClient(builder);

            client.RegisterMessageHandler(async(queueMessage, token) =>
            {
                //                    if (toId == null)
                //                    {
                //                        throw new Exception("Cannot send message if I haven't received one. We should probably fix this.");
                //                    }

                // Use the data stored previously to create the required objects.
//                    var userAccount = new ChannelAccount(toId, toName);
                var botAccount = new ChannelAccount(FromId, FromName);
                var connector  = new ConnectorClient(new Uri(ServiceUrl));

                var body = Encoding.UTF8.GetString(queueMessage.Body);

                var responseMessage = JsonConvert.DeserializeObject <ResponseMessage>(body);



                // Create a new message.
                IMessageActivity message = Activity.CreateMessageActivity();
//                    if (!string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(channelId))
//                    {
                // If conversation ID and channel ID was stored previously, use it.
                message.ChannelId = ChannelId;
//                    }
//                    else
//                    {
//                        // Conversation ID was not stored previously, so create a conversation.
//                        // Note: If the user has an existing conversation in a channel, this will likely create a new conversation window.
//                        conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, null, cancellationToken: token)).Id;
//                    }

                // Set the address-related properties in the message and send the message.
                message.From = botAccount;
//                    message.Recipient = userAccount;
                message.Conversation = new ConversationAccount(id: ConversationId);

                if (responseMessage.Status == Status.fail)
                {
                    message.Text = responseMessage.Error;
                }

                if (!String.IsNullOrEmpty(responseMessage.Data))
                {
                    AttachmentData attachmentData = new AttachmentData();
                    attachmentData.Name           = "Redis-cache-item.txt";
                    attachmentData.OriginalBase64 = Encoding.UTF8.GetBytes(responseMessage.Data);
                    attachmentData.Type           = "text/plain";
                    var response = await connector.Conversations.UploadAttachmentAsync(ConversationId, attachmentData, token);

                    var uri = new Attachments(connector).GetAttachmentUri(response.Id);

                    var attachment = new Attachment
                    {
                        Name        = "Redis-cache-item.txt",
                        ContentType = "text/plain",
                        ContentUrl  = uri
                    };
                    message.Attachments = new List <Attachment> {
                        attachment
                    };
                }
                else
                {
                    if (responseMessage.Status == Status.success)
                    {
                        message.Text = "The cache was successfully cleared!";
                    }
                }

                message.Locale = "en-us";
                await connector.Conversations.SendToConversationAsync((Activity)message, token);

                await client.CompleteAsync(queueMessage.SystemProperties.LockToken);
            }, new MessageHandlerOptions(LogMessageHandlerException)
            {
                AutoComplete = false, MaxConcurrentCalls = 1
            });
        }
예제 #17
0
 public Task CompleteAsync(string lockToken)
 {
     return(queueClient.CompleteAsync(lockToken));
 }
예제 #18
0
 private static async Task MessageHandler(Message message, CancellationToken cancellationToken)
 {
     ProcessMessage(message);
     await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
 }
예제 #19
0
 static async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body: {message.Body}");
     await queueClient.CompleteAsync(message.SystemProperties.LockToken);
 }
예제 #20
0
 public async Task CompleteAsync(string lockToken)
 {
     await _client.CompleteAsync(lockToken).ConfigureAwait(false);
 }
예제 #21
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                MessageQueueItem mqi = null;

                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        try
                        {
                            mqi = ObjectSerialization.Deserialize <MessageQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessMessageQueueItem(mqi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();

                    if (mqi != null)
                    {
                        ex.Data.Add("DepartmentId", mqi.DepartmentId);

                        if (mqi.Message != null)
                        {
                            ex.Data.Add("MessageId", mqi.Message.MessageId);
                            ex.Data.Add("SendingUserId", mqi.Message.SendingUserId);
                            ex.Data.Add("RecievingUserId", mqi.Message.ReceivingUserId);
                        }
                    }

                    ex.Data.Add("MQI", JsonConvert.SerializeObject(mqi));

                    Logging.LogException(ex);
                    await _client.AbandonAsync(message.SystemProperties.LockToken);

                    //message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
예제 #22
0
        /// <summary>
        /// Process incoming Service Bus messages, and create a new conversation with the user.
        /// This will call <see cref="MessageCallback(T, UserInfoEntity)"/> when teh new conversation was successfuly created.
        /// </summary>
        /// <param name="message">Service Bus message object.</param>
        /// <param name="cancellationToken" >(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>Task.</returns>
        private async Task ProcessMessagesAsync(Message message, CancellationToken cancellationToken)
        {
            var json          = Encoding.UTF8.GetString(message.Body);
            var parsedMessage = JsonConvert.DeserializeObject <T>(json);

            var logProperties = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);

            logProperties.Add("ProactiveMessageType", GetType().Name);
            logProperties.Add("ServiceBusSequenceNumber", message.SystemProperties.SequenceNumber.ToString());

            var userInfos = await _table.RetrieveUserInfoAsync(parsedMessage.UserId);

            if (userInfos == null || userInfos.Count == 0)
            {
                await _queueClient.CompleteAsync(message.SystemProperties.LockToken);

                _telemetryClient.TrackEvent(
                    "Failed to send bot proactive message: User was not found in the bot's database.",
                    logProperties);
            }

            if (!_env.IsProduction())
            {
                userInfos = userInfos.Where(i => i.ChannelId == ChannelIds.Emulator).ToList();
            }

            foreach (var userInfo in userInfos)
            {
                try
                {
                    await _botFrameworkAdapter.CreateConversationAsync(
                        userInfo.ChannelId,
                        userInfo.ServiceUrl,
                        new MicrosoftAppCredentials(_endpoint.AppId, _endpoint.AppPassword),
                        new ConversationParameters(bot : userInfo.Bot, members : new List <ChannelAccount> {
                        userInfo.User
                    }, channelData : userInfo.ChannelData),
                        MessageCallback(parsedMessage, userInfo),
                        cancellationToken);

                    // Same with an existing conversation
                    // var conversation = new ConversationReference(
                    //   null,
                    //   userInfo.User,
                    //   userInfo.Bot,
                    //   new ConversationAccount(null, null, userInfo.CurrentConversation.Conversation.Id, null, null, null),
                    //   userInfo.ChannelId,
                    //   userInfo.ServiceUrl);
                    // await _botFrameworkAdapter.ContinueConversationAsync(_endpoint.AppId, conversation, MessageCallback(), cancellationToken);
                }
                catch (ErrorResponseException e)
                {
                    _telemetryClient.TrackException(
                        e,
                        new Dictionary <string, string>
                    {
                        { "Error message", e.Message },
                        { "Response body", e.Response.Content },
                        { "Request body", e.Request.Content },
                        { "Request uri", $"{e.Request.Method.ToString()} {e.Request.RequestUri.AbsoluteUri}" },
                        { "Request headers", e.Request.Headers.ToJson() },
                    });
                }
                catch (Exception e)
                {
                    _telemetryClient.TrackException(e);
                }
            }

            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls
            // to avoid unnecessary exceptions.
            //
            // Complete the message so that it is not received again.
            // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
            await _queueClient.CompleteAsync(message.SystemProperties.LockToken);

            _telemetryClient.TrackEvent(
                "Proactive message sent by bot.",
                logProperties,
                new Dictionary <string, double>
            {
                { "Proactive message", 1 },
                { $"Proactive{GetType().Name}", 1 },
            });
        }
예제 #23
0
 static async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     Console.WriteLine(Encoding.UTF8.GetString(message.Body));
     await inQ.CompleteAsync(message.SystemProperties.LockToken);
 }