コード例 #1
0
        public SubscriptionModelFactory(IAddressModelFactory addressModelFactory,
                                        ISubscriptionService subscriptionService,
                                        IWorkContext workContext,
                                        ICurrencyService currencyService,
                                        IPriceFormatter priceFormatter,
                                        ISubscriptionProcessingService subscriptionProcessingService,
                                        IDateTimeHelper dateTimeHelper,
                                        IPaymentService paymentService,
                                        ILocalizationService localizationService,
                                        ICountryService countryService,
                                        IArticleAttributeParser articleAttributeParser,
                                        IDownloadService downloadService,
                                        IStoreContext storeContext,
                                        ISubscriptionTotalCalculationService subscriptionTotalCalculationService,
                                        IRewardPointService rewardPointService,
                                        CatalogSettings catalogSettings,
                                        SubscriptionSettings subscriptionSettings,
                                        TaxSettings taxSettings,
                                        AddressSettings addressSettings,
                                        RewardPointsSettings rewardPointsSettings,
                                        PdfSettings pdfSettings)
        {
            this._addressModelFactory                 = addressModelFactory;
            this._subscriptionService                 = subscriptionService;
            this._workContext                         = workContext;
            this._currencyService                     = currencyService;
            this._priceFormatter                      = priceFormatter;
            this._subscriptionProcessingService       = subscriptionProcessingService;
            this._dateTimeHelper                      = dateTimeHelper;
            this._paymentService                      = paymentService;
            this._localizationService                 = localizationService;
            this._countryService                      = countryService;
            this._articleAttributeParser              = articleAttributeParser;
            this._downloadService                     = downloadService;
            this._storeContext                        = storeContext;
            this._subscriptionTotalCalculationService = subscriptionTotalCalculationService;
            this._rewardPointService                  = rewardPointService;

            this._catalogSettings      = catalogSettings;
            this._subscriptionSettings = subscriptionSettings;
            this._taxSettings          = taxSettings;
            this._addressSettings      = addressSettings;
            this._rewardPointsSettings = rewardPointsSettings;
            this._pdfSettings          = pdfSettings;
        }
コード例 #2
0
        public void CheckExtensionParameters()
        {
            var log        = A.Fake <ILog>();
            var settings   = A.Fake <ISettings>();
            var fileSystem = A.Fake <IFileSystemProxy>();

            var instance = new SubscriptionSettings(log, settings, fileSystem);

            var parameters = new List <(string Name, string Value)>
            {
                (Name : "1", Value : "val1"),
                (Name : "2", Value : "val2")
            };

            instance.ExtensionParameters = parameters;

            Assert.Equal(parameters, instance.ExtensionParameters);
        }
コード例 #3
0
ファイル: QCAlgorithm.cs プロジェクト: sprgn/LeanITrend
        /// <summary>
        /// QCAlgorithm Base Class Constructor - Initialize the underlying QCAlgorithm components.
        /// QCAlgorithm manages the transactions, portfolio, charting and security subscriptions for the users algorithms.
        /// </summary>
        public QCAlgorithm()
        {
            // AlgorithmManager will flip this when we're caught up with realtime
            IsWarmingUp = true;

            //Initialise the Algorithm Helper Classes:
            //- Note - ideally these wouldn't be here, but because of the DLL we need to make the classes shared across
            //  the Worker & Algorithm, limiting ability to do anything else.

            //Initialise Start and End Dates:
            _startDate = new DateTime(1998, 01, 01);
            _endDate   = DateTime.Now.AddDays(-1);

            // intialize our time keeper with only new york
            _timeKeeper = new TimeKeeper(_startDate, new[] { TimeZones.NewYork });
            // set our local time zone
            _localTimeKeeper = _timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);

            //Initialise Data Manager
            SubscriptionManager = new SubscriptionManager(_timeKeeper);

            Securities     = new SecurityManager(_timeKeeper);
            Transactions   = new SecurityTransactionManager(Securities);
            Portfolio      = new SecurityPortfolioManager(Securities, Transactions);
            BrokerageModel = new DefaultBrokerageModel();
            Notify         = new NotificationManager(false); // Notification manager defaults to disabled.

            //Initialise Algorithm RunMode to Series - Parallel Mode deprecated:
            _runMode = RunMode.Series;

            //Initialise to unlocked:
            _locked = false;

            // get exchange hours loaded from the market-hours-database.csv in /Data/market-hours
            _exchangeHoursProvider = SecurityExchangeHoursProvider.FromDataFolder();

            UniverseSettings = new SubscriptionSettings(Resolution.Minute, 2m, true, false);

            // initialize our scheduler, this acts as a liason to the real time handler
            Schedule = new ScheduleManager(Securities, TimeZone);

            // initialize the trade builder
            TradeBuilder = new TradeBuilder(FillGroupingMethod.FillToFill, FillMatchingMethod.FIFO);
        }
コード例 #4
0
        private async Task SendToSubscriber(SubscriptionSettings subscription, EventGridEvent[] events)
        {
            try
            {
                _logger.LogDebug("Sending to subscriber '{SubscriberName}'.", subscription.Name);

                // "Event Grid sends the events to subscribers in an array that has a single event. This behavior may change in the future."
                // https://docs.microsoft.com/en-us/azure/event-grid/event-schema
                foreach (var evt in events)
                {
                    var json = JsonConvert.SerializeObject(new[] { evt }, Formatting.Indented);
                    using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
                        using (var httpClient = new HttpClient())
                        {
                            httpClient.DefaultRequestHeaders.Add("aeg-event-type", "Notification");
                            httpClient.Timeout = TimeSpan.FromSeconds(5);

                            await httpClient.PostAsync(subscription.Endpoint, content)
                            .ContinueWith(t =>
                            {
                                if (t.IsCompletedSuccessfully && t.Result.IsSuccessStatusCode)
                                {
                                    _logger.LogDebug(
                                        "Event {EventId} sent to subscriber '{SubscriberName}' successfully.", evt.Id, subscription.Name);
                                }
                                else
                                {
                                    _logger.LogError(t.Exception?.GetBaseException(),
                                                     "Failed to send event {EventId} to subscriber '{SubscriberName}', '{TaskStatus}', '{Reason}'.", evt.Id,
                                                     subscription.Name,
                                                     t.Status.ToString(),
                                                     t.Result?.ReasonPhrase);
                                }
                            });
                        }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                                 "Failed to send to subscriber '{SubscriberName}'.", subscription.Name);
            }
        }
コード例 #5
0
ファイル: Settings.cs プロジェクト: mbernier/StrongGrid
        /// <summary>
        /// Change the Subscription Tracking settings
        /// </summary>
        /// <param name="enabled">if set to <c>true</c> [enabled].</param>
        /// <param name="landingPageHtml">The landing page HTML.</param>
        /// <param name="url">The URL.</param>
        /// <param name="replacementTag">The replacement tag.</param>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <param name="textContent">Content of the text.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The <see cref="SubscriptionSettings" />.
        /// </returns>
        public Task <SubscriptionSettings> UpdateSubscriptionTrackingSettingsAsync(bool enabled, string landingPageHtml, string url, string replacementTag, string htmlContent, string textContent, CancellationToken cancellationToken = default(CancellationToken))
        {
            var subscriptionTrackingSettings = new SubscriptionSettings
            {
                Enabled         = enabled,
                LandingPageHtml = landingPageHtml,
                Url             = url,
                ReplacementTag  = replacementTag,
                HtmlContent     = htmlContent,
                TextContent     = textContent
            };
            var data = JObject.FromObject(subscriptionTrackingSettings);

            return(_client
                   .PatchAsync("tracking_settings/subscription")
                   .WithJsonBody(data)
                   .WithCancellationToken(cancellationToken)
                   .AsSendGridObject <SubscriptionSettings>());
        }
コード例 #6
0
        /// <summary>
        /// Change the Subscription Tracking settings.
        /// </summary>
        /// <param name="enabled">if set to <c>true</c> [enabled].</param>
        /// <param name="landingPageHtml">The landing page HTML.</param>
        /// <param name="url">The URL.</param>
        /// <param name="replacementTag">The replacement tag.</param>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <param name="textContent">Content of the text.</param>
        /// <param name="onBehalfOf">The user to impersonate.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The <see cref="SubscriptionSettings" />.
        /// </returns>
        public Task <SubscriptionSettings> UpdateSubscriptionTrackingSettingsAsync(bool enabled, string landingPageHtml, string url, string replacementTag, string htmlContent, string textContent, string onBehalfOf = null, CancellationToken cancellationToken = default)
        {
            var data = new SubscriptionSettings
            {
                Enabled         = enabled,
                LandingPageHtml = landingPageHtml,
                Url             = url,
                ReplacementTag  = replacementTag,
                HtmlContent     = htmlContent,
                TextContent     = textContent
            };

            return(_client
                   .PatchAsync("tracking_settings/subscription")
                   .OnBehalfOf(onBehalfOf)
                   .WithJsonBody(data)
                   .WithCancellationToken(cancellationToken)
                   .AsObject <SubscriptionSettings>());
        }
コード例 #7
0
        public CheckoutModelFactory(IAddressModelFactory addressModelFactory,
                                    IWorkContext workContext,
                                    IStoreContext storeContext,
                                    IStoreMappingService storeMappingService,
                                    ILocalizationService localizationService,
                                    ITaxService taxService,
                                    ICurrencyService currencyService,
                                    IPriceFormatter priceFormatter,
                                    ISubscriptionProcessingService subscriptionProcessingService,
                                    IGenericAttributeService genericAttributeService,
                                    ICountryService countryService,
                                    IStateProvinceService stateProvinceService,
                                    IPaymentService paymentService,
                                    ISubscriptionTotalCalculationService subscriptionTotalCalculationService,
                                    IRewardPointService rewardPointService,
                                    IWebHelper webHelper,
                                    SubscriptionSettings subscriptionSettings,
                                    RewardPointsSettings rewardPointsSettings,
                                    PaymentSettings paymentSettings,
                                    AddressSettings addressSettings)
        {
            this._addressModelFactory                 = addressModelFactory;
            this._workContext                         = workContext;
            this._storeContext                        = storeContext;
            this._storeMappingService                 = storeMappingService;
            this._localizationService                 = localizationService;
            this._taxService                          = taxService;
            this._currencyService                     = currencyService;
            this._priceFormatter                      = priceFormatter;
            this._subscriptionProcessingService       = subscriptionProcessingService;
            this._genericAttributeService             = genericAttributeService;
            this._countryService                      = countryService;
            this._stateProvinceService                = stateProvinceService;
            this._paymentService                      = paymentService;
            this._subscriptionTotalCalculationService = subscriptionTotalCalculationService;
            this._rewardPointService                  = rewardPointService;
            this._webHelper = webHelper;

            this._subscriptionSettings = subscriptionSettings;
            this._rewardPointsSettings = rewardPointsSettings;
            this._paymentSettings      = paymentSettings;
            this._addressSettings      = addressSettings;
        }
コード例 #8
0
        public void CheckFileName()
        {
            var log        = A.Fake <ILog>();
            var settings   = A.Fake <ISettings>();
            var fileSystem = A.Fake <IFileSystemProxy>();

            var instance = new SubscriptionSettings(log, settings, fileSystem);

            var parameters = new List <(string Name, string Value)>
            {
                (Name : SubscriptionSettings.FILENAME, Value : SubscriptionSettings.FILENAME)
            };

            instance.ExtensionParameters = parameters;

            var result = instance.FileName;

            Assert.Equal(SubscriptionSettings.FILENAME, result);
        }
        public async Task SubscriptionRegistrationBackgroundServiceCorrectWebhookSettingReturnsSuccessful()
        {
            //Arrange
            var subscriptionSettings = new SubscriptionSettings
            {
                Endpoint = new Uri("https://somewebhookreceiver.com/receive"),
                SubscriptionServiceEndpoint = new Uri("https://somewheretosubscribeto.com"),
                Filter = new SubscriptionFilter
                {
                    IncludeEventTypes = new List <string> {
                        "published", "unpublished", "deleted"
                    },
                },
                SubscriptionRegistrationDelay = new TimeSpan(0, 0, 5),
            };

            A.CallTo(() => configuration["Configuration:ApplicationName"]).Returns("test-app");
            A.CallTo(() => settings.CurrentValue).Returns(subscriptionSettings);

            var httpResponse = new HttpResponseMessage {
                StatusCode = System.Net.HttpStatusCode.OK
            };
            var fakeHttpRequestSender  = A.Fake <IFakeHttpRequestSender>();
            var fakeHttpMessageHandler = new FakeHttpMessageHandler(fakeHttpRequestSender);
            var httpClient             = new HttpClient(fakeHttpMessageHandler);

            A.CallTo(() => fakeHttpRequestSender.Send(A <HttpRequestMessage> .Ignored)).Returns(httpResponse);
            A.CallTo(() => httpClientFactory.CreateClient(A <string> .Ignored)).Returns(httpClient);

            var serviceToTest = new SubscriptionRegistrationService(settings, httpClientFactory, logger);

            //Act
            await serviceToTest.RegisterSubscription("a-test-subscriber").ConfigureAwait(false);

            //Assert
            A.CallTo(() => fakeHttpRequestSender.Send(A <HttpRequestMessage> .Ignored)).MustHaveHappenedOnceExactly();

            Assert.Equal(3, subscriptionSettings.Filter.IncludeEventTypes.Count);

            httpResponse.Dispose();
            fakeHttpMessageHandler.Dispose();
            httpClient.Dispose();
        }
コード例 #10
0
        public override void Configure(Container container)
        {
            //when using a ReadModelSubscription we do not pass in the stream name
            //since it subscribes to all streams (the $all projection in event store)
            var subscriptionSettings = new SubscriptionSettings()
                                       .SubscribeToStreams(s => s.Add(new ReadModelSubscription()
                                                                      .WithStorage(new ReadModelStorage(StorageType.Redis, "localhost:6379"))));

            //these three settings are the minimum configuration required to
            //set up a connection to EventStore
            var connectionSettings = new EventStoreConnectionSettings()
                                     .UserName("admin")
                                     .Password("changeit")
                                     .TcpEndpoint("localhost:1113");

            //we instantiate the plugin using the connection and subscription data as well as a
            //parameter array of the assemblies where the plugin can find the CLR event types
            Plugins.Add(new EventStoreFeature(connectionSettings, subscriptionSettings, typeof(TestAppHost).Assembly));
        }
コード例 #11
0
        public SubscriptionUpdateManager(
            ILoggerFactory loggerFactory,
            SubscriptionManager subscriptionManager,
            SubscriptionSettings subscriptionSettingsRepository
            )
        {
            _logger = loggerFactory.CreateLogger <SubscriptionUpdateManager>();
            _subscriptionManager        = subscriptionManager;
            _subscriptionSettings       = subscriptionSettingsRepository;
            _subscriptionManager.Added += _subscriptionManager_Added;

            _updateFrequency     = _subscriptionSettings.SubscriptionsUpdateFrequency;
            _IsAutoUpdateEnabled = _subscriptionSettings.IsSubscriptionAutoUpdateEnabled;

            StartOrResetTimer();

            App.Current.Suspending += Current_Suspending;
            App.Current.Resuming   += Current_Resuming;
        }
 private void LogResult(Task <HttpResponseMessage> task, EventGridEvent evt, SubscriptionSettings subscription)
 {
     if (task.IsCompletedSuccessfully && task.Result.IsSuccessStatusCode)
     {
         _logger.LogDebug("Event {EventId} sent to subscriber '{SubscriberName}' successfully.", evt.Id, subscription.Name);
     }
     else if (IsWebHookNotListening(task))
     {
         _logger.LogError("Event {EventId} sent to subscriber '{SubscriberName}' failed, Subscriber actively refused connection.", evt.Id, subscription.Name);
     }
     else
     {
         _logger.LogError(task.Exception?.GetBaseException(),
                          "Failed to send event {EventId} to subscriber '{SubscriberName}', '{TaskStatus}', '{Reason}'.",
                          evt.Id,
                          subscription.Name,
                          task.Status.ToString(),
                          task.Result?.ReasonPhrase);
     }
 }
コード例 #13
0
        public SubscriptionHomeController(NccSettingsService nccSettingsService, ILoggerFactory factory, SubscriptionUserService subscriptionUserService)
        {
            _logger = factory.CreateLogger <SubscriptionHomeController>();
            nccSubscriptionSettings = new SubscriptionSettings();

            _nccSettingsService      = nccSettingsService;
            _subscriptionUserService = subscriptionUserService;
            try
            {
                var tempSettings = _nccSettingsService.GetByKey("NccSubscription_Settings");
                if (tempSettings != null)
                {
                    nccSubscriptionSettings = JsonConvert.DeserializeObject <SubscriptionSettings>(tempSettings.Value);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
            }
        }
コード例 #14
0
        public void It_reads_catalog_from_open_connection()
        {
            var definition = new SqlServerTransport();
            Func <Task <SqlConnection> > factory = async() =>
            {
                var connection = new SqlConnection(connectionString);
                await connection.OpenAsync().ConfigureAwait(false);

                return(connection);
            };
            var settings = new SettingsHolder();

            settings.Set(SettingsKeys.ConnectionFactoryOverride, factory);
            var pubSubSettings = new SubscriptionSettings();

            pubSubSettings.DisableSubscriptionCache();
            settings.Set(pubSubSettings);
            definition.Initialize(settings, "Invalid-connection-string");
            Assert.Pass();
        }
        private async Task SendToSubscriber(SubscriptionSettings subscription, EventGridEvent[] events)
        {
            try
            {
                if (!subscription.DisableValidation &&
                    subscription.ValidationStatus != SubscriptionValidationStatus.ValidationSuccessful)
                {
                    _logger.LogWarning("Subscription '{SubscriberName}' can't receive events. It's still pending validation.", subscription.Name);
                    return;
                }

                _logger.LogDebug("Sending to subscriber '{SubscriberName}'.", subscription.Name);

                // "Event Grid sends the events to subscribers in an array that has a single event. This behaviour may change in the future."
                // https://docs.microsoft.com/en-us/azure/event-grid/event-schema
                foreach (var evt in events)
                {
                    if (subscription.Filter.AcceptsEvent(evt))
                    {
                        var json = JsonConvert.SerializeObject(new[] { evt }, Formatting.Indented);
                        using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
                        {
                            var httpClient = _httpClientFactory.CreateClient();
                            httpClient.DefaultRequestHeaders.Add("aeg-event-type", "Notification");
                            httpClient.Timeout = TimeSpan.FromSeconds(15);

                            await httpClient.PostAsync(subscription.Endpoint, content)
                            .ContinueWith(t => LogResult(t, evt, subscription));
                        }
                    }
                    else
                    {
                        _logger.LogWarning("Event {EventId} filtered out for subscriber '{SubscriberName}'.", evt.Id, subscription.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to send to subscriber '{SubscriberName}'.", subscription.Name);
            }
        }
コード例 #16
0
    protected override void Setup(FeatureConfigurationContext context)
    {
        var settings = context.Settings;

        var connectionManager = settings.GetConnectionBuilder <StorageType.Subscriptions>();
        var tablePrefix       = settings.GetTablePrefix();
        var sqlDialect        = settings.GetSqlDialect();
        var cacheFor          = SubscriptionSettings.GetCacheFor(settings);
        var persister         = new SubscriptionPersister(connectionManager, tablePrefix, sqlDialect, cacheFor);

        sqlDialect.ValidateTablePrefix(tablePrefix);

        settings.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.Subscriptions",
                                              new
        {
            EntriesCashedFor        = cacheFor,
            CustomConnectionBuilder = settings.HasSetting($"SqlPersistence.ConnectionManager.{typeof(StorageType.Subscriptions).Name}")
        });

        context.Container.RegisterSingleton(typeof(ISubscriptionStorage), persister);
    }
コード例 #17
0
        public async Task <ComicDeliveryResult> SendComicTo(SubscriptionSettings settings)
        {
            HttpResponseMessage response = await client.PostAsync(settings.WebhookUrl, content.Value);

            if (response.IsSuccessStatusCode)
            {
                return(new ComicDeliveryResult()
                {
                    IsSuccess = true
                });
            }
            else
            {
                string errorResponse = await response.Content.ReadAsStringAsync();

                return(new ComicDeliveryResult()
                {
                    IsSuccess = false, Message = errorResponse
                });
            }
        }
コード例 #18
0
        public void LoadAndReplaceValueUsingSettings()
        {
            var log        = A.Fake <ILog>();
            var settings   = A.Fake <ISettings>();
            var fileSystem = A.Fake <IFileSystemProxy>();

            A.CallTo(() => settings.SubscriptionFileSharePath).Returns(nameof(settings.SubscriptionFileSharePath));
            A.CallTo(() => settings.SSRSUser).Returns(nameof(settings.SSRSUser));
            A.CallTo(() => settings.SSRSPassword).Returns(nameof(settings.SSRSPassword));
            A.CallTo(() => fileSystem.LoadXElement(string.Empty)).Returns(XElement.Parse(@"
<SubscriptionSettings>
  <ExtensionName>" + SubscriptionSettings.ReportServerFileShare + @"</ExtensionName>
  <ExtensionParameters>
    <Parameter>
      <Name>PATH</Name>
      <Value>Sample</Value>
    </Parameter>
    <Parameter>
      <Name>USERNAME</Name>
      <Value>user</Value>
    </Parameter>
    <Parameter>
      <Name>PASSWORD</Name>
      <Value>password</Value>
    </Parameter>
  </ExtensionParameters>
</SubscriptionSettings>"));

            var instance = new SubscriptionSettings(log, settings, fileSystem);

            instance.Load(string.Empty);

            var extensionParameters = instance.ExtensionParameters;

            Assert.Equal(nameof(settings.SubscriptionFileSharePath), extensionParameters.Single(x => x.Name == "PATH").Value);
            Assert.Equal(nameof(settings.SSRSUser), extensionParameters.Single(x => x.Name == "USERNAME").Value);
            Assert.Equal(nameof(settings.SSRSPassword), extensionParameters.Single(x => x.Name == "PASSWORD").Value);
            A.CallTo(() => fileSystem.LoadXElement(A <string> ._)).MustHaveHappened();
        }
コード例 #19
0
ファイル: QueueClient.cs プロジェクト: gerakul/SqlQueue
        public void UpdateSubscription(string name, SubscriptionSettings settings)
        {
            var subID = FindSubscriptionOrThrowException(name);

            using (var conn = new SqlConnection(ConnectionString))
            {
                conn.Open();

                var cmd = conn.CreateCommand();
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = $"[{QueueName}].[SetSubscriptionSettings]";
                cmd.Parameters.AddWithValue("subscriptionID", subID);
                cmd.Parameters.AddWithValue("maxIdleIntervalSeconds", settings.MaxIdleIntervalSeconds.HasValue
                    ? new SqlInt32(settings.MaxIdleIntervalSeconds.Value) : SqlInt32.Null);
                cmd.Parameters.AddWithValue("maxUncompletedMessages", settings.MaxUncompletedMessages.HasValue
                    ? new SqlInt32(settings.MaxUncompletedMessages.Value) : SqlInt32.Null);
                cmd.Parameters.AddWithValue("actionOnLimitExceeding", settings.ActionOnLimitExceeding.HasValue
                    ? new SqlInt32((int)settings.ActionOnLimitExceeding.Value) : SqlInt32.Null);

                cmd.ExecuteNonQuery();
            }
        }
コード例 #20
0
        /// <summary>
        /// Change the Subscription Tracking settings
        /// </summary>
        /// <param name="enabled">if set to <c>true</c> [enabled].</param>
        /// <param name="landingPageHtml">The landing page HTML.</param>
        /// <param name="url">The URL.</param>
        /// <param name="replacementTag">The replacement tag.</param>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <param name="textContent">Content of the text.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The <see cref="SubscriptionSettings" />.
        /// </returns>
        public async Task <SubscriptionSettings> UpdateSubscriptionTrackingSettingsAsync(bool enabled, string landingPageHtml, string url, string replacementTag, string htmlContent, string textContent, CancellationToken cancellationToken = default(CancellationToken))
        {
            var subscriptionTrackingSettings = new SubscriptionSettings
            {
                Enabled         = enabled,
                LandingPageHtml = landingPageHtml,
                Url             = url,
                ReplacementTag  = replacementTag,
                HtmlContent     = htmlContent,
                TextContent     = textContent
            };
            var data     = JObject.FromObject(subscriptionTrackingSettings);
            var response = await _client.PatchAsync("/tracking_settings/subscription", data, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccess();

            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var subscriptionSettings = JObject.Parse(responseContent).ToObject <SubscriptionSettings>();

            return(subscriptionSettings);
        }
コード例 #21
0
 public ReturnRequestModelFactory(IReturnRequestService returnRequestService,
                                  ISubscriptionService subscriptionService,
                                  IWorkContext workContext,
                                  IStoreContext storeContext,
                                  ICurrencyService currencyService,
                                  IPriceFormatter priceFormatter,
                                  ILocalizationService localizationService,
                                  IDateTimeHelper dateTimeHelper,
                                  IDownloadService downloadService,
                                  SubscriptionSettings subscriptionSettings,
                                  ICacheManager cacheManager)
 {
     this._returnRequestService = returnRequestService;
     this._subscriptionService  = subscriptionService;
     this._workContext          = workContext;
     this._storeContext         = storeContext;
     this._currencyService      = currencyService;
     this._priceFormatter       = priceFormatter;
     this._localizationService  = localizationService;
     this._dateTimeHelper       = dateTimeHelper;
     this._downloadService      = downloadService;
     this._subscriptionSettings = subscriptionSettings;
     this._cacheManager         = cacheManager;
 }
コード例 #22
0
        public IServiceBusReceiveEndpointTopology CreateReceiveEndpointTopology(Uri inputAddress, SubscriptionSettings settings)
        {
            var topologyLayout = BuildTopology(settings);

            return(new ServiceBusReceiveEndpointTopology(_configuration, inputAddress, MessageSerializer, _host, _sendTransportProvider, topologyLayout));
        }
コード例 #23
0
 public SubscriptionClientContextFactory(IMessagingFactoryCache messagingFactoryCache, INamespaceCache namespaceCache, IPipe <MessagingFactoryContext> messagingFactoryPipe,
                                         IPipe <NamespaceContext> namespacePipe, SubscriptionSettings settings)
     : base(messagingFactoryCache, namespaceCache, messagingFactoryPipe, namespacePipe, settings)
 {
     _settings = settings;
 }
コード例 #24
0
        private static void UpdateRules(NamespaceManager namespaceManager, string servicebusConnectionString, TopicSettings topic, SubscriptionSettings subscription)
        {
            string sqlExpression = null;
            if (!string.IsNullOrWhiteSpace(subscription.SqlFilter))
            {
                sqlExpression = subscription.SqlFilter;
            }

            UpdateSqlFilter(namespaceManager, servicebusConnectionString, sqlExpression, subscription.Name, topic.Path);
        }
コード例 #25
0
        private void CreateSubscriptionIfNotExists(NamespaceManager namespaceManager, TopicSettings topic, SubscriptionSettings subscription)
        {
            var subscriptionDescription =
                new SubscriptionDescription(topic.Path, subscription.Name)
                {
                    RequiresSession = subscription.RequiresSession,
                    LockDuration = TimeSpan.FromSeconds(150),
                };

            try
            {
                namespaceManager.CreateSubscription(subscriptionDescription);
            }
            catch (MessagingEntityAlreadyExistsException) { }
        }
コード例 #26
0
 public Task <ComicDeliveryResult> Push(SubscriptionSettings settings)
 {
     return(StartDeliveryTask(settings));
 }
コード例 #27
0
        /// <summary>
        /// Calculate volume for slave account
        /// </summary>
        /// <param name="signal">Signal initiator</param>
        /// <param name="equity"></param>
        /// <param name="settings">Subscription settigns</param>
        /// <param name="balance"></param>
        /// <returns>Volume</returns>
        public static double CalculateVolume(MT4TradeSignal signal, double balance, double equity, SubscriptionSettings settings)
        {
            switch ((SubscriptionType)settings.SignalType)
            {
            case SubscriptionType.Fixed:
                return(settings.MaxVolume / 100d);

            case SubscriptionType.ByBalance:
                if (Math.Abs(balance) < 0.000001)
                {
                    return(double.NaN);                                                      // Balance is empty
                }
                return(signal.Volume * (balance / signal.Balance) * settings.Risk);

            case SubscriptionType.ByEquity:
                if (Math.Abs(equity) < 0.000001)
                {
                    return(double.NaN);                                                     // Balance is empty
                }
                return(signal.Volume * (equity / signal.Equity) * settings.Risk);

            case SubscriptionType.ByMultiplier:
                return(signal.Volume * settings.Multiplier);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #28
0
        private async Task <bool> ValidateSubscription(TopicSettings topic, SubscriptionSettings subscription)
        {
            var validationUrl = $"https://{_validationIpAddress}:{topic.Port}/validate?id={subscription.ValidationCode}";

            try
            {
                _logger.LogDebug("Sending subscription validation event to subscriber '{SubscriberName}'.", subscription.Name);

                var evt = new EventGridEvent
                {
                    EventTime       = DateTime.UtcNow.ToString("O"),
                    DataVersion     = "1",
                    EventType       = "Microsoft.EventGrid.SubscriptionValidationEvent",
                    Id              = Guid.NewGuid().ToString(),
                    Subject         = "",
                    MetadataVersion = "1",
                    Data            = new SubscriptionValidationRequest
                    {
                        ValidationCode = subscription.ValidationCode,
                        ValidationUrl  = $"https://{_validationIpAddress}:{topic.Port}/validate?id={subscription.ValidationCode}"
                    }
                };

                var json = JsonConvert.SerializeObject(new[] { evt }, Formatting.Indented);
                using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
                {
                    var httpClient = _httpClientFactory.CreateClient();
                    httpClient.DefaultRequestHeaders.Add("aeg-event-type", "SubscriptionValidation");

                    if (!string.IsNullOrEmpty(topic.Key))
                    {
                        httpClient.DefaultRequestHeaders.Add("aeg-sas-key", topic.Key);
                    }

                    httpClient.Timeout = TimeSpan.FromSeconds(15);

                    subscription.ValidationStatus = SubscriptionValidationStatus.ValidationEventSent;

                    var response = await httpClient.PostAsync(subscription.Endpoint, content);

                    response.EnsureSuccessStatusCode();

                    var text = await response.Content.ReadAsStringAsync();

                    var validationResponse = JsonConvert.DeserializeObject <SubscriptionValidationResponse>(text);

                    if (validationResponse.ValidationResponse == subscription.ValidationCode)
                    {
                        subscription.ValidationStatus = SubscriptionValidationStatus.ValidationSuccessful;
                        _logger.LogInformation("Successfully validated subscriber '{SubscriberName}'.", subscription.Name);
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to receive validation event from subscriber '{SubscriberName}'", subscription.Name);
                _logger.LogInformation("'{SubscriberName}' manual validation url: {ValidationUrl}", subscription.Name, validationUrl);
            }

            subscription.ValidationStatus = SubscriptionValidationStatus.ValidationFailed;
            return(false);
        }
コード例 #29
0
        public static ExecutionOrder Resolve(MT4TradeSignal signal, int login, double balance, double equity, SubscriptionSettings settings)
        {
            //Close only
            if (((SubscriptionStatus)settings.Status == SubscriptionStatus.CloseOnly && signal.ActionType != ActionType.Close))
            {
                return(null);
            }
            //Side
            if (((SignalOrderType)settings.OrdersType == SignalOrderType.Buy && signal.Side == TradeSide.Sell) ||
                ((SignalOrderType)settings.OrdersType == SignalOrderType.Sell && signal.Side == TradeSide.Buy))
            {
                return(null);
            }

            var execution = new ExecutionOrder
            {
                ActionType = signal.ActionType,
                Login      = login,
                //Reverse
                Side    = GetSide(settings.Reverse, signal.Side),
                Symbol  = signal.Symbol,
                OrderID = signal.OrderID
            };

            //Max volume
            execution.Volume = CalculateVolume(signal, balance, equity, settings);
            if (settings.MaxVolume != -1)
            {
                execution.Volume = execution.Volume > (settings.MaxVolume / 100d) ? (settings.MaxVolume / 100d) : execution.Volume;
            }
            execution.Commission = 1.7d;
            return(execution);
        }
コード例 #30
0
        public FeedResultAddToWatchLater(
            IScheduler scheduler,
            SubscriptionManager subscriptionManager,
            SubscriptionSettings subscriptionSettingsRepository,
            QueuePlaylist queuePlaylist
            )
        {
            _scheduler                      = scheduler;
            _subscriptionManager            = subscriptionManager;
            _subscriptionSettingsRepository = subscriptionSettingsRepository;
            _queuePlaylist                  = queuePlaylist;
            Observable.FromEventPattern <SubscriptionFeedUpdateResult>(
                h => _subscriptionManager.Updated += h,
                h => _subscriptionManager.Updated -= h
                )
            .Select(x => x.EventArgs)
            .Do(x => Results.Add(x))
            .Throttle(TimeSpan.FromSeconds(5))
            .SubscribeOn(_scheduler)
            .Subscribe(_ =>
            {
                var items = Results.ToList();
                Results.Clear();

                foreach (var newVideo in items.SelectMany(x => x.NewVideos))
                {
                    if (!_queuePlaylist.Contains(newVideo.VideoId))
                    {
                        _queuePlaylist.Add(newVideo);

                        Debug.WriteLine("[FeedResultAddToWatchLater] added: " + newVideo.Label);
                    }
                }

                /*
                 * if (!_subscriptionSettingsRepository.IsSortWithSubscriptionUpdated)
                 * {
                 *  foreach (var newVideo in items.SelectMany(x => x.NewVideos))
                 *  {
                 *      _queuePlaylist.Add(newVideo);
                 *
                 *      Debug.WriteLine("[FeedResultAddToWatchLater] added: " + newVideo.Label);
                 *  }
                 * }
                 * else
                 * {
                 *  // 注意: SubscriptionManager.Updatedイベントの挙動に依存した動作になる
                 *  // 新着動画が無くても購読を上から順番に全部更新し通知するという仕様に依存する
                 *  // キチンとやるなら 新着の無い購読ソースの動画が歯抜けにならぬよう SubscriptionManager.GetAllSubscriptionInfo() を利用して埋める必要がある
                 *
                 *  var backup = _hohoemaPlaylist.QueuePlaylist.ToImmutableArray();
                 *  var watchAfterItems = _hohoemaPlaylist.QueuePlaylist.ToDictionary(x => x.VideoId);
                 *  _hohoemaPlaylist.QueuePlaylist.ClearOnScheduler();
                 *
                 *  List<NicoVideo> videos = new List<NicoVideo>();
                 *  foreach (var subscUpdateResult in items)
                 *  {
                 *      // あとで見るに購読から追加済みのものを切り分けてリスト化
                 *      List<NicoVideo> unsortedVideos = new List<NicoVideo>();
                 *      foreach (var video in subscUpdateResult.Videos)
                 *      {
                 *          if (watchAfterItems.Remove(video.Id, out var item))
                 *          {
                 *              unsortedVideos.Add(video);
                 *          }
                 *      }
                 *
                 *      // 新着動画も加えて
                 *      unsortedVideos.AddRange(subscUpdateResult.NewVideos);
                 *
                 *      if (subscUpdateResult.Entity.SourceType == SubscriptionSourceType.User)
                 *      {
                 *          // 購読ソース毎の動画リストに対するソートを実行
                 *          // 1. タイトルの類似度によるグループ化
                 *          // 2. 類似度グループ内でのPostAtによる昇順ソート(同一投稿時間の場合は動画タイトルによる昇順ソート)
                 *          // 3. 各類似度グループの個数による昇順ソート
                 *
                 *          const double TitleSimilarlityThreshold = 0.60;
                 *
                 *          // Note: 類似度のしきい値について
                 *          // 0.9ぐらい高くしてしまうと、例えばパート投稿してるシリーズの「サブタイトル」部分の変化で類似判定から漏れてしまいます
                 *          // 逆に低すぎると「【ゆっくり実況】xxxxxのxxxx partYY」といったタイトルの他パート動画と同じ定型部分によって類似判定が通ってしまいます
                 *
                 *          var nearByTitleMap = new Dictionary<string, List<NicoVideo>>();
                 *          foreach (var video in unsortedVideos)
                 *          {
                 *              bool isDetected = false;
                 *              foreach (var heroTitle in nearByTitleMap.Keys)
                 *              {
                 *                  if (StringHelper.CalculateSimilarity(heroTitle, video.Title) >= TitleSimilarlityThreshold)
                 *                  {
                 *                      nearByTitleMap[heroTitle].Add(video);
                 *                      isDetected = true;
                 *                      break;
                 *                  }
                 *              }
                 *
                 *              if (!isDetected)
                 *              {
                 *                  nearByTitleMap.Add(video.Title, new List<NicoVideo>() { video });
                 *              }
                 *          }
                 *
                 *          videos.AddRange(nearByTitleMap.Values.OrderBy(x => x.Count).SelectMany(x => x.OrderBy(x => x.PostedAt).ThenBy(x => x.Title)));
                 *      }
                 *      else
                 *      {
                 *          videos.AddRange(unsortedVideos.OrderBy(x => x.PostedAt));
                 *      }
                 *
                 *  }
                 *
                 *  // ここまでで watchAfterItems には購読ソースに関連しない動画のみが残ってる
                 *
                 *  // 購読ソース毎タイトルでソート済みの動画 と あとで見るに追加されていたが購読ソースと関連しない動画 を連結してあとで見るに追加
                 *  try
                 *  {
                 *      _hohoemaPlaylist.QueuePlaylist.AddRangeOnScheduler(
                 *          videos.Concat(watchAfterItems.Values)
                 *          );
                 *  }
                 *  catch
                 *  {
                 *      _hohoemaPlaylist.QueuePlaylist.AddRangeOnScheduler(backup);
                 *  }
                 * }
                 */
            });
        }
コード例 #31
0
 public PrepareSubscriptionClientFilter(SubscriptionSettings settings)
 {
     _settings = settings;
 }
コード例 #32
0
 public SubscriptionClientContext(IMessageReceiver messageReceiver, Uri inputAddress, SubscriptionSettings settings)
 {
     _messageReceiver = messageReceiver;
     _settings        = settings;
     InputAddress     = inputAddress;
 }