Beispiel #1
6
        public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();
            var settings = new Mock<IApplicationSettings>();
            var mockPipeline = new Mock<IHubPipelineInvoker>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState);

            var prinicipal = new Mock<IPrincipal>();

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);
            request.Setup(m => m.User).Returns(prinicipal.Object);

            // setup context
            chat.Context = new HubCallerContext(request.Object, connectionId);

            return chat;
        }
Beispiel #2
1
        public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Agent = new ClientAgent(mockedConnectionObject, "Chat");

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();
            chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState);

            // setup context
            chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId);

            return chat;
        }
Beispiel #3
0
            public void ThrowsIfNameIsInValid()
            {
                var repository = new InMemoryRepository();
                var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object);

                Assert.Throws<InvalidOperationException>(() => service.AddUser("some in valid name", clientId: null, userAgent: null, password: null));
            }
        public void SharpRepository_Supports_Basic_Crud_Operations()
        {
            // Declare your generic InMemory Repository.
            // Check out HowToAbstractAwayTheGenericRepository.cs for cleaner ways to new up a repo.
            var repo = new InMemoryRepository<Order, int>();

            // Create
            var create = new Order { Name = "Big sale" };
            repo.Add(create);

            const int expectedOrderId = 1;
            create.OrderId.ShouldEqual(expectedOrderId);

            // Read
            var read = repo.Get(expectedOrderId);
            read.Name.ShouldEqual(create.Name);

            // Update
            read.Name = "Really big sale";
            repo.Update(read);

            var update = repo.Get(expectedOrderId);
            update.OrderId.ShouldEqual(expectedOrderId);
            update.Name.ShouldEqual(read.Name);

            // Delete
            repo.Delete(update);
            var delete = repo.Get(expectedOrderId);
            delete.ShouldBeNull();
        }
            public void ThrowsIfPasswordIsTooShort()
            {
                var repository = new InMemoryRepository();
                var service = new MembershipService(repository, new Mock<ICryptoService>().Object);

                Assert.Throws<InvalidOperationException>(() => service.AddUser("SomeUser", "email", password: "******"));
            }
            public void ThrowsIfNameIsInValid()
            {
                var repository = new InMemoryRepository();
                var service = new MembershipService(repository, new Mock<ICryptoService>().Object);

                Assert.Throws<InvalidOperationException>(() => service.AddUser("some in valid name", "email", password: null));
            }
        public void Should_return_matches_from_a_repository()
        {
            var users = new List<InstalledPlugin>
                               {
                                    new InstalledPlugin { Id = Guid.NewGuid(), Name = "Blog", Version = "1.0.0"},
                                    new InstalledPlugin { Id = Guid.NewGuid(), Name = "News", Version = "1.0.0"},
                                    new InstalledPlugin { Id = Guid.NewGuid(), Name = "Events", Version = "1.0.0"}
                               };

            IRepository<InstalledPlugin> repository = new InMemoryRepository<InstalledPlugin>(users);
            var matches = repository.Find(new OrderedPlugins());

            Assert.AreEqual(3, matches.Count);

            var count = 0;
            foreach (var item in matches)
            {
                if (count == 0)
                    Assert.AreEqual("Blog", item.Name);
                if (count == 1)
                    Assert.AreEqual("Events", item.Name);
                if (count == 2)
                    Assert.AreEqual("News", item.Name);

                count++;
            }
        }
        public void CanCreateInstanceOfRepository()
        {
            IRepository<SomeEntity> repo = new InMemoryRepository<SomeEntity>();

            Assert.IsNotNull(repo);
            Assert.IsInstanceOf<InMemoryRepository<SomeEntity>>(repo);
        }
Beispiel #9
0
            public void ThrowsIfPasswordIsTooShort()
            {
                var repository = new InMemoryRepository();
                var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object);

                Assert.Throws<InvalidOperationException>(() => service.AddUser("SomeUser", clientId: null, userAgent: null, password: "******"));
            }
        public void Init()
        {
            // this.userRepo = TestObjectFactory.GetUsersRepository();
            this.sectionsRepo = TestObjectFactory.GetSectionsRepository();

            this.sectionsService = new SectionService(this.sectionsRepo);
        }
        public void Init()
        {
            // this.userRepo = TestObjectFactory.GetUsersRepository();
            this.categoriesRepo = TestObjectFactory.GetCategoriesRepository();

            this.categoriesService = new CategoriesService(this.categoriesRepo);
        }
 public void CachingEnabled_Should_Be_True_When_CachingStrategy_Is_Changed_From_NoCachingStrategy()
 {
     var repository = new InMemoryRepository<Contact, Int32>(new NoCachingStrategy<Contact, int>());
     repository.CachingEnabled.ShouldBeFalse();
     repository.CachingStrategy = new TimeoutCachingStrategy<Contact, int>(60);
     repository.CachingEnabled.ShouldBeTrue();
 }
        public void Should_return_matches_from_a_repository()
        {
            var users = new List<UserGroup>
                               {
                                    new UserGroup {Id = Guid.NewGuid(), Name = "First Group"},
                                    new UserGroup {Id = Guid.NewGuid(), Name = "Second Group"},
                                    new UserGroup {Id = Guid.NewGuid(), Name = "Third Group"},
                             		new UserGroup {Id = Guid.NewGuid(), Name = "News Editor Group"},
                             		new UserGroup {Id = Guid.NewGuid(), Name = "Publishing Group"},
                             		new UserGroup {Id = Guid.NewGuid(), Name = "Blogging Group"},
                             		new UserGroup {Id = Guid.NewGuid(), Name = "Product Editing Group"}
                               };

            IRepository<UserGroup> repository = new InMemoryRepository<UserGroup>(users);
            var matches = repository.Find(new PagedUserGroups(3, 3));

            Assert.AreEqual(3, matches.Count);

            var count = 0;
            foreach (var item in matches)
            {
                if (count == 0)
                    Assert.AreEqual("News Editor Group", item.Name);
                if (count == 1)
                    Assert.AreEqual("Publishing Group", item.Name);
                if (count == 2)
                    Assert.AreEqual("Blogging Group", item.Name);

                count++;
            }
        }
Beispiel #14
0
        public MainWindow()
        {
            InitializeComponent();

            // Use this as construction root for simplicity.
            // In real world app there should be good framework for this and this should be done
            // outside of main window for reason that then mainwindow is interchangeable too if required.
            var dataSource = new InMemoryRepository();

            // Dummy data for testing...
            dataSource.Add(new CarImage {Color="Black", RegisterPlate = "ABC-123", Speed = 140});

            var messenger = new MessageAggregator();
            var reportViewModel = new ReportViewModel(dataSource, messenger);
            var colorFilter = new ColorFilterViewModel();
            var filterViewModel = new FiltersViewModel(new List<IFilter> {colorFilter}, messenger);

            // Just for testing, apply dummy filter so that data is shown.
            messenger.Publish(new Messages.FiltersAppliedMessage());

            DataContext = new
            {
                Report = reportViewModel,
                Filters = filterViewModel
            };
        }
Beispiel #15
0
            public void MakesOwnerAllowedIfRoomLocked()
            {
                var repository = new InMemoryRepository();
                var user = new ChatUser
                {
                    Name = "foo"
                };
                var user2 = new ChatUser
                {
                    Name = "foo2"
                };
                repository.Add(user);
                repository.Add(user2);
                var room = new ChatRoom
                {
                    Name = "Room",
                    Creator = user,
                    Private = true
                };
                room.Owners.Add(user);
                user.OwnedRooms.Add(room);
                user.Rooms.Add(room);
                room.Users.Add(user);

                var service = new ChatService(repository, new Mock<ICryptoService>().Object);

                service.AddOwner(user, user2, room);

                Assert.True(user2.AllowedRooms.Contains(room));
                Assert.True(room.AllowedUsers.Contains(user2));
                Assert.True(room.Owners.Contains(user2));
                Assert.True(user2.OwnedRooms.Contains(room));
            }
Beispiel #16
0
        public static TestableChat GetTestableChat(string connectionId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();
            var settings = new Mock<IApplicationSettings>();

            settings.Setup(m => m.AuthApiKey).Returns("key");

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Clients = new ClientProxy(mockedConnectionObject, "Chat");

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(new Cookies(cookies));
            request.Setup(m => m.User).Returns(prinicipal.Object);

            chat.Caller = new StatefulSignalProxy(mockedConnectionObject, connectionId, "Chat", clientState);

            // setup context
            chat.Context = new HubCallerContext(request.Object, connectionId);

            return chat;
        }
Beispiel #17
0
            public void MakesUserOwner()
            {
                var repository = new InMemoryRepository();
                var user = new ChatUser
                {
                    Name = "foo"
                };
                var user2 = new ChatUser
                {
                    Name = "foo2"
                };
                repository.Add(user);
                repository.Add(user2);
                var room = new ChatRoom
                {
                    Name = "Room",
                    Creator = user
                };
                room.Owners.Add(user);
                user.OwnedRooms.Add(room);
                user.Rooms.Add(room);
                room.Users.Add(user);

                var service = new ChatService(repository);

                service.AddOwner(user, user2, room);

                Assert.True(room.Owners.Contains(user2));
                Assert.True(user2.OwnedRooms.Contains(room));
            }
        public void Repository_Handles_Sorting()
        {
            var repo = new InMemoryRepository<Order>();
            repo.Add(OrdersToLoad());

            // there are 2 ways to handle sorting, there is an Expression based way
            //  and a "magic string" based approach.
            // Why the 2 approaches?
            //  For convenience really.  In a Web based applicaiton sometimes it is easier to
            //  post back a string that represents the properrty that you want to sort on.

            // First, the Expression way
            var descendingOrders = repo.GetAll(new SortingOptions<Order, DateTime>(x => x.OrderDate, isDescending: true));
            descendingOrders.First().OrderId.ShouldEqual(1);

            var ascendingOrders = repo.GetAll(new SortingOptions<Order, DateTime>(x => x.OrderDate, isDescending: false));
            ascendingOrders.First().OrderId.ShouldEqual(2);

            // You can also combine sortings and selectors (See HowToUseGetSelectors for more info)
            var descendingNames = repo.GetAll(x => x.Name, new SortingOptions<Order, DateTime>(x => x.OrderDate, isDescending: true));
            descendingNames.First().ShouldEqual("Order 1");

            // The Magic String approach to sorting
            //  you can see that you don't need the second generic type (the property type to sort on), just the name of the property
            ascendingOrders = repo.GetAll(new SortingOptions<Order>("OrderDate", isDescending: false));
            ascendingOrders.First().OrderId.ShouldEqual(2);

            // using sorting with FindAll
            var minDate = DateTime.Now.AddDays(-7);
            var ordersWithinAWeek = repo.FindAll(x => x.OrderDate > minDate, new SortingOptions<Order, double>(x => x.Total, true));
            ordersWithinAWeek.Count().ShouldEqual(2);
        }
Beispiel #19
0
        public static InMemoryRepository<Message> GetMessageRepository(int numberOfMessage = 25)
        {
            var repo = new InMemoryRepository<Message>();
            var friendship = new Friendship()
            {
                 Id = 1,
                 IsFirstUserSender = true,
                 FirstUserId = "12345",
                 SecondUserId = "54321",
                 CreatedOn = DateTime.Now,
                 IsApproved = true
            };

            for (var i = 0; i < numberOfMessage; i++)
            {
                var date = new DateTime(2015, 11, 5, 23, 47, 12);
                date.AddDays(i);

                repo.Add(new Message
                {
                    Id = i,
                    Author = new User
                    {
                        FirstName = "FName" + i,
                        LastName = "LName" + i,
                        ProfilePhoto = new byte[i]
                    },
                    Content = "Content" + i,
                    SentOn = date,
                    FriendshipId = friendship.Id
                });
            }

            return repo;
        }
        public void Add_adds_to_internal_list()
        {
            var list = new List<string> { "Apple", "Ball", "Cat", "Dog" };
            var repository = new InMemoryRepository<string>(list);

            repository.Add("DoDo");
            Assert.That(list.Contains("DoDo"));
        }
        public void delete_removes_from_internal_list()
        {
            var list = new List<string> { "Apple", "Ball", "Cat", "Dog" };
            var repository = new InMemoryRepository<string>(list);
            repository.Delete("Apple");

            Assert.That(list.Contains("Apple"), Is.False);
        }
 public When_a_user_is_successfully_logged_in()
 {
     var username = "******";
     var password = "******";
     Repository = new InMemoryRepository<User>(SecurityHelper.GetUserList());
     UserService = new UsersService(Repository);
     CurrentUser = UserService.LoginUser(username, password);
 }
 public void Batch_Is_IDisposable_Type()
 {
     var repo = new InMemoryRepository<Order, int>();
     using (var batch = repo.BeginBatch())
     {
         batch.ShouldNotBeNull();
     }
 }
            public void ThrowsIfNameIsNullOrEmpty()
            {
                var repository = new InMemoryRepository();
                var service = new MembershipService(repository, new Mock<ICryptoService>().Object);

                Assert.Throws<InvalidOperationException>(() => service.AddUser(null, "email", password: null));
                Assert.Throws<InvalidOperationException>(() => service.AddUser(String.Empty, "email", password: null));
            }
        public void Repository_Supports_Selectors()
        {
            var repo = new InMemoryRepository<Order>();

            // let's add a couple of orders to work with
            repo.Add(new Order()
                         {
                             Name = "Order 1",
                             Total = 120.00,
                             OrderDate = new DateTime(2013, 4, 26)
                         });

            repo.Add(new Order()
                         {
                             Name = "Order 2",
                             Total = 80.00,
                             OrderDate = new DateTime(2013, 4, 24)
                         });

            // normal Get method
            var order = repo.Get(1);
            order.OrderId.ShouldEqual(1);

            // in this case we only need the order name
            var orderName = repo.Get(1, x => x.Name);
            orderName.ShouldEqual("Order 1");

            // we can also bring back an anonymous type if needed
            var anonymousType = repo.Get(1, x => new { Name = x.Name, IsExpensiveOrder = x.Total > 100.0 });
            anonymousType.IsExpensiveOrder.ShouldBeTrue();

            // or we can map it to a specific type we have defined like a ViewModel
            var viewModel = repo.Get(1, x => new OrderViewModel() {Name = x.Name, IsExpensiveOrder = x.Total > 100.0});
            viewModel.IsExpensiveOrder.ShouldBeTrue();

            // We have the same options with the GetAll, Find and FindAll as well
            orderName = repo.Find(x => x.OrderId == 2, x => x.Name);
            orderName.ShouldEqual("Order 2");

            // we can also bring back an anonymous type if needed
            var anonymousTypes = repo.GetAll(x => new { Name = x.Name, IsExpensiveOrder = x.Total > 100.0 }).ToList();
            anonymousTypes.Count.ShouldEqual(2);
            anonymousTypes.First().Name.ShouldEqual("Order 1");
            anonymousTypes.First().IsExpensiveOrder.ShouldBeTrue();

            anonymousTypes.Last().Name.ShouldEqual("Order 2");
            anonymousTypes.Last().IsExpensiveOrder.ShouldBeFalse();

            // or we can map it to a specific type we have defined like a ViewModel
            var viewModels = repo.FindAll(x => x.OrderId < 5, x => new OrderViewModel() { Name = x.Name, IsExpensiveOrder = x.Total > 100.0 }).ToList();
            viewModels.Count.ShouldEqual(2);
            viewModels.First().Name.ShouldEqual("Order 1");
            viewModels.First().IsExpensiveOrder.ShouldBeTrue();

            viewModels.Last().Name.ShouldEqual("Order 2");
            viewModels.Last().IsExpensiveOrder.ShouldBeFalse();
        }
        public void Batch_Default_Should_Contain_No_Actions()
        {
            var repository = new InMemoryRepository<Contact, Int32>();

            using (var batch = repository.BeginBatch())
            {
                batch.BatchActions.Count.ShouldEqual(0);
            }
        }
Beispiel #27
0
        public void TestMethod1()
        {
            IRepository<TestItem> repo = new InMemoryRepository<TestItem>();
            repo.Create(new TestItem() { ID = 1, Name = "Frank" });

            var item = repo.GetBy(p => p.ID == 1);
            item.Name = "Fred";
            int i = 0;
        }
        public void Init()
        {
            this.userRepo = TestObjectFactory.GetUsersRepository();
            this.projectsRepo = TestObjectFactory.GetProjectsRepository();

            this.projectsService = new ProjectsService(
                projectsRepo,
                this.userRepo);
        }
Beispiel #29
0
 public void Now_It_Can_Be_Tested_Too()
 {
     // now testing is much easier, and there are no surprises
     var repo = new InMemoryRepository<Post>();
     var blog = new BetterBlog(repo);
     Assert.IsEmpty(blog.FindAllPosts());
     blog.Save(new Post());
     Assert.IsNotEmpty(blog.FindAllPosts());
 }
        public InMemoryUnitOfWork(IList source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            _repository = new InMemoryRepository(source);
        }
Beispiel #31
0
 public folder()
 {
     file_system          = new InMemoryFileSystem();
     repository_directory = file_system.CreateTempDirectory();
     source_repository    = new InMemoryRepository("somewhere");
 }
Beispiel #32
0
 public ServiceTema(InMemoryRepository <int, Tema> temaRepo)
 {
     this.temaRepo = temaRepo;
 }
Beispiel #33
0
 public GroupFactory(InMemoryRepository repo)
 {
     _repo = repo;
 }
 public CountryNullIMFilter(InMemoryRepository repo, int order, string value) : base(repo, order, value)
 {
 }
Beispiel #35
0
 public override void Init()
 {
     Repository = new InMemoryRepository <PlainstProcessData>();
 }
 public ChatHub(IChatService chatService)
 {
     _repository  = InMemoryRepository.GetInstance();
     _chatService = chatService;
 }
        public void InMemoryRepository_Requires_Generic_Type_And_KeyType()
        {
            var repo = new InMemoryRepository <Order, int>();

            repo.ShouldNotBeNull();
        }
Beispiel #38
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o =>
            {
                o.AddPolicy("AllowCors", p =>
                {
                    p.WithOrigins(configuration.GetSection("CorsOrigins").Get <string[]>())
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            services
            .AddSignalR()
            .AddNewtonsoftJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
                options.PayloadSerializerSettings.Converters.Add(new StringEnumConverter());
                options.PayloadSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            services.AddMvcCore()
            .AddNewtonsoftJson(
                options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            })
            .AddApiExplorer()
            .AddAuthorization(
                options =>
            {
                // add any authorization policy
                options.AddPolicy(AuthorizationPolicies.System,
                                  policy => policy.RequireClaim(JwtClaimTypes.Scope, "axle_api:server"));
                options.AddPolicy(AuthorizationPolicies.Mobile,
                                  policy => policy.AddRequirements(new MobileClientAndAccountOwnerRequirement()));
                options.AddPolicy(PermissionsManagement.Client.Constants.AuthorizeUserPolicy,
                                  policy => policy.AddRequirements(new AuthorizeUserRequirement()));
                options.AddPolicy(AuthorizationPolicies.AccountOwnerOrSupport,
                                  policy => policy.AddRequirements(new AccountOwnerOrSupportRequirement()));
            });

            var authority          = configuration.GetValue <string>("Api-Authority");
            var apiName            = configuration.GetValue <string>("Api-Name");
            var apiSecret          = configuration.GetValue <string>("Api-Secret");
            var validateIssuerName = configuration.GetValue <bool>("Validate-Issuer-Name");
            var requireHttps       = configuration.GetValue <bool>("Require-Https");

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = apiName, Version = "v1"
                });
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{authority}/connect/authorize", UriKind.Absolute),
                            Scopes           =
                            {
                                { apiName,             "CFD Platform (Nova)"                     },
                                { $"{apiName}:server", "CFD Platform (Nova) server side methods" },
                                { $"{apiName}:mobile", "CFD Platform (Nova) mobile side methods" }
                            }
                        }
                    }
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id   = "oauth2",
                                Type = ReferenceType.SecurityScheme
                            }
                        },
                        new[] { apiName }
                    }
                });
            });

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            })
            .AddIdentityServerAuthentication(
                IdentityServerAuthenticationDefaults.AuthenticationScheme,
                options =>
            {
                options.Authority = authority;
                options.ApiName   = apiName;
                options.ApiSecret = apiSecret;

                // NOTE (Cameron): This is only used because we're performing HTTPS termination at the proxy.
                options.RequireHttpsMetadata = requireHttps;
                options.IntrospectionDiscoveryPolicy.RequireHttps       = requireHttps;
                options.IntrospectionDiscoveryPolicy.ValidateIssuerName = validateIssuerName;

                options.TokenRetriever = BearerTokenRetriever.FromHeaderAndQueryString;

                options.EnableCaching = configuration.GetValue("IntrospectionCache:Enabled", true);
                options.CacheDuration = TimeSpan.FromSeconds(configuration.GetValue("IntrospectionCache:DurationInSeconds", 600));
            });

            var connectionRepository = new InMemoryRepository <string, HubCallerContext>();

            services.AddSingleton <IRepository <string, HubCallerContext> >(connectionRepository);
            services.AddSingleton <IRepository <string, int> >(new InMemoryRepository <string, int>());
            services.AddSingleton <IReadOnlyRepository <string, HubCallerContext> >(connectionRepository);

            var sessionSettings = configuration.GetSection("SessionConfig").Get <SessionSettings>() ?? new SessionSettings();

            services.AddSingleton(sessionSettings);
            services.AddSingleton <INotificationService, NotificationService>();

            services.AddSingleton <ISessionRepository, RedisSessionRepository>(x =>
                                                                               new RedisSessionRepository(
                                                                                   x.GetService <IConnectionMultiplexer>(),
                                                                                   sessionSettings.Timeout,
                                                                                   x.GetService <ILogger <RedisSessionRepository> >()));
            services.AddSingleton <ISessionService, SessionService>();
            services.AddSingleton <IHubConnectionService, HubConnectionService>();
            services.AddSingleton <IActivityService, ActivityService>();

            var rabbitMqSettings = configuration.GetSection("ActivityPublisherSettings").Get <RabbitMqSubscriptionSettings>().MakeDurable();

            rabbitMqSettings.ConnectionString = configuration["ConnectionStrings:RabbitMq"];

            services.AddSingleton(x => new RabbitMqPublisher <SessionActivity>(rabbitMqSettings)
                                  .DisableInMemoryQueuePersistence()
                                  .SetSerializer(new MessagePackMessageSerializer <SessionActivity>())
                                  .SetPublishStrategy(new DefaultFanoutPublishStrategy(rabbitMqSettings))
                                  .SetLogger(new LykkeLoggerAdapter <RabbitMqPublisher <SessionActivity> >(x.GetService <ILogger <RabbitMqPublisher <SessionActivity> > >()))
                                  .PublishSynchronously());

            services.AddSingleton <IConnectionMultiplexer>(x => ConnectionMultiplexer.Connect(configuration.GetValue <string>("ConnectionStrings:Redis")));

            services.AddSingleton <IDiscoveryCache, DiscoveryCache>(p => new DiscoveryCache(authority,
                                                                                            new DiscoveryPolicy {
                RequireHttps = requireHttps, ValidateIssuerName = validateIssuerName
            }));
            services.AddSingleton <ITokenRevocationService, BouncerService>();

            services.AddSingleton <IHttpStatusCodeMapper, DefaultHttpStatusCodeMapper>();
            services.AddSingleton <ILogLevelMapper, DefaultLogLevelMapper>();

            // AuditSettings registration for Lykke.Middlewares.AuditHandlerMiddleware
            services.AddSingleton(configuration.GetSection("AuditSettings")?.Get <AuditSettings>() ?? new AuditSettings());

            services.AddMtCoreDalRepositories(
                configuration.GetValue <string>("mtCoreAccountsMgmtServiceUrl"),
                configuration.GetValue <string>("mtCoreAccountsApiKey"),
                configuration.GetValue("BackofficeSupportMode", false));

            services.AddChestClient(
                configuration.GetValue <string>("chestUrl"),
                configuration.GetValue <string>("chestApiKey"));

            services.AddSingleton <IAccountsService, AccountsService>();
            // The security groups are being injected by permissions management library, not obvious but no need to remove
            services.AddSingleton(configuration.GetSection("SecurityGroups").Get <IEnumerable <SecurityGroup> >());
            services.AddSingleton <IUserRoleToPermissionsTransformer, UserRoleToPermissionsTransformer>();
            services.AddSingleton <IUserPermissionsClient, FakeUserPermissionsRepository>();
            services.AddSingleton <IClaimsTransformation, ClaimsTransformation>();
            services.AddSingleton <IAuthorizationHandler, AuthorizeUserHandler>();
            services.AddSingleton <IAuthorizationHandler, AccountOwnerOrSupportHandler>();
            services.AddSingleton <IAuthorizationHandler, MobileClientAndAccountOwnerHandler>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IAccountsCache, AccountsCache>();

            services.AddHostedService <SessionExpirationService>();
            services.AddHostedService <SessionTerminationListener>();
            services.AddHostedService <OtherTabTerminationListener>();

            services.AddMemoryCache(o => o.ExpirationScanFrequency = TimeSpan.FromMinutes(1));
            services.AddDistributedMemoryCache(
                options => options.ExpirationScanFrequency = TimeSpan.FromSeconds(
                    configuration.GetValue("IntrospectionCache:ExpirationScanFrequencyInSeconds", 60)));

            services.AddHttpClient();
        }
 public ProductManagerController()
 {
     cRepositoryProducts   = new InMemoryRepository <ModelProduct>();
     cRepositoryCategories = new InMemoryRepository <ModelProductCategory>();
 }
Beispiel #40
0
 public ServiceStudent(InMemoryRepository <int, Student> studentRepo)
 {
     this.studentRepo = studentRepo;
 }
Beispiel #41
0
 public SuggestResponseDtoConverter(InMemoryRepository repo)
 {
     _repo     = repo;
     _accounts = _repo.Accounts;
 }
 public void Init()
 {
     this.albums = ObjectsFactory.GetAlbumRepository();
     this.users  = ObjectsFactory.GetUserRepository();
     this.photos = ObjectsFactory.GetEmptyPhotoRepository();
 }
        public void InMemoryRepository_Defaults_Key_To_Int()
        {
            var repo = new InMemoryRepository <Order>();

            repo.ShouldNotBeNull();
        }
        public void InMemoryTests()
        {
            var obj1 = new InMemoryObject("1", "Test 1");
            var obj2 = new InMemoryObject("A", "Test 2");
            var obj3 = new InMemoryObject("!", "Test 3");
            var rep  = new InMemoryRepository <InMemoryObject, string>();

            Assert.AreEqual(rep.GetAll().Count(x => true), 0);
            Assert.AreEqual(rep.Contains(obj1), false);
            Assert.AreEqual(rep.Contains(obj2), false);
            Assert.AreEqual(rep.Contains(obj3), false);

            // Add 1
            rep.Add(obj1);

            Assert.AreEqual(rep.GetAll().Count(x => true), 1);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), false);
            Assert.AreEqual(rep.Contains(obj3), false);

            // Add 2
            rep.Add(obj2);

            Assert.AreEqual(rep.GetAll().Count(x => true), 2);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), true);
            Assert.AreEqual(rep.Contains(obj3), false);

            // Add 3
            rep.Add(obj3);

            Assert.AreEqual(rep.GetAll().Count(x => true), 3);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), true);
            Assert.AreEqual(rep.Contains(obj3), true);

            // Readd
            rep.Add(obj3);

            Assert.AreEqual(rep.GetAll().Count(x => true), 3);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), true);
            Assert.AreEqual(rep.Contains(obj3), true);

            // Store
            var obj1Get = rep.GetAll().Where(x => x.ID == "1").FirstOrDefault();

            obj1Get.UpdateTest("Test 1a");
            Assert.AreEqual(true, rep.Store(obj1Get));

            // Remove 2
            rep.Remove(obj2);

            Assert.AreEqual(rep.GetAll().Count(x => true), 2);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), false);
            Assert.AreEqual(rep.Contains(obj3), true);

            // Remove 1
            rep.Remove(obj1);

            Assert.AreEqual(rep.GetAll().Count(x => true), 1);
            Assert.AreEqual(rep.Contains(obj1), false);
            Assert.AreEqual(rep.Contains(obj2), false);
            Assert.AreEqual(rep.Contains(obj3), true);

            // Add 1 & 2
            rep.AddRange(new[] { obj1, obj2 });

            Assert.AreEqual(rep.GetAll().Count(x => true), 3);
            Assert.AreEqual(rep.Contains(obj1), true);
            Assert.AreEqual(rep.Contains(obj2), true);
            Assert.AreEqual(rep.Contains(obj3), true);

            rep.Clear();

            Assert.AreEqual(rep.GetAll().Count(x => true), 0);
            Assert.AreEqual(rep.Contains(obj1), false);
            Assert.AreEqual(rep.Contains(obj2), false);
            Assert.AreEqual(rep.Contains(obj3), false);
        }
Beispiel #45
0
 public EmailDomainIMFilter(InMemoryRepository repo, int order, string value) : base(repo, order, value)
 {
 }
Beispiel #46
0
 public GetAll()
 {
     _repo = new InMemoryRepository <TestEntity>();
 }
Beispiel #47
0
 public ManyToMany()
 {
     _repo = InMemoryRepository <ManyToManyElement <M, O> > .GetInstance();
 }
 public PhoneCodeIMFilter(InMemoryRepository repo, int order, string value) : base(repo, order, value)
 {
 }
Beispiel #49
0
 public void SetUp()
 {
     _sut = new InMemoryRepository <TestModel>();
 }
 public SNameEqIMFilter(InMemoryRepository repo, int order, string value) : base(repo, order, value)
 {
 }
        public void TestCashflowSucessCase()
        {
            var repo       = new InMemoryRepository();
            var periodeId1 = new PeriodeId(new DateTime(2015, 11, 1), new DateTime(2015, 11, 6));
            var periode    = new Periode(periodeId1, StatusPeriode.Mingguan);

            repo.SavePeriod(periode);
            var periodeSnapShot = new PeriodeDto()
            {
                StartPeriode = new DateTime(2015, 11, 1),
                EndPeriode   = new DateTime(2015, 11, 6),
                IsPeriode    = StatusPeriode.Bebas
            };

            var periodeSave = repo.FindPeriodForDate(new DateTime(2015, 11, 3));

            Assert.AreEqual(periodeSnapShot, periodeSave.Snap());

            //cashflow
            var cashFlow = new CashFlow("ABC", periodeId1, 500000.0);

            repo.Save(cashFlow);

            var cashflowSnapshotDto = new CashFlowDto()
            {
                TenantId           = "ABC",
                PeriodId           = periode.Snap(),
                SaldoAwal          = 500000.0,
                SaldoAkhir         = 500000.0,
                TotalPenjualan     = 0.0,
                TotalPenjualanLain = 0.0,
                TotalPengeluaran   = 0.0,
            };


            var findCashFlow = repo.FindCashFlowByPeriod(periodeId1);

            Assert.AreEqual(cashflowSnapshotDto, findCashFlow.Snap());

            //Penjualan
            cashFlow.AddPenjualan(new DateTime(2015, 11, 1), 200000.0);
            repo.Save(cashFlow);
            var repoFind                  = repo.FindPeriodForDate(new DateTime(2015, 11, 3));
            var cashFlowSnapshot          = cashFlow.Snap();
            var cashflowPenjualanSnapshot = new CashFlowDto()
            {
                TenantId           = "ABC",
                PeriodId           = periode.Snap(),
                SaldoAwal          = 500000.0,
                SaldoAkhir         = 700000.0,
                TotalPenjualan     = 200000.0,
                TotalPenjualanLain = 0.0,
                TotalPengeluaran   = 0.0,
            };

            Assert.AreEqual(cashflowPenjualanSnapshot, cashFlowSnapshot);
            Assert.AreEqual(1, cashFlowSnapshot.ItemsPenjualan.Count);
            var itemPenjualan = cashFlowSnapshot.ItemsPenjualan[0];

            Assert.AreEqual(new DateTime(2015, 11, 1), itemPenjualan.DateTime);
            Assert.AreEqual(200000.0, itemPenjualan.Nominal);

            //PenjualanLain
            cashFlow.AddPenjualanLain(new DateTime(2015, 11, 1), 200000.0);
            repo.Save(cashFlow);
            var repoFindLain                  = repo.FindPeriodForDate(new DateTime(2015, 11, 3));
            var cashFlowSnapshotLain          = cashFlow.Snap();
            var cashflowPenjualanLainSnapshot = new CashFlowDto()
            {
                TenantId           = "ABC",
                PeriodId           = periode.Snap(),
                SaldoAwal          = 500000.0,
                SaldoAkhir         = 900000.0,
                TotalPenjualan     = 200000.0,
                TotalPenjualanLain = 200000.0,
                TotalPengeluaran   = 0.0,
            };

            Assert.AreEqual(cashflowPenjualanLainSnapshot, cashFlowSnapshotLain);
            Assert.AreEqual(1, cashFlowSnapshotLain.ItemsPenjualanLain.Count);
            var itemPenjualanLain = cashFlowSnapshotLain.ItemsPenjualanLain[0];

            Assert.AreEqual(new DateTime(2015, 11, 1), itemPenjualanLain.DateTimeLain);
            Assert.AreEqual(200000.0, itemPenjualanLain.NominalLain);

            //Pengeluaran
            cashFlow.ChangePengeluaran("Ayam", 200000, 5);
            repo.Save(cashFlow);
            var repoFindPengeluaran         = repo.FindPeriodForDate(new DateTime(2015, 11, 3));
            var cashFlowSnapshotPengeluaran = cashFlow.Snap();
            var cashflowPengeluaranSnapshot = new CashFlowDto()
            {
                TenantId           = "ABC",
                PeriodId           = periode.Snap(),
                SaldoAwal          = 500000.0,
                SaldoAkhir         = 700000.0,
                TotalPenjualan     = 200000.0,
                TotalPenjualanLain = 200000.0,
                TotalPengeluaran   = 200000.0,
            };

            Assert.AreEqual(cashflowPengeluaranSnapshot, cashFlowSnapshotPengeluaran);
            Assert.AreEqual(1, cashFlowSnapshotPengeluaran.ItemsPengeluaran.Count);
            var itemPengeluaran = cashFlowSnapshotPengeluaran.ItemsPengeluaran[0];

            Assert.AreEqual("Ayam", itemPengeluaran.Akun);
            Assert.AreEqual(200000.0, itemPengeluaran.Nominal);
            Assert.AreEqual(5, itemPengeluaran.Jumlah);

            //NotaPengeluaran

            //var noNota = new NotaPengeluaranId("123");
            //var notaPengeluaran = new NotaPengeluaran(new DateTime(2015, 11, 1), noNota);
            //repo.SaveNota(notaPengeluaran);
            //var foundNota = repo.FindNotaPengeluaranByID("123");
            ////var notaSnapshot = notaPengeluaran.Snap();
            //var notaSnap = new NotaPengeluaranDto()
            //{
            //    Tanggal = new DateTime(2015, 11, 1),
            //    NoNota = noNota,
            //    TotalNota = 0.0
            //};
            //Assert.AreEqual(notaSnap, foundNota.Snap());

            ////AddAkunNota
            //notaPengeluaran.AddAkun("Ayam", 200000, 5);
            //repo.SaveNota(notaPengeluaran);
            //var repoFindNotaAkun = repo.FindPeriodForDate(new DateTime(2015, 11, 3));
            //var notaAkunSnapshot = notaPengeluaran.Snap();
            //var notaAkunSnap = new NotaPengeluaranDto()
            //{
            //    Tanggal = new DateTime(2015, 10, 26),
            //    NoNota = "123",
            //    TotalNota = 0.0
            //};
            //Assert.AreEqual(notaAkunSnap, notaAkunSnapshot);
        }
 public FilterFactory(InMemoryRepository repo)
 {
     _repo = repo;
 }
Beispiel #53
0
 protected override void PerformSetUp()
 {
     Repository = new InMemoryRepository();
 }
 public GroupByInterests(int interestsCount, InMemoryRepository repo) : base(interestsCount, repo)
 {
 }
Beispiel #55
0
 public GroupBySex(int sexCount, InMemoryRepository repo) : base(sexCount, repo)
 {
 }
        public void IntegerModelReference()
        {
            // Arrange
            var entityData = new List <EntityData>
            {
                new EntityDataBuilder("CherrySeed.Test.Models.EntityWithConformIntPk",
                                      "Id")
                .WithEntity("E1")
                .WithEntity("E2")
                .Build(),
                new EntityDataBuilder("CherrySeed.Test.Models.EntityWithIntReferenceModel",
                                      "ReferenceModel")
                .WithEntity("E2")
                .WithEntity("E2")
                .Build(),
            };

            // Act
            var repository = new InMemoryRepository((o, id) =>
            {
                var pk = o as EntityWithConformIntPk;
                if (pk != null)
                {
                    return(pk.Id == (int)id);
                }

                throw new InvalidOperationException("Failed");
            });

            _cherrySeedDriver.InitAndSeed(entityData.ToDictionaryDataProvider(), repository, cfg =>
            {
                cfg.WithPrimaryKeyIdGenerationInApplicationAsInteger();

                cfg.ForEntity <EntityWithConformIntPk>();
                cfg.ForEntity <EntityWithIntReferenceModel>()
                .WithReference(e => e.ReferenceModel, typeof(EntityWithConformIntPk));
            });

            // Assert
            Assert.AreEqual(4, repository.CountSeededObjects());
            Assert.AreEqual(2, repository.CountSeededObjects <EntityWithConformIntPk>());
            Assert.AreEqual(2, repository.CountSeededObjects <EntityWithIntReferenceModel>());
            EntityAsserts.AssertEntityWithConformIntPk(repository.GetEntities <EntityWithConformIntPk>()[0], new EntityWithConformIntPk
            {
                Id = 1
            });
            EntityAsserts.AssertEntityWithConformIntPk(repository.GetEntities <EntityWithConformIntPk>()[1], new EntityWithConformIntPk
            {
                Id = 2
            });

            EntityAsserts.AssertEntityWithIntReferenceModel(repository.GetEntities <EntityWithIntReferenceModel>()[0], new EntityWithIntReferenceModel
            {
                ReferenceModel = new EntityWithConformIntPk {
                    Id = 2
                }
            });
            EntityAsserts.AssertEntityWithIntReferenceModel(repository.GetEntities <EntityWithIntReferenceModel>()[1], new EntityWithIntReferenceModel
            {
                ReferenceModel = new EntityWithConformIntPk {
                    Id = 2
                }
            });
        }
 protected NullFilterBase(InMemoryRepository repo, int order, string value) : base(repo, order, value)
 {
 }
Beispiel #58
0
 public ProductManagerController()
 {
     context           = new InMemoryRepository <Product>();
     productCategories = new InMemoryRepository <ProductCategory>();
 }
 public void Init()
 {
     this.photos   = ObjectsFactory.GetPhotoRepository();
     this.comments = ObjectsFactory.GetCommentRepository();
 }
Beispiel #60
0
 public DupeDiControllerFactory()
 {
     _bindings = new Dictionary <Type, object>();
     _bindings[typeof(IRepository)] = new InMemoryRepository().WithKey <Teacher>(t => t.Id);
     _bindings[typeof(ICommandHandler <AddTeacherCommand>)] = new AddTeacher(GetInstance <IRepository>());
 }