/// <summary>
            /// Retrieves the security verification configuration.
            /// </summary>
            /// <returns>The security verification configuration.</returns>
            public LogOnConfiguration GetSecurityVerificationConfiguration()
            {
                LogOnConfiguration verificationConfiguration;

                if (this.CanUseLocalDatabase)
                {
                    GetChannelConfigurationDataRequest getChannelConfiguration = new GetChannelConfigurationDataRequest(this.ChannelId.Value);
                    ChannelConfiguration channelConfiguration = this.context.Execute <SingleEntityDataServiceResponse <ChannelConfiguration> >(getChannelConfiguration).Entity;

                    // make sure channel configuration is valid
                    if (channelConfiguration == null)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture,
                            "The channel {0} does not exist.",
                            this.ChannelId.Value);
                        throw new SecurityException(SecurityErrors.Microsoft_Dynamics_Commerce_Runtime_InvalidChannel, errorMessage);
                    }

                    verificationConfiguration = channelConfiguration.TransactionServiceProfile.StaffLogOnConfiguration;
                }
                else
                {
                    // no channel, we can only use headquarters
                    verificationConfiguration = LogOnConfiguration.RealTimeService;
                }

                return(verificationConfiguration);
            }
Exemplo n.º 2
0
        /// <summary>
        /// Edits the channel.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        void EditChannel(ChannelConfiguration configuration)
        {
            if (configuration != null)
            {
                ChannelSetupControlPanel.Children.Clear();

                // Setup Control
                ChannelSetupControl setupControl = new ChannelSetupControl(configuration.Clone());
                setupControl.IsInEditModus         = true;
                setupControl.Username              = configuration.InputChannel.Authentication.Username;
                setupControl.HorizontalAlignment   = HorizontalAlignment.Center;
                setupControl.VerticalAlignment     = VerticalAlignment.Center;
                setupControl.OnValidationFinished += OnValidationFinishedHandler;
                setupControl.OnCancel             += OnCancelHandler;
                setupControl.RenderTransform       = new TranslateTransform(0, 0);

                ChannelSetupControlPanel.Children.Add(setupControl);

                // Play Animation
                var firstItem  = (FrameworkElement)transitionContainer.Items[0];
                var secondItem = (FrameworkElement)transitionContainer.Items[1];

                FlipTransition transition = Resources["FlipTransition"] as FlipTransition;
                transition.Rotation                      = Direction.RightToLeft;
                transitionContainer.Transition           = transition;
                transitionContainer.TransitionCompleted -= OnTransitionCompleted;
                transitionContainer.ApplyTransition(firstItem, secondItem);

                OnPropertyChanged("AllChannelConfigurations");
                OnPropertyChanged("ChannelConfiguration");
            }
        }
Exemplo n.º 3
0
        void LoadChannelConfigs()
        {
            if (!configLoaded)
            {
                if (SourceChannelId > 0)
                {
                    var channel = ChannelsManager.GetChannelObject(SourceChannelId);

                    if (channel != null)
                    {
                        sourceChannelConfig = channel.Configuration;
                    }
                }

                if (TargetChannelId > 0)
                {
                    var channel = ChannelsManager.GetChannelObject(TargetChannelId);

                    if (channel != null)
                    {
                        targetChannelConfig = channel.Configuration;
                    }
                }

                configLoaded = true;
            }
        }
Exemplo n.º 4
0
            /// <summary>
            /// Inserts audit log.
            /// </summary>
            /// <param name="request">The <see cref="InsertAuditLogDataRequest"/>log request.</param>
            /// <returns>The <see cref="NullResponse"/>response.</returns>
            private NullResponse InsertAuditLog(InsertAuditLogDataRequest request)
            {
                // Insert
                ChannelConfiguration channelConfiguration = request.RequestContext.GetChannelConfiguration();

                // RetailLog is an AX table, DataAreaId field is mandatory. We need to confirm channelConfiguration is present
                // before inserting data to RetailLog, otherwise P-job will fail due to DataAreaId is missing.
                if (channelConfiguration != null)
                {
                    var parameters = new ParameterSet();
                    parameters["@RETAILLOGID"]        = DateTimeOffset.UtcNow.Ticks;
                    parameters["@DATE"]               = request.RequestContext.GetNowInChannelTimeZone().DateTime;
                    parameters["@CODEUNIT"]           = request.Source;
                    parameters["@LOGSTRING"]          = request.LogEntry;
                    parameters["@LOGLEVEL"]           = request.LogLevel;
                    parameters["@STOREID"]            = request.StoreId;
                    parameters["@TERMINALID"]         = request.TerminalId;
                    parameters["@DURATIONINMILLISEC"] = request.DurationInMilliseconds;
                    parameters["@DATAAREAID"]         = channelConfiguration.InventLocationDataAreaId;

                    using (SqlServerDatabaseContext sqlServerDatabaseContext = new SqlServerDatabaseContext(request))
                    {
                        sqlServerDatabaseContext.ExecuteStoredProcedureNonQuery(AuditLogSqlServerDataService.InsertAuditLogSprocName, parameters);
                    }
                }

                return(new NullResponse());
            }
 public ReceiveFoldersTask(ChannelConfiguration config, IClientInputChannel channel) : base(config, channel)
 {
     this.config      = config;
     this.channel     = channel;
     this.folders     = new List <ChannelFolder>();
     this.dataService = ClientState.Current.DataService;
 }
            /// <summary>
            /// Cancels a customer order on the headquarters.
            /// </summary>
            /// <param name="request">The save customer order request.</param>
            /// <returns>The customer order service default response.</returns>
            private static Response SaveCancellationOrder(SaveCustomerOrderRealtimeRequest request)
            {
                Response             response;
                SalesTransaction     salesTransaction     = request.SalesTransaction;
                ChannelConfiguration channelConfiguration = request.ChannelConfiguration;

                // Keep all charge line references
                List <ChargeLine> chargeLines = new List <ChargeLine>(salesTransaction.ChargeLines);

                if (!string.IsNullOrWhiteSpace(channelConfiguration.CancellationChargeCode))
                {
                    // Get all cancellation charges
                    var cancellationChargeLines = salesTransaction.ChargeLines
                                                  .Where(chargeLine => channelConfiguration.CancellationChargeCode.Equals(chargeLine.ChargeCode, StringComparison.OrdinalIgnoreCase))
                                                  .ToArray();

                    // Remove all non-cancellation charges from header - since AX will blindly use the charges to header as cancellation charges
                    salesTransaction.ChargeLines.Clear();
                    salesTransaction.ChargeLines.AddRange(cancellationChargeLines);
                }

                // Cancels order in headquarters
                response = CustomerOrderService.SaveCustomerOrderInHeadquarter(request);

                // Restore charge lines
                salesTransaction.ChargeLines.Clear();
                salesTransaction.ChargeLines.AddRange(chargeLines);

                return(response);
            }
 public UpdateMessageStateTask(ChannelConfiguration config, IReadStateChannel channel, List <ChannelFolder> availableFolders, Message message)
 {
     this.config           = config;
     this.channel          = channel;
     this.availableFolders = availableFolders;
     this.message          = message;
 }
Exemplo n.º 8
0
        public GoogleSheetProxy(ChannelConfiguration configuration, ILoggerFactory loggerFactory)
        {
            Config      = configuration;
            this.Logger = loggerFactory.CreateLogger("GoogleSheetProxy");

            ConfigureGoogleSheetsAccess();
        }
Exemplo n.º 9
0
        public void ShouldGetFeatureConfiguration()
        {
            // arrange
            const string CHANNELNAME = "TestChannel";
            var          config      = new ChannelConfiguration()
            {
                ChannelId = "1234"
            };

            config.FeatureConfigurations.Add("UserActivityConfiguration", new UserActivityConfiguration
            {
                ChannelName = CHANNELNAME,
                IsEnabled   = true,
                Type        = UserActivityConfiguration.UserActivityTrainType.Follow
            });
            base.AddChannelConfiguration(CHANNELNAME, config);

            var configActor = this.Sys.ActorOf(Props.Create <CORE.ChannelConfigurationActor>(base.ConfigurationContext, null), "TestConfig");

            BotConfiguration.ChannelConfigurationInstancePath = configActor.Path.ToStringWithAddress();

            // act
            var sut = new UserActivityTrainModel();

            sut.ChannelName = CHANNELNAME;
            sut.ActorSystem = this.Sys;
            sut.GetWidgetConfiguration();

            // assert
            Assert.NotNull(sut.Configuration);
        }
Exemplo n.º 10
0
 public ValidateLoginTask(ChannelConfiguration configuration, IClientInputChannel channel)
     : base(configuration, channel)
 {
     this.configuration = configuration;
     this.channel       = channel;
     this.context       = new SetupChannelClientContext();
 }
Exemplo n.º 11
0
 public ReceiveMessageDetailsTask(ChannelConfiguration config, IClientInputChannel channel, ChannelMessageHeader header, ChannelFolder folder)
 {
     this.config  = config;
     this.channel = channel;
     this.header  = header;
     this.folder  = folder;
 }
Exemplo n.º 12
0
        public NewSubscriberActor(ChannelConfiguration config, IEnumerable <IFeature> features, ICurrencyRepository currencyRepository)
        {
            this.Config             = config;
            this.CurrencyRepository = currencyRepository;

            this.Receive <OnNewSubscriberArgs>(NewSubscriber);
        }
Exemplo n.º 13
0
        public async Task CreateOrUpdateChannelConfiguration(ChannelConfigurationItemViewModel item)
        {
            ChannelConfiguration entity;

            if (string.IsNullOrWhiteSpace(item.Id))
            {
                entity      = new ChannelConfiguration();
                entity.User = GetCurrentUser();
            }
            else
            {
                entity = await unitOfWork.GetAll <ChannelConfiguration>()
                         .Include(x => x.User)
                         .Include(x => x.HardwareFunction)
                         .SingleAsync(x => x.Id == item.Id);
            }

            entity.ChannelNumber   = item.ChannelNumber > 0 ? item.ChannelNumber : 1;
            entity.StartNucleotide = !string.IsNullOrWhiteSpace(item.StartNucleotide) ? item.StartNucleotide : "A";

            if (item.HardwareFunction != null && !string.IsNullOrWhiteSpace(item.HardwareFunction.Id))
            {
                entity.HardwareFunction = unitOfWork.GetById <HardwareFunction>(item.HardwareFunction.Id);
            }
            else
            {
                entity.HardwareFunction =
                    await unitOfWork.GetAll <HardwareFunction>().Where(x => x.FunctionType == HardwareFunctionType.ActivateChannel).FirstAsync();
            }

            unitOfWork.InsertOrUpdate(entity);
            unitOfWork.Commit();
        }
Exemplo n.º 14
0
 public void SetChannel(ChannelConfiguration channel)
 {
     if (channel != null)
     {
         ChannelName = channel.DisplayName;
     }
 }
Exemplo n.º 15
0
            /// <summary>
            /// Initializes a new instance of the <see cref="SqliteDatabaseContext"/> class.
            /// </summary>
            /// <param name="requestContext">The request context.</param>
            public SqliteDatabaseContext(RequestContext requestContext)
                : base(requestContext)
            {
                ChannelConfiguration channelConfiguration = requestContext.GetChannelConfiguration();

                if (channelConfiguration != null)
                {
                    this.ChannelId  = channelConfiguration.RecordId;
                    this.DataAreaId = channelConfiguration.InventLocationDataAreaId;
                }

                OrgUnit orgUnit = requestContext.GetOrgUnit();

                if (orgUnit != null)
                {
                    this.StoreNumber = orgUnit.OrgUnitNumber;
                }

                this.connectionElementUniqueIdentifier = 0;
                this.ShiftId         = requestContext.GetPrincipal().ShiftId;
                this.ShiftTerminalId = requestContext.GetPrincipal().ShiftTerminalId;

                GetCurrentTerminalIdDataRequest dataRequest = new GetCurrentTerminalIdDataRequest();

                this.TerminalId = requestContext.Runtime.Execute <SingleEntityDataServiceResponse <string> >(dataRequest, requestContext, skipRequestTriggers: true).Entity;
            }
Exemplo n.º 16
0
        public ReSubscriberActor(ChannelConfiguration config, ICurrencyRepository currencyRepository)
        {
            this.Config             = config;
            this.CurrencyRepository = currencyRepository;

            this.Receive <OnReSubscriberArgs>(ReSubscriber);
        }
Exemplo n.º 17
0
        public GiftSubscriberActor(ChannelConfiguration config, IEnumerable <IFeature> features, ICurrencyRepository currencyRepository)
        {
            this.Config             = config;
            this.CurrencyRepository = currencyRepository;

            this.Receive <OnGiftedSubscriptionArgs>(GiftSub);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RabbitAcknowledger"/> class.
 /// </summary>
 /// <param name="configuration">channel configuration</param>
 /// <param name="rabbitMQChannel">RabbitMQ channel/model</param>
 /// <param name="logger">injected logger</param>
 public RabbitAcknowledger(ChannelConfiguration configuration, IModel rabbitMQChannel, ILogger logger)
     : base(configuration, rabbitMQChannel, logger)
 {
     Arguments.NotNull(configuration, nameof(configuration));
     Arguments.NotNull(rabbitMQChannel, nameof(rabbitMQChannel));
     Arguments.NotNull(logger, nameof(logger));
 }
Exemplo n.º 19
0
            /// <summary>
            /// Gets the channel currency string template.
            /// </summary>
            /// <param name="ecommerceContext">The eCommerce context.</param>
            /// <returns>The template for channel currency string.</returns>
            public static async Task <string> GetChannelCurrencyStringTemplate(EcommerceContext ecommerceContext)
            {
                OperatingUnitConfiguration operatingUnitConfig = null;

                if (cachedOperatingUnitConfig.TryGetValue(ecommerceContext.OperatingUnitId, out operatingUnitConfig))
                {
                    if (!string.IsNullOrEmpty(operatingUnitConfig.CurrencyStringTemplate))
                    {
                        return(operatingUnitConfig.CurrencyStringTemplate);
                    }
                }

                ManagerFactory       factory              = Utilities.GetManagerFactory(ecommerceContext);
                IOrgUnitManager      orgUnitManager       = factory.GetManager <IOrgUnitManager>();
                ChannelConfiguration channelConfiguration = await orgUnitManager.GetOrgUnitConfiguration();

                string currencySymbol = Utilities.GetChannelCurrencySymbol(channelConfiguration.Currency);

                CultureInfo      cultureInfo      = Utilities.GetCultureInfo(ecommerceContext.Locale);
                NumberFormatInfo nfi              = cultureInfo.NumberFormat;
                bool             symbolToTheRight = (nfi.CurrencyPositivePattern % 2 == 0) ? false : true;

                string currencyTemplate = symbolToTheRight ? "{0}" + currencySymbol : currencySymbol + "{0}";

                // Update cache
                Utilities.cachedOperatingUnitConfig[ecommerceContext.OperatingUnitId].CurrencySymbol         = currencySymbol;
                Utilities.cachedOperatingUnitConfig[ecommerceContext.OperatingUnitId].CurrencyStringTemplate = currencyTemplate;

                return(currencyTemplate);
            }
Exemplo n.º 20
0
            private static RoundingRule GetRoundingRule(RequestContext context)
            {
                ChannelConfiguration channelConfiguration = context.GetChannelConfiguration();
                string currencyCode = channelConfiguration.Currency;

                return(amountToRound => RoundWithPricesRounding(context, amountToRound, currencyCode));
            }
Exemplo n.º 21
0
        public RaidActor(ChannelConfiguration config, ICurrencyRepository currencyRepository)
        {
            this.Config             = config;
            this.CurrencyRepository = currencyRepository;

            this.Receive <OnRaidNotificationArgs>(Raid);
        }
Exemplo n.º 22
0
        void SendCloudMessage(ChannelConfiguration channel, ChannelMessage message)
        {
            var data = String.Format("wrap_access_token={0}&targetchannelkey={1}&from={2}&to={3}&cc={4}&bcc={5}&subject={6}&inreplyto={7}&conversationidentifier={8}&body={9}",
                                     CloudApi.AccessToken,
                                     channel.ChannelKey,
                                     HttpUtility.UrlEncode(message.From.ToString()),
                                     HttpUtility.UrlEncode(message.To.ToString()),
                                     HttpUtility.UrlEncode(message.CC.ToString()),
                                     HttpUtility.UrlEncode(message.BCC.ToString()),
                                     HttpUtility.UrlEncode(message.Context),
                                     HttpUtility.UrlEncode(message.InReplyTo),
                                     HttpUtility.UrlEncode(message.ConversationId),
                                     HttpUtility.UrlEncode(message.BodyHtml.ReadString()));

            string messageKey;

            if (message.Attachments.Count > 0)
            {
                var files = message.Attachments
                            .Select(s => new UploadFile(s.ContentStream, s.Filename, "application/octet-stream"))
                            .ToList();

                messageKey = HttpServiceRequest.Post(String.Concat(CloudApi.ApiBaseUrl, "send/message"), data, files, true);
            }
            else
            {
                messageKey = HttpServiceRequest.Post(String.Concat(CloudApi.ApiBaseUrl, "send/message"), data, true);
            }

            // Update messagekey
            this.message.MessageKey = messageKey;

            ClientState.Current.DataService.Update(this.message);
        }
Exemplo n.º 23
0
        // Sort of registration of factory, because the channel setup is merely a factory containing the data provider instances.
        public void CreateChannel <T1, T2>(IChannelSetup <T1, T2> setup)
            where T1 : TBase1
            where T2 : TBase2
        {
            // Constructing or expanding the channel setup model in such a way while still having type information
            // is a better strategy. Doing it afterwards requires a lot more effort using reflection.
            // - Find endpoints and build configuration using them.
            var t1Endpoint       = Source1.GetEndpoint <T1>();
            var t1Extractor      = Source1.CreateResolver <T1>(); // Because constraint on this, as a whole this can't be moved into Source itself.
            var t1TypeConfig     = new TypeConfiguration <T1, TId>(t1Extractor, Source2.DefaultExtractorValue);
            var t1EndpointConfig = new EndpointConfiguration <T1, TId>(t1TypeConfig, t1Endpoint);

            var t2Endpoint       = Source2.GetEndpoint <T2>();
            var t2Extractor      = Source2.CreateResolver <T2>();
            var t2TypeConfig     = new TypeConfiguration <T2, TId>(t2Extractor, Source2.DefaultExtractorValue);
            var t2EndpointConfig = new EndpointConfiguration <T2, TId>(t2TypeConfig, t2Endpoint);

            var channelConfig = new ChannelConfiguration <T1, T2, TId, ItemMatch <T1, T2> >(t1EndpointConfig, t2EndpointConfig, setup.TypeTranslator);

            var plumber = PlumberFactory.Create(channelConfig, _rules);

            // Could move towards a construction where factories are registered instead of the actual objects for preventing to many channels linguering
            // around in memory. However, right now the channels needs to be singletons and run in sequence due to sqlite limitations of having only one
            // thread writing!
            var channel = setup.Create(channelConfig, plumber);

            _channels.Add(channel);
        }
Exemplo n.º 24
0
 public ItemMatcherTest()
 {
     var channelConfig = new ChannelConfiguration<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(
         ltr => ltr.CorrelationId.HasValue ? ltr.CorrelationId.Value : -1, // This stinks somewhat. Not going with generics is probably the alternative?
         ltr => ltr.Id);
     _itemMatcherUnderTest = new ItemMatcher<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(channelConfig);
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        public IAmqpConsumerManager <IBasicConsumer> CreateConsumerManager(ChannelConfiguration channelConfiguration)
        {
            this.InitializeIfRequired();

            using var auto = new AutoFactory <ConsumerManager>(() => new ConsumerManager(channelConfiguration, this.rabbitMQConnection.CreateModel(), this.Logger.Create("ConsumerManager")));

            return(auto.Return());
        }
Exemplo n.º 26
0
 public IEnumerable <FenceConfiguration> GetFencesConfigurationForChannel(ChannelConfiguration channelConfiguration)
 {
     if (channelConfiguration == null)
     {
         return(new List <FenceConfiguration>());
     }
     return(_fencesConfiguration.GetFences(channelConfiguration.Fences));
 }
Exemplo n.º 27
0
        /// <inheritdoc />
        public IAmqpPublisher CreatePublishManager(ChannelConfiguration channelConfiguration)
        {
            this.InitializeIfRequired();

            using var auto = new AutoFactory <RabbitPublisher>(() => new RabbitPublisher(channelConfiguration, this.rabbitMQConnection.CreateModel(), this.Logger.Create("PublishManager")));

            return(auto.Return());
        }
Exemplo n.º 28
0
        public ItemMatcherTest()
        {
            var channelConfig = new ChannelConfiguration <LocalTestResource, RemoteTestResource, int, ItemMatch <LocalTestResource, RemoteTestResource> >(
                ltr => ltr.CorrelationId.HasValue ? ltr.CorrelationId.Value : -1, // This stinks somewhat. Not going with generics is probably the alternative?
                ltr => ltr.Id);

            _itemMatcherUnderTest = new ItemMatcher <LocalTestResource, RemoteTestResource, int, ItemMatch <LocalTestResource, RemoteTestResource> >(channelConfig);
        }
            private static ReadOnlyCollection <StockCountJournal> GetStockCountJournalsFromAx(RequestContext context)
            {
                ChannelConfiguration channelConfiguration = context.GetChannelConfiguration();

                var stockCountJournalsRequest = new GetStockCountJournalsRealtimeRequest(channelConfiguration.InventLocation);

                return(context.Execute <EntityDataServiceResponse <StockCountJournal> >(stockCountJournalsRequest).PagedEntityCollection.Results);
            }
Exemplo n.º 30
0
            /// <summary>
            /// Gets the channel configuration.
            /// </summary>
            /// <returns>Response containing the channel configuration.</returns>
            public async Task <ActionResult> GetChannelConfiguration()
            {
                EcommerceContext         ecommerceContext         = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                OrgUnitOperationsHandler orgUnitOperationsHandler = new OrgUnitOperationsHandler(ecommerceContext);
                ChannelConfiguration     channelConfiguration     = await orgUnitOperationsHandler.GetChannelConfiguration();

                return(this.Json(channelConfiguration));
            }
        public void ChannelConfigurationTest()
        {
            ChannelConfiguration config = new ChannelConfiguration(DeviceType.PowerMeter, session);

            Assert.IsTrue(config.ChannelId == 2);
            Assert.IsTrue(config.DeviceId == 486);
            Assert.IsTrue(config.DeviceIdLsb == 0xE6);
        }
Exemplo n.º 32
0
        public RiffDTO SaveRiff(string name, AudioFormat audioFormat, ChannelConfiguration channelConfiguration, int sampleRate, byte[] data, string userId)
        {
            var audio = new Audio();

            audio.SetAudioFormat(audioFormat);
            audio.SetChannelConfiguration(channelConfiguration);
            audio.SampleRate = sampleRate;
            audio.Data = data;

            audio = _ar.Insert(audio);

            var riff = new Riff();

            riff.AudioID = audio.AudioID;
            riff.Name = name;
            riff.UserID = userId;

            riff = _rr.Insert(riff);

            return new RiffDTO(riff, audio);
        }
Exemplo n.º 33
0
        public void SetUpTest()
        {
            var type1Config = new TypeConfiguration<LocalTestResource, int>(ltr => ltr.CorrelationId.HasValue ? ltr.CorrelationId.Value : -1);
            _localEndpoint = new InMemoryCrudDataEndpoint<LocalTestResource, int>(type1Config, TestData.LocalResults);
            var endpoint1Config = new EndpointConfiguration<LocalTestResource, int>(
                type1Config,
                _localEndpoint);

            var type2Config = new TypeConfiguration<RemoteTestResource, int>(rtr => rtr.Id);
            _remoteEndpoint = new InMemoryCrudDataEndpoint<RemoteTestResource, int>(type2Config, TestData.RemoteResults);
            var endpoint2Config = new EndpointConfiguration<RemoteTestResource, int>(
                type2Config,
                _remoteEndpoint);

            // This clearly requires a configuration API.
            var channelConfig = new ChannelConfiguration<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(endpoint1Config, endpoint2Config, new TestResourceTranslator());
            var itemsPreprocessor = new ItemMatcher<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(channelConfig);
            channelConfig.ItemsPreprocessor = itemsPreprocessor.Match;
            channelConfig.AddSynchAction(new SynchronizationResolver<ItemMatch<LocalTestResource,RemoteTestResource>, ChannelConfiguration<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>>(
                channelConfig,
                (item, cfg) =>
                {
                    return item.Result1 == null;
                },
                (item, cfg) =>
                {
                    var synchItem = item.Result1;
                    cfg.TypeTranslator.TranslateBackward(item.Result2, ref synchItem);
                    // Now the translate decides wether a new item has to be created, but the decision is there anyway because of the Create.
                    cfg.Type1EndpointConfiguration.Endpoint.Create(synchItem);
                    return new SynchronizationResult(true);
                }
            ));

            //var t2epConfig = new EndpointConfiguration()
            _channelUnderTest = new OneWayPullChannel<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(
                channelConfig,
                () => Task.FromResult(_localEndpoint.ReadAll().AsEnumerable()),
                () => Task.FromResult(_remoteEndpoint.ReadAll().AsEnumerable()));
        }
        public void SetUpTest()
        {
            var type1Config = new TypeConfiguration<LocalTestResource, int>(
                ltr => ltr.CorrelationId.HasValue ? ltr.CorrelationId.Value : -1,
                -1);
            LocalEndpoint = new InMemoryCrudDataEndpoint<LocalTestResource, int>(type1Config, TestData.LocalResults);
            var endpoint1Config = new EndpointConfiguration<LocalTestResource, int>(
                type1Config,
                LocalEndpoint);

            var type2Config = new TypeConfiguration<RemoteTestResource, int>(rtr => rtr.Id, 0);
            RemoteEndpoint = new InMemoryCrudDataEndpoint<RemoteTestResource, int>(type2Config, TestData.RemoteResults);
            var endpoint2Config = new EndpointConfiguration<RemoteTestResource, int>(
                type2Config,
                RemoteEndpoint);

            // This clearly requires a configuration API.
            ChannelConfig = new ChannelConfiguration<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(endpoint1Config, endpoint2Config, new TestResourceTranslator());
            var itemsPreprocessor = new ItemMatcher<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(ChannelConfig);

            ChannelConfig.ItemsPreprocessor = itemsPreprocessor.Match;

            var resolvers = new List<ISynchronizationResolver<ItemMatch<LocalTestResource, RemoteTestResource>>>
            {
                new SynchronizationResolver<ItemMatch<LocalTestResource,RemoteTestResource>, ChannelConfiguration<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>>(
                ChannelConfig,
                (item, cfg) => item.Result1 == null,
                (item, cfg) =>
                {
                    var synchItem = item.Result1;
                    cfg.TypeTranslator.TranslateBackward(item.Result2, ref synchItem);

                    // Now the translate decides wether a new item has to be created, but the decision is there anyway because of the Create.
                    cfg.Type1EndpointConfiguration.Endpoint.Create(synchItem);
                    return new SynchronizationResult(true);
                })
            };
            Plumber = new ItemMatchPipelinePlumber<LocalTestResource, RemoteTestResource, int>(ChannelConfig, resolvers, itemsPreprocessor.Match);
            ConstructTestSubject();
        }
Exemplo n.º 35
0
        private void DisplayPoints(string user, string channel, ChannelConfiguration channelInfo)
        {
            if (!_config.Channels.Any(c => c.ChannelName.Equals(channel))) return;

            var currencyInfo = GetCurrencyInfo(user, channel);

            string message;
            if (currencyInfo != null)
                message =
                    $"@{user}: You have {currencyInfo.AvailableAmount} unspent {channelInfo.CurrencyName}. Up through the ages you have accumulated {currencyInfo.TotalCurrency} {channelInfo.CurrencyName}.";
            else
                message = $"Sorry @{user}, but I have not registered any {channelInfo.CurrencyName} for you :( Stay here a while and you will get them.";

            _ircClient.SendMessage(message, channel);
        }
Exemplo n.º 36
0
        private void DoAddBonus(ServerMessage message, ChannelConfiguration channelInfo)
        {
            var channelName = message.GetChannelName();

            if (!_config.Channels.Any(c => c.ChannelName.Equals(channelName))) return;

            try
            {
                var target = message.Trailing.Split(' ')[1];
                var amount = int.Parse(message.Trailing.Split(' ')[2]);
                var currencyInfo = GetCurrencyInfo(target, channelName);

                currencyInfo.TotalCurrency += amount;
                _database.Update(currencyInfo);

                _ircClient.SendMessage($"{target} was given a bonus of {amount} and now have {currencyInfo.AvailableAmount} {channelInfo.CurrencyName}.", channelName);
                _logger.Write($"{message.GetSender()} did !bonus to {target} with amount {amount} on {channelName}");
            }
            catch (Exception e)
            {
                if (e is FormatException || e is IndexOutOfRangeException)
                {
                    _ircClient.SendMessage($"Usage: !bonus <user> <amount>", channelName);
                    return;
                }

                throw;
            }
        }
Exemplo n.º 37
0
        private void DoAddBonusAll(ServerMessage message, ChannelConfiguration channelInfo)
        {
            var channelName = message.GetChannelName();

            if (!_config.Channels.Any(c => c.ChannelName.Equals(channelName))) return;

            try
            {
                var amount = int.Parse(message.Trailing.Split(' ')[1]);
                foreach (var user in _ircClient.Channels[channelName].Users)
                {
                    var currencyInfo = GetCurrencyInfo(user.Nick, channelName);
                    currencyInfo.TotalCurrency += amount;
                    _database.Update(currencyInfo);
                }

                _ircClient.SendMessage($"Everyone that is online now was given a bonus of {amount} bonus {channelInfo.CurrencyName}!", channelName);
                _logger.Write($"{message.GetSender()} did !bonusall with amount {amount} on {channelName}");
            }
            catch (Exception e)
            {
                if (e is FormatException || e is IndexOutOfRangeException)
                {
                    _ircClient.SendMessage($"Usage: !bonusall <amount>", channelName);
                    return;
                }

                throw;
            }
        }
Exemplo n.º 38
0
        private void DoGamble(ServerMessage message, ChannelConfiguration channelInfo)
        {
            var nickName = message.GetSender();
            var channelName = message.GetChannelName();

            if (!_config.Channels.Any(c => c.ChannelName.Equals(channelName))) return;

            var currencyInfo = GetCurrencyInfo(nickName, channelName);

            if (currencyInfo == null) return; //Perhaps notify the user?

            try
            {
                var amount = 0;
                if (int.TryParse(message.Trailing.Split(' ')[1], out amount))
                {
                    if (!currencyInfo.CanAfford(amount))
                    {
                        _ircClient.SendMessage($"Sorry @{nickName}, but you don't have that many {channelInfo.CurrencyName}... You have {currencyInfo.AvailableAmount} {channelInfo.CurrencyName} to spend.", channelName);
                        return;
                    }

                    var randomNumber = _random.Next(1, 101); //Note: maxValue in random is NOT included in the range

                    if (randomNumber <= 50)
                    {
                        currencyInfo.UsedCurrency += amount;
                        _ircClient.SendMessage($"@{nickName} rolled {randomNumber} and lost {amount} and now has {currencyInfo.AvailableAmount} {channelInfo.CurrencyName}. Better luck next time!", channelName);
                        _database.Update(currencyInfo);
                    }
                    else if (randomNumber <= 98)
                    {
                        //You won and doubled!
                        currencyInfo.TotalCurrency += amount;
                        _ircClient.SendMessage($"@{nickName} rolled {randomNumber} and DOUBLED the bet! You won {amount} and now has {currencyInfo.AvailableAmount} {channelInfo.CurrencyName}!", channelName);
                        _database.Update(currencyInfo);
                    }
                    else //(randomNumber > 98)
                    {
                        //You won and trippled the points!
                        currencyInfo.TotalCurrency += 2 * amount;
                        _ircClient.SendMessage($"@{nickName} rolled {randomNumber} and TRIPPLED the bet! You won {2 * amount} and now has {currencyInfo.AvailableAmount} {channelInfo.CurrencyName}!", channelName);
                        _database.Update(currencyInfo);
                    }
                }
            }
            catch (Exception e)
            {
                if (e is FormatException || e is IndexOutOfRangeException)
                {
                    _ircClient.SendMessage($"Usage: !gamble <amount>. Roll a number between 1 and 100. Lose: 1-50, Double: 51-98, Tripple: 99-100", message.GetChannelName());
                    return;
                }

                throw;
            }
        }
Exemplo n.º 39
0
        private void DoGive(ServerMessage message, ChannelConfiguration channelInfo)
        {
            var nickName = message.GetSender();
            var channelName = message.GetChannelName();

            if (!_config.Channels.Any(c => c.ChannelName.Equals(channelName))) return;

            try
            {
                var target = message.Trailing.Split(' ')[1];
                var amount = int.Parse(message.Trailing.Split(' ')[2]);
                var currencySenderInfo = GetCurrencyInfo(nickName, channelName);
                var currencyTargetInfo = GetCurrencyInfo(target, channelName);

                if (currencySenderInfo.CanAfford(amount))
                {
                    currencySenderInfo.UsedCurrency += amount;
                    _database.Update(currencySenderInfo);

                    currencyTargetInfo.TotalCurrency += amount;
                    _database.Update(currencyTargetInfo);

                    _ircClient.SendMessage($"@{nickName} gave @{target} {amount} {channelInfo.CurrencyName}! How kind :)", channelName);
                    _logger.Write($"{message.GetSender()} did !give to {target} with amount {amount} on {channelName}");
                }
                else
                {
                    _ircClient.SendMessage($"Sorry @{nickName}, but you cannot afford to give {amount} {channelInfo.CurrencyName}. You only have {channelInfo.CurrencyName} {channelInfo.CurrencyName} in the bank.", channelName);
                }
            }
            catch (Exception e)
            {
                if (e is FormatException || e is IndexOutOfRangeException)
                {
                    _ircClient.SendMessage($"Usage: !give <user> <amount>", channelName);
                    return;
                }

                throw;
            }
        }
        // ------------------------------------------------------------------------------------------------------
        private void _addChannelWrapper(ChannelConfiguration cfg)
        {
            ChannelWrapper wrapper = new ChannelWrapper(cfg.buffer);
            mChannelWrappers.Add(wrapper);
            EEGChannelGraph graph = new EEGChannelGraph();
            mGraphConfigs[wrapper] = cfg;
            mGraphs[wrapper] = graph;

            Controls.Add(graph);
        }
Exemplo n.º 41
0
 public void SetChannelConfiguration(ChannelConfiguration cc)
 {
     ChannelConfigurationInt = (int)cc;
 }