Пример #1
0
        internal List <VolumeModel> LoadFromService(string distributorId)
        {
            var proxy = GetProxy();

            try
            {
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetDistributorVolumeResponse_V01>();

                var countryCode      = Thread.CurrentThread.CurrentUICulture.Name.Substring(3);
                var currentLocalTime = DateUtils.GetCurrentLocalTime(countryCode);
                var getVolumeRequest = new GetDistributorVolumeRequest_V01
                {
                    DistributorID = distributorId,
                    StartDate     = DateTimeUtils.GetFirstDayOfMonth(currentLocalTime.AddMonths(-1)),
                    EndDate       = DateTimeUtils.GetLastDayOfMonth(currentLocalTime)
                };
                var response =
                    circuitBreaker.Execute(
                        () => proxy.GetDistributorVolumePoints(new GetDistributorVolumePointsRequest(getVolumeRequest)).GetDistributorVolumePointsResult as GetDistributorVolumeResponse_V01);

                if (response == null)
                {
                    LoggerHelper.Error("Null response was returned for " + distributorId);
                    return(null);
                }

                if (response.Status == ServiceResponseStatusType.Success)
                {
                    return(GetVolumeViewModel(response.VolumePoints, countryCode, distributorId));
                }

                LoggerHelper.Error(
                    string.Format(
                        "VolumeProvider.LoadFromService Error. Unsuccessful result from web service. Status: {0}",
                        response.Status));
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(string.Format("Exception occured Load Volume method {0}\n{1}",
                                                 distributorId, ex));
                throw;
            }
            finally
            {
                if (null != proxy)
                {
                    proxy.Close();
                }
            }
            return(null);
        }
        public Dictionary <DateTime, DateTime> Load(string countryCode, DateTime localNow)
        {
            if (string.IsNullOrWhiteSpace(countryCode))
            {
                throw new ArgumentException("CountryCode is blank", "countryCode");
            }
            var fromDate = DateTimeUtils.GetFirstDayOfMonth(localNow);
            var toDate   = DateTimeUtils.GetLastDayOfMonth(localNow);

            var proxy = ServiceClientProvider.GetCatalogServiceProxy();

            try
            {
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetDualMonthDatesResponse_V01>();

                var response =
                    circuitBreaker.Execute(() => proxy.GetDualMonthDates(new GetDualMonthDatesRequest1(new GetDualMonthDatesRequest_V01
                {
                    CountryCode = countryCode,
                    FromDate    = fromDate,
                    ToDate      = toDate
                })).GetDualMonthDatesResult as GetDualMonthDatesResponse_V01);
                if (response != null && response.Status == ServiceResponseStatusType.Success)
                {
                    return(GetDualMonthDictionary(response.DualMonth, localNow));
                }
            }
            catch
            {
                LoggerHelper.Error("Errored out in GetDualOrderMonth" + countryCode);
                if (null != proxy)
                {
                    proxy.Close();
                }
                throw;
            }
            finally
            {
                if (null != proxy)
                {
                    proxy.Close();
                }
            }
            LoggerHelper.Error("Errored out in GetDualOrderMonth Catalog service" + countryCode);
            return(null);
        }
        public static List <InvoiceCRMConatactModel> GetCustomersFromService(List <string> memberIds, string CountryCode)
        {
            var contacts = new List <InvoiceCRMConatactModel>();
            var proxy    = ServiceClientProvider.GetCRMContactServiceProxy();

            try
            {
                var getCrmContactForMultipleDistributorsRequest = new GetCrmContactForMultipleDistributorsRequest
                {
                    DetailLevel      = (ContactListDetailLevel)Enum.Parse(typeof(ContactListDetailLevel), "2"),
                    SearchDescriptor = new ContactSearchFilterDescriptor
                    {
                        Filters = CreateContactFilters(),
                    },
                    DistributorIds      = memberIds,
                    ShowMultipleAddress = true,
                    Take = 1000,
                };

                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetCrmContactsForMultipleDistributorsResponse>();
                var response = circuitBreaker.Execute(() => proxy.GetContacts(new GetContactsRequest(getCrmContactForMultipleDistributorsRequest)).GetContactsResult as GetCrmContactsForMultipleDistributorsResponse);

                if (response == null)
                {
                    LoggerHelper.Warn($"Get customer for ds {string.Join(",", memberIds)} failed: response is null.");
                    return(null);
                }

                if (response.Contacts != null)
                {
                    contacts = PopulateCustomerList(response.Contacts.ToList(), CountryCode);
                }

                return(contacts);
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(string.Format("GetContacts  error : {0}", ex.Message));
            }
            finally
            {
                proxy.Close();
            }
            return(contacts);
        }
Пример #4
0
        public void ShouldReturnSameBreakerWhenCreateMultiple()
        {
            // given
            var optionMock = new Mock <IOptions <CircuitBreakerOptions> >();

            var opt = new CircuitBreakerOptions();

            optionMock.Setup(x => x.Value).Returns(opt);

            var factory = new CircuitBreakerFactory(optionMock.Object);

            // when
            var cb  = factory.CreateCircuitBreaker("test");
            var cb2 = factory.CreateCircuitBreaker("test");

            // then
            cb.Should().BeEquivalentTo(cb2);
        }
Пример #5
0
        public static BankSlipData GetBankSlipData(string orderNumber)
        {
            var proxy = ServiceClientProvider.GetOrderServiceProxy();

            try
            {
                var request = new GetBankSlipReprintDataRequest_V01
                {
                    OrderNumber = orderNumber
                };

                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetBankSlipReprintDataResponse_V01>();

                var response =
                    circuitBreaker.Execute(() => proxy.GetBankSlipReprintData(new GetBankSlipReprintDataRequest1(request))).GetBankSlipReprintDataResult as
                    GetBankSlipReprintDataResponse_V01;

                if (response != null && response.Status == ServiceResponseStatusType.Success)
                {
                    return(response.BankSlipData);
                }
            }
            catch (Exception ex)
            {
                WebUtilities.LogServiceExceptionWithContext(ex, proxy);
            }
            finally
            {
                if (null != proxy)
                {
                    if (proxy.State == CommunicationState.Faulted)
                    {
                        proxy.Abort();
                    }
                    else
                    {
                        proxy.Close();
                    }
                }
            }

            return(null);
        }
Пример #6
0
        public void Construct_InitializesConfigGauge_GaugeFiresForOneBulkhead()
        {
            // Arrange

            var key      = AnyString;
            var groupKey = GroupKey.Named(key);

            var expectedMinimumOperations     = AnyPositiveInt;
            var expectedWindowMillis          = AnyPositiveInt;
            var expectedThresholdPercent      = AnyPositiveInt;
            var expectedTrippedDurationMillis = AnyPositiveInt;
            var expectedForceTripped          = false;
            var expectedForceFixed            = false;

            var mockMetricEvents = new Mock <IMetricEvents>();

            var mockBreakerConfig = new Mock <IFailurePercentageCircuitBreakerConfig>(MockBehavior.Strict);

            mockBreakerConfig.Setup(m => m.GetMinimumOperations(groupKey)).Returns(expectedMinimumOperations);
            mockBreakerConfig.Setup(m => m.GetWindowMillis(groupKey)).Returns(expectedWindowMillis);
            mockBreakerConfig.Setup(m => m.GetThresholdPercentage(groupKey)).Returns(expectedThresholdPercent);
            mockBreakerConfig.Setup(m => m.GetTrippedDurationMillis(groupKey)).Returns(expectedTrippedDurationMillis);
            mockBreakerConfig.Setup(m => m.GetForceTripped(groupKey)).Returns(expectedForceTripped);
            mockBreakerConfig.Setup(m => m.GetForceFixed(groupKey)).Returns(expectedForceFixed);

            var mockLogFactory = new Mock <IMjolnirLogFactory>(MockBehavior.Strict);

            mockLogFactory.Setup(m => m.CreateLog <FailurePercentageCircuitBreaker>()).Returns(new DefaultMjolnirLog <FailurePercentageCircuitBreaker>());
            mockLogFactory.Setup(m => m.CreateLog <ResettingNumbersBucket>()).Returns(new DefaultMjolnirLog <ResettingNumbersBucket>());
            // Act + Assert

            var factory = new CircuitBreakerFactory(mockMetricEvents.Object, mockBreakerConfig.Object, mockLogFactory.Object);

            // Gauge won't fire immediately, it'll start one second after construction
            mockMetricEvents.Verify(m => m.BreakerGauge(It.IsAny <string>(), It.IsAny <long>(), It.IsAny <long>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <long>(), It.IsAny <long>()), Times.Never);

            // Add two breakers
            var firstBreaker = factory.GetCircuitBreaker(groupKey);

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

            mockMetricEvents.Verify(m => m.BreakerGauge(key, expectedMinimumOperations, expectedWindowMillis, expectedThresholdPercent, expectedTrippedDurationMillis, expectedForceTripped, expectedForceFixed, false, 0, 0));
        }
Пример #7
0
        private static MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumeResponse_V01 getVolumePoints(string distributorId)
        {
            var cacheKey = "VOLAPFExempt_" + distributorId;

            // tries to get object from cache
            var result = HttpRuntime.Cache[cacheKey];

            if (null != result)
            {
                return(result as MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumeResponse_V01);
            }

            try
            {
                var proxy          = ServiceClientProvider.GetDistributorServiceProxy();
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumeResponse_V01>();

                var getVolumeRequest = new MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumeRequest_V01
                {
                    DistributorID = distributorId,
                    StartDate     = DateTimeUtils.GetFirstDayOfMonth(DateTime.UtcNow.AddMonths(-1)),
                    EndDate       = DateTimeUtils.GetLastDayOfMonth(DateTime.UtcNow)
                };
                var response =
                    circuitBreaker.Execute(
                        () => proxy.GetDistributorVolumePoints(new MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumePointsRequest(getVolumeRequest)).GetDistributorVolumePointsResult as MyHerbalife3.Ordering.ServiceProvider.DistributorSvc.GetDistributorVolumeResponse_V01);
                HttpRuntime.Cache.Insert(cacheKey,
                                         response,
                                         null,
                                         DateTime.Now.AddMinutes(APFDUE_CACHE_MINUTES),
                                         Cache.NoSlidingExpiration,
                                         CacheItemPriority.Normal,
                                         null);
                return(response);
            }
            catch (Exception ex)
            {
                HL.Common.Logging.LoggerHelper.Error("APFDueProvider.IsAPFExemptOn200VP() Error \n" + ex.StackTrace);
            }

            return(null);
        }
        public CartWidgetModel GetCartWidgetFromSource(string id, string countryCode, string locale)
        {
            var proxy = ServiceClientProvider.GetShoppingCartServiceProxy();

            try
            {
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetShoppingCartResponse_V01>();
                var response =
                    circuitBreaker.Execute(() => proxy.GetShoppingCart(new GetShoppingCartRequest1(new GetShoppingCartRequest_V01
                {
                    Locale        = locale,
                    DistributorId = id,
                    Platform      = "MyHL"
                })).GetShoppingCartResult as GetShoppingCartResponse_V01);

                if (response != null && response.Status == ServiceProvider.ShoppingCartSvc.ServiceResponseStatusType.Success)
                {
                    return(GetCartWidgetModel(response));
                }
                LogErrorIfAny(response);
            }
            catch (Exception ex)
            {
                LoggerHelper.Exception("Error", ex,
                                       "Errored out in GetCartWidgetFromSource " + id + countryCode);
                if (null != proxy)
                {
                    proxy.Close();
                }
                throw;
            }
            finally
            {
                if (null != proxy)
                {
                    proxy.Close();
                }
            }

            return(new CartWidgetModel());
        }
Пример #9
0
        public List <TopSellerProductModel> GetTopSellerProductsFromSource(string id, string countryCode, string locale)
        {
            var proxy = ServiceClientProvider.GetCatalogServiceProxy();

            try
            {
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetTopSellersResponse_V01>();
                var response =
                    circuitBreaker.Execute(() => proxy.GetTopSellers(new GetTopSellersRequest1(new GetTopSellersRequest_V01
                {
                    CountryCode   = countryCode,
                    Locale        = locale,
                    DistributorId = id
                })).GetTopSellersResult as GetTopSellersResponse_V01);

                if (response != null && response.Status == MyHerbalife3.Ordering.ServiceProvider.CatalogSvc.ServiceResponseStatusType.Success)
                {
                    return(GetTopSellerProductModel(response.Skus, id, locale));
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Exception("Error", ex,
                                       "Errored out in TopSellerSource" + id + countryCode);
                if (null != proxy)
                {
                    proxy.Close();
                }
                throw;
            }
            finally
            {
                if (null != proxy)
                {
                    proxy.Close();
                }
            }

            return(null);
        }
        public List <RecentOrderModel> GetRecentOrdersFromSource(string id, string countryCode)
        {
            var proxy = ServiceClientProvider.GetOrderServiceProxy();

            try
            {
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <RecentOrderModel>();
                var response =
                    circuitBreaker.Execute(() => proxy.GetLatestOrder(new GetLatestOrderRequest1(new GetLatestOrderRequest_V01
                {
                    CountryCode   = countryCode,
                    DistributorId = id
                })).GetLatestOrderResult as GetLatestOrderResponse_V01);

                if (response != null && response.Status == ServiceResponseStatusType.Success)
                {
                    return(GetRecentOrdersModel(response.Orders.OfType <Order_V03>().ToList()));
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Exception("Error", ex,
                                       "Errored out in MyRecentOrdersSource" + countryCode);
                if (null != proxy)
                {
                    proxy.Close();
                }
                throw;
            }
            finally
            {
                if (null != proxy)
                {
                    proxy.Close();
                }
            }
            LoggerHelper.Error("Errored out in MyRecentOrdersSource Catalog service" + countryCode);
            return(null);
        }
        public static void CheckForMPCFraud(DistributorOrderingProfile distributor)
        {
            string errorResxKey = string.Empty;

            try
            {
                if (distributor != null && distributor.IsMPCFraud == null)
                {
                    using (var proxyDs = ServiceClientProvider.GetDistributorServiceProxy())
                    {
                        var requestV01 = new GetBasicDistributorRequest_V01
                        {
                            DistributorID = distributor.Id
                        };

                        var circuitBreaker =
                            CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetBasicDistributorResponse_V01>();
                        var responseV01 =
                            circuitBreaker.Execute(() => proxyDs.GetBasicDistributor(new GetBasicDistributorRequest(requestV01))).GetBasicDistributorResult as
                            GetBasicDistributorResponse_V01;

                        if (responseV01 != null && responseV01.Status == ServiceResponseStatusType.Success)
                        {
                            if (responseV01.Distributor != null)
                            {
                                distributor.IsMPCFraud = responseV01.Distributor.IsMPCFraud;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Exception("System.Exception", new Exception(
                                           string.Format(
                                               "Error retrieving MPC Fraud from Distributor service for: DS:{0} - Country:{1}, {2}",
                                               distributor.Id, distributor.CurrentLoggedInCountry, ex)));
            }
        }
Пример #12
0
        public void GetCircuitBreaker_ReturnsSameObjectForSameKey()
        {
            // Arrange

            var mockMetricEvents  = new Mock <IMetricEvents>();
            var mockBreakerConfig = new Mock <IFailurePercentageCircuitBreakerConfig>(MockBehavior.Strict);
            var mockLogFactory    = new Mock <IMjolnirLogFactory>(MockBehavior.Strict);

            mockLogFactory.Setup(m => m.CreateLog <BulkheadFactory>()).Returns(new DefaultMjolnirLog <BulkheadFactory>());
            mockLogFactory.Setup(m => m.CreateLog <FailurePercentageCircuitBreaker>()).Returns(new DefaultMjolnirLog <FailurePercentageCircuitBreaker>());
            mockLogFactory.Setup(m => m.CreateLog <ResettingNumbersBucket>()).Returns(new DefaultMjolnirLog <ResettingNumbersBucket>());
            var groupKey = AnyGroupKey;
            var factory  = new CircuitBreakerFactory(mockMetricEvents.Object, mockBreakerConfig.Object, mockLogFactory.Object);

            // Act

            var firstBreaker  = factory.GetCircuitBreaker(groupKey);
            var secondBreaker = factory.GetCircuitBreaker(groupKey);

            // Assert

            Assert.True(firstBreaker == secondBreaker);                 // Reference should be equal for same object.
            Assert.True(firstBreaker.Metrics == secondBreaker.Metrics); // Inner metrics instances should also be the same.
        }
        public static string CheckForDRFraud(DistributorOrderingProfile distributor, string zipCode)
        {
            string errorResxKey = string.Empty;
            var    fraudStatus = DRFraudStatusType.None;
            bool   isBlocked, isSponsorBlocked, isDsFound;

            isBlocked = isSponsorBlocked = isDsFound = false;

            using (var proxy = ServiceClientProvider.GetOrderServiceProxy())
            {
                try
                {
                    if (distributor != null && distributor.FraudStatus == null)
                    {
                        using (var proxyDs = ServiceClientProvider.GetDistributorServiceProxy())
                        {
                            var requestV01 = new GetBasicDistributorRequest_V01
                            {
                                DistributorID = distributor.Id
                            };

                            var circuitBreaker =
                                CircuitBreakerFactory.GetFactory().GetCircuitBreaker <GetBasicDistributorResponse_V01>();
                            var responseV01 =
                                circuitBreaker.Execute(() => proxyDs.GetBasicDistributor(new GetBasicDistributorRequest(requestV01))).GetBasicDistributorResult as
                                GetBasicDistributorResponse_V01;

                            if (responseV01 != null && responseV01.Status == ServiceResponseStatusType.Success)
                            {
                                if (responseV01.Distributor != null)
                                {
                                    isBlocked        = responseV01.Distributor.DRFraudStatusFlags.IsDistributorblocked;
                                    isSponsorBlocked = responseV01.Distributor.DRFraudStatusFlags.IsSponsorBlocked;
                                    isDsFound        = true;
                                }
                            }
                        }
                    }
                    else if (distributor != null && distributor.FraudStatus != null)
                    {
                        isBlocked        = distributor.FraudStatus.IsDistributorblocked;
                        isSponsorBlocked = distributor.FraudStatus.IsSponsorBlocked;
                        isDsFound        = true;
                    }

                    if (isDsFound)
                    {
                        var request = new GetDRFraudStatusRequest_V01();
                        request.DistributorID        = distributor.Id;
                        request.CountryCode          = distributor.CurrentLoggedInCountry;
                        request.PostalCode           = zipCode;
                        request.DistributorIsBlocked = isBlocked;
                        request.SponsorIsBlocked     = isSponsorBlocked;

                        var response =
                            proxy.GetDRFraudStatus(new GetDRFraudStatusRequest(request)).GetDRFraudStatusResult as GetDRFraudStatusResponse_V01;
                        if (response.Status == ServiceProvider.OrderSvc.ServiceResponseStatusType.Success)
                        {
                            fraudStatus = response.FraudStatus;
                        }
                    }
                    else
                    {
                        LoggerHelper.Exception("System.Exception", new Exception(
                                                   string.Format(
                                                       "Error retrieving DS DRFraudStatusFlags from Cache and Distributor service for: DS:{0} - Country:{1}",
                                                       distributor.Id, distributor.CurrentLoggedInCountry)));
                        fraudStatus = DRFraudStatusType.None;
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.Exception("System.Exception", new Exception(
                                               string.Format(
                                                   "Error retrieving DRFraud Status from Order service for: DS:{0} - Country:{1}, {2}",
                                                   distributor.Id, distributor.CurrentLoggedInCountry, ex)));
                    fraudStatus = DRFraudStatusType.None;
                }
            }

            if (fraudStatus == DRFraudStatusType.DistributorIsBlocked)
            {
                errorResxKey = "BlockedDS";
            }
            else if (fraudStatus == DRFraudStatusType.PostalCodeIsBlocked)
            {
                errorResxKey = "BlockedZip";
            }

            return(errorResxKey);
        }
Пример #14
0
        internal static CommandState PrepareInternal(Type commandType, IJellyfishContext context, string commandGroup, string commandName, CommandPropertiesBuilder propertiesBuilder = null, IClock clock = null, CommandMetrics metrics = null, ICircuitBreaker circuitBreaker = null)
        {
            var state = new CommandState();

            state.CommandName  = commandName ?? commandType.FullName;
            state.CommandGroup = commandGroup ?? state.CommandName;

            clock = clock ?? Clock.GetInstance();
            var properties = propertiesBuilder?.Build(state.CommandName) ?? new CommandProperties(state.CommandName);

            metrics        = metrics ?? CommandMetricsFactory.GetInstance(state.CommandName, state.CommandGroup, properties, clock);
            circuitBreaker = circuitBreaker ?? (properties.CircuitBreakerEnabled.Value ? CircuitBreakerFactory.GetOrCreateInstance(state.CommandName, properties, metrics, clock) : new NoOpCircuitBreaker());
            context.MetricsPublisher.CreateOrRetrievePublisherForCommand(state.CommandGroup, metrics, circuitBreaker);

            ServiceCommandOptions flags = ServiceCommandOptions.None;

            if (IsMethodImplemented(commandType, "GetFallback"))
            {
                flags |= ServiceCommandOptions.HasFallBack;
            }
            if (IsMethodImplemented(commandType, "GetCacheKey"))
            {
                flags |= ServiceCommandOptions.HasCacheKey;
            }
            state.Flags = flags;
            return(state);
        }
        internal ServiceCommand(IJellyfishContext context, IClock clock, string commandGroup = null, string commandName = null, string threadPoolKey = null, CommandPropertiesBuilder properties = null, ICircuitBreaker circuitBreaker = null, CommandMetrics metrics = null, CommandExecutionHook executionHook = null)
        {
            Contract.Requires(context != null);
            CommandState state = _states.GetOrAdd(this.GetType().FullName, (n) => ServiceCommandHelper.PrepareInternal(this.GetType(), context, commandGroup, commandName, properties, clock, metrics, circuitBreaker));

            if (String.IsNullOrEmpty(state.CommandGroup))
            {
                throw new ArgumentException("commandGroup can not be null or empty.");
            }

            Logger = context.GetService <ILoggerFactory>()?.CreateLogger(this.GetType().FullName) ?? EmptyLogger.Instance;

            CommandGroup    = state.CommandGroup;
            CommandName     = state.CommandName;
            _clock          = clock ?? Clock.GetInstance(); // for test
            Properties      = properties?.Build(CommandName) ?? new CommandProperties(CommandName);
            Metrics         = metrics ?? CommandMetricsFactory.GetInstance(CommandName, CommandGroup, Properties, _clock);
            _circuitBreaker = circuitBreaker ?? (Properties.CircuitBreakerEnabled.Value ? CircuitBreakerFactory.GetOrCreateInstance(CommandName, Properties, Metrics, _clock) : new NoOpCircuitBreaker());
            context.MetricsPublisher.CreateOrRetrievePublisherForCommand(CommandGroup, Metrics, _circuitBreaker);

            this._flags = state.Flags;

            _threadPoolKey   = threadPoolKey ?? CommandGroup;
            _executionResult = new ExecutionResult();
            _executionHook   = executionHook ?? context.CommandExecutionHook;

            var executionPolicy = Properties.ExecutionIsolationStrategy.Value;

            if (executionPolicy == ExecutionIsolationStrategy.Semaphore)
            {
                _flags |= ServiceCommandOptions.SemaphoreExecutionStrategy;
            }
            if (executionPolicy == ExecutionIsolationStrategy.Thread)
            {
                _flags |= ServiceCommandOptions.ThreadExecutionStrategy;
            }

            if (Properties.RequestLogEnabled.Value)
            {
                _currentRequestLog = context.GetRequestLog();
            }

            if ((_flags & ServiceCommandOptions.HasCacheKey) == ServiceCommandOptions.HasCacheKey && Properties.RequestCacheEnabled.Value)
            {
                _requestCache = context.GetCache <CacheItem>(CommandName);
            }
        }
 public CircuitBreakerConfig(CircuitBreakerFactory circuitBreakerFactory)
 {
     this.circuitBreakerFactory = circuitBreakerFactory;
 }
        private String GetCommandJson(CommandMetrics commandMetrics)
        {
            var circuitBreaker = this.circuitBreaker ?? CircuitBreakerFactory.GetInstance(commandMetrics.CommandName);

            var          sb   = new StringBuilder(1024);
            StringWriter sw   = new StringWriter(sb, CultureInfo.InvariantCulture);
            var          json = new JsonWriter(sw);

            json.writeStartObject();
            json.writeStringField("type", "ServiceCommand");
            json.writeStringField("name", commandMetrics.CommandName);
            json.writeStringField("group", commandMetrics.CommandGroup);
            json.writeNumberField("currentTime", DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); // TODO check this

            // circuit breaker
            if (circuitBreaker == null)
            {
                // circuit breaker is disabled and thus never open
                json.writeBooleanField("isCircuitBreakerOpen", false);
            }
            else
            {
                json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.IsOpen());
            }
            HealthCounts healthCounts = commandMetrics.GetHealthCounts();

            json.writeNumberField("errorPercentage", healthCounts.ErrorPercentage);
            json.writeNumberField("errorCount", healthCounts.ErrorCount);
            json.writeNumberField("requestCount", healthCounts.TotalRequests);

            // rolling counters
            json.writeNumberField("rollingCountBadRequests", commandMetrics.GetRollingCount(RollingNumberEvent.BAD_REQUEST));
            json.writeNumberField("rollingCountExceptionsThrown", commandMetrics.GetRollingCount(RollingNumberEvent.EXCEPTION_THROWN));
            json.writeNumberField("rollingCountFailure", commandMetrics.GetRollingCount(RollingNumberEvent.FAILURE));
            json.writeNumberField("rollingCountFallbackFailure", commandMetrics.GetRollingCount(RollingNumberEvent.FALLBACK_FAILURE));
            json.writeNumberField("rollingCountFallbackRejection", commandMetrics.GetRollingCount(RollingNumberEvent.FALLBACK_REJECTION));
            json.writeNumberField("rollingCountFallbackSuccess", commandMetrics.GetRollingCount(RollingNumberEvent.FALLBACK_SUCCESS));
            json.writeNumberField("rollingCountResponsesFromCache", commandMetrics.GetRollingCount(RollingNumberEvent.RESPONSE_FROM_CACHE));
            json.writeNumberField("rollingCountSemaphoreRejected", commandMetrics.GetRollingCount(RollingNumberEvent.SEMAPHORE_REJECTED));
            json.writeNumberField("rollingCountShortCircuited", commandMetrics.GetRollingCount(RollingNumberEvent.SHORT_CIRCUITED));
            json.writeNumberField("rollingCountSuccess", commandMetrics.GetRollingCount(RollingNumberEvent.SUCCESS));
            json.writeNumberField("rollingCountThreadPoolRejected", commandMetrics.GetRollingCount(RollingNumberEvent.THREAD_POOL_REJECTED));
            json.writeNumberField("rollingCountTimeout", commandMetrics.GetRollingCount(RollingNumberEvent.TIMEOUT));

            json.writeNumberField("currentConcurrentExecutionCount", commandMetrics.CurrentConcurrentExecutionCount);
            json.writeNumberField("rollingMaxConcurrentExecutionCount", commandMetrics.GetRollingMaxConcurrentExecutions());

            // latency percentiles
            json.writeNumberField("latencyExecute_mean", commandMetrics.GetExecutionTimeMean());
            json.writeObjectFieldStart("latencyExecute");
            json.writeNumberField("0", commandMetrics.GetExecutionTimePercentile(0));
            json.writeNumberField("25", commandMetrics.GetExecutionTimePercentile(25));
            json.writeNumberField("50", commandMetrics.GetExecutionTimePercentile(50));
            json.writeNumberField("75", commandMetrics.GetExecutionTimePercentile(75));
            json.writeNumberField("90", commandMetrics.GetExecutionTimePercentile(90));
            json.writeNumberField("95", commandMetrics.GetExecutionTimePercentile(95));
            json.writeNumberField("99", commandMetrics.GetExecutionTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.GetExecutionTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.GetExecutionTimePercentile(100));
            json.writeEndObject();
            //
            json.writeNumberField("latencyTotal_mean", commandMetrics.GetTotalTimeMean());
            json.writeObjectFieldStart("latencyTotal");
            json.writeNumberField("0", commandMetrics.GetTotalTimePercentile(0));
            json.writeNumberField("25", commandMetrics.GetTotalTimePercentile(25));
            json.writeNumberField("50", commandMetrics.GetTotalTimePercentile(50));
            json.writeNumberField("75", commandMetrics.GetTotalTimePercentile(75));
            json.writeNumberField("90", commandMetrics.GetTotalTimePercentile(90));
            json.writeNumberField("95", commandMetrics.GetTotalTimePercentile(95));
            json.writeNumberField("99", commandMetrics.GetTotalTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.GetTotalTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.GetTotalTimePercentile(100));
            json.writeEndObject();

            // property values for reporting what is actually seen by the command rather than what was set somewhere
            var commandProperties = commandMetrics.Properties;

            json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold", commandProperties.CircuitBreakerRequestVolumeThreshold.Value);
            json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds", commandProperties.CircuitBreakerSleepWindowInMilliseconds.Value);
            json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage", commandProperties.CircuitBreakerErrorThresholdPercentage.Value);
            json.writeBooleanField("propertyValue_circuitBreakerForceOpen", commandProperties.CircuitBreakerForceOpen.Value);
            json.writeBooleanField("propertyValue_circuitBreakerForceClosed", commandProperties.CircuitBreakerForceClosed.Value);
            json.writeBooleanField("propertyValue_circuitBreakerEnabled", commandProperties.CircuitBreakerEnabled.Value);

            json.writeStringField("propertyValue_executionIsolationStrategy", commandProperties.ExecutionIsolationStrategy.Value.ToString());
            json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds", commandProperties.ExecutionIsolationThreadTimeoutInMilliseconds.Value);
            json.writeNumberField("propertyValue_executionTimeoutInMilliseconds", commandProperties.ExecutionIsolationThreadTimeoutInMilliseconds.Value);
            //json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout", commandProperties.executionIsolationThreadInterruptOnTimeout().get());
            //json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride", commandProperties.executionIsolationThreadPoolKeyOverride().get());
            json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", commandProperties.ExecutionIsolationSemaphoreMaxConcurrentRequests.Value);
            json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", commandProperties.FallbackIsolationSemaphoreMaxConcurrentRequests.Value);

            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", commandProperties.MetricsRollingStatisticalWindowInMilliseconds.Value);

            json.writeBooleanField("propertyValue_requestCacheEnabled", commandProperties.RequestCacheEnabled.Value);
            json.writeBooleanField("propertyValue_requestLogEnabled", commandProperties.RequestLogEnabled.Value);

            json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster
                                                        //json.writeStringField("threadPool", commandMetrics.getThreadPoolKey().name());

            // Hystrix specific
            json.writeNumberField("rollingCountCollapsedRequests", 0);
            json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout", false);

            json.writeEndObject();

            return(sb.ToString());
        }
        private static SaveUpdateResponseModel Create(InvoiceCRMConatactModel contact, string memberId)
        {
            var proxy = ServiceClientProvider.GetCRMContactServiceProxy();

            try
            {
                var createCrmContactRequest = new CreateCrmContactRequest();
                createCrmContactRequest.OwnerId = memberId;
                createCrmContactRequest.IsContactInformationRequired = true;

                CrmContact crmContact = new CrmContact();
                crmContact.ContactId       = null;
                crmContact.ContactType     = CrmContactType.Customer;
                crmContact.ContactPriority = ContactPriorityType.None;
                crmContact.ContactSource   = ContactSourceType.ECommerce;
                crmContact.ContactStatus   = ContactStatusType.None;
                crmContact.OwnerMemberId   = memberId;

                crmContact.IsDuplicateNameCheckRequired = contact.IsDuplicateCheckRequire;

                crmContact.EmailAddresses = contact.EmailDetail != null && string.IsNullOrEmpty(contact.EmailDetail.EmailAddress) ? null : new List <EmailAddress_V01> {
                    new ContactEmailAddress {
                        EmailId = string.Empty, Address = contact.EmailDetail.EmailAddress, IsPrimary = true
                    }
                };

                crmContact.FollowupAppointments = new List <FollowupAppointment>()
                ;
                crmContact.Addresses = contact.Address == null
                    ? null
                    : new List <Address_V03>()
                {
                    new ContactAddress
                    {
                        AddressId = null,
                        Line1     = contact.Address.Address1,
                        City      = contact.Address.City,
                        Line2     = contact.Address.Address2,
                        StateProvinceTerritory = contact.Address.State,
                        PostalCode             = contact.Address.PostalCode,
                        Country       = contact.Address.Country,
                        IsPrimary     = true,
                        TypeOfAddress = AddressType.ShipTo
                    }
                };

                crmContact.Name = new Name_V01
                {
                    First = contact.FirstName,
                    Last  = contact.LastName,
                };

                crmContact.Phones = contact.PhoneDetail == null || string.IsNullOrEmpty(contact.PhoneDetail.PhoneNumber)
                    ? null
                    : new List <CrmContactPhone>()
                {
                    new CrmContactPhone
                    {
                        Id        = string.Empty,
                        IsPrimary = true,
                        Number    = contact.PhoneDetail.PhoneNumber,
                        PhoneType = CrmContactPhoneType.Mobile
                    }
                };
                createCrmContactRequest.Value = crmContact;

                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <CreateCrmContactResponse>();
                var response = circuitBreaker.Execute(() => proxy.CreateContact(new CreateContactRequest(createCrmContactRequest)).CreateContactResult as CreateCrmContactResponse);


                if (response == null)
                {
                    LoggerHelper.Warn($"Create customer for ds {memberId} failed: response is null.");
                    return(null);
                }
                return(createContactResponseModel(response, contact));
            }
            catch (Exception ex)
            {
                LoggerHelper.Info($"ContactSaver:Create Failed. message: {ex.Message}, exception: {ex}");
                SaveUpdateResponseModel errorModel = new SaveUpdateResponseModel();
                return(errorModel);
            }
            finally
            {
                proxy.Close();
            }
        }
 public CircuitBreakerConfig(CircuitBreakerFactory circuitBreakerFactory)
 {
     this.circuitBreakerFactory = circuitBreakerFactory;
 }
        private static SaveUpdateResponseModel Update(InvoiceCRMConatactModel contact, string memberId)
        {
            var proxy = ServiceClientProvider.GetCRMContactServiceProxy();

            try
            {
                var hasAddressChanges = (contact.Address != null && contact.Address.Id > 0);
                var hasPhoneChanges   = (contact.PhoneDetail != null && contact.PhoneDetail.Id > 0) || (contact.PhoneDetail != null && !string.IsNullOrEmpty(contact.PhoneDetail.PhoneNumber));
                var hasEmailChanges   = (contact.EmailDetail != null && contact.EmailDetail.Id > 0) || (contact.EmailDetail != null && !string.IsNullOrEmpty(contact.EmailDetail.EmailAddress));

                var updatingField = new List <string>();
                updatingField.Add("FirstName");
                updatingField.Add("LastName");

                if (hasAddressChanges)
                {
                    updatingField.Add("Addresses");
                }

                if (hasPhoneChanges)
                {
                    updatingField.Add("Phones");
                }

                if (hasEmailChanges)
                {
                    updatingField.Add("EmailAddress");
                }

                var crmContactUpdateRequest = new CrmContactUpdateRequest
                {
                    Fields = updatingField,
                    Value  = new CrmContact
                    {
                        EmailAddresses = hasEmailChanges ? new List <EmailAddress_V01>()
                        {
                            new ContactEmailAddress {
                                IsPrimary = true, EmailId = contact.EmailDetail.Id.ToString(), Address = contact.EmailDetail.EmailAddress
                            }
                        } : null,
                        Addresses = hasAddressChanges ?
                                    new List <Address_V03>()
                        {
                            new ContactAddress
                            {
                                AddressId = contact.Address.Id <= 0 ? null : contact.Address.Id.ToString(),
                                City      = string.IsNullOrEmpty(contact.Address.City)?string.Empty:contact.Address.City,
                                Country   = string.IsNullOrEmpty(contact.Address.Country)?string.Empty:contact.Address.Country,
                                Line1     = string.IsNullOrEmpty(contact.Address.Address1)?string.Empty:contact.Address.Address1,
                                Line2     = string.IsNullOrEmpty(contact.Address.Address2)?string.Empty:contact.Address.Address2,
                                StateProvinceTerritory = string.IsNullOrEmpty(contact.Address.State)?string.Empty:contact.Address.State,
                                PostalCode             = string.IsNullOrEmpty(contact.Address.PostalCode)?string.Empty:contact.Address.PostalCode,
                                TypeOfAddress          = AddressType.ShipTo,
                            }
                        } : null,
                        Name = new Name_V01 {
                            First = contact.FirstName, Last = contact.LastName
                        },
                        Phones = hasPhoneChanges ? new List <CrmContactPhone>()
                        {
                            new CrmContactPhone {
                                IsPrimary = true, Number = contact.PhoneDetail.PhoneNumber, PhoneType = CrmContactPhoneType.Mobile, Id = contact.PhoneDetail.Id.ToString() == "0" ? null : contact.PhoneDetail.Id.ToString()
                            }
                        } : null,
                        ContactType   = CrmContactType.Customer,
                        OwnerMemberId = memberId,
                        ContactId     = contact.ContactId.ToString(),
                        IsDuplicateNameCheckRequired = false,
                        FollowupAppointments         = new List <FollowupAppointment>(),
                    }
                };
                var circuitBreaker =
                    CircuitBreakerFactory.GetFactory().GetCircuitBreaker <UpdateContactResponse>();
                var response = circuitBreaker.Execute(() => proxy.UpdateContact(new UpdateContactRequest(crmContactUpdateRequest)).UpdateContactResult);


                if (response == null)
                {
                    LoggerHelper.Warn($"Create customer for ds {memberId} failed: response is null.");
                    return(null);
                }
                return(new SaveUpdateResponseModel {
                    Data = contact
                });
            }
            catch (Exception ex)
            {
                LoggerHelper.Warn("ContactSaver Update : " + ex.StackTrace.ToString());
                throw;
            }
            finally
            {
                proxy.Close();
            }
        }
        public CartWidgetModel AddToCart(CartWidgetModel cartWidget, string id, string countryCode, string locale)
        {
            if (null == cartWidget)
            {
                throw new ArgumentException("cartWidget is null", "cartWidget");
            }
            if (string.IsNullOrEmpty(countryCode))
            {
                throw new ArgumentException("countryCode is blank", "countryCode");
            }

            if (string.IsNullOrEmpty(locale))
            {
                throw new ArgumentException("Locale is blank", "locale");
            }

            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException("id is blank", "id");
            }

            var cartModel = GetCartWidget(id, countryCode, locale);

            if (null != cartModel)
            {
                cartWidget.Id = cartModel.Id;
                var proxy = ServiceClientProvider.GetShoppingCartServiceProxy();
                try
                {
                    var circuitBreaker =
                        CircuitBreakerFactory.GetFactory().GetCircuitBreaker <AddItemsToCartResponse_V01>();
                    var response =
                        circuitBreaker.Execute(() => proxy.AddItemsToCart(new AddItemsToCartRequest1(new AddItemsToCartRequest_V01
                    {
                        ShoppingCartID = cartWidget.Id,
                        OrderItems     =
                            new List <ServiceProvider.ShoppingCartSvc.OrderItem>
                        {
                            new ServiceProvider.ShoppingCartSvc.OrderItem {
                                Quantity = cartWidget.Quantity, SKU = cartWidget.Sku
                            }
                        },
                        Platform      = "MyHL",
                        DistributorId = id,
                        Locale        = locale
                    }))).AddItemsToCartResult as AddItemsToCartResponse_V01;

                    if (response != null && response.Status == ServiceProvider.ShoppingCartSvc.ServiceResponseStatusType.Success)
                    {
                        ExpireShoppingCartCache(id, locale);
                        ClearShoppingCartFromSession(id, locale);
                        return(new CartWidgetModel
                        {
                            Id = response.ShoppingCartID,
                            Quantity = response.TotalItems,
                            Subtotal = response.Subtotal,
                            DisplaySubtotal =
                                String.Format("{0}{1}",
                                              HLConfigManager.Configurations.CheckoutConfiguration.CurrencySymbol,
                                              response.Subtotal)
                        });
                    }

                    LogErrorIfAny(response);

                    return(null);
                }
                catch (Exception ex)
                {
                    LoggerHelper.Exception("Error", ex,
                                           "Errored out in AddToCart");
                    if (null != proxy)
                    {
                        proxy.Close();
                    }
                    throw;
                }
                finally
                {
                    if (null != proxy)
                    {
                        proxy.Close();
                    }
                }
            }
            return(null);
        }