public OutgoingTransportContext(LogicalMessage message, TransportMessage outgoingTransportMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
     : base(configuration)
 {
     this.Set(message);
     this.Set(OutgoingTransportMessageKey, outgoingTransportMessage);
     this.Set(IncomingTransportMessageKey, incomingTransportMessage);
     this.Set(options);
 }
Ejemplo n.º 2
0
 public DeliveryOptions GetDeliveryOptions(Shipment shipment)
 {
     DeliveryOptions options = new DeliveryOptions();
     if(shipment.Vendor == "USPS")
     {
         options.PurchaseInsuranceEnabled = false;
         options.RequireSignatureEnabled = false;
     }
     else
     {
         options.PurchaseInsuranceEnabled = true;
         options.RequireSignatureEnabled = true;
     }
     return options;
 }
Ejemplo n.º 3
0
        public virtual async Task Invoke(LogicalMessage outgoingLogicalMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
        {
            executingLogicalPipeline = new Queue<IOutgoingLogicalStep>(registeredlogicalPipelineSteps);
            var logicalContext = new OutgoingLogicalContext(outgoingLogicalMessage, options, configuration);
            await InvokeLogical(logicalContext)
                .ConfigureAwait(false);

            // We assume that someone in the pipeline made transport message
            var outgoingTransportMessage = logicalContext.Get<TransportMessage>();

            executingTransportPipeline = new Queue<IOutgoingTransportStep>(registeredTransportPipelineSteps);
            var transportContext = new OutgoingTransportContext(outgoingLogicalMessage, outgoingTransportMessage, options, configuration, incomingTransportMessage);
            await InvokeTransport(transportContext)
                .ConfigureAwait(false);
        }
        public static void FillKafkaProperties(TransportMessage message, DeliveryOptions options, dynamic properties)
        {
            properties.MessageId = message.Id;

            if (!String.IsNullOrEmpty(message.CorrelationId))
            {
                properties.CorrelationId = message.CorrelationId;
            }

            if (message.TimeToBeReceived < TimeSpan.MaxValue)
            {
                properties.Expiration = message.TimeToBeReceived.TotalMilliseconds.ToString();
            }

            properties.SetPersistent(message.Recoverable);

            properties.Headers = message.Headers.ToDictionary(p => p.Key, p => (object)p.Value);

            if (message.Headers.ContainsKey(Headers.EnclosedMessageTypes))
            {
                properties.Type = message.Headers[Headers.EnclosedMessageTypes].Split(new[]
                {
                    ','
                }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
            }

            if (message.Headers.ContainsKey(Headers.ContentType))
            {
                properties.ContentType = message.Headers[Headers.ContentType];
            }
            else
            {
                properties.ContentType = "application/octet-stream";
            }

            var replyToAddress = options.ReplyToAddress ?? message.ReplyToAddress;
            if (replyToAddress != null)
            {
                properties.ReplyTo = replyToAddress.Queue;
            }
        }
        private CachedDeliveryClient GetCachedDeliveryClient(Action mockAction = null, Func <RequestCount, RequestCount> mockFunc = null, RequestCount actualHttpRequests = null)
        {
            HttpClient      httpClient      = null;
            DeliveryOptions deliveryOptions = null;

            if (mockAction != null)
            {
                InitClientPrerequisites(out httpClient, out deliveryOptions, mockAction: mockAction);
            }
            else if (mockFunc != null && actualHttpRequests != null)
            {
                InitClientPrerequisites(out httpClient, out deliveryOptions, mockFunc: mockFunc, actualHttpRequests: actualHttpRequests);
            }

            var projectOptions = Options.Create(new ProjectOptions
            {
                CacheTimeoutSeconds = 60,
                DeliveryOptions     = deliveryOptions
            });

            var memoryCacheOptions = Options.Create(new MemoryCacheOptions
            {
                Clock = new TestClock(),
                ExpirationScanFrequency = new TimeSpan(0, 0, 5)
            });

            var cacheManager = new ReactiveCacheManager(projectOptions, new MemoryCache(memoryCacheOptions), new DependentFormatResolver(), new WebhookListener());

            return(new CachedDeliveryClient(projectOptions, cacheManager
                                            , new DeliveryClient(deliveryOptions)
            {
                HttpClient = httpClient
            })
            {
                CodeFirstModelProvider = { TypeProvider = new Models.CustomTypeProvider() }
            });
        }
        public async void Retries_WithMaxRetrySet_SettingReflected()
        {
            int retryAttempts          = 3;
            int expectedAttepts        = retryAttempts + 1;
            int actualHttpRequestCount = 0;

            _mockHttp.When($"{_baseUrl}/items")
            .Respond((request) => GetResponseAndLogRequest(HttpStatusCode.RequestTimeout, ref actualHttpRequestCount));
            var httpClient = _mockHttp.ToHttpClient();

            var deliveryOptions = new DeliveryOptions()
            {
                ProjectId        = _guid,
                MaxRetryAttempts = retryAttempts
            };
            var client = new DeliveryClient(deliveryOptions)
            {
                HttpClient = httpClient
            };

            await Assert.ThrowsAsync <DeliveryException>(async() => await client.GetItemsAsync());

            Assert.Equal(expectedAttepts, actualHttpRequestCount);
        }
Ejemplo n.º 7
0
 public void Save(int orderId, DeliveryOptions deliveryOptionsToSave)
 {
     this.deliveryOptions.Add(orderId, deliveryOptionsToSave);
 }
Ejemplo n.º 8
0
 public OutgoingTransportContext(LogicalMessage message, TransportMessage outgoingTransportMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
     : base(configuration)
 {
     Set(message);
     Set(OutgoingTransportMessageKey, outgoingTransportMessage);
     Set(IncomingTransportMessageKey, incomingTransportMessage);
     Set(options);
 }
        /// <summary>
        /// Registers a <see cref="IDeliveryClient"/> instance to an <see cref="IDeliveryClient"/> interface in <see cref="ServiceCollection"/>.
        /// </summary>
        /// <param name="services">A <see cref="ServiceCollection"/> instance for registering and resolving dependencies.</param>
        /// <param name="deliveryOptions">A <see cref="DeliveryOptions"/> instance.  Options themselves are not further validated (see <see cref="DeliveryOptionsValidator.Validate"/>).</param>
        /// <returns>The <paramref name="services"/> instance with <see cref="IDeliveryClient"/> registered in it</returns>
        public static IServiceCollection AddDeliveryClient(this IServiceCollection services, DeliveryOptions deliveryOptions)
        {
            if (deliveryOptions == null)
            {
                throw new ArgumentNullException(nameof(deliveryOptions), "The Delivery options object is not specified.");
            }

            return(services
                   .RegisterOptions(deliveryOptions)
                   .RegisterDependencies());
        }
        /// <summary>
        /// Registers a delegate that will be used to configure a named <see cref="IDeliveryClient"/> via <see cref="IDeliveryClientFactory"/>
        /// </summary>
        ///<param name="name">The name of the client configuration</param>
        /// <param name="services">A <see cref="ServiceCollection"/> instance for registering and resolving dependencies.</param>
        /// <param name="deliveryOptions">A <see cref="DeliveryOptions"/> instance.  Options themselves are not further validated (see <see cref="DeliveryOptionsValidator.Validate"/>).</param>
        /// <returns>The <paramref name="services"/> instance with <see cref="IDeliveryClient"/> registered in it</returns>
        public static IServiceCollection AddDeliveryClient(this IServiceCollection services, string name, DeliveryOptions deliveryOptions)
        {
            if (deliveryOptions == null)
            {
                throw new ArgumentNullException(nameof(deliveryOptions), "The Delivery options object is not specified.");
            }

            services.AddTransient <IConfigureOptions <DeliveryClientFactoryOptions> >(s =>
            {
                return(new ConfigureNamedOptions <DeliveryClientFactoryOptions>(name, options =>
                {
                    options.DeliveryClientsActions.Add(() =>
                    {
                        services.AddDeliveryClient(deliveryOptions);
                        var serviceProvider = services.BuildServiceProvider();
                        return serviceProvider.GetService <IDeliveryClient>();
                    });
                }));
            });

            return(services
                   .Configure <DeliveryClientFactoryOptions>(_ => { })
                   .RegisterFactoryDependencies());
        }
Ejemplo n.º 11
0
 public void Send(Payload payload, DeliveryOptions deliveryOptions, Guid sessionId)
 {
     _roomSender.Send(payload, deliveryOptions, sessionId);
 }
Ejemplo n.º 12
0
        public void ProcessMessage(Payload message, DeliveryOptions deliveryOptions, Guid sessionId)
        {
            var operationCode = MessageBase.GetOperationCode(message.Buffer, message.Offset);

            Trace($"Message {operationCode} received");
        }
Ejemplo n.º 13
0
        // Options here are not validated on purpose, it is left to users to validate them if they want to.
        private static IServiceCollection RegisterOptions(this IServiceCollection services, DeliveryOptions options, string name = null)
        {
            void Configure(DeliveryOptions o)
            {
                o.ProjectId                 = options.ProjectId;
                o.ProductionEndpoint        = options.ProductionEndpoint;
                o.PreviewEndpoint           = options.PreviewEndpoint;
                o.PreviewApiKey             = options.PreviewApiKey;
                o.UsePreviewApi             = options.UsePreviewApi;
                o.WaitForLoadingNewContent  = options.WaitForLoadingNewContent;
                o.UseSecureAccess           = options.UseSecureAccess;
                o.SecureAccessApiKey        = options.SecureAccessApiKey;
                o.EnableRetryPolicy         = options.EnableRetryPolicy;
                o.DefaultRetryPolicyOptions = options.DefaultRetryPolicyOptions;
                o.IncludeTotalCount         = options.IncludeTotalCount;
            }

            if (name == null)
            {
                services.Configure <DeliveryOptions>(Configure);
            }
            else
            {
                services.Configure <DeliveryOptions>(name, Configure);
            }

            return(services);
        }
Ejemplo n.º 14
0
        public Scenario(IDistributedCache distributedCache, CacheExpirationType cacheExpirationType, HttpClient httpClient, DeliveryOptions deliveryOptions, Dictionary <string, int> requestCounter)
        {
            _requestCounter = requestCounter;
            _cacheManager   = new DistributedCacheManager(distributedCache, Options.Create(new DeliveryCacheOptions {
                DefaultExpirationType = cacheExpirationType
            }));
            var baseClient = DeliveryClientBuilder.WithOptions(_ => deliveryOptions).WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            CachingClient = new DeliveryClientCache(_cacheManager, baseClient);
        }
Ejemplo n.º 15
0
 public PacketInfo(DeliveryOptions deliveryOptions, int maxPacketSize,
                   IShamanLogger logger, Payload payload) : this(deliveryOptions, maxPacketSize, logger, (int)payload.Length)
 {
     AppendLength(payload.Length);
     AppendPayload(payload);
 }
        public void EnableOrDisableTheInsuranceAndSignatureCheckboxesWhenShippingOptionChanges()
        {
            // Setting up the expected set of Delivery options
            DeliveryOptions deliveryOptions = new DeliveryOptions();
            deliveryOptions.PurchaseInsuranceEnabled = true;
            deliveryOptions.RequireSignatureEnabled = false;

            // Set up the expectations for coordinating both
            // the service and the view
            using (mocks.Record())
            {
                service.CalculateCost(null);
                LastCall.IgnoreArguments();
                Expect.Call(service.GetDeliveryOptions(presenter.Shipment)).Return(deliveryOptions);
                screen.InsuranceEnabled = deliveryOptions.PurchaseInsuranceEnabled;
                screen.SignatureEnabled = deliveryOptions.RequireSignatureEnabled;
            }

            // Perform the work and check the expectations
            using (mocks.Playback())
            {
                presenter.ShippingOptionChanged();
                mocks.VerifyAll();
            }
        }
Ejemplo n.º 17
0
 public void SendToAll(Payload payload, DeliveryOptions deliveryOptions)
 {
     _roomSender.SendToAll(payload, deliveryOptions);
 }
Ejemplo n.º 18
0
 public void SendToAll(Payload payload, DeliveryOptions deliveryOptions, Guid exceptionSessionId)
 {
     _roomSender.SendToAll(payload, deliveryOptions, exceptionSessionId);
 }
Ejemplo n.º 19
0
 public void Send(Payload payload, DeliveryOptions deliveryOptions, IEnumerable <Guid> sessionIds)
 {
     _roomSender.Send(payload, deliveryOptions, sessionIds);
 }
Ejemplo n.º 20
0
        private void ProcessMessage(IPEndPoint endPoint, Payload payload,
                                    DeliveryOptions deliveryOptions,
                                    GamePeer peer)
        {
            var operationCode = MessageBase.GetOperationCode(payload.Buffer, payload.Offset);

            _logger.Debug($"Message received. Operation code: {operationCode}");

            if (peer == null)
            {
                _logger.Warning($"GamePeerListener.OnReceivePacketFromClient error: can not find peer for endpoint {endPoint.Address}:{endPoint.Port}");
                return;
            }

            //listener handles only auth message, others are sent to roomManager
            switch (operationCode)
            {
            case ShamanOperationCode.Connect:
                _logger.Error($"Sending ConnectedEvent to peer {peer.GetPeerId()}");
                _messageSender.Send(new ConnectedEvent(), peer);
                break;

            case ShamanOperationCode.Ping:
                _messageSender.Send(new PingEvent(), peer);
                break;

            case ShamanOperationCode.Disconnect:
                OnClientDisconnect(endPoint, new SimpleDisconnectInfo(ShamanDisconnectReason.PeerLeave));
                break;

            case ShamanOperationCode.Authorization:
                var authMessage = Serializer.DeserializeAs <AuthorizationRequest>(payload.Buffer, payload.Offset, payload.Length);

                if (!Config.IsAuthOn)
                {
                    //if success - send auth success
                    peer.IsAuthorizing = false;
                    peer.IsAuthorized  = true;
                    //this sessionID will be got from backend, after we send authToken, which will come in player properties
                    peer.SetSessionId(authMessage.SessionId);
                    _messageSender.Send(new AuthorizationResponse(), peer);
                }
                else
                {
                    //TODO authorizing logic
                    throw new NotImplementedException();
                }
                break;

            default:
                if (!peer.IsAuthorized && Config.IsAuthOn)
                {
                    _messageSender.Send(new AuthorizationResponse()
                    {
                        ResultCode = ResultCode.NotAuthorized
                    }, peer);
                    return;
                }
                else
                {
                    if (!peer.IsAuthorized)
                    {
                        _messageSender.Send(new AuthorizationResponse(), peer);
                    }
                }

                switch (operationCode)
                {
                default:
                    _roomManager.ProcessMessage(operationCode, payload, deliveryOptions, peer);
                    break;
                }

                break;
            }
        }
        static void SetHeaders(TransportMessage message, DeliveryOptions options, ReadOnlySettings settings, Configure config, BrokeredMessage brokeredMessage)
        {
            foreach (var header in message.Headers)
            {
                brokeredMessage.Properties[header.Key] = header.Value;
            }

            brokeredMessage.Properties[Headers.MessageIntent] = message.MessageIntent.ToString();
            brokeredMessage.MessageId = message.Id;
            brokeredMessage.CorrelationId = message.CorrelationId;

            if (message.ReplyToAddress != null)
            {
                brokeredMessage.ReplyTo = new DeterminesBestConnectionStringForAzureServiceBus(config.TransportConnectionString()).Determine(settings, message.ReplyToAddress);
            }
            else if (options.ReplyToAddress != null)
            {
                brokeredMessage.ReplyTo = new DeterminesBestConnectionStringForAzureServiceBus(config.TransportConnectionString()).Determine(settings, options.ReplyToAddress);
            }
        }
Ejemplo n.º 22
0
 public async Task <MessageStatus> PublishAsync(object message, DeliveryOptions deliveryOptions)
 {
     return(await PublishAsync(message, DEFAULT_CHANNEL_NAME, null, deliveryOptions));
 }
Ejemplo n.º 23
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureServices((hostContext, services) =>
        {
            var configuration = hostContext.Configuration;

            // Add logging
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();
            services.AddLogging(c => c.AddSerilog());

            // Add application options
            services.AddDataRepositories(configuration);

            // Add options
            services.Configure <DeliveryOptions>(configuration.GetSection(nameof(DeliveryOptions)));
            services.Configure <RabbitMqOptions>(configuration.GetSection(nameof(RabbitMqOptions)));

            RabbitMqOptions rabbitmqOptions = null;
            DeliveryOptions deliveryOptions = null;
            IEnumerable <Subscription> subscriptions;

            using (var provider = services.BuildServiceProvider())
            {
                rabbitmqOptions = provider.GetService <IOptions <RabbitMqOptions> >().Value;
                deliveryOptions = provider.GetService <IOptions <DeliveryOptions> >().Value;
                subscriptions   = provider.GetService <ISubscriptonsRepository>().GetSubscriptions(true).Result;
            }

            #region MassTransit config
            services.AddMassTransit(x =>
            {
                x.AddBus(busContext => Bus.Factory.CreateUsingRabbitMq(config =>
                {
                    config.Host(rabbitmqOptions.Uri, h =>
                    {
                        h.Username(rabbitmqOptions.Username);
                        h.Password(rabbitmqOptions.Password);
                    });

                    #region Command consumers

                    x.AddConsumer <ActivateSubscriptionConsumer>();
                    config.ReceiveEndpoint(queueName: typeof(ActivateSubscription).FullName, c =>
                    {
                        c.ConfigureConsumeTopology = false;
                        c.ConfigureConsumer <ActivateSubscriptionConsumer>(busContext);
                    });

                    x.AddConsumer <DeactivateSubscriptionConsumer>();
                    config.ReceiveEndpoint(queueName: typeof(DeactivateSubscription).FullName, c =>
                    {
                        c.ConfigureConsumeTopology = false;
                        c.ConfigureConsumer <DeactivateSubscriptionConsumer>(busContext);
                    });

                    #endregion

                    #region Event consumers
                    foreach (var subscription in subscriptions)
                    {
                        var eventType = DomainEventsHelper.GetDomainEventTypes().SingleOrDefault(t => t.FullName == subscription.Event);
                        if (eventType == null)
                        {
                            continue;         // TODO: Log invalid event
                        }
                        #region Add event consumers
                        var addConsumerMethod = x.GetType()
                                                .GetMethods().Single(m => m.Name == nameof(IServiceCollectionBusConfigurator.AddConsumer) &&
                                                                     m.ContainsGenericParameters &&
                                                                     m.GetParameters().Length == 1 &&
                                                                     m.GetParameters()[0].ParameterType.IsGenericType &&
                                                                     m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Action <>)
                                                                     )
                                                .MakeGenericMethod(typeof(DomainEventConsumer <>).MakeGenericType(eventType));
                        addConsumerMethod.Invoke(x, new object[] { null });

                        //x.AddConsumer(eventType);
                        //x.AddConsumer<DomainEventConsumer<OperationCompletedEvent>>();

                        #endregion

                        #region Configure event consumers
                        config.ReceiveEndpoint(queueName: $"{subscription.Event}_{subscription.Id}", c =>
                        {
                            c.Bind(exchangeName: eventType.FullName);
                            c.UseMessageRetry(r => r.Interval(deliveryOptions.Attempts, TimeSpan.FromSeconds(deliveryOptions.AttemptDelay)));
                            c.ConfigureConsumeTopology  = false;
                            var configureConsumerMethod = typeof(RegistrationContextExtensions)
                                                          .GetMethods().Single(m => m.Name == nameof(RegistrationContextExtensions.ConfigureConsumer) &&
                                                                               m.ContainsGenericParameters &&
                                                                               m.GetParameters().Length == 3 &&
                                                                               m.GetParameters()[0].ParameterType == typeof(IReceiveEndpointConfigurator) &&
                                                                               m.GetParameters()[1].ParameterType == typeof(IRegistration) &&
                                                                               m.GetParameters()[2].ParameterType.IsGenericType &&
                                                                               m.GetParameters()[2].ParameterType.GetGenericTypeDefinition() == typeof(Action <>)
                                                                               )
                                                          .MakeGenericMethod(typeof(DomainEventConsumer <>).MakeGenericType(eventType));

                            configureConsumerMethod.Invoke(null, new object[] { c, busContext, null });

                            //c.ConfigureConsumer(busContext, eventType);
                            //c.ConfigureConsumer<DomainEventConsumer<OperationCompletedEvent>>(busContext);
                        });
                        #endregion
                    }
                    #endregion
                }));
            });

            services.AddScoped <ActivateSubscriptionConsumer>();
            services.AddScoped <DeactivateSubscriptionConsumer>();

            foreach (var @event in DomainEventsHelper.GetDomainEventTypes())
            {
                services.AddScoped(typeof(DomainEventConsumer <>).MakeGenericType(@event));
            }

            #endregion

            #region HttpClientFactory config
            services.AddHttpClient(HttpClientNames.WebhookSubscriptionHttpClient, c =>
            {
                if (deliveryOptions.Timeout > 0)
                {
                    c.Timeout = TimeSpan.FromSeconds(deliveryOptions.Timeout);
                }
            });
            #endregion

            services.AddHostedService <Worker>();
        });
Ejemplo n.º 24
0
 public async Task <MessageStatus> PublishAsync(object message, string channelName, PublishOptions publishOptions,
                                                DeliveryOptions deliveryOptions)
 {
     return(await Task.Run(() => Publish( message, channelName, publishOptions, deliveryOptions ))
            .ConfigureAwait(false));
 }
Ejemplo n.º 25
0
 public IEnumerable <DeliveryPrice> GetDeliveryPrices(DateTime postDate, string originalZipCode, string deliveryZipCode, DeliveryOptions deliveryOptions,
                                                      int height, int width, int length, float weight)
 {
     return(GetDeliveryPricesAsync(postDate, originalZipCode, deliveryZipCode, deliveryOptions, height, width, length, weight).Result);
 }
        /// <summary>
        /// Registers a delegate that will be used to configure a named <see cref="IDeliveryClient"/> via <see cref="IDeliveryClientFactory"/>
        /// </summary>
        ///<param name="name">The name of the client configuration</param>
        /// <param name="services">A <see cref="ServiceCollection"/> instance for registering and resolving dependencies.</param>
        /// <param name="deliveryOptions">A <see cref="DeliveryOptions"/> instance.  Options themselves are not further validated (see <see cref="DeliveryOptionsValidator.Validate"/>).</param>
        /// <param name="namedServiceProviderType">A named service provider type.</param>
        /// <returns>The <paramref name="services"/> instance with <see cref="IDeliveryClient"/> registered in it</returns>
        public static IServiceCollection AddDeliveryClient(this IServiceCollection services, string name, DeliveryOptions deliveryOptions, NamedServiceProviderType namedServiceProviderType = NamedServiceProviderType.None)
        {
            if (deliveryOptions == null)
            {
                throw new ArgumentNullException(nameof(deliveryOptions), "The Delivery options object is not specified.");
            }

            deliveryOptions.Name = name;

            return(services
                   .RegisterOptions(deliveryOptions, name)
                   .RegisterDependencies(true)
                   .RegisterNamedServices(namedServiceProviderType));
        }
Ejemplo n.º 27
0
 public async Task <MessageStatus> PublishAsync(object message, string channelName, DeliveryOptions deliveryOptions)
 {
     return(await PublishAsync(message, channelName, null, deliveryOptions));
 }
Ejemplo n.º 28
0
        private FormUrlEncodedContent CreateDeliveryPriceRequest(DateTime postDate, string originalZipCode, string deliveryZipCode, DeliveryOptions deliveryOption,
                                                                 int height, int width, int length, float weight)
        {
            string deliveryOptionValue = deliveryOption.GetAttributeValue();

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("data", postDate.ToString("dd/MM/yyyy")),
                new KeyValuePair <string, string>("dataAtual", DateTime.Now.ToString("dd/MM/yyyy")),
                new KeyValuePair <string, string>("cepOrigem", originalZipCode),
                new KeyValuePair <string, string>("cepDestino", deliveryZipCode),

                new KeyValuePair <string, string>("servico", deliveryOptionValue),

                new KeyValuePair <string, string>("embalagem1", "outraEmbalagem1"), //TODO: Give to user the options

                new KeyValuePair <string, string>("Altura", height.ToString()),
                new KeyValuePair <string, string>("Largura", width.ToString()),
                new KeyValuePair <string, string>("Comprimento", length.ToString()),
                new KeyValuePair <string, string>("peso", weight.ToString(CultureInfo.InvariantCulture)),


                new KeyValuePair <string, string>("Selecao", ""),
                new KeyValuePair <string, string>("embalagem2", ""),
                new KeyValuePair <string, string>("Selecao1", ""),
                new KeyValuePair <string, string>("proCod_in_1", ""),
                new KeyValuePair <string, string>("nomeEmbalagemCaixa", ""),
                new KeyValuePair <string, string>("TipoEmbalagem1", ""),
                new KeyValuePair <string, string>("Selecao2", ""),
                new KeyValuePair <string, string>("proCod_in_2", ""),
                new KeyValuePair <string, string>("TipoEmbalagem2", ""),
                new KeyValuePair <string, string>("Selecao3", ""),
                new KeyValuePair <string, string>("proCod_in_3", ""),
                new KeyValuePair <string, string>("TipoEmbalagem3", ""),
                new KeyValuePair <string, string>("Selecao4", ""),
                new KeyValuePair <string, string>("proCod_in_4", ""),
                new KeyValuePair <string, string>("TipoEmbalagem4", ""),
                new KeyValuePair <string, string>("Selecao5", ""),
                new KeyValuePair <string, string>("proCod_in_5", ""),
                new KeyValuePair <string, string>("TipoEmbalagem5", ""),
                new KeyValuePair <string, string>("Selecao6", ""),
                new KeyValuePair <string, string>("proCod_in_6", ""),
                new KeyValuePair <string, string>("TipoEmbalagem6", ""),
                new KeyValuePair <string, string>("Selecao7", ""),
                new KeyValuePair <string, string>("proCod_in_7", ""),
                new KeyValuePair <string, string>("TipoEmbalagem7", ""),
                new KeyValuePair <string, string>("Selecao8", ""),
                new KeyValuePair <string, string>("proCod_in_8", ""),
                new KeyValuePair <string, string>("nomeEmbalagemEnvelope", ""),
                new KeyValuePair <string, string>("TipoEmbalagem8", ""),
                new KeyValuePair <string, string>("Selecao9", ""),
                new KeyValuePair <string, string>("proCod_in_9", ""),
                new KeyValuePair <string, string>("TipoEmbalagem9", ""),
                new KeyValuePair <string, string>("Selecao10", ""),
                new KeyValuePair <string, string>("proCod_in_10", ""),
                new KeyValuePair <string, string>("Selecao11", ""),
                new KeyValuePair <string, string>("proCod_in_11", ""),
                new KeyValuePair <string, string>("Selecao12", ""),
                new KeyValuePair <string, string>("proCod_in_12", ""),
                new KeyValuePair <string, string>("TipoEmbalagem12", ""),
                new KeyValuePair <string, string>("Selecao13", ""),
                new KeyValuePair <string, string>("proCod_in_13", ""),
                new KeyValuePair <string, string>("TipoEmbalagem13", ""),
                new KeyValuePair <string, string>("valorDeclarado", ""),
                new KeyValuePair <string, string>("Calcular", "Calcular"),
            });

            return(content);
        }
        // Options here are not validated on purpose, it is left to users to validate them if they want to.
        private static IServiceCollection RegisterOptions(this IServiceCollection services, DeliveryOptions options)
        {
            services.TryAddSingleton(Options.Options.Create(options));

            return(services);
        }
Ejemplo n.º 30
0
        public async Task <IEnumerable <DeliveryPrice> > GetDeliveryPricesAsync(DateTime postDate, string originalZipCode, string deliveryZipCode, DeliveryOptions deliveryOptions,
                                                                                int height, int width, int length, float weight)
        {
            originalZipCode = originalZipCode.Replace(".", "").Replace("-", "");
            deliveryZipCode = deliveryZipCode.Replace(".", "").Replace("-", "");

            if (height < 2 || height > 100)
            {
                throw new PackageSizeException("A altura da caixa deve ter no mínimo 2cm e no máximo 100cm");
            }

            if (width < 11 || width > 100)
            {
                throw new PackageSizeException("A largura da caixa deve ter no mínimo 11cm e no máximo 100cm");
            }

            if (length < 16 || length > 100)
            {
                throw new PackageSizeException("O comprimento da caixa deve ter no mínimo 16cm e no máximo 100cm");
            }

            if (height + width + length > 200)
            {
                throw new PackageSizeException("A soma resultante do comprimento + largura + altura não deve superar 200 cm");
            }


            if (weight < 0.3f)
            {
                weight = 0.3f;
            }
            else if (weight > 0.3f && weight < 1)
            {
                weight = 1f;
            }
            else if (weight != 0.3f)
            {
                weight = (float)Math.Ceiling(weight);
            }

            Array values = Enum.GetValues(typeof(DeliveryOptions));
            List <DeliveryPrice> deliveryPrices = new List <DeliveryPrice>();

            foreach (DeliveryOptions option in values)
            {
                if (deliveryOptions.HasFlag(option))
                {
                    var body = CreateDeliveryPriceRequest(postDate, originalZipCode, deliveryZipCode, option, height, width, length, weight);

                    using (var response = await _httpClient.PostAsync(DELIVERY_PRICES_ADDRESS_URL, body))
                    {
                        var html  = response.Content.ReadAsStringAsync().Result;
                        var price = Parser.ParseDeliveryPrices(option.GetAttributeDescription(), html);

                        deliveryPrices.Add(price);
                    }
                }
            }

            return(deliveryPrices);
        }
        // Options here are not validated on purpose, it is left to users to validate them if they want to.
        private static IServiceCollection RegisterOptions(this IServiceCollection services, DeliveryOptions options)
        {
            services.Configure <DeliveryOptions>(o =>
            {
                o.ProjectId                 = options.ProjectId;
                o.ProductionEndpoint        = options.ProductionEndpoint;
                o.PreviewEndpoint           = options.PreviewEndpoint;
                o.PreviewApiKey             = options.PreviewApiKey;
                o.UsePreviewApi             = options.UsePreviewApi;
                o.WaitForLoadingNewContent  = options.WaitForLoadingNewContent;
                o.UseSecureAccess           = options.UseSecureAccess;
                o.SecureAccessApiKey        = options.SecureAccessApiKey;
                o.EnableRetryPolicy         = options.EnableRetryPolicy;
                o.DefaultRetryPolicyOptions = options.DefaultRetryPolicyOptions;
                o.IncludeTotalCount         = options.IncludeTotalCount;
            });

            return(services);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Creates a new instance of <see cref="OutgoingContext"/>.
 /// </summary>
 /// <param name="parentContext">The parent context.</param>
 /// <param name="deliveryOptions">The delivery options.</param>
 /// <param name="message">The actual message to be sent out.</param>
 public OutgoingContext(BehaviorContext parentContext, DeliveryOptions deliveryOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(deliveryOptions);
     Set(OutgoingLogicalMessageKey, message);
 }
 private static IServiceCollection RegisterOptions(this IServiceCollection services, DeliveryOptions options)
 {
     return(services.Configure <DeliveryOptions>((o) => o.Configure(options)));
 }
Ejemplo n.º 34
0
 public OutgoingLogicalContext(LogicalMessage message, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration)
     : base(configuration)
 {
     Set(message);
     Set(options);
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Creates a new instance of <see cref="OutgoingContext"/>.
 /// </summary>
 /// <param name="parentContext">The parent context.</param>
 /// <param name="deliveryOptions">The delivery options.</param>
 /// <param name="message">The actual message to be sent out.</param>
 public OutgoingContext(BehaviorContext parentContext, DeliveryOptions deliveryOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(deliveryOptions);
     Set(OutgoingLogicalMessageKey, message);
 }
Ejemplo n.º 36
0
        public void ProcessMessage(ushort operationCode, Payload message, DeliveryOptions deliveryOptions,
                                   IPeer peer)
        {
            try
            {
                //room manager handles only room flow messages, others are sent to particular room
                var sessionId = peer.GetSessionId();

                switch (operationCode)
                {
                case ShamanOperationCode.JoinRandomRoom:
                    var joinRandomRoomMessage = _serializer.DeserializeAs <DirectJoinRandomRoomRequest>(message.Buffer, message.Offset, message.Length);
                    var roomToRandomJoin      = GetRandomRoomOrCreateOne(sessionId, joinRandomRoomMessage.RoomProperties);

                    if (roomToRandomJoin == null)
                    {
                        var msg = $"Error joining random room";
                        _logger.Error(msg);
                        _messageSender.Send(new JoinRoomResponse()
                        {
                            ResultCode = ResultCode.RequestProcessingError
                        }, peer);
                    }
                    else
                    {
                        JoinRoomAndReport(roomToRandomJoin, sessionId, peer, joinRandomRoomMessage.JoinProperties,
                                          new DirectJoinRandomRoomResponse(roomToRandomJoin.GetRoomId()),
                                          new DirectJoinRandomRoomResponse()
                        {
                            ResultCode = ResultCode.RequestProcessingError
                        });
                    }

                    break;

                case ShamanOperationCode.JoinRoom:
                    var joinMessage = _serializer.DeserializeAs <JoinRoomRequest>(message.Buffer, message.Offset, message.Length);

                    var roomToJoin = GetRoomById(joinMessage.RoomId);

                    if (roomToJoin == null)
                    {
                        var msg = $"Peer {sessionId} attempted to join to non-exist room {joinMessage.RoomId}";
                        _logger.Error(msg);
                        _messageSender.Send(new JoinRoomResponse()
                        {
                            ResultCode = ResultCode.RequestProcessingError
                        }, peer);
                    }
                    else
                    {
                        JoinRoomAndReport(roomToJoin, sessionId, peer, joinMessage.Properties,
                                          new JoinRoomResponse(),
                                          new JoinRoomResponse()
                        {
                            ResultCode = ResultCode.RequestProcessingError
                        });
                    }

                    break;

                case ShamanOperationCode.LeaveRoom:
                    PeerDisconnected(peer, new SimpleDisconnectInfo(ShamanDisconnectReason.PeerLeave));
                    break;

                case ShamanOperationCode.Bundle:
                    if (_sessionsToRooms.TryGetValue(peer.GetSessionId(), out var room))
                    {
                        room.ProcessMessage(message, deliveryOptions, peer.GetSessionId());
                    }
                    else
                    {
                        _logger.Error($"ProcessMessage error: Can not get room for peer {peer.GetSessionId()}");
                        _messageSender.Send(new ErrorResponse()
                        {
                            ResultCode = ResultCode.MessageProcessingError
                        }, peer);
                    }

                    break;

                default:
                    throw new RoomManagerException($"Unknown operation code received: {operationCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"RoomManager.ProcessMessage: Error processing {operationCode} message: {ex}");
                _messageSender.Send(new ErrorResponse()
                {
                    ResultCode = ResultCode.MessageProcessingError
                }, peer);
            }
        }
 public OutgoingLogicalContext(LogicalMessage message, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration)
     : base(configuration)
 {
     this.Set(message);
     this.Set(options);
 }
 public LightDeliveryClient(DeliveryOptions options)
 {
     Options = options;
 }