예제 #1
0
 public static DistributedCacheEntryOptions GetCacheEntryOptions(this ExpirationOptions source) =>
 new DistributedCacheEntryOptions
 {
     AbsoluteExpiration = source.AbsoluteExpiration,
     AbsoluteExpirationRelativeToNow = source.AbsoluteExpirationRelativeToNow,
     SlidingExpiration = source.SlidingExpiration
 };
예제 #2
0
        public async Task Build_transfer_coins_transaction()
        {
            //ARRANGE
            string transactionResponse = "transactionResponse";

            var client = PrepareClient <AppSettings>((options) =>
            {
                var aggregator = CreateMocksAndSetupFactories(options);

                options.IntegrationName = $"{nameof(TransactionExecutorClientTests)}+{nameof(Build_transfer_coins_transaction)}";
                aggregator.HealthProvider.Setup(x => x.GetDiseaseAsync()).ReturnsAsync(Disease);
                aggregator.TransferCoinsTransactionsBuilder
                .Setup(x => x.BuildTransferCoinsAsync(It.IsAny <BuildTransferCoinsTransactionRequest>()))
                .ReturnsAsync(new BuildTransactionResponse(Base64String.Encode(transactionResponse)));
            });

            //ACT
            var coinsToSpend = new[]
            {
                new CoinToSpend(new CoinId("tx1", 0),
                                new Asset("assetId"),
                                UMoney.Create(1000, 4),
                                new Address("0x1"),
                                Base64String.Encode("context"),
                                1),
            };
            var coinsToReceive = new[]
            {
                new CoinToReceive(0,
                                  new Asset("assetId"),
                                  UMoney.Create(1000, 4),
                                  new Address("0x2"),
                                  new AddressTag("tag"),
                                  AddressTagType.Text
                                  ),
            };
            var expirationOptions = new ExpirationOptions(DateTime.Now + TimeSpan.FromDays(1));

            var request = new BuildTransferCoinsTransactionRequest(coinsToSpend, coinsToReceive, expirationOptions);
            var result  = await client.BuildTransferCoinsTransactionAsync(request);

            //ASSERT

            Assert.True(result != null);
            Assert.True(result.TransactionContext.DecodeToString() == transactionResponse);
        }
예제 #3
0
        public void Bad_request_transfer_coins_transaction()
        {
            //ARRANGE

            var client = PrepareClient <AppSettings>((options) =>
            {
                var aggregator = CreateMocksAndSetupFactories(options);

                options.IntegrationName = $"{nameof(TransactionExecutorClientTests)}+{nameof(Bad_request_transfer_coins_transaction)}";
                aggregator.HealthProvider.Setup(x => x.GetDiseaseAsync()).ReturnsAsync(Disease);
                aggregator.TransferCoinsTransactionsBuilder
                .Setup(x => x.BuildTransferCoinsAsync(It.IsAny <BuildTransferCoinsTransactionRequest>()))
                .ThrowsAsync(new TransactionBuildingException(TransactionBuildingError.RetryLater, "some error"));
            });

            //ACT && ASSERT
            var coinsToSpend = new[]
            {
                new CoinToSpend(new CoinId("tx1", 0),
                                new Asset("assetId"),
                                UMoney.Create(1000, 4),
                                new Address("0x1"),
                                Base64String.Encode("context"),
                                1),
            };
            var coinsToReceive = new[]
            {
                new CoinToReceive(0,
                                  new Asset("assetId"),
                                  UMoney.Create(1000, 4),
                                  new Address("0x2"),
                                  new AddressTag("tag"),
                                  AddressTagType.Text
                                  ),
            };
            var expirationOptions = new ExpirationOptions(DateTime.Now + TimeSpan.FromDays(1));

            Assert.ThrowsAsync <TransactionBuildingWebApiException>(async() =>
            {
                var request = new BuildTransferCoinsTransactionRequest(coinsToSpend, coinsToReceive, expirationOptions);
                await client.BuildTransferCoinsTransactionAsync(request);
            });
        }
예제 #4
0
        /// <summary>
        /// Get the item setup.
        /// </summary>
        /// <param name="screen"></param>
        public BasicSettingsFlyout(IScreen screen)
        {
            this.InitializeComponent();
            _screen = screen;

            var timeList = ExpirationOptions.GetListExpirationOptions();

            ClearCacheAgenda.ItemsSource    = timeList;
            ClearCacheTalkFiles.ItemsSource = timeList;

            // Set the currently selected times
            var s = Settings.CacheAgendaTime;

            ClearCacheAgenda.SelectedItem = timeList.Where(x => x.Time == s).FirstOrDefault();
            s = Settings.CacheFilesTime;
            ClearCacheTalkFiles.SelectedItem = timeList.Where(x => x.Time == s).FirstOrDefault();

            // And the auto download
            AutoDownload.IsOn = Settings.AutoDownloadNewMeeting;
        }
        public void TestReceiveIgnoreExpirationMessage(
            [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge,
                    AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)]
            AcknowledgementMode ackMode,
            [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)]
            MsgDeliveryMode deliveryMode,
            [Values(ExpirationOptions.DEFAULT, ExpirationOptions.IGNORE, ExpirationOptions.DO_NOT_IGNORE)]
            ExpirationOptions expirationOption)
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                connection.Start();
                using (Session session = connection.CreateSession(ackMode) as Session)
                {
                    string destinationName = DESTINATION_NAME;

                    if (ExpirationOptions.IGNORE == expirationOption)
                    {
                        destinationName += "?consumer.nms.ignoreExpiration=true";
                    }
                    else if (ExpirationOptions.DO_NOT_IGNORE == expirationOption)
                    {
                        destinationName += "?consumer.nms.ignoreExpiration=false";
                    }

                    try
                    {
                        IDestination destination = SessionUtil.GetDestination(session, destinationName);

                        using (IMessageConsumer consumer = session.CreateConsumer(destination))
                            using (IMessageProducer producer = session.CreateProducer(destination))
                            {
                                producer.DeliveryMode = deliveryMode;

                                string msgText = string.Format("ExpiredMessage: {0}", Guid.NewGuid().ToString());

                                TextMessage msg = session.CreateTextMessage(msgText) as TextMessage;

                                // Give it two seconds to live.
                                msg.NMSTimeToLive = TimeSpan.FromMilliseconds(2000);

                                producer.Send(msg);

                                if (AcknowledgementMode.Transactional == ackMode)
                                {
                                    session.Commit();
                                }

                                // Wait for four seconds before processing it.  The broker will have sent it to our local
                                // client dispatch queue, but we won't attempt to process the message until it has had
                                // a chance to expire within our internal queue system.
                                Thread.Sleep(4000);

                                TextMessage rcvMsg = consumer.ReceiveNoWait() as TextMessage;

                                if (ExpirationOptions.IGNORE == expirationOption)
                                {
                                    Assert.IsNotNull(rcvMsg, "Did not receive expired message.");
                                    rcvMsg.Acknowledge();

                                    Assert.AreEqual(msgText, rcvMsg.Text, "Message text does not match.");
                                    Assert.IsTrue(rcvMsg.IsExpired());

                                    if (AcknowledgementMode.Transactional == ackMode)
                                    {
                                        session.Commit();
                                    }
                                }
                                else
                                {
                                    // Should not receive a message.
                                    Assert.IsNull(rcvMsg, "Received an expired message!");
                                }

                                consumer.Close();
                                producer.Close();
                            }
                    }
                    finally
                    {
                        try
                        {
                            // Ensure that Session resources on the Broker release transacted Consumers.
                            session.Close();
                            // Give the Broker some time to remove the subscriptions.
                            Thread.Sleep(2000);
                            SessionUtil.DeleteDestination(session, destinationName);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
예제 #6
0
 public FooRequestCacheable(TimeSpan expirationTimeSpan)
 {
     Key     = "FooRequestCacheable";
     Options = new ExpirationOptions(expirationTimeSpan);
 }
예제 #7
0
        /// <summary>
        /// Basic settings are configured on the view that is attached to this VM.
        /// </summary>
        /// <param name="screen"></param>
        public BasicSettingsViewModel(IScreen screen)
        {
            HostScreen = screen;

            // Look for a currently loaded cert and update the status...
            // We can't start this b.c. the ToProperty is lazy - and it won't
            // fire until Status is data-bound!
            LookupCertStatus = ReactiveCommand.CreateAsyncTask(a => SecurityUtils.FindCert(SecurityUtils.CERNCertName));
            LookupCertStatus
            .Select(c => c == null ? "No Cert Loaded" : string.Format("Loaded (expires {0})", c.ValidTo.ToLocalTime().ToString("yyyy-MM-dd HH:mm")))
            .ToProperty(this, x => x.Status, out _status, "", RxApp.MainThreadScheduler);

            LookupCertStatus
            .ExecuteAsync()
            .Subscribe();

            // Error and status messages...
            var errors = new Subject <string>();

            errors
            .ToProperty(this, x => x.Error, out _error, "", RxApp.MainThreadScheduler);

            // Given a file and a password, see if we can install it as a cert
            // in our internal repository.
            LoadFiles = ReactiveCommand.Create();
            LoadFiles
            .Subscribe(x => errors.OnNext(""));

            var files = LoadFiles
                        .Cast <Tuple <IReadOnlyList <StorageFile>, string> >();

            files
            .Where(finfo => finfo.Item1 == null || finfo.Item1.Count != 1)
            .Select(f => "Invalid certificate file")
            .Subscribe(errors);

            files
            .Where(finfo => finfo.Item1 != null && finfo.Item1.Count == 1)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Select(mf =>
            {
                // We use this double subscribe because the readBufferAsync and ImportPfxDataAsync often return exceptions.
                // If we let the exception bubble all the way up, it terminates the sequence. Which means if the user entered
                // the wrong password they wouldn't get a chance to try again!
                return(Observable.Return(mf)
                       .SelectMany(async f =>
                {
                    // Work around for the TplEventListener not working correctly.
                    // https://social.msdn.microsoft.com/Forums/windowsapps/en-US/3e505e04-7f30-4313-aa47-275eaef333dd/systemargumentexception-use-of-undefined-keyword-value-1-for-event-taskscheduled-in-async?forum=wpdevelop
                    await Task.Delay(1);

                    var fs = f.Item1[0] as StorageFile;
                    var buffer = await FileIO.ReadBufferAsync(fs);
                    var cert = CryptographicBuffer.EncodeToBase64String(buffer);

                    await CertificateEnrollmentManager.ImportPfxDataAsync(cert, f.Item2, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.DeleteExpired, SecurityUtils.CERNCertName);
                    return Unit.Default;
                }));
            })
            .Subscribe(c => c.Subscribe(
                           g => LookupCertStatus.ExecuteAsync().Subscribe(),
                           e => errors.OnNext(e.Message.TakeFirstLine())
                           ));

            // Set/Get the file expiration policy.
            CacheDecayOptions = ExpirationOptions.GetListExpirationOptions();

            // Get the list of indico api keys we are watching
            // and hook up the MV for doing the api key manipulation
            ApiKeysForIndico = new ReactiveList <IndicoApiKey>();
            ApiKeysForIndico.AddRange(IndicoApiKeyAccess.LoadAllKeys());
            IndicoApiKeyAccess.IndicoApiKeysUpdated
            .Subscribe(_ =>
            {
                using (ApiKeysForIndico.SuppressChangeNotifications())
                {
                    ApiKeysForIndico.Clear();
                    ApiKeysForIndico.AddRange(IndicoApiKeyAccess.LoadAllKeys());
                }
            });

            ShowIndicoApiKey = ReactiveCommand.Create();
            ShowIndicoApiKey
            .Cast <IndicoApiKey>()
            .Select(x => new AddOrUpdateIndicoApiKeyViewModel(x))
            .ToProperty(this, x => x.IndicoApiKey, out _indicoApiKeyVM, new AddOrUpdateIndicoApiKeyViewModel(null));
        }
예제 #8
0
 public GetFooByIdQuery(int id)
 {
     Id      = id;
     Key     = $"Foo_{id}";
     Options = new ExpirationOptions(TimeSpan.FromSeconds(60));
 }