예제 #1
0
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId  = Any.Word();
            target    = new CommandTarget(targetId);
            store     = new InMemoryStore <CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            CommandSchedulerDbContext.NameOrConnectionString =
                @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";

            configuration = new Configuration()
                            .UseInMemoryCommandScheduling()
                            .UseDependency <IStore <CommandTarget> >(_ => store)
                            .UseDependency <GetClockName>(c => _ => clockName)
                            .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler <CommandTarget>();

            Command <CommandTarget> .AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId = Any.Word();
            target = new CommandTarget(targetId);
            store = new InMemoryStore<CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            configuration = new Configuration()
                .UseInMemoryCommandScheduling()
                .UseDependency<IStore<CommandTarget>>(_ => store)
                .UseDependency<GetClockName>(c => _ => clockName)
                .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler<CommandTarget>();

            Command<CommandTarget>.AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
예제 #3
0
 public void TestSetUp()
 {
     storageSystem = new InMemoryStorageSystem();
     testStore     = storageSystem.CreateStore("TestStore");
     objStore      = new ObjectStore(1, testStore);
     objStore.Create();
 }
예제 #4
0
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId  = Any.Word();
            target    = new CommandTarget(targetId);
            store     = new InMemoryStore <CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            configuration = new Configuration()
                            .UseInMemoryCommandScheduling()
                            .UseDependency <IStore <CommandTarget> >(_ => store)
                            .UseDependency <GetClockName>(c => _ => clockName)
                            .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler <CommandTarget>();

            Command <CommandTarget> .AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
    private IMultiTenantStore <TenantInfo> CreateCaseSensitiveTestStore()
    {
        var services = new ServiceCollection();

        services.AddOptions().Configure <InMemoryStoreOptions <TenantInfo> >(o => o.IsCaseSensitive = true);
        var sp = services.BuildServiceProvider();

        var store = new InMemoryStore <TenantInfo>(sp.GetRequiredService <IOptions <InMemoryStoreOptions <TenantInfo> > >());

        var ti1 = new TenantInfo
        {
            Id         = "initech",
            Identifier = "initech",
            Name       = "initech"
        };
        var ti2 = new TenantInfo
        {
            Id         = "lol",
            Identifier = "lol",
            Name       = "lol"
        };

        store.TryAddAsync(ti1).Wait();
        store.TryAddAsync(ti2).Wait();

        return(store);
    }
예제 #6
0
        public void InMemoryStoreTest()
        {
            using (var store = new InMemoryStore())
            {
                store.Register <Author>();
                IUnitOfWork uow         = store as IUnitOfWork;
                const int   authorCount = 100;
                Parallel.For(0, authorCount, i =>
                {
                    uow.Add(new Author(i, $"Author {i}"));
                });
                ILinqProvider linq = store as ILinqProvider;

                Assert.AreEqual(authorCount, linq.Query <Author>().Count());
                int id = 3;
                Assert.AreEqual(1, linq.Query <Author>().Where(a => a.Id == id).Count());
                Assert.AreEqual(id, linq.Query <Author>().Where(a => a.Id == id).FirstOrDefault().Id);
                Assert.AreEqual($"Author {id}", linq.Query <Author>().Where(a => a.Id == id).FirstOrDefault().Name);

                var author = new Author(id, $"Author#{id}");
                uow.Update(author);
                uow.Commit();

                Assert.AreEqual(1, linq.Query <Author>().Where(a => a.Id == id).Count());
                Assert.AreEqual(author.Id, linq.Query <Author>().Where(a => a.Id == id).FirstOrDefault().Id);
                Assert.AreEqual(author.Name, linq.Query <Author>().Where(a => a.Id == id).FirstOrDefault().Name);

                Parallel.For(0, 100, i =>
                {
                    var updAuthor = new Author(id, $"Author#{i}");
                    uow.Update(updAuthor);
                });
            }
        }
        public MainWindowViewModel(IDialogService dialogService, IDispatcher dispatcher)
        {
            if (dialogService == null)
            {
                throw new ArgumentNullException(nameof(dialogService));
            }
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            _dialogService = dialogService;
            _dispatcher    = dispatcher;

            var analyzer = new SimpleAnalyzer();
            var store    = new InMemoryStore();

            _indexer = new Indexer(new SearchIndex(analyzer, store));
            _indexer.IndexingProgress += OnIndexingProgress;

            _addDirectoryCommand = new DelegateCommand(AddDirectory);
            _addFilesCommand     = new DelegateCommand(AddFiles);
            _searchCommand       = new DelegateCommand <string>(Search);

            _searchResultsSource.Source = _searchResults;
            _searchResultsSource.SortDescriptions.Add(new SortDescription(string.Empty, ListSortDirection.Ascending));
        }
예제 #8
0
파일: Fixture.cs 프로젝트: kdma/PagoPaChat
        public void AClientCanSendAMessage()
        {
            var msgWait = new ManualResetEvent(false);

            var inMemoryStore = new InMemoryStore(new SingleClientTestPeer(msgWait));
            var clientPool    = new ClientPool();

            var server = new Server(inMemoryStore, clientPool);

            Task.Run(() => server.Start());

            var aClient = new TcpClient();

            aClient.Connect(IPAddress.Parse("127.0.0.1"), 10000);

            Assert.That(aClient.GetStream().CanWrite);

            var message   = $"Hello, World!{Environment.NewLine}";
            var msgBuffer = Encoding.ASCII.GetBytes(message);

            aClient.GetStream().Write(msgBuffer, 0, msgBuffer.Length);

            msgWait.WaitOne();

            StringAssert.AreEqualIgnoringCase(message, inMemoryStore.Read().First().Value);
        }
예제 #9
0
        public void TestScheduleTriggerWithNoJobDataMapSavesEmptyDataOnTrigger()
        {
            // Arrange
            Scheduler.Shutdown();
            Scheduler.Initialize((config =>
            {
                config.EnableWebApiSelfHost = false;
                config.EnableAuditHistory = false;
            }));
            IPersistanceStore persistanceStore = new InMemoryStore();

            _schedulerCore = new SchedulerCore(Scheduler.Instance(), persistanceStore);

            const string jobName     = "Job1";
            const string jobGroup    = "Group1";
            const string triggerName = "Trigger1";

            _schedulerCore.CreateJob(jobName, jobGroup, typeof(NoOpJob), new Dictionary <string, object>(), string.Empty);

            var simpleTrigger = new SimpleTrigger
            {
                RepeatCount    = 1,
                RepeatInterval = new TimeSpan(0, 1, 0, 0),
                JobName        = jobName,
                JobGroup       = jobGroup,
                Name           = triggerName
            };

            // Act
            var result = _schedulerCore.ScheduleTrigger(simpleTrigger);

            // Assert
            Assert.Equal(triggerName, Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).Key.Name);
            Assert.Equal(0, Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).JobDataMap.Count);
        }
예제 #10
0
        private void RegisterMartenSession()
        {
            var store = new InMemoryStore();

            ForSingletonOf <IDocumentStore>().Use("Create DocumentStore", context =>
            {
                var connectionString = context.GetInstance <ConnectionStringParser>().GetString();

                return(!string.IsNullOrWhiteSpace(connectionString)
                    ? DocumentStore.For(connectionString)
                    : (IDocumentStore)store);
            });

            For <IQuerySession>()
            .Use("Create QuerySession", context =>
            {
                var connectionString = context.GetInstance <ConnectionStringParser>().GetString();

                return(!string.IsNullOrWhiteSpace(connectionString)
                        ? context.GetInstance <IDocumentStore>().QuerySession()
                        : store);
            })
            .ContainerScoped();

            For <IDocumentSession>()
            .Use("Create DocumentSession", context =>
            {
                var connectionString = context.GetInstance <ConnectionStringParser>().GetString();

                return(!string.IsNullOrWhiteSpace(connectionString)
                        ? context.GetInstance <IDocumentStore>().DirtyTrackedSession()
                        : store);
            })
            .ContainerScoped();
        }
예제 #11
0
        public void Expect(params IEvent <T>[] g)
        {
            _thenWasCalled = true;
            _then.AddRange(g);

            IEnumerable <IEvent <T> > actual;
            var givenEvents = _givenEvents.Cast <IEvent <IIdentity> >().ToArray();

            if (_dontExecuteOnExpect)
            {
                return;
            }
            var store = new InMemoryStore(givenEvents);

            try
            {
                ExecuteCommand(store, _when);
                actual = store.Store.Skip(_givenEvents.Count).Cast <IEvent <T> >().ToArray();
            }
            catch (DomainError e)
            {
                actual = new IEvent <T>[] { new ExceptionThrown(e.Name) };
            }

            var results = CompareAssert(_then.ToArray(), actual.ToArray()).ToArray();

            PrintSpecification();
            PrintResults(results);

            if (results.Any(r => r.Failure != null))
            {
                Assert.Fail("Specification failed");
            }
        }
예제 #12
0
        static String test(String query)
        {
            MyDiagnosticHandler diagnosticHandler = new MyDiagnosticHandler();

            InMemoryStore store = InMemoryStore.getInstance();
            Zorba         zorba = Zorba.getInstance(store);

            XQuery        xquery   = zorba.compileQuery(query, diagnosticHandler);
            StringBuilder sbuilder = new StringBuilder();
            Iterator      iter     = xquery.iterator();

            iter.open();
            Item item = new Item();

            while (iter.next(item))
            {
                sbuilder.Append(item.getStringValue());
            }
            iter.close();
            iter.Dispose();
            xquery.destroy();
            xquery.Dispose();

            zorba.shutdown();
            InMemoryStore.shutdown(store);

            return(sbuilder.ToString());
        }
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId = Any.Word();
            target = new CommandTarget(targetId);
            store = new InMemoryStore<CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            CommandSchedulerDbContext.NameOrConnectionString =
                @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";

            configuration = new Configuration()
                .UseInMemoryCommandScheduling()
                .UseDependency<IStore<CommandTarget>>(_ => store)
                .UseDependency<GetClockName>(c => _ => clockName)
                .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler<CommandTarget>();

            Command<CommandTarget>.AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
예제 #14
0
        public void ShouldNotSearchDeleted()
        {
            var file1 = Path.Combine(_directory, "1.txt");
            var file2 = Path.Combine(_directory, "2.txt");
            var file3 = Path.Combine(_directory, "3.txt");
            var file4 = Path.Combine(_directory, "4.pdf");

            File.WriteAllText(file1, "hello world");
            File.WriteAllText(file2, "hello pretty world");
            File.WriteAllText(file3, "just hello");
            File.WriteAllText(file4, "hello ugly world");
            var analyzer = new SimpleAnalyzer();
            var store    = new InMemoryStore();

            BlockingCollection <IndexingEventArgs> events = new BlockingCollection <IndexingEventArgs>();

            var indexer = new Indexer(new SearchIndex(analyzer, store));

            indexer.IndexingProgress += (o, e) => events.Add(e);
            indexer.AddDirectory(_directory, "*.txt");

            WaitForIndexed(indexer, events);

            File.Delete(file1);

            WaitForIndexed(indexer, events);

            var result = indexer.Search("hello world");

            CollectionAssert.AreEquivalent(new[] { file2 }, result);

            indexer.Dispose();
        }
예제 #15
0
        public void ShouldRemoveFileWhenRenamed()
        {
            var file1 = Path.Combine(_directory, "1.txt");

            File.WriteAllText(file1, "hello world");
            var analyzer = new SimpleAnalyzer();
            var store    = new InMemoryStore();

            BlockingCollection <IndexingEventArgs> events = new BlockingCollection <IndexingEventArgs>();

            var indexer = new Indexer(new SearchIndex(analyzer, store));

            indexer.IndexingProgress += (o, e) => events.Add(e);
            indexer.AddFile(file1);

            WaitForIndexed(indexer, events);

            var result = indexer.Search("hello world");

            CollectionAssert.AreEquivalent(new[] { file1 }, result);

            File.Move(file1, Path.Combine(_directory, "2.txt"));

            WaitForIndexed(indexer, events);

            result = indexer.Search("hello");
            CollectionAssert.IsEmpty(result);

            indexer.Dispose();
        }
예제 #16
0
        private void RegisterMartenSession()
        {
            var store = new InMemoryStore();

            ForSingletonOf<IDocumentStore>().Use("Create DocumentStore", context =>
            {
                var connectionString = context.GetInstance<ConnectionStringParser>().GetString();

                return !string.IsNullOrWhiteSpace(connectionString)
                    ? DocumentStore.For(connectionString)
                    : (IDocumentStore) store;
            });

            For<IQuerySession>()
                .Use("Create QuerySession", context =>
                {
                    var connectionString = context.GetInstance<ConnectionStringParser>().GetString();

                    return !string.IsNullOrWhiteSpace(connectionString) 
                        ? context.GetInstance<IDocumentStore>().QuerySession() 
                        : store;
                })
                .ContainerScoped();

            For<IDocumentSession>()
                .Use("Create DocumentSession", context =>
                {
                    var connectionString = context.GetInstance<ConnectionStringParser>().GetString();

                    return !string.IsNullOrWhiteSpace(connectionString)
                        ? context.GetInstance<IDocumentStore>().DirtyTrackedSession()
                        : store;
                })
                .ContainerScoped();
        }
예제 #17
0
        static string test(string query, string xml, string doc)
        {
            InMemoryStore store = InMemoryStore.getInstance();
            Zorba         zorba = Zorba.getInstance(store);

            XmlDataManager dataManager = zorba.getXmlDataManager();
            Iterator       docIter     = dataManager.parseXML(xml);

            docIter.open();
            Item idoc = new Item();

            docIter.next(idoc);
            docIter.close();
            docIter.Dispose();

            DocumentManager docManager = dataManager.getDocumentManager();

            docManager.put(doc, idoc);

            XQuery xquery = zorba.compileQuery(query);
            string result = xquery.execute();

            xquery.destroy();
            xquery.Dispose();

            zorba.shutdown();
            InMemoryStore.shutdown(store);

            return(result);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.Name    = $"{Configuration["applicationName"]}.AspNetCore.Consent";
            });
            services.AddSingleton <ConfiguredDiscoverCacheContainerFactory>();

            var inMemoryStore = new InMemoryStore <ApplicationUser, ApplicationRole>();

            services.AddSingleton <IUserStore <ApplicationUser> >(provider =>
            {
                return(inMemoryStore);
            });
            services.AddSingleton <IUserRoleStore <ApplicationUser> >(provider =>
            {
                return(inMemoryStore);
            });
            services.AddSingleton <IRoleStore <ApplicationRole> >(provider =>
            {
                return(inMemoryStore);
            });
            var identityBuilder = services.AddIdentity <ApplicationUser, ApplicationRole>()
                                  .AddDefaultTokenProviders();

            //        identityBuilder.Services.AddTransientDecorator<IAuthenticationService, IdentityServerAuthenticationService>();
            //       identityBuilder.Services.AddTransientDecorator<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsFactory<ApplicationUser>>();

            services.ConfigureApplicationCookie(options => {
                options.Cookie.Name = $"{Configuration["applicationName"]}.AspNetCore.Identity.Application";
            });
            services.AddAuthentication <ApplicationUser>(Configuration);


            // Hosting doesn't add IHttpContextAccessor by default
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddSessionStateTempDataProvider();

            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.Cookie.Name = $"{Configuration["applicationName"]}.Session";
                // Set a short timeout for easy testing.
                options.IdleTimeout     = TimeSpan.FromSeconds(3600);
                options.Cookie.HttpOnly = true;
            });
            services.Configure <List <OAuth2SchemeRecord> >(Configuration.GetSection("oauth2"));
            services.AddSingleton <TokenClientAccessor>();
        }
예제 #19
0
        public void Keys(
            IDictionary <string, string> originData,
            ICollection <string> expectedKeys)
        {
            var store = new InMemoryStore(originData, _textProcessorMock);
            var keys  = store.Keys();

            keys.Should().BeEquivalentTo(expectedKeys);
        }
예제 #20
0
        ///<summary>
        /// Create an InMemory Store that uses Microsoft.Extensions.DependencyInjection for a MemoryStore Instance
        ///</summary>
        public static IServiceCollection InMemoryStore(this IServiceCollection services, string initialAdminName, string pw, string appName = "testAdmin")
        {
            string hash  = PasswordHasher.GenerateHash(pw);
            var    store = new InMemoryStore(initialAdminName, hash, appName);

            services.AddSingleton <IStorageModel>(store);
            services.AddSingleton <IAuthStorageModel>(store);
            return(services);
        }
예제 #21
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Running: Get zorba instance and shutdown");
            InMemoryStore store = InMemoryStore.getInstance();
            Zorba         zorba = Zorba.getInstance(store);

            zorba.shutdown();
            InMemoryStore.shutdown(store);
            System.Console.WriteLine("Success");
        }
예제 #22
0
        public void Setup()
        {
            configMock.Setup(config => config["RemoveOldItemsInLastSec"]).Returns("2");
            configMock.Setup(config => config["MinimumItemsToKeep"]).Returns("100");
            configMock.Setup(config => config["RunCleanUpEveryInSec"]).Returns("5");

            LoggerFactory logger = new LoggerFactory();

            store = new InMemoryStore(configMock.Object, logger);
        }
예제 #23
0
        public static IUnitOfWork CreateMemoryUoW(params Type[] types)
        {
            var uow = new InMemoryStore();

            foreach (var t in types)
            {
                uow.Register(t);
            }
            return(uow);
        }
예제 #24
0
        public async Task DecompressesFromExpectedBytes()
        {
            // Arrange
            var memoryStore = new InMemoryStore();
            await memoryStore.SetAsync(Key, new MemoryStream(OptimalCompressInputText), CancellationToken.None);

            var gzipStore = new GZipStore(memoryStore, CompressionLevel.Optimal);

            // Act, Assert
            await VerifyStringAsync(gzipStore, Key, InputText);
        }
예제 #25
0
        public async Task SupportsRoundTrip()
        {
            // Arrange
            var memoryStore = new InMemoryStore();
            var gzipStore   = new GZipStore(memoryStore, CompressionLevel.Optimal);

            // Act, Assert
            await gzipStore.SetAsync(Key, GetStream(InputText), CancellationToken.None);

            await VerifyStringAsync(gzipStore, Key, InputText);
        }
        public override void ConfigureServices(IServiceCollection services)
        {
            base.ConfigureServices(services);
            services.Remove(services.FirstOrDefault(x => x.ServiceType == typeof(IParkingRateRepository)));

            var store = new InMemoryStore();

            store.DefaultFlatRates.Add(new DefaultFlatRate(23));
            services.AddScoped <IInMemoryStore>(_ => store);
            services.AddScoped <IParkingRateRepository, InMemoryRepository>();
        }
        public static IdentityBuilder AddInMemoryIdentity <TUser, TRole>(this IServiceCollection services)
            where TUser : MemoryUser
            where TRole : MemoryRole
        {
            var inMemoryStore = new InMemoryStore <TUser, TRole>();

            services.AddSingleton <IUserStore <TUser> >(provider => inMemoryStore);
            services.AddSingleton <IUserRoleStore <TUser> >(provider => inMemoryStore);
            services.AddSingleton <IRoleStore <TRole> >(provider => inMemoryStore);
            return(services.AddIdentity <TUser, TRole>());
        }
예제 #28
0
        public async Task CompressesToExpectedBytes()
        {
            // Arrange
            var memoryStore = new InMemoryStore();
            var gzipStore   = new GZipStore(memoryStore, CompressionLevel.Optimal);

            // Act
            await gzipStore.SetAsync(Key, GetStream(InputText), CancellationToken.None);

            // Assert
            await VerifyBytesAsync(memoryStore, Key, OptimalCompressInputText);
        }
예제 #29
0
파일: Program.cs 프로젝트: Stephanvs/Even
        static void Main(string[] args)
        {
            var actorSystem = ActorSystem.Create("Sample");

            Task.Run(async() =>
            {
                // this is used to retrieve the events later
                var memoryStore = new InMemoryStore();

                // initialize the event store
                var gateway = await actorSystem
                              .SetupEven()
                              .UseStore(memoryStore)
                              .AddProjection <ActiveProducts>()
                              .Start("even");

                // send some commands
                await Task.WhenAll(
                    gateway.SendAggregateCommand <Product>(1, new CreateProduct {
                    Name = "Product 1"
                }),
                    gateway.SendAggregateCommand <Product>(2, new CreateProduct {
                    Name = "Product 2"
                }),
                    gateway.SendAggregateCommand <Product>(3, new CreateProduct {
                    Name = "Product 3"
                }),
                    gateway.SendAggregateCommand <Product>(2, new RenameProduct {
                    NewName = "Product 2 - Renamed"
                }),
                    gateway.SendAggregateCommand <Product>(1, new DeleteProduct())
                    );

                // add some delay to make sure the data is flushed to the store
                await Task.Delay(100);

                // print the contents of the event store
                Console.WriteLine();
                Console.WriteLine("Event Store Data");
                Console.WriteLine("================");
                Console.WriteLine();
                Console.WriteLine($"{"Seq",-6} {"Stream ID",-50} Event Name");

                foreach (var e in memoryStore.GetEvents())
                {
                    Console.WriteLine($"{e.GlobalSequence,-6} {e.Stream,-50} {e.EventType}");
                }
            }).Wait();

            Console.WriteLine();
            Console.WriteLine("End");
            Console.ReadLine();
        }
예제 #30
0
        public async Task AdheresToProvidedCompressionLevel(CompressionLevel compression)
        {
            // Arrange
            var expected    = Compress(InputText, compression);
            var memoryStore = new InMemoryStore();
            var gzipStore   = new GZipStore(memoryStore, compression);

            // Act
            await gzipStore.SetAsync(Key, GetStream(InputText), CancellationToken.None);

            // Assert
            await VerifyBytesAsync(memoryStore, Key, expected);
        }
예제 #31
0
        public async Task Should_Throw_Exception_Given_No_DefaultFlatRate()
        {
            var store = new InMemoryStore();

            store.DefaultFlatRates.Clear();
            var repository = new InMemoryRepository(store);
            var service    = new ParkingFeeCalculator(repository);
            var timeEntry  = DateTime.Parse("2020-07-07").AddHours(10);
            var timeExit   = timeEntry.AddHours(4);

            Func <Task> act = async() => await service.GetFeeAmount(timeEntry, timeExit);

            await act.Should().ThrowAsync <ProcessException>().WithMessage("Internal data error.");
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.Name    = $"{Configuration["applicationName"]}.AspNetCore.Consent";
            });
            services.AddSingleton <OIDCDiscoverCacheContainer>();

            var inMemoryStore = new InMemoryStore <ApplicationUser, ApplicationRole>();

            services.AddSingleton <IUserStore <ApplicationUser> >(provider =>
            {
                return(inMemoryStore);
            });
            services.AddSingleton <IUserRoleStore <ApplicationUser> >(provider =>
            {
                return(inMemoryStore);
            });
            services.AddSingleton <IRoleStore <ApplicationRole> >(provider =>
            {
                return(inMemoryStore);
            });
            services.AddIdentity <ApplicationUser, ApplicationRole>()
            .AddDefaultTokenProviders();
            services.ConfigureApplicationCookie(options => {
                options.Cookie.Name = $"{Configuration["applicationName"]}.AspNetCore.Identity.Application";
            });
            services.AddAuthentication <ApplicationUser>(Configuration);
            services
            .AddScoped
            <Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory <ApplicationUser>,
             AppClaimsPrincipalFactory <ApplicationUser, ApplicationRole> >();

            // Hosting doesn't add IHttpContextAccessor by default
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            });

            // Register no-op EmailSender used by account confirmation and password reset during development
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            services.AddSingleton <IEmailSender, EmailSender>();
        }
예제 #33
0
        static String test(String query)
        {
            InMemoryStore store = InMemoryStore.getInstance();
            Zorba         zorba = Zorba.getInstance(store);

            XQuery xquery = zorba.compileQuery(query);
            String result = xquery.printPlanAsDOT();

            xquery.destroy();
            xquery.Dispose();

            zorba.shutdown();
            InMemoryStore.shutdown(store);

            return(result);
        }
예제 #34
0
        /// <summary>
        /// serializes an object's state to a store
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static InMemoryStore ConvertToStore(object obj, Func<FieldInfo, bool> filter)
        {
            Condition.Requires(obj).IsNotNull();

            InMemoryStore store = new InMemoryStore();

            Type objType = obj.GetType();

            //register the object type
            var objectTypeEntry = ContextualAsId<string, Type>.New(TYPEKEY, objType);
            store.SaveItem(objectTypeEntry);

            var fields = ReflectionUtil.GetFieldInfosIncludingBaseClasses(objType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            //for each field, build data to save to the store
            foreach (FieldInfo field in fields)
            {
                if (filter != null && filter(field))
                    continue;

                //key the field 
                var id = field.DeclaringType.Name + "_" + field.Name;

                //get the field value
                var val = field.GetValue(obj);
                
                //build the entries (isNull, and actual value)
                var isNullEntry = ContextualAsId<string,bool>.New(id, val == null);
                store.SaveItem(isNullEntry);

                if(val !=null)
                {
                    var valueEntry = ContextualAsId<string,object>.New(id, val); //we specify the context type as object to simplify lookup
                    store.SaveItem(valueEntry);
                }
            }
            return store;
        }