Example #1
0
        public async Task Wait_Cancels_WhenAnySubscriptionWaitsCancels()
        {
            var message = new Amqp.Message();

            IDelivery[] subscriptions = Enumerable
                                        .Range(0, 3)
                                        .Select((_, index) =>
            {
                IDelivery subscription = Substitute.For <IDelivery>();
                subscription
                .WaitAsync(Arg.Any <TimeSpan>(), Arg.Any <CancellationToken>())
                .Returns(async call =>
                {
                    TimeSpan delay = index != 1 ? call.ArgAt <TimeSpan>(0) : TimeSpan.FromSeconds(15);
                    CancellationToken cancellationToken = call.ArgAt <CancellationToken>(1);
                    await Task.Delay(delay.Add(TimeSpan.FromMilliseconds(1)), cancellationToken);
                    cancellationToken.ThrowIfCancellationRequested();
                    return(true);
                });
                return(subscription);
            })
                                        .ToArray();
            var         delivery = new TopicDelivery(message, subscriptions);
            var         cts      = new CancellationTokenSource(TimeSpan.FromMilliseconds(10));
            Task <bool> task     = delivery.WaitAsync(TimeSpan.FromMilliseconds(1), cts.Token);

            await task.ShouldCancelOperationAsync();
        }
Example #2
0
        public void OnAccept(IDelivery delivery)
        {
            Interlocked.Increment(ref numAcceptedMessages);

            modelReference.Execute(
                m => m.BasicAck(delivery.Tag, false));
        }
Example #3
0
 public void BeforePublish(IDelivery delivery, IModel publishModel, IBasicProperties properties, Action <BasicReturn> basicReturnCallback)
 {
     foreach (var module in inner)
     {
         module.BeforePublish(delivery, publishModel, properties, basicReturnCallback);
     }
 }
Example #4
0
        public string CreateDeliveryAndGetName()
        {
            IDelivery delivery = CreateDelivery();
            var       result   = "Created delivery type:  " + delivery.GetDeliveryType();

            return(result);
        }
Example #5
0
        public void OnReject(IDelivery delivery, bool requeue)
        {
            Interlocked.Increment(ref numRejectedMessages);

            modelReference.Execute(
                m => m.BasicNack(delivery.Tag, false, requeue));
        }
Example #6
0
 public Cargo(double _QualityMod, double _SellMod, IDelivery _delivery)
 {
     QualityMod  = _QualityMod;
     SellMod     = _SellMod;
     delivery    = _delivery;
     ingradients = new List <IngradientOnCargo>();
 }
Example #7
0
 public OrderedDelivery(OrderingCarrier orderingCarrier, IDelivery voucherDelivery, OrderVoucher orderVoucher, int cost)
 {
     Carrier         = orderingCarrier;
     VoucherDelivery = voucherDelivery;
     OrderVoucher    = orderVoucher;
     Cost            = cost;
 }
Example #8
0
        public void OnAccept(IDelivery delivery)
        {
            Interlocked.Increment(ref numAcceptedMessages);

            modelReference.Execute(
                m => m.BasicAck(delivery.Tag, false));
        }
Example #9
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="delivery">
		/// The new cargo <see cref="IDelivery"/> status. Will not be null.
		/// </param>
		/// <param name="completionDate">
		/// The completion <see cref="DateTime"/>
		/// </param>
		/// <exception cref="ArgumentNullException"><paramref name="delivery"/> is <value>null</value>.</exception>
		public HandlingEventArgs (IDelivery delivery, DateTime completionDate)
		{
			if (null == delivery)
				throw new ArgumentNullException ("delivery");
			Delivery = delivery;
			CompletionDate = completionDate;
		}
Example #10
0
        public void OnReject(IDelivery delivery, bool requeue)
        {
            Interlocked.Increment(ref numRejectedMessages);

            modelReference.Execute(
                m => m.BasicNack(delivery.Tag, false, requeue));
        }
Example #11
0
 private void RedisQueue_OnDelivery(IDelivery delivery)
 {
     foreach (var consumer in m_consumers)
     {
         consumer.Consume(delivery);
     }
 }
Example #12
0
 public void BeforePublish(IDelivery delivery, IModel publishModel, IBasicProperties properties, Action <BasicReturn> basicReturnCallback)
 {
     // todo: handle this, we don't want to subscribe multiple times in case of republish
     if (basicReturnCallback != null)
     {
         basicReturnHandler.Subscribe(new RogerGuid(properties.MessageId), basicReturnCallback);
     }
 }
Example #13
0
        public DeliveryProxy()
        {
            //Real = new DeliveryMockForFail();
            //Real = new DeliveryMockForConnectionFail();
            //Real = null;

            Real = new DeliveryReal(new HttpClient());
        }
        public void Process(IDelivery delivery)
        {
            var messageSerializer = messageSerializers.FindOrDefault(delivery.ContentType);
            var deserialized      = messageSerializer.Deserialize <T>(delivery.Body);
            var deliveryContext   = new DeliveryContext(bus, delivery);

            handler(deserialized.Body, deliveryContext);
        }
Example #15
0
        /// <summary>
        /// Формирует ответ на запрос.
        /// </summary>
        /// <param name="delivery">
        /// Входящее сообщение, которое является ответом.
        /// </param>
        /// <param name="responseType">
        /// Тип ответного сообщения.
        /// </param>
        /// <returns>
        /// Сообщение с ответом на запрос.
        /// </returns>
        private IMessage BuildResponse(IDelivery delivery, Type responseType)
        {
            IMessage response = delivery.UnpackAs(responseType);

            this.validatorRegistry.Validate(response);

            return(response);
        }
Example #16
0
 public OrderedGood(Goods good, int quantity, IDelivery delivery) : base(good, quantity, delivery)
 {
     this.Good         = good;
     this.Quantity     = quantity;
     this.TotalWeight  = this.Good.Weight * this.Quantity;
     this.DeliveryType = delivery;
     this.Cost         = this.DeliveryType.calculateCost(this.TotalWeight) + this.Good.Price * this.Quantity;
 }
Example #17
0
        public void Dispose_DoesNotThrow_WhenSubscriptionNotDisposable()
        {
            IDelivery subscription = Substitute.For <IDelivery>();
            var       delivery     = new TopicDelivery(new Amqp.Message(), new List <IDelivery> {
                subscription
            });

            Should.NotThrow(() => delivery.Dispose());
        }
        public void OnFailure(IDelivery delivery, Exception exception)
        {
            logger.ErrorFormat(exception, "Error Queue is handling exception");

            var error = BuildFault(delivery, exception);
            publisher.Value.Publish(error);

            delivery.Accept();
        }
Example #19
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="delivery">
 /// The new cargo <see cref="IDelivery"/> status. Will not be null.
 /// </param>
 /// <param name="completionDate">
 /// The completion <see cref="DateTime"/>
 /// </param>
 /// <exception cref="ArgumentNullException"><paramref name="delivery"/> is <value>null</value>.</exception>
 public HandlingEventArgs(IDelivery delivery, DateTime completionDate)
 {
     if (null == delivery)
     {
         throw new ArgumentNullException("delivery");
     }
     Delivery       = delivery;
     CompletionDate = completionDate;
 }
        public IActionResult BuyBook([FromBody] BuyBookModel model)
        {
            double.TryParse(model.DeliveryCost, out double cost);
            var       serviceType = (DeliveryType)Enum.Parse(typeof(DeliveryType), model.DeliveryService);
            IDelivery delivery    = _deliveryServiceGenerator.ExecuteCreation(serviceType, cost);
            var       orderInfo   = delivery.GetInfo();

            return(Ok(orderInfo));
        }
Example #21
0
        public void Handle_UpdatesDeliveryTag_WhenEventIdIsSendDeliveryAndContextIsIDelivery()
        {
            IDelivery  fakeDelivery = Substitute.For <IDelivery>();
            MethodInfo factory      = typeof(Event).GetMethod("Create", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            var        evt          = (Event)factory.Invoke(null, new object[] { EventId.SendDelivery, null, null, null, fakeDelivery });

            AzureHandler.Instance.Handle(evt);

            fakeDelivery.Tag.Length.ShouldBe(Guid.NewGuid().ToByteArray().Length);
        }
        public void OnFailure(IDelivery delivery, Exception exception)
        {
            logger.ErrorFormat(exception, "Error Queue is handling exception");

            var error = BuildFault(delivery, exception);

            publisher.Value.Publish(error);

            delivery.Accept();
        }
Example #23
0
        /// <summary>
        /// Constructs a client with the specified storage and delivery classes.
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="delivery"></param>
        /// <param name="breadcrumbs"></param>
        /// <param name="sessionTracking"></param>
        public Client(IConfiguration configuration, IDelivery delivery, IBreadcrumbs breadcrumbs, ISessionTracker sessionTracking)
        {
            _configuration   = configuration;
            _delivery        = delivery;
            _breadcrumbs     = breadcrumbs;
            _sessionTracking = sessionTracking;
            _middleware      = new List <Middleware>();

            UnhandledException.Instance.ConfigureClient(this, configuration);
        }
Example #24
0
        public async Task Wait_ReturnsTrue_WhenSubscriptionsEmpty()
        {
            var message       = new Amqp.Message();
            var subscriptions = new IDelivery[0];
            var delivery      = new TopicDelivery(message, subscriptions);

            var result = await delivery.WaitAsync(TimeSpan.FromMilliseconds(1));

            result.ShouldBeTrue();
        }
Example #25
0
        public IDelivery Get(CountryEnum country)
        {
            IDelivery result = null;

            if (deliveryDictionary.ContainsKey(country))
            {
                result = deliveryDictionary[country];
            }

            return(result);
        }
 public void Add(IDelivery delivery)
 {
     if (!_deliveries.Any(x => x.DeliveryId == delivery.DeliveryId))
     {
         _deliveries.Add(delivery);
     }
     else
     {
         throw new Exception("This delivery already exists.");
     }
 }
Example #27
0
        public void Consume(IDelivery delivery)
        {
            m_count++;
            var duration = DateTime.Now.Subtract(m_before).TotalMilliseconds;

            m_before = DateTime.Now;
            Console.WriteLine("{0} consumed {1} {2}", m_name, m_count, delivery.Payload);

            Thread.Sleep(TimeSpan.FromMilliseconds(1));

            delivery.Ack();
        }
Example #28
0
        public void Handle_DoesNotUpdateDeliveryTag_WhenEventIdIsNotSendDelivery()
        {
            IDelivery fakeDelivery = Substitute.For <IDelivery>();

            fakeDelivery.Tag = null;
            MethodInfo factory = typeof(Event).GetMethod("Create", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            var        evt     = (Event)factory.Invoke(null, new object[] { EventId.ReceiveDelivery, null, null, null, fakeDelivery });

            AzureHandler.Instance.Handle(evt);

            fakeDelivery.Tag.ShouldBeNull();
        }
Example #29
0
        public void Post_CreatesEndEnqueuesDelivery()
        {
            var message = new Amqp.Message();
            var entity  = new QueueEntity("s");

            IDelivery delivery = entity.Post(message);

            entity.ShouldSatisfyAllConditions(
                () => delivery.Message.ShouldBeSameAs(message),
                () => ((IEntity)entity).DeliveryQueue.Dequeue(CancellationToken.None).ShouldBeSameAs(message)
                );
        }
Example #30
0
        public double CalculateDeliveryCost(Order order)
        {
            if (order == null)
            {
                return(-1);
            }

            IDelivery delivery = Factory.Instance.Get(order.Country);
            double    result   = delivery.CalculateCost(order);

            return(result);
        }
Example #31
0
        public void Ctor_withValidDelivery_works()
        {
            // arrange:
            IDelivery mDelivery = MockRepository.GenerateStrictMock <IDelivery>();
            DateTime  cTime     = DateTime.UtcNow;

            // act:
            HandlingEventArgs args = new HandlingEventArgs(mDelivery, cTime);

            // assert:
            Assert.AreEqual(cTime, args.CompletionDate);
            Assert.AreSame(mDelivery, args.Delivery);
        }
        public override void Deliver(IDelivery delivery)
        {
            try
            {
                connectedProcessor.Process(delivery);
            }
            catch (Exception e)
            {
                delivery.Failed(e);
                return;
            }

            delivery.Accept();
        }
Example #33
0
        public Task DeliverOnTask(IDelivery delivery)
        {
            var worker = new TaskWorker(connectedProcessor);
            workers.TryAdd(worker.GetHashCode(), worker);

            var currentDelivery = delivery;

            return Task.Factory.StartNew(() =>
            {
                worker.Deliver(currentDelivery);

                TaskWorker removed;
                workers.TryRemove(worker.GetHashCode(), out removed);
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BusProcessingContext"/> class.
        /// </summary>
        /// <param name="delivery">Current delivery. Must not be null</param>
        /// <param name="busContext">Bus context. Must not be null</param>
        public BusProcessingContext(IDelivery delivery, IBusContext busContext)
        {
            if (delivery == null)
            {
                throw new ArgumentNullException(nameof(delivery));
            }

            if (busContext == null)
            {
                throw new ArgumentNullException(nameof(busContext));
            }

            this.Delivery   = delivery;
            this.BusContext = busContext;
        }
Example #35
0
        public void Deliver(IDelivery delivery)
        {
            BeforeDeliver();

            try
            {
                connectedProcessor.Process(delivery);
                delivery.Accept();
            }
            catch (Exception e)
            {
                delivery.Failed(e);
            }

            AfterDeliver();
        }
Example #36
0
        /// <summary>
        /// Print result
        /// </summary>
        /// <param name="delivery"></param>
        public static void Print(this IDelivery delivery)
        {
            var rule = delivery.Rule.GetDescription();
            var cost = delivery.GetCost();

            Console.WriteLine("Category: {0}", rule);

            if (cost != null)
            {
                Console.WriteLine("Cost: ${0}", cost);
            }
            else
            {
                Console.WriteLine("Cost: N/A");
            }
        }
        public Fault BuildFault(IDelivery delivery, Exception exception)
        {
            var messageAsString = Encoding.UTF8.GetString(delivery.Body);

            return new Fault
            {
                RoutingKey = delivery.RoutingKey,
                Exchange = delivery.Exchange,
                FaultedMessage = messageAsString,
                Exception = new FaultException
                {
                    Message = exception.Message,
                    Type = exception.GetType().FullName,
                    StackTrace = exception.StackTrace
                }
            };
        }
 public void OnReject(IDelivery delivery, bool requeue)
 {
     action();
 }
Example #39
0
 public void BeforePublish(IDelivery delivery, IModel publishModel, IBasicProperties properties, Action<BasicReturn> basicReturnCallback)
 {
     unconfirmedCommands.TryAdd(publishModel.NextPublishSeqNo, new UnconfirmedDeliveryFactory(delivery, consideredUnconfirmedAfter));
 }
Example #40
0
 public override void Deliver(IDelivery delivery)
 {
     DeliverOnTask(delivery);
 }
Example #41
0
 public void BeforePublish(IDelivery delivery, IModel publishModel, IBasicProperties properties, Action<BasicReturn> basicReturnCallback)
 {
     // todo: handle this, we don't want to subscribe multiple times in case of republish
     if (basicReturnCallback != null)
         basicReturnHandler.Subscribe(new RogerGuid(properties.MessageId), basicReturnCallback);
 }
 public UnconfirmedDeliveryFactory(IDelivery inner, TimeSpan? consideredUnconfirmedAfter)
 {
     created = SystemTime.Now;
     this.inner = inner;
     this.consideredUnconfirmedAfter = consideredUnconfirmedAfter;
 }
 public void OnFailure(IDelivery delivery, Exception exception)
 {
     notifier();
 }
 public void OnFailure(IDelivery delivery, Exception exception)
 {
     delivery.Reject(true);
     Thread.Sleep(5000);
 }
Example #45
0
 public void BeforePublish(IDelivery delivery, IModel publishModel, IBasicProperties properties, Action<BasicReturn> basicReturnCallback)
 {
     foreach (var module in inner)
         module.BeforePublish(delivery, publishModel, properties, basicReturnCallback);
 }
Example #46
0
        public void OnFailed(IDelivery delivery, Exception exception)
        {
            subscriptionFailureStrategy.OnFailure(delivery, exception);

            Interlocked.Increment(ref numFailedMessages);
        }
 public void OnFailed(IDelivery delivery, Exception exception)
 {
     action();
 }
 public void OnAccept(IDelivery delivery)
 {
     action();
 }
 /// <summary>
 /// Создает объект контекста.
 /// </summary>
 /// <param name="delivery">Доставка.</param>
 public BusProcessingContext(IDelivery delivery)
 {
     this.Delivery = delivery;
 }