Ejemplo n.º 1
0
        public void SendTwiceAndReceiveMultipleMessage()
        {
            Helper.CreateAndOpenQueue(queue =>
            {
                var transportMessage = new ServiceBusMessage(new object[]
                {
                    new Message1("MessageName1", 2011),
                    new Message2("MessageName2", 2012),
                    new Message1("MessageName3", 2013),
                    new Message2("MessageName4", 2014),
                    new Message2("MessageName5", 2015),
                });

                queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));
                queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));

                Helper.AssertTransportMessage(transportMessage,
                    queue.Transport.TranslateToServiceBusMessage(queue.Receive(TimeSpan.FromSeconds(5))));

                Helper.AssertTransportMessage(transportMessage,
                    queue.Transport.TranslateToServiceBusMessage(queue.Receive(TimeSpan.FromSeconds(5))));
            },
            new ITransport[]
            {
                new MsmqTransport(),
                new InMemoryTransport()
            });
        }
        public void ObserveTest()
        {
            Helper.CreateAndOpenQueue(queue =>
            {
                var messageCount = 0;
                var transportMessage = new ServiceBusMessage(new object[]
                {
                    new Message1("MessageName", 2011)
                });

                using(var observer = queue.Transport.CreateObserver(queue.Name))
                {
                    observer.MessageReceived += (message, ob) =>
                    {
                        messageCount++;
                        Helper.AssertTransportMessage(transportMessage,
                            queue.Transport.TranslateToServiceBusMessage(message));
                    };

                    observer.Start();
                    queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));
                    queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));
                    queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));

                    observer.Wait();
                }

                Assert.AreEqual(messageCount, 3);
            });
        }
            public ServiceBusMessage ReceiveMessage(int timeOut = 0)
            {
                ServiceBusMessage sbMessage = null;
                {
                    try
                    {
                        BrokeredMessage receivedMessage = this._QueueClient.Receive(new TimeSpan(0, 0, timeOut));
                        if (receivedMessage != null)
                        {
                            sbMessage = new ServiceBusMessage()
                            {
                                ID = receivedMessage.MessageId,
                                Message = receivedMessage.GetBody<string>()
                            };

                            receivedMessage.Complete();
                        }
                    }
                    catch (MessagingException)
                    {
                        //throw new Exception(e.Message);
                    }
                }
                return sbMessage;
            }
Ejemplo n.º 4
0
        public static void AssertTransportMessage(ServiceBusMessage sent, ServiceBusMessage received)
        {
            Assert.AreEqual(sent.Messages.Length, received.Messages.Length);

            for (int i = 0; i < sent.Messages.Length; i++)
            {
                var sentMessage = sent.Messages[i];
                var receivedMessage = received.Messages[i];

                Assert.AreEqual(sentMessage.GetType(), receivedMessage.GetType());
                ObjectComparer.AreObjectsEqual(sentMessage, receivedMessage);
            }
        }
            public void SendMessage(ServiceBusMessage sbMessage)
            {
                BrokeredMessage brokeredMessage = new BrokeredMessage(sbMessage.Message);
                brokeredMessage.MessageId = sbMessage.ID;

                try
                {
                    this._QueueClient.SendAsync(brokeredMessage);
                }
                catch (MessagingException e)
                {
                    throw new Exception(e.Message);
                }
            }
        public void TestIt()
        {
            Helper.CreateAndOpenQueue(queue =>
            {
                var transportMessage = new ServiceBusMessage(new object[]
                {
                    new Message1("MessageName", 2011)
                });

                queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));

                var queue2 = queue.Transport.OpenEndpoint(queue.Name);
                queue2.Send(queue.Transport.TranslateToTransportMessage(transportMessage));
            });
        }
Ejemplo n.º 7
0
        public TransportMessage TranslateToTransportMessage(ServiceBusMessage serviceBusMessage)
        {
            // do not send empty messages
            if (serviceBusMessage.Messages == null || serviceBusMessage.Messages.Length == 0)
                throw new ArgumentException("Transport message is null or empty.");

            Message message = new Message
            {
                Body = serviceBusMessage,
                Formatter = new MsmqMessageFormatter(),
                Label = serviceBusMessage.Messages.First().GetType().FullName
            };

            return new TransportMessage(message);
        }
Ejemplo n.º 8
0
        public void SendAndReceiveSingleMessage()
        {
            Helper.CreateAndOpenQueue(queue =>
            {
                var transportMessage = new ServiceBusMessage(new object[]
                {
                    new Message1("MessageName", 2011)
                });

                queue.Send(queue.Transport.TranslateToTransportMessage(transportMessage));

                Helper.AssertTransportMessage(transportMessage,
                    queue.Transport.TranslateToServiceBusMessage(queue.Receive(TimeSpan.FromSeconds(5))));
            },
            new ITransport[]
            {
                new MsmqTransport(),
                new InMemoryTransport()
            });
        }      
Ejemplo n.º 9
0
 public Task <ServiceBusMessage> UpdateAsync(ServiceBusMessage content)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets service bus action details.
        /// </summary>
        /// <param name="jobActionType">Job action type.</param>
        /// <param name="serviceBusMessage">Service bus message.</param>
        /// <returns>PSServiceBusJobActionDetails</returns>
        internal static PSServiceBusJobActionDetails GetServiceBusJobActionDetails(JobActionType jobActionType, ServiceBusMessage serviceBusMessage)
        {
            if (serviceBusMessage == null)
            {
                throw new ArgumentNullException(paramName: "serviceBusMessage");
            }

            var psServieBusJobActionDetails = new PSServiceBusJobActionDetails(jobActionType)
            {
                ServiceBusAuthentication = Converter.GetServiceBusActionAuthenticationDetails(serviceBusMessage.Authentication),
                ServiceBusMessage = serviceBusMessage.Message,
                ServiceBusNamespaceProperty = serviceBusMessage.NamespaceProperty,
                ServiceBusTransportType = serviceBusMessage.TransportType.ToString()
            };

            return psServieBusJobActionDetails;
        }
Ejemplo n.º 11
0
 private void SendResponseSchemaEvent(ServiceBusMessage result)
 {
     SendClientResponse(result, (action, content) => action.udsSchemaEvent(result.Content));
 }
Ejemplo n.º 12
0
 public override bool TryAdd(ServiceBusMessage message)
 {
     TryAddCalledWith = message;
     return(true);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Renews the lock on the message specified by the lock token. The lock will be renewed based on the setting specified on the queue.
 /// </summary>
 /// <remarks>
 /// When a message is received in <see cref="ReceiveMode.PeekLock"/> mode, the message is locked on the server for this
 /// receiver instance for a duration as specified during the Queue/Subscription creation (LockDuration).
 /// If processing of the message requires longer than this duration, the lock needs to be renewed.
 /// For each renewal, it resets the time the message is locked by the LockDuration set on the Entity.
 /// </remarks>
 public virtual async Task RenewLockAsync(
     ServiceBusMessage message,
     CancellationToken cancellationToken = default)
 {
     message.SystemProperties.LockedUntilUtc = await RenewLockAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Publishes message with group into broker.
 /// </summary>
 /// <param name="message">Incoming message.</param>
 /// <param name="groupName">Group identifier.</param>
 public void AcceptMessage(ServiceBusMessage message, string groupName)
 {
     // TODO: реализовать
     throw new NotImplementedException();
 }
 // Passes a service bus message from a queue to topic using a brokered message
 public static void SBQueue2SBTopic(
     [ServiceBusTrigger(SecondQueueNameKey)] string message,
     [ServiceBus(TopicNameKey)] out ServiceBusMessage output)
 {
     output = SBQueue2SBTopic_GetOutputMessage(message);
 }
Ejemplo n.º 16
0
 public TransportMessage TranslateToTransportMessage(ServiceBusMessage serviceBusMessage)
 {
     return(new TransportMessage(serviceBusMessage));
 }
        public static AmqpMessage SBMessageToAmqpMessage(ServiceBusMessage sbMessage)
        {
            // body
            var amqpMessage = sbMessage.ToAmqpMessage();

            // properties
            amqpMessage.Properties.MessageId       = sbMessage.MessageId;
            amqpMessage.Properties.CorrelationId   = sbMessage.CorrelationId;
            amqpMessage.Properties.ContentType     = sbMessage.ContentType;
            amqpMessage.Properties.ContentEncoding = sbMessage.AmqpMessage.Properties.ContentEncoding;
            amqpMessage.Properties.Subject         = sbMessage.Subject;
            amqpMessage.Properties.To             = sbMessage.To;
            amqpMessage.Properties.ReplyTo        = sbMessage.ReplyTo;
            amqpMessage.Properties.GroupId        = sbMessage.SessionId;
            amqpMessage.Properties.ReplyToGroupId = sbMessage.ReplyToSessionId;
            amqpMessage.Properties.GroupSequence  = sbMessage.AmqpMessage.Properties.GroupSequence;

            if (sbMessage.AmqpMessage.Properties.UserId.HasValue)
            {
                ReadOnlyMemory <byte> userId = sbMessage.AmqpMessage.Properties.UserId.Value;
                if (MemoryMarshal.TryGetArray(userId, out ArraySegment <byte> segment))
                {
                    amqpMessage.Properties.UserId = segment;
                }
                else
                {
                    amqpMessage.Properties.UserId = new ArraySegment <byte>(userId.ToArray());
                }
            }

            // If TTL is set, it is used to calculate AbsoluteExpiryTime and CreationTime
            if (sbMessage.TimeToLive != TimeSpan.MaxValue)
            {
                amqpMessage.Header.Ttl = (uint)sbMessage.TimeToLive.TotalMilliseconds;
                amqpMessage.Properties.CreationTime = DateTime.UtcNow;

                if (AmqpConstants.MaxAbsoluteExpiryTime - amqpMessage.Properties.CreationTime.Value > sbMessage.TimeToLive)
                {
                    amqpMessage.Properties.AbsoluteExpiryTime = amqpMessage.Properties.CreationTime.Value + sbMessage.TimeToLive;
                }
                else
                {
                    amqpMessage.Properties.AbsoluteExpiryTime = AmqpConstants.MaxAbsoluteExpiryTime;
                }
            }
            else
            {
                if (sbMessage.AmqpMessage.Properties.CreationTime.HasValue)
                {
                    amqpMessage.Properties.CreationTime = sbMessage.AmqpMessage.Properties.CreationTime.Value.UtcDateTime;
                }
                if (sbMessage.AmqpMessage.Properties.AbsoluteExpiryTime.HasValue)
                {
                    amqpMessage.Properties.AbsoluteExpiryTime = sbMessage.AmqpMessage.Properties.AbsoluteExpiryTime.Value.UtcDateTime;
                }
            }

            // message annotations

            foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.MessageAnnotations)
            {
                switch (kvp.Key)
                {
                case AmqpMessageConstants.ScheduledEnqueueTimeUtcName:
                    if ((sbMessage.ScheduledEnqueueTime != null) && sbMessage.ScheduledEnqueueTime > DateTimeOffset.MinValue)
                    {
                        amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ScheduledEnqueueTimeUtcName, sbMessage.ScheduledEnqueueTime.UtcDateTime);
                    }
                    break;

                case AmqpMessageConstants.PartitionKeyName:
                    if (sbMessage.PartitionKey != null)
                    {
                        amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.PartitionKeyName, sbMessage.PartitionKey);
                    }
                    break;

                case AmqpMessageConstants.ViaPartitionKeyName:
                    if (sbMessage.TransactionPartitionKey != null)
                    {
                        amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ViaPartitionKeyName, sbMessage.TransactionPartitionKey);
                    }
                    break;

                default:
                    amqpMessage.MessageAnnotations.Map.Add(kvp.Key, kvp.Value);
                    break;
                }
            }

            // application properties

            if (sbMessage.ApplicationProperties != null && sbMessage.ApplicationProperties.Count > 0)
            {
                if (amqpMessage.ApplicationProperties == null)
                {
                    amqpMessage.ApplicationProperties = new ApplicationProperties();
                }

                foreach (KeyValuePair <string, object> pair in sbMessage.ApplicationProperties)
                {
                    if (TryGetAmqpObjectFromNetObject(pair.Value, MappingType.ApplicationProperty, out var amqpObject))
                    {
                        amqpMessage.ApplicationProperties.Map.Add(pair.Key, amqpObject);
                    }
                    else
                    {
                        throw new NotSupportedException(Resources.InvalidAmqpMessageProperty.FormatForUser(pair.Key.GetType()));
                    }
                }
            }

            // delivery annotations

            foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.DeliveryAnnotations)
            {
                if (TryGetAmqpObjectFromNetObject(kvp.Value, MappingType.ApplicationProperty, out var amqpObject))
                {
                    amqpMessage.DeliveryAnnotations.Map.Add(kvp.Key, amqpObject);
                }
            }

            // header - except for ttl which is set above with the properties

            if (sbMessage.AmqpMessage.Header.DeliveryCount != null)
            {
                amqpMessage.Header.DeliveryCount = sbMessage.AmqpMessage.Header.DeliveryCount;
            }
            if (sbMessage.AmqpMessage.Header.Durable != null)
            {
                amqpMessage.Header.Durable = sbMessage.AmqpMessage.Header.Durable;
            }
            if (sbMessage.AmqpMessage.Header.FirstAcquirer != null)
            {
                amqpMessage.Header.FirstAcquirer = sbMessage.AmqpMessage.Header.FirstAcquirer;
            }
            if (sbMessage.AmqpMessage.Header.Priority != null)
            {
                amqpMessage.Header.Priority = sbMessage.AmqpMessage.Header.Priority;
            }

            // footer

            foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.Footer)
            {
                amqpMessage.Footer.Map.Add(kvp.Key, kvp.Value);
            }

            return(amqpMessage);
        }
Ejemplo n.º 18
0
        protected override void AfterSave(Protocol entity)
        {
            try
            {
                _logger.WriteDebug(new LogMessage($"VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Protocols.AfterSave with entity UniqueId {entity.UniqueId}"), LogCategories);
                Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueIdWithRole(entity.UniqueId).FirstOrDefault();
                if (protocol != null)
                {
                    IList <CategoryFascicle> categoryFascicles = protocol.Category.CategoryFascicles.Where(f => f.DSWEnvironment == (int)DSWEnvironmentType.Protocol || f.DSWEnvironment == 0).ToList();
                    CategoryFascicle         categoryFascicle  = categoryFascicles.FirstOrDefault();
                    if (categoryFascicles != null && categoryFascicles.Count > 1)
                    {
                        categoryFascicle = categoryFascicles.FirstOrDefault(f => f.FascicleType == FascicleType.Period);
                    }
                    IIdentityContext identity = new IdentityContext(_currentIdentity.FullUserName);
                    ICQRS            command  = null;

                    if (CurrentUpdateActionType.HasValue && CurrentUpdateActionType == UpdateActionType.ActivateProtocol)
                    {
                        command = new CommandCreateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (CurrentDeleteActionType.HasValue && CurrentDeleteActionType == DeleteActionType.DeleteProtocol)
                    {
                        command = new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (HttpContext.Current.Request.HttpMethod == HttpMethod.Put.Method &&
                        CurrentUpdateActionType.HasValue && CurrentUpdateActionType != UpdateActionType.ActivateProtocol)
                    {
                        command = new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (command != null)
                    {
                        WorkflowActionDocumentUnitLinkModel workflowActionDocumentUnitLinkModel;
                        DocumentUnitModel documentUnitModel;
                        foreach (IWorkflowAction workflowAction in WorkflowActions)
                        {
                            workflowAction.IdWorkflowActivity = IdWorkflowActivity;
                            if (workflowAction is IWorkflowActionDocumentUnitLink)
                            {
                                workflowActionDocumentUnitLinkModel = (WorkflowActionDocumentUnitLinkModel)workflowAction;
                                documentUnitModel = workflowActionDocumentUnitLinkModel.GetReferenced();
                                if (documentUnitModel.UniqueId != protocol.UniqueId)
                                {
                                    documentUnitModel = workflowActionDocumentUnitLinkModel.GetDestinationLink();
                                }
                                documentUnitModel.Year   = protocol.Year;
                                documentUnitModel.Number = protocol.Number.ToString();
                            }
                            command.WorkflowActions.Add(workflowAction);
                        }
                        ServiceBusMessage message = _cqrsMapper.Map(command, new ServiceBusMessage());
                        if (message == null || string.IsNullOrEmpty(message.ChannelName))
                        {
                            throw new DSWException($"Queue name to command [{command}] is not mapped", null, DSWExceptionCode.SC_Mapper);
                        }
                        Task.Run(async() =>
                        {
                            await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message);
                        }).Wait();
                    }
                }
            }
            catch (DSWException ex)
            {
                _logger.WriteError(ex, LogCategories);
            }
            base.AfterSave(entity);
        }
Ejemplo n.º 19
0
 private void AddMessageDelay(DateTimeOffset enqueueTime, ServiceBusMessage message)
 => message.ScheduledEnqueueTime = enqueueTime;
Ejemplo n.º 20
0
 public ServiceBusMessage Create(ServiceBusMessage content)
 {
     return(CreateAsync(content).Result);
 }
 /// <summary>
 /// Update service bus properties.
 /// </summary>
 /// <param name="serviceBusParams">Service bus message properties specified via PowerShell.</param>
 /// <param name="existingServiceBusMessage">Existing job's service bus message properties.</param>
 private void UpdateServiceBus(PSServiceBusParams serviceBusParams, ServiceBusMessage existingServiceBusMessage)
 {
     if (existingServiceBusMessage != null)
     {
         existingServiceBusMessage.TransportType = serviceBusParams.TransportType.GetValueOrDefaultEnum<ServiceBusTransportType?>(defaultValue: existingServiceBusMessage.TransportType);
         existingServiceBusMessage.NamespaceProperty = serviceBusParams.NamespaceProperty.GetValueOrDefault(defaultValue: existingServiceBusMessage.NamespaceProperty);
         existingServiceBusMessage.Message = serviceBusParams.Message.GetValueOrDefault(defaultValue: existingServiceBusMessage.Message);
         
         this.PopulateServiceBusAuthentication(serviceBusParams.Authentication, existingServiceBusMessage.Authentication);
     }
 }
 public TransportMessage TranslateToTransportMessage(ServiceBusMessage serviceBusMessage)
 {
     return new TransportMessage(serviceBusMessage);
 }
Ejemplo n.º 23
0
 private static void AddMessageLabel <T>(Message <T> eventMessage, ServiceBusMessage message) where T : IMessage
 => message.Subject = eventMessage.Label;
Ejemplo n.º 24
0
 public Task <bool> DeleteAsync(ServiceBusMessage content)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 25
0
 public async Task Publish <T>(T @event) where T : Event
 {
     ServiceBusMessage message = new ServiceBusMessage(JsonConvert.SerializeObject(@event));
     await serviceBusSender.SendMessageAsync(message);
 }
Ejemplo n.º 26
0
 public ServiceBusMessage Update(ServiceBusMessage content)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 27
0
        public async Task <IActionResult> PublishRoutineAsync(
            [HttpTrigger(AuthorizationLevel.Function, HttpVerbs.Post, Route = "routines/{routineId}/publish")] HttpRequest req,
            Guid routineId,
            ExecutionContext context,
            [ServiceBus(GymLogTopicKey)] IAsyncCollector <ServiceBusMessage> collector,
            ILogger log)
        {
            var request = await req.ToRequestMessageAsync <PublishRequestMessage>().ConfigureAwait(false);

            var eventId       = context.InvocationId;
            var spanId        = request.SpanId;
            var correlationId = request.CorrelationId;
            var upn           = request.Upn;
            var @interface    = request.Interface;

            log.LogData(LogLevel.Information, request,
                        EventType.PublishRequestReceived, EventStatusType.Succeeded, eventId,
                        SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                        @interface, correlationId);

            if (routineId != request.RoutineId)
            {
                log.LogData(LogLevel.Error, request,
                            EventType.InvalidPublishRequest, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            message: EventType.InvalidPublishRequest.ToDisplayName());

                return(new BadRequestResult());
            }

            var entity = new RoutineEntity()
            {
                PartitionKey  = correlationId.ToString(),
                RowKey        = eventId.ToString(),
                Upn           = upn,
                CorrelationId = correlationId,
                SpanId        = spanId,
                Interface     = @interface,
                EventId       = eventId,
                EventName     = EventType.RoutineCompleted.ToDisplayName(),
                RoutineId     = routineId,
                Routine       = request.Routine,
            };

            var res = default(ObjectResult);

            try
            {
                if (this._settings.ForceError.Publisher.Publish)
                {
                    throw new ErrorEnforcementException("Error Enforced!");
                }

                await this._client.CreateTableIfNotExistsAsync(this._settings.GymLog.StorageAccount.Table.TableName).ConfigureAwait(false);

                var table = this._client.GetTableClient(this._settings.GymLog.StorageAccount.Table.TableName);

                var records = await table.QueryAsync <ExerciseEntity>(p => p.PartitionKey == correlationId.ToString() &&
                                                                      p.SpanId == spanId)
                              .ToListAsync()
                              .ConfigureAwait(false);

                records = records.Where(p => !p.Exercise.IsNullOrWhiteSpace())
                          .ToList();

                if (!records.Any())
                {
                    res = records.ToPublishResponseMessage(request, eventId);

                    log.LogData(LogLevel.Error, res.Value,
                                EventType.RecordNotFound, EventStatusType.Failed, eventId,
                                SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                                request.Interface, correlationId,
                                message: EventType.RecordNotFound.ToDisplayName());

                    return(res);
                }

                var entities = records.GroupBy(p => p.Exercise)
                               .Select(g => new ExerciseEntityGroup()
                {
                    Exercise = g.Key, Entity = g.OrderByDescending(q => q.Timestamp).First()
                })
                               .Select(p => p.Entity)
                               .OrderByDescending(p => p.Timestamp)
                               .ToList();

                res = entities.ToPublishResponseMessage(request, eventId);

                log.LogData(LogLevel.Information, res.Value,
                            EventType.RecordPopulated, EventStatusType.Succeeded, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            message: EventType.RecordPopulated.ToDisplayName());

                var messageId = Guid.NewGuid();
                var subSpanId = Guid.NewGuid();
                var timestamp = DateTimeOffset.UtcNow;
                var message   = (RoutineQueueMessage)(PublishResponseMessage)res.Value;
                var msg       = new ServiceBusMessage(message.ToJson())
                {
                    CorrelationId = correlationId.ToString(),
                    MessageId     = messageId.ToString(),
                    ContentType   = ContentTypes.ApplicationJson,
                };
                msg.ApplicationProperties.Add("pubSpanId", spanId);
                msg.ApplicationProperties.Add("subSpanId", subSpanId);
                msg.ApplicationProperties.Add("interface", @interface.ToString());
                msg.ApplicationProperties.Add("timestamp", timestamp.ToString(CultureInfo.InvariantCulture));

                await collector.AddAsync(msg).ConfigureAwait(false);

                log.LogData(LogLevel.Information, msg,
                            EventType.MessagePublished, EventStatusType.Succeeded, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            messageId: messageId.ToString(),
                            message: EventType.MessagePublished.ToDisplayName());

                var response = await table.UpsertEntityAsync(entity).ConfigureAwait(false);

                var r = response.ToRoutineResponseMessage(request, eventId, entity.RoutineId);

                log.LogData(response.Status.ToLogLevel(), r.Value,
                            response.Status.ToRoutineCompletedEventType(), response.Status.ToEventStatusType(), eventId,
                            SpanType.Publisher, SpanStatusType.PublisherCompleted, spanId,
                            @interface, correlationId,
                            clientRequestId: response.ClientRequestId,
                            message: response.Status.ToResponseMessage(r));
            }
            catch (Exception ex)
            {
                res = new InternalServerErrorObjectResult()
                {
                    Upn           = upn,
                    CorrelationId = correlationId,
                    Interface     = @interface,
                    SpanId        = spanId,
                    EventId       = eventId,
                    Message       = ex.Message,
                };

                log.LogData(LogLevel.Error, res.Value,
                            EventType.MessageNotPublished, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherCompleted, spanId,
                            @interface, correlationId,
                            ex: ex,
                            message: ex.Message);
            }

            return(res);
        }
Ejemplo n.º 28
0
 public bool Delete(ServiceBusMessage content)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="timeout"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        internal async Task <long> ScheduleMessageInternalAsync(
            ServiceBusMessage message,
            TimeSpan timeout,
            CancellationToken cancellationToken = default)
        {
            var stopWatch = Stopwatch.StartNew();

            using (AmqpMessage amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message))
            {
                var request = AmqpRequestMessage.CreateRequest(
                    ManagementConstants.Operations.ScheduleMessageOperation,
                    timeout,
                    null);

                if (_sendLink.TryGetOpenedObject(out SendingAmqpLink sendLink))
                {
                    request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name;
                }

                ArraySegment <byte>[] payload = amqpMessage.GetPayload();
                var buffer = new BufferListStream(payload);
                ArraySegment <byte> value = buffer.ReadBytes((int)buffer.Length);

                var entry = new AmqpMap();
                {
                    entry[ManagementConstants.Properties.Message]   = value;
                    entry[ManagementConstants.Properties.MessageId] = message.MessageId;

                    if (!string.IsNullOrWhiteSpace(message.SessionId))
                    {
                        entry[ManagementConstants.Properties.SessionId] = message.SessionId;
                    }

                    if (!string.IsNullOrWhiteSpace(message.PartitionKey))
                    {
                        entry[ManagementConstants.Properties.PartitionKey] = message.PartitionKey;
                    }

                    if (!string.IsNullOrWhiteSpace(message.ViaPartitionKey))
                    {
                        entry[ManagementConstants.Properties.ViaPartitionKey] = message.ViaPartitionKey;
                    }
                }

                request.Map[ManagementConstants.Properties.Messages] = new List <AmqpMap> {
                    entry
                };

                RequestResponseAmqpLink mgmtLink = await _managementLink.GetOrCreateAsync(
                    UseMinimum(_connectionScope.SessionTimeout,
                               timeout.CalculateRemaining(stopWatch.Elapsed)))
                                                   .ConfigureAwait(false);

                using AmqpMessage response = await mgmtLink.RequestAsync(
                          request.AmqpMessage,
                          timeout.CalculateRemaining(stopWatch.Elapsed))
                                             .ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
                stopWatch.Stop();

                AmqpResponseMessage amqpResponseMessage = AmqpResponseMessage.CreateResponse(response);

                if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK)
                {
                    var sequenceNumbers = amqpResponseMessage.GetValue <long[]>(ManagementConstants.Properties.SequenceNumbers);
                    if (sequenceNumbers == null || sequenceNumbers.Length < 1)
                    {
                        throw new ServiceBusException(true, "Could not schedule message successfully.");
                    }

                    return(sequenceNumbers[0]);
                }
                else
                {
                    throw amqpResponseMessage.ToMessagingContractException();
                }
            }
        }
Ejemplo n.º 30
0
 public async Task <bool> SendServiceBusMessage(ServiceBusMessage message)
 {
     return(true);
     //ToDo: Add Service Bus logic here
 }
Ejemplo n.º 31
0
        protected async override Task <object> InternalProcessMessageAsync(ServiceBusMessage message)
        {
            Stopwatch watch = Stopwatch.StartNew();

            Interlocked.Increment(ref _receivedMessage);

            lock (typeof(CsvProcessor))
            {
                _maxAge = Math.Max(Math.Abs(message.Age.Ticks), _maxAge);
            }

            Payload payload = null;

            try
            {
                string jsonSerialized = System.Text.Encoding.UTF8.GetString(message.Data);

                payload = await JsonConvert.DeserializeObjectAsync <Payload>(jsonSerialized);

                if (payload.IsRequest)
                {
                    Interlocked.Increment(ref _requestCount);

                    var responsePayload = new Payload()
                    {
                        IsRequest = false,
                        Sql       = payload.Sql,
                        Result    = new List <string>()
                    };

                    string connectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;

                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        await connection.OpenAsync();

                        using (SqlCommand command = new SqlCommand(payload.Sql, connection))
                        {
                            command.CommandType    = System.Data.CommandType.Text;
                            command.CommandTimeout = 60;
                            command.CommandText    = payload.Sql;

                            using (var reader = await command.ExecuteReaderAsync())
                            {
                                bool read = await reader.ReadAsync();

                                if (read)
                                {
                                    int      recordIndex     = 0;
                                    object[] fieldsFlyWeight = new object[reader.FieldCount];

                                    while (read != false)
                                    {
                                        var values = reader.GetValues(fieldsFlyWeight);
                                        recordIndex++;
                                        var csv = String.Join(",", fieldsFlyWeight);
                                        responsePayload.Result.Add(csv);
                                        read = await reader.ReadAsync();
                                    }
                                }
                            }
                        }
                    }

                    if (message.OriginatorRequiresReply)
                    {
                        var data         = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(responsePayload));
                        var replyMessage = ServiceBusMessage.CreateReply(message, data, DataFormatEnum.BinaryNet);
                        Interlocked.Increment(ref _replyCount);
                        Root.ServiceBusInstance.SendAsync(replyMessage);
                    }
                }
                else
                {
                    Interlocked.Increment(ref _responseCount);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                lock (typeof(CsvProcessor))
                {
                    _maxProcessingTime = Math.Max((watch.Elapsed).Ticks, _maxProcessingTime);
                }

                watch.Stop();
            }

            return(payload);
        }
Ejemplo n.º 32
0
        public async Task ProcessMessages()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
            {
                #region Snippet:ServiceBusProcessMessages
#if SNIPPET
                string connectionString = "<connection_string>";
                string queueName        = "<queue_name>";
                // since ServiceBusClient implements IAsyncDisposable we create it with "await using"
                await using var client = new ServiceBusClient(connectionString);
#else
                string connectionString = TestEnvironment.ServiceBusConnectionString;
                string queueName        = scope.QueueName;
                await using var client = CreateClient();
#endif

                // create the sender
                ServiceBusSender sender = client.CreateSender(queueName);

                // create a set of messages that we can send
                ServiceBusMessage[] messages = new ServiceBusMessage[]
                {
                    new ServiceBusMessage("First"),
                    new ServiceBusMessage("Second")
                };

                // send the message batch
                await sender.SendMessagesAsync(messages);

                #region Snippet:ServiceBusConfigureProcessor
                // create the options to use for configuring the processor
                var options = new ServiceBusProcessorOptions
                {
                    // By default or when AutoCompleteMessages is set to true, the processor will complete the message after executing the message handler
                    // Set AutoCompleteMessages to false to [settle messages](https://docs.microsoft.com/en-us/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock) on your own.
                    // In both cases, if the message handler throws an exception without settling the message, the processor will abandon the message.
                    AutoCompleteMessages = false,

                    // I can also allow for multi-threading
                    MaxConcurrentCalls = 2
                };

                // create a processor that we can use to process the messages
                await using ServiceBusProcessor processor = client.CreateProcessor(queueName, options);

                // configure the message and error handler to use
                processor.ProcessMessageAsync += MessageHandler;
                processor.ProcessErrorAsync   += ErrorHandler;

                async Task MessageHandler(ProcessMessageEventArgs args)
                {
                    string body = args.Message.Body.ToString();

                    Console.WriteLine(body);

                    // we can evaluate application logic and use that to determine how to settle the message.
                    await args.CompleteMessageAsync(args.Message);
                }

                Task ErrorHandler(ProcessErrorEventArgs args)
                {
                    // the error source tells me at what point in the processing an error occurred
                    Console.WriteLine(args.ErrorSource);
                    // the fully qualified namespace is available
                    Console.WriteLine(args.FullyQualifiedNamespace);
                    // as well as the entity path
                    Console.WriteLine(args.EntityPath);
                    Console.WriteLine(args.Exception.ToString());
                    return(Task.CompletedTask);
                }

                // start processing
                await processor.StartProcessingAsync();

                // since the processing happens in the background, we add a Conole.ReadKey to allow the processing to continue until a key is pressed.
                Console.ReadKey();
                #endregion
                #endregion
            }
        }
Ejemplo n.º 33
0
        public static AmqpMessage SBMessageToAmqpMessage(ServiceBusMessage sbMessage)
        {
            var amqpMessage = sbMessage.ToAmqpMessage();

            amqpMessage.Properties.MessageId      = sbMessage.MessageId;
            amqpMessage.Properties.CorrelationId  = sbMessage.CorrelationId;
            amqpMessage.Properties.ContentType    = sbMessage.ContentType;
            amqpMessage.Properties.Subject        = sbMessage.Subject;
            amqpMessage.Properties.To             = sbMessage.To;
            amqpMessage.Properties.ReplyTo        = sbMessage.ReplyTo;
            amqpMessage.Properties.GroupId        = sbMessage.SessionId;
            amqpMessage.Properties.ReplyToGroupId = sbMessage.ReplyToSessionId;

            if (sbMessage.TimeToLive != TimeSpan.MaxValue)
            {
                amqpMessage.Header.Ttl = (uint)sbMessage.TimeToLive.TotalMilliseconds;
                amqpMessage.Properties.CreationTime = DateTime.UtcNow;

                if (AmqpConstants.MaxAbsoluteExpiryTime - amqpMessage.Properties.CreationTime.Value > sbMessage.TimeToLive)
                {
                    amqpMessage.Properties.AbsoluteExpiryTime = amqpMessage.Properties.CreationTime.Value + sbMessage.TimeToLive;
                }
                else
                {
                    amqpMessage.Properties.AbsoluteExpiryTime = AmqpConstants.MaxAbsoluteExpiryTime;
                }
            }

            if ((sbMessage.ScheduledEnqueueTime != null) && sbMessage.ScheduledEnqueueTime > DateTimeOffset.MinValue)
            {
                amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ScheduledEnqueueTimeUtcName, sbMessage.ScheduledEnqueueTime.UtcDateTime);
            }

            if (sbMessage.PartitionKey != null)
            {
                amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.PartitionKeyName, sbMessage.PartitionKey);
            }

            if (sbMessage.TransactionPartitionKey != null)
            {
                amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ViaPartitionKeyName, sbMessage.TransactionPartitionKey);
            }

            if (sbMessage.ApplicationProperties != null && sbMessage.ApplicationProperties.Count > 0)
            {
                if (amqpMessage.ApplicationProperties == null)
                {
                    amqpMessage.ApplicationProperties = new ApplicationProperties();
                }

                foreach (var pair in sbMessage.ApplicationProperties)
                {
                    if (TryGetAmqpObjectFromNetObject(pair.Value, MappingType.ApplicationProperty, out var amqpObject))
                    {
                        amqpMessage.ApplicationProperties.Map.Add(pair.Key, amqpObject);
                    }
                    else
                    {
                        throw new NotSupportedException(Resources.InvalidAmqpMessageProperty.FormatForUser(pair.Key.GetType()));
                    }
                }
            }

            return(amqpMessage);
        }
Ejemplo n.º 34
0
        public async Task CreateFromReceivedMessageCopiesProperties()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: true))
            {
                var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                var sender = client.CreateSender(scope.QueueName);
                var msg    = new ServiceBusMessage(new BinaryData(GetRandomBuffer(100)));
                msg.ContentType   = "contenttype";
                msg.CorrelationId = "correlationid";
                msg.Subject       = "label";
                msg.MessageId     = "messageId";
                msg.PartitionKey  = "key";
                msg.ApplicationProperties.Add("testProp", "my prop");
                msg.ReplyTo              = "replyto";
                msg.ReplyToSessionId     = "replytosession";
                msg.ScheduledEnqueueTime = DateTimeOffset.Now;
                msg.SessionId            = "key";
                msg.TimeToLive           = TimeSpan.FromSeconds(60);
                msg.To = "to";
                await sender.SendMessageAsync(msg);

                ServiceBusSessionReceiver receiver = await client.AcceptNextSessionAsync(scope.QueueName);

                ServiceBusReceivedMessage received = await receiver.ReceiveMessageAsync();

                AmqpAnnotatedMessage rawReceived = received.GetRawAmqpMessage();
                Assert.IsNotNull(rawReceived.Header.DeliveryCount);
                Assert.IsTrue(rawReceived.MessageAnnotations.ContainsKey(AmqpMessageConstants.LockedUntilName));
                Assert.IsTrue(rawReceived.MessageAnnotations.ContainsKey(AmqpMessageConstants.SequenceNumberName));
                Assert.IsTrue(rawReceived.MessageAnnotations.ContainsKey(AmqpMessageConstants.EnqueueSequenceNumberName));
                Assert.IsTrue(rawReceived.MessageAnnotations.ContainsKey(AmqpMessageConstants.EnqueuedTimeUtcName));

                AssertMessagesEqual(msg, received);
                var toSend = new ServiceBusMessage(received);
                AmqpAnnotatedMessage rawSend = toSend.GetRawAmqpMessage();

                // verify that all system set properties have been cleared out
                Assert.IsNull(rawSend.Header.DeliveryCount);
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.LockedUntilName));
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.SequenceNumberName));
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.DeadLetterSourceName));
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.EnqueueSequenceNumberName));
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.EnqueuedTimeUtcName));
                Assert.IsFalse(rawSend.MessageAnnotations.ContainsKey(AmqpMessageConstants.DeadLetterSourceName));
                Assert.IsFalse(toSend.ApplicationProperties.ContainsKey(AmqpMessageConstants.DeadLetterReasonHeader));
                Assert.IsFalse(toSend.ApplicationProperties.ContainsKey(AmqpMessageConstants.DeadLetterErrorDescriptionHeader));

                AssertMessagesEqual(toSend, received);

                void AssertMessagesEqual(ServiceBusMessage sentMessage, ServiceBusReceivedMessage received)
                {
                    Assert.IsTrue(received.Body.ToArray().SequenceEqual(sentMessage.Body.ToArray()));
                    Assert.AreEqual(received.ContentType, sentMessage.ContentType);
                    Assert.AreEqual(received.CorrelationId, sentMessage.CorrelationId);
                    Assert.AreEqual(received.Subject, sentMessage.Subject);
                    Assert.AreEqual(received.ContentType, sentMessage.ContentType);
                    Assert.AreEqual(received.CorrelationId, sentMessage.CorrelationId);
                    Assert.AreEqual(received.MessageId, sentMessage.MessageId);
                    Assert.AreEqual(received.PartitionKey, sentMessage.PartitionKey);
                    Assert.AreEqual((string)received.ApplicationProperties["testProp"], (string)sentMessage.ApplicationProperties["testProp"]);
                    Assert.AreEqual(received.ReplyTo, sentMessage.ReplyTo);
                    Assert.AreEqual(received.ReplyToSessionId, sentMessage.ReplyToSessionId);
                    Assert.AreEqual(received.ScheduledEnqueueTime.UtcDateTime.Second, sentMessage.ScheduledEnqueueTime.UtcDateTime.Second);
                    Assert.AreEqual(received.SessionId, sentMessage.SessionId);
                    Assert.AreEqual(received.TimeToLive, sentMessage.TimeToLive);
                    Assert.AreEqual(received.To, sentMessage.To);
                    Assert.AreEqual(received.TransactionPartitionKey, sentMessage.TransactionPartitionKey);
                }
            }
        }
Ejemplo n.º 35
0
 private async Task SendAsync(ServiceBusSender client, ServiceBusMessage message, CancellationToken cancellationToken)
 {
     await client.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
 }
        public async Task TransactionThrowsWhenOperationsOfDifferentPartitionsAreInSameTransaction()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false))
            {
                var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                ServiceBusSender   sender   = client.CreateSender(scope.QueueName);
                ServiceBusReceiver receiver = client.CreateReceiver(scope.QueueName);

                string            body     = Guid.NewGuid().ToString("N");
                ServiceBusMessage message1 = GetMessage(partitionKey: "1");
                ServiceBusMessage message2 = GetMessage(partitionKey: "2");

                // Two send operations to different partitions.
                var transaction = new CommittableTransaction();
                using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
                {
                    await sender.SendAsync(message1);

                    Assert.ThrowsAsync <InvalidOperationException>(
                        async() => await sender.SendAsync(message2));
                    ts.Complete();
                }

                transaction.Rollback();

                // Adding delay since transaction Commit/Rollback is an asynchronous operation.
                // Operating on the same message should not be done.
                await Task.Delay(TimeSpan.FromSeconds(2));

                // Two complete operations to different partitions.
                await sender.SendAsync(message1);

                await sender.SendAsync(message2);

                ServiceBusReceivedMessage receivedMessage1 = await receiver.ReceiveAsync();

                Assert.NotNull(receivedMessage1);
                ServiceBusReceivedMessage receivedMessage2 = await receiver.ReceiveAsync();

                Assert.NotNull(receivedMessage2);

                transaction = new CommittableTransaction();
                using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
                {
                    await receiver.CompleteAsync(receivedMessage1);

                    Assert.ThrowsAsync <InvalidOperationException>(
                        async() => await receiver.CompleteAsync(receivedMessage2));
                    ts.Complete();
                }

                transaction.Rollback();

                // Adding delay since transaction Commit/Rollback is an asynchronous operation.
                // Operating on the same message should not be done.
                await Task.Delay(TimeSpan.FromSeconds(2));

                await receiver.CompleteAsync(receivedMessage1);

                // the service seems to abandon the message that
                // triggered the InvalidOperationException
                // in the transaction
                Assert.That(
                    async() =>
                    await receiver.CompleteAsync(receivedMessage2), Throws.InstanceOf <ServiceBusException>()
                    .And.Property(nameof(ServiceBusException.Reason))
                    .EqualTo(ServiceBusException.FailureReason.MessageLockLost));
            }
        }
Ejemplo n.º 37
0
 private void SendResponseDataErrorEvent(ServiceBusMessage result)
 {
     SendClientResponse(result, (action, content) => action.udsDataError(result.Content));
 }
        public async Task TransactionalSendViaCommitTest()
        {
            var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);

            await using var intermediateQueue = await ServiceBusScope.CreateWithQueue(enablePartitioning : true, enableSession : false);

            await using var destination1 = await ServiceBusScope.CreateWithTopic(enablePartitioning : true, enableSession : false);

            await using var destination2 = await ServiceBusScope.CreateWithQueue(enablePartitioning : true, enableSession : false);

            var intermediateSender    = client.CreateSender(intermediateQueue.QueueName);
            var intermediateReceiver  = client.CreateReceiver(intermediateQueue.QueueName);
            var destination1Sender    = client.CreateSender(destination1.TopicName);
            var destination1ViaSender = client.CreateSender(destination1.TopicName, new ServiceBusSenderOptions
            {
                ViaQueueOrTopicName = intermediateQueue.QueueName
            });
            var destination2ViaSender = client.CreateSender(destination2.QueueName, new ServiceBusSenderOptions
            {
                ViaQueueOrTopicName = intermediateQueue.QueueName
            });
            var destination1Receiver = client.CreateReceiver(destination1.TopicName, destination1.SubscriptionNames.First());
            var destination2Receiver = client.CreateReceiver(destination2.QueueName);

            var body     = Encoding.Default.GetBytes(Guid.NewGuid().ToString("N"));
            var message1 = new ServiceBusMessage(body)
            {
                MessageId = "1", PartitionKey = "pk1"
            };
            var message2 = new ServiceBusMessage(body)
            {
                MessageId = "2", PartitionKey = "pk2", ViaPartitionKey = "pk1"
            };
            var message3 = new ServiceBusMessage(body)
            {
                MessageId = "3", PartitionKey = "pk3", ViaPartitionKey = "pk1"
            };

            await intermediateSender.SendAsync(message1).ConfigureAwait(false);

            var receivedMessage = await intermediateReceiver.ReceiveAsync();

            Assert.NotNull(receivedMessage);
            Assert.AreEqual("pk1", receivedMessage.PartitionKey);

            // If the transaction succeeds, then all the operations occurred on the same partition.
            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await intermediateReceiver.CompleteAsync(receivedMessage);

                await destination1ViaSender.SendAsync(message2);

                await destination2ViaSender.SendAsync(message3);

                ts.Complete();
            }

            // Assert that first message indeed completed.
            receivedMessage = await intermediateReceiver.ReceiveAsync(TimeSpan.FromSeconds(5));

            Assert.Null(receivedMessage);

            // Assert that second message reached its destination.
            var receivedMessage1 = await destination1Receiver.ReceiveAsync();

            Assert.NotNull(receivedMessage1);
            Assert.AreEqual("pk2", receivedMessage1.PartitionKey);

            // Assert destination1 message actually used partitionKey in the destination entity.
            var destination1Message = new ServiceBusMessage(body)
            {
                PartitionKey = "pk2"
            };

            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await destination1Receiver.CompleteAsync(receivedMessage1);

                await destination1Sender.SendAsync(destination1Message);

                ts.Complete();
            }

            // Assert that third message reached its destination.
            var receivedMessage2 = await destination2Receiver.ReceiveAsync();

            Assert.NotNull(receivedMessage2);
            Assert.AreEqual("pk3", receivedMessage2.PartitionKey);
            await destination2Receiver.CompleteAsync(receivedMessage2);

            // Cleanup
            receivedMessage1 = await destination1Receiver.ReceiveAsync();

            await destination1Receiver.CompleteAsync(receivedMessage1);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            string appId, kind, username, @params, authRule, year, number, uniqueId, token, user;

            appId = kind = username = @params = authRule = year = number = uniqueId = token = user = string.Empty;
            try
            {
                _logger.WriteDebug(new LogMessage("GrantResourceOwnerCredentials"), LogCategories);
                IFormCollection forms = await context.OwinContext.Request.ReadFormAsync();

                appId = forms.Single(f => f.Key == "appId").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("AppID-> ", appId)), LogCategories);

                kind = forms.Single(f => f.Key == "kind").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("Kind-> ", kind)), LogCategories);

                username = forms.Single(f => f.Key == "username").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("Username-> ", username)), LogCategories);

                authRule = forms.Single(f => f.Key == "authRule").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("AuthRule-> ", authRule)), LogCategories);

                @params = forms.Single(f => f.Key == "params").Value.SingleOrDefault();
                _logger.WriteDebug(new LogMessage(string.Concat("Params-> ", @params)), LogCategories);

                if (kind == "Protocol")
                {
                    string[] keys = @params.Split('|');
                    year     = keys.Single(f => f.StartsWith("year=")).Split('=').Last();
                    number   = keys.Single(f => f.StartsWith("number=")).Split('=').Last();
                    uniqueId = _unitOfWork.Repository <Protocol>().GetByCompositeKey(short.Parse(year), int.Parse(number)).Single().UniqueId.ToString();
                }
                if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
                {
                    string[] keys = @params.Split('|');
                    token = keys.Single(f => f.StartsWith("token=")).Split('=').Last();
                    user  = keys.Single(f => f.StartsWith("user="******"The AppId '{appId}' is not valid."), LogCategories);
                context.SetError("invalid_grant", $"The AppId {appId} is not valid.");
                context.Rejected();
                return;
            }
            if (string.IsNullOrEmpty(kind))
            {
                _logger.WriteWarning(new LogMessage($"The Kind '{kind}' is not valid."), LogCategories);
                context.SetError("invalid_grant", "The Kind is not valid.");
                context.Rejected();
                return;
            }
            if (string.IsNullOrEmpty(username) || !ValidIntegrations.Any(f => f.Key == username))
            {
                _logger.WriteWarning(new LogMessage($"The Username '{username}' is not valid."), LogCategories);
                context.SetError("invalid_grant", $"The Username {username} is not valid.");
                context.Rejected();
                return;
            }

            if (string.IsNullOrEmpty(authRule))
            {
                _logger.WriteWarning(new LogMessage($"The AuthRule '{authRule}' is not valid."), LogCategories);
                context.SetError("invalid_grant", "The AuthRule is not valid.");
                context.Rejected();
                return;
            }
            currentIntegration = ValidIntegrations[username];
            if (currentIntegration.Key != authenticationId || currentIntegration.Value != authRule)
            {
                _logger.WriteWarning(new LogMessage($"{username}: The configuration is not valid."), LogCategories);
                context.SetError("invalid_grant", "The configuration is not valid.");
                context.Rejected();
                return;
            }

            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_OAuth2 &&
                (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number)))
            {
                _logger.WriteWarning(new LogMessage($"The protocols oauth2 params {year}/{number} is not valid."), LogCategories);
                context.SetError("invalid_grant", "The protocols oauth2 params is not valid.");
                context.Rejected();
                return;
            }
            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token &&
                (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number)))
            {
                _logger.WriteWarning(new LogMessage($"The protocols token params {user}/{token}/{year}/{number} is not valid."), LogCategories);
                context.SetError("invalid_grant", "The protocols token params is not valid.");
                context.Rejected();
                return;
            }
            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
            {
                string topicName = _messageConfiguration.GetConfigurations()["EventTokenSecurity"].TopicName;
                if (!await _topicService.SubscriptionExists(topicName, token))
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token {authenticationId}"), LogCategories);
                    context.SetError($"AppId {appId} has not validate token {authenticationId}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                ServiceBusMessage   serviceBusMessage  = (await _topicService.GetMessagesAsync(topicName, token)).FirstOrDefault();
                IEventTokenSecurity tokenSecurityModel = null;
                if (serviceBusMessage == null || (tokenSecurityModel = (IEventTokenSecurity)serviceBusMessage.Content) == null)
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token"), LogCategories);
                    context.SetError($"AppId {appId} has not validate token {token}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                if (tokenSecurityModel.ContentType.ContentTypeValue.DocumentUnitAuhtorized.UniqueId.ToString() != uniqueId)
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}"), LogCategories);
                    context.SetError($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                Guid secureToken = tokenSecurityModel.ContentType.ContentTypeValue.Token;
                _logger.WriteDebug(new LogMessage($"SecureToken is {secureToken}"), LogCategories);
            }
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Kind, kind, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
            identity.AddClaim(new Claim(CLAIM_ExternalViewer_AuthenticationRule, authRule, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));

            if (kind == "Protocol")
            {
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Year, year, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Number, number, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_UniqueId, uniqueId, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));

                if (authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
                {
                    identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_Hash, token, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                    identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_User, user, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                }
            }
            context.Validated(identity);
        }
Ejemplo n.º 40
0
        private static async Task Main(string[] args)
        {
            await using var stage = await Prepare.Stage(connectionString, destination);

            await using var serviceBusClient = new ServiceBusClient(connectionString);

            await using var sender = serviceBusClient.CreateSender(destination);

            var messages = new List <ServiceBusMessage>();

            for (var i = 0; i < 10; i++)
            {
                var message = new ServiceBusMessage("Deep Dive{i}");
                messages.Add(message);
            }

            WriteLine($"Sending {messages.Count} messages in a batch.");
            await sender.SendMessagesAsync(messages);

            messages.Clear();
            WriteLine();

            for (var i = 0; i < 6500; i++)
            {
                var message = new ServiceBusMessage($"Deep Dive{i}");
                messages.Add(message);
            }

            try
            {
                WriteLine($"Sending {messages.Count} messages in a batch.");
                await sender.SendMessagesAsync(messages);
            }
            catch (ServiceBusException ex) when(ex.Reason == ServiceBusFailureReason.MessageSizeExceeded)
            {
                await Error.WriteLineAsync(ex.Message);
            }

            messages.Clear();
            WriteLine();

            for (var i = 0; i < 101; i++)
            {
                var message = new ServiceBusMessage($"Deep Dive{i}");
                messages.Add(message);
            }

            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    WriteLine($"Sending {messages.Count} messages in a batch with in transaction '{Transaction.Current.TransactionInformation.LocalIdentifier}'.");
                    await sender.SendMessagesAsync(messages);

                    scope.Complete();
                }
            }
            catch (ServiceBusException ex) when(ex.Reason == ServiceBusFailureReason.QuotaExceeded)
            {
                await Error.WriteLineAsync(ex.Message);
            }

            var messagesToSend = new Queue <ServiceBusMessage>();

            for (var i = 0; i < 4500; i++)
            {
                var message = new ServiceBusMessage($"Deep Dive{i}. Deep Dive{i}. Deep Dive{i}.");
                messagesToSend.Enqueue(message);
            }

            var messageCount = messagesToSend.Count;
            int batchCount   = 1;

            while (messagesToSend.Count > 0)
            {
                using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

                if (messageBatch.TryAddMessage(messagesToSend.Peek()))
                {
                    messagesToSend.Dequeue();
                }
                else
                {
                    throw new Exception($"Message {messageCount - messagesToSend.Count} is too large and cannot be sent.");
                }

                while (messagesToSend.Count > 0 && messageBatch.TryAddMessage(messagesToSend.Peek()))
                {
                    messagesToSend.Dequeue();
                }

                WriteLine($"Sending {messageBatch.Count} messages in a batch {batchCount++}.");
                await sender.SendMessagesAsync(messageBatch);
            }
        }
Ejemplo n.º 41
0
 private static void AddMessageId <T>(Message <T> eventMessage, ServiceBusMessage message) where T : IMessage
 => message.MessageId = eventMessage.MessageId;
        /// <summary>
        /// Populates Service bus message object with valid values.
        /// </summary>
        /// <param name="serviceBusQueueActionParams">Service bus properties specified via PowerShell.</param>
        /// <param name="serviceBusMessage">Servce message object to be populated.</param>
        private void PopulateServiceBusMessage(PSServiceBusParams serviceBusQueueActionParams, ServiceBusMessage serviceBusMessage)
        {
            if (string.IsNullOrWhiteSpace(serviceBusQueueActionParams.NamespaceProperty) ||
                string.IsNullOrWhiteSpace(serviceBusQueueActionParams.Message) ||
                string.IsNullOrWhiteSpace(serviceBusQueueActionParams.TransportType))
            {
                throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidServiceBus);
            }

            if (serviceBusMessage == null)
            {
                throw new ArgumentException("serviceBusMessage: Object must be initialized");
            }

            ServiceBusAuthentication authentication = this.GetServiceBusAuthentication(serviceBusQueueActionParams.Authentication);

            serviceBusMessage.Authentication = this.GetServiceBusAuthentication(serviceBusQueueActionParams.Authentication);
            serviceBusMessage.Message = serviceBusQueueActionParams.Message;
            serviceBusMessage.NamespaceProperty = serviceBusQueueActionParams.NamespaceProperty;
            serviceBusMessage.TransportType = serviceBusQueueActionParams.TransportType.GetValueOrDefaultEnum<ServiceBusTransportType>(defaultValue: ServiceBusTransportType.NetMessaging);
        }